@bino-bi/bn-template-engine 1.0.0-alpha.5 → 1.0.0-alpha.6

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.
Files changed (157) hide show
  1. package/dist/bn-template-engine/bn-template-engine.esm.js +1 -1
  2. package/dist/bn-template-engine/p-06946f44.entry.js +1 -0
  3. package/dist/bn-template-engine/p-0fabe296.entry.js +1 -0
  4. package/dist/bn-template-engine/p-1164c0b0.entry.js +1 -0
  5. package/dist/bn-template-engine/p-355abdf0.entry.js +1 -0
  6. package/dist/bn-template-engine/p-79KuA4Ox.js +1 -0
  7. package/dist/bn-template-engine/p-859cc06d.entry.js +1 -0
  8. package/dist/bn-template-engine/p-8acec99e.entry.js +1 -0
  9. package/dist/bn-template-engine/p-8f490c45.entry.js +1 -0
  10. package/dist/bn-template-engine/p-98cf512f.entry.js +1 -0
  11. package/dist/bn-template-engine/p-9a564f8f.entry.js +1 -0
  12. package/dist/bn-template-engine/{p-CL1RYuNU.js → p-B0lsgVuN.js} +1 -1
  13. package/dist/bn-template-engine/p-B7p8beYH.js +1 -0
  14. package/dist/bn-template-engine/p-BDh7GfC5.js +1 -0
  15. package/dist/bn-template-engine/p-BoMtoHJB.js +1 -0
  16. package/dist/bn-template-engine/p-Bs8BqBsb.js +1 -0
  17. package/dist/bn-template-engine/p-CYjZRKdI.js +1 -0
  18. package/dist/bn-template-engine/{p-P7pGJBgc.js → p-DG-1MR_T.js} +1 -1
  19. package/dist/bn-template-engine/p-bdd2b243.entry.js +1 -0
  20. package/dist/bn-template-engine/p-e6b24f15.entry.js +1 -0
  21. package/dist/bn-template-engine/p-f27995c9.entry.js +1 -0
  22. package/dist/bn-template-engine/{p-Bnhh02CF.js → p-sRO-lj7X.js} +1 -1
  23. package/dist/bn-template-engine/p-tzFCK9qn.js +1 -0
  24. package/dist/cjs/{Order-iG11HI4R.js → Order-BGx39pS5.js} +448 -0
  25. package/dist/cjs/{alasql.min-C_nHTuEQ.js → SVGVariancesStyleGroup-BqAdPYtL.js} +8228 -3
  26. package/dist/cjs/bn-asset_16.cjs.entry.js +9018 -0
  27. package/dist/cjs/bn-card.cjs.entry.js +3 -4
  28. package/dist/cjs/bn-chart-time.cjs.entry.js +11 -16
  29. package/dist/cjs/bn-grid.cjs.entry.js +5 -8
  30. package/dist/cjs/bn-image.cjs.entry.js +5 -8
  31. package/dist/cjs/bn-internationalization.cjs.entry.js +3 -4
  32. package/dist/cjs/bn-layout-card.cjs.entry.js +125 -6
  33. package/dist/cjs/bn-template-engine.cjs.js +1 -1
  34. package/dist/cjs/bn-template.cjs.entry.js +2 -3
  35. package/dist/cjs/bn-text.cjs.entry.js +7 -11
  36. package/dist/cjs/bn-tree.cjs.entry.js +5 -8
  37. package/dist/cjs/{formatter-DIJL_crx.js → formatter-4XCS0d2B.js} +8 -2
  38. package/dist/cjs/ibcs-chart-time.cjs.entry.js +37 -42
  39. package/dist/cjs/loader.cjs.js +1 -1
  40. package/dist/cjs/{scaling-9Tz595RQ.js → scaling-BidPsO53.js} +115 -12
  41. package/dist/cjs/{withBodyObserver-CKpSD8UT.js → withBodyObserver-C6gLgq_e.js} +3 -3
  42. package/dist/cjs/{withComponentStatus-Bw70BhO0.js → withComponentStatus-_x4LQZ0N.js} +5 -5
  43. package/dist/cjs/{withComponentStyle-aIbTCtfj.js → withComponentStyle-ClSJfCku.js} +4 -4
  44. package/dist/cjs/{utils-CwHIVbbL.js → withHasError-B8gHkfV2.js} +69 -1
  45. package/dist/cjs/{withStyled-CS1Yp4sv.js → withStyled-9tG024gQ.js} +62 -9
  46. package/dist/collection/components/bn-layout-card/bn-layout-card.css +1 -0
  47. package/dist/collection/components/bn-layout-card/bn-layout-card.js +162 -27
  48. package/dist/collection/components/bn-layout-page/bn-layout-page.css +1 -0
  49. package/dist/collection/components/bn-layout-page/bn-layout-page.js +151 -33
  50. package/dist/collection/utils/parentDimensions.js +38 -6
  51. package/dist/components/bn-layout-card.js +1 -1
  52. package/dist/components/bn-layout-page.js +1 -1
  53. package/dist/components/scaling.js +1 -1
  54. package/dist/esm/{Order-Bnhh02CF.js → Order-sRO-lj7X.js} +448 -1
  55. package/dist/esm/{alasql.min-CWu4NkIt.js → SVGVariancesStyleGroup-DOIT-zvI.js} +8212 -2
  56. package/dist/esm/bn-asset_16.entry.js +9001 -0
  57. package/dist/esm/bn-card.entry.js +4 -5
  58. package/dist/esm/bn-chart-time.entry.js +8 -13
  59. package/dist/esm/bn-grid.entry.js +6 -9
  60. package/dist/esm/bn-image.entry.js +6 -9
  61. package/dist/esm/bn-internationalization.entry.js +4 -5
  62. package/dist/esm/bn-layout-card.entry.js +126 -7
  63. package/dist/esm/bn-template-engine.js +1 -1
  64. package/dist/esm/bn-template.entry.js +2 -3
  65. package/dist/esm/bn-text.entry.js +7 -11
  66. package/dist/esm/bn-tree.entry.js +6 -9
  67. package/dist/esm/{context-protocol-BHnQsVsr.js → context-protocol-2peaD4y8.js} +1 -1
  68. package/dist/esm/editor-companion.entry.js +1 -1
  69. package/dist/esm/{formatter-DTMEZ6d8.js → formatter-BDh7GfC5.js} +6 -2
  70. package/dist/esm/ibcs-chart-time.entry.js +3 -8
  71. package/dist/esm/loader.js +1 -1
  72. package/dist/esm/{scaling-Cehc74IE.js → scaling-BOcjT8M0.js} +112 -10
  73. package/dist/esm/{withBodyObserver-FQ8NwCIz.js → withBodyObserver-DczL5ia8.js} +1 -1
  74. package/dist/esm/{withComponentStatus-DWjDYtZ7.js → withComponentStatus-DodoSXe-.js} +1 -1
  75. package/dist/esm/{withComponentStyle-9uP_hcDq.js → withComponentStyle-D3VWOsto.js} +2 -2
  76. package/dist/esm/{utils-DvvwfRQG.js → withHasError-B3QX2emi.js} +69 -1
  77. package/dist/esm/{withStyled--qQWquTH.js → withStyled-CE3_3taP.js} +57 -5
  78. package/dist/types/components/bn-layout-card/bn-layout-card.d.ts +139 -0
  79. package/dist/types/components/bn-layout-page/bn-layout-page.d.ts +154 -0
  80. package/dist/types/components.d.ts +168 -0
  81. package/dist/types/utils/parentDimensions.d.ts +6 -1
  82. package/package.json +1 -1
  83. package/dist/bn-template-engine/p-1265d8d3.entry.js +0 -1
  84. package/dist/bn-template-engine/p-15516dac.entry.js +0 -1
  85. package/dist/bn-template-engine/p-1c716641.entry.js +0 -1
  86. package/dist/bn-template-engine/p-1jFf17Vj.js +0 -1
  87. package/dist/bn-template-engine/p-27cc8dc0.entry.js +0 -1
  88. package/dist/bn-template-engine/p-3b4c7425.entry.js +0 -1
  89. package/dist/bn-template-engine/p-4426d484.entry.js +0 -1
  90. package/dist/bn-template-engine/p-51f8dc9e.entry.js +0 -1
  91. package/dist/bn-template-engine/p-53d4e690.entry.js +0 -1
  92. package/dist/bn-template-engine/p-5KQYRQLK.js +0 -1
  93. package/dist/bn-template-engine/p-7337e03d.entry.js +0 -1
  94. package/dist/bn-template-engine/p-75e97c87.entry.js +0 -1
  95. package/dist/bn-template-engine/p-7a560278.entry.js +0 -1
  96. package/dist/bn-template-engine/p-BFTU3MAI.js +0 -1
  97. package/dist/bn-template-engine/p-BYBpC0EO.js +0 -1
  98. package/dist/bn-template-engine/p-BYmPQYxx.js +0 -1
  99. package/dist/bn-template-engine/p-BfXY5dsy.js +0 -1
  100. package/dist/bn-template-engine/p-BgnHJQ9Q.js +0 -1
  101. package/dist/bn-template-engine/p-Bhd_WSML.js +0 -1
  102. package/dist/bn-template-engine/p-Bka-Z6jo.js +0 -1
  103. package/dist/bn-template-engine/p-C7dQL8CS.js +0 -1
  104. package/dist/bn-template-engine/p-CYwd_ZNM.js +0 -1
  105. package/dist/bn-template-engine/p-ChlK-T9I.js +0 -1
  106. package/dist/bn-template-engine/p-DHezf8pZ.js +0 -1
  107. package/dist/bn-template-engine/p-DlppAFq9.js +0 -1
  108. package/dist/bn-template-engine/p-DvDDgmcV.js +0 -1
  109. package/dist/bn-template-engine/p-DvvwfRQG.js +0 -1
  110. package/dist/bn-template-engine/p-abc0067c.entry.js +0 -1
  111. package/dist/bn-template-engine/p-b34eaf86.entry.js +0 -1
  112. package/dist/bn-template-engine/p-bdb8b44c.entry.js +0 -1
  113. package/dist/bn-template-engine/p-c44fcb8e.entry.js +0 -1
  114. package/dist/bn-template-engine/p-c7e1a49b.entry.js +0 -1
  115. package/dist/bn-template-engine/p-d9003041.entry.js +0 -1
  116. package/dist/bn-template-engine/p-daa7ffa3.entry.js +0 -1
  117. package/dist/bn-template-engine/p-e084f50a.entry.js +0 -1
  118. package/dist/bn-template-engine/p-eaba6658.entry.js +0 -1
  119. package/dist/bn-template-engine/p-u8igQLRZ.js +0 -1
  120. package/dist/cjs/DataFormatDigits-DKcOeLNK.js +0 -142
  121. package/dist/cjs/DateStringFactory-CSKvbS8K.js +0 -452
  122. package/dist/cjs/SVGVariancesStyleGroup-K-Tw6lOD.js +0 -7960
  123. package/dist/cjs/_commonjsHelpers-BJu3ubxk.js +0 -10
  124. package/dist/cjs/bn-asset.cjs.entry.js +0 -42
  125. package/dist/cjs/bn-body_4.cjs.entry.js +0 -748
  126. package/dist/cjs/bn-chart-structure_5.cjs.entry.js +0 -3948
  127. package/dist/cjs/bn-component-style.cjs.entry.js +0 -44
  128. package/dist/cjs/bn-dataset.cjs.entry.js +0 -306
  129. package/dist/cjs/bn-layout-page.cjs.entry.js +0 -143
  130. package/dist/cjs/bn-message.cjs.entry.js +0 -52
  131. package/dist/cjs/bn-table.cjs.entry.js +0 -981
  132. package/dist/cjs/contentDecoder-JxOldq1e.js +0 -419
  133. package/dist/cjs/emotion-hash.esm-nbbEQ0Dn.js +0 -57
  134. package/dist/cjs/ibcs-table.cjs.entry.js +0 -2276
  135. package/dist/cjs/ibcsRuleSet-DgUoXOfd.js +0 -136
  136. package/dist/cjs/index-Dm85hG6t.js +0 -65
  137. package/dist/cjs/withHasError-D7ue5vAv.js +0 -72
  138. package/dist/cjs/withTranslation-rwgyITqe.js +0 -77
  139. package/dist/esm/DataFormatDigits-oSZ1hBKE.js +0 -137
  140. package/dist/esm/DateStringFactory-CSGz6TDk.js +0 -450
  141. package/dist/esm/SVGVariancesStyleGroup-CqTjrZYg.js +0 -7950
  142. package/dist/esm/_commonjsHelpers-BFTU3MAI.js +0 -7
  143. package/dist/esm/bn-asset.entry.js +0 -40
  144. package/dist/esm/bn-body_4.entry.js +0 -743
  145. package/dist/esm/bn-chart-structure_5.entry.js +0 -3942
  146. package/dist/esm/bn-component-style.entry.js +0 -42
  147. package/dist/esm/bn-dataset.entry.js +0 -304
  148. package/dist/esm/bn-layout-page.entry.js +0 -141
  149. package/dist/esm/bn-message.entry.js +0 -50
  150. package/dist/esm/bn-table.entry.js +0 -979
  151. package/dist/esm/contentDecoder-oMmxz6nJ.js +0 -416
  152. package/dist/esm/emotion-hash.esm-BYBpC0EO.js +0 -55
  153. package/dist/esm/ibcs-table.entry.js +0 -2274
  154. package/dist/esm/ibcsRuleSet-K4ytuA1f.js +0 -133
  155. package/dist/esm/index-DHezf8pZ.js +0 -65
  156. package/dist/esm/withHasError-FyY5mQ_3.js +0 -70
  157. package/dist/esm/withTranslation-BqD0Kp7b.js +0 -75
