@masterteam/components 0.0.343 → 0.0.345

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.
@@ -1,12 +1,14 @@
1
1
  import * as i0 from '@angular/core';
2
- import { signal, Injectable, InjectionToken, inject, input, computed, DestroyRef, ChangeDetectionStrategy, Component, viewChild, ElementRef, afterNextRender, Directive, effect, untracked, ViewEncapsulation, output, NgZone, model } from '@angular/core';
2
+ import { signal, Injectable, InjectionToken, inject, computed, input, ChangeDetectionStrategy, Component, DestroyRef, output, viewChild, ElementRef, effect, afterNextRender, Directive, untracked, ViewEncapsulation, NgZone, model } from '@angular/core';
3
3
  import { Tooltip, TruncateTooltip } from '@masterteam/components/tooltip';
4
4
  import { Icon } from '@masterteam/icons';
5
5
  import { NgTemplateOutlet, NgComponentOutlet, DOCUMENT } from '@angular/common';
6
- import { TranslocoPipe, TranslocoService } from '@jsverse/transloco';
6
+ import { TranslocoService, TranslocoPipe } from '@jsverse/transloco';
7
7
  import { Popover } from 'primeng/popover';
8
8
  import { MTDateFormatPipe, REQUEST_CONTEXT, coerceCheckboxValue, readableTextOn, getLightColor } from '@masterteam/components';
9
- import { HttpClient, HttpContext } from '@angular/common/http';
9
+ import { ModalService } from '@masterteam/components/modal';
10
+ import { HttpHeaders, HttpClient, HttpContext } from '@angular/common/http';
11
+ import { of, forkJoin, map, catchError, switchMap, finalize, take, EMPTY } from 'rxjs';
10
12
  import { toSignal } from '@angular/core/rxjs-interop';
11
13
  import { Avatar } from '@masterteam/components/avatar';
12
14
  import { SecureImagePipe, UploadField } from '@masterteam/components/upload-field';
@@ -14,9 +16,7 @@ import { Progress } from '@masterteam/components/progress';
14
16
  import * as i1 from '@angular/forms';
15
17
  import { FormsModule } from '@angular/forms';
16
18
  import { Button } from '@masterteam/components/button';
17
- import { forkJoin, finalize, of, take, switchMap, EMPTY, map, catchError } from 'rxjs';
18
19
  import { Chip } from '@masterteam/components/chip';
19
- import { ModalService } from '@masterteam/components/modal';
20
20
  import * as i1$1 from 'primeng/tooltip';
21
21
  import { TooltipModule } from 'primeng/tooltip';
22
22
  import { CdkDrag, CdkDropList, CdkDragPlaceholder } from '@angular/cdk/drag-drop';
@@ -346,6 +346,10 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImpor
346
346
  */
347
347
  const ENTITY_LIST_TABLE_COMPONENT = new InjectionToken('ENTITY_LIST_TABLE_COMPONENT');
348
348
 
349
+ /** Records named one by one when the owner's list did not have them. */
350
+ const SINGLE_READS = 20;
351
+ /** A missing name only costs a label: never a toast. */
352
+ const SILENT = new HttpHeaders({ noMessage: 'true' });
349
353
  /**
350
354
  * Reads the latest saved calculation of a value. The request never
351
355
  * recalculates anything; the response is marked `no-store`, so every open
@@ -369,6 +373,104 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImpor
369
373
  type: Injectable,
370
374
  args: [{ providedIn: 'root' }]
371
375
  }] });
376
+ /**
377
+ * Names the records a calculation read (schedule items, financial rows) through
378
+ * the normal runtime record reads, so a contributor reads as its title rather
379
+ * than its id. Only names are taken; the numbers stay the captured ones.
380
+ */
381
+ class CalculationRecordNames {
382
+ http = inject(HttpClient);
383
+ /**
384
+ * Names by {@link calculationRecordKey}. A record the reader may not see, or
385
+ * any failed read, is simply absent.
386
+ */
387
+ read(owner, refs) {
388
+ const byContext = new Map();
389
+ for (const ref of refs) {
390
+ const context = toFetchContextKey(ref.contextKey);
391
+ if (!context || !(ref.recordId > 0))
392
+ continue;
393
+ const ids = byContext.get(context) ?? new Set();
394
+ ids.add(ref.recordId);
395
+ byContext.set(context, ids);
396
+ }
397
+ if (!byContext.size) {
398
+ return of({});
399
+ }
400
+ // A level record's own rows (its schedule, its financial lines) are read
401
+ // in one list; a module record's are read one by one.
402
+ const ownerLevelData = /^level:\d+$/i.test(owner.contextKey.trim())
403
+ ? owner.recordId
404
+ : null;
405
+ return forkJoin([...byContext].map(([context, ids]) => this.readContext(context, [...ids], ownerLevelData))).pipe(map((parts) => Object.assign({}, ...parts)));
406
+ }
407
+ readContext(context, ids, ownerLevelData) {
408
+ const query = (propertyKeys) => this.http
409
+ .post('fetch/query', {
410
+ contextKey: context,
411
+ projection: 'Flat',
412
+ propertyKeys,
413
+ filters: [
414
+ {
415
+ key: 'levelDataId',
416
+ operator: 'Equals',
417
+ value: String(ownerLevelData),
418
+ },
419
+ ],
420
+ page: 1,
421
+ pageSize: 500,
422
+ }, { headers: SILENT })
423
+ .pipe(map((response) => response?.data?.records ?? []));
424
+ const listed = ownerLevelData === null
425
+ ? of([])
426
+ : // Only the name column: every column is ~30x the payload. A module
427
+ // without a `name` property (Financial) rejects the key; its
428
+ // records still carry a name when no column is named.
429
+ query(['name']).pipe(catchError(() => query([])), catchError(() => of([])));
430
+ return listed.pipe(switchMap((records) => {
431
+ const names = {};
432
+ for (const record of records) {
433
+ if (ids.includes(record.id) && record.name?.trim()) {
434
+ names[calculationRecordKey(context, record.id)] = record.name;
435
+ }
436
+ }
437
+ const missing = ids
438
+ .filter((id) => !names[calculationRecordKey(context, id)])
439
+ .slice(0, SINGLE_READS);
440
+ if (!missing.length) {
441
+ return of(names);
442
+ }
443
+ return forkJoin(missing.map((id) => this.http
444
+ .get(`fetch/records/${id}`, {
445
+ params: { contextKey: context, projection: 'Flat' },
446
+ headers: SILENT,
447
+ })
448
+ .pipe(map((response) => response?.data?.record ?? null), catchError(() => of(null))))).pipe(map((single) => {
449
+ for (const record of single) {
450
+ if (record?.name?.trim()) {
451
+ names[calculationRecordKey(context, record.id)] = record.name;
452
+ }
453
+ }
454
+ return names;
455
+ }));
456
+ }));
457
+ }
458
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: CalculationRecordNames, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
459
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: CalculationRecordNames, providedIn: 'root' });
460
+ }
461
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: CalculationRecordNames, decorators: [{
462
+ type: Injectable,
463
+ args: [{ providedIn: 'root' }]
464
+ }] });
465
+ /** `Level:1/Module:4` → `level:1/module:4`, the casing record reads use. */
466
+ function toFetchContextKey(contextKey) {
467
+ const key = toCalculationContextKey(contextKey ?? '');
468
+ return key ? key.toLowerCase() : null;
469
+ }
470
+ /** The key a record's name is stored under. */
471
+ function calculationRecordKey(contextKey, recordId) {
472
+ return `${toFetchContextKey(contextKey) ?? ''}#${recordId}`;
473
+ }
372
474
  /**
373
475
  * The context key in the casing the endpoint accepts. Fetch contexts are
374
476
  * written `level:12/module:5`, but this endpoint validates `Level:12/Module:5`
@@ -387,17 +489,15 @@ function toCalculationContextKey(contextKey) {
387
489
  return moduleOnly ? `Module:${moduleOnly[1]}` : null;
388
490
  }
389
491
  /**
390
- * What a value's calculated-value mark explains on click: only a calculated
391
- * value whose host named the record it was read from. A status is
392
- * recalculated but has no formula (the endpoint answers `unsupported`), so it
393
- * keeps the plain mark.
492
+ * What a value's calculated-value mark explains on click: any calculated value
493
+ * (a formula, a status, a generated code, a date or an amount) whose host
494
+ * named the record it was read from.
394
495
  */
