@masterteam/work-center 0.0.99 → 0.0.101

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.
@@ -0,0 +1,1287 @@
1
+ import * as i0 from '@angular/core';
2
+ import { inject, Injectable, computed } from '@angular/core';
3
+ import { Action, Selector, State, Store, select } from '@ngxs/store';
4
+ import { HttpClient } from '@angular/common/http';
5
+ import { handleApiRequest } from '@masterteam/components';
6
+ import { catchError, EMPTY, map } from 'rxjs';
7
+
8
+ class EnterArea {
9
+ area;
10
+ static type = '[WorkCenter] Enter Area';
11
+ constructor(area) {
12
+ this.area = area;
13
+ }
14
+ }
15
+ class HydrateFromContext {
16
+ area;
17
+ patch;
18
+ static type = '[WorkCenter] Hydrate From Context';
19
+ constructor(area, patch) {
20
+ this.area = area;
21
+ this.patch = patch;
22
+ }
23
+ }
24
+ class SetParams {
25
+ area;
26
+ inputs;
27
+ static type = '[WorkCenter] Set Params';
28
+ constructor(area, inputs) {
29
+ this.area = area;
30
+ this.inputs = inputs;
31
+ }
32
+ }
33
+ class SetLookups {
34
+ lookups;
35
+ static type = '[WorkCenter] Set Lookups';
36
+ constructor(lookups) {
37
+ this.lookups = lookups;
38
+ }
39
+ }
40
+ class LoadRuntime {
41
+ area;
42
+ reason;
43
+ static type = '[WorkCenter] Load Runtime';
44
+ constructor(area, reason = 'manual') {
45
+ this.area = area;
46
+ this.reason = reason;
47
+ }
48
+ }
49
+ /**
50
+ * Replaces the header filter slice (rules from
51
+ * `mt-property-filter-builder`). Resets `page` to 1 and triggers a
52
+ * BE reload with the merged `headerFilters` + `columnFilters` payload.
53
+ */
54
+ class ApplyHeaderFilters {
55
+ area;
56
+ filters;
57
+ static type = '[WorkCenter] Apply Header Filters';
58
+ constructor(area, filters) {
59
+ this.area = area;
60
+ this.filters = filters;
61
+ }
62
+ }
63
+ /**
64
+ * Replaces the in-table column filter slice (rules translated from the
65
+ * `mt-table` filters map). Resets `page` to 1 and triggers a BE reload
66
+ * with the merged `headerFilters` + `columnFilters` payload.
67
+ */
68
+ class ApplyColumnFilters {
69
+ area;
70
+ filters;
71
+ static type = '[WorkCenter] Apply Column Filters';
72
+ constructor(area, filters) {
73
+ this.area = area;
74
+ this.filters = filters;
75
+ }
76
+ }
77
+ /**
78
+ * Switches the selected card and drops everything that was scoped to the
79
+ * previous one: advanced filters, in-table column filters, grouping and the
80
+ * sort that grouping implied. Each card brings its own columns and filter
81
+ * schema, so carrying those over would filter on fields the new card doesn't
82
+ * have and group by a column it doesn't show.
83
+ */
84
+ class SelectCard {
85
+ area;
86
+ selectedCardKey;
87
+ static type = '[WorkCenter] Select Card';
88
+ constructor(area, selectedCardKey) {
89
+ this.area = area;
90
+ this.selectedCardKey = selectedCardKey;
91
+ }
92
+ }
93
+ /**
94
+ * Sets the grouped column. Grouping is expressed to the backend as a single
95
+ * sort on the same field, so this also rewrites `context.sort` and resets
96
+ * `page` to 1 before reloading. `groupBy: null` clears both.
97
+ */
98
+ class SetGroupBy {
99
+ area;
100
+ groupBy;
101
+ dir;
102
+ static type = '[WorkCenter] Set Group By';
103
+ constructor(area, groupBy, dir = 'asc') {
104
+ this.area = area;
105
+ this.groupBy = groupBy;
106
+ this.dir = dir;
107
+ }
108
+ }
109
+ /**
110
+ * Clears both the header filter slice and the column filter slice in one
111
+ * state update, triggering a single BE reload.
112
+ */
113
+ class ClearAllFilters {
114
+ area;
115
+ static type = '[WorkCenter] Clear All Filters';
116
+ constructor(area) {
117
+ this.area = area;
118
+ }
119
+ }
120
+
121
+ var WorkCenterActionKey;
122
+ (function (WorkCenterActionKey) {
123
+ WorkCenterActionKey["LoadRuntime"] = "loadRuntime";
124
+ })(WorkCenterActionKey || (WorkCenterActionKey = {}));
125
+ const WORK_CENTER_QUERY_VERSION = 1;
126
+ const WORK_CENTER_MAX_PAGE_SIZE = 100;
127
+ const WORK_CENTER_MAX_FILTERS = 20;
128
+ const WORK_CENTER_MAX_SORT = 5;
129
+ /**
130
+ * Backend column key carrying the row's LevelData display label
131
+ * (`extra.levelDataName`). Grouping by it maps to a single backend sort on the
132
+ * same key — see `WORK_CENTER_LEVEL_GROUP_FIELD` for the grouping identity.
133
+ */
134
+ const WORK_CENTER_LEVEL_NAME_KEY = 'levelDataName';
135
+ /**
136
+ * Synthetic per-row field holding the *identity* behind the Level Name column.
137
+ * The visible label is ambiguous (two LevelData records may share a name), so
138
+ * rows are bucketed by `context.levelDataId` instead — except rows with no
139
+ * visible label, which get an empty identity so they all collapse into the one
140
+ * shared "—" group the backend contract requires.
141
+ */
142
+ const WORK_CENTER_LEVEL_GROUP_FIELD = '__mtLevelGroup';
143
+ /** Rendered in place of a missing / restricted LevelData label. */
144
+ const WORK_CENTER_EMPTY_LABEL = '—';
145
+ /**
146
+ * Bootstrap `group` value meaning "the user turned grouping off". Needed
147
+ * because an absent `group` means "not chosen yet" and falls back to the
148
+ * default grouping — without a distinct value, clearing the group would be
149
+ * undone by the next navigation.
150
+ */
151
+ const WORK_CENTER_GROUP_NONE = 'none';
152
+
153
+ const AREA_COLORS = ['violet', 'blue', 'emerald', 'amber', 'teal'];
154
+ /** Fallback accent rotation used only when the backend sends no stat color. */
155
+ const KPI_COLORS = ['violet', 'blue', 'emerald', 'amber', 'teal'];
156
+ /**
157
+ * Default page size when bootstrapping a work-center area. Matches the table
158
+ * paginator default so the first BE request asks for exactly one rendered
159
+ * page.
160
+ */
161
+ const WORK_CENTER_DEFAULT_PAGE_SIZE = 20;
162
+ const WORK_CENTER_LOCAL_FETCH_SIZE = WORK_CENTER_DEFAULT_PAGE_SIZE;
163
+ const FILTER_OPERATORS = new Set([
164
+ 'Eq',
165
+ 'Neq',
166
+ 'In',
167
+ 'Contains',
168
+ 'StartsWith',
169
+ 'Gt',
170
+ 'Gte',
171
+ 'Lt',
172
+ 'Lte',
173
+ 'Between',
174
+ 'IsNull',
175
+ 'IsNotNull',
176
+ ]);
177
+ function clampPage(value, fallback = 1) {
178
+ if (!Number.isFinite(value))
179
+ return fallback;
180
+ return Math.max(1, Math.floor(value));
181
+ }
182
+ function clampPageSize(value, fallback = WORK_CENTER_LOCAL_FETCH_SIZE) {
183
+ if (!Number.isFinite(value))
184
+ return fallback;
185
+ const parsed = Math.floor(value);
186
+ return Math.min(WORK_CENTER_MAX_PAGE_SIZE, Math.max(1, parsed));
187
+ }
188
+ function sanitizeSort(rules) {
189
+ if (!Array.isArray(rules))
190
+ return [];
191
+ return rules
192
+ .filter((rule) => typeof rule?.field === 'string' &&
193
+ rule.field.length > 0 &&
194
+ (rule.dir === 'asc' || rule.dir === 'desc'))
195
+ .slice(0, WORK_CENTER_MAX_SORT);
196
+ }
197
+ function sanitizeFilters(filters) {
198
+ if (!Array.isArray(filters))
199
+ return [];
200
+ return filters
201
+ .filter((filter) => typeof filter?.field === 'string' &&
202
+ filter.field.length > 0 &&
203
+ typeof filter?.op === 'string' &&
204
+ FILTER_OPERATORS.has(filter.op))
205
+ .slice(0, WORK_CENTER_MAX_FILTERS);
206
+ }
207
+ function parseJson(value) {
208
+ if (typeof value !== 'string')
209
+ return value;
210
+ if (!value.trim())
211
+ return null;
212
+ try {
213
+ return JSON.parse(value);
214
+ }
215
+ catch {
216
+ return null;
217
+ }
218
+ }
219
+ function toOptionalInt(value) {
220
+ if (value === null || value === undefined || value === '')
221
+ return null;
222
+ const parsed = Number(value);
223
+ return Number.isFinite(parsed) ? Math.floor(parsed) : null;
224
+ }
225
+ function toSelectedCardKey(value) {
226
+ if (typeof value !== 'string')
227
+ return null;
228
+ const parsed = value.trim();
229
+ return parsed.length ? parsed : null;
230
+ }
231
+ function parseSortInput(value) {
232
+ const parsed = parseJson(value);
233
+ return Array.isArray(parsed)
234
+ ? sanitizeSort(parsed)
235
+ : [];
236
+ }
237
+ /**
238
+ * Resolves the grouped column key from bootstrap inputs.
239
+ *
240
+ * A missing `group` keeps whatever state already has, so an unrelated
241
+ * navigation doesn't drop the user's grouping. `WORK_CENTER_GROUP_NONE` is the
242
+ * only way to express "turn it off" — a bare `null` can't, because it is also
243
+ * what a host passes for an absent query param.
244
+ */
245
+ function resolveGroupByFromInputs(current, group) {
246
+ if (!hasParamValue(group) || typeof group !== 'string') {
247
+ return current;
248
+ }
249
+ const parsed = group.trim();
250
+ if (!parsed || parsed === WORK_CENTER_GROUP_NONE) {
251
+ return null;
252
+ }
253
+ return parsed;
254
+ }
255
+ /**
256
+ * The card these inputs resolve to — the same rule `buildContextFromInputs`
257
+ * applies, exposed so callers can detect a card switch before building the
258
+ * context (what survives the switch depends on it).
259
+ */
260
+ function resolveSelectedCardKeyFromInputs(currentContext, inputs = {}) {
261
+ return toSelectedCardKey(inputs.card) ?? currentContext.selectedCardKey;
262
+ }
263
+ function parseFiltersInput(value) {
264
+ const parsed = parseJson(value);
265
+ return Array.isArray(parsed)
266
+ ? sanitizeFilters(parsed)
267
+ : [];
268
+ }
269
+ function hasParamValue(value) {
270
+ return value !== null && value !== undefined && value !== '';
271
+ }
272
+ function toLabel(value) {
273
+ const segment = value.split('.').pop() ?? value;
274
+ return segment
275
+ .replace(/[_-]/g, ' ')
276
+ .replace(/([a-z])([A-Z])/g, '$1 $2')
277
+ .replace(/\s+/g, ' ')
278
+ .trim()
279
+ .replace(/\b\w/g, (char) => char.toUpperCase());
280
+ }
281
+ function toViewType(viewType, key) {
282
+ if (viewType?.trim()) {
283
+ return viewType;
284
+ }
285
+ return key.toLowerCase().includes('date') ? 'Date' : 'Text';
286
+ }
287
+ function normalizeColumnKey(key) {
288
+ return key
289
+ .trim()
290
+ .toLowerCase()
291
+ .replace(/[\s._-]+/g, '');
292
+ }
293
+ function resolveColumnWeight(key) {
294
+ const normalizedKey = normalizeColumnKey(key);
295
+ if (normalizedKey.includes('title'))
296
+ return 26;
297
+ if (normalizedKey.includes('subtitle') ||
298
+ normalizedKey.includes('description')) {
299
+ return 20;
300
+ }
301
+ if (normalizedKey.includes('status'))
302
+ return 14;
303
+ if (normalizedKey.includes('progress'))
304
+ return 17;
305
+ if (normalizedKey.includes('createdby') ||
306
+ normalizedKey.includes('assignedto') ||
307
+ normalizedKey.includes('owner') ||
308
+ normalizedKey.includes('user')) {
309
+ return 20;
310
+ }
311
+ if (normalizedKey.includes('duedate') ||
312
+ normalizedKey.includes('createdat') ||
313
+ normalizedKey.includes('updatedat') ||
314
+ normalizedKey.endsWith('date')) {
315
+ return 15;
316
+ }
317
+ if (normalizedKey.includes('priority'))
318
+ return 12;
319
+ return 16;
320
+ }
321
+ function applySmartColumnWidths(columns) {
322
+ const dynamicWeightTotal = columns.reduce((total, column) => {
323
+ return column.width?.trim()
324
+ ? total
325
+ : total + resolveColumnWeight(column.key);
326
+ }, 0);
327
+ if (!dynamicWeightTotal) {
328
+ return columns;
329
+ }
330
+ return columns.map((column) => {
331
+ if (column.width?.trim()) {
332
+ return column;
333
+ }
334
+ const width = ((resolveColumnWeight(column.key) / dynamicWeightTotal) *
335
+ 100).toFixed(2);
336
+ return {
337
+ ...column,
338
+ width: `${width}%`,
339
+ };
340
+ });
341
+ }
342
+ function getValue(record, key) {
343
+ return key.split('.').reduce((current, part) => {
344
+ if (!current || typeof current !== 'object') {
345
+ return undefined;
346
+ }
347
+ return current[part];
348
+ }, record);
349
+ }
350
+ function flattenRuntimeRow(row) {
351
+ const extra = row['extra'];
352
+ if (!extra || typeof extra !== 'object' || Array.isArray(extra)) {
353
+ return row;
354
+ }
355
+ return {
356
+ ...extra,
357
+ ...row,
358
+ };
359
+ }
360
+ function toDisplayValue(value, column) {
361
+ if (column.viewType !== 'Text') {
362
+ return value;
363
+ }
364
+ if (!value || typeof value !== 'object') {
365
+ return value;
366
+ }
367
+ const display = value['display'];
368
+ return typeof display === 'string' ? display : value;
369
+ }
370
+ function buildColumnsFromProperties(properties) {
371
+ return properties
372
+ .filter((property) => typeof property?.key === 'string' && property.key.length > 0)
373
+ .map((property) => ({
374
+ ...property,
375
+ key: property.key,
376
+ label: property.name?.display ||
377
+ property.name?.en ||
378
+ property.name?.ar ||
379
+ toLabel(property.key),
380
+ type: 'entity',
381
+ viewType: toViewType(property.viewType, property.key),
382
+ ...withLevelNameGrouping(property.key),
383
+ }));
384
+ }
385
+ /**
386
+ * Level Name is a free-text column, so the table's cardinality heuristic would
387
+ * never offer it in the group picker. The backend orders the whole result set
388
+ * by that label before paging, which makes its groups contiguous and therefore
389
+ * groupable — so opt it in explicitly and point the table at the identity
390
+ * field instead of the ambiguous label.
391
+ */
392
+ function withLevelNameGrouping(key) {
393
+ return key === WORK_CENTER_LEVEL_NAME_KEY
394
+ ? { groupable: true, groupKey: WORK_CENTER_LEVEL_GROUP_FIELD }
395
+ : {};
396
+ }
397
+ function buildColumns(columnsConfig) {
398
+ const propertyColumns = buildColumnsFromProperties(columnsConfig?.properties ?? []);
399
+ if (propertyColumns.length) {
400
+ return applySmartColumnWidths(propertyColumns);
401
+ }
402
+ const keys = columnsConfig?.columns?.length ? columnsConfig.columns : [];
403
+ return applySmartColumnWidths(keys.map((key) => ({
404
+ key,
405
+ label: toLabel(key),
406
+ type: 'entity',
407
+ viewType: toViewType(undefined, key),
408
+ ...withLevelNameGrouping(key),
409
+ })));
410
+ }
411
+ function toDisplayRows(rows, columns) {
412
+ const hasLevelName = columns.some((column) => column.key === WORK_CENTER_LEVEL_NAME_KEY);
413
+ return rows.map((row) => {
414
+ const sourceRow = flattenRuntimeRow(row);
415
+ const displayRow = { ...sourceRow };
416
+ for (const column of columns) {
417
+ const value = getValue(sourceRow, column.key);
418
+ displayRow[column.key] = {
419
+ ...column,
420
+ value: toDisplayValue(value, column),
421
+ };
422
+ }
423
+ if (hasLevelName) {
424
+ applyLevelNameGrouping(displayRow, sourceRow);
425
+ }
426
+ return displayRow;
427
+ });
428
+ }
429
+ /**
430
+ * Adds the Level Name grouping identity to a display row and normalizes a
431
+ * missing / restricted label to `—`.
432
+ *
433
+ * The backend omits `extra.levelDataName` when the record is missing, deleted,
434
+ * or the user can't see it — those rows must share one group and must never
435
+ * expose the numeric id as a label. Rows that do have a label are keyed by
436
+ * `context.levelDataId` so two records with the same name stay separate.
437
+ */
438
+ function applyLevelNameGrouping(displayRow, sourceRow) {
439
+ const cell = displayRow[WORK_CENTER_LEVEL_NAME_KEY];
440
+ const label = typeof cell?.value === 'string' ? cell.value.trim() : '';
441
+ if (!label) {
442
+ displayRow[WORK_CENTER_LEVEL_NAME_KEY] = {
443
+ ...cell,
444
+ value: WORK_CENTER_EMPTY_LABEL,
445
+ };
446
+ displayRow[WORK_CENTER_LEVEL_GROUP_FIELD] = '';
447
+ return;
448
+ }
449
+ const levelDataId = getValue(sourceRow, 'context.levelDataId');
450
+ const hasId = levelDataId !== null && levelDataId !== undefined && levelDataId !== '';
451
+ displayRow[WORK_CENTER_LEVEL_GROUP_FIELD] = hasId
452
+ ? `id:${String(levelDataId)}`
453
+ : `name:${label}`;
454
+ }
455
+ function buildMenuItems(cards) {
456
+ const mapped = cards.map((card, index) => ({
457
+ key: card.key,
458
+ title: card.name?.display || card.name?.en || card.name?.ar || toLabel(card.key),
459
+ subtitle: undefined,
460
+ count: card.count ?? 0,
461
+ color: AREA_COLORS[index % AREA_COLORS.length],
462
+ icon: card.icon ?? 'custom.task',
463
+ isAvailable: card.isAvailable !== false,
464
+ }));
465
+ const available = mapped.filter((card) => card.isAvailable);
466
+ const source = available.length ? available : mapped;
467
+ return source.map((card) => ({
468
+ key: card.key,
469
+ title: card.title,
470
+ subtitle: undefined,
471
+ count: card.count ?? 0,
472
+ color: card.color,
473
+ icon: card.icon ?? 'custom.task',
474
+ }));
475
+ }
476
+ /**
477
+ * KPI accent colors are owned by the backend (`stats[].color`) and used
478
+ * verbatim. Only when the backend sends no color do we fall back to the
479
+ * previous `KPI_COLORS` rotation by card position — never map a color from
480
+ * the stat key or label.
481
+ */
482
+ function buildKpis(stats, fallbackIcon) {
483
+ return stats.map((stat, index) => ({
484
+ title: String(stat.count ?? 0),
485
+ subTitle: stat.label.display,
486
+ icon: (fallbackIcon ?? 'custom.task'),
487
+ color: stat.color?.trim() || KPI_COLORS[index % KPI_COLORS.length],
488
+ }));
489
+ }
490
+ /** The backend sort that renders a grouped column as contiguous rows. */
491
+ function sortForGroup(groupBy) {
492
+ return groupBy ? [{ field: groupBy, dir: 'asc' }] : [];
493
+ }
494
+ function createDefaultContext(area) {
495
+ return {
496
+ area,
497
+ templateId: null,
498
+ levelDataId: null,
499
+ selectedCardKey: null,
500
+ page: 1,
501
+ pageSize: WORK_CENTER_LOCAL_FETCH_SIZE,
502
+ sort: [],
503
+ runtimeFilters: [],
504
+ includeStats: true,
505
+ };
506
+ }
507
+ function createDefaultAreaState(area) {
508
+ return {
509
+ context: createDefaultContext(area),
510
+ headerFilters: [],
511
+ columnFilters: [],
512
+ groupBy: null,
513
+ menuItems: [],
514
+ rows: [],
515
+ columns: [],
516
+ kpis: [],
517
+ runtimeFilterSchema: null,
518
+ totalCount: 0,
519
+ warnings: [],
520
+ lastLoadedAt: null,
521
+ };
522
+ }
523
+ /**
524
+ * Combines header (property-filter-builder) and column (in-table) rules into
525
+ * the single `runtimeFilters` payload the BE expects. Header rules come
526
+ * first; a column rule with the same `(field, op)` pair replaces the matching
527
+ * header rule.
528
+ */
529
+ function mergeRuntimeFilters(headerFilters, columnFilters) {
530
+ const seen = new Map();
531
+ const ordered = [];
532
+ const push = (rule) => {
533
+ const key = `${rule.field}::${rule.op}`;
534
+ if (!seen.has(key))
535
+ ordered.push(key);
536
+ seen.set(key, rule);
537
+ };
538
+ (headerFilters ?? []).forEach(push);
539
+ (columnFilters ?? []).forEach(push);
540
+ return sanitizeFilters(ordered.map((key) => seen.get(key)));
541
+ }
542
+ const WORK_CENTER_DEFAULT_STATE = {
543
+ activeArea: 'MyInbox',
544
+ byArea: {
545
+ MyInbox: createDefaultAreaState('MyInbox'),
546
+ TasksCenter: createDefaultAreaState('TasksCenter'),
547
+ Workspace: createDefaultAreaState('Workspace'),
548
+ },
549
+ lookups: [],
550
+ loadingActive: [],
551
+ errors: {},
552
+ };
553
+ function normalizeContext(context) {
554
+ return {
555
+ ...context,
556
+ page: clampPage(context.page, 1),
557
+ pageSize: clampPageSize(context.pageSize, WORK_CENTER_LOCAL_FETCH_SIZE),
558
+ sort: sanitizeSort(context.sort),
559
+ runtimeFilters: sanitizeFilters(context.runtimeFilters),
560
+ };
561
+ }
562
+ function buildContextFromInputs(currentContext, area, inputs = {},
563
+ /**
564
+ * Already-resolved grouped column. Grouping is executed as a backend sort,
565
+ * so when the host supplies no explicit `sort` the grouped column defines
566
+ * it — that is what makes the default grouping reach the very first request
567
+ * instead of costing a second round trip.
568
+ */
569
+ groupBy = null) {
570
+ const parsedCardKey = toSelectedCardKey(inputs.card);
571
+ const parsedTemplateId = toOptionalInt(inputs.templateId);
572
+ const parsedLevelDataId = toOptionalInt(inputs.levelDataId);
573
+ const hasPageInput = hasParamValue(inputs.page);
574
+ const parsedPage = hasPageInput ? toOptionalInt(inputs.page) : null;
575
+ const parsedPageSize = toOptionalInt(inputs.pageSize);
576
+ return normalizeContext({
577
+ ...currentContext,
578
+ area,
579
+ selectedCardKey: parsedCardKey ?? currentContext.selectedCardKey,
580
+ page: hasPageInput ? (parsedPage ?? 1) : 1,
581
+ pageSize: parsedPageSize ?? currentContext.pageSize,
582
+ templateId: parsedTemplateId ?? currentContext.templateId,
583
+ levelDataId: parsedLevelDataId ?? currentContext.levelDataId,
584
+ sort: hasParamValue(inputs.sort)
585
+ ? parseSortInput(inputs.sort)
586
+ : groupBy
587
+ ? sortForGroup(groupBy)
588
+ : inputs.sort === null
589
+ ? []
590
+ : currentContext.sort,
591
+ runtimeFilters: hasParamValue(inputs.filters)
592
+ ? parseFiltersInput(inputs.filters)
593
+ : inputs.filters === null
594
+ ? []
595
+ : currentContext.runtimeFilters,
596
+ });
597
+ }
598
+ function isSameContext(left, right) {
599
+ return (left.area === right.area &&
600
+ left.templateId === right.templateId &&
601
+ left.levelDataId === right.levelDataId &&
602
+ left.selectedCardKey === right.selectedCardKey &&
603
+ left.page === right.page &&
604
+ left.pageSize === right.pageSize &&
605
+ left.includeStats === right.includeStats &&
606
+ JSON.stringify(left.sort) === JSON.stringify(right.sort) &&
607
+ JSON.stringify(left.runtimeFilters) === JSON.stringify(right.runtimeFilters));
608
+ }
609
+ function mapRuntimeResponse(current, response) {
610
+ const selectedCard = response.selectedCard;
611
+ const menuItems = buildMenuItems(response.cards);
612
+ const requestedCardKey = selectedCard?.key ?? current.context.selectedCardKey ?? null;
613
+ const selectedCardKey = requestedCardKey &&
614
+ response.cards.some((card) => card.key === requestedCardKey)
615
+ ? requestedCardKey
616
+ : (menuItems[0]?.key ?? response.cards[0]?.key ?? null);
617
+ const selectedCardFromList = selectedCardKey
618
+ ? (response.cards.find((card) => card.key === selectedCardKey) ?? null)
619
+ : null;
620
+ const selectedMenuItem = menuItems.find((item) => item.key === selectedCardKey);
621
+ const columns = buildColumns(selectedCard?.columnsConfig ?? selectedCardFromList?.columnsConfig);
622
+ const rows = toDisplayRows(selectedCard?.items ?? [], columns);
623
+ const kpis = buildKpis(selectedCard?.stats ?? [], selectedMenuItem?.icon ?? null);
624
+ // A card that doesn't advertise the grouped column can't be grouped by it —
625
+ // drop it here rather than letting the table discover the stale column and
626
+ // bounce a second request. The sort goes with it when it was the one the
627
+ // grouping asked for.
628
+ const groupBy = current.groupBy && columns.some((column) => column.key === current.groupBy)
629
+ ? current.groupBy
630
+ : null;
631
+ const droppedGroup = !groupBy && current.groupBy;
632
+ const sort = droppedGroup && isSortForGroup(current.context.sort, current.groupBy)
633
+ ? []
634
+ : current.context.sort;
635
+ return {
636
+ ...current,
637
+ groupBy,
638
+ menuItems,
639
+ rows,
640
+ columns,
641
+ kpis,
642
+ runtimeFilterSchema: selectedCard?.runtimeFilterSchema ??
643
+ selectedCardFromList?.runtimeFilterSchema ??
644
+ null,
645
+ totalCount: selectedCard?.pagination.totalCount ?? 0,
646
+ warnings: response.warnings ?? [],
647
+ lastLoadedAt: new Date().toISOString(),
648
+ context: {
649
+ ...current.context,
650
+ selectedCardKey,
651
+ sort,
652
+ page: selectedCard?.pagination.page ?? current.context.page,
653
+ pageSize: selectedCard?.pagination.pageSize ?? current.context.pageSize,
654
+ },
655
+ };
656
+ }
657
+ /** True when `sort` is exactly the single rule a grouping would produce. */
658
+ function isSortForGroup(sort, groupBy) {
659
+ return !!groupBy && sort.length === 1 && sort[0].field === groupBy;
660
+ }
661
+
662
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
663
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
664
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
665
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
666
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
667
+ };
668
+ let WorkCenterState = class WorkCenterState {
669
+ http = inject(HttpClient);
670
+ static getState(state) {
671
+ return state;
672
+ }
673
+ static activeArea(state) {
674
+ return state.activeArea;
675
+ }
676
+ static activeSnapshot(activeArea, state) {
677
+ return state.byArea[activeArea];
678
+ }
679
+ static context(snapshot) {
680
+ return snapshot.context;
681
+ }
682
+ static menuItems(snapshot) {
683
+ return snapshot.menuItems;
684
+ }
685
+ static rows(snapshot) {
686
+ return snapshot.rows;
687
+ }
688
+ static columns(snapshot) {
689
+ return snapshot.columns;
690
+ }
691
+ static kpis(snapshot) {
692
+ return snapshot.kpis;
693
+ }
694
+ static runtimeFilterSchema(snapshot) {
695
+ return snapshot.runtimeFilterSchema;
696
+ }
697
+ static headerFilters(snapshot) {
698
+ return snapshot.headerFilters;
699
+ }
700
+ static columnFilters(snapshot) {
701
+ return snapshot.columnFilters;
702
+ }
703
+ static groupBy(snapshot) {
704
+ return snapshot.groupBy;
705
+ }
706
+ static totalCount(snapshot) {
707
+ return snapshot.totalCount;
708
+ }
709
+ static warnings(snapshot) {
710
+ return snapshot.warnings;
711
+ }
712
+ static lookups(state) {
713
+ return state.lookups;
714
+ }
715
+ static getLoadingActive(state) {
716
+ return state.loadingActive;
717
+ }
718
+ static getErrors(state) {
719
+ return state.errors;
720
+ }
721
+ enterArea(ctx, action) {
722
+ if (ctx.getState().activeArea === action.area)
723
+ return;
724
+ ctx.patchState({ activeArea: action.area });
725
+ }
726
+ hydrateFromContext(ctx, action) {
727
+ const state = ctx.getState();
728
+ const current = state.byArea[action.area];
729
+ const nextContext = normalizeContext({
730
+ ...current.context,
731
+ ...action.patch,
732
+ area: action.area,
733
+ });
734
+ if (state.activeArea === action.area &&
735
+ isSameContext(current.context, nextContext)) {
736
+ return;
737
+ }
738
+ // External `runtimeFilters` writes are treated as header-slice writes so
739
+ // the in-table column filter slice doesn't get stranded out of sync.
740
+ const filtersChanged = action.patch.runtimeFilters !== undefined;
741
+ const nextHeaderFilters = filtersChanged
742
+ ? nextContext.runtimeFilters
743
+ : current.headerFilters;
744
+ const nextColumnFilters = filtersChanged ? [] : current.columnFilters;
745
+ ctx.patchState({
746
+ activeArea: action.area,
747
+ byArea: {
748
+ ...state.byArea,
749
+ [action.area]: {
750
+ ...current,
751
+ headerFilters: nextHeaderFilters,
752
+ columnFilters: nextColumnFilters,
753
+ context: nextContext,
754
+ },
755
+ },
756
+ });
757
+ }
758
+ setParams(ctx, action) {
759
+ const state = ctx.getState();
760
+ const current = state.byArea[action.area];
761
+ // A card switch invalidates everything scoped to the previous card. The
762
+ // host usually drops those query params too, but a stale URL must not be
763
+ // able to re-apply a filter on a field the new card doesn't have.
764
+ const cardChanged = resolveSelectedCardKeyFromInputs(current.context, action.inputs) !==
765
+ current.context.selectedCardKey;
766
+ // Resolve grouping first: with no explicit `sort` input it is what defines
767
+ // the backend sort.
768
+ const nextGroupBy = resolveGroupByFromInputs(cardChanged ? null : current.groupBy, action.inputs?.group);
769
+ const builtContext = buildContextFromInputs(current.context, action.area, action.inputs, nextGroupBy);
770
+ const filtersFromInputs = action.inputs?.filters !== undefined;
771
+ const nextContext = cardChanged && !filtersFromInputs
772
+ ? { ...builtContext, runtimeFilters: [] }
773
+ : builtContext;
774
+ const areaChanged = state.activeArea !== action.area;
775
+ const contextChanged = !isSameContext(current.context, nextContext);
776
+ const groupChanged = nextGroupBy !== current.groupBy;
777
+ const runtimeLoading = state.loadingActive.includes(WorkCenterActionKey.LoadRuntime);
778
+ const shouldLoad = areaChanged || contextChanged || !runtimeLoading;
779
+ if (areaChanged || contextChanged || groupChanged) {
780
+ // URL-derived filters land on the header slice. Anything previously
781
+ // applied via the in-table column filters is dropped so the BE payload
782
+ // matches what the user sees on the page header.
783
+ const nextHeaderFilters = filtersFromInputs
784
+ ? nextContext.runtimeFilters
785
+ : cardChanged
786
+ ? []
787
+ : current.headerFilters;
788
+ const nextColumnFilters = filtersFromInputs || cardChanged ? [] : current.columnFilters;
789
+ ctx.patchState({
790
+ activeArea: action.area,
791
+ byArea: {
792
+ ...state.byArea,
793
+ [action.area]: {
794
+ ...current,
795
+ headerFilters: nextHeaderFilters,
796
+ columnFilters: nextColumnFilters,
797
+ groupBy: nextGroupBy,
798
+ context: nextContext,
799
+ },
800
+ },
801
+ });
802
+ }
803
+ if (!shouldLoad)
804
+ return;
805
+ return ctx.dispatch(new LoadRuntime(action.area, 'route-enter'));
806
+ }
807
+ setLookups(ctx, action) {
808
+ if (ctx.getState().lookups === action.lookups) {
809
+ return;
810
+ }
811
+ ctx.patchState({
812
+ lookups: Array.isArray(action.lookups) ? action.lookups : [],
813
+ });
814
+ }
815
+ applyHeaderFilters(ctx, action) {
816
+ return this.applyFilterSlice(ctx, action.area, {
817
+ headerFilters: action.filters,
818
+ });
819
+ }
820
+ applyColumnFilters(ctx, action) {
821
+ return this.applyFilterSlice(ctx, action.area, {
822
+ columnFilters: action.filters,
823
+ });
824
+ }
825
+ selectCard(ctx, action) {
826
+ const state = ctx.getState();
827
+ const current = state.byArea[action.area];
828
+ if (current.context.selectedCardKey === action.selectedCardKey) {
829
+ return;
830
+ }
831
+ ctx.patchState({
832
+ activeArea: action.area,
833
+ byArea: {
834
+ ...state.byArea,
835
+ [action.area]: {
836
+ ...current,
837
+ headerFilters: [],
838
+ columnFilters: [],
839
+ groupBy: null,
840
+ context: {
841
+ ...current.context,
842
+ selectedCardKey: action.selectedCardKey,
843
+ runtimeFilters: [],
844
+ sort: [],
845
+ page: 1,
846
+ },
847
+ },
848
+ },
849
+ });
850
+ return ctx.dispatch(new LoadRuntime(action.area, 'menu-change'));
851
+ }
852
+ /**
853
+ * Grouping is a backend concern: the table only renders contiguous rows, so
854
+ * the grouped column is pushed down as the single `context.sort` entry and
855
+ * pagination restarts at page 1. Clearing the group sends `sort: []`.
856
+ */
857
+ setGroupBy(ctx, action) {
858
+ const state = ctx.getState();
859
+ const current = state.byArea[action.area];
860
+ const nextGroupBy = action.groupBy?.trim() ? action.groupBy : null;
861
+ const nextSort = nextGroupBy
862
+ ? [{ field: nextGroupBy, dir: action.dir }]
863
+ : [];
864
+ const sameGroup = current.groupBy === nextGroupBy;
865
+ const sameSort = JSON.stringify(current.context.sort) === JSON.stringify(nextSort);
866
+ if (sameGroup && sameSort)
867
+ return;
868
+ ctx.patchState({
869
+ activeArea: action.area,
870
+ byArea: {
871
+ ...state.byArea,
872
+ [action.area]: {
873
+ ...current,
874
+ groupBy: nextGroupBy,
875
+ context: sameSort
876
+ ? current.context
877
+ : { ...current.context, sort: nextSort, page: 1 },
878
+ },
879
+ },
880
+ });
881
+ // A group change that doesn't move the backend order (already sorted by
882
+ // that field) is a pure render concern — no refetch.
883
+ if (sameSort)
884
+ return;
885
+ return ctx.dispatch(new LoadRuntime(action.area, 'group-change'));
886
+ }
887
+ clearAllFilters(ctx, action) {
888
+ return this.applyFilterSlice(ctx, action.area, {
889
+ headerFilters: [],
890
+ columnFilters: [],
891
+ });
892
+ }
893
+ applyFilterSlice(ctx, area, patch) {
894
+ const state = ctx.getState();
895
+ const current = state.byArea[area];
896
+ const headerFilters = patch.headerFilters ?? current.headerFilters;
897
+ const columnFilters = patch.columnFilters ?? current.columnFilters;
898
+ const runtimeFilters = mergeRuntimeFilters(headerFilters, columnFilters);
899
+ const sameHeader = JSON.stringify(headerFilters) === JSON.stringify(current.headerFilters);
900
+ const sameColumn = JSON.stringify(columnFilters) === JSON.stringify(current.columnFilters);
901
+ const sameMerged = JSON.stringify(runtimeFilters) ===
902
+ JSON.stringify(current.context.runtimeFilters);
903
+ if (sameHeader && sameColumn && sameMerged) {
904
+ return;
905
+ }
906
+ ctx.patchState({
907
+ activeArea: area,
908
+ byArea: {
909
+ ...state.byArea,
910
+ [area]: {
911
+ ...current,
912
+ headerFilters,
913
+ columnFilters,
914
+ context: {
915
+ ...current.context,
916
+ runtimeFilters,
917
+ page: 1,
918
+ },
919
+ },
920
+ },
921
+ });
922
+ return ctx.dispatch(new LoadRuntime(area, 'filters-change'));
923
+ }
924
+ loadRuntime(ctx, action) {
925
+ const state = ctx.getState();
926
+ const areaState = state.byArea[action.area];
927
+ const request = normalizeContext(areaState.context);
928
+ const nextAreaState = {
929
+ ...areaState,
930
+ rows: [],
931
+ kpis: [],
932
+ totalCount: 0,
933
+ };
934
+ ctx.patchState({
935
+ byArea: {
936
+ ...state.byArea,
937
+ [action.area]: nextAreaState,
938
+ },
939
+ });
940
+ return handleApiRequest({
941
+ ctx,
942
+ key: WorkCenterActionKey.LoadRuntime,
943
+ request$: this.getRuntime(request),
944
+ onSuccess: (response, latestState) => {
945
+ const current = latestState.byArea[action.area];
946
+ return {
947
+ byArea: {
948
+ ...latestState.byArea,
949
+ [action.area]: mapRuntimeResponse(current, response),
950
+ },
951
+ };
952
+ },
953
+ errorMessage: 'Failed to load Work Center runtime.',
954
+ }).pipe(catchError(() => EMPTY));
955
+ }
956
+ getRuntime(request) {
957
+ return this.http
958
+ .post('workcenter/runtime', request)
959
+ .pipe(map((response) => {
960
+ if (response.code === 1)
961
+ return response.data;
962
+ const fallbackError = 'Failed to load Work Center runtime.';
963
+ const message = response.errors?.message ??
964
+ response.message ??
965
+ fallbackError;
966
+ throw new Error(message);
967
+ }));
968
+ }
969
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: WorkCenterState, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
970
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: WorkCenterState });
971
+ };
972
+ __decorate([
973
+ Action(EnterArea)
974
+ ], WorkCenterState.prototype, "enterArea", null);
975
+ __decorate([
976
+ Action(HydrateFromContext)
977
+ ], WorkCenterState.prototype, "hydrateFromContext", null);
978
+ __decorate([
979
+ Action(SetParams)
980
+ ], WorkCenterState.prototype, "setParams", null);
981
+ __decorate([
982
+ Action(SetLookups)
983
+ ], WorkCenterState.prototype, "setLookups", null);
984
+ __decorate([
985
+ Action(ApplyHeaderFilters)
986
+ ], WorkCenterState.prototype, "applyHeaderFilters", null);
987
+ __decorate([
988
+ Action(ApplyColumnFilters)
989
+ ], WorkCenterState.prototype, "applyColumnFilters", null);
990
+ __decorate([
991
+ Action(SelectCard)
992
+ ], WorkCenterState.prototype, "selectCard", null);
993
+ __decorate([
994
+ Action(SetGroupBy)
995
+ ], WorkCenterState.prototype, "setGroupBy", null);
996
+ __decorate([
997
+ Action(ClearAllFilters)
998
+ ], WorkCenterState.prototype, "clearAllFilters", null);
999
+ __decorate([
1000
+ Action(LoadRuntime)
1001
+ ], WorkCenterState.prototype, "loadRuntime", null);
1002
+ __decorate([
1003
+ Selector()
1004
+ ], WorkCenterState, "getState", null);
1005
+ __decorate([
1006
+ Selector()
1007
+ ], WorkCenterState, "activeArea", null);
1008
+ __decorate([
1009
+ Selector([WorkCenterState.activeArea, WorkCenterState.getState])
1010
+ ], WorkCenterState, "activeSnapshot", null);
1011
+ __decorate([
1012
+ Selector([WorkCenterState.activeSnapshot])
1013
+ ], WorkCenterState, "context", null);
1014
+ __decorate([
1015
+ Selector([WorkCenterState.activeSnapshot])
1016
+ ], WorkCenterState, "menuItems", null);
1017
+ __decorate([
1018
+ Selector([WorkCenterState.activeSnapshot])
1019
+ ], WorkCenterState, "rows", null);
1020
+ __decorate([
1021
+ Selector([WorkCenterState.activeSnapshot])
1022
+ ], WorkCenterState, "columns", null);
1023
+ __decorate([
1024
+ Selector([WorkCenterState.activeSnapshot])
1025
+ ], WorkCenterState, "kpis", null);
1026
+ __decorate([
1027
+ Selector([WorkCenterState.activeSnapshot])
1028
+ ], WorkCenterState, "runtimeFilterSchema", null);
1029
+ __decorate([
1030
+ Selector([WorkCenterState.activeSnapshot])
1031
+ ], WorkCenterState, "headerFilters", null);
1032
+ __decorate([
1033
+ Selector([WorkCenterState.activeSnapshot])
1034
+ ], WorkCenterState, "columnFilters", null);
1035
+ __decorate([
1036
+ Selector([WorkCenterState.activeSnapshot])
1037
+ ], WorkCenterState, "groupBy", null);
1038
+ __decorate([
1039
+ Selector([WorkCenterState.activeSnapshot])
1040
+ ], WorkCenterState, "totalCount", null);
1041
+ __decorate([
1042
+ Selector([WorkCenterState.activeSnapshot])
1043
+ ], WorkCenterState, "warnings", null);
1044
+ __decorate([
1045
+ Selector()
1046
+ ], WorkCenterState, "lookups", null);
1047
+ __decorate([
1048
+ Selector()
1049
+ ], WorkCenterState, "getLoadingActive", null);
1050
+ __decorate([
1051
+ Selector()
1052
+ ], WorkCenterState, "getErrors", null);
1053
+ WorkCenterState = __decorate([
1054
+ State({
1055
+ name: 'workCenter',
1056
+ defaults: WORK_CENTER_DEFAULT_STATE,
1057
+ })
1058
+ ], WorkCenterState);
1059
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: WorkCenterState, decorators: [{
1060
+ type: Injectable
1061
+ }], propDecorators: { enterArea: [], hydrateFromContext: [], setParams: [], setLookups: [], applyHeaderFilters: [], applyColumnFilters: [], selectCard: [], setGroupBy: [], clearAllFilters: [], loadRuntime: [] } });
1062
+
1063
+ class WorkCenterFacade {
1064
+ store = inject(Store);
1065
+ activeArea = select(WorkCenterState.activeArea);
1066
+ context = select(WorkCenterState.context);
1067
+ menuItems = select(WorkCenterState.menuItems);
1068
+ rows = select(WorkCenterState.rows);
1069
+ columns = select(WorkCenterState.columns);
1070
+ kpis = select(WorkCenterState.kpis);
1071
+ lookups = select(WorkCenterState.lookups);
1072
+ runtimeFilterSchema = select(WorkCenterState.runtimeFilterSchema);
1073
+ headerFilters = select(WorkCenterState.headerFilters);
1074
+ columnFilters = select(WorkCenterState.columnFilters);
1075
+ groupBy = select(WorkCenterState.groupBy);
1076
+ totalCount = select(WorkCenterState.totalCount);
1077
+ warnings = select(WorkCenterState.warnings);
1078
+ loadingActive = select(WorkCenterState.getLoadingActive);
1079
+ errors = select(WorkCenterState.getErrors);
1080
+ loading = computed(() => this.loadingActive().includes(WorkCenterActionKey.LoadRuntime), ...(ngDevMode ? [{ debugName: "loading" }] : /* istanbul ignore next */ []));
1081
+ error = computed(() => this.errors()[WorkCenterActionKey.LoadRuntime] ?? null, ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
1082
+ /**
1083
+ * Snapshot reads for callers that must observe state *immediately* after a
1084
+ * dispatch — e.g. an output handler mirroring the runtime query into the URL.
1085
+ * The `select()` signals above are the right choice everywhere else.
1086
+ */
1087
+ snapshotContext() {
1088
+ return this.store.selectSnapshot(WorkCenterState.context);
1089
+ }
1090
+ snapshotGroupBy() {
1091
+ return this.store.selectSnapshot(WorkCenterState.groupBy);
1092
+ }
1093
+ enterArea(area) {
1094
+ return this.store.dispatch(new EnterArea(area));
1095
+ }
1096
+ hydrateContext(area, patch) {
1097
+ return this.store.dispatch(new HydrateFromContext(area, patch));
1098
+ }
1099
+ setParams(area, inputs) {
1100
+ return this.store.dispatch(new SetParams(area, inputs));
1101
+ }
1102
+ setLookups(lookups) {
1103
+ return this.store.dispatch(new SetLookups(lookups));
1104
+ }
1105
+ /**
1106
+ * Switches card and drops the previous card's filters, grouping and sort —
1107
+ * each card has its own columns and filter schema.
1108
+ */
1109
+ selectCardAndLoad(area, selectedCardKey) {
1110
+ return this.store.dispatch(new SelectCard(area, selectedCardKey));
1111
+ }
1112
+ applyTableLazyLoadAndLoad(area, event) {
1113
+ const context = this.store.selectSnapshot(WorkCenterState.context);
1114
+ const patch = {};
1115
+ let changed = false;
1116
+ const page = this.toPositiveInt(event?.currentPage);
1117
+ if (page !== null && page !== context.page) {
1118
+ patch.page = page;
1119
+ changed = true;
1120
+ }
1121
+ const pageSize = this.toPositiveInt(event?.pageSize);
1122
+ if (pageSize !== null) {
1123
+ const normalizedPageSize = Math.min(WORK_CENTER_MAX_PAGE_SIZE, Math.max(1, pageSize));
1124
+ if (normalizedPageSize !== context.pageSize) {
1125
+ patch.pageSize = normalizedPageSize;
1126
+ changed = true;
1127
+ }
1128
+ }
1129
+ const sort = this.toSortFromLazyEvent(event);
1130
+ if (sort && !this.isSameSort(sort, context.sort)) {
1131
+ patch.sort = sort;
1132
+ changed = true;
1133
+ }
1134
+ if (!changed) {
1135
+ return;
1136
+ }
1137
+ return this.store.dispatch([
1138
+ new HydrateFromContext(area, patch),
1139
+ new LoadRuntime(area, 'table-lazy'),
1140
+ ]);
1141
+ }
1142
+ applyRuntimeFiltersAndLoad(area, runtimeFilters) {
1143
+ // Back-compat: any caller that previously set the entire `runtimeFilters`
1144
+ // array now lands on the header slice. The in-table column filter slice is
1145
+ // cleared so the merged payload matches what callers expect.
1146
+ return this.store.dispatch(new ApplyHeaderFilters(area, runtimeFilters));
1147
+ }
1148
+ /**
1149
+ * Replaces the property-filter-builder slice. Resets pagination to page 1
1150
+ * and reloads with merged `headerFilters` + `columnFilters`.
1151
+ */
1152
+ applyHeaderFiltersAndLoad(area, runtimeFilters) {
1153
+ return this.store.dispatch(new ApplyHeaderFilters(area, runtimeFilters));
1154
+ }
1155
+ /**
1156
+ * Replaces the in-table column filter slice. Resets pagination to page 1
1157
+ * and reloads with merged `headerFilters` + `columnFilters`.
1158
+ */
1159
+ applyColumnFiltersAndLoad(area, runtimeFilters) {
1160
+ return this.store.dispatch(new ApplyColumnFilters(area, runtimeFilters));
1161
+ }
1162
+ /**
1163
+ * Groups the table by `groupBy` (or clears grouping with `null`). Pushes the
1164
+ * grouped column down as the single backend sort, resets to page 1 and
1165
+ * reloads. Safe to call from the table's `groupByChange` — the lazy event
1166
+ * that follows carries the same sort and is absorbed as a no-op.
1167
+ */
1168
+ setGroupByAndLoad(area, groupBy, dir = 'asc') {
1169
+ return this.store.dispatch(new SetGroupBy(area, groupBy, dir));
1170
+ }
1171
+ /**
1172
+ * Clears both header and column filter slices in one state update,
1173
+ * triggering a single BE reload.
1174
+ */
1175
+ clearAllFiltersAndLoad(area) {
1176
+ return this.store.dispatch(new ClearAllFilters(area));
1177
+ }
1178
+ loadRuntime(area, reason = 'manual') {
1179
+ return this.store.dispatch(new LoadRuntime(area, reason));
1180
+ }
1181
+ toPositiveInt(value) {
1182
+ const parsed = Number(value);
1183
+ if (!Number.isFinite(parsed)) {
1184
+ return null;
1185
+ }
1186
+ return Math.max(1, Math.floor(parsed));
1187
+ }
1188
+ /**
1189
+ * `mt-table` always reports its sort on a lazy event, so a `null` field is an
1190
+ * explicit "no sort" and must clear `context.sort` (the BE contract asks for
1191
+ * `sort: []`). Only an event with no `sortField` key at all — nothing the
1192
+ * current table emits — leaves the existing sort alone.
1193
+ */
1194
+ toSortFromLazyEvent(event) {
1195
+ if (!event || !('sortField' in event)) {
1196
+ return null;
1197
+ }
1198
+ const sortField = event.sortField;
1199
+ if (typeof sortField !== 'string' || !sortField.length) {
1200
+ return [];
1201
+ }
1202
+ return [
1203
+ {
1204
+ field: sortField,
1205
+ dir: event.sortOrder === -1 ? 'desc' : 'asc',
1206
+ },
1207
+ ];
1208
+ }
1209
+ isSameSort(left, right) {
1210
+ const leftValue = left ?? [];
1211
+ const rightValue = right ?? [];
1212
+ if (leftValue.length !== rightValue.length) {
1213
+ return false;
1214
+ }
1215
+ return leftValue.every((rule, index) => rule.field === rightValue[index]?.field &&
1216
+ rule.dir === rightValue[index]?.dir);
1217
+ }
1218
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: WorkCenterFacade, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1219
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: WorkCenterFacade, providedIn: 'root' });
1220
+ }
1221
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: WorkCenterFacade, decorators: [{
1222
+ type: Injectable,
1223
+ args: [{
1224
+ providedIn: 'root',
1225
+ }]
1226
+ }] });
1227
+
1228
+ const APP_STATES = [WorkCenterState];
1229
+
1230
+ // Context keys contain `/`; keep them in one route segment without `%2F`/`%25`.
1231
+ const ROUTE_CONTEXT_KEY_PREFIX = 'wc1.';
1232
+ const HEX_PAIR_PATTERN = /^[\da-f]{2}$/i;
1233
+ function encodeWorkCenterRouteContextKey(contextKey) {
1234
+ const encoded = encodeURIComponent(contextKey);
1235
+ let hex = '';
1236
+ for (let index = 0; index < encoded.length; index += 1) {
1237
+ if (encoded[index] === '%') {
1238
+ hex += encoded.slice(index + 1, index + 3).toLowerCase();
1239
+ index += 2;
1240
+ continue;
1241
+ }
1242
+ hex += encoded.charCodeAt(index).toString(16).padStart(2, '0');
1243
+ }
1244
+ return `${ROUTE_CONTEXT_KEY_PREFIX}${hex}`;
1245
+ }
1246
+ function decodeWorkCenterRouteContextKey(value) {
1247
+ if (!value) {
1248
+ return null;
1249
+ }
1250
+ if (value.startsWith(ROUTE_CONTEXT_KEY_PREFIX)) {
1251
+ return decodeRouteSafeContextKey(value.slice(ROUTE_CONTEXT_KEY_PREFIX.length));
1252
+ }
1253
+ try {
1254
+ return decodeURIComponent(value);
1255
+ }
1256
+ catch {
1257
+ return value;
1258
+ }
1259
+ }
1260
+ function decodeRouteSafeContextKey(hex) {
1261
+ if (hex.length % 2 !== 0) {
1262
+ return null;
1263
+ }
1264
+ const parts = hex.match(/.{2}/g) ?? [];
1265
+ if (parts.some((part) => !HEX_PAIR_PATTERN.test(part))) {
1266
+ return null;
1267
+ }
1268
+ try {
1269
+ return decodeURIComponent(parts.map((part) => `%${part.toUpperCase()}`).join(''));
1270
+ }
1271
+ catch {
1272
+ return null;
1273
+ }
1274
+ }
1275
+
1276
+ /*
1277
+ * The light entry: the Work Center store, its models and the route-key helpers. Startup code
1278
+ * (a store config, a top-bar search) imports this instead of `@masterteam/work-center`, whose
1279
+ * pages load the standard grid.
1280
+ */
1281
+
1282
+ /**
1283
+ * Generated bundle index. Do not edit.
1284
+ */
1285
+
1286
+ export { APP_STATES, ApplyColumnFilters, ApplyHeaderFilters, ClearAllFilters, EnterArea, HydrateFromContext, LoadRuntime, SelectCard, SetGroupBy, SetLookups, SetParams, WORK_CENTER_DEFAULT_STATE, WORK_CENTER_EMPTY_LABEL, WORK_CENTER_GROUP_NONE, WORK_CENTER_LEVEL_GROUP_FIELD, WORK_CENTER_LEVEL_NAME_KEY, WORK_CENTER_MAX_FILTERS, WORK_CENTER_MAX_PAGE_SIZE, WORK_CENTER_MAX_SORT, WORK_CENTER_QUERY_VERSION, WorkCenterActionKey, WorkCenterFacade, WorkCenterState, decodeWorkCenterRouteContextKey, encodeWorkCenterRouteContextKey };
1287
+ //# sourceMappingURL=masterteam-work-center-state.mjs.map