@stamhoofd/metabase 2.148.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +32 -0
- package/README.md +136 -0
- package/dist/api.d.ts +217 -0
- package/dist/api.d.ts.map +1 -0
- package/dist/api.js +334 -0
- package/dist/api.js.map +1 -0
- package/dist/naming.d.ts +36 -0
- package/dist/naming.d.ts.map +1 -0
- package/dist/naming.js +42 -0
- package/dist/naming.js.map +1 -0
- package/dist/report.d.ts +141 -0
- package/dist/report.d.ts.map +1 -0
- package/dist/report.js +297 -0
- package/dist/report.js.map +1 -0
- package/dist/sync-report.d.ts +212 -0
- package/dist/sync-report.d.ts.map +1 -0
- package/dist/sync-report.js +653 -0
- package/dist/sync-report.js.map +1 -0
- package/package.json +33 -0
- package/report/eenheden.sql +459 -0
- package/report/filters.sql +65 -0
- package/report/includes/aangesloten.sql +23 -0
- package/report/includes/aansluiting.sql +26 -0
- package/report/includes/facts-alle-jaren.sql +53 -0
- package/report/includes/facts.sql +102 -0
- package/report/includes/gtp.sql +49 -0
- package/report/includes/ingeschreven-voor.sql +27 -0
- package/report/includes/jaren.sql +20 -0
- package/report/includes/keeo/tak-categorie.sql +30 -0
- package/report/includes/leden-per-jaar.sql +29 -0
- package/report/includes/leden.sql +39 -0
- package/report/includes/omkaderingscijfer.sql +17 -0
- package/report/includes/postcode-coordinaten.sql +8 -0
- package/report/includes/ravot/gtp.sql +32 -0
- package/report/includes/ravot/omkaderingscijfer.sql +25 -0
- package/report/includes/ravot/tak-categorie.sql +28 -0
- package/report/includes/ravot/type-deelnemers.sql +22 -0
- package/report/includes/tak-categorie.sql +18 -0
- package/report/includes/takken.sql +20 -0
- package/report/includes/tarief.sql +14 -0
- package/report/includes/type-deelnemers.sql +14 -0
- package/report/includes/uldk.sql +23 -0
- package/report/jeugdbewegingen.sql +221 -0
- package/report/nationaal.sql +229 -0
- package/report/netwerk.sql +70 -0
- package/report/varia.sql +35 -0
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
import { isLegacyReportCollectionName } from './naming.js';
|
|
2
|
+
export const reportFilters = [
|
|
3
|
+
{ name: 'scoutsjaar', title: 'Scoutsjaar', valuesFrom: 'scoutsjaar', column: 'Scoutsjaar', keepOrder: false, multiple: false },
|
|
4
|
+
{ name: 'eenheid', title: 'Eenheid', valuesFrom: 'eenheid', column: 'Eenheid', keepOrder: false, multiple: false },
|
|
5
|
+
{ name: 'aansluiting', title: 'Aansluiting', valuesFrom: 'aansluiting', column: 'Aansluiting', keepOrder: false, multiple: true },
|
|
6
|
+
{ name: 'ingeschreven_voor', title: 'Ingeschreven voor', valuesFrom: 'ingeschreven-voor', column: 'Ingeschreven voor', keepOrder: true, multiple: true, start: ['Leeftijdsgroepen'] },
|
|
7
|
+
];
|
|
8
|
+
/**
|
|
9
|
+
* What a question is called in the collection.
|
|
10
|
+
*
|
|
11
|
+
* Qualified with its tab because a title is not unique — the report shows "Aantal leden per postcode"
|
|
12
|
+
* on two pages, as the client's own does — and questions are matched by name to be updated in place.
|
|
13
|
+
* Two of them sharing a name means one silently overwrites the other. The dashboard still shows the
|
|
14
|
+
* plain title: that comes from the card's own `card.title` setting.
|
|
15
|
+
*/
|
|
16
|
+
export function cardName(card, tab) {
|
|
17
|
+
return `${card.title} (${tab.title})`;
|
|
18
|
+
}
|
|
19
|
+
/** Metabase lays a dashboard out on a 24 column grid. */
|
|
20
|
+
const gridWidth = 24;
|
|
21
|
+
const widths = { full: 24, 'two-thirds': 16, half: 12, third: 8, quarter: 6, sixth: 4 };
|
|
22
|
+
/**
|
|
23
|
+
* Extra rows for the band the rotated labels sit in.
|
|
24
|
+
*
|
|
25
|
+
* Rotated labels are drawn below the plot and eat into it, which leaves a card at the normal height
|
|
26
|
+
* with bars too short to tell apart. The band is as tall as the longest label, which has nothing to
|
|
27
|
+
* do with how wide the card is, so this is added on top rather than scaled.
|
|
28
|
+
*/
|
|
29
|
+
const xLabelRows = {
|
|
30
|
+
show: 0,
|
|
31
|
+
hide: 0,
|
|
32
|
+
compact: 0,
|
|
33
|
+
'rotate-45': 4,
|
|
34
|
+
'rotate-90': 6,
|
|
35
|
+
};
|
|
36
|
+
function heightOf(card) {
|
|
37
|
+
if (card.height !== undefined) {
|
|
38
|
+
return card.height;
|
|
39
|
+
}
|
|
40
|
+
if (card.display === 'scalar') {
|
|
41
|
+
return 3;
|
|
42
|
+
}
|
|
43
|
+
// A gauge stands next to the chart of the same figure over the years, and only sits level with it
|
|
44
|
+
// at the height of a chart.
|
|
45
|
+
if (card.display === 'gauge') {
|
|
46
|
+
return 6;
|
|
47
|
+
}
|
|
48
|
+
if (card.display === 'table') {
|
|
49
|
+
return 8;
|
|
50
|
+
}
|
|
51
|
+
// A row chart is as tall as the rows it has to hold: Metabase gives each of them 24 pixels and
|
|
52
|
+
// silently drops the ones that no longer fit, so a row chart at the height of a normal chart
|
|
53
|
+
// would quietly stop showing the oldest scoutsjaren as the years pile up. Ten grid rows hold
|
|
54
|
+
// some eighteen of them.
|
|
55
|
+
if (card.display === 'row') {
|
|
56
|
+
return 10;
|
|
57
|
+
}
|
|
58
|
+
return (card.size === 'full' ? 7 : 6) + (card.xLabels === undefined ? 0 : xLabelRows[card.xLabels]);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Places the cards left to right in the order the report lists them, wrapping to a new row when the
|
|
62
|
+
* next one no longer fits.
|
|
63
|
+
*
|
|
64
|
+
* A row is as tall as its tallest card and every card in it is drawn that tall, so the row ends on
|
|
65
|
+
* one line. The cards of a row are two readings of one thing -- the geslachten as a pie beside the
|
|
66
|
+
* geslachten over the years -- and one of them stopping halfway leaves a hole under it that the row
|
|
67
|
+
* below cannot fill.
|
|
68
|
+
*
|
|
69
|
+
* A card that spans rows keeps its columns in the rows below it, which the cards after it wrap
|
|
70
|
+
* around, and ends up as tall as those rows together: the netwerk map stands beside the chart and
|
|
71
|
+
* the pie stacked next to it. It does not decide how tall those rows are -- the cards stacked beside
|
|
72
|
+
* it do, which is what makes it end exactly where they do.
|
|
73
|
+
*/
|
|
74
|
+
export function layoutCards(cards) {
|
|
75
|
+
const rows = [];
|
|
76
|
+
const placed = [];
|
|
77
|
+
let index = 0;
|
|
78
|
+
const rowAt = (position) => {
|
|
79
|
+
while (rows.length <= position) {
|
|
80
|
+
rows.push({ taken: [], height: 0 });
|
|
81
|
+
}
|
|
82
|
+
return rows[position];
|
|
83
|
+
};
|
|
84
|
+
for (const card of cards) {
|
|
85
|
+
const sizeX = widths[card.size];
|
|
86
|
+
let col = freeColumn(rowAt(index), sizeX);
|
|
87
|
+
while (col === undefined) {
|
|
88
|
+
index += 1;
|
|
89
|
+
col = freeColumn(rowAt(index), sizeX);
|
|
90
|
+
}
|
|
91
|
+
for (let offset = 0; offset < card.span; offset++) {
|
|
92
|
+
rowAt(index + offset).taken.push({ col, sizeX });
|
|
93
|
+
}
|
|
94
|
+
// Only what a row holds on its own decides how tall it is. A card spanning several still has
|
|
95
|
+
// to fit in them, so it asks each for its share -- which is what a row holding nothing else
|
|
96
|
+
// ends up at.
|
|
97
|
+
const height = card.span === 1 ? heightOf(card) : Math.ceil(heightOf(card) / card.span);
|
|
98
|
+
for (let offset = 0; offset < card.span; offset++) {
|
|
99
|
+
rowAt(index + offset).height = Math.max(rowAt(index + offset).height, height);
|
|
100
|
+
}
|
|
101
|
+
placed.push({ card, index, col, sizeX });
|
|
102
|
+
}
|
|
103
|
+
const tops = rows.reduce((offsets, row, position) => [...offsets, offsets[position] + row.height], [0]);
|
|
104
|
+
return placed.map(entry => ({
|
|
105
|
+
card: entry.card,
|
|
106
|
+
row: tops[entry.index],
|
|
107
|
+
col: entry.col,
|
|
108
|
+
sizeX: entry.sizeX,
|
|
109
|
+
sizeY: tops[entry.index + entry.card.span] - tops[entry.index],
|
|
110
|
+
}));
|
|
111
|
+
}
|
|
112
|
+
/** The leftmost column a card of this width still fits at, or nothing when the row is full. */
|
|
113
|
+
function freeColumn(row, sizeX) {
|
|
114
|
+
for (let col = 0; col + sizeX <= gridWidth; col++) {
|
|
115
|
+
if (row.taken.every(entry => col + sizeX <= entry.col || entry.col + entry.sizeX <= col)) {
|
|
116
|
+
return col;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Metabase identifies a template tag by a uuid that has to stay the same between runs, otherwise
|
|
123
|
+
* every filter connection is rebuilt on each push. Derived from the card and parameter name so it is
|
|
124
|
+
* stable without having to be stored anywhere.
|
|
125
|
+
*/
|
|
126
|
+
export function templateTagId(cardKey, parameter) {
|
|
127
|
+
const seed = `${cardKey}:${parameter}`;
|
|
128
|
+
let hash = 0;
|
|
129
|
+
for (const character of seed) {
|
|
130
|
+
hash = (Math.imul(hash, 31) + character.codePointAt(0)) | 0;
|
|
131
|
+
}
|
|
132
|
+
const hex = (Math.abs(hash) >>> 0).toString(16).padStart(8, '0');
|
|
133
|
+
return `${hex}-0000-4000-8000-${hex}00000000`.slice(0, 36);
|
|
134
|
+
}
|
|
135
|
+
export function buildTemplateTags(card) {
|
|
136
|
+
const tags = {};
|
|
137
|
+
for (const parameter of card.parameters) {
|
|
138
|
+
const filter = reportFilters.find(entry => entry.name === parameter);
|
|
139
|
+
tags[parameter] = {
|
|
140
|
+
id: templateTagId(card.key, parameter),
|
|
141
|
+
name: parameter,
|
|
142
|
+
'display-name': filter?.title ?? parameter,
|
|
143
|
+
type: 'text',
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
return tags;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* What Metabase actually draws. A map needs a coordinate per postal code, and those are loaded
|
|
150
|
+
* separately from anything Stamhoofd holds; while `postal_codes` is empty the card is a bar chart of
|
|
151
|
+
* the same figures rather than an empty map.
|
|
152
|
+
*/
|
|
153
|
+
export function effectiveDisplay(card, hasCoordinates) {
|
|
154
|
+
return card.display === 'map' && !hasCoordinates ? 'bar' : card.display;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* The scale the ranges of a figure are colored along: red where it is at its worst, green where it is
|
|
158
|
+
* at its best, through the yellow that lies between them. Metabase's own three, so these cards sit
|
|
159
|
+
* beside the rest of the report rather than beside a palette of their own.
|
|
160
|
+
*/
|
|
161
|
+
const segmentScale = ['#ED6E6E', '#F9CF48', '#84BB4C'];
|
|
162
|
+
/**
|
|
163
|
+
* The color of each range, mixed along that scale rather than picked per range: the ranges of a
|
|
164
|
+
* figure are read against each other, so what a color says has to be where it sits between the worst
|
|
165
|
+
* and the best -- whether a card splits the figure in three or in six.
|
|
166
|
+
*
|
|
167
|
+
* A figure that is better the lower it is runs the scale the other way, which is the whole of the
|
|
168
|
+
* difference between the two figures of the page: green is always the end an eenheid is doing well at.
|
|
169
|
+
*/
|
|
170
|
+
export function segmentColors(count, best) {
|
|
171
|
+
const colors = [...new Array(count).keys()].map((index) => {
|
|
172
|
+
const position = count === 1 ? 0 : (index / (count - 1)) * (segmentScale.length - 1);
|
|
173
|
+
const step = Math.min(Math.floor(position), segmentScale.length - 2);
|
|
174
|
+
return mixColors(segmentScale[step], segmentScale[step + 1], position - step);
|
|
175
|
+
});
|
|
176
|
+
return best === 'low' ? colors.reverse() : colors;
|
|
177
|
+
}
|
|
178
|
+
function mixColors(from, to, ratio) {
|
|
179
|
+
const channels = [0, 1, 2].map((channel) => {
|
|
180
|
+
const start = Number.parseInt(from.slice(1 + channel * 2, 3 + channel * 2), 16);
|
|
181
|
+
const end = Number.parseInt(to.slice(1 + channel * 2, 3 + channel * 2), 16);
|
|
182
|
+
return Math.round(start + (end - start) * ratio).toString(16).padStart(2, '0');
|
|
183
|
+
});
|
|
184
|
+
return `#${channels.join('')}`;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* What a range is called under the gauge. The two outer ones say where they open rather than where
|
|
188
|
+
* they end: they are as long as the arc has room for, and an eenheid twice over the highest boundary
|
|
189
|
+
* is read in the same range as one just above it.
|
|
190
|
+
*/
|
|
191
|
+
function gaugeLabel(segments, index) {
|
|
192
|
+
if (index === 0) {
|
|
193
|
+
return `< ${segments[1]}`;
|
|
194
|
+
}
|
|
195
|
+
if (index === segments.length - 2) {
|
|
196
|
+
return `> ${segments[index]}`;
|
|
197
|
+
}
|
|
198
|
+
return `${segments[index]}-${segments[index + 1]}`;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* The ranges of a figure as the display reading them says it. The colors are the same either way --
|
|
202
|
+
* the number at the top of the page and the meter below it are read together -- but the ends are
|
|
203
|
+
* not. An arc has to stop somewhere, while a number has nowhere to run out of: leaving its outer
|
|
204
|
+
* ranges open is what keeps an eenheid past the last boundary colored at all, instead of falling
|
|
205
|
+
* outside every range and being drawn in the plain text color exactly where it matters most.
|
|
206
|
+
*
|
|
207
|
+
* Only the arc carries labels. Under a number Metabase writes each range beside its own color.
|
|
208
|
+
*/
|
|
209
|
+
function buildSegments(card, display) {
|
|
210
|
+
const colors = segmentColors(card.segments.length - 1, card.best);
|
|
211
|
+
return card.segments.slice(0, -1).map((min, index) => {
|
|
212
|
+
const open = display === 'scalar';
|
|
213
|
+
const last = index === card.segments.length - 2;
|
|
214
|
+
return {
|
|
215
|
+
...(open && index === 0 ? {} : { min }),
|
|
216
|
+
...(open && last ? {} : { max: card.segments[index + 1] }),
|
|
217
|
+
color: colors[index],
|
|
218
|
+
...(display === 'gauge' ? { label: gaugeLabel(card.segments, index) } : {}),
|
|
219
|
+
};
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* The colors the values of a column are drawn in, wherever a card splits on it.
|
|
224
|
+
*
|
|
225
|
+
* Kept by the column rather than by the card because the same split stands on several pages -- the
|
|
226
|
+
* geslachten are a pie on two of them and the bars of a third -- and someone reading two pages side
|
|
227
|
+
* by side reads the colors before the legend. A value the palette does not name keeps whichever
|
|
228
|
+
* color Metabase gives it.
|
|
229
|
+
*/
|
|
230
|
+
export const columnPalettes = new Map([
|
|
231
|
+
['Geslacht', {
|
|
232
|
+
Man: '#0892D0',
|
|
233
|
+
Vrouw: '#DE8A8A',
|
|
234
|
+
Andere: '#8A2BE2',
|
|
235
|
+
Onbekend: '#949AAB',
|
|
236
|
+
}],
|
|
237
|
+
]);
|
|
238
|
+
/**
|
|
239
|
+
* The colors a chart falls back to, per platform: the ones the platform shows itself in everywhere
|
|
240
|
+
* else. A chart takes them for the series nothing else has colored -- a column palette colors first,
|
|
241
|
+
* and a card that says its own colors keeps them -- which is what makes these the default rather
|
|
242
|
+
* than the colors. A platform the report is not written for keeps Metabase's own palette.
|
|
243
|
+
*
|
|
244
|
+
* Said per card because the setting that colors every chart of an instance at once,
|
|
245
|
+
* `application-colors`, is a paid feature. An instance serves one platform anyway.
|
|
246
|
+
*/
|
|
247
|
+
export const environmentColors = new Map([
|
|
248
|
+
['keeo', ['#00549E', '#C7DD06', '#FF5797']],
|
|
249
|
+
['ravot', ['#0067B1', '#EF3E42', '#ED7D34']],
|
|
250
|
+
]);
|
|
251
|
+
/** How many series a chart is handed colors for before Metabase's own palette takes over. */
|
|
252
|
+
const chartColorCount = 12;
|
|
253
|
+
/**
|
|
254
|
+
* The platform's colors, and after them the same ones lightened and darkened.
|
|
255
|
+
*
|
|
256
|
+
* A chart with more series than the platform has colors has to get them from somewhere: repeating
|
|
257
|
+
* one draws two takken as if they were one, and stopping after three leaves the rest of the legend in
|
|
258
|
+
* Metabase's palette, which reads as a chart drawn in two sets of colors. Shades of the three stay
|
|
259
|
+
* the platform's own.
|
|
260
|
+
*/
|
|
261
|
+
export function chartColors(colors, count = chartColorCount) {
|
|
262
|
+
// Towards white where positive, towards black where negative, and the platform's own where zero.
|
|
263
|
+
const shades = [0, 0.35, -0.3, 0.6, -0.55];
|
|
264
|
+
return [...new Array(count).keys()].map((index) => {
|
|
265
|
+
const color = colors[index % colors.length];
|
|
266
|
+
const shade = shades[Math.floor(index / colors.length) % shades.length];
|
|
267
|
+
return shade === 0 ? color : mixColors(color, shade > 0 ? '#FFFFFF' : '#000000', Math.abs(shade));
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* How the report describes its x-axis labels, in what Metabase calls them.
|
|
272
|
+
*/
|
|
273
|
+
const xAxisLabels = {
|
|
274
|
+
show: true,
|
|
275
|
+
hide: false,
|
|
276
|
+
compact: 'compact',
|
|
277
|
+
'rotate-45': 'rotate-45',
|
|
278
|
+
'rotate-90': 'rotate-90',
|
|
279
|
+
};
|
|
280
|
+
export function buildVisualizationSettings(card, hasCoordinates = true, env) {
|
|
281
|
+
const settings = { 'card.title': card.title };
|
|
282
|
+
if (card.description !== undefined) {
|
|
283
|
+
settings['card.description'] = card.description;
|
|
284
|
+
}
|
|
285
|
+
// What the header of an export reads. Metabase writes it from the column's title and falls back
|
|
286
|
+
// to what it makes of the alias itself, which is not what a sheet delivered to a government
|
|
287
|
+
// department may be called. Keyed by name rather than by field, the way a native query's columns
|
|
288
|
+
// are addressed; a key matching no column is ignored, so a renamed column loses its title
|
|
289
|
+
// instead of dropping the sheet's other columns.
|
|
290
|
+
if (card.columns.length > 0) {
|
|
291
|
+
settings['column_settings'] = Object.fromEntries(card.columns.map(column => [JSON.stringify(['name', column]), { column_title: column }]));
|
|
292
|
+
}
|
|
293
|
+
const display = effectiveDisplay(card, hasCoordinates);
|
|
294
|
+
if (display === 'map') {
|
|
295
|
+
// A pin map, which needs nothing but the two coordinate columns: Metabase only knows the
|
|
296
|
+
// outlines of countries and US states, and a map of Belgian postal code areas would mean
|
|
297
|
+
// hosting a GeoJSON on a public url for it to fetch.
|
|
298
|
+
settings['map.type'] = 'pin';
|
|
299
|
+
settings['map.latitude_column'] = card.latitude;
|
|
300
|
+
settings['map.longitude_column'] = card.longitude;
|
|
301
|
+
return settings;
|
|
302
|
+
}
|
|
303
|
+
if (display === 'gauge') {
|
|
304
|
+
// Left unsaid, Metabase splits the arc in three equal ranges of its own between 0 and the
|
|
305
|
+
// value it first drew, which says nothing about whether the figure is a good one.
|
|
306
|
+
if (card.segments.length > 0) {
|
|
307
|
+
settings['gauge.segments'] = buildSegments(card, 'gauge');
|
|
308
|
+
}
|
|
309
|
+
return settings;
|
|
310
|
+
}
|
|
311
|
+
if (display === 'scalar') {
|
|
312
|
+
// The figure at the top of the page in the color of the range it falls in, so it says what
|
|
313
|
+
// the meter further down says without having to be read against it.
|
|
314
|
+
if (card.segments.length > 0) {
|
|
315
|
+
settings['scalar.segments'] = buildSegments(card, 'scalar');
|
|
316
|
+
}
|
|
317
|
+
return settings;
|
|
318
|
+
}
|
|
319
|
+
if (display === 'pie') {
|
|
320
|
+
settings['pie.dimension'] = card.dimensions[0];
|
|
321
|
+
settings['pie.metric'] = card.metrics[0];
|
|
322
|
+
// Keyed by the value of the dimension, which is what a slice is: the pie has no series to
|
|
323
|
+
// hang a color on the way a bar chart does.
|
|
324
|
+
const palette = columnPalettes.get(card.dimensions[0]);
|
|
325
|
+
if (palette !== undefined) {
|
|
326
|
+
settings['pie.colors'] = palette;
|
|
327
|
+
}
|
|
328
|
+
return settings;
|
|
329
|
+
}
|
|
330
|
+
if (['bar', 'line', 'combo', 'area', 'row'].includes(display)) {
|
|
331
|
+
settings['graph.dimensions'] = card.dimensions;
|
|
332
|
+
settings['graph.metrics'] = card.metrics;
|
|
333
|
+
// Left unset, Metabase decides for itself and drops the labels when too many do not fit --
|
|
334
|
+
// which is every chart with a bar per eenheid. An explicit value is used as given.
|
|
335
|
+
if (card.xLabels !== undefined) {
|
|
336
|
+
settings['graph.x_axis.axis_enabled'] = xAxisLabels[card.xLabels];
|
|
337
|
+
}
|
|
338
|
+
if (card.stacked !== undefined) {
|
|
339
|
+
settings['stackable.stack_type'] = card.stacked === 'normalized' ? 'normalized' : 'stacked';
|
|
340
|
+
}
|
|
341
|
+
// Under `series_settings` -- one of the few settings without the `graph.` prefix, and an
|
|
342
|
+
// unknown key is dropped without a word. A chart with a second dimension draws a series per
|
|
343
|
+
// value of it, keyed by the value itself; one without draws a series per metric, keyed by
|
|
344
|
+
// the column name.
|
|
345
|
+
const series = Object.fromEntries(Object.entries(columnPalettes.get(card.dimensions[1]) ?? {}).map(([value, color]) => [value, { color }]));
|
|
346
|
+
const platform = env === undefined ? undefined : environmentColors.get(env);
|
|
347
|
+
if (platform !== undefined) {
|
|
348
|
+
const colors = chartColors(platform);
|
|
349
|
+
// By position, since the series of a chart that splits on a column are its values, which
|
|
350
|
+
// are in the data rather than in the report. Metabase reads them only where nothing else
|
|
351
|
+
// colored that series.
|
|
352
|
+
settings['graph.colors'] = colors;
|
|
353
|
+
// A chart without a second dimension draws a series per metric, and a metric has a name
|
|
354
|
+
// this can hand a color to. It is also the only place a row chart reads a color: that
|
|
355
|
+
// one colors by series name and never looks at `graph.colors`.
|
|
356
|
+
if (card.dimensions.length < 2) {
|
|
357
|
+
for (const [index, metric] of card.metrics.entries()) {
|
|
358
|
+
series[metric] = { ...series[metric], color: colors[index] };
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
// Left to itself a combo chart draws its first series as a line and the rest as bars, the
|
|
363
|
+
// other way round from what the "aantal leden + GTP index" chart needs, so every series is
|
|
364
|
+
// given its own shape.
|
|
365
|
+
if (display === 'combo') {
|
|
366
|
+
for (const [index, metric] of card.metrics.entries()) {
|
|
367
|
+
series[metric] = { ...series[metric], display: index === 0 ? 'bar' : 'line' };
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
if (Object.keys(series).length > 0) {
|
|
371
|
+
settings['series_settings'] = series;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return settings;
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* The filters shown above the dashboard: every one that any tab asks for.
|
|
378
|
+
*
|
|
379
|
+
* Metabase puts filters above the whole dashboard rather than on a tab, so a filter named by one tab
|
|
380
|
+
* is visible on all of them. Which cards it actually reaches is decided per tab in `buildDashcards`,
|
|
381
|
+
* so the Eenheid filter cannot quietly turn the national figures into one unit's.
|
|
382
|
+
*/
|
|
383
|
+
export function buildParameters(tabs, filterCardIds, orderedValues = new Map()) {
|
|
384
|
+
const wanted = new Set(tabs.flatMap(tab => tab.filters));
|
|
385
|
+
return reportFilters
|
|
386
|
+
.filter(filter => wanted.has(filter.name))
|
|
387
|
+
.map((filter) => {
|
|
388
|
+
const cardId = filterCardIds.get(filter.valuesFrom);
|
|
389
|
+
const values = filter.keepOrder ? orderedValues.get(filter.valuesFrom) : undefined;
|
|
390
|
+
return {
|
|
391
|
+
id: templateTagId('dashboard', filter.name).slice(0, 8),
|
|
392
|
+
name: filter.title,
|
|
393
|
+
slug: filter.name,
|
|
394
|
+
type: 'string/=',
|
|
395
|
+
sectionId: 'string',
|
|
396
|
+
isMultiSelect: filter.multiple,
|
|
397
|
+
// Without this the widget is a plain text box, however well the values source is
|
|
398
|
+
// configured: it is what picks the dropdown over an input box.
|
|
399
|
+
values_query_type: 'list',
|
|
400
|
+
// A list even where one value is chosen: a multi-select filter hands its cards every
|
|
401
|
+
// value it holds, and a bare string is read as a filter holding none.
|
|
402
|
+
...(filter.start === undefined ? {} : { default: filter.start }),
|
|
403
|
+
...buildValuesSource(filter.column, cardId, values),
|
|
404
|
+
};
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Where a dropdown gets its values. A fixed list when the order matters and the values are known,
|
|
409
|
+
* otherwise the question itself, which keeps the list up to date on its own.
|
|
410
|
+
*/
|
|
411
|
+
function buildValuesSource(column, cardId, values) {
|
|
412
|
+
if (values !== undefined && values.length > 0) {
|
|
413
|
+
return { values_source_type: 'static-list', values_source_config: { values } };
|
|
414
|
+
}
|
|
415
|
+
if (cardId === undefined) {
|
|
416
|
+
return {};
|
|
417
|
+
}
|
|
418
|
+
return {
|
|
419
|
+
values_source_type: 'card',
|
|
420
|
+
values_source_config: {
|
|
421
|
+
card_id: cardId,
|
|
422
|
+
value_field: ['field', column, { 'base-type': 'type/Text' }],
|
|
423
|
+
},
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* The tabs, in the order the report lists them. A tab that is already there keeps its id so links
|
|
428
|
+
* into it survive; a new one gets a negative id, which is how Metabase is told to create it.
|
|
429
|
+
*/
|
|
430
|
+
export function buildTabs(tabs, existing) {
|
|
431
|
+
return tabs.map((tab, position) => ({
|
|
432
|
+
id: existing.get(tab.title) ?? -(position + 1),
|
|
433
|
+
name: tab.title,
|
|
434
|
+
position,
|
|
435
|
+
}));
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Where each card of the report sits on the dashboard.
|
|
439
|
+
*
|
|
440
|
+
* `existing` holds the placed cards the dashboard already has, keyed by tab and card, so a card that
|
|
441
|
+
* is still there keeps the id it was placed under. Metabase addresses a card on a dashboard by that
|
|
442
|
+
* id: giving out new ones on every run leaves anyone with the dashboard open asking for placements
|
|
443
|
+
* that no longer exist, and every card on their screen answers 404 until they load the page again.
|
|
444
|
+
*/
|
|
445
|
+
/** How a placed card is recognised between two runs: the same card on the same tab. */
|
|
446
|
+
export function dashcardKey(tabId, cardId) {
|
|
447
|
+
return `${tabId ?? ''}:${cardId ?? ''}`;
|
|
448
|
+
}
|
|
449
|
+
export function buildDashcards(tabs, cardIds, parameters, tabIds, existing = new Map()) {
|
|
450
|
+
const dashcards = [];
|
|
451
|
+
const free = new Map(existing);
|
|
452
|
+
for (const tab of tabs) {
|
|
453
|
+
for (const placed of layoutCards(tab.cards)) {
|
|
454
|
+
const cardId = cardIds.get(placed.card.key);
|
|
455
|
+
const tabId = tabIds.get(tab.title);
|
|
456
|
+
const key = dashcardKey(tabId, cardId);
|
|
457
|
+
const id = free.get(key);
|
|
458
|
+
// Only once: the same card placed twice on a tab is one placement that stays and one new.
|
|
459
|
+
free.delete(key);
|
|
460
|
+
dashcards.push({
|
|
461
|
+
// Metabase reads a negative id as "this one is new".
|
|
462
|
+
id: id ?? -1 - dashcards.length,
|
|
463
|
+
card_id: cardId,
|
|
464
|
+
dashboard_tab_id: tabId,
|
|
465
|
+
row: placed.row,
|
|
466
|
+
col: placed.col,
|
|
467
|
+
size_x: placed.sizeX,
|
|
468
|
+
size_y: placed.sizeY,
|
|
469
|
+
visualization_settings: {},
|
|
470
|
+
parameter_mappings: parameters
|
|
471
|
+
// A filter reaches a card only when its own tab asks for it and its query takes it.
|
|
472
|
+
.filter(parameter => tab.filters.includes(parameter.slug) && placed.card.parameters.includes(parameter.slug))
|
|
473
|
+
.map(parameter => ({
|
|
474
|
+
parameter_id: parameter.id,
|
|
475
|
+
card_id: cardId,
|
|
476
|
+
target: ['variable', ['template-tag', parameter.slug]],
|
|
477
|
+
})),
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
return dashcards;
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Where the first dashboard is pinned in its collection; the ones after it follow. Pinned because
|
|
485
|
+
* the dashboards are the only things in there worth opening directly -- everything else in the
|
|
486
|
+
* collection is a question one of them draws.
|
|
487
|
+
*/
|
|
488
|
+
export const reportCollectionPosition = 1;
|
|
489
|
+
/**
|
|
490
|
+
* The dashboards to write and the tabs each of them holds, in the order the report lists them. A tab
|
|
491
|
+
* lands on the report's own dashboard unless it names one, which is what gives a tab that mirrors no
|
|
492
|
+
* page of the client's report -- the aanlevering to the department -- a dashboard of its own.
|
|
493
|
+
*/
|
|
494
|
+
export function groupByDashboard(tabs, dashboardName) {
|
|
495
|
+
const dashboards = [];
|
|
496
|
+
for (const tab of tabs) {
|
|
497
|
+
const name = tab.dashboard ?? dashboardName;
|
|
498
|
+
const dashboard = dashboards.find(entry => entry.name === name);
|
|
499
|
+
if (dashboard) {
|
|
500
|
+
dashboard.tabs.push(tab);
|
|
501
|
+
}
|
|
502
|
+
else {
|
|
503
|
+
dashboards.push({ name, tabs: [tab] });
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
return dashboards;
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* Write the whole report to Metabase: a dashboard with a tab per page, and one per tab that asked for
|
|
510
|
+
* its own. Cards first, because a dashboard can only point at cards that exist, and the filter
|
|
511
|
+
* dropdowns point at cards too.
|
|
512
|
+
*
|
|
513
|
+
* `env` is the platform being written, the same name the report was loaded for. It says which colors
|
|
514
|
+
* a chart falls back to; without it they are Metabase's.
|
|
515
|
+
*/
|
|
516
|
+
export async function syncReport(api, databaseId, tabs, collection, dashboardName, hasCoordinates = false, env) {
|
|
517
|
+
const renamedCollection = await renameLegacyCollection(api, collection);
|
|
518
|
+
const { id: collectionId, created: createdCollection } = await api.ensureCollection(collection);
|
|
519
|
+
const existingCards = new Map((await api.listCards(collectionId)).map(card => [card.name, card.id]));
|
|
520
|
+
const cardIds = new Map();
|
|
521
|
+
const filterCardIds = new Map();
|
|
522
|
+
for (const tab of tabs) {
|
|
523
|
+
for (const card of tab.cards) {
|
|
524
|
+
const id = await api.saveCard({
|
|
525
|
+
name: cardName(card, tab),
|
|
526
|
+
description: card.description,
|
|
527
|
+
display: effectiveDisplay(card, hasCoordinates),
|
|
528
|
+
databaseId,
|
|
529
|
+
query: card.sql,
|
|
530
|
+
templateTags: buildTemplateTags(card),
|
|
531
|
+
visualizationSettings: buildVisualizationSettings(card, hasCoordinates, env),
|
|
532
|
+
collectionId,
|
|
533
|
+
}, existingCards.get(cardName(card, tab)));
|
|
534
|
+
cardIds.set(card.key, id);
|
|
535
|
+
if (tab.hidden) {
|
|
536
|
+
filterCardIds.set(card.key, id);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
const visible = tabs.filter(tab => !tab.hidden);
|
|
541
|
+
const orderedValues = await readOrderedValues(api, filterCardIds);
|
|
542
|
+
const existingDashboards = await api.listDashboards(collectionId);
|
|
543
|
+
const written = [];
|
|
544
|
+
for (const [index, dashboard] of groupByDashboard(visible, dashboardName).entries()) {
|
|
545
|
+
const dashboardId = existingDashboards.find(entry => entry.name === dashboard.name)?.id
|
|
546
|
+
?? await api.createDashboard(dashboard.name, undefined, collectionId);
|
|
547
|
+
const layout = await api.getDashboardLayout(dashboardId);
|
|
548
|
+
const existingTabs = new Map(layout.tabs.map(tab => [tab.name, tab.id]));
|
|
549
|
+
const existingDashcards = new Map(layout.cards.map(placed => [dashcardKey(placed.tabId, placed.cardId), placed.id]));
|
|
550
|
+
const parameters = buildParameters(dashboard.tabs, filterCardIds, orderedValues);
|
|
551
|
+
const dashboardTabs = buildTabs(dashboard.tabs, existingTabs);
|
|
552
|
+
const tabIds = new Map(dashboardTabs.map(tab => [tab.name, tab.id]));
|
|
553
|
+
await api.updateDashboard(dashboardId, {
|
|
554
|
+
name: dashboard.name,
|
|
555
|
+
parameters,
|
|
556
|
+
tabs: dashboardTabs,
|
|
557
|
+
dashcards: buildDashcards(dashboard.tabs, cardIds, parameters, tabIds, existingDashcards),
|
|
558
|
+
// Pinned in the order the report writes them, so the pages the client knows stay first.
|
|
559
|
+
collectionPosition: reportCollectionPosition + index,
|
|
560
|
+
});
|
|
561
|
+
const { created: bookmarked } = await api.bookmarkDashboard(dashboardId);
|
|
562
|
+
written.push({ name: dashboard.name, id: dashboardId, tabs: dashboard.tabs.map(tab => tab.title), bookmarked });
|
|
563
|
+
}
|
|
564
|
+
await archiveSupersededDashboards(api, existingDashboards, visible, written.map(dashboard => dashboard.name));
|
|
565
|
+
await archiveSupersededCards(api, collectionId, tabs);
|
|
566
|
+
// Deduplicated: two tabs show a map under the same title, and naming it twice reads as an error.
|
|
567
|
+
const mapsWithoutCoordinates = [...new Set(tabs
|
|
568
|
+
.flatMap(tab => tab.cards)
|
|
569
|
+
.filter(card => card.display === 'map' && !hasCoordinates)
|
|
570
|
+
.map(card => card.title))];
|
|
571
|
+
return { collection, collectionId, createdCollection, renamedCollection, dashboards: written, cards: cardIds.size, mapsWithoutCoordinates };
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* The collection to rename into the one written now: the one this wrote while collections were named
|
|
575
|
+
* per environment. Renaming keeps its id, and with it every question, dashboard, link and bookmark
|
|
576
|
+
* that points into it, where writing a new collection would leave all of that behind.
|
|
577
|
+
*
|
|
578
|
+
* Only when exactly one is left, which is every instance that serves one platform. A development
|
|
579
|
+
* machine that served several has no single right answer, so it gets a new collection and can throw
|
|
580
|
+
* the old ones away itself.
|
|
581
|
+
*/
|
|
582
|
+
export function collectionToRename(collections, name) {
|
|
583
|
+
if (collections.some(collection => collection.name === name)) {
|
|
584
|
+
return undefined;
|
|
585
|
+
}
|
|
586
|
+
const legacy = collections.filter(collection => isLegacyReportCollectionName(collection.name));
|
|
587
|
+
return legacy.length === 1 ? legacy[0] : undefined;
|
|
588
|
+
}
|
|
589
|
+
async function renameLegacyCollection(api, name) {
|
|
590
|
+
const legacy = collectionToRename(await api.listCollections(), name);
|
|
591
|
+
if (!legacy) {
|
|
592
|
+
return undefined;
|
|
593
|
+
}
|
|
594
|
+
await api.renameCollection(legacy.id, name);
|
|
595
|
+
return legacy.name;
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* Clear away questions this command wrote earlier that the report no longer has: a renamed card, a
|
|
599
|
+
* removed one, or one left behind by the older naming that did not qualify a title with its tab.
|
|
600
|
+
*
|
|
601
|
+
* Only names this command could have produced are touched, so a question the client saved into the
|
|
602
|
+
* collection themselves stays where it is.
|
|
603
|
+
*/
|
|
604
|
+
async function archiveSupersededCards(api, collectionId, tabs) {
|
|
605
|
+
const wanted = new Set(tabs.flatMap(tab => tab.cards.map(card => cardName(card, tab))));
|
|
606
|
+
const ours = new Set(tabs.flatMap(tab => tab.cards.map(card => card.title)));
|
|
607
|
+
const tabTitles = tabs.map(tab => tab.title);
|
|
608
|
+
for (const card of await api.listCards(collectionId)) {
|
|
609
|
+
if (wanted.has(card.name)) {
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
const qualified = tabTitles.some(title => card.name.endsWith(` (${title})`));
|
|
613
|
+
if (ours.has(card.name) || qualified) {
|
|
614
|
+
await api.archiveCard(card.id);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* Clear away the dashboard-per-page layout an earlier version of this command left behind. Only
|
|
620
|
+
* dashboards named exactly after a tab are touched, so anything the client built themselves stays,
|
|
621
|
+
* and never one this run just wrote: a tab may share its name with the dashboard it asked for.
|
|
622
|
+
*/
|
|
623
|
+
async function archiveSupersededDashboards(api, existing, tabs, written) {
|
|
624
|
+
const titles = new Set(tabs.map(tab => tab.title));
|
|
625
|
+
const ours = new Set(written);
|
|
626
|
+
for (const dashboard of existing.filter(dashboard => !ours.has(dashboard.name) && titles.has(dashboard.name))) {
|
|
627
|
+
await api.archiveDashboard(dashboard.id);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* Run the filter questions whose order has to be kept and remember what they returned.
|
|
632
|
+
*
|
|
633
|
+
* A question that cannot run yet — an empty statistics database, most likely — is not worth failing
|
|
634
|
+
* the whole push for: that filter falls back to reading its values from the question, which costs
|
|
635
|
+
* the ordering but keeps the dashboards working.
|
|
636
|
+
*/
|
|
637
|
+
async function readOrderedValues(api, filterCardIds) {
|
|
638
|
+
const values = new Map();
|
|
639
|
+
for (const filter of reportFilters.filter(filter => filter.keepOrder)) {
|
|
640
|
+
const cardId = filterCardIds.get(filter.valuesFrom);
|
|
641
|
+
if (cardId === undefined) {
|
|
642
|
+
continue;
|
|
643
|
+
}
|
|
644
|
+
try {
|
|
645
|
+
values.set(filter.valuesFrom, await api.runCardValues(cardId));
|
|
646
|
+
}
|
|
647
|
+
catch {
|
|
648
|
+
continue;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
return values;
|
|
652
|
+
}
|
|
653
|
+
//# sourceMappingURL=sync-report.js.map
|