395
496
  function toCalculationExplanationTarget(entity, label) {
396
497
  const source = entity?.calculationSource;
397
498
  if (!entity?.calculated ||
398
499
  !source ||
399
500
  !entity.key ||
400
- entity.viewType === 'Status' ||
401
501
  !(source.recordId > 0) ||
402
502
  !toCalculationContextKey(source.contextKey)) {
403
503
  return null;
@@ -407,8 +507,20 @@ function toCalculationExplanationTarget(entity, label) {
407
507
  propertyKey: entity.key,
408
508
  label: label || entity.name || entity.key,
409
509
  displayedValue: entity.rawValue,
510
+ viewType: entity.viewType,
511
+ statusNames: statusNamesOf(entity.value),
410
512
  };
411
513
  }
514
+ /** The name of the status on screen, keyed by its status key. */
515
+ function statusNamesOf(value) {
516
+ if (!value || typeof value !== 'object') {
517
+ return undefined;
518
+ }
519
+ const { key, display } = value;
520
+ return typeof key === 'string' && typeof display === 'string' && display
521
+ ? { [key]: display }
522
+ : undefined;
523
+ }
412
524
  /**
413
525
  * Lets an explanation ask the host that rendered a value to read it again,
414
526
  * when the saved value no longer matches the one on screen. Provided by
@@ -417,173 +529,3117 @@ function toCalculationExplanationTarget(entity, label) {
417
529
  class EntityCalculationRefresher {
418
530
  }
419
531
 
420
- const KEY_PREFIX = 'components.entitiesPreview.calculationExplanation';
421
- /** Unavailable outcomes with their own message; anything else is generic. */
422
- const UNAVAILABLE_KEYS = {
423
- notCaptured: `${KEY_PREFIX}.notCaptured`,
424
- unsupported: `${KEY_PREFIX}.unsupported`,
425
- limitExceeded: `${KEY_PREFIX}.limitExceeded`,
426
- restricted: `${KEY_PREFIX}.restricted`,
427
- valueChanged: `${KEY_PREFIX}.valueChanged`,
428
- notCalculated: `${KEY_PREFIX}.notCalculated`,
532
+ /**
533
+ * The application's currency unit (`SAR`), shown after captured amounts. The
534
+ * explanation never guesses a currency: without this token, or with an empty
535
+ * unit, amounts are shown as plain numbers.
536
+ */
537
+ const MT_CALCULATION_CURRENCY = new InjectionToken('MT_CALCULATION_CURRENCY', { providedIn: 'root', factory: () => signal('').asReadonly() });
538
+ const MT_CALCULATION_STATUS_NAMES = new InjectionToken('MT_CALCULATION_STATUS_NAMES', {
539
+ providedIn: 'root',
540
+ factory: () => () => ({}),
541
+ });
542
+ const CALCULATION_EXPLANATION_KEYS = 'components.entitiesPreview.calculationExplanation';
543
+ const K = CALCULATION_EXPLANATION_KEYS;
544
+ /**
545
+ * Every key of the backend's text-key catalog
546
+ * (`Pplus5.BE/Docs/Calculation-Explanation-Text-Keys.json`) this version
547
+ * translates. A key outside it reads as a generic heading.
548
+ */
549
+ const SERVER_TEXT_KEYS = new Set([
550
+ 'calculation.fact.effectiveScheduleResults',
551
+ 'calculation.fact.latestBaseline',
552
+ 'calculation.fact.linkedScheduleLeaves',
553
+ 'calculation.fact.matchingDescendants',
554
+ 'calculation.fact.numericLeafValues',
555
+ 'calculation.fact.orderedPhaseGates',
556
+ 'calculation.fact.phaseGateConfigurationAndTime',
557
+ 'calculation.fact.scheduleInputs',
558
+ 'calculation.fact.schedulePolicyAndInputs',
559
+ 'calculation.fact.selectedWorkingDays',
560
+ 'calculation.fact.selectionPolicyAndTime',
561
+ 'calculation.fact.unfilteredDescendants',
562
+ 'calculation.method.completedActualFinish',
563
+ 'calculation.method.descendantCount',
564
+ 'calculation.method.earliestStart',
565
+ 'calculation.method.latestBaseline',
566
+ 'calculation.method.latestPlannedFinish',
567
+ 'calculation.method.leafAverage',
568
+ 'calculation.method.linkedScheduleProgress',
569
+ 'calculation.method.phaseGatePosition',
570
+ 'calculation.method.phaseGateStatus',
571
+ 'calculation.method.phaseGateWeight',
572
+ 'calculation.method.totalWorkingDays',
573
+ 'calculation.method.weightedPhaseGateProgress',
574
+ 'calculation.schedule.actual_finish',
575
+ 'calculation.schedule.actual_start',
576
+ 'calculation.schedule.baseline',
577
+ 'calculation.schedule.duration',
578
+ 'calculation.schedule.is_summary',
579
+ 'calculation.schedule.manualStatus',
580
+ 'calculation.schedule.order',
581
+ 'calculation.schedule.planned_progress',
582
+ 'calculation.schedule.retainedStatus',
583
+ 'calculation.status.firstMatch',
584
+ ]);
585
+ /**
586
+ * Functions read as words, `%0` being an argument and `%*` all of them.
587
+ * Any other function, or one called with another number of arguments, reads
588
+ * as `NAME(arguments)`.
589
+ */
590
+ const FUNCTION_PHRASES = new Set([
591
+ 'SUM',
592
+ 'SUM_IF',
593
+ 'AVG',
594
+ 'AVG_IF',
595
+ 'COUNT',
596
+ 'COUNT_IF',
597
+ 'MIN',
598
+ 'MAX',
599
+ 'MEDIAN',
600
+ 'STDDEV',
601
+ 'WEIGHTED_AVG',
602
+ 'ROUND',
603
+ 'CEIL',
604
+ 'FLOOR',
605
+ 'ABS',
606
+ 'CLAMP',
607
+ 'ISNULL',
608
+ 'NOT_ISNULL',
609
+ 'NOT',
610
+ 'IF',
611
+ 'COALESCE',
612
+ 'TODAY',
613
+ 'DATE_DIFF',
614
+ 'MONTH_DIFF',
615
+ 'BUSINESS_DAYS',
616
+ 'CONTAINS',
617
+ 'IN',
618
+ ]);
619
+ /** Joined between their arguments: `a and b and c`. */
620
+ const LOGICAL_FUNCTIONS = { AND: 'and', OR: 'or' };
621
+ /** Yes/no checks: their result adds nothing beside a condition. */
622
+ const PREDICATES = new Set(['AND', 'OR', 'NOT', 'ISNULL', 'IN', 'CONTAINS']);
623
+ const NUMERIC_VIEW_TYPES$1 = new Set(['Number', 'Currency', 'Percentage']);
624
+ const DATE_VIEW_TYPES = {
625
+ Date: 'date',
626
+ DateTime: 'dateTime',
627
+ Time: 'time',
628
+ };
629
+ /** Typed text a date never hides in. */
630
+ const TEXT_VIEW_TYPES = new Set(['Text', 'LongText', 'Lookup', 'Status']);
631
+ const ISO_DATE$1 = /^\d{4}-\d{2}-\d{2}(?:T00:00:00(?:\.0+)?(?:Z|[+-]00:00)?)?$/;
632
+ const ISO_DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;
633
+ const EQUATION_KINDS = new Set([
634
+ 'literal',
635
+ 'input',
636
+ 'semantic',
637
+ 'table',
638
+ 'binary',
639
+ 'unary',
640
+ 'function',
641
+ 'conditional',
642
+ 'array',
643
+ ]);
644
+ const OPERATORS = {
645
+ '+': '+',
646
+ '-': '−',
647
+ '*': '×',
648
+ '/': '÷',
649
+ '%': 'mod',
650
+ '==': '=',
651
+ '!=': '≠',
652
+ '<': '<',
653
+ '<=': '≤',
654
+ '>': '>',
655
+ '>=': '≥',
429
656
  };
657
+ const LOGICAL_OPERATORS = { '&&': 'and', '||': 'or' };
658
+ /** How tightly each operator binds: brackets only where a reader needs them. */
659
+ const LOOSEST = 0;
660
+ const COMPARISON = 3;
661
+ const ARITHMETIC = 4;
662
+ const UNARY = 6;
663
+ const TIGHTEST = 9;
664
+ const PRECEDENCE = {
665
+ '||': 1,
666
+ '&&': 2,
667
+ '==': COMPARISON,
668
+ '!=': COMPARISON,
669
+ '<': COMPARISON,
670
+ '<=': COMPARISON,
671
+ '>': COMPARISON,
672
+ '>=': COMPARISON,
673
+ '+': ARITHMETIC,
674
+ '-': ARITHMETIC,
675
+ '*': 5,
676
+ '/': 5,
677
+ '%': 5,
678
+ };
679
+ const NON_ASSOCIATIVE = new Set([
680
+ '-',
681
+ '/',
682
+ '%',
683
+ '==',
684
+ '!=',
685
+ '<',
686
+ '<=',
687
+ '>',
688
+ '>=',
689
+ ]);
690
+ const SEMANTIC_KEYS = new Set([
691
+ 'actual_progress',
692
+ 'planned_progress',
693
+ 'baseline_progress',
694
+ 'baseline_count',
695
+ ]);
696
+ const PROGRESS_KEYS = new Set([
697
+ 'actual_progress',
698
+ 'planned_progress',
699
+ 'baseline_progress',
700
+ ]);
701
+ const CODE_BLOCK_TYPES = new Set([
702
+ 'Source',
703
+ 'StaticText',
704
+ 'Counter',
705
+ 'CurrentDatePart',
706
+ ]);
430
707
  /**
431
- * How a calculated value was calculated: its formula with the values it used,
432
- * the result and when, as saved with the value. Fetched each time it opens and
433
- * never recalculated here.
708
+ * Notes about the whole rollup. Zero-weight and missing-input items are not
709
+ * noted again: each such item's row already says why it reads as it does,
710
+ * and a missing baseline has its own notice.
434
711
  */
435
- class EntityCalculationExplanation {
436
- api = inject(CalculationExplanationApi);
437
- refresher = inject(EntityCalculationRefresher, {
438
- optional: true,
439
- });
440
- target = input.required(...(ngDevMode ? [{ debugName: "target" }] : /* istanbul ignore next */ []));
441
- prefix = KEY_PREFIX;
442
- state = signal({ kind: 'loading' }, ...(ngDevMode ? [{ debugName: "state" }] : /* istanbul ignore next */ []));
443
- available = computed(() => {
444
- const state = this.state();
445
- return state.kind === 'available' ? state : null;
446
- }, ...(ngDevMode ? [{ debugName: "available" }] : /* istanbul ignore next */ []));
447
- unavailableKey = computed(() => {
448
- const state = this.state();
449
- return state.kind === 'unavailable' ? state.messageKey : null;
450
- }, ...(ngDevMode ? [{ debugName: "unavailableKey" }] : /* istanbul ignore next */ []));
451
- request;
452
- constructor() {
453
- inject(DestroyRef).onDestroy(() => this.request?.unsubscribe());
712
+ const SCHEDULE_NOTES = new Set([
713
+ 'noEligibleScheduleItems',
714
+ 'allWeightsZeroUsingArithmeticMean',
715
+ ]);
716
+ const ITEM_TYPES = new Set(['Task', 'Milestone', 'Deliverable']);
717
+ /** Field names of native facts with a business label, lower-cased. */
718
+ const FIELD_LABELS = new Set([
719
+ 'asofutc',
720
+ 'utcnow',
721
+ 'iscurrent',
722
+ 'iscompleted',
723
+ 'weight',
724
+ 'totallevelweight',
725
+ 'allitemscompleted',
726
+ 'baselineprogress',
727
+ 'version',
728
+ 'baselineversion',
729
+ 'value',
730
+ 'source',
731
+ 'includemilestones',
732
+ 'excludesamedaymilestones',
733
+ 'leafonly',
734
+ 'plannedstart',
735
+ 'plannedfinish',
736
+ 'actualstart',
737
+ 'actualfinish',
738
+ 'finish',
739
+ 'workingdays',
740
+ 'calendar',
741
+ 'timezoneid',
742
+ 'workdaystartminute',
743
+ 'workdayendminute',
744
+ 'holidays',
745
+ 'order',
746
+ 'selectedstatus',
747
+ 'modulekey',
748
+ 'progress',
749
+ 'calculation',
750
+ 'recordids',
751
+ 'policy',
752
+ 'nodes',
753
+ 'dependencies',
754
+ 'target',
755
+ 'results',
756
+ 'duration',
757
+ 'issummary',
758
+ ]);
759
+ /** Technical identifiers a reader has no use for. */
760
+ const HIDDEN_FIELDS = new Set([
761
+ 'id',
762
+ 'levelid',
763
+ 'leveldataid',
764
+ 'parentid',
765
+ 'key',
766
+ 'propertykey',
767
+ 'schemaid',
768
+ 'filtercondition',
769
+ ]);
770
+ const FIELD_VALUES = new Set(['latestBaseline', 'storedBaseline']);
771
+ const MINUTE_FIELDS = new Set(['workdaystartminute', 'workdayendminute']);
772
+ /** List inputs show their values inline up to this many. */
773
+ const INLINE_VALUES = 3;
774
+ /** Nested captured data rendered as fields up to this depth, then as text. */
775
+ const DATA_DEPTH = 3;
776
+ /** Captured tables show this many rows, then a count of the rest. */
777
+ const DATA_ROWS = 20;
778
+ // ── Values ─────────────────────────────────────────────────────────────────
779
+ /** A number as captured: grouped, never rounded, with a real minus sign. */
780
+ function formatExplanationNumber(value) {
781
+ if (!Number.isFinite(value)) {
782
+ return String(value);
454
783
  }
455
- // Created when the popover opens and destroyed when it closes: one read per
456
- // open, never re-read when the value it explains is refreshed underneath.
457
- ngOnInit() {
458
- this.load(false);
784
+ return new Intl.NumberFormat('en-US', { maximumFractionDigits: 20 })
785
+ .format(value)
786
+ .replace(/^-/, '−');
787
+ }
788
+ /** A captured value as plain text. Never formatted or rounded here. */
789
+ function formatExplanationValue(value) {
790
+ if (value === null || value === undefined) {
791
+ return '—';
459
792
  }
460
- load(retried) {
461
- const target = this.target();
462
- this.request?.unsubscribe();
463
- this.request = this.api.read(target.source, target.propertyKey).subscribe({
464
- next: (response) => this.apply(response, retried),
465
- error: () => this.state.set({ kind: 'failed' }),
466
- });
793
+ return typeof value === 'object' ? JSON.stringify(value) : String(value);
794
+ }
795
+ /**
796
+ * A captured value the way its property shows values: grouped numbers, the
797
+ * application currency, `%`, the configured date format, yes/no. An untyped
798
+ * value (a function result) that is a date reads as one.
799
+ */
800
+ function formatTypedValue(value, viewType, ctx) {
801
+ if (value === null || value === undefined || value === '') {
802
+ return '—';
467
803
  }
468
- apply(response, retried) {
469
- // The value was saved again while the explanation was read: show the new
470
- // value, then explain that one.
471
- if (response.status === 'valueChanged' && !retried) {
472
- this.refresher?.refreshStaleCalculatedValue();
473
- this.load(true);
474
- return;
804
+ if (Array.isArray(value)) {
805
+ return value
806
+ .map((item) => formatTypedValue(item, viewType, ctx))
807
+ .join(', ');
808
+ }
809
+ if (typeof value === 'object') {
810
+ return JSON.stringify(value);
811
+ }
812
+ if (typeof value === 'boolean') {
813
+ return ctx.translate(`${K}.${value ? 'yes' : 'no'}`);
814
+ }
815
+ const type = viewType ?? '';
816
+ if (typeof value === 'number') {
817
+ return formatTypedNumber(value, type, ctx);
818
+ }
819
+ if (NUMERIC_VIEW_TYPES$1.has(type) && isNumericText(value)) {
820
+ return formatTypedNumber(Number(value), type, ctx);
821
+ }
822
+ const dateType = DATE_VIEW_TYPES[type] ??
823
+ (TEXT_VIEW_TYPES.has(type)
824
+ ? undefined
825
+ : ISO_DATE$1.test(value)
826
+ ? 'date'
827
+ : ISO_DATE_TIME.test(value)
828
+ ? 'dateTime'
829
+ : undefined);
830
+ if (dateType) {
831
+ return ctx.formatDate(value, dateType) || value;
832
+ }
833
+ if (type === 'Checkbox' && (value === 'true' || value === 'false')) {
834
+ return ctx.translate(`${K}.${value === 'true' ? 'yes' : 'no'}`);
835
+ }
836
+ return value;
837
+ }
838
+ function formatTypedNumber(value, viewType, ctx) {
839
+ const text = formatExplanationNumber(value);
840
+ if (viewType === 'Currency') {
841
+ return ctx.currency ? `${text} ${ctx.currency}` : text;
842
+ }
843
+ return viewType === 'Percentage' ? `${text}%` : text;
844
+ }
845
+ function isNumericText(value) {
846
+ return value.trim() !== '' && Number.isFinite(Number(value));
847
+ }
848
+ function percent(value) {
849
+ return `${formatExplanationNumber(value)}%`;
850
+ }
851
+ // ── Labels ─────────────────────────────────────────────────────────────────
852
+ /** A property's current name in the active language. */
853
+ function displayName(display, lang) {
854
+ if (!display) {
855
+ return null;
856
+ }
857
+ const preferred = lang.startsWith('ar')
858
+ ? [display.nameAr, display.name, display.nameEn]
859
+ : [display.nameEn, display.name, display.nameAr];
860
+ return preferred.find((name) => !!name?.trim()) ?? null;
861
+ }
862
+ /** `totalLevelWeight` / `is_cancelled` → `Total level weight` / `Is cancelled`. */
863
+ function humanizeKey$1(key) {
864
+ const words = key
865
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
866
+ .replace(/[_.-]+/g, ' ')
867
+ .trim()
868
+ .toLowerCase();
869
+ return words ? words[0].toUpperCase() + words.slice(1) : key;
870
+ }
871
+ /**
872
+ * A server-authored text key (`calculation.method.leafAverage`) in the active
873
+ * language; null for a missing or unknown key.
874
+ */
875
+ function serverText(key, ctx) {
876
+ return key && SERVER_TEXT_KEYS.has(key)
877
+ ? ctx.translate(`${K}.text.${key.slice('calculation.'.length)}`)
878
+ : null;
879
+ }
880
+ /**
881
+ * What a document's calculation does, in words: its description key, or for
882
+ * an older capture a generic description of its kind.
883
+ */
884
+ function describeDocument(document, ctx) {
885
+ return (serverText(document.descriptionKey, ctx) ??
886
+ (document.provider === 'status'
887
+ ? ctx.translate(`${K}.text.status.firstMatch`)
888
+ : document.provider === 'schedule'
889
+ ? ctx.translate(`${K}.generic.schedule`)
890
+ : ctx.translate(`${K}.generic.method`)));
891
+ }
892
+ /** The column of a reference: `Current::project_budget` → `project_budget`. */
893
+ function referenceColumn(reference) {
894
+ if (!reference) {
895
+ return null;
896
+ }
897
+ const at = reference.lastIndexOf('::');
898
+ return at >= 0 ? reference.slice(at + 2) : reference;
899
+ }
900
+ /** The table of a reference: `Modules.Financial::amount` → `Modules.Financial`. */
901
+ function referenceTable(reference) {
902
+ if (!reference) {
903
+ return null;
904
+ }
905
+ const at = reference.indexOf('::');
906
+ return at >= 0 ? reference.slice(0, at) : null;
907
+ }
908
+ function semanticKey(reference) {
909
+ const column = referenceColumn(reference);
910
+ return column && SEMANTIC_KEYS.has(column) ? column : null;
911
+ }
912
+ /**
913
+ * A node's business label: the property's authorized name, a known schedule
914
+ * value, or a generic label. Never a reference, key or formula text.
915
+ */
916
+ function nodeLabel(node, ctx) {
917
+ // A schedule rollup reads as what it rolls up: its column's display name
918
+ // is the property's own (`Baseline Progress = Baseline Progress`).
919
+ const semantic = semanticKey(node.reference);
920
+ if (node.kind === 'semantic' && semantic) {
921
+ return ctx.translate(`${K}.semantic.${semantic}`);
922
+ }
923
+ const named = displayName(node.display, ctx.lang);
924
+ if (named) {
925
+ return named;
926
+ }
927
+ if (semantic) {
928
+ return ctx.translate(`${K}.semantic.${semantic}`);
929
+ }
930
+ if (node.kind === 'semantic') {
931
+ return ctx.translate(`${K}.generic.scheduleValue`);
932
+ }
933
+ if (node.kind === 'table') {
934
+ return ctx.translate(`${K}.generic.records`);
935
+ }
936
+ return ctx.translate(`${K}.generic.value`);
937
+ }
938
+ /** How a node's value shows: its property's view type, or a progress `%`. */
939
+ function nodeViewType(node) {
940
+ if (node.display?.viewType) {
941
+ return node.display.viewType;
942
+ }
943
+ const column = referenceColumn(node.reference);
944
+ return column && PROGRESS_KEYS.has(column) ? 'Percentage' : null;
945
+ }
946
+ function nodeValueText(node, ctx) {
947
+ if (node.state === 'notEvaluated') {
948
+ return ctx.translate(`${K}.notEvaluated`);
949
+ }
950
+ const value = node.value;
951
+ const viewType = nodeViewType(node);
952
+ if (Array.isArray(value)) {
953
+ return value.length <= INLINE_VALUES
954
+ ? value.map((item) => formatTypedValue(item, viewType, ctx)).join(', ')
955
+ : ctx.translate(`${K}.valueCount`, { count: value.length });
956
+ }
957
+ return formatTypedValue(value, viewType, ctx);
958
+ }
959
+ function scheduleDetailOf(document, reference) {
960
+ return ((reference &&
961
+ document.schedule?.find((detail) => detail.reference === reference)) ||
962
+ null);
963
+ }
964
+ /** `Weighted average`: how a rollup combined its items (counts are in the panel). */
965
+ function describeRollup(detail, ctx) {
966
+ const aggregation = ['weightedAverage', 'arithmeticMean'].includes(detail.aggregation)
967
+ ? detail.aggregation
968
+ : 'empty';
969
+ return ctx.translate(`${K}.schedule.aggregation.${aggregation}`);
970
+ }
971
+ function functionName(node) {
972
+ const name = (node.operation ?? '').trim().toUpperCase();
973
+ return name || (node.kind === 'conditional' ? 'IF' : node.kind);
974
+ }
975
+ // ── Equations ──────────────────────────────────────────────────────────────
976
+ /** Whether the document's root reads as an equation. */
977
+ function isEquationDocument(document) {
978
+ const root = document.nodes?.find((node) => node.id === document.rootNodeId);
979
+ return !!root && EQUATION_KINDS.has(root.kind);
980
+ }
981
+ /**
982
+ * The calculation as readable business wording: inputs by their property
983
+ * names, operators as symbols, functions as words (`sum of Amount where …`).
984
+ * `null` when the document is not an equation (a native method, a status
985
+ * selection, a generated code), or, in `values` mode, when an input is a list
986
+ * of values the line cannot show (the details list them by record).
987
+ *
988
+ * Nodes form a graph: the same input can be reached from several places, and
989
+ * each place shows it in full. Only a node already on the current path (a
990
+ * cycle, which a valid document never has) reads as `…`.
991
+ */
992
+ function buildExplanationSegments(document, ctx, mode = 'inline', startId = document.rootNodeId) {
993
+ if (!isEquationDocument(document)) {
994
+ return null;
995
+ }
996
+ const byId = new Map((document.nodes ?? []).map((node) => [node.id, node]));
997
+ const start = byId.get(startId);
998
+ if (!start || !EQUATION_KINDS.has(start.kind)) {
999
+ return null;
1000
+ }
1001
+ const path = new Set();
1002
+ // Values mode: set when an input is a list, so the line can't be shown.
1003
+ let listed = false;
1004
+ const notEvaluated = () => [
1005
+ { kind: 'muted', text: ctx.translate(`${K}.notEvaluated`) },
1006
+ ];
1007
+ /**
1008
+ * A node in a place that binds at `context`: it gets brackets only when it
1009
+ * binds looser (`(a + b) × c`, `a and (b or c)`), never around a single
1010
+ * term, so `Baseline − Actual ≤ 5` and `a and b and c` read bare.
1011
+ */
1012
+ const render = (id, context) => {
1013
+ const node = byId.get(id);
1014
+ if (!node || path.has(id)) {
1015
+ return [{ kind: 'muted', text: '…' }];
475
1016
  }
476
- const explanation = response.explanation;
477
- if (response.status !== 'available' ||
478
- !explanation ||
479
- explanation.schemaVersion !== 1 ||
480
- explanation.provider !== 'formula') {
481
- this.state.set({
482
- kind: 'unavailable',
483
- messageKey: UNAVAILABLE_KEYS[response.status] ?? `${KEY_PREFIX}.unavailable`,
484
- });
485
- return;
1017
+ path.add(id);
1018
+ try {
1019
+ const segments = renderNode(node);
1020
+ // Inside a condition, a nested difference or product shows what it gave.
1021
+ const shown = mode === 'inline' &&
1022
+ node.id !== startId &&
1023
+ node.kind === 'binary' &&
1024
+ (PRECEDENCE[node.operation ?? ''] ?? 0) >= ARITHMETIC &&
1025
+ typeof node.value === 'number';
1026
+ if (shown) {
1027
+ segments.push({
1028
+ kind: 'result',
1029
+ text: formatTypedValue(node.value, null, ctx),
1030
+ });
1031
+ }
1032
+ const wrap = segments.length > 1 && (shown || precedenceOf(node) < context);
1033
+ return wrap
1034
+ ? [
1035
+ { kind: 'text', text: '(' },
1036
+ ...segments,
1037
+ { kind: 'text', text: ')' },
1038
+ ]
1039
+ : segments;
486
1040
  }
487
- const stale = !isSameSavedValue(response.savedValue, this.target().displayedValue);
488
- if (stale) {
489
- this.refresher?.refreshStaleCalculatedValue();
1041
+ finally {
1042
+ path.delete(id);
490
1043
  }
491
- this.state.set({
492
- kind: 'available',
493
- formulaWithValues: explanation.formulaWithValues,
494
- result: formatExplanationValue(explanation.result),
495
- calculatedAt: explanation.calculatedAt,
496
- definitionChanged: response.definitionChanged,
497
- refreshed: stale && !!this.refresher,
498
- });
499
- }
500
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: EntityCalculationExplanation, deps: [], target: i0.ɵɵFactoryTarget.Component });
501
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: EntityCalculationExplanation, isStandalone: true, selector: "mt-entity-calculation-explanation", inputs: { target: { classPropertyName: "target", publicName: "target", isSignal: true, isRequired: true, transformFunction: null } }, ngImport: i0, template: `
502
- <div class="flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-3 text-sm">
503
- <div class="flex min-w-0 flex-col gap-0.5">
504
- <span
505
- class="truncate font-semibold text-surface-900 dark:text-surface-0"
506
- >
507
- {{ target().label }}
508
- </span>
509
- <span class="text-xs text-surface-500 dark:text-surface-400">
510
- {{ prefix + '.title' | transloco }}
511
- </span>
512
- </div>
513
-
514
- @switch (state().kind) {
515
- @case ('loading') {
516
- <div class="flex flex-col gap-2" aria-busy="true">
517
- <div
518
- class="h-10 animate-pulse rounded-md bg-surface-100 dark:bg-surface-800"
519
- ></div>
520
- <div
521
- class="h-3 w-1/2 animate-pulse rounded-md bg-surface-100 dark:bg-surface-800"
522
- ></div>
523
- </div>
1044
+ };
1045
+ const precedenceOf = (node) => {
1046
+ switch (node.kind) {
1047
+ case 'binary':
1048
+ return PRECEDENCE[node.operation ?? ''] ?? TIGHTEST;
1049
+ case 'unary':
1050
+ return node.operation === 'Not' ? COMPARISON : UNARY;
1051
+ case 'conditional':
1052
+ return LOOSEST;
1053
+ case 'function': {
1054
+ const name = functionName(node);
1055
+ if (name in LOGICAL_FUNCTIONS) {
1056
+ return name === 'OR' ? PRECEDENCE['||'] : PRECEDENCE['&&'];
1057
+ }
1058
+ if (name === 'TODAY' || !FUNCTION_PHRASES.has(name)) {
1059
+ return TIGHTEST;
1060
+ }
1061
+ // `x is empty` reads as a comparison; `sum of x where …` needs
1062
+ // brackets inside anything.
1063
+ return PREDICATES.has(name) ? COMPARISON : LOOSEST;
1064
+ }
1065
+ default:
1066
+ return TIGHTEST;
524
1067
  }
525
- @case ('available') {
526
- @if (available(); as explanation) {
527
- <div
528
- class="rounded-md border border-surface-200 bg-surface-50 px-3 py-2 font-mono text-sm break-words text-surface-800 dark:border-surface-700 dark:bg-surface-800 dark:text-surface-100"
529
- dir="ltr"
530
- >
531
- @if (explanation.formulaWithValues) {
532
- <span>{{ explanation.formulaWithValues }}</span>
533
- <span class="px-1 text-surface-400">=</span>
534
- }
535
- <span class="font-semibold">{{ explanation.result }}</span>
536
- </div>
537
- <div class="text-xs text-surface-500 dark:text-surface-400">
538
- {{ prefix + '.calculatedAt' | transloco }}
539
- <span dir="ltr" class="tabular-nums">{{
540
- explanation.calculatedAt | mtDateFormat: 'dateTime'
541
- }}</span>
542
- </div>
543
- @if (explanation.definitionChanged) {
544
- <div
545
- class="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-700"
546
- >
547
- {{ prefix + '.definitionChanged' | transloco }}
548
- </div>
1068
+ };
1069
+ const renderNode = (node) => {
1070
+ const skipped = node.state === 'notEvaluated' && mode !== 'labels';
1071
+ switch (node.kind) {
1072
+ case 'literal':
1073
+ return [{ kind: 'value', text: literalText(node, ctx) }];
1074
+ case 'input':
1075
+ if (mode === 'labels') {
1076
+ return [{ kind: 'term', label: nodeLabel(node, ctx), value: null }];
1077
+ }
1078
+ if (mode === 'values') {
1079
+ if (Array.isArray(node.value)) {
1080
+ listed = true;
1081
+ return [];
1082
+ }
1083
+ return skipped
1084
+ ? notEvaluated()
1085
+ : [{ kind: 'value', text: nodeValueText(node, ctx) }];
1086
+ }
1087
+ return [
1088
+ {
1089
+ kind: 'term',
1090
+ label: nodeLabel(node, ctx),
1091
+ value: nodeValueText(node, ctx),
1092
+ },
1093
+ ];
1094
+ case 'semantic': {
1095
+ if (mode === 'labels') {
1096
+ return [{ kind: 'term', label: nodeLabel(node, ctx), value: null }];
1097
+ }
1098
+ if (skipped) {
1099
+ return notEvaluated();
1100
+ }
1101
+ // A schedule rollup on its own reads as how it was aggregated; inside
1102
+ // a larger formula, as its value.
1103
+ const rollup = scheduleDetailOf(document, node.reference);
1104
+ if (mode === 'values') {
1105
+ return [
1106
+ {
1107
+ kind: 'value',
1108
+ text: rollup && node.id === startId
1109
+ ? describeRollup(rollup, ctx)
1110
+ : nodeValueText(node, ctx),
1111
+ },
1112
+ ];
1113
+ }
1114
+ return [
1115
+ {
1116
+ kind: 'term',
1117
+ label: nodeLabel(node, ctx),
1118
+ value: nodeValueText(node, ctx),
1119
+ },
1120
+ ];
549
1121
  }
550
- @if (explanation.refreshed) {
551
- <div
552
- class="rounded-md border border-primary-200 bg-primary-50 px-3 py-2 text-xs text-primary-700"
553
- >
554
- {{ prefix + '.valueRefreshed' | transloco }}
555
- </div>
1122
+ case 'table': {
1123
+ if (mode === 'values') {
1124
+ listed = true;
1125
+ return [];
1126
+ }
1127
+ const rows = Math.max(0, ...node.children.map((child) => byId.get(child)?.recordIds?.length ?? 0));
1128
+ return [
1129
+ {
1130
+ kind: 'term',
1131
+ label: nodeLabel(node, ctx),
1132
+ value: mode === 'inline'
1133
+ ? ctx.translate(`${K}.recordCount`, { count: rows })
1134
+ : null,
1135
+ },
1136
+ ];
556
1137
  }
557
- }
1138
+ case 'binary': {
1139
+ if (skipped) {
1140
+ return notEvaluated();
1141
+ }
1142
+ const operation = node.operation ?? '';
1143
+ const logical = LOGICAL_OPERATORS[operation];
1144
+ const text = logical
1145
+ ? ctx.translate(`${K}.op.${logical}`)
1146
+ : (OPERATORS[operation] ?? operation);
1147
+ const own = PRECEDENCE[operation] ?? TIGHTEST;
1148
+ // `a − (b − c)`: the right side of a non-associative operator binds
1149
+ // tighter than the operator itself.
1150
+ const right = NON_ASSOCIATIVE.has(operation) ? own + 1 : own;
1151
+ return [
1152
+ ...render(node.children[0], own),
1153
+ { kind: 'text', text },
1154
+ ...render(node.children[1], right),
1155
+ ];
1156
+ }
1157
+ case 'unary': {
1158
+ if (skipped) {
1159
+ return notEvaluated();
1160
+ }
1161
+ const child = byId.get(node.children[0]);
1162
+ if (node.operation === 'Not') {
1163
+ // `!ISNULL(x)` reads as `x is not empty`.
1164
+ if (child?.kind === 'function' &&
1165
+ functionName(child) === 'ISNULL' &&
1166
+ child.children.length === 1) {
1167
+ return phrase('NOT_ISNULL', [render(child.children[0], LOOSEST)]);
1168
+ }
1169
+ return phrase('NOT', [render(node.children[0], COMPARISON + 1)]);
1170
+ }
1171
+ return [
1172
+ { kind: 'text', text: node.operation === 'Negate' ? '−' : '+' },
1173
+ ...render(node.children[0], UNARY),
1174
+ ];
1175
+ }
1176
+ case 'function':
1177
+ case 'conditional':
1178
+ return renderFunction(node, skipped);
1179
+ case 'array':
1180
+ return [
1181
+ { kind: 'text', text: '[' },
1182
+ ...joined(node.children.map((child) => render(child, LOOSEST))),
1183
+ { kind: 'text', text: ']' },
1184
+ ];
1185
+ default:
1186
+ // A kind this version does not know: shown as labelled data.
1187
+ return [
1188
+ {
1189
+ kind: 'term',
1190
+ label: nodeLabel(node, ctx),
1191
+ value: mode === 'labels' ? null : nodeValueText(node, ctx),
1192
+ },
1193
+ ];
558
1194
  }
559
- @case ('unavailable') {
560
- @if (unavailableKey(); as messageKey) {
561
- <div
562
- class="rounded-md border border-surface-200 bg-surface-50 px-3 py-2 text-surface-600 dark:border-surface-700 dark:bg-surface-800 dark:text-surface-300"
563
- >
564
- {{ messageKey | transloco }}
565
- </div>
566
- }
1195
+ };
1196
+ const renderFunction = (node, skipped) => {
1197
+ if (skipped) {
1198
+ return notEvaluated();
567
1199
  }
568
- @case ('failed') {
569
- <div
570
- class="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-red-700"
571
- >
572
- {{ prefix + '.loadFailed' | transloco }}
573
- </div>
1200
+ const name = functionName(node);
1201
+ const value = formatTypedValue(node.value, null, ctx);
1202
+ if (name === 'TODAY' && node.children.length === 0) {
1203
+ const label = ctx.translate(`${K}.fn.TODAY`);
1204
+ return mode === 'values'
1205
+ ? [{ kind: 'value', text: value }]
1206
+ : [
1207
+ {
1208
+ kind: 'term',
1209
+ label,
1210
+ value: mode === 'inline' ? value : null,
1211
+ },
1212
+ ];
574
1213
  }
575
- }
576
- </div>
577
- `, isInline: true, dependencies: [{ kind: "pipe", type: TranslocoPipe, name: "transloco" }, { kind: "pipe", type: MTDateFormatPipe, name: "mtDateFormat" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
1214
+ // In values mode a function over a list reads as its result: the list
1215
+ // itself is in the details.
1216
+ const before = listed;
1217
+ listed = false;
1218
+ const logical = LOGICAL_FUNCTIONS[name];
1219
+ const own = precedenceOf(node);
1220
+ const args = node.children.map((child) => render(child, logical ? own : LOOSEST));
1221
+ const overList = listed;
1222
+ listed = before;
1223
+ if (mode === 'values' && overList) {
1224
+ if (node.id === startId) {
1225
+ listed = true;
1226
+ return [];
1227
+ }
1228
+ return [{ kind: 'value', text: value }];
1229
+ }
1230
+ if (logical) {
1231
+ const word = ctx.translate(`${K}.op.${logical}`);
1232
+ return args.flatMap((arg, index) => index === 0 ? arg : [{ kind: 'text', text: word }, ...arg]);
1233
+ }
1234
+ const segments = phrase(name, args);
1235
+ // Inside a condition, a nested value function shows what it gave.
1236
+ if (mode === 'inline' &&
1237
+ node.id !== startId &&
1238
+ !PREDICATES.has(name) &&
1239
+ node.value !== undefined) {
1240
+ segments.push({ kind: 'result', text: value });
1241
+ }
1242
+ return segments;
1243
+ };
1244
+ const phrase = (name, args) => {
1245
+ const template = FUNCTION_PHRASES.has(name)
1246
+ ? ctx.translate(`${K}.fn.${name}`)
1247
+ : null;
1248
+ return (template && fillPhrase(template, args)) || callForm(name, args);
1249
+ };
1250
+ const out = render(startId, LOOSEST);
1251
+ return mode === 'values' && listed ? null : out;
578
1252
  }
579
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: EntityCalculationExplanation, decorators: [{
580
- type: Component,
581
- args: [{
582
- selector: 'mt-entity-calculation-explanation',
583
- changeDetection: ChangeDetectionStrategy.OnPush,
584
- imports: [TranslocoPipe, MTDateFormatPipe],
585
- template: `
586
- <div class="flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-3 text-sm">
1253
+ /**
1254
+ * `%0` and `%*` filled with arguments; null when the count differs. Not
1255
+ * `{0}`: an ICU MessageFormat transpiler (the apps use one) fills braces
1256
+ * itself, with `undefined`.
1257
+ */
1258
+ function fillPhrase(template, args) {
1259
+ const parts = template.split(/(%\d|%\*)/);
1260
+ const rest = parts.includes('%*');
1261
+ const positions = parts
1262
+ .map((part) => /^%(\d)$/.exec(part))
1263
+ .filter((match) => !!match)
1264
+ .map((match) => Number(match[1]));
1265
+ const expected = positions.length ? Math.max(...positions) + 1 : 0;
1266
+ if (rest ? args.length < expected + 1 : args.length !== expected) {
1267
+ return null;
1268
+ }
1269
+ const out = [];
1270
+ for (const part of parts) {
1271
+ const position = /^%(\d)$/.exec(part);
1272
+ if (position) {
1273
+ out.push(...args[Number(position[1])]);
1274
+ }
1275
+ else if (part === '%*') {
1276
+ out.push(...joined(args.slice(expected)));
1277
+ }
1278
+ else if (part.trim()) {
1279
+ out.push({ kind: 'text', text: part.trim() });
1280
+ }
1281
+ }
1282
+ return out;
1283
+ }
1284
+ /** `NAME(a, b)`: a function this version has no words for. */
1285
+ function callForm(name, args) {
1286
+ return [
1287
+ { kind: 'text', text: `${name}(` },
1288
+ ...joined(args),
1289
+ { kind: 'text', text: ')' },
1290
+ ];
1291
+ }
1292
+ function joined(items) {
1293
+ return items.flatMap((item, index) => index === 0 ? item : [{ kind: 'text', text: ',' }, ...item]);
1294
+ }
1295
+ /** A literal the way the formula wrote it: `"Paid"`, `No`, `1,000`, a date. */
1296
+ function literalText(node, ctx) {
1297
+ const value = node.value === undefined || node.value === null
1298
+ ? literalOf(node)
1299
+ : node.value;
1300
+ if (typeof value === 'string') {
1301
+ return ISO_DATE$1.test(value) || ISO_DATE_TIME.test(value)
1302
+ ? formatTypedValue(value, null, ctx)
1303
+ : `"${value}"`;
1304
+ }
1305
+ if (typeof value === 'number') {
1306
+ return formatExplanationNumber(value);
1307
+ }
1308
+ if (typeof value === 'boolean') {
1309
+ return formatTypedValue(value, null, ctx);
1310
+ }
1311
+ return formatExplanationValue(value);
1312
+ }
1313
+ /**
1314
+ * A literal on a branch that never ran has no captured value; it is still
1315
+ * the constant the formula wrote (`false`, `0`, `"Paid"`).
1316
+ */
1317
+ function literalOf(node) {
1318
+ if (node.kind !== 'literal' || !node.expression?.trim()) {
1319
+ return node.value ?? null;
1320
+ }
1321
+ try {
1322
+ const parsed = JSON.parse(node.expression);
1323
+ return parsed === null || typeof parsed !== 'object'
1324
+ ? parsed
1325
+ : null;
1326
+ }
1327
+ catch {
1328
+ return null;
1329
+ }
1330
+ }
1331
+ /** Capitalizes the first word, for an equation that starts a line. */
1332
+ function capitalizeSegments(segments) {
1333
+ const [first, ...rest] = segments;
1334
+ if (first?.kind !== 'text' || !first.text) {
1335
+ return segments;
1336
+ }
1337
+ return [
1338
+ { kind: 'text', text: first.text[0].toUpperCase() + first.text.slice(1) },
1339
+ ...rest,
1340
+ ];
1341
+ }
1342
+ /**
1343
+ * A condition as a checklist: each part the rule requires on its own line
1344
+ * with whether it held, so a reader sees why a rule matched or which part
1345
+ * failed. Every truth is the captured one; nothing is evaluated here.
1346
+ *
1347
+ * `a and b and c` becomes three parts. `IF(guard, false, rest)` — the usual
1348
+ * "skip when data is missing" form — becomes `Unless guard` plus the parts of
1349
+ * `rest`. An `or` becomes one part whose options are listed. Null when the
1350
+ * document is not an equation.
1351
+ */
1352
+ function buildConditionChecks(document, ctx) {
1353
+ if (!isEquationDocument(document)) {
1354
+ return null;
1355
+ }
1356
+ const byId = new Map((document.nodes ?? []).map((node) => [node.id, node]));
1357
+ const truth = (node) => node.state === 'evaluated' && typeof node.value === 'boolean'
1358
+ ? node.value
1359
+ : null;
1360
+ const is = (node, logical) => (node.kind === 'binary' &&
1361
+ LOGICAL_OPERATORS[node.operation ?? ''] === logical) ||
1362
+ (node.kind === 'function' &&
1363
+ LOGICAL_FUNCTIONS[functionName(node)] === logical);
1364
+ const isFalse = (node) => node.kind === 'literal' && literalOf(node) === false;
1365
+ const wording = (node) => buildExplanationSegments(document, ctx, 'inline', node.id) ?? [];
1366
+ const part = (node) => ({
1367
+ segments: wording(node),
1368
+ met: truth(node),
1369
+ anyOf: null,
1370
+ });
1371
+ const children = (node) => node.children
1372
+ .map((id) => byId.get(id))
1373
+ .filter((child) => !!child);
1374
+ const visited = new Set();
1375
+ const parts = (node) => {
1376
+ if (visited.has(node.id)) {
1377
+ return [part(node)];
1378
+ }
1379
+ visited.add(node.id);
1380
+ try {
1381
+ if (is(node, 'and')) {
1382
+ return children(node).flatMap(parts);
1383
+ }
1384
+ const name = node.kind === 'conditional' ? 'IF' : functionName(node);
1385
+ const [guard, then, otherwise] = children(node);
1386
+ if ((node.kind === 'conditional' || node.kind === 'function') &&
1387
+ name === 'IF' &&
1388
+ node.children.length === 3 &&
1389
+ guard &&
1390
+ then &&
1391
+ otherwise) {
1392
+ if (isFalse(then)) {
1393
+ const guardTruth = truth(guard);
1394
+ const words = fillPhrase(ctx.translate(`${K}.check.unless`), [
1395
+ wording(guard),
1396
+ ]);
1397
+ return [
1398
+ {
1399
+ segments: words ?? wording(guard),
1400
+ met: guardTruth === null ? null : !guardTruth,
1401
+ anyOf: null,
1402
+ },
1403
+ // A guard that held means the rest was never checked.
1404
+ ...(guardTruth === true ? [] : parts(otherwise)),
1405
+ ];
1406
+ }
1407
+ if (isFalse(otherwise)) {
1408
+ return [
1409
+ ...parts(guard),
1410
+ ...(truth(guard) === false ? [] : parts(then)),
1411
+ ];
1412
+ }
1413
+ }
1414
+ if (is(node, 'or')) {
1415
+ return [
1416
+ {
1417
+ segments: [],
1418
+ met: truth(node),
1419
+ anyOf: children(node).map(part),
1420
+ },
1421
+ ];
1422
+ }
1423
+ return [part(node)];
1424
+ }
1425
+ finally {
1426
+ visited.delete(node.id);
1427
+ }
1428
+ };
1429
+ const root = byId.get(document.rootNodeId);
1430
+ return root ? parts(root) : null;
1431
+ }
1432
+ /** A generated code as its parts: `PRJ + - + 2026 + - + 0042`. */
1433
+ function buildCodeSegments(document, ctx) {
1434
+ const blocks = (document.nodes ?? []).filter((node) => node.kind === 'codeBlock');
1435
+ return blocks.flatMap((node, index) => [
1436
+ ...(index > 0 ? [{ kind: 'text', text: '+' }] : []),
1437
+ {
1438
+ kind: 'value',
1439
+ text: JSON.stringify(formatTypedValue(node.value, null, ctx)),
1440
+ },
1441
+ ]);
1442
+ }
1443
+ // ── Captured data ──────────────────────────────────────────────────────────
1444
+ /**
1445
+ * Captured JSON (native method facts) as labelled fields, lists or tables.
1446
+ * Field names read as business labels; record ids read as a count.
1447
+ */
1448
+ function toExplanationData(value, ctx, depth = 0, field = '') {
1449
+ if (field && MINUTE_FIELDS.has(field) && typeof value === 'number') {
1450
+ return { kind: 'text', text: clock(value) };
1451
+ }
1452
+ if (Array.isArray(value) && field && isIdField(field)) {
1453
+ return {
1454
+ kind: 'text',
1455
+ text: ctx.translate(`${K}.recordCount`, { count: value.length }),
1456
+ };
1457
+ }
1458
+ if (value === null || value === undefined || typeof value !== 'object') {
1459
+ return {
1460
+ kind: 'text',
1461
+ text: typeof value === 'string' && FIELD_VALUES.has(value)
1462
+ ? ctx.translate(`${K}.fieldValue.${value}`)
1463
+ : formatTypedValue(value, null, ctx),
1464
+ };
1465
+ }
1466
+ if (depth >= DATA_DEPTH) {
1467
+ return {
1468
+ kind: 'text',
1469
+ text: Array.isArray(value)
1470
+ ? ctx.translate(`${K}.valueCount`, { count: value.length })
1471
+ : '…',
1472
+ };
1473
+ }
1474
+ if (Array.isArray(value)) {
1475
+ if (value.length === 0) {
1476
+ return { kind: 'text', text: '—' };
1477
+ }
1478
+ if (value.every((item) => isPlainObject(item))) {
1479
+ const records = value;
1480
+ const columns = [
1481
+ ...new Set(records.flatMap((row) => Object.keys(row))),
1482
+ ].filter((column) => !HIDDEN_FIELDS.has(column.toLowerCase()));
1483
+ return {
1484
+ kind: 'table',
1485
+ columns: columns.map((column) => fieldLabel(column, ctx)),
1486
+ rows: records.slice(0, DATA_ROWS).map((row) => columns.map((column) => {
1487
+ const cell = toExplanationData(row[column], ctx, DATA_DEPTH - 1, column.toLowerCase());
1488
+ return cell.kind === 'text' ? cell.text : '…';
1489
+ })),
1490
+ more: Math.max(0, records.length - DATA_ROWS),
1491
+ };
1492
+ }
1493
+ return {
1494
+ kind: 'list',
1495
+ items: value.map((item) => {
1496
+ const cell = toExplanationData(item, ctx, DATA_DEPTH - 1);
1497
+ return cell.kind === 'text' ? cell.text : '…';
1498
+ }),
1499
+ };
1500
+ }
1501
+ return {
1502
+ kind: 'fields',
1503
+ fields: Object.entries(value)
1504
+ .filter(([key]) => !HIDDEN_FIELDS.has(key.toLowerCase()))
1505
+ .map(([key, item]) => ({
1506
+ label: fieldLabel(key, ctx),
1507
+ data: toExplanationData(item, ctx, depth + 1, key.toLowerCase()),
1508
+ })),
1509
+ };
1510
+ }
1511
+ function isIdField(field) {
1512
+ return field === 'recordids' || field.endsWith('ids');
1513
+ }
1514
+ function fieldLabel(key, ctx) {
1515
+ const normalized = key.toLowerCase();
1516
+ return FIELD_LABELS.has(normalized)
1517
+ ? ctx.translate(`${K}.field.${normalized}`)
1518
+ : humanizeKey$1(key);
1519
+ }
1520
+ function isPlainObject(value) {
1521
+ return !!value && typeof value === 'object' && !Array.isArray(value);
1522
+ }
1523
+ /** Everything the details panel shows, read from the document as is. */
1524
+ function buildExplanationDetails(document, ctx, statusNames = {}) {
1525
+ const equation = isEquationDocument(document);
1526
+ const nodes = document.nodes ?? [];
1527
+ const values = [];
1528
+ const steps = [];
1529
+ const facts = [];
1530
+ const codeBlocks = [];
1531
+ const seenValues = new Set();
1532
+ const byId = new Map(nodes.map((node) => [node.id, node]));
1533
+ // A schedule rollup's own columns (`__central_progress`, …) are internal:
1534
+ // the schedule section shows its contributors.
1535
+ const rollupColumns = new Set();
1536
+ for (const node of nodes) {
1537
+ if (node.kind === 'semantic') {
1538
+ node.children.forEach((child) => rollupColumns.add(child));
1539
+ }
1540
+ }
1541
+ for (const node of nodes) {
1542
+ if (rollupColumns.has(node.id)) {
1543
+ continue;
1544
+ }
1545
+ const root = node.id === document.rootNodeId;
1546
+ switch (node.kind) {
1547
+ case 'input':
1548
+ case 'semantic': {
1549
+ if (!equation) {
1550
+ // A native method's observed facts.
1551
+ facts.push({
1552
+ label: serverText(node.labelKey, ctx) ??
1553
+ ctx.translate(`${K}.generic.fact`),
1554
+ data: toExplanationData(node.value, ctx),
1555
+ });
1556
+ break;
1557
+ }
1558
+ if (Array.isArray(node.value) || root)
1559
+ break;
1560
+ if (node.kind === 'semantic' &&
1561
+ scheduleDetailOf(document, node.reference)) {
1562
+ break;
1563
+ }
1564
+ const item = {
1565
+ label: nodeLabel(node, ctx),
1566
+ value: nodeValueText(node, ctx),
1567
+ };
1568
+ const key = `${item.label}\u0000${item.value}`;
1569
+ if (!seenValues.has(key)) {
1570
+ seenValues.add(key);
1571
+ values.push(item);
1572
+ }
1573
+ break;
1574
+ }
1575
+ case 'function':
1576
+ case 'conditional': {
1577
+ const name = functionName(node);
1578
+ if (root ||
1579
+ !equation ||
1580
+ document.provider === 'codeBuilder' ||
1581
+ PREDICATES.has(name) ||
1582
+ name === 'TODAY' ||
1583
+ node.state === 'notEvaluated') {
1584
+ break;
1585
+ }
1586
+ const segments = buildExplanationSegments(document, ctx, 'labels', node.id);
1587
+ if (segments?.length) {
1588
+ steps.push({
1589
+ segments: capitalizeSegments(segments),
1590
+ result: formatTypedValue(node.value, null, ctx),
1591
+ });
1592
+ }
1593
+ break;
1594
+ }
1595
+ case 'codeBlock': {
1596
+ const raw = byId.get(node.children[0]);
1597
+ const value = formatTypedValue(node.value, null, ctx);
1598
+ const rawText = raw && raw.value !== undefined
1599
+ ? formatTypedValue(raw.value, null, ctx)
1600
+ : null;
1601
+ codeBlocks.push({
1602
+ type: CODE_BLOCK_TYPES.has(node.operation ?? '')
1603
+ ? ctx.translate(`${K}.codeBlock.${node.operation}`)
1604
+ : ctx.translate(`${K}.generic.codePart`),
1605
+ value,
1606
+ raw: rawText !== null && rawText !== value ? rawText : null,
1607
+ });
1608
+ break;
1609
+ }
1610
+ default:
1611
+ break;
1612
+ }
1613
+ }
1614
+ return {
1615
+ // A status's rules section says how rules are chosen.
1616
+ description: equation || document.statusRules?.length
1617
+ ? null
1618
+ : describeDocument(document, ctx),
1619
+ values,
1620
+ records: equation ? recordTables(document, rollupColumns, ctx) : [],
1621
+ steps,
1622
+ statusRules: toStatusRuleViews(document, ctx, statusNames),
1623
+ schedule: (document.schedule ?? []).map((detail) => toScheduleView(detail, ctx,
1624
+ // The rollup is the whole formula: the summary already names it.
1625
+ byId.get(document.rootNodeId)?.reference === detail.reference)),
1626
+ codeBlocks,
1627
+ facts,
1628
+ };
1629
+ }
1630
+ /**
1631
+ * List inputs side by side by the rows they came from: `value[i]` belongs to
1632
+ * `recordIds[i]`, nulls and repeats included. Inputs whose ids don't line up
1633
+ * with their values are left out rather than guessed.
1634
+ */
1635
+ function recordTables(document, rollupColumns, ctx) {
1636
+ const groups = new Map();
1637
+ for (const node of document.nodes ?? []) {
1638
+ if (node.kind !== 'input' ||
1639
+ rollupColumns.has(node.id) ||
1640
+ !Array.isArray(node.value) ||
1641
+ !node.recordIds?.length ||
1642
+ node.recordIds.length !== node.value.length) {
1643
+ continue;
1644
+ }
1645
+ const table = referenceTable(node.reference) ?? '';
1646
+ const key = `${table}|${node.recordIds.join(',')}`;
1647
+ const group = groups.get(key) ?? {
1648
+ table,
1649
+ ids: node.recordIds,
1650
+ columns: [],
1651
+ };
1652
+ if (!group.columns.some((column) => column.reference === node.reference)) {
1653
+ group.columns.push(node);
1654
+ }
1655
+ groups.set(key, group);
1656
+ }
1657
+ return [...groups.values()].map((group) => ({
1658
+ columns: group.columns.map((column) => nodeLabel(column, ctx)),
1659
+ rows: group.ids.map((recordId, index) => {
1660
+ // The source names the context of a row; its order is never used.
1661
+ const source = (document.sources ?? []).find((item) => item.tablePath === group.table &&
1662
+ !!item.contextKey &&
1663
+ item.recordIds?.includes(recordId));
1664
+ return {
1665
+ ref: source?.contextKey
1666
+ ? { contextKey: source.contextKey, recordId }
1667
+ : null,
1668
+ cells: group.columns.map((column) => formatTypedValue(column.value[index], nodeViewType(column), ctx)),
1669
+ };
1670
+ }),
1671
+ }));
1672
+ }
1673
+ /** Whether the details have anything beyond the summary. */
1674
+ function hasExplanationDetails(view) {
1675
+ return (view.values.length > 0 ||
1676
+ view.records.length > 0 ||
1677
+ view.steps.length > 0 ||
1678
+ view.statusRules.length > 0 ||
1679
+ view.schedule.length > 0 ||
1680
+ view.codeBlocks.length > 0 ||
1681
+ view.facts.length > 0);
1682
+ }
1683
+ /** Every record the details name, for one batch of name reads. */
1684
+ function detailRecordRefs(view) {
1685
+ return [
1686
+ ...view.records.flatMap((table) => table.rows
1687
+ .map((row) => row.ref)
1688
+ .filter((ref) => !!ref)),
1689
+ ...view.schedule.flatMap((detail) => detail.contributors.map((row) => row.ref)),
1690
+ ];
1691
+ }
1692
+ /**
1693
+ * The status a rule selects, by the name its property gives it. A status the
1694
+ * host has no name for reads as its key in words (`no_baseline` → `No
1695
+ * baseline`): a generic label would make every rule read the same.
1696
+ */
1697
+ function statusName(key, statusNames) {
1698
+ return statusNames[key] || humanizeKey$1(key);
1699
+ }
1700
+ /** The rule that chose the status, if one did. */
1701
+ function selectedStatusRule(document) {
1702
+ return document.statusRules?.find((rule) => rule.selected) ?? null;
1703
+ }
1704
+ /** Status rules in the order they are checked. */
1705
+ function orderedStatusRules(document) {
1706
+ return (document.statusRules ?? []).slice().sort((a, b) => a.order - b.order);
1707
+ }
1708
+ function toStatusRuleViews(document, ctx, statusNames) {
1709
+ return orderedStatusRules(document).map((rule, index) => {
1710
+ const result = rule.condition?.result;
1711
+ const verdict = rule.selected
1712
+ ? 'selected'
1713
+ : rule.state === 'failed'
1714
+ ? 'failed'
1715
+ : rule.state === 'notEvaluated'
1716
+ ? 'notEvaluated'
1717
+ : result === true
1718
+ ? 'matched'
1719
+ : result === false
1720
+ ? 'notMatched'
1721
+ : 'checked';
1722
+ return {
1723
+ key: rule.key,
1724
+ name: statusName(rule.key, statusNames),
1725
+ position: index + 1,
1726
+ verdict,
1727
+ // Each condition resolves its node ids within its own document.
1728
+ segments: rule.condition && rule.condition.status === 'available'
1729
+ ? buildExplanationSegments(rule.condition, ctx, 'inline')
1730
+ : null,
1731
+ checks: rule.condition && rule.condition.status === 'available'
1732
+ ? buildConditionChecks(rule.condition, ctx)
1733
+ : null,
1734
+ };
1735
+ });
1736
+ }
1737
+ function scheduleKind(reference) {
1738
+ const column = referenceColumn(reference);
1739
+ return column === 'actual_progress'
1740
+ ? 'actual'
1741
+ : column === 'planned_progress'
1742
+ ? 'planned'
1743
+ : column === 'baseline_progress'
1744
+ ? 'baseline'
1745
+ : 'other';
1746
+ }
1747
+ /** Whether a rollup found no baseline at all, so its 0 is not a baseline. */
1748
+ function isMissingBaseline(detail) {
1749
+ return (detail.notes ?? []).includes('noBaselineProgressInputs');
1750
+ }
1751
+ function toScheduleView(detail, ctx, standalone = false) {
1752
+ const t = (key, params) => ctx.translate(`${K}.schedule.${key}`, params);
1753
+ const kind = scheduleKind(detail.reference);
1754
+ const missingBaseline = isMissingBaseline(detail);
1755
+ const contributors = detail.contributors ?? [];
1756
+ const counted = contributors.filter((row) => row.includedInAggregation);
1757
+ const aggregation = ['weightedAverage', 'arithmeticMean', 'empty'].includes(detail.aggregation)
1758
+ ? t(`aggregation.${detail.aggregation}`)
1759
+ : null;
1760
+ const weighting = detail.weightMode === 'workingDays' ||
1761
+ detail.weightMode === 'explicitWeight'
1762
+ ? t(`weightMode.${detail.weightMode}`)
1763
+ : null;
1764
+ const semantic = semanticKey(detail.reference);
1765
+ return {
1766
+ kind,
1767
+ standalone,
1768
+ title: semantic
1769
+ ? ctx.translate(`${K}.semantic.${semantic}`)
1770
+ : ctx.translate(`${K}.generic.scheduleValue`),
1771
+ meaning: kind === 'other' ? null : t(`meaning.${kind}`),
1772
+ result: percent(detail.result),
1773
+ // A standalone rollup's aggregation is already in the summary.
1774
+ method: [standalone ? null : aggregation, weighting]
1775
+ .filter((part) => !!part)
1776
+ .join(' · '),
1777
+ counted: t('counted', {
1778
+ counted: counted.length,
1779
+ total: contributors.length,
1780
+ }),
1781
+ notes: (detail.notes ?? [])
1782
+ .map((note) => (SCHEDULE_NOTES.has(note) ? t(`note.${note}`) : null))
1783
+ .filter((note) => !!note),
1784
+ missingBaseline,
1785
+ weightLabel: detail.weightMode === 'workingDays' ? t('workingDays') : t('weight'),
1786
+ contributors: contributors.map((row) => toContributorView(row, kind, missingBaseline, ctx)),
1787
+ };
1788
+ }
1789
+ function toContributorView(row, kind, missingBaseline, ctx) {
1790
+ const t = (key, params) => ctx.translate(`${K}.schedule.${key}`, params);
1791
+ const plan = row.plannedCalculation;
1792
+ const start = plan?.plannedStart ?? row.plannedStart;
1793
+ const finish = plan?.plannedFinish ?? row.plannedFinish;
1794
+ const reason = !row.includedInAggregation
1795
+ ? row.weight === 0
1796
+ ? t('reason.zeroWeight')
1797
+ : t('reason.notCounted')
1798
+ : row.inputMissing
1799
+ ? t(kind === 'baseline' || missingBaseline
1800
+ ? 'reason.missingBaseline'
1801
+ : 'reason.missingInput')
1802
+ : null;
1803
+ return {
1804
+ ref: { contextKey: row.contextKey ?? '', recordId: row.recordId },
1805
+ type: ITEM_TYPES.has(row.moduleKey) ? t(`itemType.${row.moduleKey}`) : null,
1806
+ progress: row.inputMissing && (kind === 'baseline' || missingBaseline)
1807
+ ? '—'
1808
+ : percent(row.progress),
1809
+ weight: formatExplanationNumber(row.weight),
1810
+ counted: row.includedInAggregation,
1811
+ reason,
1812
+ planned: plan
1813
+ ? {
1814
+ dates: start || finish
1815
+ ? `${start ? ctx.formatDate(start, 'date') : '—'} – ${finish ? ctx.formatDate(finish, 'date') : '—'}`
1816
+ : null,
1817
+ time: plan.elapsedWorkingMinutes !== null &&
1818
+ plan.totalWorkingMinutes !== null
1819
+ ? t('workingHoursElapsed', {
1820
+ elapsed: formatExplanationNumber(Math.round((plan.elapsedWorkingMinutes / 60) * 100) / 100),
1821
+ total: formatExplanationNumber(Math.round((plan.totalWorkingMinutes / 60) * 100) / 100),
1822
+ })
1823
+ : null,
1824
+ }
1825
+ : null,
1826
+ };
1827
+ }
1828
+ /** Minutes after midnight as `08:30`. */
1829
+ function clock(minutes) {
1830
+ const h = Math.floor(minutes / 60);
1831
+ const m = minutes % 60;
1832
+ return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
1833
+ }
1834
+
1835
+ /** Everything both the tooltip and the details panel show. */
1836
+ function buildCalculationExplanationView(explanation, target, ctx, statusNames) {
1837
+ const { document, basis } = explanation;
1838
+ const status = document.provider === 'status';
1839
+ const result = status
1840
+ ? statusName(String(document.result ?? ''), statusNames)
1841
+ : formatTypedValue(document.result, explanation.viewType, ctx);
1842
+ const summary = summarize(document, target, ctx);
1843
+ const built = buildExplanationDetails(document, ctx, statusNames);
1844
+ // The values line already shows every single value the formula used; the
1845
+ // panel does not list them again.
1846
+ const details = summary.values ? { ...built, values: [] } : built;
1847
+ return {
1848
+ basis,
1849
+ calculatedAt: document.calculatedAt,
1850
+ result,
1851
+ summary,
1852
+ definitionChanged: explanation.definitionChanged,
1853
+ refreshed: explanation.refreshed,
1854
+ // A current calculation is shown beside the value on the page, never in
1855
+ // place of it: the page keeps what it read.
1856
+ differs: basis === 'currentCalculation' &&
1857
+ !status &&
1858
+ !isSameSavedValue(primitiveText(document.result), target.displayedValue)
1859
+ ? {
1860
+ page: formatTypedValue(target.displayedValue ?? null, explanation.viewType, ctx),
1861
+ current: result,
1862
+ }
1863
+ : null,
1864
+ missingBaseline: (document.schedule ?? []).some(isMissingBaseline),
1865
+ details,
1866
+ hasDetails: hasExplanationDetails(details),
1867
+ };
1868
+ }
1869
+ function summarize(document, target, ctx) {
1870
+ const none = {
1871
+ labels: null,
1872
+ values: null,
1873
+ description: null,
1874
+ status: null,
1875
+ noRuleMatched: false,
1876
+ recordCount: null,
1877
+ };
1878
+ if (document.provider === 'status' && document.statusRules?.length) {
1879
+ const rules = orderedStatusRules(document);
1880
+ const rule = selectedStatusRule(document);
1881
+ return {
1882
+ ...none,
1883
+ status: rule
1884
+ ? {
1885
+ position: rules.indexOf(rule) + 1,
1886
+ total: rules.length,
1887
+ condition: rule.condition?.status === 'available'
1888
+ ? buildExplanationSegments(rule.condition, ctx, 'inline')
1889
+ : null,
1890
+ checks: rule.condition?.status === 'available'
1891
+ ? buildConditionChecks(rule.condition, ctx)
1892
+ : null,
1893
+ }
1894
+ : null,
1895
+ noRuleMatched: !rule,
1896
+ };
1897
+ }
1898
+ if (document.provider === 'codeBuilder') {
1899
+ const parts = buildCodeSegments(document, ctx);
1900
+ if (parts.length) {
1901
+ return { ...none, values: parts };
1902
+ }
1903
+ }
1904
+ if (isEquationDocument(document)) {
1905
+ const shape = buildExplanationSegments(document, ctx, 'labels');
1906
+ if (shape?.length) {
1907
+ const values = buildExplanationSegments(document, ctx, 'values');
1908
+ return {
1909
+ ...none,
1910
+ labels: [
1911
+ { kind: 'term', label: target.label, value: null },
1912
+ { kind: 'text', text: '=' },
1913
+ ...shape,
1914
+ ],
1915
+ values: values?.length ? capitalizeSegments(values) : null,
1916
+ recordCount: values ? null : listedRecordCount(document),
1917
+ };
1918
+ }
1919
+ }
1920
+ // A native method, a schedule field or a manual status: the calculation
1921
+ // in words, then its result.
1922
+ return { ...none, description: describeDocument(document, ctx) };
1923
+ }
1924
+ /** Records the formula's list inputs read, counted once each. */
1925
+ function listedRecordCount(document) {
1926
+ const tables = new Map();
1927
+ for (const node of document.nodes ?? []) {
1928
+ if (node.kind !== 'input' || !Array.isArray(node.value))
1929
+ continue;
1930
+ const table = (node.reference ?? '').split('::')[0];
1931
+ const ids = tables.get(table) ?? new Set();
1932
+ (node.recordIds ?? []).forEach((id) => ids.add(id));
1933
+ tables.set(table, ids);
1934
+ }
1935
+ const counts = [...tables.values()].map((ids) => ids.size);
1936
+ return counts.length ? Math.max(...counts) : null;
1937
+ }
1938
+ function primitiveText(value) {
1939
+ return value === null || value === undefined || typeof value === 'object'
1940
+ ? null
1941
+ : String(value);
1942
+ }
1943
+ /**
1944
+ * Whether the saved value is the one on screen. Both are the persisted string,
1945
+ * but a number may be written either way (`40` and `40.0`), so numbers compare
1946
+ * as numbers.
1947
+ */
1948
+ function isSameSavedValue(saved, displayed) {
1949
+ const a = (saved ?? '').trim();
1950
+ const b = (displayed ?? '').trim();
1951
+ if (a === b) {
1952
+ return true;
1953
+ }
1954
+ if (a === '' || b === '') {
1955
+ return false;
1956
+ }
1957
+ const x = Number(a);
1958
+ const y = Number(b);
1959
+ return Number.isFinite(x) && Number.isFinite(y) && x === y;
1960
+ }
1961
+
1962
+ /**
1963
+ * One shared active-language signal per `TranslocoService`.
1964
+ *
1965
+ * `mt-entity-preview` renders once per property per record — a client-list card
1966
+ * grid mounts thousands of them — so a `toSignal(langChanges$)` inside each
1967
+ * instance would open thousands of subscriptions to the same Subject just to
1968
+ * read one global value. The language is global, so the signal is too: created
1969
+ * once, cached against the service, and shared by every entity that needs it.
1970
+ *
1971
+ * `manualCleanup` is deliberate. The cached signal outlives any single
1972
+ * component by design, and the service it hangs off is the root injector's —
1973
+ * tying its subscription to whichever entity happened to ask first would tear
1974
+ * it down the moment that entity scrolled out of view.
1975
+ */
1976
+ const langSignals = new WeakMap();
1977
+ function sharedActiveLang(transloco) {
1978
+ const cached = langSignals.get(transloco);
1979
+ if (cached) {
1980
+ return cached;
1981
+ }
1982
+ const lang = toSignal(transloco.langChanges$, {
1983
+ initialValue: transloco.getActiveLang(),
1984
+ manualCleanup: true,
1985
+ });
1986
+ langSignals.set(transloco, lang);
1987
+ return lang;
1988
+ }
1989
+
1990
+ /**
1991
+ * The formatting context of an explanation (language, currency, dates, text)
1992
+ * and the business names of the explained status property's statuses. Call
1993
+ * in an injection context of a component that provides `MTDateFormatPipe`.
1994
+ */
1995
+ function injectExplanationContext(target) {
1996
+ const transloco = inject(TranslocoService);
1997
+ const lang = sharedActiveLang(transloco);
1998
+ const currency = inject(MT_CALCULATION_CURRENCY);
1999
+ const namesOf = inject(MT_CALCULATION_STATUS_NAMES);
2000
+ const datePipe = inject(MTDateFormatPipe);
2001
+ return {
2002
+ context: computed(() => ({
2003
+ lang: lang(),
2004
+ currency: currency(),
2005
+ formatDate: (value, type) => datePipe.transform(value, type),
2006
+ translate: (key, params) => transloco.translate(key, params),
2007
+ })),
2008
+ // The property's own names first; the value on screen fills a gap.
2009
+ statusNames: computed(() => ({
2010
+ ...(target().statusNames ?? {}),
2011
+ ...namesOf(target().propertyKey, lang()),
2012
+ })),
2013
+ };
2014
+ }
2015
+
2016
+ /** Pieces that hug their neighbour: `(a`, `a)`, `a,`, `f(a`. */
2017
+ const OPENERS = /[([]$/;
2018
+ const CLOSERS = /^[)\],،]$/;
2019
+ /**
2020
+ * A readable equation: `Remaining = Budget − Spent`, or its values
2021
+ * `10,000 SAR − 125,454 SAR = −115,454 SAR`. It reads in the page's direction:
2022
+ * functions read as words (`sum of Amount where …`), and in Arabic those words
2023
+ * run right to left. Each term and value is isolated and kept whole, so a name
2024
+ * or an amount never breaks across lines or reorders with its neighbours.
2025
+ * Every piece is interpolated as text.
2026
+ */
2027
+ class CalculationExplanationEquation {
2028
+ segments = input.required(...(ngDevMode ? [{ debugName: "segments" }] : /* istanbul ignore next */ []));
2029
+ /** Shown after the equation, behind `resultOperator`. */
2030
+ result = input(null, ...(ngDevMode ? [{ debugName: "result" }] : /* istanbul ignore next */ []));
2031
+ resultOperator = input('=', ...(ngDevMode ? [{ debugName: "resultOperator" }] : /* istanbul ignore next */ []));
2032
+ pieces = computed(() => {
2033
+ const segments = this.segments();
2034
+ return segments.map((segment, index) => {
2035
+ const next = segments[index + 1];
2036
+ const text = segment.kind === 'text' ? segment.text : '';
2037
+ const nextText = next?.kind === 'text' ? next.text : '';
2038
+ return {
2039
+ segment,
2040
+ space: !!next && !OPENERS.test(text) && !CLOSERS.test(nextText),
2041
+ };
2042
+ });
2043
+ }, ...(ngDevMode ? [{ debugName: "pieces" }] : /* istanbul ignore next */ []));
2044
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: CalculationExplanationEquation, deps: [], target: i0.ɵɵFactoryTarget.Component });
2045
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: CalculationExplanationEquation, isStandalone: true, selector: "mt-calculation-explanation-equation", inputs: { segments: { classPropertyName: "segments", publicName: "segments", isSignal: true, isRequired: true, transformFunction: null }, result: { classPropertyName: "result", publicName: "result", isSignal: true, isRequired: false, transformFunction: null }, resultOperator: { classPropertyName: "resultOperator", publicName: "resultOperator", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0, template: `
2046
+ <div class="text-start break-words">
2047
+ @for (piece of pieces(); track $index) {
2048
+ @switch (piece.segment.kind) {
2049
+ @case ('term') {
2050
+ <bdi class="inline-block max-w-full"
2051
+ ><span class="font-medium text-surface-900 dark:text-surface-0">{{
2052
+ piece.segment.label
2053
+ }}</span>
2054
+ @if (piece.segment.value !== null) {
2055
+ <!-- The leading space lives inside the text node: Angular
2056
+ drops whitespace-only nodes between elements. -->
2057
+ <span class="text-surface-500 dark:text-surface-400">
2058
+ ({{ piece.segment.value }})</span
2059
+ >
2060
+ }
2061
+ </bdi>
2062
+ }
2063
+ @case ('value') {
2064
+ <bdi
2065
+ class="inline-block max-w-full font-medium text-surface-800 tabular-nums dark:text-surface-100"
2066
+ >{{ piece.segment.text }}</bdi
2067
+ >
2068
+ }
2069
+ @case ('result') {
2070
+ <bdi
2071
+ class="inline-block max-w-full text-surface-500 dark:text-surface-400"
2072
+ >→ {{ piece.segment.text }}</bdi
2073
+ >
2074
+ }
2075
+ @case ('muted') {
2076
+ <span class="text-surface-400 italic">{{
2077
+ piece.segment.text
2078
+ }}</span>
2079
+ }
2080
+ @default {
2081
+ <span class="text-surface-500 dark:text-surface-400">{{
2082
+ piece.segment.text
2083
+ }}</span>
2084
+ }
2085
+ }
2086
+ @if (piece.space) {
2087
+ {{ ' ' }}
2088
+ }
2089
+ }
2090
+ @if (result(); as value) {
2091
+ <span class="text-surface-400"> {{ resultOperator() }} </span>
2092
+ <bdi
2093
+ class="inline-block max-w-full font-semibold text-surface-900 tabular-nums dark:text-surface-0"
2094
+ >{{ value }}</bdi
2095
+ >
2096
+ }
2097
+ </div>
2098
+ `, isInline: true, changeDetection: i0.ChangeDetectionStrategy.OnPush });
2099
+ }
2100
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: CalculationExplanationEquation, decorators: [{
2101
+ type: Component,
2102
+ args: [{
2103
+ selector: 'mt-calculation-explanation-equation',
2104
+ changeDetection: ChangeDetectionStrategy.OnPush,
2105
+ template: `
2106
+ <div class="text-start break-words">
2107
+ @for (piece of pieces(); track $index) {
2108
+ @switch (piece.segment.kind) {
2109
+ @case ('term') {
2110
+ <bdi class="inline-block max-w-full"
2111
+ ><span class="font-medium text-surface-900 dark:text-surface-0">{{
2112
+ piece.segment.label
2113
+ }}</span>
2114
+ @if (piece.segment.value !== null) {
2115
+ <!-- The leading space lives inside the text node: Angular
2116
+ drops whitespace-only nodes between elements. -->
2117
+ <span class="text-surface-500 dark:text-surface-400">
2118
+ ({{ piece.segment.value }})</span
2119
+ >
2120
+ }
2121
+ </bdi>
2122
+ }
2123
+ @case ('value') {
2124
+ <bdi
2125
+ class="inline-block max-w-full font-medium text-surface-800 tabular-nums dark:text-surface-100"
2126
+ >{{ piece.segment.text }}</bdi
2127
+ >
2128
+ }
2129
+ @case ('result') {
2130
+ <bdi
2131
+ class="inline-block max-w-full text-surface-500 dark:text-surface-400"
2132
+ >→ {{ piece.segment.text }}</bdi
2133
+ >
2134
+ }
2135
+ @case ('muted') {
2136
+ <span class="text-surface-400 italic">{{
2137
+ piece.segment.text
2138
+ }}</span>
2139
+ }
2140
+ @default {
2141
+ <span class="text-surface-500 dark:text-surface-400">{{
2142
+ piece.segment.text
2143
+ }}</span>
2144
+ }
2145
+ }
2146
+ @if (piece.space) {
2147
+ {{ ' ' }}
2148
+ }
2149
+ }
2150
+ @if (result(); as value) {
2151
+ <span class="text-surface-400"> {{ resultOperator() }} </span>
2152
+ <bdi
2153
+ class="inline-block max-w-full font-semibold text-surface-900 tabular-nums dark:text-surface-0"
2154
+ >{{ value }}</bdi
2155
+ >
2156
+ }
2157
+ </div>
2158
+ `,
2159
+ }]
2160
+ }], propDecorators: { segments: [{ type: i0.Input, args: [{ isSignal: true, alias: "segments", required: true }] }], result: [{ type: i0.Input, args: [{ isSignal: true, alias: "result", required: false }] }], resultOperator: [{ type: i0.Input, args: [{ isSignal: true, alias: "resultOperator", required: false }] }] } });
2161
+
2162
+ const MARKS = {
2163
+ met: { text: '✓', class: 'bg-green-50 text-green-700' },
2164
+ notMet: { text: '✗', class: 'bg-red-50 text-red-700' },
2165
+ notChecked: {
2166
+ text: '–',
2167
+ class: 'bg-surface-100 text-surface-500 dark:bg-surface-800 dark:text-surface-400',
2168
+ },
2169
+ };
2170
+ /**
2171
+ * A condition as a checklist: each part a rule requires on its own line,
2172
+ * marked met, not met, or not checked (a part evaluation never reached).
2173
+ * An `or` lists its options under "At least one of".
2174
+ */
2175
+ class CalculationExplanationChecks {
2176
+ checks = input.required(...(ngDevMode ? [{ debugName: "checks" }] : /* istanbul ignore next */ []));
2177
+ prefix = CALCULATION_EXPLANATION_KEYS;
2178
+ marks = MARKS;
2179
+ markOf(met) {
2180
+ return met === null ? 'notChecked' : met ? 'met' : 'notMet';
2181
+ }
2182
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: CalculationExplanationChecks, deps: [], target: i0.ɵɵFactoryTarget.Component });
2183
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: CalculationExplanationChecks, isStandalone: true, selector: "mt-calculation-explanation-checks", inputs: { checks: { classPropertyName: "checks", publicName: "checks", isSignal: true, isRequired: true, transformFunction: null } }, ngImport: i0, template: `
2184
+ <ng-template #list let-checks>
2185
+ <ul class="flex flex-col gap-1">
2186
+ @for (check of checks; track $index) {
2187
+ @let mark = markOf(check.met);
2188
+ <li class="flex items-start gap-2">
2189
+ <span
2190
+ class="mt-0.5 inline-flex size-4 shrink-0 items-center justify-center rounded-full text-[10px] leading-none font-bold"
2191
+ [class]="marks[mark].class"
2192
+ role="img"
2193
+ [attr.aria-label]="prefix + '.check.' + mark | transloco"
2194
+ >{{ marks[mark].text }}</span
2195
+ >
2196
+ <div class="flex min-w-0 flex-1 flex-col gap-1">
2197
+ @if (check.anyOf; as options) {
2198
+ <span class="text-surface-600 dark:text-surface-300">{{
2199
+ prefix + '.check.anyOf' | transloco
2200
+ }}</span>
2201
+ <ng-container
2202
+ [ngTemplateOutlet]="list"
2203
+ [ngTemplateOutletContext]="{ $implicit: options }"
2204
+ />
2205
+ } @else {
2206
+ <mt-calculation-explanation-equation
2207
+ [segments]="check.segments"
2208
+ />
2209
+ }
2210
+ </div>
2211
+ </li>
2212
+ }
2213
+ </ul>
2214
+ </ng-template>
2215
+ <ng-container
2216
+ [ngTemplateOutlet]="list"
2217
+ [ngTemplateOutletContext]="{ $implicit: checks() }"
2218
+ />
2219
+ `, isInline: true, dependencies: [{ kind: "component", type: CalculationExplanationEquation, selector: "mt-calculation-explanation-equation", inputs: ["segments", "result", "resultOperator"] }, { kind: "directive", type: NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "pipe", type: TranslocoPipe, name: "transloco" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
2220
+ }
2221
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: CalculationExplanationChecks, decorators: [{
2222
+ type: Component,
2223
+ args: [{
2224
+ selector: 'mt-calculation-explanation-checks',
2225
+ changeDetection: ChangeDetectionStrategy.OnPush,
2226
+ imports: [CalculationExplanationEquation, NgTemplateOutlet, TranslocoPipe],
2227
+ template: `
2228
+ <ng-template #list let-checks>
2229
+ <ul class="flex flex-col gap-1">
2230
+ @for (check of checks; track $index) {
2231
+ @let mark = markOf(check.met);
2232
+ <li class="flex items-start gap-2">
2233
+ <span
2234
+ class="mt-0.5 inline-flex size-4 shrink-0 items-center justify-center rounded-full text-[10px] leading-none font-bold"
2235
+ [class]="marks[mark].class"
2236
+ role="img"
2237
+ [attr.aria-label]="prefix + '.check.' + mark | transloco"
2238
+ >{{ marks[mark].text }}</span
2239
+ >
2240
+ <div class="flex min-w-0 flex-1 flex-col gap-1">
2241
+ @if (check.anyOf; as options) {
2242
+ <span class="text-surface-600 dark:text-surface-300">{{
2243
+ prefix + '.check.anyOf' | transloco
2244
+ }}</span>
2245
+ <ng-container
2246
+ [ngTemplateOutlet]="list"
2247
+ [ngTemplateOutletContext]="{ $implicit: options }"
2248
+ />
2249
+ } @else {
2250
+ <mt-calculation-explanation-equation
2251
+ [segments]="check.segments"
2252
+ />
2253
+ }
2254
+ </div>
2255
+ </li>
2256
+ }
2257
+ </ul>
2258
+ </ng-template>
2259
+ <ng-container
2260
+ [ngTemplateOutlet]="list"
2261
+ [ngTemplateOutletContext]="{ $implicit: checks() }"
2262
+ />
2263
+ `,
2264
+ }]
2265
+ }], propDecorators: { checks: [{ type: i0.Input, args: [{ isSignal: true, alias: "checks", required: true }] }] } });
2266
+
2267
+ /**
2268
+ * The short form of an explanation: the result with its business reason
2269
+ * (`Remaining = Budget − Spent`, then `10,000 SAR − 125,454 SAR =
2270
+ * −115,454 SAR`), and the notices that change how to read it. Shown in the
2271
+ * tooltip and at the top of the details panel.
2272
+ */
2273
+ class CalculationExplanationSummary {
2274
+ view = input.required(...(ngDevMode ? [{ debugName: "view" }] : /* istanbul ignore next */ []));
2275
+ prefix = CALCULATION_EXPLANATION_KEYS;
2276
+ empty = [];
2277
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: CalculationExplanationSummary, deps: [], target: i0.ɵɵFactoryTarget.Component });
2278
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: CalculationExplanationSummary, isStandalone: true, selector: "mt-calculation-explanation-summary", inputs: { view: { classPropertyName: "view", publicName: "view", isSignal: true, isRequired: true, transformFunction: null } }, ngImport: i0, template: `
2279
+ @let v = view();
2280
+ <div class="flex flex-col gap-2">
2281
+ <div
2282
+ class="flex flex-col gap-1.5 rounded-md border border-surface-200 bg-surface-50 px-3 py-2 text-surface-800 dark:border-surface-700 dark:bg-surface-800 dark:text-surface-100"
2283
+ >
2284
+ @if (v.summary.status; as status) {
2285
+ <bdi class="font-semibold text-surface-900 dark:text-surface-0">{{
2286
+ v.result
2287
+ }}</bdi>
2288
+ <span class="text-xs text-surface-500 dark:text-surface-400">
2289
+ {{
2290
+ prefix + '.statusSelected'
2291
+ | transloco: { position: status.position, total: status.total }
2292
+ }}
2293
+ </span>
2294
+ @if (status.checks; as checks) {
2295
+ <mt-calculation-explanation-checks
2296
+ class="text-xs"
2297
+ [checks]="checks"
2298
+ />
2299
+ } @else if (status.condition; as condition) {
2300
+ <mt-calculation-explanation-equation
2301
+ class="text-xs"
2302
+ [segments]="condition"
2303
+ />
2304
+ }
2305
+ } @else if (v.summary.noRuleMatched) {
2306
+ <span>{{
2307
+ prefix + '.noRuleMatched' | transloco: { status: v.result }
2308
+ }}</span>
2309
+ } @else {
2310
+ @if (v.summary.labels; as labels) {
2311
+ <mt-calculation-explanation-equation [segments]="labels" />
2312
+ }
2313
+ @if (v.summary.description; as description) {
2314
+ <p class="break-words">{{ description }}</p>
2315
+ }
2316
+ @if (v.summary.values; as values) {
2317
+ <mt-calculation-explanation-equation
2318
+ [segments]="values"
2319
+ [result]="v.result"
2320
+ />
2321
+ } @else {
2322
+ <mt-calculation-explanation-equation
2323
+ [segments]="empty"
2324
+ [result]="v.result"
2325
+ />
2326
+ }
2327
+ @if (v.summary.recordCount; as count) {
2328
+ <span class="text-xs text-surface-500 dark:text-surface-400">{{
2329
+ prefix + '.recordsUsed' | transloco: { count }
2330
+ }}</span>
2331
+ }
2332
+ }
2333
+ </div>
2334
+ @if (v.missingBaseline) {
2335
+ <div
2336
+ class="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-700"
2337
+ >
2338
+ {{ prefix + '.missingBaseline' | transloco }}
2339
+ </div>
2340
+ }
2341
+ @if (v.differs; as differs) {
2342
+ <div
2343
+ class="rounded-md border border-primary-200 bg-primary-50 px-3 py-2 text-xs text-primary-700"
2344
+ >
2345
+ {{ prefix + '.differsFromPage' | transloco: differs }}
2346
+ </div>
2347
+ }
2348
+ @if (v.definitionChanged) {
2349
+ <div
2350
+ class="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-700"
2351
+ >
2352
+ {{ prefix + '.definitionChanged' | transloco }}
2353
+ </div>
2354
+ }
2355
+ @if (v.refreshed) {
2356
+ <div
2357
+ class="rounded-md border border-primary-200 bg-primary-50 px-3 py-2 text-xs text-primary-700"
2358
+ >
2359
+ {{ prefix + '.valueRefreshed' | transloco }}
2360
+ </div>
2361
+ }
2362
+ </div>
2363
+ `, isInline: true, dependencies: [{ kind: "component", type: CalculationExplanationChecks, selector: "mt-calculation-explanation-checks", inputs: ["checks"] }, { kind: "component", type: CalculationExplanationEquation, selector: "mt-calculation-explanation-equation", inputs: ["segments", "result", "resultOperator"] }, { kind: "pipe", type: TranslocoPipe, name: "transloco" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
2364
+ }
2365
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: CalculationExplanationSummary, decorators: [{
2366
+ type: Component,
2367
+ args: [{
2368
+ selector: 'mt-calculation-explanation-summary',
2369
+ changeDetection: ChangeDetectionStrategy.OnPush,
2370
+ imports: [
2371
+ CalculationExplanationChecks,
2372
+ CalculationExplanationEquation,
2373
+ TranslocoPipe,
2374
+ ],
2375
+ template: `
2376
+ @let v = view();
2377
+ <div class="flex flex-col gap-2">
2378
+ <div
2379
+ class="flex flex-col gap-1.5 rounded-md border border-surface-200 bg-surface-50 px-3 py-2 text-surface-800 dark:border-surface-700 dark:bg-surface-800 dark:text-surface-100"
2380
+ >
2381
+ @if (v.summary.status; as status) {
2382
+ <bdi class="font-semibold text-surface-900 dark:text-surface-0">{{
2383
+ v.result
2384
+ }}</bdi>
2385
+ <span class="text-xs text-surface-500 dark:text-surface-400">
2386
+ {{
2387
+ prefix + '.statusSelected'
2388
+ | transloco: { position: status.position, total: status.total }
2389
+ }}
2390
+ </span>
2391
+ @if (status.checks; as checks) {
2392
+ <mt-calculation-explanation-checks
2393
+ class="text-xs"
2394
+ [checks]="checks"
2395
+ />
2396
+ } @else if (status.condition; as condition) {
2397
+ <mt-calculation-explanation-equation
2398
+ class="text-xs"
2399
+ [segments]="condition"
2400
+ />
2401
+ }
2402
+ } @else if (v.summary.noRuleMatched) {
2403
+ <span>{{
2404
+ prefix + '.noRuleMatched' | transloco: { status: v.result }
2405
+ }}</span>
2406
+ } @else {
2407
+ @if (v.summary.labels; as labels) {
2408
+ <mt-calculation-explanation-equation [segments]="labels" />
2409
+ }
2410
+ @if (v.summary.description; as description) {
2411
+ <p class="break-words">{{ description }}</p>
2412
+ }
2413
+ @if (v.summary.values; as values) {
2414
+ <mt-calculation-explanation-equation
2415
+ [segments]="values"
2416
+ [result]="v.result"
2417
+ />
2418
+ } @else {
2419
+ <mt-calculation-explanation-equation
2420
+ [segments]="empty"
2421
+ [result]="v.result"
2422
+ />
2423
+ }
2424
+ @if (v.summary.recordCount; as count) {
2425
+ <span class="text-xs text-surface-500 dark:text-surface-400">{{
2426
+ prefix + '.recordsUsed' | transloco: { count }
2427
+ }}</span>
2428
+ }
2429
+ }
2430
+ </div>
2431
+ @if (v.missingBaseline) {
2432
+ <div
2433
+ class="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-700"
2434
+ >
2435
+ {{ prefix + '.missingBaseline' | transloco }}
2436
+ </div>
2437
+ }
2438
+ @if (v.differs; as differs) {
2439
+ <div
2440
+ class="rounded-md border border-primary-200 bg-primary-50 px-3 py-2 text-xs text-primary-700"
2441
+ >
2442
+ {{ prefix + '.differsFromPage' | transloco: differs }}
2443
+ </div>
2444
+ }
2445
+ @if (v.definitionChanged) {
2446
+ <div
2447
+ class="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-700"
2448
+ >
2449
+ {{ prefix + '.definitionChanged' | transloco }}
2450
+ </div>
2451
+ }
2452
+ @if (v.refreshed) {
2453
+ <div
2454
+ class="rounded-md border border-primary-200 bg-primary-50 px-3 py-2 text-xs text-primary-700"
2455
+ >
2456
+ {{ prefix + '.valueRefreshed' | transloco }}
2457
+ </div>
2458
+ }
2459
+ </div>
2460
+ `,
2461
+ }]
2462
+ }], propDecorators: { view: [{ type: i0.Input, args: [{ isSignal: true, alias: "view", required: true }] }] } });
2463
+
2464
+ /**
2465
+ * A part of the details panel the reader can fold: its title (and a count)
2466
+ * always shows, its content only when open. A native `<details>`, so it
2467
+ * works with the keyboard and screen readers without any state here; `open`
2468
+ * only sets how it starts.
2469
+ */
2470
+ class CalculationExplanationSection {
2471
+ title = input.required(...(ngDevMode ? [{ debugName: "title" }] : /* istanbul ignore next */ []));
2472
+ /** Shown at the end of the title row: a count or a result. */
2473
+ aside = input(null, ...(ngDevMode ? [{ debugName: "aside" }] : /* istanbul ignore next */ []));
2474
+ /** Whether it starts open. */
2475
+ open = input(false, ...(ngDevMode ? [{ debugName: "open" }] : /* istanbul ignore next */ []));
2476
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: CalculationExplanationSection, deps: [], target: i0.ɵɵFactoryTarget.Component });
2477
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: CalculationExplanationSection, isStandalone: true, selector: "mt-calculation-explanation-section", inputs: { title: { classPropertyName: "title", publicName: "title", isSignal: true, isRequired: true, transformFunction: null }, aside: { classPropertyName: "aside", publicName: "aside", isSignal: true, isRequired: false, transformFunction: null }, open: { classPropertyName: "open", publicName: "open", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0, template: `
2478
+ <details
2479
+ class="group rounded-md border border-surface-200 dark:border-surface-700"
2480
+ [open]="open()"
2481
+ >
2482
+ <summary
2483
+ class="flex cursor-pointer list-none items-center gap-2 rounded-md px-3 py-2 select-none hover:bg-surface-50 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary-500 dark:hover:bg-surface-800 [&::-webkit-details-marker]:hidden"
2484
+ >
2485
+ <mt-icon
2486
+ icon="arrow.chevron-right"
2487
+ size="xs"
2488
+ class="shrink-0 text-surface-500 transition-transform group-open:rotate-90 rtl:rotate-180 dark:text-surface-400"
2489
+ />
2490
+ <span
2491
+ class="min-w-0 flex-1 font-semibold text-surface-900 dark:text-surface-0"
2492
+ >{{ title() }}</span
2493
+ >
2494
+ @if (aside(); as text) {
2495
+ <span
2496
+ class="shrink-0 text-xs text-surface-500 tabular-nums dark:text-surface-400"
2497
+ >{{ text }}</span
2498
+ >
2499
+ }
2500
+ </summary>
2501
+ <div
2502
+ class="flex flex-col gap-2 border-t border-surface-200 px-3 py-2 dark:border-surface-700"
2503
+ >
2504
+ <ng-content />
2505
+ </div>
2506
+ </details>
2507
+ `, isInline: true, dependencies: [{ kind: "component", type: Icon, selector: "mt-icon", inputs: ["icon"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
2508
+ }
2509
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: CalculationExplanationSection, decorators: [{
2510
+ type: Component,
2511
+ args: [{
2512
+ selector: 'mt-calculation-explanation-section',
2513
+ changeDetection: ChangeDetectionStrategy.OnPush,
2514
+ imports: [Icon],
2515
+ template: `
2516
+ <details
2517
+ class="group rounded-md border border-surface-200 dark:border-surface-700"
2518
+ [open]="open()"
2519
+ >
2520
+ <summary
2521
+ class="flex cursor-pointer list-none items-center gap-2 rounded-md px-3 py-2 select-none hover:bg-surface-50 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary-500 dark:hover:bg-surface-800 [&::-webkit-details-marker]:hidden"
2522
+ >
2523
+ <mt-icon
2524
+ icon="arrow.chevron-right"
2525
+ size="xs"
2526
+ class="shrink-0 text-surface-500 transition-transform group-open:rotate-90 rtl:rotate-180 dark:text-surface-400"
2527
+ />
2528
+ <span
2529
+ class="min-w-0 flex-1 font-semibold text-surface-900 dark:text-surface-0"
2530
+ >{{ title() }}</span
2531
+ >
2532
+ @if (aside(); as text) {
2533
+ <span
2534
+ class="shrink-0 text-xs text-surface-500 tabular-nums dark:text-surface-400"
2535
+ >{{ text }}</span
2536
+ >
2537
+ }
2538
+ </summary>
2539
+ <div
2540
+ class="flex flex-col gap-2 border-t border-surface-200 px-3 py-2 dark:border-surface-700"
2541
+ >
2542
+ <ng-content />
2543
+ </div>
2544
+ </details>
2545
+ `,
2546
+ }]
2547
+ }], propDecorators: { title: [{ type: i0.Input, args: [{ isSignal: true, alias: "title", required: true }] }], aside: [{ type: i0.Input, args: [{ isSignal: true, alias: "aside", required: false }] }], open: [{ type: i0.Input, args: [{ isSignal: true, alias: "open", required: false }] }] } });
2548
+
2549
+ /** Lists up to this many rows start open; longer ones start folded. */
2550
+ const OPEN_ROWS = 10;
2551
+ /**
2552
+ * The detailed part of an explanation, shown in its side panel below the
2553
+ * summary. Each part folds, so a long status or schedule reads as a short
2554
+ * list of titles first: records behind list inputs (by name), intermediate
2555
+ * results, status rules (one row each, opening to their checklist), schedule
2556
+ * rollups with their items, generated-code parts
2557
+ * and native facts. Everything is the backend's captured data in business
2558
+ * wording; nothing is recalculated here.
2559
+ */
2560
+ class CalculationExplanationDetails {
2561
+ details = input.required(...(ngDevMode ? [{ debugName: "details" }] : /* istanbul ignore next */ []));
2562
+ /** Record titles by `calculationRecordKey`; `null` while they are read. */
2563
+ recordNames = input({}, ...(ngDevMode ? [{ debugName: "recordNames" }] : /* istanbul ignore next */ []));
2564
+ /** Generic labels for records without a readable title, by position. */
2565
+ fallbackLabel = input((position) => String(position), ...(ngDevMode ? [{ debugName: "fallbackLabel" }] : /* istanbul ignore next */ []));
2566
+ prefix = CALCULATION_EXPLANATION_KEYS;
2567
+ scheduleKeys = `${CALCULATION_EXPLANATION_KEYS}.schedule`;
2568
+ openRows = OPEN_ROWS;
2569
+ verdictClass = {
2570
+ selected: 'bg-primary-100 text-primary-700',
2571
+ matched: 'bg-green-50 text-green-700',
2572
+ notMatched: 'bg-surface-100 text-surface-600',
2573
+ checked: 'bg-surface-100 text-surface-600',
2574
+ failed: 'bg-red-50 text-red-700',
2575
+ notEvaluated: 'bg-surface-100 text-surface-400',
2576
+ };
2577
+ /** A record by its title; never by its id. */
2578
+ nameOf(ref, index) {
2579
+ const name = ref
2580
+ ? this.recordNames()?.[calculationRecordKey(ref.contextKey, ref.recordId)]
2581
+ : undefined;
2582
+ return name || this.fallbackLabel()(index + 1);
2583
+ }
2584
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: CalculationExplanationDetails, deps: [], target: i0.ɵɵFactoryTarget.Component });
2585
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: CalculationExplanationDetails, isStandalone: true, selector: "mt-calculation-explanation-details", inputs: { details: { classPropertyName: "details", publicName: "details", isSignal: true, isRequired: true, transformFunction: null }, recordNames: { classPropertyName: "recordNames", publicName: "recordNames", isSignal: true, isRequired: false, transformFunction: null }, fallbackLabel: { classPropertyName: "fallbackLabel", publicName: "fallbackLabel", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0, template: `
2586
+ <!-- A record by its title, a placeholder while titles are read, or a
2587
+ generic label; never its id. -->
2588
+ <ng-template #recordName let-ref let-n="n">
2589
+ @if (recordNames() === null) {
2590
+ <span
2591
+ class="inline-block h-3 w-24 animate-pulse rounded-md bg-surface-100 align-middle dark:bg-surface-800"
2592
+ aria-busy="true"
2593
+ ></span>
2594
+ } @else {
2595
+ <bdi class="break-words">{{ nameOf(ref, n) }}</bdi>
2596
+ }
2597
+ </ng-template>
2598
+
2599
+ <ng-template #dataTpl let-data>
2600
+ @switch (data.kind) {
2601
+ @case ('text') {
2602
+ <bdi class="break-words">{{ data.text }}</bdi>
2603
+ }
2604
+ @case ('list') {
2605
+ <bdi class="break-words">{{ data.items.join(', ') }}</bdi>
2606
+ }
2607
+ @case ('table') {
2608
+ <div class="overflow-x-auto">
2609
+ <table class="w-full text-xs tabular-nums">
2610
+ <thead>
2611
+ <tr class="text-surface-500 dark:text-surface-400">
2612
+ @for (column of data.columns; track $index) {
2613
+ <th class="px-2 py-1 text-start font-medium">
2614
+ {{ column }}
2615
+ </th>
2616
+ }
2617
+ </tr>
2618
+ </thead>
2619
+ <tbody>
2620
+ @for (row of data.rows; track $index) {
2621
+ <tr
2622
+ class="border-t border-surface-200 dark:border-surface-700"
2623
+ >
2624
+ @for (cell of row; track $index) {
2625
+ <td class="px-2 py-1 align-top break-words">
2626
+ <bdi>{{ cell }}</bdi>
2627
+ </td>
2628
+ }
2629
+ </tr>
2630
+ }
2631
+ </tbody>
2632
+ </table>
2633
+ @if (data.more > 0) {
2634
+ <p class="mt-1 text-surface-500 dark:text-surface-400">
2635
+ {{ prefix + '.moreRows' | transloco: { count: data.more } }}
2636
+ </p>
2637
+ }
2638
+ </div>
2639
+ }
2640
+ @case ('fields') {
2641
+ <dl
2642
+ class="grid grid-cols-[minmax(0,auto)_minmax(0,1fr)] gap-x-3 gap-y-1"
2643
+ >
2644
+ @for (field of data.fields; track $index) {
2645
+ <dt class="text-surface-500 dark:text-surface-400">
2646
+ {{ field.label }}
2647
+ </dt>
2648
+ <dd class="ms-0 min-w-0">
2649
+ <ng-container
2650
+ [ngTemplateOutlet]="dataTpl"
2651
+ [ngTemplateOutletContext]="{ $implicit: field.data }"
2652
+ />
2653
+ </dd>
2654
+ }
2655
+ </dl>
2656
+ }
2657
+ }
2658
+ </ng-template>
2659
+
2660
+ @let view = details();
2661
+ <div
2662
+ class="flex flex-col gap-3 text-sm text-surface-700 dark:text-surface-200"
2663
+ >
2664
+ @if (view.description) {
2665
+ <p>{{ view.description }}</p>
2666
+ }
2667
+
2668
+ @if (view.values.length) {
2669
+ <mt-calculation-explanation-section
2670
+ [title]="prefix + '.valuesUsed' | transloco"
2671
+ [aside]="'' + view.values.length"
2672
+ [open]="true"
2673
+ >
2674
+ <dl class="grid grid-cols-[minmax(0,1fr)_auto] gap-x-4 gap-y-1">
2675
+ @for (item of view.values; track $index) {
2676
+ <dt class="min-w-0 break-words">
2677
+ <bdi>{{ item.label }}</bdi>
2678
+ </dt>
2679
+ <dd class="ms-0 text-end font-medium tabular-nums">
2680
+ <bdi>{{ item.value }}</bdi>
2681
+ </dd>
2682
+ }
2683
+ </dl>
2684
+ </mt-calculation-explanation-section>
2685
+ }
2686
+
2687
+ @for (table of view.records; track $index) {
2688
+ <mt-calculation-explanation-section
2689
+ [title]="prefix + '.contributingRecords' | transloco"
2690
+ [aside]="'' + table.rows.length"
2691
+ [open]="table.rows.length <= openRows"
2692
+ >
2693
+ <div class="overflow-x-auto">
2694
+ <table class="w-full tabular-nums">
2695
+ <thead>
2696
+ <tr class="text-xs text-surface-500 dark:text-surface-400">
2697
+ <th class="py-1 pe-3 text-start font-medium">
2698
+ {{ prefix + '.record' | transloco }}
2699
+ </th>
2700
+ @for (column of table.columns; track $index) {
2701
+ <th class="py-1 ps-3 text-end font-medium">
2702
+ {{ column }}
2703
+ </th>
2704
+ }
2705
+ </tr>
2706
+ </thead>
2707
+ <tbody>
2708
+ @for (row of table.rows; track $index; let n = $index) {
2709
+ <tr
2710
+ class="border-t border-surface-200 dark:border-surface-700"
2711
+ >
2712
+ <td class="py-1.5 pe-3 break-words">
2713
+ <ng-container
2714
+ [ngTemplateOutlet]="recordName"
2715
+ [ngTemplateOutletContext]="{ $implicit: row.ref, n }"
2716
+ />
2717
+ </td>
2718
+ @for (cell of row.cells; track $index) {
2719
+ <td class="py-1.5 ps-3 text-end">
2720
+ <bdi>{{ cell }}</bdi>
2721
+ </td>
2722
+ }
2723
+ </tr>
2724
+ }
2725
+ </tbody>
2726
+ </table>
2727
+ </div>
2728
+ </mt-calculation-explanation-section>
2729
+ }
2730
+
2731
+ @if (view.steps.length) {
2732
+ <mt-calculation-explanation-section
2733
+ [title]="prefix + '.steps' | transloco"
2734
+ [aside]="'' + view.steps.length"
2735
+ >
2736
+ <ul class="flex flex-col gap-1.5">
2737
+ @for (step of view.steps; track $index) {
2738
+ <li>
2739
+ <mt-calculation-explanation-equation
2740
+ [segments]="step.segments"
2741
+ [result]="step.result"
2742
+ />
2743
+ </li>
2744
+ }
2745
+ </ul>
2746
+ </mt-calculation-explanation-section>
2747
+ }
2748
+
2749
+ @if (view.statusRules.length) {
2750
+ <mt-calculation-explanation-section
2751
+ [title]="prefix + '.statusRules' | transloco"
2752
+ [aside]="'' + view.statusRules.length"
2753
+ [open]="true"
2754
+ >
2755
+ <!-- One row per rule, in the order they are checked; a row opens
2756
+ to the parts its condition required. -->
2757
+ <ol class="flex flex-col gap-1">
2758
+ @for (rule of view.statusRules; track rule.key) {
2759
+ <li>
2760
+ <details
2761
+ class="group/rule rounded-md"
2762
+ [class]="
2763
+ rule.verdict === 'selected'
2764
+ ? 'bg-primary-50 dark:bg-primary-950'
2765
+ : ''
2766
+ "
2767
+ >
2768
+ <summary
2769
+ class="flex cursor-pointer list-none items-center gap-2 rounded-md px-2 py-1.5 select-none hover:bg-surface-50 focus-visible:outline-2 focus-visible:outline-primary-500 dark:hover:bg-surface-800 [&::-webkit-details-marker]:hidden"
2770
+ >
2771
+ <mt-icon
2772
+ icon="arrow.chevron-right"
2773
+ size="xs"
2774
+ class="shrink-0 text-surface-400 transition-transform group-open/rule:rotate-90 rtl:rotate-180"
2775
+ />
2776
+ <span
2777
+ class="shrink-0 text-xs text-surface-500 tabular-nums dark:text-surface-400"
2778
+ >{{ rule.position }}.</span
2779
+ >
2780
+ <bdi class="min-w-0 flex-1 font-medium">{{
2781
+ rule.name
2782
+ }}</bdi>
2783
+ <span
2784
+ class="shrink-0 rounded-md px-1.5 py-0.5 text-xs"
2785
+ [class]="verdictClass[rule.verdict]"
2786
+ >
2787
+ {{ prefix + '.verdict.' + rule.verdict | transloco }}
2788
+ </span>
2789
+ </summary>
2790
+ <div class="px-2 pt-1 pb-2 ps-8">
2791
+ @if (rule.checks; as checks) {
2792
+ <mt-calculation-explanation-checks
2793
+ class="text-xs"
2794
+ [checks]="checks"
2795
+ />
2796
+ } @else if (rule.segments; as segments) {
2797
+ <mt-calculation-explanation-equation
2798
+ class="text-xs"
2799
+ [segments]="segments"
2800
+ />
2801
+ }
2802
+ </div>
2803
+ </details>
2804
+ </li>
2805
+ }
2806
+ </ol>
2807
+ </mt-calculation-explanation-section>
2808
+ }
2809
+
2810
+ @for (detail of view.schedule; track $index) {
2811
+ <section class="flex flex-col gap-2">
2812
+ <!-- A rollup that is the whole formula already heads the summary. -->
2813
+ @if (!detail.standalone) {
2814
+ <div class="flex items-baseline justify-between gap-3">
2815
+ <h3 class="font-semibold text-surface-900 dark:text-surface-0">
2816
+ {{ detail.title }}
2817
+ </h3>
2818
+ <bdi class="font-semibold tabular-nums">{{ detail.result }}</bdi>
2819
+ </div>
2820
+ }
2821
+ @if (detail.meaning) {
2822
+ <p class="text-surface-500 dark:text-surface-400">
2823
+ {{ detail.meaning }}
2824
+ </p>
2825
+ }
2826
+ <p>
2827
+ @if (detail.method) {
2828
+ {{ detail.method }} ·
2829
+ }
2830
+ <span class="font-medium">{{ detail.counted }}</span>
2831
+ </p>
2832
+ @for (note of detail.notes; track $index) {
2833
+ <div
2834
+ class="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-amber-700"
2835
+ >
2836
+ {{ note }}
2837
+ </div>
2838
+ }
2839
+ @if (detail.contributors.length) {
2840
+ <mt-calculation-explanation-section
2841
+ [title]="scheduleKeys + '.items' | transloco"
2842
+ [aside]="'' + detail.contributors.length"
2843
+ [open]="detail.contributors.length <= openRows"
2844
+ >
2845
+ <div class="overflow-x-auto">
2846
+ <table class="w-full tabular-nums">
2847
+ <thead>
2848
+ <tr class="text-xs text-surface-500 dark:text-surface-400">
2849
+ <th class="py-1 pe-3 text-start font-medium">
2850
+ {{ scheduleKeys + '.item' | transloco }}
2851
+ </th>
2852
+ <th class="px-3 py-1 text-end font-medium">
2853
+ {{
2854
+ scheduleKeys +
2855
+ (detail.kind === 'planned'
2856
+ ? '.expected'
2857
+ : '.progress') | transloco
2858
+ }}
2859
+ </th>
2860
+ <th class="px-3 py-1 text-end font-medium">
2861
+ {{ detail.weightLabel }}
2862
+ </th>
2863
+ <th class="py-1 ps-3 text-start font-medium">
2864
+ {{ scheduleKeys + '.included' | transloco }}
2865
+ </th>
2866
+ </tr>
2867
+ </thead>
2868
+ <tbody>
2869
+ @for (
2870
+ row of detail.contributors;
2871
+ track $index;
2872
+ let n = $index
2873
+ ) {
2874
+ <tr
2875
+ class="border-t border-surface-200 align-top dark:border-surface-700"
2876
+ >
2877
+ <td class="py-1.5 pe-3">
2878
+ <div class="flex flex-col gap-0.5">
2879
+ <ng-container
2880
+ [ngTemplateOutlet]="recordName"
2881
+ [ngTemplateOutletContext]="{
2882
+ $implicit: row.ref,
2883
+ n,
2884
+ }"
2885
+ />
2886
+ @if (row.type || row.planned) {
2887
+ <span
2888
+ class="text-xs text-surface-500 dark:text-surface-400"
2889
+ >
2890
+ {{ row.type }}
2891
+ @if (row.planned; as planned) {
2892
+ @if (row.type) {
2893
+ ·
2894
+ }
2895
+ <bdi>{{ planned.dates }}</bdi>
2896
+ }
2897
+ </span>
2898
+ }
2899
+ </div>
2900
+ </td>
2901
+ <td class="px-3 py-1.5 text-end">
2902
+ <bdi>{{ row.progress }}</bdi>
2903
+ @if (row.planned?.time; as time) {
2904
+ <div
2905
+ class="text-xs text-surface-500 dark:text-surface-400"
2906
+ >
2907
+ <bdi>{{ time }}</bdi>
2908
+ </div>
2909
+ }
2910
+ </td>
2911
+ <td class="px-3 py-1.5 text-end">
2912
+ <bdi>{{ row.weight }}</bdi>
2913
+ </td>
2914
+ <td class="py-1.5 ps-3">
2915
+ @if (row.counted && !row.reason) {
2916
+ <mt-icon
2917
+ icon="general.check"
2918
+ size="xs"
2919
+ class="text-green-700"
2920
+ [attr.aria-label]="prefix + '.yes' | transloco"
2921
+ />
2922
+ } @else {
2923
+ <span
2924
+ class="text-xs"
2925
+ [class]="
2926
+ row.counted
2927
+ ? 'text-surface-600 dark:text-surface-300'
2928
+ : 'text-surface-500 dark:text-surface-400'
2929
+ "
2930
+ >{{ row.reason }}</span
2931
+ >
2932
+ }
2933
+ </td>
2934
+ </tr>
2935
+ }
2936
+ </tbody>
2937
+ </table>
2938
+ </div>
2939
+ </mt-calculation-explanation-section>
2940
+ }
2941
+ </section>
2942
+ }
2943
+
2944
+ @if (view.codeBlocks.length) {
2945
+ <mt-calculation-explanation-section
2946
+ [title]="prefix + '.codeBlocks' | transloco"
2947
+ [aside]="'' + view.codeBlocks.length"
2948
+ [open]="true"
2949
+ >
2950
+ <ol class="flex flex-col gap-1">
2951
+ @for (block of view.codeBlocks; track $index) {
2952
+ <li class="flex items-baseline justify-between gap-3">
2953
+ <span class="text-surface-500 dark:text-surface-400">{{
2954
+ block.type
2955
+ }}</span>
2956
+ <span class="flex flex-col items-end">
2957
+ <bdi class="font-medium">{{ block.value }}</bdi>
2958
+ @if (block.raw !== null) {
2959
+ <span
2960
+ class="text-xs text-surface-500 dark:text-surface-400"
2961
+ >
2962
+ {{
2963
+ prefix + '.codeBlockBefore'
2964
+ | transloco: { value: block.raw }
2965
+ }}
2966
+ </span>
2967
+ }
2968
+ </span>
2969
+ </li>
2970
+ }
2971
+ </ol>
2972
+ </mt-calculation-explanation-section>
2973
+ }
2974
+
2975
+ @for (fact of view.facts; track $index) {
2976
+ <mt-calculation-explanation-section
2977
+ [title]="fact.label"
2978
+ [open]="view.facts.length === 1"
2979
+ >
2980
+ <ng-container
2981
+ [ngTemplateOutlet]="dataTpl"
2982
+ [ngTemplateOutletContext]="{ $implicit: fact.data }"
2983
+ />
2984
+ </mt-calculation-explanation-section>
2985
+ }
2986
+ </div>
2987
+ `, isInline: true, dependencies: [{ kind: "component", type: CalculationExplanationChecks, selector: "mt-calculation-explanation-checks", inputs: ["checks"] }, { kind: "component", type: CalculationExplanationEquation, selector: "mt-calculation-explanation-equation", inputs: ["segments", "result", "resultOperator"] }, { kind: "component", type: CalculationExplanationSection, selector: "mt-calculation-explanation-section", inputs: ["title", "aside", "open"] }, { kind: "component", type: Icon, selector: "mt-icon", inputs: ["icon"] }, { kind: "directive", type: NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "pipe", type: TranslocoPipe, name: "transloco" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
2988
+ }
2989
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: CalculationExplanationDetails, decorators: [{
2990
+ type: Component,
2991
+ args: [{
2992
+ selector: 'mt-calculation-explanation-details',
2993
+ changeDetection: ChangeDetectionStrategy.OnPush,
2994
+ imports: [
2995
+ CalculationExplanationChecks,
2996
+ CalculationExplanationEquation,
2997
+ CalculationExplanationSection,
2998
+ Icon,
2999
+ NgTemplateOutlet,
3000
+ TranslocoPipe,
3001
+ ],
3002
+ template: `
3003
+ <!-- A record by its title, a placeholder while titles are read, or a
3004
+ generic label; never its id. -->
3005
+ <ng-template #recordName let-ref let-n="n">
3006
+ @if (recordNames() === null) {
3007
+ <span
3008
+ class="inline-block h-3 w-24 animate-pulse rounded-md bg-surface-100 align-middle dark:bg-surface-800"
3009
+ aria-busy="true"
3010
+ ></span>
3011
+ } @else {
3012
+ <bdi class="break-words">{{ nameOf(ref, n) }}</bdi>
3013
+ }
3014
+ </ng-template>
3015
+
3016
+ <ng-template #dataTpl let-data>
3017
+ @switch (data.kind) {
3018
+ @case ('text') {
3019
+ <bdi class="break-words">{{ data.text }}</bdi>
3020
+ }
3021
+ @case ('list') {
3022
+ <bdi class="break-words">{{ data.items.join(', ') }}</bdi>
3023
+ }
3024
+ @case ('table') {
3025
+ <div class="overflow-x-auto">
3026
+ <table class="w-full text-xs tabular-nums">
3027
+ <thead>
3028
+ <tr class="text-surface-500 dark:text-surface-400">
3029
+ @for (column of data.columns; track $index) {
3030
+ <th class="px-2 py-1 text-start font-medium">
3031
+ {{ column }}
3032
+ </th>
3033
+ }
3034
+ </tr>
3035
+ </thead>
3036
+ <tbody>
3037
+ @for (row of data.rows; track $index) {
3038
+ <tr
3039
+ class="border-t border-surface-200 dark:border-surface-700"
3040
+ >
3041
+ @for (cell of row; track $index) {
3042
+ <td class="px-2 py-1 align-top break-words">
3043
+ <bdi>{{ cell }}</bdi>
3044
+ </td>
3045
+ }
3046
+ </tr>
3047
+ }
3048
+ </tbody>
3049
+ </table>
3050
+ @if (data.more > 0) {
3051
+ <p class="mt-1 text-surface-500 dark:text-surface-400">
3052
+ {{ prefix + '.moreRows' | transloco: { count: data.more } }}
3053
+ </p>
3054
+ }
3055
+ </div>
3056
+ }
3057
+ @case ('fields') {
3058
+ <dl
3059
+ class="grid grid-cols-[minmax(0,auto)_minmax(0,1fr)] gap-x-3 gap-y-1"
3060
+ >
3061
+ @for (field of data.fields; track $index) {
3062
+ <dt class="text-surface-500 dark:text-surface-400">
3063
+ {{ field.label }}
3064
+ </dt>
3065
+ <dd class="ms-0 min-w-0">
3066
+ <ng-container
3067
+ [ngTemplateOutlet]="dataTpl"
3068
+ [ngTemplateOutletContext]="{ $implicit: field.data }"
3069
+ />
3070
+ </dd>
3071
+ }
3072
+ </dl>
3073
+ }
3074
+ }
3075
+ </ng-template>
3076
+
3077
+ @let view = details();
3078
+ <div
3079
+ class="flex flex-col gap-3 text-sm text-surface-700 dark:text-surface-200"
3080
+ >
3081
+ @if (view.description) {
3082
+ <p>{{ view.description }}</p>
3083
+ }
3084
+
3085
+ @if (view.values.length) {
3086
+ <mt-calculation-explanation-section
3087
+ [title]="prefix + '.valuesUsed' | transloco"
3088
+ [aside]="'' + view.values.length"
3089
+ [open]="true"
3090
+ >
3091
+ <dl class="grid grid-cols-[minmax(0,1fr)_auto] gap-x-4 gap-y-1">
3092
+ @for (item of view.values; track $index) {
3093
+ <dt class="min-w-0 break-words">
3094
+ <bdi>{{ item.label }}</bdi>
3095
+ </dt>
3096
+ <dd class="ms-0 text-end font-medium tabular-nums">
3097
+ <bdi>{{ item.value }}</bdi>
3098
+ </dd>
3099
+ }
3100
+ </dl>
3101
+ </mt-calculation-explanation-section>
3102
+ }
3103
+
3104
+ @for (table of view.records; track $index) {
3105
+ <mt-calculation-explanation-section
3106
+ [title]="prefix + '.contributingRecords' | transloco"
3107
+ [aside]="'' + table.rows.length"
3108
+ [open]="table.rows.length <= openRows"
3109
+ >
3110
+ <div class="overflow-x-auto">
3111
+ <table class="w-full tabular-nums">
3112
+ <thead>
3113
+ <tr class="text-xs text-surface-500 dark:text-surface-400">
3114
+ <th class="py-1 pe-3 text-start font-medium">
3115
+ {{ prefix + '.record' | transloco }}
3116
+ </th>
3117
+ @for (column of table.columns; track $index) {
3118
+ <th class="py-1 ps-3 text-end font-medium">
3119
+ {{ column }}
3120
+ </th>
3121
+ }
3122
+ </tr>
3123
+ </thead>
3124
+ <tbody>
3125
+ @for (row of table.rows; track $index; let n = $index) {
3126
+ <tr
3127
+ class="border-t border-surface-200 dark:border-surface-700"
3128
+ >
3129
+ <td class="py-1.5 pe-3 break-words">
3130
+ <ng-container
3131
+ [ngTemplateOutlet]="recordName"
3132
+ [ngTemplateOutletContext]="{ $implicit: row.ref, n }"
3133
+ />
3134
+ </td>
3135
+ @for (cell of row.cells; track $index) {
3136
+ <td class="py-1.5 ps-3 text-end">
3137
+ <bdi>{{ cell }}</bdi>
3138
+ </td>
3139
+ }
3140
+ </tr>
3141
+ }
3142
+ </tbody>
3143
+ </table>
3144
+ </div>
3145
+ </mt-calculation-explanation-section>
3146
+ }
3147
+
3148
+ @if (view.steps.length) {
3149
+ <mt-calculation-explanation-section
3150
+ [title]="prefix + '.steps' | transloco"
3151
+ [aside]="'' + view.steps.length"
3152
+ >
3153
+ <ul class="flex flex-col gap-1.5">
3154
+ @for (step of view.steps; track $index) {
3155
+ <li>
3156
+ <mt-calculation-explanation-equation
3157
+ [segments]="step.segments"
3158
+ [result]="step.result"
3159
+ />
3160
+ </li>
3161
+ }
3162
+ </ul>
3163
+ </mt-calculation-explanation-section>
3164
+ }
3165
+
3166
+ @if (view.statusRules.length) {
3167
+ <mt-calculation-explanation-section
3168
+ [title]="prefix + '.statusRules' | transloco"
3169
+ [aside]="'' + view.statusRules.length"
3170
+ [open]="true"
3171
+ >
3172
+ <!-- One row per rule, in the order they are checked; a row opens
3173
+ to the parts its condition required. -->
3174
+ <ol class="flex flex-col gap-1">
3175
+ @for (rule of view.statusRules; track rule.key) {
3176
+ <li>
3177
+ <details
3178
+ class="group/rule rounded-md"
3179
+ [class]="
3180
+ rule.verdict === 'selected'
3181
+ ? 'bg-primary-50 dark:bg-primary-950'
3182
+ : ''
3183
+ "
3184
+ >
3185
+ <summary
3186
+ class="flex cursor-pointer list-none items-center gap-2 rounded-md px-2 py-1.5 select-none hover:bg-surface-50 focus-visible:outline-2 focus-visible:outline-primary-500 dark:hover:bg-surface-800 [&::-webkit-details-marker]:hidden"
3187
+ >
3188
+ <mt-icon
3189
+ icon="arrow.chevron-right"
3190
+ size="xs"
3191
+ class="shrink-0 text-surface-400 transition-transform group-open/rule:rotate-90 rtl:rotate-180"
3192
+ />
3193
+ <span
3194
+ class="shrink-0 text-xs text-surface-500 tabular-nums dark:text-surface-400"
3195
+ >{{ rule.position }}.</span
3196
+ >
3197
+ <bdi class="min-w-0 flex-1 font-medium">{{
3198
+ rule.name
3199
+ }}</bdi>
3200
+ <span
3201
+ class="shrink-0 rounded-md px-1.5 py-0.5 text-xs"
3202
+ [class]="verdictClass[rule.verdict]"
3203
+ >
3204
+ {{ prefix + '.verdict.' + rule.verdict | transloco }}
3205
+ </span>
3206
+ </summary>
3207
+ <div class="px-2 pt-1 pb-2 ps-8">
3208
+ @if (rule.checks; as checks) {
3209
+ <mt-calculation-explanation-checks
3210
+ class="text-xs"
3211
+ [checks]="checks"
3212
+ />
3213
+ } @else if (rule.segments; as segments) {
3214
+ <mt-calculation-explanation-equation
3215
+ class="text-xs"
3216
+ [segments]="segments"
3217
+ />
3218
+ }
3219
+ </div>
3220
+ </details>
3221
+ </li>
3222
+ }
3223
+ </ol>
3224
+ </mt-calculation-explanation-section>
3225
+ }
3226
+
3227
+ @for (detail of view.schedule; track $index) {
3228
+ <section class="flex flex-col gap-2">
3229
+ <!-- A rollup that is the whole formula already heads the summary. -->
3230
+ @if (!detail.standalone) {
3231
+ <div class="flex items-baseline justify-between gap-3">
3232
+ <h3 class="font-semibold text-surface-900 dark:text-surface-0">
3233
+ {{ detail.title }}
3234
+ </h3>
3235
+ <bdi class="font-semibold tabular-nums">{{ detail.result }}</bdi>
3236
+ </div>
3237
+ }
3238
+ @if (detail.meaning) {
3239
+ <p class="text-surface-500 dark:text-surface-400">
3240
+ {{ detail.meaning }}
3241
+ </p>
3242
+ }
3243
+ <p>
3244
+ @if (detail.method) {
3245
+ {{ detail.method }} ·
3246
+ }
3247
+ <span class="font-medium">{{ detail.counted }}</span>
3248
+ </p>
3249
+ @for (note of detail.notes; track $index) {
3250
+ <div
3251
+ class="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-amber-700"
3252
+ >
3253
+ {{ note }}
3254
+ </div>
3255
+ }
3256
+ @if (detail.contributors.length) {
3257
+ <mt-calculation-explanation-section
3258
+ [title]="scheduleKeys + '.items' | transloco"
3259
+ [aside]="'' + detail.contributors.length"
3260
+ [open]="detail.contributors.length <= openRows"
3261
+ >
3262
+ <div class="overflow-x-auto">
3263
+ <table class="w-full tabular-nums">
3264
+ <thead>
3265
+ <tr class="text-xs text-surface-500 dark:text-surface-400">
3266
+ <th class="py-1 pe-3 text-start font-medium">
3267
+ {{ scheduleKeys + '.item' | transloco }}
3268
+ </th>
3269
+ <th class="px-3 py-1 text-end font-medium">
3270
+ {{
3271
+ scheduleKeys +
3272
+ (detail.kind === 'planned'
3273
+ ? '.expected'
3274
+ : '.progress') | transloco
3275
+ }}
3276
+ </th>
3277
+ <th class="px-3 py-1 text-end font-medium">
3278
+ {{ detail.weightLabel }}
3279
+ </th>
3280
+ <th class="py-1 ps-3 text-start font-medium">
3281
+ {{ scheduleKeys + '.included' | transloco }}
3282
+ </th>
3283
+ </tr>
3284
+ </thead>
3285
+ <tbody>
3286
+ @for (
3287
+ row of detail.contributors;
3288
+ track $index;
3289
+ let n = $index
3290
+ ) {
3291
+ <tr
3292
+ class="border-t border-surface-200 align-top dark:border-surface-700"
3293
+ >
3294
+ <td class="py-1.5 pe-3">
3295
+ <div class="flex flex-col gap-0.5">
3296
+ <ng-container
3297
+ [ngTemplateOutlet]="recordName"
3298
+ [ngTemplateOutletContext]="{
3299
+ $implicit: row.ref,
3300
+ n,
3301
+ }"
3302
+ />
3303
+ @if (row.type || row.planned) {
3304
+ <span
3305
+ class="text-xs text-surface-500 dark:text-surface-400"
3306
+ >
3307
+ {{ row.type }}
3308
+ @if (row.planned; as planned) {
3309
+ @if (row.type) {
3310
+ ·
3311
+ }
3312
+ <bdi>{{ planned.dates }}</bdi>
3313
+ }
3314
+ </span>
3315
+ }
3316
+ </div>
3317
+ </td>
3318
+ <td class="px-3 py-1.5 text-end">
3319
+ <bdi>{{ row.progress }}</bdi>
3320
+ @if (row.planned?.time; as time) {
3321
+ <div
3322
+ class="text-xs text-surface-500 dark:text-surface-400"
3323
+ >
3324
+ <bdi>{{ time }}</bdi>
3325
+ </div>
3326
+ }
3327
+ </td>
3328
+ <td class="px-3 py-1.5 text-end">
3329
+ <bdi>{{ row.weight }}</bdi>
3330
+ </td>
3331
+ <td class="py-1.5 ps-3">
3332
+ @if (row.counted && !row.reason) {
3333
+ <mt-icon
3334
+ icon="general.check"
3335
+ size="xs"
3336
+ class="text-green-700"
3337
+ [attr.aria-label]="prefix + '.yes' | transloco"
3338
+ />
3339
+ } @else {
3340
+ <span
3341
+ class="text-xs"
3342
+ [class]="
3343
+ row.counted
3344
+ ? 'text-surface-600 dark:text-surface-300'
3345
+ : 'text-surface-500 dark:text-surface-400'
3346
+ "
3347
+ >{{ row.reason }}</span
3348
+ >
3349
+ }
3350
+ </td>
3351
+ </tr>
3352
+ }
3353
+ </tbody>
3354
+ </table>
3355
+ </div>
3356
+ </mt-calculation-explanation-section>
3357
+ }
3358
+ </section>
3359
+ }
3360
+
3361
+ @if (view.codeBlocks.length) {
3362
+ <mt-calculation-explanation-section
3363
+ [title]="prefix + '.codeBlocks' | transloco"
3364
+ [aside]="'' + view.codeBlocks.length"
3365
+ [open]="true"
3366
+ >
3367
+ <ol class="flex flex-col gap-1">
3368
+ @for (block of view.codeBlocks; track $index) {
3369
+ <li class="flex items-baseline justify-between gap-3">
3370
+ <span class="text-surface-500 dark:text-surface-400">{{
3371
+ block.type
3372
+ }}</span>
3373
+ <span class="flex flex-col items-end">
3374
+ <bdi class="font-medium">{{ block.value }}</bdi>
3375
+ @if (block.raw !== null) {
3376
+ <span
3377
+ class="text-xs text-surface-500 dark:text-surface-400"
3378
+ >
3379
+ {{
3380
+ prefix + '.codeBlockBefore'
3381
+ | transloco: { value: block.raw }
3382
+ }}
3383
+ </span>
3384
+ }
3385
+ </span>
3386
+ </li>
3387
+ }
3388
+ </ol>
3389
+ </mt-calculation-explanation-section>
3390
+ }
3391
+
3392
+ @for (fact of view.facts; track $index) {
3393
+ <mt-calculation-explanation-section
3394
+ [title]="fact.label"
3395
+ [open]="view.facts.length === 1"
3396
+ >
3397
+ <ng-container
3398
+ [ngTemplateOutlet]="dataTpl"
3399
+ [ngTemplateOutletContext]="{ $implicit: fact.data }"
3400
+ />
3401
+ </mt-calculation-explanation-section>
3402
+ }
3403
+ </div>
3404
+ `,
3405
+ }]
3406
+ }], propDecorators: { details: [{ type: i0.Input, args: [{ isSignal: true, alias: "details", required: true }] }], recordNames: [{ type: i0.Input, args: [{ isSignal: true, alias: "recordNames", required: false }] }], fallbackLabel: [{ type: i0.Input, args: [{ isSignal: true, alias: "fallbackLabel", required: false }] }] } });
3407
+
3408
+ /**
3409
+ * The full explanation of a calculated value, in a wide side panel opened from
3410
+ * its tooltip: the result and reason, then the values, contributing records by
3411
+ * name, status rules, schedule rollups and their calendar.
3412
+ *
3413
+ * Created through `ModalService`, so it is built with the root injector and
3414
+ * its inputs arrive through `inputValues`: it takes the explanation the
3415
+ * tooltip already read and only reads the names of the records it shows.
3416
+ */
3417
+ class CalculationExplanationPanel {
3418
+ target = input.required(...(ngDevMode ? [{ debugName: "target" }] : /* istanbul ignore next */ []));
3419
+ explanation = input.required(...(ngDevMode ? [{ debugName: "explanation" }] : /* istanbul ignore next */ []));
3420
+ names = inject(CalculationRecordNames);
3421
+ transloco = inject(TranslocoService);
3422
+ destroyRef = inject(DestroyRef);
3423
+ explanationContext = injectExplanationContext(this.target);
3424
+ prefix = CALCULATION_EXPLANATION_KEYS;
3425
+ /** Record titles, `null` while they are being read. */
3426
+ recordNames = signal(null, ...(ngDevMode ? [{ debugName: "recordNames" }] : /* istanbul ignore next */ []));
3427
+ view = computed(() => buildCalculationExplanationView(this.explanation(), this.target(), this.explanationContext.context(), this.explanationContext.statusNames()), ...(ngDevMode ? [{ debugName: "view" }] : /* istanbul ignore next */ []));
3428
+ fallbackLabel = (position) => this.transloco.translate(`${CALCULATION_EXPLANATION_KEYS}.recordFallback`, {
3429
+ n: position,
3430
+ });
3431
+ // Names only: the explanation itself is never read again here.
3432
+ ngOnInit() {
3433
+ const refs = detailRecordRefs(this.view().details);
3434
+ if (!refs.length) {
3435
+ this.recordNames.set({});
3436
+ return;
3437
+ }
3438
+ const subscription = this.names
3439
+ .read(this.target().source, refs)
3440
+ .subscribe((names) => this.recordNames.set(names));
3441
+ this.destroyRef.onDestroy(() => subscription.unsubscribe());
3442
+ }
3443
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: CalculationExplanationPanel, deps: [], target: i0.ɵɵFactoryTarget.Component });
3444
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: CalculationExplanationPanel, isStandalone: true, selector: "mt-calculation-explanation-panel", inputs: { target: { classPropertyName: "target", publicName: "target", isSignal: true, isRequired: true, transformFunction: null }, explanation: { classPropertyName: "explanation", publicName: "explanation", isSignal: true, isRequired: true, transformFunction: null } }, host: { classAttribute: "block h-full" }, providers: [MTDateFormatPipe], ngImport: i0, template: `
3445
+ @let v = view();
3446
+ <div class="flex h-full flex-col gap-4 overflow-y-auto p-5 text-sm">
3447
+ <!-- One line: when, and on what basis only when it is not the saved
3448
+ value (the drawer's title already names the value). -->
3449
+ <span class="text-xs text-surface-500 dark:text-surface-400">
3450
+ @if (v.basis === 'currentCalculation') {
3451
+ {{ prefix + '.currentTitle' | transloco }} ·
3452
+ {{ prefix + '.currentCalculatedAt' | transloco }}
3453
+ } @else {
3454
+ {{ prefix + '.calculatedAt' | transloco }}
3455
+ }
3456
+ <bdi class="tabular-nums">{{
3457
+ v.calculatedAt | mtDateFormat: 'dateTime'
3458
+ }}</bdi>
3459
+ </span>
3460
+ <mt-calculation-explanation-summary [view]="v" />
3461
+ <mt-calculation-explanation-details
3462
+ [details]="v.details"
3463
+ [recordNames]="recordNames()"
3464
+ [fallbackLabel]="fallbackLabel"
3465
+ />
3466
+ </div>
3467
+ `, isInline: true, dependencies: [{ kind: "component", type: CalculationExplanationSummary, selector: "mt-calculation-explanation-summary", inputs: ["view"] }, { kind: "component", type: CalculationExplanationDetails, selector: "mt-calculation-explanation-details", inputs: ["details", "recordNames", "fallbackLabel"] }, { kind: "pipe", type: TranslocoPipe, name: "transloco" }, { kind: "pipe", type: MTDateFormatPipe, name: "mtDateFormat" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
3468
+ }
3469
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: CalculationExplanationPanel, decorators: [{
3470
+ type: Component,
3471
+ args: [{
3472
+ selector: 'mt-calculation-explanation-panel',
3473
+ changeDetection: ChangeDetectionStrategy.OnPush,
3474
+ imports: [
3475
+ TranslocoPipe,
3476
+ MTDateFormatPipe,
3477
+ CalculationExplanationSummary,
3478
+ CalculationExplanationDetails,
3479
+ ],
3480
+ providers: [MTDateFormatPipe],
3481
+ // `h-full` lets the drawer's content area scroll this panel; see
3482
+ // `EntityListDrawer`. The drawer pads only its header (`px-5`): content
3483
+ // that owns its scroll pads itself to line up with it.
3484
+ host: { class: 'block h-full' },
3485
+ template: `
3486
+ @let v = view();
3487
+ <div class="flex h-full flex-col gap-4 overflow-y-auto p-5 text-sm">
3488
+ <!-- One line: when, and on what basis only when it is not the saved
3489
+ value (the drawer's title already names the value). -->
3490
+ <span class="text-xs text-surface-500 dark:text-surface-400">
3491
+ @if (v.basis === 'currentCalculation') {
3492
+ {{ prefix + '.currentTitle' | transloco }} ·
3493
+ {{ prefix + '.currentCalculatedAt' | transloco }}
3494
+ } @else {
3495
+ {{ prefix + '.calculatedAt' | transloco }}
3496
+ }
3497
+ <bdi class="tabular-nums">{{
3498
+ v.calculatedAt | mtDateFormat: 'dateTime'
3499
+ }}</bdi>
3500
+ </span>
3501
+ <mt-calculation-explanation-summary [view]="v" />
3502
+ <mt-calculation-explanation-details
3503
+ [details]="v.details"
3504
+ [recordNames]="recordNames()"
3505
+ [fallbackLabel]="fallbackLabel"
3506
+ />
3507
+ </div>
3508
+ `,
3509
+ }]
3510
+ }], propDecorators: { target: [{ type: i0.Input, args: [{ isSignal: true, alias: "target", required: true }] }], explanation: [{ type: i0.Input, args: [{ isSignal: true, alias: "explanation", required: true }] }] } });
3511
+
3512
+ const KEY_PREFIX = CALCULATION_EXPLANATION_KEYS;
3513
+ /** Unavailable outcomes with their own message; anything else is generic. */
3514
+ const UNAVAILABLE_KEYS = {
3515
+ notCaptured: `${KEY_PREFIX}.notCaptured`,
3516
+ unsupported: `${KEY_PREFIX}.unsupported`,
3517
+ limitExceeded: `${KEY_PREFIX}.limitExceeded`,
3518
+ restricted: `${KEY_PREFIX}.restricted`,
3519
+ valueChanged: `${KEY_PREFIX}.valueChanged`,
3520
+ notCalculated: `${KEY_PREFIX}.notCalculated`,
3521
+ };
3522
+ const PROVIDERS = new Set([
3523
+ 'formula',
3524
+ 'status',
3525
+ 'nativeMethod',
3526
+ 'codeBuilder',
3527
+ 'schedule',
3528
+ ]);
3529
+ const BASES = new Set(['savedCalculation', 'currentCalculation']);
3530
+ /**
3531
+ * How a calculated value was calculated, in short: the result with its
3532
+ * business reason (`Remaining = Budget − Spent`, then the values), when it was
3533
+ * calculated, and a way into the full details panel. Fetched each time it
3534
+ * opens; reading it never recalculates anything, and nothing here is
3535
+ * recalculated either.
3536
+ */
3537
+ class EntityCalculationExplanation {
3538
+ api = inject(CalculationExplanationApi);
3539
+ modal = inject(ModalService);
3540
+ refresher = inject(EntityCalculationRefresher, {
3541
+ optional: true,
3542
+ });
3543
+ target = input.required(...(ngDevMode ? [{ debugName: "target" }] : /* istanbul ignore next */ []));
3544
+ /** The details panel opened; the host closes the tooltip under it. */
3545
+ detailsOpened = output();
3546
+ explanationContext = injectExplanationContext(this.target);
3547
+ prefix = KEY_PREFIX;
3548
+ state = signal({ kind: 'loading' }, ...(ngDevMode ? [{ debugName: "state" }] : /* istanbul ignore next */ []));
3549
+ available = computed(() => {
3550
+ const state = this.state();
3551
+ return state.kind === 'available' ? state : null;
3552
+ }, ...(ngDevMode ? [{ debugName: "available" }] : /* istanbul ignore next */ []));
3553
+ unavailableKey = computed(() => {
3554
+ const state = this.state();
3555
+ return state.kind === 'unavailable' ? state.messageKey : null;
3556
+ }, ...(ngDevMode ? [{ debugName: "unavailableKey" }] : /* istanbul ignore next */ []));
3557
+ view = computed(() => {
3558
+ const state = this.available();
3559
+ return state
3560
+ ? buildCalculationExplanationView(state, this.target(), this.explanationContext.context(), this.explanationContext.statusNames())
3561
+ : null;
3562
+ }, ...(ngDevMode ? [{ debugName: "view" }] : /* istanbul ignore next */ []));
3563
+ request;
3564
+ constructor() {
3565
+ inject(DestroyRef).onDestroy(() => this.request?.unsubscribe());
3566
+ }
3567
+ // Created when the popover opens and destroyed when it closes: one read per
3568
+ // open, never re-read when the value it explains is refreshed underneath.
3569
+ ngOnInit() {
3570
+ this.load(false);
3571
+ }
3572
+ openDetails() {
3573
+ const state = this.available();
3574
+ if (!state) {
3575
+ return;
3576
+ }
3577
+ const { kind: _kind, ...explanation } = state;
3578
+ this.modal.openModal(CalculationExplanationPanel, 'drawer', {
3579
+ header: this.target().label,
3580
+ position: 'end',
3581
+ // Contributor tables need the width a tooltip does not have.
3582
+ styleClass: '!w-[48rem] max-w-[96vw]',
3583
+ dismissableMask: true,
3584
+ inputValues: {
3585
+ target: this.target(),
3586
+ explanation,
3587
+ },
3588
+ });
3589
+ this.detailsOpened.emit();
3590
+ }
3591
+ load(retried) {
3592
+ const target = this.target();
3593
+ this.request?.unsubscribe();
3594
+ this.request = this.api.read(target.source, target.propertyKey).subscribe({
3595
+ next: (response) => this.apply(response, retried),
3596
+ error: () => this.state.set({ kind: 'failed' }),
3597
+ });
3598
+ }
3599
+ apply(response, retried) {
3600
+ // The value was saved again while the explanation was read: show the new
3601
+ // value (a read, never a recalculation), then explain that one.
3602
+ if (response.status === 'valueChanged' && !retried) {
3603
+ this.refresher?.refreshStaleCalculatedValue();
3604
+ this.load(true);
3605
+ return;
3606
+ }
3607
+ const explanation = response.explanation;
3608
+ const basis = response.basis ?? 'savedCalculation';
3609
+ if (response.status !== 'available' ||
3610
+ !explanation ||
3611
+ explanation.schemaVersion !== 1 ||
3612
+ !PROVIDERS.has(explanation.provider) ||
3613
+ !BASES.has(basis)) {
3614
+ this.state.set({
3615
+ kind: 'unavailable',
3616
+ messageKey: UNAVAILABLE_KEYS[response.status] ?? `${KEY_PREFIX}.unavailable`,
3617
+ });
3618
+ return;
3619
+ }
3620
+ // Only a saved calculation names the persisted value; a newer one than
3621
+ // the value on screen means the screen is behind.
3622
+ const stale = basis === 'savedCalculation' &&
3623
+ !isSameSavedValue(response.savedValue, this.target().displayedValue);
3624
+ if (stale) {
3625
+ this.refresher?.refreshStaleCalculatedValue();
3626
+ }
3627
+ this.state.set({
3628
+ kind: 'available',
3629
+ basis: basis,
3630
+ document: explanation,
3631
+ definitionChanged: response.definitionChanged,
3632
+ refreshed: stale && !!this.refresher,
3633
+ viewType: response.display?.viewType ?? this.target().viewType,
3634
+ });
3635
+ }
3636
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: EntityCalculationExplanation, deps: [], target: i0.ɵɵFactoryTarget.Component });
3637
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: EntityCalculationExplanation, isStandalone: true, selector: "mt-entity-calculation-explanation", inputs: { target: { classPropertyName: "target", publicName: "target", isSignal: true, isRequired: true, transformFunction: null } }, outputs: { detailsOpened: "detailsOpened" }, host: { classAttribute: "block" }, providers: [MTDateFormatPipe], ngImport: i0, template: `
3638
+ <!-- pb-1: the calculation time's text box is a pixel taller than its
3639
+ line; without room for it the box showed a scrollbar for 1px. -->
3640
+ <div
3641
+ class="flex max-h-[70vh] w-80 max-w-[calc(100vw-2rem)] flex-col gap-3 overflow-y-auto pb-1 text-sm"
3642
+ >
587
3643
  <div class="flex min-w-0 flex-col gap-0.5">
588
3644
  <span
589
3645
  class="truncate font-semibold text-surface-900 dark:text-surface-0"
@@ -591,7 +3647,12 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImpor
591
3647
  {{ target().label }}
592
3648
  </span>
593
3649
  <span class="text-xs text-surface-500 dark:text-surface-400">
594
- {{ prefix + '.title' | transloco }}
3650
+ {{
3651
+ prefix +
3652
+ (available()?.basis === 'currentCalculation'
3653
+ ? '.currentTitle'
3654
+ : '.title') | transloco
3655
+ }}
595
3656
  </span>
596
3657
  </div>
597
3658
 
@@ -607,37 +3668,125 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImpor
607
3668
  </div>
608
3669
  }
609
3670
  @case ('available') {
610
- @if (available(); as explanation) {
3671
+ @if (view(); as v) {
3672
+ <mt-calculation-explanation-summary [view]="v" />
611
3673
  <div
612
- class="rounded-md border border-surface-200 bg-surface-50 px-3 py-2 font-mono text-sm break-words text-surface-800 dark:border-surface-700 dark:bg-surface-800 dark:text-surface-100"
613
- dir="ltr"
3674
+ class="flex flex-wrap items-center justify-between gap-x-3 gap-y-1"
614
3675
  >
615
- @if (explanation.formulaWithValues) {
616
- <span>{{ explanation.formulaWithValues }}</span>
617
- <span class="px-1 text-surface-400">=</span>
3676
+ <span class="text-xs text-surface-500 dark:text-surface-400">
3677
+ {{
3678
+ prefix +
3679
+ (v.basis === 'currentCalculation'
3680
+ ? '.currentCalculatedAt'
3681
+ : '.calculatedAt') | transloco
3682
+ }}
3683
+ <bdi class="tabular-nums">{{
3684
+ v.calculatedAt | mtDateFormat: 'dateTime'
3685
+ }}</bdi>
3686
+ </span>
3687
+ @if (v.hasDetails) {
3688
+ <button
3689
+ type="button"
3690
+ class="rounded-md text-xs font-medium text-primary-700 hover:underline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary-500 dark:text-primary-300"
3691
+ aria-haspopup="dialog"
3692
+ (click)="openDetails()"
3693
+ >
3694
+ {{ prefix + '.showDetails' | transloco }}
3695
+ </button>
618
3696
  }
619
- <span class="font-semibold">{{ explanation.result }}</span>
620
3697
  </div>
621
- <div class="text-xs text-surface-500 dark:text-surface-400">
622
- {{ prefix + '.calculatedAt' | transloco }}
623
- <span dir="ltr" class="tabular-nums">{{
624
- explanation.calculatedAt | mtDateFormat: 'dateTime'
625
- }}</span>
3698
+ }
3699
+ }
3700
+ @case ('unavailable') {
3701
+ @if (unavailableKey(); as messageKey) {
3702
+ <div
3703
+ class="rounded-md border border-surface-200 bg-surface-50 px-3 py-2 text-surface-600 dark:border-surface-700 dark:bg-surface-800 dark:text-surface-300"
3704
+ >
3705
+ {{ messageKey | transloco }}
3706
+ </div>
3707
+ }
3708
+ }
3709
+ @case ('failed') {
3710
+ <div
3711
+ class="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-red-700"
3712
+ >
3713
+ {{ prefix + '.loadFailed' | transloco }}
3714
+ </div>
3715
+ }
3716
+ }
3717
+ </div>
3718
+ `, isInline: true, dependencies: [{ kind: "component", type: CalculationExplanationSummary, selector: "mt-calculation-explanation-summary", inputs: ["view"] }, { kind: "pipe", type: TranslocoPipe, name: "transloco" }, { kind: "pipe", type: MTDateFormatPipe, name: "mtDateFormat" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
3719
+ }
3720
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: EntityCalculationExplanation, decorators: [{
3721
+ type: Component,
3722
+ args: [{
3723
+ selector: 'mt-entity-calculation-explanation',
3724
+ changeDetection: ChangeDetectionStrategy.OnPush,
3725
+ imports: [TranslocoPipe, MTDateFormatPipe, CalculationExplanationSummary],
3726
+ providers: [MTDateFormatPipe],
3727
+ // A box, so its host can follow its size (the popover re-aligns on it).
3728
+ host: { class: 'block' },
3729
+ template: `
3730
+ <!-- pb-1: the calculation time's text box is a pixel taller than its
3731
+ line; without room for it the box showed a scrollbar for 1px. -->
3732
+ <div
3733
+ class="flex max-h-[70vh] w-80 max-w-[calc(100vw-2rem)] flex-col gap-3 overflow-y-auto pb-1 text-sm"
3734
+ >
3735
+ <div class="flex min-w-0 flex-col gap-0.5">
3736
+ <span
3737
+ class="truncate font-semibold text-surface-900 dark:text-surface-0"
3738
+ >
3739
+ {{ target().label }}
3740
+ </span>
3741
+ <span class="text-xs text-surface-500 dark:text-surface-400">
3742
+ {{
3743
+ prefix +
3744
+ (available()?.basis === 'currentCalculation'
3745
+ ? '.currentTitle'
3746
+ : '.title') | transloco
3747
+ }}
3748
+ </span>
3749
+ </div>
3750
+
3751
+ @switch (state().kind) {
3752
+ @case ('loading') {
3753
+ <div class="flex flex-col gap-2" aria-busy="true">
3754
+ <div
3755
+ class="h-10 animate-pulse rounded-md bg-surface-100 dark:bg-surface-800"
3756
+ ></div>
3757
+ <div
3758
+ class="h-3 w-1/2 animate-pulse rounded-md bg-surface-100 dark:bg-surface-800"
3759
+ ></div>
3760
+ </div>
3761
+ }
3762
+ @case ('available') {
3763
+ @if (view(); as v) {
3764
+ <mt-calculation-explanation-summary [view]="v" />
3765
+ <div
3766
+ class="flex flex-wrap items-center justify-between gap-x-3 gap-y-1"
3767
+ >
3768
+ <span class="text-xs text-surface-500 dark:text-surface-400">
3769
+ {{
3770
+ prefix +
3771
+ (v.basis === 'currentCalculation'
3772
+ ? '.currentCalculatedAt'
3773
+ : '.calculatedAt') | transloco
3774
+ }}
3775
+ <bdi class="tabular-nums">{{
3776
+ v.calculatedAt | mtDateFormat: 'dateTime'
3777
+ }}</bdi>
3778
+ </span>
3779
+ @if (v.hasDetails) {
3780
+ <button
3781
+ type="button"
3782
+ class="rounded-md text-xs font-medium text-primary-700 hover:underline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary-500 dark:text-primary-300"
3783
+ aria-haspopup="dialog"
3784
+ (click)="openDetails()"
3785
+ >
3786
+ {{ prefix + '.showDetails' | transloco }}
3787
+ </button>
3788
+ }
626
3789
  </div>
627
- @if (explanation.definitionChanged) {
628
- <div
629
- class="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-700"
630
- >
631
- {{ prefix + '.definitionChanged' | transloco }}
632
- </div>
633
- }
634
- @if (explanation.refreshed) {
635
- <div
636
- class="rounded-md border border-primary-200 bg-primary-50 px-3 py-2 text-xs text-primary-700"
637
- >
638
- {{ prefix + '.valueRefreshed' | transloco }}
639
- </div>
640
- }
641
3790
  }
642
3791
  }
643
3792
  @case ('unavailable') {
@@ -660,32 +3809,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImpor
660
3809
  </div>
661
3810
  `,
662
3811
  }]
663
- }], ctorParameters: () => [], propDecorators: { target: [{ type: i0.Input, args: [{ isSignal: true, alias: "target", required: true }] }] } });
664
- /**
665
- * Whether the saved value is the one on screen. Both are the persisted string,
666
- * but a number may be written either way (`40` and `40.0`), so numbers compare
667
- * as numbers.
668
- */
669
- function isSameSavedValue(saved, displayed) {
670
- const a = (saved ?? '').trim();
671
- const b = (displayed ?? '').trim();
672
- if (a === b) {
673
- return true;
674
- }
675
- if (a === '' || b === '') {
676
- return false;
677
- }
678
- const x = Number(a);
679
- const y = Number(b);
680
- return Number.isFinite(x) && Number.isFinite(y) && x === y;
681
- }
682
- /** A captured value as plain text. Never formatted or rounded here. */
683
- function formatExplanationValue(value) {
684
- if (value === null || value === undefined) {
685
- return '—';
686
- }
687
- return typeof value === 'object' ? JSON.stringify(value) : String(value);
688
- }
3812
+ }], ctorParameters: () => [], propDecorators: { target: [{ type: i0.Input, args: [{ isSignal: true, alias: "target", required: true }] }], detailsOpened: [{ type: i0.Output, args: ["detailsOpened"] }] } });
689
3813
 
690
3814
  const TOOLTIP_KEYS = {
691
3815
  idle: 'components.entitiesPreview.calculatedValue',
@@ -762,6 +3886,22 @@ class EntityCalculatedIndicator {
762
3886
  explanation = input(null, ...(ngDevMode ? [{ debugName: "explanation" }] : /* istanbul ignore next */ []));
763
3887
  popover = viewChild(Popover, ...(ngDevMode ? [{ debugName: "popover" }] : /* istanbul ignore next */ []));
764
3888
  opened = signal(false, ...(ngDevMode ? [{ debugName: "opened" }] : /* istanbul ignore next */ []));
3889
+ explanationElement = viewChild(EntityCalculationExplanation, { ...(ngDevMode ? { debugName: "explanationElement" } : /* istanbul ignore next */ {}), read: ElementRef });
3890
+ constructor() {
3891
+ // PrimeNG places the popover once, when it opens, measuring it before the
3892
+ // explanation inside has rendered or loaded. Too narrow then, it is never
3893
+ // flipped back from the edge, and in a right-to-left page it ran off the
3894
+ // screen. It is placed again whenever the explanation changes size.
3895
+ effect((onCleanup) => {
3896
+ const element = this.explanationElement()?.nativeElement;
3897
+ if (!element || typeof ResizeObserver === 'undefined') {
3898
+ return;
3899
+ }
3900
+ const observer = new ResizeObserver(() => this.popover()?.align());
3901
+ observer.observe(element);
3902
+ onCleanup(() => observer.disconnect());
3903
+ });
3904
+ }
765
3905
  pulsing = computed(() => !!this.status() && this.status() !== 'delayed', ...(ngDevMode ? [{ debugName: "pulsing" }] : /* istanbul ignore next */ []));
766
3906
  tooltipKey = computed(() => {
767
3907
  const status = this.status();
@@ -785,7 +3925,7 @@ class EntityCalculatedIndicator {
785
3925
  this.popover()?.toggle(event);
786
3926
  }
787
3927
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: EntityCalculatedIndicator, deps: [], target: i0.ɵɵFactoryTarget.Component });
788
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: EntityCalculatedIndicator, isStandalone: true, selector: "mt-entity-calculated-indicator", inputs: { status: { classPropertyName: "status", publicName: "status", isSignal: true, isRequired: false, transformFunction: null }, change: { classPropertyName: "change", publicName: "change", isSignal: true, isRequired: false, transformFunction: null }, explanation: { classPropertyName: "explanation", publicName: "explanation", isSignal: true, isRequired: false, transformFunction: null } }, host: { classAttribute: "inline-flex shrink-0" }, viewQueries: [{ propertyName: "popover", first: true, predicate: Popover, descendants: true, isSignal: true }], ngImport: i0, template: `
3928
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: EntityCalculatedIndicator, isStandalone: true, selector: "mt-entity-calculated-indicator", inputs: { status: { classPropertyName: "status", publicName: "status", isSignal: true, isRequired: false, transformFunction: null }, change: { classPropertyName: "change", publicName: "change", isSignal: true, isRequired: false, transformFunction: null }, explanation: { classPropertyName: "explanation", publicName: "explanation", isSignal: true, isRequired: false, transformFunction: null } }, host: { classAttribute: "inline-flex shrink-0" }, viewQueries: [{ propertyName: "popover", first: true, predicate: Popover, descendants: true, isSignal: true }, { propertyName: "explanationElement", first: true, predicate: EntityCalculationExplanation, descendants: true, read: ElementRef, isSignal: true }], ngImport: i0, template: `
789
3929
  <ng-template #mark>
790
3930
  @if (pulsing()) {
791
3931
  <span
@@ -822,7 +3962,10 @@ class EntityCalculatedIndicator {
822
3962
  (onHide)="opened.set(false)"
823
3963
  >
824
3964
  @if (opened()) {
825
- <mt-entity-calculation-explanation [target]="target" />
3965
+ <mt-entity-calculation-explanation
3966
+ [target]="target"
3967
+ (detailsOpened)="popover()?.hide()"
3968
+ />
826
3969
  }
827
3970
  </p-popover>
828
3971
  } @else {
@@ -841,7 +3984,7 @@ class EntityCalculatedIndicator {
841
3984
  <ng-container [ngTemplateOutlet]="mark" />
842
3985
  </span>
843
3986
  }
844
- `, isInline: true, dependencies: [{ kind: "component", type: EntityCalculatedGlyph, selector: "mt-entity-calculated-glyph" }, { kind: "component", type: EntityCalculationExplanation, selector: "mt-entity-calculation-explanation", inputs: ["target"] }, { kind: "directive", type: NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "component", type: Popover, selector: "p-popover", inputs: ["ariaLabel", "ariaLabelledBy", "dismissable", "style", "styleClass", "appendTo", "autoZIndex", "ariaCloseLabel", "baseZIndex", "focusOnShow", "showTransitionOptions", "hideTransitionOptions", "motionOptions"], outputs: ["onShow", "onHide"] }, { kind: "directive", type: Tooltip, selector: "[mtTooltip]" }, { kind: "pipe", type: TranslocoPipe, name: "transloco" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
3987
+ `, isInline: true, dependencies: [{ kind: "component", type: EntityCalculatedGlyph, selector: "mt-entity-calculated-glyph" }, { kind: "component", type: EntityCalculationExplanation, selector: "mt-entity-calculation-explanation", inputs: ["target"], outputs: ["detailsOpened"] }, { kind: "directive", type: NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "component", type: Popover, selector: "p-popover", inputs: ["ariaLabel", "ariaLabelledBy", "dismissable", "style", "styleClass", "appendTo", "autoZIndex", "ariaCloseLabel", "baseZIndex", "focusOnShow", "showTransitionOptions", "hideTransitionOptions", "motionOptions"], outputs: ["onShow", "onHide"] }, { kind: "directive", type: Tooltip, selector: "[mtTooltip]" }, { kind: "pipe", type: TranslocoPipe, name: "transloco" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
845
3988
  }
846
3989
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: EntityCalculatedIndicator, decorators: [{
847
3990
  type: Component,
@@ -893,7 +4036,10 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImpor
893
4036
  (onHide)="opened.set(false)"
894
4037
  >
895
4038
  @if (opened()) {
896
- <mt-entity-calculation-explanation [target]="target" />
4039
+ <mt-entity-calculation-explanation
4040
+ [target]="target"
4041
+ (detailsOpened)="popover()?.hide()"
4042
+ />
897
4043
  }
898
4044
  </p-popover>
899
4045
  } @else {
@@ -917,35 +4063,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImpor
917
4063
  class: 'inline-flex shrink-0',
918
4064
  },
919
4065
  }]
920
- }], propDecorators: { status: [{ type: i0.Input, args: [{ isSignal: true, alias: "status", required: false }] }], change: [{ type: i0.Input, args: [{ isSignal: true, alias: "change", required: false }] }], explanation: [{ type: i0.Input, args: [{ isSignal: true, alias: "explanation", required: false }] }], popover: [{ type: i0.ViewChild, args: [i0.forwardRef(() => Popover), { isSignal: true }] }] } });
921
-
922
- /**
923
- * One shared active-language signal per `TranslocoService`.
924
- *
925
- * `mt-entity-preview` renders once per property per record — a client-list card
926
- * grid mounts thousands of them — so a `toSignal(langChanges$)` inside each
927
- * instance would open thousands of subscriptions to the same Subject just to
928
- * read one global value. The language is global, so the signal is too: created
929
- * once, cached against the service, and shared by every entity that needs it.
930
- *
931
- * `manualCleanup` is deliberate. The cached signal outlives any single
932
- * component by design, and the service it hangs off is the root injector's —
933
- * tying its subscription to whichever entity happened to ask first would tear
934
- * it down the moment that entity scrolled out of view.
935
- */
936
- const langSignals = new WeakMap();
937
- function sharedActiveLang(transloco) {
938
- const cached = langSignals.get(transloco);
939
- if (cached) {
940
- return cached;
941
- }
942
- const lang = toSignal(transloco.langChanges$, {
943
- initialValue: transloco.getActiveLang(),
944
- manualCleanup: true,
945
- });
946
- langSignals.set(transloco, lang);
947
- return lang;
948
- }
4066
+ }], ctorParameters: () => [], propDecorators: { status: [{ type: i0.Input, args: [{ isSignal: true, alias: "status", required: false }] }], change: [{ type: i0.Input, args: [{ isSignal: true, alias: "change", required: false }] }], explanation: [{ type: i0.Input, args: [{ isSignal: true, alias: "explanation", required: false }] }], popover: [{ type: i0.ViewChild, args: [i0.forwardRef(() => Popover), { isSignal: true }] }], explanationElement: [{ type: i0.ViewChild, args: [i0.forwardRef(() => EntityCalculationExplanation), { ...{ read: ElementRef }, isSignal: true }] }] } });
949
4067
 
950
4068
  /**
951
4069
  * The largest amount still rendered in full.
@@ -4400,7 +7518,8 @@ const CALCULATION_CHANGE_CHIP_MS = 30_000;
4400
7518
  * Whether a surface marks this property as calculated. `isCalculated` alone is
4401
7519
  * too broad: the backend also sets it, with no calculation method, on system
4402
7520
  * columns such as `created_at`, `id` and `team_members`. A status has no method
4403
- * but is recalculated, and an auto code is generated once.
7521
+ * but is recalculated. An auto code is generated rather than recalculated, but
7522
+ * the backend explains it like any calculated value, so it is marked too.
4404
7523
  */
4405
7524
  function isCalculatedProperty(meta) {
4406
7525
  if (!meta) {
@@ -4409,9 +7528,7 @@ function isCalculatedProperty(meta) {
4409
7528
  if (meta.viewType === 'Status') {
4410
7529
  return true;
4411
7530
  }
4412
- return (meta.isCalculated === true &&
4413
- !!meta.calculationMethod &&
4414
- meta.calculationMethod !== 'CodeBuilder');
7531
+ return meta.isCalculated === true && !!meta.calculationMethod;
4415
7532
  }
4416
7533
  const EMPTY_CHANGES = new Map();
4417
7534
  const historyKey = (scope, recordId, propertyKey) => `${scope}|${recordId}|${propertyKey}`;
@@ -5065,5 +8182,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImpor
5065
8182
  * Generated bundle index. Do not edit.
5066
8183
  */
5067
8184
 
5068
- export { CALCULATION_CHANGE_CHIP_MS, CONNECTION_KEY_SEPARATOR, CURRENCY_COMPACT_THRESHOLD, CalculatedValueHistory, CalculationExplanationApi, ComparisonEntityList, ComparisonValue, DEFAULT_PERFORMANCE_SCORE_CHART_SIZE, DEFAULT_PHASE_GATE_COLOR, ENTITY_EMPTY_VALUE_PLACEHOLDER, ENTITY_HEADER_VIEW_TYPES, ENTITY_LIST_TABLE_COMPONENT, ENTITY_ROW_SPANS, EntitiesManage, EntitiesPreview, EntitiesResizeBase, EntityAttachment, EntityCalculatedGlyph, EntityCalculatedIndicator, EntityCalculationChangeChip, EntityCalculationExplanation, EntityCalculationRefresher, EntityCheckbox, EntityColor, EntityConnection, EntityCurrency, EntityDate, EntityField, EntityHeader, EntityIcon, EntityLeafDetails, EntityListDrawer, EntityListPreview, EntityLocation, EntityLongText, EntityLookup, EntityLookupModuleCheckList, EntityPercentage, EntityPerformanceScore, EntityPhaseGate, EntityPreview, EntityPreviewBody, EntityRuntimeContextStore, EntityScheduleItem, EntityStatus, EntityText, EntityUser, FitText, LEAF_DETAILS_KEY_SEPARATOR, LEAF_PHASES_KEY_SEPARATOR, PERFORMANCE_SCORE_CHART_SIZES, SECTION_KEY_PREFIX, buildConnectionKey, buildDisplayEntities, buildEntityListRows, buildSectionKey, canEntityBeHeader, compactCurrencyDisplay, currencyUnitOf, describeCalculationChange, displayOrPlaceholder, expandConnectionEntity, expandLeafDetailsEntity, extractDisplayText, formatCalculationDelta, formatExplanationValue, getEntitySectionTitle, getPerformanceScoreBands, groupEntitiesIntoSections, humanizeEntityListKey, isCalculatedProperty, isConnectionSyntheticKey, isEntityAlignEnd, isEntityHeader, isEntityLabelHidden, isEntityListLocalDocument, isEntityListSelectionDocument, isEntitySection, isLeafDetailsCatalogConfiguration, isLeafDetailsCollectionValue, isLeafDetailsRuntimeValue, isLeafDetailsSyntheticKey, isLeafDetailsValue, isLeafPhasesSyntheticKey, isLeafSyntheticKey, isSameSavedValue, isSectionKey, isValueMissing, localCellsByFieldId, matchesPercentageColorRule, mergeStakeholderNameColumns, mergeStakeholderNameEntities, mergeStakeholderNameRows, normalizeConnectionSourceLevels, normalizeNumerals, parseCurrencyAmount, parsePerformanceScore, pinEntityHeaderFirst, readEntityHeaderDefaults, readEntityValueColor, resolveConnectionLevelName, resolveEntityGridRow, resolveEntityHeader, resolveEntityInfo, resolveEntityLabelPosition, resolveLocalFieldConfiguration, resolveLocalFieldLabel, resolveLocalFieldViewType, resolveLocalizedLabel, resolvePercentageColor, resolvePerformanceScoreStatus, serializeEntityRawValue, sharedActiveLang, sortLocalRows, splitConnectionKey, splitLeafKey, summarizeEntityListRows, toCalculationContextKey, toCalculationExplanationTarget, visibleLocalSchemaFields };
8185
+ export { CALCULATION_CHANGE_CHIP_MS, CALCULATION_EXPLANATION_KEYS, CONNECTION_KEY_SEPARATOR, CURRENCY_COMPACT_THRESHOLD, CalculatedValueHistory, CalculationExplanationApi, CalculationExplanationChecks, CalculationExplanationDetails, CalculationExplanationEquation, CalculationExplanationPanel, CalculationExplanationSummary, CalculationRecordNames, ComparisonEntityList, ComparisonValue, DEFAULT_PERFORMANCE_SCORE_CHART_SIZE, DEFAULT_PHASE_GATE_COLOR, ENTITY_EMPTY_VALUE_PLACEHOLDER, ENTITY_HEADER_VIEW_TYPES, ENTITY_LIST_TABLE_COMPONENT, ENTITY_ROW_SPANS, EntitiesManage, EntitiesPreview, EntitiesResizeBase, EntityAttachment, EntityCalculatedGlyph, EntityCalculatedIndicator, EntityCalculationChangeChip, EntityCalculationExplanation, EntityCalculationRefresher, EntityCheckbox, EntityColor, EntityConnection, EntityCurrency, EntityDate, EntityField, EntityHeader, EntityIcon, EntityLeafDetails, EntityListDrawer, EntityListPreview, EntityLocation, EntityLongText, EntityLookup, EntityLookupModuleCheckList, EntityPercentage, EntityPerformanceScore, EntityPhaseGate, EntityPreview, EntityPreviewBody, EntityRuntimeContextStore, EntityScheduleItem, EntityStatus, EntityText, EntityUser, FitText, LEAF_DETAILS_KEY_SEPARATOR, LEAF_PHASES_KEY_SEPARATOR, MT_CALCULATION_CURRENCY, MT_CALCULATION_STATUS_NAMES, PERFORMANCE_SCORE_CHART_SIZES, SECTION_KEY_PREFIX, buildCalculationExplanationView, buildCodeSegments, buildConditionChecks, buildConnectionKey, buildDisplayEntities, buildEntityListRows, buildExplanationDetails, buildExplanationSegments, buildSectionKey, calculationRecordKey, canEntityBeHeader, capitalizeSegments, compactCurrencyDisplay, currencyUnitOf, describeCalculationChange, describeDocument, detailRecordRefs, displayName, displayOrPlaceholder, expandConnectionEntity, expandLeafDetailsEntity, extractDisplayText, formatCalculationDelta, formatExplanationNumber, formatExplanationValue, formatTypedValue, getEntitySectionTitle, getPerformanceScoreBands, groupEntitiesIntoSections, hasExplanationDetails, humanizeEntityListKey, humanizeKey$1 as humanizeKey, isCalculatedProperty, isConnectionSyntheticKey, isEntityAlignEnd, isEntityHeader, isEntityLabelHidden, isEntityListLocalDocument, isEntityListSelectionDocument, isEntitySection, isEquationDocument, isLeafDetailsCatalogConfiguration, isLeafDetailsCollectionValue, isLeafDetailsRuntimeValue, isLeafDetailsSyntheticKey, isLeafDetailsValue, isLeafPhasesSyntheticKey, isLeafSyntheticKey, isMissingBaseline, isSameSavedValue, isSectionKey, isValueMissing, localCellsByFieldId, matchesPercentageColorRule, mergeStakeholderNameColumns, mergeStakeholderNameEntities, mergeStakeholderNameRows, normalizeConnectionSourceLevels, normalizeNumerals, orderedStatusRules, parseCurrencyAmount, parsePerformanceScore, pinEntityHeaderFirst, readEntityHeaderDefaults, readEntityValueColor, resolveConnectionLevelName, resolveEntityGridRow, resolveEntityHeader, resolveEntityInfo, resolveEntityLabelPosition, resolveLocalFieldConfiguration, resolveLocalFieldLabel, resolveLocalFieldViewType, resolveLocalizedLabel, resolvePercentageColor, resolvePerformanceScoreStatus, selectedStatusRule, serializeEntityRawValue, serverText, sharedActiveLang, sortLocalRows, splitConnectionKey, splitLeafKey, statusName, summarizeEntityListRows, toCalculationContextKey, toCalculationExplanationTarget, toExplanationData, toFetchContextKey, visibleLocalSchemaFields };
5069
8186
  //# sourceMappingURL=masterteam-components-entities.mjs.map