@@ -1,2276 +0,0 @@
1
- 'use strict';
2
-
3
- var index$1 = require('./index-Cjw0q6gP.js');
4
- var index = require('./index-Dm85hG6t.js');
5
- var formatter = require('./formatter-DIJL_crx.js');
6
- var Order = require('./Order-iG11HI4R.js');
7
- var alasql_min = require('./alasql.min-C_nHTuEQ.js');
8
- var ibcsRuleSet = require('./ibcsRuleSet-DgUoXOfd.js');
9
- var DataFormatDigits = require('./DataFormatDigits-DKcOeLNK.js');
10
- var withComponentStyle = require('./withComponentStyle-aIbTCtfj.js');
11
- require('./_commonjsHelpers-BJu3ubxk.js');
12
- require('./context-protocol-DRQWrwsA.js');
13
- require('./utils-CwHIVbbL.js');
14
-
15
- // import {Formatter} from "../../../../utils/formatter";
16
- // import {DataFormatDigits} from "../../../../utils/model/DataFormatDigits";
17
- /**
18
- * Represents a single table cell with formatting and rendering capabilities.
19
- *
20
- * The draw() method implements a formatting pipeline:
21
- * 1. Checks for undefined/null/NaN values -- returns empty string for missing data
22
- * 2. Non-numeric values (category labels) are returned as-is
23
- * 3. Numeric values are routed through Formatter.number() with the cell's type
24
- * (decimal or percent) and configured digit precision
25
- * 4. For decimal type, the raw value is divided by measureScale before formatting,
26
- * enabling SI prefix display (e.g. "in Mio EUR")
27
- */
28
- class Cell {
29
- constructor(scenario, index, value, cssStyle, type, prefix, prefixStyle, colSpan, measureScale) {
30
- this.prefixStyle = "prefix";
31
- this.isBarChart = false;
32
- this.key = scenario;
33
- this.index = index;
34
- this.value = value;
35
- this.prefix = prefix || "";
36
- this.cssStyle = cssStyle || "";
37
- this.prefixStyle = prefixStyle || "prefix";
38
- this.type = type;
39
- this.mark = undefined;
40
- this.colSpan = colSpan || 1;
41
- this.measureScale = measureScale || 1;
42
- }
43
- getAsHeaderList() {
44
- if (this.value == null) {
45
- return [""];
46
- }
47
- const result = [];
48
- for (const line of this.value.toString().split("<br/>")) {
49
- result.push(line);
50
- }
51
- return result;
52
- }
53
- draw(dataFormatDigits) {
54
- let cellValue = this.value;
55
- if (cellValue === "undefined" || cellValue === undefined || cellValue == null) {
56
- return "";
57
- }
58
- if (Number.isNaN(Number(cellValue))) {
59
- return cellValue;
60
- }
61
- if (this.type === "" || this.type === undefined || this.type == null) {
62
- return cellValue;
63
- }
64
- let digitsMin = dataFormatDigits.percent;
65
- let scale = dataFormatDigits.percent;
66
- if (this.type === "decimal") {
67
- cellValue = +cellValue / this.measureScale;
68
- digitsMin = dataFormatDigits.decimal;
69
- scale = dataFormatDigits.decimal;
70
- }
71
- return formatter.Formatter.number(Number(cellValue), this.type, digitsMin, scale);
72
- }
73
- drawPrefix() {
74
- if (this.prefix == null) {
75
- return "";
76
- }
77
- return this.prefix;
78
- }
79
- }
80
-
81
- /**
82
- * Represents a single row in an IBCS table, containing an ordered list of Cells.
83
- *
84
- * The CSS class is determined by the TableRowType:
85
- * - HEADER -> "groupheader"
86
- * - SEPERATORLINE -> "" (styled via cell-level scenario classes)
87
- * - DRILLELEMENT -> "ofit" (thereof rows)
88
- * - PARTELEMENT -> "partof" (percentage-of-parent rows)
89
- * - SUM -> "sum"
90
- * - STANDARD -> ""
91
- *
92
- * createElement() applies type-specific overrides:
93
- * - HEADER rows force "headerlabel" CSS on all cells
94
- * - SEPERATORLINE rows use the scenario name as CSS class for border styling
95
- * - PARTELEMENT rows show "-" for percent cells and force percent type on data cells
96
- */
97
- class TableRow {
98
- constructor(index, groupIndex, type) {
99
- this.index = index;
100
- this.groupindex = groupIndex;
101
- this.type = type;
102
- this.cssStyle = this.initCssStyle();
103
- this.elements = [];
104
- }
105
- initCssStyle() {
106
- switch (this.type) {
107
- case index.TableRowType.HEADER: {
108
- return "groupheader";
109
- }
110
- case index.TableRowType.SEPERATORLINE: {
111
- return "";
112
- }
113
- case index.TableRowType.DRILLELEMENT: {
114
- return "ofit";
115
- }
116
- case index.TableRowType.PARTELEMENT: {
117
- return "partof";
118
- }
119
- case index.TableRowType.STANDARD: {
120
- return "";
121
- }
122
- case index.TableRowType.SUM: {
123
- return "sum";
124
- }
125
- default: {
126
- return "";
127
- }
128
- }
129
- }
130
- getCells() {
131
- return this.elements;
132
- }
133
- createElement(value, scenario, columnType, cellType, prefix, cellStyle, isSecondaryElement, categoryWidth, measureScale, isBarChart = false, columnStats) {
134
- let cssStyle = cellStyle;
135
- if (scenario === "category" && categoryWidth != null) {
136
- cssStyle = `category-${categoryWidth.toString()}`;
137
- }
138
- if (this.type === index.TableRowType.HEADER) {
139
- cssStyle = "headerlabel";
140
- }
141
- else if (this.type === index.TableRowType.SEPERATORLINE) {
142
- cssStyle = scenario;
143
- }
144
- if (this.type === index.TableRowType.PARTELEMENT) {
145
- if (cellType === "percent") {
146
- value = "-";
147
- }
148
- if (scenario !== "category" && scenario !== "operation") {
149
- cellType = "percent";
150
- cssStyle = "";
151
- }
152
- }
153
- if (value === "-") {
154
- cssStyle = "";
155
- }
156
- let prefixStyle = "prefix-first";
157
- if (isSecondaryElement) {
158
- prefixStyle = "prefix-second";
159
- }
160
- if (columnType) {
161
- cssStyle = `${cssStyle} ${columnType}`;
162
- }
163
- const cell = new Cell(scenario, this.elements.length, value, cssStyle, cellType, prefix, prefixStyle, 1, measureScale);
164
- cell.isBarChart = isBarChart;
165
- cell.columnStats = columnStats;
166
- this.elements.push(cell);
167
- }
168
- }
169
-
170
- // Default fallback colors (should come from componentStyle)
171
- const DEFAULT_STYLES = {
172
- positive: { stroke: "#008f96", fill: "#008f96", fillpattern: "solid" },
173
- negative: { stroke: "#ff0000", fill: "#ff0000", fillpattern: "solid" },
174
- neutral: { stroke: "#808080", fill: "#808080", fillpattern: "outlined" },
175
- scenarios: {
176
- ac: { stroke: "#404040", fill: "#404040", fillpattern: "solid" },
177
- pp: { stroke: "#A6A6A6", fill: "#A6A6A6", fillpattern: "solid" },
178
- fc: { stroke: "#404040", fill: "#ffffff", fillpattern: "hatched" },
179
- pl: { stroke: "#404040", fill: "#ffffff", fillpattern: "outlined" },
180
- },
181
- fontColor: "#000000",
182
- fontSize: 11,
183
- fontFamily: "'Noto Sans', sans-serif",
184
- unitScaling: 0.01, // Default: 1000 units = 10 pixels
185
- percentageScaling: 0.5, // Default: 100% = 50 pixels
186
- scaleFactor: 1,
187
- };
188
- const AXIS_COLOR = "#666666";
189
- /**
190
- * Creates a unique pattern ID for the SVG defs
191
- */
192
- function getPatternId(prefix, color) {
193
- return `pattern-${prefix}-${color.replace("#", "")}`;
194
- }
195
- /**
196
- * Renders SVG pattern definitions for hatched fills
197
- */
198
- const PatternDefs = ({ styles }) => {
199
- const s = styles.scaleFactor;
200
- const patternSize = 6 * s;
201
- const patterns = [
202
- { id: getPatternId("pos", styles.positive.stroke), stroke: styles.positive.stroke, fill: styles.positive.fill },
203
- { id: getPatternId("neg", styles.negative.stroke), stroke: styles.negative.stroke, fill: styles.negative.fill },
204
- { id: getPatternId("neu", styles.neutral.stroke), stroke: styles.neutral.stroke, fill: styles.neutral.fill },
205
- ];
206
- return (index$1.h("defs", null, patterns.map((p) => (index$1.h("pattern", { id: p.id, patternUnits: "userSpaceOnUse", width: patternSize, height: patternSize }, index$1.h("rect", { width: patternSize, height: patternSize, fill: "#ffffff" }), index$1.h("line", { x1: "0", y1: patternSize, x2: patternSize, y2: "0", stroke: p.stroke, "stroke-width": 1.5 * s }))))));
207
- };
208
- /**
209
- * Formats a number for display with appropriate SI prefix.
210
- */
211
- function formatValue(value, isRelative, measureScale = 1) {
212
- let scaledValue;
213
- let absValue;
214
- const prefix = value >= 0 ? "+" : "";
215
- if (isRelative) {
216
- // Relative variance is stored as decimal (e.g., -2.0 = -200%)
217
- // Multiply by 100 to get percentage value for display
218
- scaledValue = value * 100;
219
- // Show as integer percentage with % suffix
220
- return prefix + Math.round(scaledValue).toString() + "%";
221
- }
222
- else {
223
- // Absolute variance - apply measure scale and use SI prefixes
224
- scaledValue = value / measureScale;
225
- absValue = Math.abs(scaledValue);
226
- let formatted;
227
- if (absValue >= 1000000000) {
228
- formatted = (scaledValue / 1000000000).toFixed(absValue >= 10000000000 ? 0 : 1) + "B";
229
- }
230
- else if (absValue >= 1000000) {
231
- formatted = (scaledValue / 1000000).toFixed(absValue >= 10000000 ? 0 : 1) + "M";
232
- }
233
- else if (absValue >= 1000) {
234
- formatted = (scaledValue / 1000).toFixed(absValue >= 10000 ? 0 : 1) + "K";
235
- }
236
- else {
237
- formatted = scaledValue.toFixed(absValue >= 10 ? 0 : 1);
238
- }
239
- // Remove trailing .0 if present
240
- formatted = formatted.replace(/\.0([KMB]?)$/, "$1");
241
- return prefix + formatted;
242
- }
243
- }
244
- /**
245
- * Checks if the column is a scenario column (ac, pp, fc, pl) vs variance (d_, dr_).
246
- */
247
- function isScenarioColumn(scenario) {
248
- const scenarioPrefix = scenario.slice(0, 2).toLowerCase();
249
- return ["ac", "pp", "fc", "pl"].includes(scenarioPrefix);
250
- }
251
- /**
252
- * Gets the scenario type from the column name (ac, pp, fc, pl).
253
- */
254
- function getScenarioType(scenario) {
255
- const scenarioPrefix = scenario.slice(0, 2).toLowerCase();
256
- if (scenarioPrefix === "pp")
257
- return "pp";
258
- if (scenarioPrefix === "fc")
259
- return "fc";
260
- if (scenarioPrefix === "pl")
261
- return "pl";
262
- return "ac"; // default
263
- }
264
- /**
265
- * Gets the style for a scenario column (ac, pp, fc, pl).
266
- */
267
- function getScenarioStyle(scenario, styles) {
268
- const type = getScenarioType(scenario);
269
- return styles.scenarios[type];
270
- }
271
- /**
272
- * Gets the variance style based on value and sentiment direction.
273
- * pos suffix = positive values are good (green), negative are bad (red)
274
- * neg suffix = negative values are good (green), positive are bad (red)
275
- */
276
- function getVarianceStyle(value, isPositiveGood, styles) {
277
- const isPositive = value >= 0;
278
- if (isPositiveGood) {
279
- return isPositive ? styles.positive : styles.negative;
280
- }
281
- else {
282
- return isPositive ? styles.negative : styles.positive;
283
- }
284
- }
285
- /**
286
- * Gets the appropriate style for a bar based on column type.
287
- * Scenarios (ac, pp, fc, pl) use scenario styles.
288
- * Variances (d_, dr_) use variance styles with pos/neg/neu coloring.
289
- */
290
- function getBarStyle(scenario, value, isPositiveGood, styles) {
291
- if (isScenarioColumn(scenario)) {
292
- return getScenarioStyle(scenario, styles);
293
- }
294
- return getVarianceStyle(value, isPositiveGood, styles);
295
- }
296
- /**
297
- * Gets the fill value for a bar - either solid color, pattern URL, or transparent with stroke.
298
- */
299
- function getBarFill(varianceStyle, patternPrefix) {
300
- const pattern = varianceStyle.fillpattern;
301
- if (pattern === "hatched") {
302
- return `url(#${getPatternId(patternPrefix, varianceStyle.stroke)})`;
303
- }
304
- if (pattern === "outlined") {
305
- return "transparent";
306
- }
307
- // Default: solid fill
308
- return varianceStyle.fill;
309
- }
310
- /**
311
- * Gets the stroke for a bar based on pattern type.
312
- */
313
- function getBarStroke(varianceStyle) {
314
- const pattern = varianceStyle.fillpattern;
315
- if (pattern === "outlined") {
316
- return { stroke: varianceStyle.stroke, strokeWidth: 1.5 }; // scaled by caller via * s
317
- }
318
- // Solid and hatched bars don't need visible stroke
319
- return { stroke: "none", strokeWidth: 0 };
320
- }
321
- /**
322
- * Renders a zigzag break indicator at a given x position, matching the structure chart style.
323
- * Two mirrored zigzag lines with a white background covering the break gap.
324
- */
325
- function renderZigzagBreak(breakX, breakGap, yTop, barHeight, s) {
326
- const midX = breakX + breakGap / 2;
327
- const halfGap = breakGap * 0.35;
328
- const zigCount = 3;
329
- const segHeight = barHeight / zigCount;
330
- const amplitude = breakGap * 0.3;
331
- let leftPath = `M ${midX - halfGap} ${yTop}`;
332
- for (let i = 0; i < zigCount; i++) {
333
- const y1 = yTop + segHeight * (i + 0.5);
334
- const y2 = yTop + segHeight * (i + 1);
335
- leftPath += ` L ${midX - halfGap - amplitude} ${y1} L ${midX - halfGap} ${y2}`;
336
- }
337
- let rightPath = `M ${midX + halfGap} ${yTop}`;
338
- for (let i = 0; i < zigCount; i++) {
339
- const y1 = yTop + segHeight * (i + 0.5);
340
- const y2 = yTop + segHeight * (i + 1);
341
- rightPath += ` L ${midX + halfGap + amplitude} ${y1} L ${midX + halfGap} ${y2}`;
342
- }
343
- return [
344
- index$1.h("rect", { x: breakX, y: yTop - 1, width: breakGap, height: barHeight + 2, fill: "#ffffff" }),
345
- index$1.h("path", { d: leftPath, fill: "none", stroke: "#000000", "stroke-width": 1 * s }),
346
- index$1.h("path", { d: rightPath, fill: "none", stroke: "#000000", "stroke-width": 1 * s }),
347
- ];
348
- }
349
- /**
350
- * Renders an absolute variance bar chart (d_ prefix).
351
- * Horizontal bar with centered axis, green for positive, red for negative.
352
- * When a bar exceeds maxBarWidth it is drawn as an overdrive bar:
353
- * base segment + zigzag break + proportional overdrive stub (like structure chart).
354
- *
355
- * Layout: [left label area][bar area with axis][right label area]
356
- */
357
- const AbsoluteVarianceBar = (props) => {
358
- const { value, scenario, columnStats, height, isPositiveGood, formattedValue, measureScale, maxBarWidth: maxBarWidthEm = 10, styles = DEFAULT_STYLES, } = props;
359
- const s = styles.scaleFactor;
360
- const fs = styles.fontSize;
361
- const labelAreaWidth = 38 * s;
362
- const maxBarWidth = maxBarWidthEm * fs;
363
- // Overdrive layout constants
364
- const breakGap = 4 * s;
365
- const overdriveZoneWidth = maxBarWidth * 0.15;
366
- const cutWidth = maxBarWidth - breakGap - overdriveZoneWidth;
367
- // Direct unit scaling via fontSize
368
- const scaledWidth = Math.abs(value) * styles.unitScaling * fs;
369
- const isExtreme = scaledWidth > cutWidth;
370
- // Compute proportional overdrive width across the column
371
- const maxScaledWidth = columnStats.absMax * styles.unitScaling * fs;
372
- const maxOverflow = Math.max(0, maxScaledWidth - cutWidth);
373
- const overflowAmount = Math.max(0, scaledWidth - cutWidth);
374
- const overdriveWidth = maxOverflow > 0 ? (overflowAmount / maxOverflow) * overdriveZoneWidth : 0;
375
- // Adaptive axis placement based on data range
376
- const hasNeg = columnStats.min < 0;
377
- const hasPos = columnStats.max > 0;
378
- const negBarWidth = hasNeg ? maxBarWidth : 0;
379
- const posBarWidth = hasPos ? maxBarWidth : 0;
380
- const barAreaWidth = negBarWidth + posBarWidth;
381
- const totalWidth = (hasNeg ? labelAreaWidth : 0) + barAreaWidth + (hasPos ? labelAreaWidth : 0);
382
- const padding = 2 * s;
383
- const barHeight = height - padding * 2;
384
- const axisX = (hasNeg ? labelAreaWidth : 0) + negBarWidth;
385
- const barY = padding;
386
- const isPositive = value >= 0;
387
- // Get style based on column type (scenario vs variance)
388
- const barStyle = getBarStyle(scenario, value, isPositiveGood, styles);
389
- const patternPrefix = isScenarioColumn(scenario)
390
- ? getScenarioType(scenario)
391
- : isPositiveGood
392
- ? isPositive
393
- ? "pos"
394
- : "neg"
395
- : isPositive
396
- ? "neg"
397
- : "pos";
398
- const fillValue = getBarFill(barStyle, patternPrefix);
399
- const { stroke: barStroke, strokeWidth: barStrokeWidth } = getBarStroke(barStyle);
400
- const displayValue = formattedValue || formatValue(value, false, measureScale);
401
- // Normal bar width (clamped to cutWidth when extreme)
402
- const baseBarWidth = isExtreme ? cutWidth : scaledWidth;
403
- // Label position accounts for overdrive
404
- const totalVisualWidth = isExtreme ? cutWidth + breakGap + overdriveWidth : scaledWidth;
405
- const labelX = isPositive ? axisX + totalVisualWidth + 4 * s : axisX - totalVisualWidth - 4 * s;
406
- const labelAnchor = isPositive ? "start" : "end";
407
- return (index$1.h("svg", { width: totalWidth, height: height, class: "cell-bar-chart absolute-variance", style: { overflow: "visible" } }, index$1.h(PatternDefs, { styles: styles }), index$1.h("line", { x1: axisX, y1: 0, x2: axisX, y2: height, stroke: AXIS_COLOR, "stroke-width": 1 * s }), baseBarWidth > 0 && (index$1.h("rect", { x: isPositive ? axisX : axisX - baseBarWidth, y: barY, width: baseBarWidth, height: barHeight, fill: fillValue, stroke: barStroke, "stroke-width": barStrokeWidth * s })), isExtreme && overdriveWidth > 0 && (index$1.h("rect", { x: isPositive ? axisX + cutWidth + breakGap : axisX - cutWidth - breakGap - overdriveWidth, y: barY, width: overdriveWidth, height: barHeight, fill: fillValue, stroke: barStroke, "stroke-width": barStrokeWidth * s })), isExtreme &&
408
- renderZigzagBreak(isPositive ? axisX + cutWidth : axisX - cutWidth - breakGap, breakGap, barY, barHeight, s), index$1.h("text", { x: labelX, y: height / 2, dy: "0.35em", "text-anchor": labelAnchor, fill: styles.fontColor, "font-size": fs, "font-family": styles.fontFamily }, displayValue)));
409
- };
410
- /**
411
- * Renders a relative variance pin chart (dr_ prefix).
412
- * Thin horizontal line from axis with dot at end and value label.
413
- *
414
- * Layout: [pin area with axis][label area on right]
415
- * Uses percentageScaling to determine pin length (pixels per percentage point).
416
- */
417
- const RelativeVariancePin = (props) => {
418
- const { value, scenario, columnStats, height, isPositiveGood, formattedValue, measureScale, maxBarWidth: maxBarWidthEm = 10, styles = DEFAULT_STYLES, } = props;
419
- const s = styles.scaleFactor;
420
- const fs = styles.fontSize;
421
- // Pin length is ~2/3 of bar width for visual balance
422
- const maxPinLength = Math.round(maxBarWidthEm * 0.67 * fs);
423
- const pinPadding = 5 * s;
424
- // Adaptive axis placement based on data range
425
- const hasNeg = columnStats.min < 0;
426
- const hasPos = columnStats.max > 0;
427
- const negPinWidth = hasNeg ? maxPinLength + pinPadding : 0;
428
- const posPinWidth = hasPos ? maxPinLength + pinPadding : 0;
429
- const pinAreaWidth = negPinWidth + posPinWidth;
430
- const labelAreaWidth = 45 * s;
431
- const totalWidth = pinAreaWidth + labelAreaWidth;
432
- const axisX = negPinWidth;
433
- const centerY = height / 2;
434
- // Direct unit scaling via fontSize
435
- const percentValue = Math.abs(value) * 100;
436
- const scaledLength = percentValue * styles.percentageScaling * fs;
437
- const isExtreme = scaledLength > maxPinLength;
438
- const pinLength = Math.min(scaledLength, maxPinLength);
439
- const isPositive = value >= 0;
440
- const pinEndX = isPositive ? axisX + pinLength : axisX - pinLength;
441
- // Get style based on column type (scenario vs variance)
442
- const barStyle = getBarStyle(scenario, value, isPositiveGood, styles);
443
- const dotRadius = 3 * s;
444
- const displayValue = formattedValue || formatValue(value, true, measureScale);
445
- // Label always on the right side after the pin area
446
- const labelX = pinAreaWidth + 4 * s;
447
- return (index$1.h("svg", { width: totalWidth, height: height, class: "cell-bar-chart relative-variance", style: { overflow: "visible" } }, index$1.h("line", { x1: axisX, y1: 0, x2: axisX, y2: height, stroke: AXIS_COLOR, "stroke-width": 1 * s }), !isExtreme && index$1.h("circle", { cx: pinEndX, cy: centerY, r: dotRadius, fill: styles.fontColor }), index$1.h("line", { x1: axisX, y1: centerY, x2: pinEndX, y2: centerY, stroke: barStyle.fill, "stroke-width": 2 * s }), isExtreme && isPositive && (index$1.h("polygon", { points: `${axisX + maxPinLength},${centerY} ${axisX + maxPinLength - 6 * s},${centerY - 3 * s} ${axisX + maxPinLength - 6 * s},${centerY + 3 * s}`, fill: barStyle.fill })), isExtreme && !isPositive && (index$1.h("polygon", { points: `${axisX - maxPinLength},${centerY} ${axisX - maxPinLength + 6 * s},${centerY - 3 * s} ${axisX - maxPinLength + 6 * s},${centerY + 3 * s}`, fill: barStyle.fill })), index$1.h("text", { x: labelX, y: height / 2, dy: "0.35em", "text-anchor": "start", fill: styles.fontColor, "font-size": fs, "font-style": "italic", "font-family": styles.fontFamily }, displayValue)));
448
- };
449
- /**
450
- * CellBarChart - Renders IBCS-compliant variance bar charts.
451
- *
452
- * Absolute variance (d_ prefix): Horizontal bars with centered axis
453
- * Relative variance (dr_ prefix): Pin/dot charts with value indication
454
- *
455
- * Uses componentStyle patterns from chart components for consistent styling.
456
- */
457
- const CellBarChart = (props) => {
458
- const { value, columnStats, isRelative, styles = DEFAULT_STYLES } = props;
459
- // Handle invalid values
460
- if (value === null || value === undefined || isNaN(value) || !columnStats || columnStats.absMax === 0) {
461
- return (index$1.h("span", { class: "bar-chart-empty", style: { color: styles.fontColor, fontStyle: "italic" } }, "-"));
462
- }
463
- if (isRelative) {
464
- return index$1.h(RelativeVariancePin, Object.assign({}, props));
465
- }
466
- return index$1.h(AbsoluteVarianceBar, Object.assign({}, props));
467
- };
468
-
469
- /**
470
- * Manages the GROUP BY column list for DataQuery's SQL statements and registers
471
- * the `transformOperator` AlaSQL custom function.
472
- *
473
- * `transformOperator` converts the dataset's `operation` field (`"+"` or `"-"`)
474
- * into a numeric multiplier (+1 / -1) so that SUM aggregations correctly add
475
- * or subtract rows based on their sign.
476
- *
477
- * The GROUP BY columns are composed dynamically: always category + categoryIndex,
478
- * plus operation for OPT types, plus rowGroup/rowGroupIndex when grouping is active.
479
- */
480
- class QueryGroups {
481
- constructor(config) {
482
- alasql_min.alasql.fn.transformOperator = function (a) {
483
- return a === "-" ? -1 : 1;
484
- };
485
- this.groups = [formatter.QueryColumnNames.CATEGORY, formatter.QueryColumnNames.CATEGORYINDEX];
486
- if (index.TableType.OPT === config.type || index.TableType.OPTNOTOTAL === config.type) {
487
- this.groups.unshift(formatter.QueryColumnNames.OPERATION);
488
- }
489
- if (config.grouped) {
490
- this.groups.push(formatter.QueryColumnNames.ROWGROUP);
491
- this.groups.push(formatter.QueryColumnNames.ROWGROUPINDEX);
492
- }
493
- }
494
- toString() {
495
- return this.groups.map((s) => `${s}`).toString();
496
- }
497
- noCategory() {
498
- return this.groups.filter((element) => element !== formatter.QueryColumnNames.CATEGORY);
499
- }
500
- toArray() {
501
- return this.groups;
502
- }
503
- }
504
-
505
- /**
506
- * AlaSQL-based query builder that produces the complete table result set for bn-table.
507
- *
508
- * Translates a {@link TableComponentConfig} into a series of SQL statements executed
509
- * against in-memory data rows. The pipeline handles scenario aggregation, row/column
510
- * grouping, drill-down expansion (thereof / partof), REST rows, sum rows, NaN detection,
511
- * column-level drill columns, and relative variance calculation.
512
- */
513
- class DataQuery {
514
- constructor(config, i18n) {
515
- this.hasPartOf = false;
516
- this.config = config;
517
- this.i18n = i18n;
518
- }
519
- /**
520
- * Executes the full query pipeline and returns a segmented result set.
521
- *
522
- * Pipeline steps:
523
- * 1. Translate scenario columns into SQL aggregation expressions
524
- * 2. Run a meta query to discover row groups and their category counts
525
- * 3. For each group: generate header row, data rows, REST overflow row, and group sum row
526
- * 4. Append a total sum row (if table type requires it)
527
- * 5. Execute all accumulated SQL statements against the input data
528
- * 6. Detect NaN cells (aggregated cells with zero contributing rows)
529
- * 7. Inject thereof/partof drill rows and column-level drill columns
530
- * 8. Calculate REST columns (parent minus drilled children)
531
- * 9. Divide absolute variances by their denominator to produce relative variances
532
- *
533
- * @returns Array of row-group segments; each segment is an array of result rows.
534
- */
535
- execute(data) {
536
- if (data.length === 0) {
537
- return [];
538
- }
539
- const queries = [];
540
- const sumGroupQueries = [];
541
- const res = [];
542
- const scenarios = this.config.scenarios
543
- .map((s) => this.translateScenarioSQL(s, false, this.config.type))
544
- .toString();
545
- const scenariosSUMQuery = this.config.scenarios
546
- .map((s) => this.translateScenarioSQL(s, true, this.config.type))
547
- .toString();
548
- const relativeScenarios = this.getRelativeScenarios();
549
- const groups = new QueryGroups(this.config);
550
- const groupsAggregated = this.config.grouped ? [formatter.QueryColumnNames.ROWGROUP, formatter.QueryColumnNames.ROWGROUPINDEX] : [];
551
- let order = ["", ""];
552
- if (this.config.sortOrder.hierarchy.length > 0) {
553
- order = this.createOrderString(this.config.sortOrder);
554
- }
555
- this.hasPartOf = this.checkConfigForPartOf();
556
- // meta defines groups and the number detail rows in each group
557
- // Bsp: 0: Object { totalrowcnt: 7, rowgroup: "Umsatz" }
558
- const meta = alasql_min.alasql(`SELECT COUNT(DISTINCT ${formatter.QueryColumnNames.CATEGORY}) as ${formatter.QueryColumnNames.TOTALROWCOUNT} ${groupsAggregated.length > 0 ? "," + groupsAggregated : ""}
559
- FROM ? ${groupsAggregated.length > 0 ? "GROUP BY " + groupsAggregated : ""}
560
- ORDER BY ${order[0]}`, [data]);
561
- // Creates DataSelection for LIST
562
- meta.forEach((rowGroupEntry) => {
563
- // the following variables are 'helper sections' which are used to constuct dynamicly the sql statement depending of the given config
564
- // is grouping active?
565
- const queryWhereSection = rowGroupEntry.rowGroup && rowGroupEntry.rowGroup.length > 0
566
- ? `WHERE ${formatter.QueryColumnNames.ROWGROUP} = '${rowGroupEntry.rowGroup}'`
567
- : ``;
568
- // is limit active?
569
- let queryLimitSection = "";
570
- if (this.config.limit) {
571
- queryLimitSection = `LIMIT ${this.config.limit}`;
572
- }
573
- this.createGroupHeaderRow(rowGroupEntry, queries);
574
- this.createDataRow(queries, rowGroupEntry, groups, scenarios, queryWhereSection, order, queryLimitSection);
575
- this.createRestRow(rowGroupEntry, queries, groups, scenarios, queryWhereSection, order);
576
- this.createGroupSumRow(queries, sumGroupQueries, rowGroupEntry, scenariosSUMQuery, order);
577
- });
578
- this.createTotalSumRow(queries, sumGroupQueries, scenariosSUMQuery);
579
- // executes main queries
580
- queries.forEach((query) => {
581
- try {
582
- res.push(alasql_min.alasql(query, [data]));
583
- }
584
- catch (err) {
585
- console.error("DataQuery: SQL query execution failed", query, err);
586
- }
587
- });
588
- this.detectNaNCells(this.config.scenarios, res);
589
- this.createThereOfDrillRows(scenarios, order, data, res);
590
- this.createPartOfDrillRows(scenarios, order, sumGroupQueries, data, res);
591
- this.createThereOfDrillColumns(this.config.categoryThereOf, data, res);
592
- this.calculateColumnGroupRest(res, this.config.categoryThereOf);
593
- this.calculateRelativeVariances(res, relativeScenarios);
594
- return res;
595
- }
596
- /**
597
- * Marks aggregated cells as NaN when no source rows contributed to the sum.
598
- *
599
- * Without this step, SUM() over zero matching rows would produce 0, which is
600
- * misleading -- it would be indistinguishable from an actual zero value.
601
- * Each scenario column has a companion `_cnt` counter; when that counter is 0
602
- * the cell is overwritten with NaN. For variance scenarios, both base and delta
603
- * counters must be non-zero.
604
- */
605
- detectNaNCells(scenarios, res) {
606
- res.forEach((group) => {
607
- group.map((row) => {
608
- scenarios.forEach((scenario) => {
609
- const varianceScenario = new formatter.VarianceScenario(scenario);
610
- if (varianceScenario.isValid === true) {
611
- if (row[varianceScenario.base + "_cnt"] === 0 || row[varianceScenario.delta + "_cnt"] === 0) {
612
- row[scenario] = Number.NaN;
613
- }
614
- }
615
- else {
616
- if (row[scenario + "_cnt"] === 0) {
617
- row[scenario] = Number.NaN;
618
- }
619
- }
620
- });
621
- return row;
622
- });
623
- });
624
- }
625
- /**
626
- * Creates "part-of" drill rows that express each category's value as a fraction
627
- * of its row group sum. Queries the drill subset, then divides each scenario
628
- * value by the corresponding group sum to produce a percentage.
629
- */
630
- createPartOfDrillRows(scenarios, order, sumGroupQueries, data, res) {
631
- if (this.config.partOf == null ||
632
- this.config.partOf.length === 0 ||
633
- this.config.type === index.TableType.LIST ||
634
- data == null ||
635
- data.length === 0) {
636
- return;
637
- }
638
- const drillQueries = this.createPartOfQuery(scenarios, order);
639
- let resDrill = []; // set of drill (subquery result injected into resultset)
640
- drillQueries.forEach(function (query) {
641
- resDrill.push(...alasql_min.alasql(query, [data]));
642
- });
643
- const scenarioNames = this.exctractScenarioNames(scenarios);
644
- const rowGroupSumResultRows = [];
645
- sumGroupQueries.forEach(function (query) {
646
- rowGroupSumResultRows.push(...alasql_min.alasql(query, [data]));
647
- });
648
- const rowGroupSumResultMap = new Map();
649
- rowGroupSumResultRows.forEach((row) => rowGroupSumResultMap.set(row[formatter.QueryColumnNames.ROWGROUP], row));
650
- resDrill = this.reduceResDrillByCategoryGroups(resDrill, scenarioNames);
651
- resDrill.forEach(function (drillItem) {
652
- scenarioNames.forEach((key) => {
653
- try {
654
- drillItem[key] =
655
- drillItem[key] /
656
- rowGroupSumResultMap.get(drillItem[formatter.QueryColumnNames.ROWGROUP])[key];
657
- }
658
- catch (err) {
659
- console.error("DataQuery: partOf drill row calculation failed", key, err);
660
- drillItem[key] = Number.NaN;
661
- }
662
- });
663
- });
664
- this.injectDrillRowsToResultRows(resDrill, res);
665
- }
666
- /**
667
- * Generates a REST row that aggregates all data rows beyond the configured limit.
668
- * Only emitted when a limit is set and the group has more rows than the limit.
669
- */
670
- createRestRow(rowGroupEntry, querys, groups, scenarios, queryWhereSection, order) {
671
- // Generates REST Row; sumsup the Bottom (total number of rows - limit)
672
- if (rowGroupEntry.totalRowCnt - this.config.limit > 0 && this.config.limit !== 0) {
673
- const rest_scenarios = ", SUM(ac1) as ac1, SUM(pp1) as pp1, SUM(dpp1_ac1_pos) as dpp1_ac1_pos, SUM(drpp1_ac1_pos) as drpp1_ac1_pos, SUM(dr_pp1)";
674
- querys.push(`SELECT ${formatter.QueryColumnNames.ROWNR}, 1 as ${formatter.QueryColumnNames.ROWGROUPINDEX} , 'ENTRY' as ${formatter.QueryColumnNames.TYPE}, 'NO_GROUP' as ${formatter.QueryColumnNames.ROWGROUP}, 'REST' as ${formatter.QueryColumnNames.CATEGORY} ${rest_scenarios} as dr_pp1 FROM` +
675
- ` (SELECT ROWNUM() AS ${formatter.QueryColumnNames.ROWNR}, ${querys.length} as ${formatter.QueryColumnNames.ROWGROUPINDEX} , 'ENTRY' as ${formatter.QueryColumnNames.TYPE}, '${rowGroupEntry.rowGroup || "NO_GROUP"}' as ${formatter.QueryColumnNames.ROWGROUP}, ${groups} ${scenarios.length > 0 ? ",".concat(scenarios) : ""} FROM ? ${queryWhereSection} GROUP BY ${groups} ORDER BY ${order[0]})` +
676
- ` t WHERE t.rowNr > ${this.config.limit}`);
677
- }
678
- }
679
- /** Generates the main data rows for a single row group, applying GROUP BY, ORDER, and LIMIT. */
680
- createDataRow(querys, rowGroupEntry, groups, scenarios, queryWhereSection, order, queryLimitSection) {
681
- // Generates DataRows
682
- querys.push(`SELECT ROWNUM() AS ${formatter.QueryColumnNames.ROWNR},
683
- ${querys.length} as ${formatter.QueryColumnNames.ROWGROUPINDEX},
684
- 'ENTRY' as ${formatter.QueryColumnNames.TYPE},
685
- '${rowGroupEntry.rowGroup || "NO_GROUP"}' as ${formatter.QueryColumnNames.ROWGROUP},
686
- '${formatter.QueryColumnNames.CATEGORYINDEX}',
687
- ${groups} ${scenarios.length > 0 ? ",".concat(scenarios) : ""}
688
- FROM ? ${queryWhereSection}
689
- GROUP BY ${groups}
690
- ORDER BY ${order[0]} ${queryLimitSection}`);
691
- }
692
- /** Generates a GROUPHEAD row used as a visual header when row grouping is active. */
693
- createGroupHeaderRow(rowGroupEntry, querys) {
694
- // Generates GroupHeader Row
695
- if (true === this.config.grouped) {
696
- const groupTitle = this.config.showGroupTitle
697
- ? `,'${rowGroupEntry.rowGroup}' as ${formatter.QueryColumnNames.CATEGORY}`
698
- : "";
699
- querys.push(`SELECT ROWNUM() AS ${formatter.QueryColumnNames.ROWNR},
700
- ${querys.length} as ${formatter.QueryColumnNames.ROWGROUPINDEX},
701
- 'GROUPHEAD' as ${formatter.QueryColumnNames.TYPE},
702
- '${rowGroupEntry.rowGroup}' as ${formatter.QueryColumnNames.ROWGROUP} ${groupTitle}
703
- FROM ?
704
- GROUP BY '1'`);
705
- }
706
- }
707
- /** Generates a GROUP_SUM row that aggregates all entries within a single row group. */
708
- createGroupSumRow(querys, groupSumQuery, rowGroupEntry, scenariosSUMQuery, order) {
709
- // Generates SUM Row; sumsup all rows of group
710
- if (true === this.config.grouped &&
711
- (index.TableType.SUM === this.config.type ||
712
- index.TableType.SUMNOTOTAL === this.config.type ||
713
- index.TableType.OPT === this.config.type ||
714
- index.TableType.OPTNOTOTAL === this.config.type)) {
715
- querys.push(`SELECT ${querys.length} as ${formatter.QueryColumnNames.ROWGROUPINDEX},
716
- '=' as ${formatter.QueryColumnNames.OPERATION},
717
- '${rowGroupEntry.rowGroup}' as ${formatter.QueryColumnNames.ROWGROUP},
718
- ROWNUM() AS ${formatter.QueryColumnNames.ROWNR},
719
- 'GROUP_SUM' as ${formatter.QueryColumnNames.TYPE} ${scenariosSUMQuery.length > 0 ? ",".concat(scenariosSUMQuery) : ""}
720
- FROM ?
721
- WHERE ${formatter.QueryColumnNames.ROWGROUP} = '${rowGroupEntry.rowGroup}'
722
- ORDER BY ${order[0]} `);
723
- groupSumQuery.push(`SELECT ${querys.length} as ${formatter.QueryColumnNames.ROWGROUPINDEX},
724
- '=' as ${formatter.QueryColumnNames.OPERATION},
725
- '${rowGroupEntry.rowGroup}' as ${formatter.QueryColumnNames.ROWGROUP},
726
- ROWNUM() AS ${formatter.QueryColumnNames.ROWNR},
727
- 'GROUP_SUM' as ${formatter.QueryColumnNames.TYPE} ${scenariosSUMQuery.length > 0 ? ",".concat(scenariosSUMQuery) : ""}
728
- FROM ?
729
- WHERE ${formatter.QueryColumnNames.ROWGROUP} = '${rowGroupEntry.rowGroup}'
730
- ORDER BY ${order[0]} `);
731
- }
732
- }
733
- /** Generates a total SUM row across all groups (only for SUM / OPT table types). */
734
- createTotalSumRow(querys, sumGroupQueries, scenariosSUMQuery) {
735
- if (index.TableType.SUM === this.config.type || index.TableType.OPT === this.config.type) {
736
- const title = `${this.hasPartOf && this.config.grouped === false ? `${this.i18n.get("SUM_TOTAL") || "SUM_TOTAL"} ` : ""}${this.config.title}`;
737
- querys.push(`SELECT ${querys.length} as ${formatter.QueryColumnNames.ROWGROUPINDEX},
738
- '${title}' as ${formatter.QueryColumnNames.ROWGROUP},
739
- '=' as ${formatter.QueryColumnNames.OPERATION},
740
- 'SUM' as ${formatter.QueryColumnNames.TYPE} ${scenariosSUMQuery.length > 0 ? ",".concat(scenariosSUMQuery) : ""}
741
- FROM ? `);
742
- }
743
- sumGroupQueries.push(`SELECT ${querys.length} as ${formatter.QueryColumnNames.ROWGROUPINDEX},
744
- 'SUM_TOTAL' as ${formatter.QueryColumnNames.ROWGROUP},
745
- '=' as ${formatter.QueryColumnNames.OPERATION},
746
- 'SUM' as ${formatter.QueryColumnNames.TYPE} ${scenariosSUMQuery.length > 0 ? ",".concat(scenariosSUMQuery) : ""}
747
- FROM ? `);
748
- }
749
- /**
750
- * Manually merges drill rows that AlaSQL fails to aggregate correctly.
751
- * Groups by composite key (rowNr + rowGroup + type + category) and sums scenario values.
752
- */
753
- reduceResDrillByCategoryGroups(resDrill, scenarioNames) {
754
- // This is workarround because alasql is not merging the rows as expected.
755
- const tmpSumMap = new Map();
756
- resDrill.forEach(function (drillItem) {
757
- const key = drillItem.rowNr + drillItem.rowGroup + drillItem.type + drillItem.category;
758
- if (tmpSumMap.has(key)) {
759
- const element = tmpSumMap.get(key);
760
- scenarioNames.forEach((key) => {
761
- try {
762
- element[key] += drillItem[key];
763
- }
764
- catch (e) {
765
- console.error("DataQuery: drill row aggregation failed", key, e);
766
- }
767
- });
768
- }
769
- else {
770
- tmpSumMap.set(key, drillItem);
771
- }
772
- });
773
- return [...tmpSumMap.values()];
774
- }
775
- /**
776
- * Inserts drill (thereof/partof) rows into the result set directly after their
777
- * parent category row. Handles both grouped and ungrouped modes, disambiguating
778
- * duplicate subCategory names by appending the rowGroup in parentheses.
779
- */
780
- injectDrillRowsToResultRows(resDrill, res) {
781
- // resDrill = resDrill.reverse();
782
- const numberOfElement = new Map();
783
- if (this.config.grouped === true) {
784
- // finds ParentElement of Drill Element and injects into result arra
785
- resDrill.forEach(function (drillItem) {
786
- res.forEach(function (resSegment) {
787
- const index = resSegment.findIndex((e) => e.category === drillItem.category && e.rowGroup === drillItem.rowGroup);
788
- if (index >= 0) {
789
- if (numberOfElement.has(`${drillItem.category}_${drillItem.rowGroup}`)) {
790
- const num = numberOfElement.get(`${drillItem.category}_${drillItem.rowGroup}`) || 0;
791
- numberOfElement.set(`${drillItem.category}_${drillItem.rowGroup}`, num + 1);
792
- }
793
- else {
794
- numberOfElement.set(`${drillItem.category}_${drillItem.rowGroup}`, 1);
795
- }
796
- drillItem[formatter.QueryColumnNames.ROWNR] = numberOfElement.get(`${drillItem.category}_${drillItem.rowGroup}`);
797
- resSegment.splice(index + drillItem[formatter.QueryColumnNames.ROWNR], 0, drillItem);
798
- }
799
- });
800
- });
801
- }
802
- else {
803
- // if no grouped mode selected matching only searching for category not for groupname
804
- const duplicateSubCategoriesList = this.findDuplicateSubCategories(resDrill);
805
- resDrill.forEach(function (drillItem) {
806
- res.forEach(function (resSegment) {
807
- const index = resSegment.findIndex((e) => e.category != null && e.category === drillItem.category);
808
- if (index >= 0) {
809
- if (numberOfElement.has(`${drillItem.category}`)) {
810
- const num = numberOfElement.get(`${drillItem.category}`) || 0;
811
- numberOfElement.set(`${drillItem.category}`, num + 1);
812
- }
813
- else {
814
- numberOfElement.set(`${drillItem.category}`, 1);
815
- }
816
- if (drillItem[formatter.QueryColumnNames.ROWNR] === 1) {
817
- drillItem.subCategory = `${drillItem.subCategory} (${drillItem.rowGroup})`;
818
- }
819
- else if (duplicateSubCategoriesList.includes(drillItem.subCategory)) {
820
- drillItem.subCategory = `${drillItem.subCategory} (${drillItem.rowGroup})`;
821
- }
822
- resSegment.splice(index + drillItem[formatter.QueryColumnNames.ROWNR], 0, drillItem);
823
- }
824
- });
825
- });
826
- }
827
- }
828
- /**
829
- * Creates "thereof" drill rows -- sub-breakdowns shown with absolute values
830
- * beneath their parent category row. Each thereof config entry produces a
831
- * filtered/grouped SQL query whose results are spliced into the result set.
832
- */
833
- createThereOfDrillRows(scenarios, order, data, res) {
834
- // adds drill rows if setup in config
835
- // if there of is set drilldown row is displayed with absolute numbers,
836
- // if part of is also not null a relative percenatage based of the selected basis is displayed
837
- if (this.config.thereOf === undefined || this.config.thereOf.length === 0) {
838
- return;
839
- }
840
- const drillQueries = [];
841
- const resDrill = []; // set of drill (subquery result injected into resultset)
842
- // let rollgroups = ['category']; // frage wo kommt das her ?
843
- // create drill queryies based on config
844
- this.config.thereOf.forEach((element) => {
845
- let isFirst = true;
846
- let fromString = "1 <> 1 OR ( "; // helper for strin concat 1<>1 OR ... OR ...
847
- if (!(null == element.category || 0 === element.category.length || !element.category.trim())) {
848
- // if not empty
849
- fromString += ` ${formatter.QueryColumnNames.CATEGORY} = '${element.category}'`;
850
- isFirst = false;
851
- }
852
- if (!(null == element.rowGroup || 0 === element.rowGroup.length || !element.rowGroup.trim())) {
853
- // if not empty
854
- fromString += ` ${isFirst ? "" : "AND"} ${formatter.QueryColumnNames.ROWGROUP} = '${element.rowGroup}'`;
855
- isFirst = false;
856
- }
857
- if (!(null == element.subCategory || 0 === element.subCategory.length || !element.subCategory.trim())) {
858
- // if not empty
859
- fromString += ` ${isFirst ? "" : "AND"} ${formatter.QueryColumnNames.SUBCATEGORY} = '${element.subCategory}'`;
860
- }
861
- fromString += `)`;
862
- drillQueries.push(`SELECT ROWNUM() AS ${formatter.QueryColumnNames.ROWNR},
863
- null as operation,
864
- 'DRILLELEMENT' as ${formatter.QueryColumnNames.TYPE},
865
- ${formatter.QueryColumnNames.CATEGORY},
866
- ${formatter.QueryColumnNames.SUBCATEGORY},
867
- ${formatter.QueryColumnNames.ROWGROUP} as ${formatter.QueryColumnNames.ROWGROUP},
868
- ${scenarios}
869
- FROM ?
870
- WHERE ${fromString}
871
- GROUP BY ${formatter.QueryColumnNames.ROWGROUP}, ${formatter.QueryColumnNames.CATEGORY}, ${formatter.QueryColumnNames.SUBCATEGORY}
872
- ORDER BY ${order[1]}`);
873
- });
874
- // invertet Sort directon because the later used insertion which results into expected order direction
875
- //drillQueries.push(`SELECT ROWNUM() AS ${QueryColumnNames.ROWNR}, null as operation, 'DRILLELEMENT' as ${QueryColumnNames.TYPE}, ${QueryColumnNames.CATEGORY}, ${QueryColumnNames.SUBCATEGORY}, ${QueryColumnNames.ROWGROUP} as ${QueryColumnNames.ROWGROUP} , ${scenarios} FROM ? WHERE ${fromString} GROUP BY ${QueryColumnNames.ROWGROUP}, ${QueryColumnNames.CATEGORY}, ${QueryColumnNames.SUBCATEGORY} ORDER BY ${order[1]}`);
876
- drillQueries.forEach(function (query) {
877
- resDrill.push(...alasql_min.alasql(query, [data]));
878
- });
879
- this.injectDrillRowsToResultRows(resDrill, res);
880
- }
881
- /**
882
- * Converts absolute variance columns into relative (percentage) variances by dividing
883
- * each `dr_*` cell by its denominator column (the delta scenario's aggregated value).
884
- */
885
- calculateRelativeVariances(res, relativeScenarios) {
886
- res.forEach((group) => {
887
- group.forEach((row) => {
888
- if (row[formatter.QueryColumnNames.TYPE] !== "GROUPHEAD") {
889
- relativeScenarios.forEach((value, key) => {
890
- row[key] = row[key] / row[value];
891
- });
892
- }
893
- });
894
- });
895
- }
896
- /**
897
- * Calculates REST columns for column-level thereof drills.
898
- * REST = parent scenario value minus sum of all drilled child columns.
899
- * Columns where REST is zero across all rows are removed entirely.
900
- */
901
- calculateColumnGroupRest(res, categoryThereOf) {
902
- if (categoryThereOf == null || categoryThereOf.size === 0) {
903
- return;
904
- }
905
- const scenarioRestMap = new Map();
906
- const scenarioRestHasValuesMap = new Map();
907
- categoryThereOf.forEach((value, key) => {
908
- const categoryDrills = value;
909
- const columnsList = [];
910
- for (const drillElement of categoryDrills) {
911
- columnsList.push(`${key}##${drillElement.name}`);
912
- }
913
- scenarioRestMap.set(key, columnsList);
914
- scenarioRestHasValuesMap.set(`${key}##REST`, false);
915
- });
916
- res.forEach((group) => {
917
- group.forEach((row) => {
918
- if (row[formatter.QueryColumnNames.TYPE] !== "GROUPHEAD") {
919
- scenarioRestMap.forEach((values, key) => {
920
- let minuent = 0;
921
- values.forEach((value) => {
922
- if (row[value] !== undefined) {
923
- minuent += row[value];
924
- }
925
- });
926
- row[`${key}##REST`] = row[key] - minuent;
927
- if (row[`${key}##REST`] !== 0) {
928
- scenarioRestHasValuesMap.set(`${key}##REST`, true);
929
- }
930
- });
931
- }
932
- });
933
- });
934
- const emptyRestColumns = Array.from(scenarioRestHasValuesMap.entries())
935
- .filter(([_key, value]) => !value)
936
- .map(([key]) => key);
937
- res.forEach((group) => {
938
- group.forEach((row) => {
939
- for (const deleteColumn of emptyRestColumns) {
940
- delete row[deleteColumn];
941
- }
942
- });
943
- });
944
- }
945
- /** Collects all relative variance scenarios and maps each to its denominator column name. */
946
- getRelativeScenarios() {
947
- const relativeScenarios = new Map();
948
- this.config.scenarios.forEach((s) => {
949
- const tmp = this.createRelativeScenario(s);
950
- if (tmp != null) {
951
- relativeScenarios.set(tmp.key, tmp.value);
952
- }
953
- });
954
- return relativeScenarios;
955
- }
956
- /**
957
- * Translates a scenario identifier into a SQL aggregation expression.
958
- *
959
- * - **OPT/OPTNOTOTAL types**: Values are summed without `transformOperator` (the
960
- * operation sign is already baked into the data). Variance scenarios produce
961
- * `SUM(base - delta)`.
962
- * - **Other types**: Each value is multiplied by `transformOperator(operation)` which
963
- * converts the `"+"` / `"-"` operation field into +1 / -1, so rows with negative
964
- * operation are subtracted from the aggregate.
965
- * - **Relative variances** (`dr_*`): additionally select the delta denominator column
966
- * so `calculateRelativeVariances` can divide later.
967
- * - A companion `_cnt` column (COUNT of non-null values) is emitted for NaN detection.
968
- */
969
- translateScenarioSQL(scenario, isSumRow, type) {
970
- const scenarios = new formatter.VarianceScenario(scenario);
971
- if (index.TableType.OPT === type || index.TableType.OPTNOTOTAL === type) {
972
- if (scenarios.isValid) {
973
- if (scenarios.type === "dr") {
974
- return `SUM(${scenarios.base} - ${scenarios.delta}) as ${scenario}, SUM(${scenarios.delta}) as dr_${scenarios.delta}`;
975
- }
976
- else {
977
- return `SUM(${scenarios.base} - ${scenarios.delta}) as ${scenario}`;
978
- }
979
- }
980
- if (isSumRow) {
981
- return `SUM(${scenario} * transformOperator(operation)) as ${scenario}, COUNT(ISNULL(${scenario})) as ${scenario}_cnt`;
982
- }
983
- return `SUM(${scenario}) as ${scenario}, COUNT(ISNULL(${scenario})) as ${scenario}_cnt`;
984
- }
985
- if (scenarios.isValid) {
986
- if (scenarios.type === "dr") {
987
- return `SUM((${scenarios.base} * transformOperator(operation)) - (${scenarios.delta} * transformOperator(operation))) as ${scenario}, SUM(${scenarios.delta} * transformOperator(operation)) as dr_${scenarios.delta}`;
988
- }
989
- else {
990
- return `SUM((${scenarios.base} * transformOperator(operation))- (${scenarios.delta} * transformOperator(operation))) as ${scenario}`;
991
- }
992
- }
993
- return `SUM(${scenario} * transformOperator(operation)) as ${scenario}, COUNT(ISNULL(${scenario})) as ${scenario}_cnt`;
994
- }
995
- /**
996
- * generates Tuple
997
- * [0] orderby string example: category asc
998
- * [1] inverted order example: category desc
999
- * @param orderComponent
1000
- */
1001
- createOrderString(orderComponent) {
1002
- const base = `${orderComponent.hierarchy.toString()} ${orderComponent.direction}`;
1003
- const inverted = `${orderComponent.hierarchy.toString()} ${index.OrderDirection.ASC === orderComponent.direction ? index.OrderDirection.DESC : index.OrderDirection.ASC}`;
1004
- return [base, inverted];
1005
- }
1006
- /** Returns a key/value pair mapping a relative variance column to its denominator, or null for non-relative scenarios. */
1007
- createRelativeScenario(scenario) {
1008
- const scenarios = new formatter.VarianceScenario(scenario);
1009
- if (scenarios.isValid && scenarios.type === "dr") {
1010
- return { key: `${scenario}`, value: `dr_${scenarios.delta}` };
1011
- }
1012
- return null;
1013
- }
1014
- /** Parses the comma-separated SQL scenario fragment to extract the alias names (the part after `as`). */
1015
- exctractScenarioNames(scenarios) {
1016
- const scenarioNames = [];
1017
- scenarios.split(",").forEach((item) => (item.length >= 2 ? scenarioNames.push(item.split("as")[1].trim()) : null));
1018
- return scenarioNames;
1019
- }
1020
- /** Identifies subCategory values that appear more than once in the drill set, requiring disambiguation. */
1021
- findDuplicateSubCategories(resDrill) {
1022
- const uniq = resDrill
1023
- .map((element) => {
1024
- return {
1025
- count: 1,
1026
- subCategory: element.subCategory,
1027
- };
1028
- })
1029
- .reduce((a, b) => {
1030
- a[b.subCategory] = (a[b.subCategory] || 0) + b.count;
1031
- return a;
1032
- }, {});
1033
- return Object.keys(uniq).filter((a) => uniq[a] > 1);
1034
- }
1035
- /** Builds the SQL query for partof drill rows, filtering to configured partOf categories. */
1036
- createPartOfQuery(scenarios, order) {
1037
- var _a;
1038
- const drillQueries = [];
1039
- let fromString = "1 <> 1 "; // helper for strin concat 1<>1 OR ... OR ...
1040
- let groupName = ` ${formatter.QueryColumnNames.ROWGROUP}`;
1041
- let rowNum = "ROWNUM()";
1042
- (_a = this.config.partOf) === null || _a === void 0 ? void 0 : _a.forEach((element) => {
1043
- fromString += `OR (${formatter.QueryColumnNames.CATEGORY} = '${element.category}'`;
1044
- if (!(null == element.rowGroup || 0 === element.rowGroup.length || !element.rowGroup.trim())) {
1045
- // if not empty
1046
- fromString += `and ${formatter.QueryColumnNames.ROWGROUP} = '${element.rowGroup}'`;
1047
- }
1048
- if (this.config.grouped === false) {
1049
- groupName = ` 'SUM_TOTAL' as ${formatter.QueryColumnNames.ROWGROUP} `;
1050
- rowNum = "1";
1051
- }
1052
- fromString += `)`;
1053
- });
1054
- // let dimensionGroups = `${QueryColumnNames.CATEGORY}, ${QueryColumnNames.SUBCATEGORY}, ${QueryColumnNames.ROWGROUP}`;
1055
- // invertet Sort directon because the later used insertion which results into expected order direction
1056
- drillQueries.push(`SELECT ${rowNum} AS ${formatter.QueryColumnNames.ROWNR},
1057
- 'PARTELEMENT' as ${formatter.QueryColumnNames.TYPE},
1058
- ${formatter.QueryColumnNames.CATEGORY},
1059
- ${groupName},
1060
- ${scenarios}
1061
- FROM ?
1062
- WHERE ${fromString}
1063
- GROUP BY ${formatter.QueryColumnNames.ROWGROUP}, ${formatter.QueryColumnNames.CATEGORY}, ${formatter.QueryColumnNames.TYPE}
1064
- ORDER BY ${order[1]}`);
1065
- return drillQueries;
1066
- }
1067
- checkConfigForPartOf() {
1068
- if (this.config.partOf == null || this.config.partOf.length === 0) {
1069
- return false;
1070
- }
1071
- return true;
1072
- }
1073
- /**
1074
- * Creates column-level thereof drill breakdowns for the configured `categoryThereOf` map.
1075
- *
1076
- * For each scenario key, queries are generated at multiple aggregation levels
1077
- * (ENTRY, DRILLELEMENT, GROUP_SUM, SUM) crossed with column dimensions
1078
- * (COLUMNGROUP, SUBGROUP). Results are stored as new properties on existing
1079
- * result rows using the `"##"` separator convention: `scenario##columnGroup` or
1080
- * `scenario##columnGroup##columnSubGroup`.
1081
- */
1082
- createThereOfDrillColumns(categoryThereOf, data, res) {
1083
- if (categoryThereOf == null || categoryThereOf.size === 0) {
1084
- return;
1085
- }
1086
- const drillQueries = [];
1087
- const resDrill = [];
1088
- categoryThereOf.forEach((value, key) => {
1089
- let whereClause = "1 <> 1 ";
1090
- value.forEach((drillColumn) => {
1091
- whereClause += ` or columnGroup = '${drillColumn.name}' `;
1092
- });
1093
- drillQueries.push(`SELECT 'ENTRY' as rowlevel,
1094
- 'COLUMNGROUP' as columnlevel,
1095
- rowGroup,
1096
- category,
1097
- columnGroup,
1098
- '${key}' as scenario,
1099
- sum(${key} * transformOperator(operation)) as val
1100
- FROM ?
1101
- WHERE ${whereClause}
1102
- GROUP BY rowlevel, rowGroup, category, columnGroup, scenario`);
1103
- drillQueries.push(`SELECT 'ENTRY' as rowlevel,
1104
- 'SUBGROUP' as columnlevel,
1105
- rowGroup,
1106
- category,
1107
- columnGroup,
1108
- columnSubGroup,
1109
- '${key}' as scenario,
1110
- sum(${key} * transformOperator(operation)) as val
1111
- FROM ?
1112
- WHERE ${whereClause}
1113
- GROUP BY rowlevel, rowGroup, category, columnGroup, columnSubGroup, scenario`);
1114
- drillQueries.push(`SELECT 'DRILLELEMENT' as rowlevel,
1115
- 'COLUMNGROUP' as columnlevel,
1116
- rowGroup,
1117
- category,
1118
- subCategory,
1119
- columnGroup,
1120
- '${key}' as scenario,
1121
- sum(${key} * transformOperator(operation)) as val
1122
- FROM ?
1123
- WHERE ${whereClause}
1124
- GROUP BY rowlevel, rowGroup, category, subCategory, columnGroup, scenario`);
1125
- drillQueries.push(`SELECT 'DRILLELEMENT' as rowlevel,
1126
- 'SUBGROUP' as columnlevel,
1127
- rowGroup,
1128
- category,
1129
- subCategory,
1130
- columnGroup,
1131
- columnSubGroup,
1132
- '${key}' as scenario,
1133
- sum(${key} * transformOperator(operation)) as val
1134
- FROM ?
1135
- WHERE ${whereClause}
1136
- GROUP BY rowlevel, rowGroup, category, subCategory, columnGroup, columnSubGroup, scenario`);
1137
- drillQueries.push(`SELECT 'GROUP_SUM' as rowlevel,
1138
- 'COLUMNGROUP' as columnlevel,
1139
- rowGroup,
1140
- columnGroup,
1141
- '${key}' as scenario,
1142
- sum(${key} * transformOperator(operation)) as val
1143
- FROM ?
1144
- WHERE ${whereClause}
1145
- GROUP BY rowlevel, rowGroup, columnGroup, scenario`);
1146
- drillQueries.push(`SELECT 'GROUP_SUM' as rowlevel,
1147
- 'SUBGROUP' as columnlevel,
1148
- rowGroup,
1149
- columnGroup,
1150
- columnSubGroup,
1151
- '${key}' as scenario,
1152
- sum(${key} * transformOperator(operation)) as val
1153
- FROM ?
1154
- WHERE ${whereClause}
1155
- GROUP BY rowlevel, rowGroup, columnGroup, columnSubGroup, scenario`);
1156
- drillQueries.push(`SELECT 'SUM' as rowlevel,
1157
- 'COLUMNGROUP' as columnlevel,
1158
- columnGroup,
1159
- '${key}' as scenario,
1160
- sum(${key} * transformOperator(operation)) as val
1161
- FROM ?
1162
- WHERE ${whereClause}
1163
- GROUP BY rowlevel, columnGroup, scenario`);
1164
- drillQueries.push(`SELECT 'SUM' as rowlevel,
1165
- 'SUBGROUP' as columnlevel,
1166
- columnGroup,
1167
- columnSubGroup,
1168
- '${key}' as scenario,
1169
- sum(${key} * transformOperator(operation)) as val
1170
- FROM ?
1171
- WHERE ${whereClause}
1172
- GROUP BY rowlevel, columnGroup, columnSubGroup, scenario`);
1173
- });
1174
- for (const query of drillQueries) {
1175
- resDrill.push(...alasql_min.alasql(query, [data]));
1176
- }
1177
- this.injectDrillColumnsToResultRows(resDrill, res);
1178
- }
1179
- /**
1180
- * Merges column-drill query results into existing result rows by matching
1181
- * row type, category, subCategory, and rowGroup. Uses the `"##"` separator
1182
- * to form composite property keys for drill column values.
1183
- */
1184
- injectDrillColumnsToResultRows(resDrill, res) {
1185
- const separator = "##";
1186
- for (const drillElement of resDrill) {
1187
- for (const tableSegment of res) {
1188
- for (const row of tableSegment) {
1189
- if (row.type !== drillElement.rowlevel) {
1190
- continue;
1191
- }
1192
- if ("ENTRY" === drillElement.rowlevel) {
1193
- if (drillElement.columnlevel === "COLUMNGROUP" && row.category === drillElement.category) {
1194
- row[drillElement.scenario + separator + drillElement.columnGroup] = drillElement.val;
1195
- }
1196
- else if (drillElement.columnlevel === "SUBGROUP" && row.category === drillElement.category) {
1197
- row[drillElement.scenario + separator + drillElement.columnGroup + separator + drillElement.columnSubGroup] = drillElement.val;
1198
- }
1199
- }
1200
- else if ("DRILLELEMENT" === drillElement.rowlevel) {
1201
- if (drillElement.columnlevel === "COLUMNGROUP" &&
1202
- row.category === drillElement.category &&
1203
- row.subCategory === drillElement.subCategory) {
1204
- row[drillElement.scenario + separator + drillElement.columnGroup] = drillElement.val;
1205
- }
1206
- else if (drillElement.columnlevel === "SUBGROUP" &&
1207
- row.category === drillElement.category &&
1208
- row.subCategory === drillElement.subCategory) {
1209
- row[drillElement.scenario + separator + drillElement.columnGroup + separator + drillElement.columnSubGroup] = drillElement.val;
1210
- }
1211
- else if (drillElement.columnlevel === "COLUMNGROUP" &&
1212
- row.category === drillElement.category &&
1213
- row.subCategory === `${drillElement.subCategory} (${drillElement.rowGroup})`) {
1214
- row[drillElement.scenario + separator + drillElement.columnGroup] = drillElement.val;
1215
- }
1216
- else if (drillElement.columnlevel === "SUBGROUP" &&
1217
- row.category === drillElement.category &&
1218
- row.subCategory === `${drillElement.subCategory} (${drillElement.rowGroup})`) {
1219
- row[drillElement.scenario + separator + drillElement.columnGroup + separator + drillElement.columnSubGroup] = drillElement.val;
1220
- }
1221
- }
1222
- else if ("SUM" === drillElement.rowlevel) {
1223
- if (drillElement.columnlevel === "COLUMNGROUP" &&
1224
- row.category === drillElement.category &&
1225
- row.subCategory === drillElement.subCategory) {
1226
- row[drillElement.scenario + separator + drillElement.columnGroup] = drillElement.val;
1227
- }
1228
- if (drillElement.columnlevel === "SUBGROUP" &&
1229
- row.category === drillElement.category &&
1230
- row.subCategory === drillElement.subCategory) {
1231
- row[drillElement.scenario + separator + drillElement.columnGroup + separator + drillElement.columnSubGroup] = drillElement.val;
1232
- }
1233
- }
1234
- else if ("GROUP_SUM" === drillElement.rowlevel) {
1235
- if (drillElement.columnlevel === "COLUMNGROUP" &&
1236
- row.category === drillElement.category &&
1237
- row.subCategory === drillElement.subCategory) {
1238
- row[drillElement.scenario + separator + drillElement.columnGroup] = drillElement.val;
1239
- }
1240
- if (drillElement.columnlevel === "SUBGROUP" &&
1241
- row.category === drillElement.category &&
1242
- row.subCategory === drillElement.subCategory) {
1243
- row[drillElement.scenario + separator + drillElement.columnGroup + separator + drillElement.columnSubGroup] = drillElement.val;
1244
- }
1245
- }
1246
- }
1247
- }
1248
- }
1249
- }
1250
- }
1251
-
1252
- /**
1253
- * Transforms raw query results into structured TableRow collections for header and body.
1254
- *
1255
- * Header normalization: prepends fixed columns (operation, category) to the configured
1256
- * scenarios, then translates labels via i18n and adds separator rows for IBCS-style borders.
1257
- *
1258
- * Body row creation: iterates DataQuery results grouped by rowGroup, creates detail rows
1259
- * with type-specific logic (GROUPHEAD, SUM, DRILLELEMENT, PARTELEMENT, ENTRY), and
1260
- * translates cell values/prefixes via i18n. Supports inline bar chart columns via
1261
- * columnStats calculation.
1262
- */
1263
- class TableDataSetFactory {
1264
- constructor() {
1265
- this.normalizedHeader = [];
1266
- }
1267
- /**
1268
- * Creates Tableheader based on the configured scenarios (in config)
1269
- * the created header is stored in the dataset json
1270
- * the lables are translated based on the used i18n map
1271
- * based on the structure of the scenarios 'spacer'coulumns are added, to
1272
- * visualise grouping.
1273
- * finally a seperator header row is created for the header underlining (border)
1274
- */
1275
- createHeader(type, scenarios, i18n, measureScale, measureUnit, showMeasureScale) {
1276
- const header = [];
1277
- this.normalizedHeader = this.normalizeHeader(type, scenarios);
1278
- const headerRow = new TableRow(0, 0, index.TableRowType.HEADER);
1279
- const separatorRow = new TableRow(1, 0, index.TableRowType.SEPERATORLINE);
1280
- for (const scenario of this.normalizedHeader) {
1281
- headerRow.createElement(formatter.Formatter.translateScenarioLabel(scenario.name, i18n), scenario.type, this.createColumnType(scenario), null, this.setHeaderPrefix(scenario, i18n, measureScale, measureUnit, showMeasureScale), null, null, null, null);
1282
- separatorRow.createElement(null, scenario.type, this.createColumnType(scenario), null, null, null, null, null, null);
1283
- }
1284
- header.push(headerRow);
1285
- header.push(separatorRow);
1286
- return header;
1287
- }
1288
- setHeaderPrefix(scenario, i18n, measureScale, measureUnit, showMeasureScale) {
1289
- let prefix = "";
1290
- if (scenario.name === "category" && showMeasureScale) {
1291
- if (measureScale.prefix.length !== 0 || measureUnit.length !== 0) {
1292
- prefix = formatter.Formatter.translateScenarioLabel("in", i18n) + " " + measureScale.prefix + measureUnit;
1293
- }
1294
- }
1295
- if (scenario.order) {
1296
- prefix += formatter.Formatter.translateScenarioLabel("ORDER_" + scenario.order, i18n);
1297
- }
1298
- return prefix;
1299
- }
1300
- /**
1301
- * combines the default columnnames (operation and category) with the
1302
- * configured scenarios.
1303
- * depending of table type operation column is used (OPT) or not (SUM | LIST)
1304
- * in addition the headers are sorted based on the ruleset and duplicates are removed
1305
- */
1306
- normalizeHeader(type, scenarios) {
1307
- let header = [
1308
- {
1309
- name: formatter.QueryColumnNames.CATEGORY,
1310
- group: formatter.QueryColumnNames.CATEGORY,
1311
- type: formatter.QueryColumnNames.CATEGORY,
1312
- order: undefined,
1313
- },
1314
- ];
1315
- if (index.TableType.OPT === type || index.TableType.OPTNOTOTAL === type) {
1316
- header = [
1317
- {
1318
- name: formatter.QueryColumnNames.OPERATION,
1319
- group: formatter.QueryColumnNames.OPERATION,
1320
- type: formatter.QueryColumnNames.OPERATION,
1321
- order: undefined,
1322
- },
1323
- {
1324
- name: formatter.QueryColumnNames.CATEGORY,
1325
- group: formatter.QueryColumnNames.CATEGORY,
1326
- type: formatter.QueryColumnNames.CATEGORY,
1327
- order: undefined,
1328
- },
1329
- ];
1330
- }
1331
- // NOTE: scenarios are already sorted in setConfig
1332
- return [...header, ...scenarios];
1333
- }
1334
- /**
1335
- * Creates table data colelction,
1336
- * eachh row consists of data columns and 'spacer' columns which are needed to seperate
1337
- * the columns correctyl (IBCS style)
1338
- */
1339
- createBodyRows(config, i18n, data) {
1340
- const bodyRows = [];
1341
- let iGroupIndex = -1; // index used in detailRow JSON to count the current group
1342
- const queryData = new DataQuery(config, i18n).execute(data); // collection of all query results
1343
- // Calculate column statistics for bar columns
1344
- const columnStatsMap = this.calculateColumnStatistics(queryData, config.barColumns);
1345
- for (const groupData of queryData) {
1346
- // groupData is a collection of dataRows, each group base on a query and represents a 'row' group
1347
- iGroupIndex += 1;
1348
- const iRowIndex = -1;
1349
- bodyRows.push(...this.createRow(config.i18n, i18n, config.scenariosUnitType, groupData, iGroupIndex, iRowIndex, config.categoryWidth, config.measureScale, config.barColumns, columnStatsMap));
1350
- }
1351
- return bodyRows;
1352
- }
1353
- /**
1354
- * Calculate min/max statistics for bar chart columns across all query data.
1355
- */
1356
- calculateColumnStatistics(queryData, barColumns) {
1357
- const statsMap = new Map();
1358
- if (!barColumns || barColumns.length === 0) {
1359
- return statsMap;
1360
- }
1361
- // Collect all values per column for median calculation
1362
- const valuesMap = new Map();
1363
- for (const column of barColumns) {
1364
- statsMap.set(column, { min: Infinity, max: -Infinity, absMax: 0, median: 0 });
1365
- valuesMap.set(column, []);
1366
- }
1367
- // Iterate through all groups and rows
1368
- for (const groupData of queryData) {
1369
- for (const row of groupData) {
1370
- for (const column of barColumns) {
1371
- const value = this.extractColumnValue(row, column);
1372
- if (value !== null && !isNaN(value)) {
1373
- const stats = statsMap.get(column);
1374
- stats.min = Math.min(stats.min, value);
1375
- stats.max = Math.max(stats.max, value);
1376
- valuesMap.get(column).push(Math.abs(value));
1377
- }
1378
- }
1379
- }
1380
- }
1381
- // Finalize absMax and median values
1382
- for (const [column, stats] of statsMap) {
1383
- if (stats.min === Infinity || stats.max === -Infinity) {
1384
- stats.min = 0;
1385
- stats.max = 0;
1386
- }
1387
- stats.absMax = Math.max(Math.abs(stats.min), Math.abs(stats.max));
1388
- const absValues = valuesMap.get(column);
1389
- if (absValues.length > 0) {
1390
- absValues.sort((a, b) => a - b);
1391
- const mid = Math.floor(absValues.length / 2);
1392
- stats.median = absValues.length % 2 === 0 ? (absValues[mid - 1] + absValues[mid]) / 2 : absValues[mid];
1393
- }
1394
- statsMap.set(column, stats);
1395
- }
1396
- return statsMap;
1397
- }
1398
- /**
1399
- * Extract a numeric value from a row for a given column name.
1400
- * Handles the various naming conventions used in the table data.
1401
- */
1402
- extractColumnValue(row, column) {
1403
- // Try direct access
1404
- if (row[column] !== undefined) {
1405
- const val = Number(row[column]);
1406
- return isNaN(val) ? null : val;
1407
- }
1408
- // Search for keys that match the column (handles scenario## prefix patterns)
1409
- for (const key of Object.keys(row)) {
1410
- if (key === column || key.endsWith("##" + column) || key === column + "##" + column) {
1411
- const val = Number(row[key]);
1412
- if (!isNaN(val)) {
1413
- return val;
1414
- }
1415
- }
1416
- }
1417
- return null;
1418
- }
1419
- /**
1420
- * Helper funciton to generate a new Table Row,
1421
- * it calls itsself recursive if a drilldown is set by the config file.
1422
- * a drilldown is detected if there is a colection of rows in .drill
1423
- *
1424
- * @param i18nMode
1425
- * @param i18n
1426
- * @param scenariosUnitType
1427
- * @param groupData
1428
- * @param iGroupIndex
1429
- * @param iRowIndex
1430
- * @param categoryWidth
1431
- * @param measureScale
1432
- * @param barColumns
1433
- * @param columnStatsMap
1434
- */
1435
- createRow(i18nMode, i18n, scenariosUnitType, groupData, iGroupIndex, iRowIndex, categoryWidth, measureScale, barColumns, columnStatsMap) {
1436
- var _a;
1437
- const result = [];
1438
- for (const rawDataRow of groupData) {
1439
- iRowIndex += 1;
1440
- // create next table row
1441
- const groupName = rawDataRow[formatter.QueryColumnNames.ROWGROUP];
1442
- const subCategory = rawDataRow[formatter.QueryColumnNames.SUBCATEGORY];
1443
- const type = rawDataRow[formatter.QueryColumnNames.TYPE];
1444
- const isSecondElement = rawDataRow[formatter.QueryColumnNames.ROWNR] >= 2;
1445
- const detailsRow = this.createDetailRow(type, iRowIndex, iGroupIndex, groupData.length);
1446
- for (const scenario of this.normalizedHeader) {
1447
- const value = this.getRawDataRowElement(rawDataRow, scenario);
1448
- const isBarChart = (_a = barColumns === null || barColumns === void 0 ? void 0 : barColumns.includes(scenario.type)) !== null && _a !== void 0 ? _a : false;
1449
- const columnStats = isBarChart ? columnStatsMap === null || columnStatsMap === void 0 ? void 0 : columnStatsMap.get(scenario.type) : undefined;
1450
- detailsRow.createElement(this.translateSumCellLabel(i18nMode, i18n, value, groupName, subCategory, type, scenario.type), scenario.type, this.createColumnType(scenario), this.setCellType(scenario.type, scenariosUnitType), this.translateCellPrefix(i18n, type, scenario.type), this.translateScenarioCSS(scenario.type, value), isSecondElement, categoryWidth, measureScale === null || measureScale === void 0 ? void 0 : measureScale.value, isBarChart, columnStats);
1451
- }
1452
- result.push(detailsRow);
1453
- }
1454
- return result;
1455
- }
1456
- getRawDataRowElement(rawDataRow, scenario) {
1457
- if (scenario.name === scenario.group && scenario.name === scenario.type) {
1458
- // Default Sum Scenario (e.g. AC)
1459
- return rawDataRow[scenario.name];
1460
- }
1461
- else if (scenario.name === scenario.group && scenario.name !== scenario.type) {
1462
- return rawDataRow[scenario.type + "##" + scenario.name];
1463
- }
1464
- return rawDataRow[scenario.type + "##" + scenario.group + "##" + scenario.name];
1465
- }
1466
- /**
1467
- * Crates a detail row depending on the radDataRow Type
1468
- * it switches between header, sum and standard,
1469
- *
1470
- * @param type valid values GROUPHEADER, SUM other values are interpreted as standard
1471
- * @param rowIndex
1472
- * @param groupIndex
1473
- * @param maxIndex total number of rows
1474
- */
1475
- createDetailRow(type, rowIndex, groupIndex, maxIndex) {
1476
- switch (type) {
1477
- case index.TableRowType.GROUPHEAD:
1478
- return new TableRow(rowIndex, groupIndex, index.TableRowType.HEADER);
1479
- case index.TableRowType.SUM:
1480
- return new TableRow(maxIndex + 2, groupIndex, index.TableRowType.SUM);
1481
- case index.TableRowType.GROUPSUM:
1482
- return new TableRow(maxIndex + 2, groupIndex, index.TableRowType.SUM);
1483
- case index.TableRowType.DRILLELEMENT:
1484
- return new TableRow(maxIndex + 2, groupIndex, index.TableRowType.DRILLELEMENT);
1485
- case index.TableRowType.PARTELEMENT:
1486
- return new TableRow(maxIndex + 2, groupIndex, index.TableRowType.PARTELEMENT);
1487
- default:
1488
- return new TableRow(rowIndex, groupIndex, index.TableRowType.STANDARD);
1489
- }
1490
- }
1491
- /**
1492
- * Translates Cell-Value (value) if possible,
1493
- * Numbers are not translated, just category names,
1494
- * if it is a SUM ROW rowGroup is used
1495
- * if it is a variance in OPT mode the absolute value is used
1496
- *
1497
- * @param value
1498
- * @param rowGroup
1499
- * @param type
1500
- * @param scenario
1501
- * @param subCategory
1502
- */
1503
- translateSumCellLabel(i18nMode, i18n, value, rowGroup, subCategory, type, scenario) {
1504
- if (Number.isNaN(Number(value)) === false) {
1505
- return value;
1506
- }
1507
- if (this.isOperationColumn(scenario)) {
1508
- return value;
1509
- }
1510
- if (this.isGroupHeadCategory(type, scenario)) {
1511
- if (i18nMode === Order.I18nMode.ALL) {
1512
- return `${i18n.get(value) || value}`;
1513
- }
1514
- return value;
1515
- }
1516
- if (this.isEntryCategory(type, scenario)) {
1517
- if (i18nMode === Order.I18nMode.ALL) {
1518
- return `${i18n.get(value) || value}`;
1519
- }
1520
- return value;
1521
- }
1522
- if (this.isDrillElementCategory(type, scenario)) {
1523
- if (i18nMode === Order.I18nMode.ALL) {
1524
- return `${i18n.get(subCategory) || subCategory}`;
1525
- }
1526
- return `${subCategory}`;
1527
- }
1528
- if (this.isPartElementCategory(type, scenario)) {
1529
- // translate allways because of default sum symbol.
1530
- if (i18nMode === Order.I18nMode.ALL || rowGroup === "SUM_TOTAL") {
1531
- return `${i18n.get(rowGroup) || rowGroup}`;
1532
- }
1533
- return `${rowGroup}`;
1534
- }
1535
- if (this.isSumElementCategory(type, scenario)) {
1536
- if (i18nMode === Order.I18nMode.ALL || rowGroup === "SUM_TOTAL") {
1537
- return `${i18n.get(rowGroup) || rowGroup}`;
1538
- }
1539
- return rowGroup;
1540
- }
1541
- if ("GROUPHEAD" === type && value == null) {
1542
- return value;
1543
- }
1544
- if (Number.isNaN(Number(value))) {
1545
- return "-";
1546
- }
1547
- else {
1548
- return Number(value);
1549
- }
1550
- }
1551
- isOperationColumn(scenario) {
1552
- return scenario === "operation";
1553
- }
1554
- /**
1555
- * converts Scenario to CSS class
1556
- *
1557
- * @param scenario
1558
- * @param value
1559
- */
1560
- translateScenarioCSS(scenario, value) {
1561
- const scenarios = new formatter.VarianceScenario(scenario);
1562
- let prefix = "pos";
1563
- if (value < 0) {
1564
- prefix = "neg";
1565
- }
1566
- if (scenarios.isValid) {
1567
- return prefix + "_" + scenarios.direction + (scenarios.type === "dr" ? " relative_variance" : "");
1568
- }
1569
- return scenario;
1570
- }
1571
- setCellType(scenario, scenariosUnitType) {
1572
- if (scenario === "category") {
1573
- return "";
1574
- }
1575
- let unitType;
1576
- const scenarios = new formatter.VarianceScenario(scenario);
1577
- if (scenariosUnitType === Order.DataFormat.PERCENT) {
1578
- unitType = "percent";
1579
- if (scenarios.isValid && scenarios.type === "d") {
1580
- unitType = "decimal";
1581
- }
1582
- }
1583
- else {
1584
- unitType = "decimal";
1585
- if (scenarios.isValid && scenarios.type === "dr") {
1586
- unitType = "percent";
1587
- }
1588
- }
1589
- return unitType;
1590
- }
1591
- isDrillElementCategory(type, scenario) {
1592
- return "DRILLELEMENT" === type && "category" === scenario;
1593
- }
1594
- isPartElementCategory(type, scenario) {
1595
- return "PARTELEMENT" === type && "category" === scenario;
1596
- }
1597
- isSumElementCategory(type, scenario) {
1598
- return ("GROUP_SUM" === type || "SUM" === type) && "category" === scenario;
1599
- }
1600
- isEntryCategory(type, scenario) {
1601
- return "ENTRY" === type && "category" === scenario;
1602
- }
1603
- isGroupHeadCategory(type, scenario) {
1604
- return "GROUPHEAD" === type && "category" === scenario;
1605
- }
1606
- translateCellPrefix(i18n, type, scenario) {
1607
- if (this.isOperationColumn(scenario)) {
1608
- return null;
1609
- }
1610
- if (this.isGroupHeadCategory(type, scenario)) {
1611
- return null;
1612
- }
1613
- if (this.isEntryCategory(type, scenario)) {
1614
- return null;
1615
- }
1616
- if (this.isDrillElementCategory(type, scenario)) {
1617
- return `${i18n.get("there_of")} `;
1618
- }
1619
- if (this.isPartElementCategory(type, scenario)) {
1620
- // translate allways because of default sum symbol.
1621
- return `${i18n.get("part_of")} `;
1622
- }
1623
- return null;
1624
- }
1625
- createColumnType(scenario) {
1626
- if (scenario.name === scenario.group && scenario.name === scenario.type) {
1627
- return "base";
1628
- }
1629
- if (scenario.name === scenario.group) {
1630
- return "columnGroup";
1631
- }
1632
- return "columnSubGroup";
1633
- }
1634
- }
1635
-
1636
- /**
1637
- * High-level controller for IBCS table generation.
1638
- *
1639
- * Coordinates the data pipeline: raw data is filtered via AlaSQL, scenarios are
1640
- * sorted by the visualization rule set, and TableDataSetFactory produces the
1641
- * header rows (with i18n-translated labels) and body rows (with grouped/drilled data).
1642
- *
1643
- * Uses a dirty-flag pattern (FactoryState) to lazily regenerate header/body rows
1644
- * only when configuration, data, or i18n changes. getHeader() and getBody() trigger
1645
- * regeneration if the state is dirty.
1646
- */
1647
- class Table {
1648
- /**
1649
- * Initialises all Variables for the DataSet, created by the factory
1650
- * @param ruleSet
1651
- */
1652
- constructor(ruleSet, data, config) {
1653
- this.data = [];
1654
- this.headerRows = [];
1655
- this.bodyRows = [];
1656
- this.ruleSet = ruleSet || new ibcsRuleSet.IBCSRuleSet();
1657
- this.dataSetFactory = new TableDataSetFactory();
1658
- this.config = this.initConfig(config);
1659
- this.i18n = this.initI18n(new Map());
1660
- this.setData(data, config.filter);
1661
- this.state = index.FactoryState.DIRTY;
1662
- }
1663
- /**
1664
- * Init load of translation dictionary map
1665
- * map is used to translate lables in the table
1666
- *
1667
- * example:
1668
- * ```
1669
- * let i18n: Map<string, string> = new Map();
1670
- * [{key: 'ac',value: 'AC'}].forEach(function(entry){
1671
- * i18n.set(entry.key, entry.value);
1672
- * })
1673
- * ```
1674
- * @param i18n
1675
- */
1676
- setI18n(i18n) {
1677
- this.i18n = this.initI18n(i18n);
1678
- }
1679
- initI18n(i18n) {
1680
- const defaultI18n = new Map([
1681
- ["", ""],
1682
- ["SEPERATOR_WS", ", "],
1683
- ["in", "in"],
1684
- ["ORDER_asc", "↑"],
1685
- ["ORDER_desc", "↓"],
1686
- ["ac1", "AC"],
1687
- ["pp1", "PY"],
1688
- ["fc1", "FC"],
1689
- ["pl1", "PL"],
1690
- ["ac2", "AC2"],
1691
- ["pp2", "PY2"],
1692
- ["fc2", "FC2"],
1693
- ["pl2", "PL2"],
1694
- ["ac3", "AC3"],
1695
- ["pp3", "PY3"],
1696
- ["fc3", "FC3"],
1697
- ["pl3", "PL3"],
1698
- ["ac4", "AC4"],
1699
- ["pp4", "PY4"],
1700
- ["fc4", "FC4"],
1701
- ["pl4", "PL4"],
1702
- ["in", "in"],
1703
- ["category", " "],
1704
- ["operation", " "],
1705
- ["there_of", "davon"],
1706
- ["part_of", "in % von"],
1707
- ["ibcssymbol_delta_ac", "Δ{%}"],
1708
- ["ibcssymbol_delta_generic", "Δ({%})"],
1709
- ["ibcssymbol_delta_ac_relative", "Δ{%}%"],
1710
- ["ibcssymbol_delta_generic_relative", "Δ({%})%"],
1711
- ["SUM_TOTAL", "❖"],
1712
- ]);
1713
- this.state = index.FactoryState.DIRTY; // mark dataSet for update
1714
- return new Map([...defaultI18n, ...(i18n || new Map())]);
1715
- }
1716
- initConfig(config) {
1717
- this.state = index.FactoryState.DIRTY; // mark dataSet for update
1718
- const tmpConfig = config;
1719
- // sorting scenario order based on Ruleset
1720
- const self = this;
1721
- config.scenarios.sort((n1, n2) => {
1722
- return self.ruleSet.getScenarioSorIndex(n1) - self.ruleSet.getScenarioSorIndex(n2);
1723
- });
1724
- return tmpConfig;
1725
- }
1726
- /**
1727
- * loads and varifies configuration which describes
1728
- * the filte for the to be generated dataset
1729
- *
1730
- * missing but necessary attributes are replaced by default values
1731
- *
1732
- * @param config
1733
- */
1734
- setConfig(config) {
1735
- this.config = this.initConfig(config);
1736
- }
1737
- setData(data, filter) {
1738
- if (data == null) {
1739
- return;
1740
- }
1741
- if (filter != null && filter.length > 0) {
1742
- try {
1743
- this.data = alasql_min.alasql(`SELECT * FROM ? WHERE ${filter}`, [data]);
1744
- }
1745
- catch (e) {
1746
- console.error("Table: filter query failed, using unfiltered data", filter, e);
1747
- this.data = data;
1748
- }
1749
- }
1750
- else {
1751
- this.data = data;
1752
- }
1753
- const normalizedScenarios = this.normalizeScenarios(this.config.scenarios, this.config.categoryThereOf, this.config.sortOrder);
1754
- this.headerRows = this.dataSetFactory.createHeader(this.config.type, normalizedScenarios, this.i18n, this.config.measureScale, this.config.measureUnit, this.config.showMeasureScale);
1755
- this.bodyRows = this.dataSetFactory.createBodyRows(this.config, this.i18n, this.data);
1756
- this.state = index.FactoryState.UP_TO_DATE;
1757
- }
1758
- update() {
1759
- const normalizedScenarios = this.normalizeScenarios(this.config.scenarios, this.config.categoryThereOf, this.config.sortOrder);
1760
- this.headerRows = this.dataSetFactory.createHeader(this.config.type, normalizedScenarios, this.i18n, this.config.measureScale, this.config.measureUnit, this.config.showMeasureScale);
1761
- this.bodyRows = this.dataSetFactory.createBodyRows(this.config, this.i18n, this.data);
1762
- this.state = index.FactoryState.UP_TO_DATE;
1763
- }
1764
- getHeader() {
1765
- if (this.state === index.FactoryState.DIRTY) {
1766
- this.update();
1767
- }
1768
- return this.headerRows;
1769
- }
1770
- getBody() {
1771
- if (this.state === index.FactoryState.DIRTY) {
1772
- this.update();
1773
- }
1774
- return this.bodyRows;
1775
- }
1776
- normalizeScenarios(scenarios, categoryThereOf, order) {
1777
- var _a;
1778
- const normalizedScenarios = [];
1779
- for (const scenario of scenarios) {
1780
- if (categoryThereOf === null || categoryThereOf === void 0 ? void 0 : categoryThereOf.has(scenario)) {
1781
- const categoryDrills = categoryThereOf.get(scenario);
1782
- for (const drillElement of categoryDrills) {
1783
- normalizedScenarios.push({
1784
- name: drillElement.name,
1785
- group: drillElement.name,
1786
- type: scenario,
1787
- order: undefined,
1788
- });
1789
- for (const drillSubElement of drillElement.subGroups) {
1790
- normalizedScenarios.push({
1791
- name: drillSubElement,
1792
- group: drillElement.name,
1793
- type: scenario,
1794
- order: undefined,
1795
- });
1796
- }
1797
- }
1798
- normalizedScenarios.push({ name: "REST", group: "REST", type: scenario, order: undefined });
1799
- }
1800
- let orderDirection = undefined;
1801
- if (((_a = order === null || order === void 0 ? void 0 : order.hierarchy) === null || _a === void 0 ? void 0 : _a.at(0)) === scenario) {
1802
- orderDirection = order.direction;
1803
- }
1804
- normalizedScenarios.push({ name: scenario, group: scenario, type: scenario, order: orderDirection });
1805
- }
1806
- return normalizedScenarios;
1807
- }
1808
- hasNoData() {
1809
- return this.data.length === 0;
1810
- }
1811
- }
1812
-
1813
- /**
1814
- * Configuration for an IBCS table component.
1815
- *
1816
- * Controls table behavior including drill-down groups, data formatting, and display modes.
1817
- *
1818
- * Drill-down concepts:
1819
- * - **thereOf** -- Sub-rows that break down a parent row's total (e.g. "thereof: domestic / international").
1820
- * Configured as an array of {@link TableDrillGroup} filters.
1821
- * - **partOf** -- Rows shown as a percentage share of a parent total.
1822
- * Also configured via {@link TableDrillGroup} filters.
1823
- * - **categoryThereOf** -- Column-level drill-down using the `##` separator convention in category names
1824
- * (e.g. `"Revenue##Product A"`) to expand a single category column into detail sub-columns.
1825
- * The Map key is the parent category, values are the detail records.
1826
- */
1827
- class TableComponentConfig {
1828
- constructor() {
1829
- this.title = "";
1830
- /** Active scenario column names (e.g. `["ac1", "pl1"]`). */
1831
- this.scenarios = [];
1832
- /** Number format for scenario values (decimal, percent, etc.). */
1833
- this.scenariosUnitType = Order.DataFormat.DECIMAL;
1834
- /** When true, rows are visually grouped by rowGroup. */
1835
- this.grouped = false;
1836
- this.showGroupTitle = true;
1837
- /** Drill-down sub-row definitions -- "thereof" breakdowns within a category. */
1838
- this.thereOf = [];
1839
- /** Column-level drill-down using `##` separator in category names. */
1840
- this.categoryThereOf = new Map();
1841
- /** Percentage-of-total sub-row definitions. */
1842
- this.partOf = [];
1843
- this.sortOrder = new Order.OrderAdapter(new ibcsRuleSet.StringAdapter()).default();
1844
- /** Table aggregation mode: LIST (flat), SUM (with totals), OPT (with optional totals), etc. */
1845
- this.type = index.TableType.LIST;
1846
- /** Maximum rows to display; 0 means unlimited. */
1847
- this.limit = 0;
1848
- this.i18n = Order.I18nMode.ALL;
1849
- /** Proportion of table width allocated to the category label column. */
1850
- this.categoryWidth = Order.TableCategoryWidth.W25;
1851
- /** SI prefix for measure scaling (e.g. "k" for thousands, "M" for millions). */
1852
- this.measureScale = new DataFormatDigits.SiPrefix();
1853
- /** Unit label displayed in the table header (e.g. "EUR", "USD"). */
1854
- this.measureUnit = "";
1855
- /** Whether the measure represents a volume or a ratio, affecting formatting. */
1856
- this.measureType = Order.MeasureType.VOLUME;
1857
- this.showMeasureScale = true;
1858
- /** AlaSQL WHERE clause for additional row filtering. */
1859
- this.filter = "";
1860
- /** Scenario columns to render as inline bar charts instead of numbers. */
1861
- this.barColumns = [];
1862
- }
1863
- }
1864
- /**
1865
- * Converts untyped JSON into a validated {@link TableComponentConfig}.
1866
- *
1867
- * Requires the raw dataset for measure scale auto-calculation when `measureScale` is set to "auto".
1868
- */
1869
- class TableComponentConfigAdapter {
1870
- constructor(tableDrillGroupAdapter, stringAdapter, orderAdapter, dataSet) {
1871
- this.tableDrillGroupAdapter = tableDrillGroupAdapter;
1872
- this.stringAdapter = stringAdapter;
1873
- this.orderAdapter = orderAdapter;
1874
- this.dataSet = dataSet;
1875
- }
1876
- adapt(data) {
1877
- const config = new TableComponentConfig();
1878
- if (Order.CompareUtil.isString(data.title)) {
1879
- config.title = data.title;
1880
- }
1881
- if (Order.CompareUtil.isArray(data.scenarios)) {
1882
- config.scenarios = Order.AdapterUtils.adaptArray(data.scenarios, this.stringAdapter);
1883
- }
1884
- if (Order.CompareUtil.isExisting(data.scenariosUnitType)) {
1885
- config.scenariosUnitType = data.scenariosUnitType;
1886
- }
1887
- if (Order.CompareUtil.isBoolean(data.grouped)) {
1888
- config.grouped = data.grouped;
1889
- }
1890
- if (Order.CompareUtil.isBoolean(data.showGroupTitle)) {
1891
- config.showGroupTitle = data.showGroupTitle;
1892
- }
1893
- if (Order.CompareUtil.isBoolean(data.showMeasureScale)) {
1894
- config.showMeasureScale = data.showMeasureScale;
1895
- }
1896
- if (Order.CompareUtil.isArray(data.thereOf)) {
1897
- config.thereOf = Order.AdapterUtils.adaptArray(data.thereOf, this.tableDrillGroupAdapter);
1898
- }
1899
- if (Order.CompareUtil.isExisting(data.categoryThereOf)) {
1900
- config.categoryThereOf = data.categoryThereOf;
1901
- }
1902
- if (Order.CompareUtil.isArray(data.partOf)) {
1903
- config.partOf = Order.AdapterUtils.adaptArray(data.partOf, this.tableDrillGroupAdapter);
1904
- }
1905
- if (Order.CompareUtil.isExisting(data.order)) {
1906
- config.sortOrder = this.orderAdapter.adapt(data.order);
1907
- }
1908
- if (Order.CompareUtil.isExisting(data.type)) {
1909
- config.type = data.type;
1910
- }
1911
- if (Order.CompareUtil.isNumber(data.limit)) {
1912
- config.limit = data.limit;
1913
- }
1914
- if (Order.CompareUtil.isExisting(data.i18n)) {
1915
- config.i18n = data.i18n;
1916
- }
1917
- if (Order.CompareUtil.isExisting(data.categoryWidth)) {
1918
- config.categoryWidth = data.categoryWidth;
1919
- }
1920
- if (Order.CompareUtil.isExisting(data.measureScale)) {
1921
- config.measureScale = DataFormatDigits.DataAnalyzer.calculateMeasureScale(this.dataSet, config.scenarios, data.measureScale);
1922
- }
1923
- if (Order.CompareUtil.isExisting(data.measureType)) {
1924
- config.measureType = data.measureType;
1925
- }
1926
- if (Order.CompareUtil.isString(data.measureUnit)) {
1927
- config.measureUnit = data.measureUnit;
1928
- }
1929
- if (Order.CompareUtil.isString(data.filter)) {
1930
- config.filter = data.filter.trim();
1931
- }
1932
- if (Order.CompareUtil.isArray(data.barColumns)) {
1933
- config.barColumns = data.barColumns;
1934
- }
1935
- return config;
1936
- }
1937
- default() {
1938
- return new TableComponentConfig();
1939
- }
1940
- }
1941
-
1942
- // import { IAdapter } from "../../../../utils/helper/IAdapter";
1943
- // import { CompareUtil } from "../../../../utils/helper/CompareUtil";
1944
- /**
1945
- * Filter definition for a table drill-down operation (thereOf or partOf).
1946
- *
1947
- * Identifies which rows in the dataset participate in a drill-down group by matching
1948
- * on the three-level row hierarchy. For partOf drill-downs, the {@link partOf} field
1949
- * names the parent category whose total is used as the 100% reference.
1950
- */
1951
- class TableDrillGroup {
1952
- constructor() {
1953
- this.rowGroup = "";
1954
- this.category = "";
1955
- this.subCategory = "";
1956
- /** Parent category name for percentage-of-total (partOf) calculations. Empty for thereOf groups. */
1957
- this.partOf = "";
1958
- }
1959
- }
1960
- /** Converts untyped JSON into a validated {@link TableDrillGroup}. */
1961
- class TableDrillGroupAdapter {
1962
- constructor() { }
1963
- adapt(data) {
1964
- const group = new TableDrillGroup();
1965
- if (Order.CompareUtil.isString(data.rowGroup)) {
1966
- group.rowGroup = data.rowGroup;
1967
- }
1968
- if (Order.CompareUtil.isString(data.category)) {
1969
- group.category = data.category;
1970
- }
1971
- if (Order.CompareUtil.isString(data.subCategory)) {
1972
- group.subCategory = data.subCategory;
1973
- }
1974
- if (Order.CompareUtil.isString(data.partOf)) {
1975
- group.partOf = data.partOf;
1976
- }
1977
- return group;
1978
- }
1979
- default() {
1980
- return new TableDrillGroup();
1981
- }
1982
- }
1983
-
1984
- // import { IAdapter } from "../../../../utils/helper/IAdapter";
1985
- // import { CompareUtil } from "../../../../utils/helper/CompareUtil";
1986
- /**
1987
- * IBCS-compliant data row for table visualizations.
1988
- *
1989
- * Represents a single record with a three-level row hierarchy (rowGroup > category > subCategory),
1990
- * a two-level column hierarchy (columnGroup > columnSubGroup), and 16 scenario value slots across
1991
- * four scenario types: actual (ac1-4), previous period (pp1-4), forecast (fc1-4), and plan (pl1-4).
1992
- *
1993
- * The {@link operation} field controls how this row participates in aggregations:
1994
- * `"+"` adds and `"-"` subtracts the row's values. This is converted to a numeric multiplier
1995
- * by `transformOperator()` in the SQL query engine.
1996
- */
1997
- class TableDataRow {
1998
- constructor() {
1999
- /** Aggregation operator: `"+"` adds values, `"-"` subtracts them in SUM/OPT roll-ups. */
2000
- this.operation = "+";
2001
- }
2002
- addRowGroup(name, index) {
2003
- this.rowGroup = name;
2004
- this.rowGroupIndex = index;
2005
- }
2006
- addCategory(name, index) {
2007
- this.category = name;
2008
- this.categoryIndex = index;
2009
- }
2010
- addSubCategory(name, index) {
2011
- this.subCategory = name;
2012
- this.subCategoryIndex = index;
2013
- }
2014
- addColumnGroup(name, index) {
2015
- this.columnGroup = name;
2016
- this.columnGroupIndex = index;
2017
- }
2018
- addSubColumnGroup(name, index) {
2019
- this.columnSubGroup = name;
2020
- this.columnSubGroupIndex = index;
2021
- }
2022
- }
2023
- /**
2024
- * Converts untyped JSON records into validated {@link TableDataRow} instances.
2025
- *
2026
- * Only assigns fields that pass type validation via {@link CompareUtil}, so malformed
2027
- * input data is silently dropped and defaults are preserved.
2028
- */
2029
- class TableDataRowAdapter {
2030
- constructor() { }
2031
- adapt(data) {
2032
- const dataRow = new TableDataRow();
2033
- if (Order.CompareUtil.isOperator(data.operation)) {
2034
- dataRow.operation = data.operation;
2035
- }
2036
- if (Order.CompareUtil.isNumber(data.rowGroupIndex) && Order.CompareUtil.isString(data.rowGroup)) {
2037
- dataRow.addRowGroup(data.rowGroup, data.rowGroupIndex);
2038
- }
2039
- if (Order.CompareUtil.isNumber(data.categoryIndex) && Order.CompareUtil.isString(data.category)) {
2040
- dataRow.addCategory(data.category, data.categoryIndex);
2041
- }
2042
- if (Order.CompareUtil.isNumber(data.subCategoryIndex) && Order.CompareUtil.isString(data.subCategory)) {
2043
- dataRow.addSubCategory(data.subCategory, data.subCategoryIndex);
2044
- }
2045
- if (Order.CompareUtil.isNumber(data.columnGroupIndex) && Order.CompareUtil.isString(data.columnGroup)) {
2046
- dataRow.addColumnGroup(data.columnGroup, data.columnGroupIndex);
2047
- }
2048
- if (Order.CompareUtil.isNumber(data.columnSubGroupIndex) && Order.CompareUtil.isString(data.columnSubGroup)) {
2049
- dataRow.addSubColumnGroup(data.columnSubGroup, data.columnSubGroupIndex);
2050
- }
2051
- this.setActualValues(data, dataRow);
2052
- this.setPlanValues(data, dataRow);
2053
- this.setPreviousPeriodValues(data, dataRow);
2054
- this.setForecastValues(data, dataRow);
2055
- return dataRow;
2056
- }
2057
- default() {
2058
- return new TableDataRow();
2059
- }
2060
- setActualValues(data, dataRow) {
2061
- if (Order.CompareUtil.isNumber(data.ac1)) {
2062
- dataRow.ac1 = data.ac1;
2063
- }
2064
- if (Order.CompareUtil.isNumber(data.ac2)) {
2065
- dataRow.ac2 = data.ac2;
2066
- }
2067
- if (Order.CompareUtil.isNumber(data.ac3)) {
2068
- dataRow.ac3 = data.ac3;
2069
- }
2070
- if (Order.CompareUtil.isNumber(data.ac4)) {
2071
- dataRow.ac4 = data.ac4;
2072
- }
2073
- }
2074
- setPlanValues(data, dataRow) {
2075
- if (Order.CompareUtil.isNumber(data.pp1)) {
2076
- dataRow.pp1 = data.pp1;
2077
- }
2078
- if (Order.CompareUtil.isNumber(data.pp2)) {
2079
- dataRow.pp2 = data.pp2;
2080
- }
2081
- if (Order.CompareUtil.isNumber(data.pp3)) {
2082
- dataRow.pp3 = data.pp3;
2083
- }
2084
- if (Order.CompareUtil.isNumber(data.pp4)) {
2085
- dataRow.pp4 = data.pp4;
2086
- }
2087
- }
2088
- setPreviousPeriodValues(data, dataRow) {
2089
- if (Order.CompareUtil.isNumber(data.pl1)) {
2090
- dataRow.pl1 = data.pl1;
2091
- }
2092
- if (Order.CompareUtil.isNumber(data.pl2)) {
2093
- dataRow.pl2 = data.pl2;
2094
- }
2095
- if (Order.CompareUtil.isNumber(data.pl3)) {
2096
- dataRow.pl3 = data.pl3;
2097
- }
2098
- if (Order.CompareUtil.isNumber(data.pl4)) {
2099
- dataRow.pl4 = data.pl4;
2100
- }
2101
- }
2102
- setForecastValues(data, dataRow) {
2103
- if (Order.CompareUtil.isNumber(data.fc1)) {
2104
- dataRow.fc1 = data.fc1;
2105
- }
2106
- if (Order.CompareUtil.isNumber(data.fc2)) {
2107
- dataRow.fc2 = data.fc2;
2108
- }
2109
- if (Order.CompareUtil.isNumber(data.fc3)) {
2110
- dataRow.fc3 = data.fc3;
2111
- }
2112
- if (Order.CompareUtil.isNumber(data.fc4)) {
2113
- dataRow.fc4 = data.fc4;
2114
- }
2115
- }
2116
- }
2117
-
2118
- const ibcsTableCss = () => `:host{position:relative;display:inline-block}table{background-color:var(--bn-font-background, white);font-size:var(--bn-font-size, 1em);color:var(--bn-font-color, black);font-family:var(--bn-font-family, "Noto Sans", "Helvetica Neue", Helvetica, sans-serif);border-spacing:0.3em 0}thead{border-style:none}tr:first-child td{border-top:none;padding-top:0.5em}td.ac1,td.ac2,td.ac3,td.ac4,td.pp1,td.pp2,td.pp3,td.pp4,td.pl1,td.pl2,td.pl3,td.pl4,td.fc1,td.fc2,td.fc3,td.fc4,td.share,td.variance,td.pos_pos,td.pos_neg,td.neg_pos,td.neg_neg,td.pos_neutral,td.neg_neutral{text-align:right}.category-w100{min-width:100em;max-width:100em}.category-w50{min-width:50em;max-width:50em}.category-w25{min-width:25em;max-width:25em}.category-w20{min-width:20em;max-width:20em}.category-w15{min-width:15em;max-width:15em}.category-w10{min-width:10em;max-width:10em}.category-w5{min-width:5em;max-width:5em}.prefix-second{color:transparent;font-style:normal}.prefix-first{font-style:normal}th{border-bottom:0.1em solid black;text-align:right;font-weight:normal;vertical-align:text-top}td.columnGroup,th.columnGroup{font-size:0.6em}td.columnSubGroup,th.columnSubGroup{font-size:0.6em;border-spacing:0em 0;font-style:italic}td.base,th.base{font-style:normal}th.ofit,td.ofit,tr.ofit,th.partof,td.partof,tr.partof{font-size:0.6em;font-style:italic}td.ofit,td.partof{font-size:0.6em;font-style:italic}th.ofit td,tr.ofit td,th.partof td,tr.partof td{border-top:0em solid black;padding-left:1em}th.ofit share,th.partof share,tr.share td{border-top:0em solid black}th.share,tr.share,td.share{font-size:0.6em;font-style:italic}th.filler{border-bottom:0em solid black;text-align:right}td.filler{border-top:0em none !important;border-bottom:0em none;text-align:right}th.group{text-align:center;border-spacing:1em 0}th.headerlabel{border-bottom:0em none black;padding-bottom:0em}td.variance:after{content:"%"}td.relative_variance{font-style:italic}td.percent{font-style:italic;text-align:right}td.decimal{text-align:right}td.pos_pos{color:#008f96}td.neg_pos{color:#ff0000}td.pos_neg{color:#ff0000}td.neg_neg{color:#008f96}td.pos_pos:before{content:"+"}td.pos_neg:before{content:"+"}td.pos_neu:before{content:"+"}th.ac1,th.ac2,th.ac3,th.ac4{padding-top:0em;border-bottom:0.3em solid black}th.pp1,th.pp2,th.pp3,th.pp4{padding-top:0em;border-bottom:0.3em solid grey}th.pl1,th.pl2,th.pl3,th.pl4{padding-top:0em;border-bottom:0.3em double black}th.fc1,th.fc2,th.fc3,th.fc4{border-bottom:0.3em solid;border-image:repeating-linear-gradient(-45deg, white, white, black, white, white 0.3em) 2}td.colsum{font-weight:bold}th.colsum{padding-top:0em;font-weight:bold}tr.sum td{border-top:0.1em solid black;font-weight:bold;padding-bottom:0.5em}tr.groupheader td{border-top:0em dotted #ddd;padding-top:0.5em;font-weight:bold;font-style:italic}tr.begingroup td{border-top:0em dotted #ddd;padding-top:0.5em}th.begin-group{padding-left:0.75em}th.end-group{padding-left:0.75em}td{box-sizing:border-box;-webkit-box-sizing:border-box;border-top:0.1em dashed #ddd;padding-left:0.5em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.table-footer{font-size:0.6em}.cell-bar-chart{display:inline-block;vertical-align:middle}.bar-chart-empty{color:#999}td:has(.cell-bar-chart){padding:0 0.25em;vertical-align:middle}td:has(.cell-bar-chart).pos_pos:before,td:has(.cell-bar-chart).pos_neg:before,td:has(.cell-bar-chart).pos_neu:before{content:none}td:has(.cell-bar-chart).variance:after{content:none}`;
2119
-
2120
- const IbcsTable = class {
2121
- constructor(hostRef) {
2122
- index$1.registerInstance(this, hostRef);
2123
- this.data = [];
2124
- this.tableTitle = "SUM_TOTAL";
2125
- this.scenarios = [];
2126
- this.scenariosDataFormat = Order.DataFormat.DECIMAL;
2127
- this.grouped = false;
2128
- this.limit = 0;
2129
- this.showGroupTitle = true;
2130
- this.thereof = [];
2131
- this.partof = [];
2132
- this.order = {
2133
- hierarchy: [],
2134
- direction: index.OrderDirection.ASC,
2135
- };
2136
- this.categorythereof = new Map();
2137
- this.type = index.TableType.LIST;
2138
- this.categoryWidth = Order.TableCategoryWidth.INF;
2139
- this.dataFormatDigits = { percent: 2, decimal: 1 };
2140
- this.i18n = new Map();
2141
- this.i18nMode = Order.I18nMode.ALL;
2142
- this.measureScale = "_";
2143
- this.measureUnit = "";
2144
- this.showMeasureScale = true;
2145
- this.measureType = Order.MeasureType.VOLUME;
2146
- this.filter = "";
2147
- this.barColumns = [];
2148
- this.barColumnMaxWidth = 30;
2149
- this.unitScaling = 0.01;
2150
- this.percentageScaling = 0.5;
2151
- this.scaleFactor = 1;
2152
- this.componentDataFormatDigits = new DataFormatDigits.DataFormatDigits();
2153
- this.componentStyle = withComponentStyle.withComponentStyle(this);
2154
- }
2155
- render() {
2156
- const helper = () => {
2157
- if (this.table === undefined) {
2158
- return;
2159
- }
2160
- if (this.table.hasNoData()) {
2161
- const errorMsg = this.i18n.get("NO_DATA") || "==No Data==";
2162
- return index$1.h("p", { class: "warning" }, errorMsg);
2163
- }
2164
- return (index$1.h("table", null, index$1.h("thead", null, this.table.getHeader().map((row) => (index$1.h("tr", { class: row.cssStyle }, row.getCells().map((cell) => (index$1.h("th", { colSpan: cell.colSpan, class: cell.cssStyle }, cell.getAsHeaderList().map((line, i, arr) => (index$1.h("span", null, i === arr.length - 1 ? (index$1.h("span", { class: line === " " ? "table-footer" : "" }, line, cell.drawPrefix(), " ")) : (index$1.h("span", null, line, cell.drawPrefix(), index$1.h("br", null))))))))))))), index$1.h("tbody", null, this.table.getBody().map((row) => (index$1.h("tr", { class: row.cssStyle }, row === null || row === void 0 ? void 0 : row.getCells().map((cell) => (index$1.h("td", { colSpan: cell.colSpan, class: cell.type ? `${cell.cssStyle} ${cell.type}` : cell.cssStyle }, cell.prefix != null ? (index$1.h("span", { class: cell.cssStyle + " " + cell.prefixStyle }, cell.drawPrefix())) : (""), cell.isBarChart && cell.columnStats && row.type !== index.TableRowType.SUM ? (index$1.h(CellBarChart, { value: cell.value, scenario: cell.key, columnStats: cell.columnStats, height: 18 * this.scaleFactor, isRelative: cell.key.startsWith("dr"), isPositiveGood: cell.key.endsWith("_pos"), measureScale: cell.measureScale, maxBarWidth: this.barColumnMaxWidth, styles: this.barChartStyles })) : (cell.draw(this.componentDataFormatDigits)))))))))));
2165
- };
2166
- return index$1.h(index$1.Host, null, helper());
2167
- }
2168
- componentWillRender() {
2169
- const config = this.prepareConfig();
2170
- const data = this.prepareData();
2171
- this.componentDataFormatDigits = new DataFormatDigits.DataFormatDigitsAdapter().adapt(this.dataFormatDigits);
2172
- this.barChartStyles = this.prepareBarChartStyles();
2173
- this.table = new Table(new ibcsRuleSet.IBCSRuleSet(), data, config);
2174
- this.table.setI18n(this.i18n);
2175
- }
2176
- prepareConfig() {
2177
- const config = new TableComponentConfigAdapter(new TableDrillGroupAdapter(), new ibcsRuleSet.StringAdapter(), new Order.OrderAdapter(new ibcsRuleSet.StringAdapter()), this.data).adapt({
2178
- title: this.tableTitle,
2179
- scenarios: this.scenarios,
2180
- scenariosUnitType: this.scenariosDataFormat,
2181
- grouped: this.grouped,
2182
- showGroupTitle: this.showGroupTitle,
2183
- thereOf: this.thereof,
2184
- partOf: this.partof,
2185
- categoryThereOf: this.categorythereof,
2186
- order: this.order,
2187
- type: this.type,
2188
- limit: this.limit,
2189
- i18n: this.i18nMode,
2190
- categoryWidth: this.categoryWidth,
2191
- measureScale: this.measureScale,
2192
- measureUnit: this.measureUnit,
2193
- measureType: this.measureType,
2194
- showMeasureScale: this.showMeasureScale,
2195
- filter: this.filter,
2196
- barColumns: this.barColumns,
2197
- });
2198
- return config;
2199
- }
2200
- prepareData() {
2201
- return Order.AdapterUtils.adaptArray(this.data, new TableDataRowAdapter());
2202
- }
2203
- /**
2204
- * Prepares bar chart styles from componentStyle store.
2205
- * Uses the same variance styles as bn-chart-time for consistency.
2206
- * Supports fillpattern for different visual treatments (solid, hatched, outlined).
2207
- * Scenario styles (ac, pp, fc, pl) use barStyles for IBCS-compliant grayscale coloring.
2208
- */
2209
- prepareBarChartStyles() {
2210
- return this.componentStyle(($) => {
2211
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1;
2212
- const varianceStyles = (_a = $["bn-chart-time"]) === null || _a === void 0 ? void 0 : _a["varianceStyles"];
2213
- const barStyles = (_b = $["bn-chart-time"]) === null || _b === void 0 ? void 0 : _b["barStyles"];
2214
- // Default variance styles with fillpattern
2215
- const defaultPos = { stroke: "#008f96", fill: "#008f96", fillpattern: "solid" };
2216
- const defaultNeg = { stroke: "#ff0000", fill: "#ff0000", fillpattern: "solid" };
2217
- const defaultNeu = { stroke: "#808080", fill: "#808080", fillpattern: "outlined" };
2218
- // Default scenario styles (IBCS grayscale)
2219
- const defaultAc = { stroke: "#404040", fill: "#404040", fillpattern: "solid" };
2220
- const defaultPp = { stroke: "#A6A6A6", fill: "#A6A6A6", fillpattern: "solid" };
2221
- const defaultFc = { stroke: "#404040", fill: "#ffffff", fillpattern: "hatched" };
2222
- const defaultPl = { stroke: "#404040", fill: "#ffffff", fillpattern: "outlined" };
2223
- /* eslint-disable @typescript-eslint/no-explicit-any */
2224
- return {
2225
- positive: {
2226
- stroke: ((_c = varianceStyles === null || varianceStyles === void 0 ? void 0 : varianceStyles.pos) === null || _c === void 0 ? void 0 : _c.stroke) || defaultPos.stroke,
2227
- fill: ((_d = varianceStyles === null || varianceStyles === void 0 ? void 0 : varianceStyles.pos) === null || _d === void 0 ? void 0 : _d.fill) || defaultPos.fill,
2228
- fillpattern: ((_e = varianceStyles === null || varianceStyles === void 0 ? void 0 : varianceStyles.pos) === null || _e === void 0 ? void 0 : _e.fillpattern) || defaultPos.fillpattern,
2229
- },
2230
- negative: {
2231
- stroke: ((_f = varianceStyles === null || varianceStyles === void 0 ? void 0 : varianceStyles.neg) === null || _f === void 0 ? void 0 : _f.stroke) || defaultNeg.stroke,
2232
- fill: ((_g = varianceStyles === null || varianceStyles === void 0 ? void 0 : varianceStyles.neg) === null || _g === void 0 ? void 0 : _g.fill) || defaultNeg.fill,
2233
- fillpattern: ((_h = varianceStyles === null || varianceStyles === void 0 ? void 0 : varianceStyles.neg) === null || _h === void 0 ? void 0 : _h.fillpattern) || defaultNeg.fillpattern,
2234
- },
2235
- neutral: {
2236
- stroke: ((_j = varianceStyles === null || varianceStyles === void 0 ? void 0 : varianceStyles.neu) === null || _j === void 0 ? void 0 : _j.stroke) || defaultNeu.stroke,
2237
- fill: ((_k = varianceStyles === null || varianceStyles === void 0 ? void 0 : varianceStyles.neu) === null || _k === void 0 ? void 0 : _k.fill) || defaultNeu.fill,
2238
- fillpattern: ((_l = varianceStyles === null || varianceStyles === void 0 ? void 0 : varianceStyles.neu) === null || _l === void 0 ? void 0 : _l.fillpattern) || defaultNeu.fillpattern,
2239
- },
2240
- scenarios: {
2241
- ac: {
2242
- stroke: ((_m = barStyles === null || barStyles === void 0 ? void 0 : barStyles.ac) === null || _m === void 0 ? void 0 : _m.stroke) || defaultAc.stroke,
2243
- fill: ((_o = barStyles === null || barStyles === void 0 ? void 0 : barStyles.ac) === null || _o === void 0 ? void 0 : _o.fill) || defaultAc.fill,
2244
- fillpattern: ((_p = barStyles === null || barStyles === void 0 ? void 0 : barStyles.ac) === null || _p === void 0 ? void 0 : _p.fillpattern) || defaultAc.fillpattern,
2245
- },
2246
- pp: {
2247
- stroke: ((_q = barStyles === null || barStyles === void 0 ? void 0 : barStyles.pp) === null || _q === void 0 ? void 0 : _q.stroke) || defaultPp.stroke,
2248
- fill: ((_r = barStyles === null || barStyles === void 0 ? void 0 : barStyles.pp) === null || _r === void 0 ? void 0 : _r.fill) || defaultPp.fill,
2249
- fillpattern: ((_s = barStyles === null || barStyles === void 0 ? void 0 : barStyles.pp) === null || _s === void 0 ? void 0 : _s.fillpattern) || defaultPp.fillpattern,
2250
- },
2251
- fc: {
2252
- stroke: ((_t = barStyles === null || barStyles === void 0 ? void 0 : barStyles.fc) === null || _t === void 0 ? void 0 : _t.stroke) || defaultFc.stroke,
2253
- fill: ((_u = barStyles === null || barStyles === void 0 ? void 0 : barStyles.fc) === null || _u === void 0 ? void 0 : _u.fill) || defaultFc.fill,
2254
- fillpattern: ((_v = barStyles === null || barStyles === void 0 ? void 0 : barStyles.fc) === null || _v === void 0 ? void 0 : _v.fillpattern) || defaultFc.fillpattern,
2255
- },
2256
- pl: {
2257
- stroke: ((_w = barStyles === null || barStyles === void 0 ? void 0 : barStyles.pl) === null || _w === void 0 ? void 0 : _w.stroke) || defaultPl.stroke,
2258
- fill: ((_x = barStyles === null || barStyles === void 0 ? void 0 : barStyles.pl) === null || _x === void 0 ? void 0 : _x.fill) || defaultPl.fill,
2259
- fillpattern: ((_y = barStyles === null || barStyles === void 0 ? void 0 : barStyles.pl) === null || _y === void 0 ? void 0 : _y.fillpattern) || defaultPl.fillpattern,
2260
- },
2261
- },
2262
- /* eslint-enable @typescript-eslint/no-explicit-any */
2263
- fontColor: ((_z = $["global"]) === null || _z === void 0 ? void 0 : _z["fontColor"]) || "#000000",
2264
- fontSize: (((_0 = $["global"]) === null || _0 === void 0 ? void 0 : _0["fontSizePx"]) || 13.3333) * 0.85 * this.scaleFactor,
2265
- fontFamily: ((_1 = $["global"]) === null || _1 === void 0 ? void 0 : _1["fontFamily"]) || "'Noto Sans', sans-serif",
2266
- unitScaling: this.unitScaling,
2267
- percentageScaling: this.percentageScaling,
2268
- scaleFactor: this.scaleFactor,
2269
- };
2270
- });
2271
- }
2272
- get element() { return index$1.getElement(this); }
2273
- };
2274
- IbcsTable.style = ibcsTableCss();
2275
-
2276
- exports.ibcs_table = IbcsTable;