@backstage-community/plugin-opencost 0.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1536 @@
1
+ import React, { useState, useEffect } from 'react';
2
+ import Grid from '@material-ui/core/Grid';
3
+ import { Page as Page$1, Header, Content } from '@backstage/core-components';
4
+ import CircularProgress from '@material-ui/core/CircularProgress';
5
+ import IconButton from '@material-ui/core/IconButton';
6
+ import Paper from '@material-ui/core/Paper';
7
+ import RefreshIcon from '@material-ui/icons/Refresh';
8
+ import Typography from '@material-ui/core/Typography';
9
+ import { useLocation, useNavigate } from 'react-router-dom';
10
+ import { forEach, get, reverse, isArray, map, sortBy, filter, reduce, round, find, upperFirst, toArray } from 'lodash';
11
+ import { makeStyles } from '@material-ui/core/styles';
12
+ import Table from '@material-ui/core/Table';
13
+ import TableBody from '@material-ui/core/TableBody';
14
+ import TableCell from '@material-ui/core/TableCell';
15
+ import TableContainer from '@material-ui/core/TableContainer';
16
+ import TableHead from '@material-ui/core/TableHead';
17
+ import TablePagination from '@material-ui/core/TablePagination';
18
+ import TableRow from '@material-ui/core/TableRow';
19
+ import TableSortLabel from '@material-ui/core/TableSortLabel';
20
+ import { ResponsiveContainer, BarChart, CartesianGrid, XAxis, YAxis, Tooltip, Bar, PieChart, Pie, Cell } from 'recharts';
21
+ import blue from '@material-ui/core/colors/blue';
22
+ import brown from '@material-ui/core/colors/brown';
23
+ import cyan from '@material-ui/core/colors/cyan';
24
+ import deepOrange from '@material-ui/core/colors/deepOrange';
25
+ import deepPurple from '@material-ui/core/colors/deepPurple';
26
+ import green from '@material-ui/core/colors/green';
27
+ import grey from '@material-ui/core/colors/grey';
28
+ import indigo from '@material-ui/core/colors/indigo';
29
+ import orange from '@material-ui/core/colors/orange';
30
+ import red from '@material-ui/core/colors/red';
31
+ import teal from '@material-ui/core/colors/teal';
32
+ import yellow from '@material-ui/core/colors/yellow';
33
+ import axios from 'axios';
34
+ import ExportIcon from '@material-ui/icons/GetApp';
35
+ import Tooltip$1 from '@material-ui/core/Tooltip';
36
+ import FormControl from '@material-ui/core/FormControl';
37
+ import InputLabel from '@material-ui/core/InputLabel';
38
+ import MenuItem from '@material-ui/core/MenuItem';
39
+ import Select from '@material-ui/core/Select';
40
+ import MuiPickersUtilsProvider from '@material-ui/pickers/MuiPickersUtilsProvider';
41
+ import KeyboardDatePicker from '@material-ui/pickers/KeyboardDatePicker';
42
+ import Button from '@material-ui/core/Button';
43
+ import LuxonUtils from '@date-io/luxon';
44
+ import Link from '@material-ui/core/Link';
45
+ import Popover from '@material-ui/core/Popover';
46
+ import TextField from '@material-ui/core/TextField';
47
+ import { isValid } from 'date-fns';
48
+ import Breadcrumbs from '@material-ui/core/Breadcrumbs';
49
+ import NavigateNextIcon from '@material-ui/icons/NavigateNext';
50
+ import List from '@material-ui/core/List';
51
+ import ListItem from '@material-ui/core/ListItem';
52
+ import ListItemIcon from '@material-ui/core/ListItemIcon';
53
+ import ListItemText from '@material-ui/core/ListItemText';
54
+ import WarningIcon from '@material-ui/icons/Warning';
55
+ import { useApi, configApiRef } from '@backstage/core-plugin-api';
56
+ import logo from '../images/pig.png';
57
+
58
+ const primary = [
59
+ blue[500],
60
+ red[500],
61
+ green[500],
62
+ yellow[500],
63
+ cyan[500],
64
+ orange[500],
65
+ teal[500],
66
+ indigo[500],
67
+ deepOrange[500],
68
+ deepPurple[500]
69
+ ];
70
+ const greyscale = [
71
+ grey[300],
72
+ grey[400],
73
+ grey[200],
74
+ grey[500],
75
+ grey[100],
76
+ grey[600]
77
+ ];
78
+ const browns = [brown[500]];
79
+
80
+ function rangeToCumulative(allocationSetRange, aggregateBy) {
81
+ if (allocationSetRange.length === 0) {
82
+ return null;
83
+ }
84
+ const result = {};
85
+ forEach(allocationSetRange, (allocSet) => {
86
+ forEach(allocSet, (alloc) => {
87
+ if (result[alloc.name] === void 0) {
88
+ const hrs = get(alloc, "minutes", 0) / 60;
89
+ result[alloc.name] = {
90
+ name: alloc.name,
91
+ [aggregateBy]: alloc.name,
92
+ cpuCost: get(alloc, "cpuCost", 0),
93
+ gpuCost: get(alloc, "gpuCost", 0),
94
+ ramCost: get(alloc, "ramCost", 0),
95
+ pvCost: get(alloc, "pvCost", 0),
96
+ networkCost: get(alloc, "networkCost", 0),
97
+ sharedCost: get(alloc, "sharedCost", 0),
98
+ externalCost: get(alloc, "externalCost", 0),
99
+ totalCost: get(alloc, "totalCost", 0),
100
+ cpuUseCoreHrs: get(alloc, "cpuCoreUsageAverage", 0) * hrs,
101
+ cpuReqCoreHrs: get(alloc, "cpuCoreRequestAverage", 0) * hrs,
102
+ ramUseByteHrs: get(alloc, "ramByteUsageAverage", 0) * hrs,
103
+ ramReqByteHrs: get(alloc, "ramByteRequestAverage", 0) * hrs,
104
+ cpuEfficiency: get(alloc, "cpuEfficiency", 0),
105
+ ramEfficiency: get(alloc, "ramEfficiency", 0),
106
+ totalEfficiency: get(alloc, "totalEfficiency", 0)
107
+ };
108
+ } else {
109
+ const hrs = get(alloc, "minutes", 0) / 60;
110
+ result[alloc.name].cpuCost += get(alloc, "cpuCost", 0);
111
+ result[alloc.name].gpuCost += get(alloc, "gpuCost", 0);
112
+ result[alloc.name].ramCost += get(alloc, "ramCost", 0);
113
+ result[alloc.name].pvCost += get(alloc, "pvCost", 0);
114
+ result[alloc.name].networkCost += get(alloc, "networkCost", 0);
115
+ result[alloc.name].sharedCost += get(alloc, "sharedCost", 0);
116
+ result[alloc.name].externalCost += get(alloc, "externalCost", 0);
117
+ result[alloc.name].totalCost += get(alloc, "totalCost", 0);
118
+ result[alloc.name].cpuUseCoreHrs += get(alloc, "cpuCoreUsageAverage", 0) * hrs;
119
+ result[alloc.name].cpuReqCoreHrs += get(alloc, "cpuCoreRequestAverage", 0) * hrs;
120
+ result[alloc.name].ramUseByteHrs += get(alloc, "ramByteUsageAverage", 0) * hrs;
121
+ result[alloc.name].ramReqByteHrs += get(alloc, "ramByteRequestAverage", 0) * hrs;
122
+ }
123
+ });
124
+ });
125
+ if (allocationSetRange.length > 1) {
126
+ forEach(result, (alloc, name) => {
127
+ let totalEfficiency = 0;
128
+ let cpuEfficiency = 0;
129
+ if (alloc.cpuReqCoreHrs > 0) {
130
+ cpuEfficiency = alloc.cpuUseCoreHrs / alloc.cpuReqCoreHrs;
131
+ } else if (alloc.cpuUseCoreHrs > 0) {
132
+ cpuEfficiency = 1;
133
+ }
134
+ let ramEfficiency = 0;
135
+ if (alloc.ramReqByteHrs > 0) {
136
+ ramEfficiency = alloc.ramUseByteHrs / alloc.ramReqByteHrs;
137
+ } else if (alloc.ramUseByteHrs > 0) {
138
+ ramEfficiency = 1;
139
+ }
140
+ if (alloc.cpuCost + alloc.ramCost > 0) {
141
+ totalEfficiency = (alloc.cpuCost * cpuEfficiency + alloc.ramCost * ramEfficiency) / (alloc.cpuCost + alloc.ramCost);
142
+ }
143
+ result[name].cpuEfficiency = cpuEfficiency;
144
+ result[name].ramEfficiency = ramEfficiency;
145
+ result[name].totalEfficiency = totalEfficiency;
146
+ });
147
+ }
148
+ return result;
149
+ }
150
+ function cumulativeToTotals(allocationSet) {
151
+ const totals = {
152
+ name: "Totals",
153
+ cpuCost: 0,
154
+ gpuCost: 0,
155
+ ramCost: 0,
156
+ pvCost: 0,
157
+ networkCost: 0,
158
+ sharedCost: 0,
159
+ externalCost: 0,
160
+ totalCost: 0,
161
+ cpuEfficiency: 0,
162
+ ramEfficiency: 0,
163
+ totalEfficiency: 0
164
+ };
165
+ let cpuReqCoreHrs = 0;
166
+ let cpuUseCoreHrs = 0;
167
+ let ramReqByteHrs = 0;
168
+ let ramUseByteHrs = 0;
169
+ let cpuCost = 0;
170
+ let ramCost = 0;
171
+ forEach(allocationSet, (alloc, name) => {
172
+ if (name !== "__idle__") {
173
+ cpuReqCoreHrs += get(alloc, "cpuReqCoreHrs", 0);
174
+ cpuUseCoreHrs += get(alloc, "cpuUseCoreHrs", 0);
175
+ ramReqByteHrs += get(alloc, "ramReqByteHrs", 0);
176
+ ramUseByteHrs += get(alloc, "ramUseByteHrs", 0);
177
+ cpuCost += get(alloc, "cpuCost", 0);
178
+ ramCost += get(alloc, "ramCost", 0);
179
+ }
180
+ totals.cpuCost += get(alloc, "cpuCost", 0);
181
+ totals.gpuCost += get(alloc, "gpuCost", 0);
182
+ totals.ramCost += get(alloc, "ramCost", 0);
183
+ totals.pvCost += get(alloc, "pvCost", 0);
184
+ totals.networkCost += get(alloc, "networkCost", 0);
185
+ totals.sharedCost += get(alloc, "sharedCost", 0);
186
+ totals.externalCost += get(alloc, "externalCost", 0);
187
+ totals.totalCost += get(alloc, "totalCost", 0);
188
+ });
189
+ if (cpuReqCoreHrs > 0) {
190
+ totals.cpuEfficiency = cpuUseCoreHrs / cpuReqCoreHrs;
191
+ } else if (cpuUseCoreHrs > 0) {
192
+ totals.cpuEfficiency = 1;
193
+ }
194
+ if (ramReqByteHrs > 0) {
195
+ totals.ramEfficiency = ramUseByteHrs / ramReqByteHrs;
196
+ } else if (ramUseByteHrs > 0) {
197
+ totals.ramEfficiency = 1;
198
+ }
199
+ if (cpuCost + ramCost > 0) {
200
+ totals.totalEfficiency = (cpuCost * totals.cpuEfficiency + ramCost * totals.ramEfficiency) / (cpuCost + ramCost);
201
+ }
202
+ totals.cpuReqCoreHrs = cpuReqCoreHrs;
203
+ totals.cpuUseCoreHrs = cpuUseCoreHrs;
204
+ totals.ramReqByteHrs = ramReqByteHrs;
205
+ totals.ramUseByteHrs = ramUseByteHrs;
206
+ return totals;
207
+ }
208
+ function toVerboseTimeRange(window) {
209
+ const months = [
210
+ "January",
211
+ "February",
212
+ "March",
213
+ "April",
214
+ "May",
215
+ "June",
216
+ "July",
217
+ "August",
218
+ "September",
219
+ "October",
220
+ "November",
221
+ "December"
222
+ ];
223
+ const start = /* @__PURE__ */ new Date();
224
+ start.setUTCHours(0, 0, 0, 0);
225
+ const end = /* @__PURE__ */ new Date();
226
+ end.setUTCHours(0, 0, 0, 0);
227
+ switch (window) {
228
+ case "today":
229
+ return `${start.getUTCDate()} ${months[start.getUTCMonth()]} ${start.getUTCFullYear()}`;
230
+ case "yesterday":
231
+ start.setUTCDate(start.getUTCDate() - 1);
232
+ return `${start.getUTCDate()} ${months[start.getUTCMonth()]} ${start.getUTCFullYear()}`;
233
+ case "week":
234
+ start.setUTCDate(start.getUTCDate() - start.getUTCDay());
235
+ return `${start.getUTCDate()} ${months[start.getUTCMonth()]} ${start.getUTCFullYear()} until now`;
236
+ case "month":
237
+ start.setUTCDate(1);
238
+ return `${start.getUTCDate()} ${months[start.getUTCMonth()]} ${start.getUTCFullYear()} until now`;
239
+ case "lastweek":
240
+ start.setUTCDate(start.getUTCDate() - (start.getUTCDay() + 7));
241
+ end.setUTCDate(end.getUTCDate() - (end.getUTCDay() + 1));
242
+ return `${start.getUTCDate()} ${months[start.getUTCMonth()]} ${start.getUTCFullYear()} through ${end.getUTCDate()} ${months[end.getUTCMonth()]} ${end.getUTCFullYear()}`;
243
+ case "lastmonth":
244
+ end.setUTCDate(1);
245
+ end.setUTCDate(end.getUTCDate() - 1);
246
+ start.setUTCDate(1);
247
+ start.setUTCDate(start.getUTCDate() - 1);
248
+ start.setUTCDate(1);
249
+ return `${start.getUTCDate()} ${months[start.getUTCMonth()]} ${start.getUTCFullYear()} through ${end.getUTCDate()} ${months[end.getUTCMonth()]} ${end.getUTCFullYear()}`;
250
+ case "6d":
251
+ start.setUTCDate(start.getUTCDate() - 6);
252
+ return `${start.getUTCDate()} ${months[start.getUTCMonth()]} ${start.getUTCFullYear()} through now`;
253
+ case "29d":
254
+ start.setUTCDate(start.getUTCDate() - 29);
255
+ return `${start.getUTCDate()} ${months[start.getUTCMonth()]} ${start.getUTCFullYear()} through now`;
256
+ case "59d":
257
+ start.setUTCDate(start.getUTCDate() - 59);
258
+ return `${start.getUTCDate()} ${months[start.getUTCMonth()]} ${start.getUTCFullYear()} through now`;
259
+ case "89d":
260
+ start.setUTCDate(start.getUTCDate() - 89);
261
+ return `${start.getUTCDate()} ${months[start.getUTCMonth()]} ${start.getUTCFullYear()} through now`;
262
+ }
263
+ const splitDates = window.split(",");
264
+ if (checkCustomWindow(window) && splitDates.length > 1) {
265
+ const s = splitDates[0].split(/\D+/).slice(0, 3);
266
+ const e = splitDates[1].split(/\D+/).slice(0, 3);
267
+ if (s.length === 3 && e.length === 3) {
268
+ start.setUTCFullYear(s[0], s[1] - 1, s[2]);
269
+ end.setUTCFullYear(e[0], e[1] - 1, e[2]);
270
+ if (start === end) {
271
+ return `${start.getUTCDate()} ${months[start.getUTCMonth()]} ${start.getUTCFullYear()}`;
272
+ }
273
+ return `${start.getUTCDate()} ${months[start.getUTCMonth()]} ${start.getUTCFullYear()} through ${end.getUTCDate()} ${months[end.getUTCMonth()]} ${end.getUTCFullYear()}`;
274
+ }
275
+ }
276
+ return "";
277
+ }
278
+ const currencyLocale = "en-US";
279
+ function toCurrency(amount, currency, precision) {
280
+ if (typeof amount !== "number") {
281
+ Console.warn(
282
+ `Tried to convert "${amount}" to currency, but it is not a number`
283
+ );
284
+ return "";
285
+ }
286
+ let ctype = currency;
287
+ if (currency === void 0 || currency === "") {
288
+ ctype = "USD";
289
+ }
290
+ const opts = {
291
+ style: "currency",
292
+ currency: ctype
293
+ };
294
+ if (typeof precision === "number") {
295
+ opts.minimumFractionDigits = precision;
296
+ opts.maximumFractionDigits = precision;
297
+ }
298
+ return amount.toLocaleString(currencyLocale, opts);
299
+ }
300
+ function checkCustomWindow(window) {
301
+ const customDateRegex = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z,\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z/;
302
+ return customDateRegex.test(window);
303
+ }
304
+
305
+ const useStyles$7 = makeStyles({
306
+ tooltip: {
307
+ borderRadius: 2,
308
+ background: "rgba(255, 255, 255, 0.95)",
309
+ padding: 12
310
+ },
311
+ tooltipLineItem: {
312
+ fontSize: "1rem",
313
+ margin: 0,
314
+ marginBottom: 4,
315
+ padding: 0
316
+ }
317
+ });
318
+ function toBarLabels(allocationRange) {
319
+ const keyToFill = {};
320
+ let p = 0;
321
+ let g = 0;
322
+ let b = 0;
323
+ for (const { idle } of allocationRange) {
324
+ for (const allocation of idle) {
325
+ const key = allocation.name;
326
+ if (keyToFill[key] === void 0) {
327
+ keyToFill[key] = greyscale[g];
328
+ g = (g + 1) % greyscale.length;
329
+ }
330
+ }
331
+ }
332
+ for (const { top } of allocationRange) {
333
+ for (const allocation of top) {
334
+ const key = allocation.name;
335
+ if (keyToFill[key] === void 0) {
336
+ if (key === "__unallocated__") {
337
+ keyToFill[key] = "#212121";
338
+ } else {
339
+ keyToFill[key] = primary[p];
340
+ p = (p + 1) % primary.length;
341
+ }
342
+ }
343
+ }
344
+ }
345
+ for (const { other } of allocationRange) {
346
+ for (const allocation of other) {
347
+ const key = allocation.name;
348
+ if (keyToFill[key] === void 0) {
349
+ keyToFill[key] = browns[b];
350
+ b = (b + 1) % browns.length;
351
+ }
352
+ }
353
+ }
354
+ const labels = [];
355
+ for (const key in keyToFill) {
356
+ if (Object.hasOwn(keyToFill, key)) {
357
+ labels.push({
358
+ dataKey: key,
359
+ fill: keyToFill[key]
360
+ });
361
+ }
362
+ }
363
+ return reverse(labels);
364
+ }
365
+ function toBar(datum) {
366
+ const { top, other, idle } = datum;
367
+ const bar = {};
368
+ for (const key in top) {
369
+ if (Object.hasOwn(top, key)) {
370
+ const allocation = top[key];
371
+ const start = new Date(allocation.start);
372
+ bar.start = `${start.getUTCFullYear()}-${start.getUTCMonth() + 1}-${start.getUTCDate()}`;
373
+ bar[allocation.name] = allocation.totalCost;
374
+ }
375
+ }
376
+ for (const key in other) {
377
+ if (Object.hasOwn(other, key)) {
378
+ const allocation = other[key];
379
+ const start = new Date(allocation.start);
380
+ bar.start = `${start.getUTCFullYear()}-${start.getUTCMonth() + 1}-${start.getUTCDate()}`;
381
+ bar[allocation.name] = allocation.totalCost;
382
+ }
383
+ }
384
+ for (const key in idle) {
385
+ if (Object.hasOwn(idle, key)) {
386
+ const allocation = idle[key];
387
+ const start = new Date(allocation.start);
388
+ bar.start = `${start.getUTCFullYear()}-${start.getUTCMonth() + 1}-${start.getUTCDate()}`;
389
+ bar[allocation.name] = allocation.totalCost;
390
+ }
391
+ }
392
+ return bar;
393
+ }
394
+ const RangeChart = ({ data, currency, height }) => {
395
+ const classes = useStyles$7();
396
+ const barData = data.map(toBar);
397
+ const barLabels = toBarLabels(data);
398
+ const CustomTooltip = (params) => {
399
+ const { active, payload } = params;
400
+ if (!payload || payload.length === 0) {
401
+ return null;
402
+ }
403
+ const total = payload.reduce((sum, item) => sum + item.value, 0);
404
+ if (active) {
405
+ return /* @__PURE__ */ React.createElement("div", { className: classes.tooltip }, /* @__PURE__ */ React.createElement(
406
+ "p",
407
+ {
408
+ className: classes.tooltipLineItem,
409
+ style: { color: "#000000" }
410
+ },
411
+ `Total: ${toCurrency(total, currency)}`
412
+ ), reverse(payload).map((item, i) => /* @__PURE__ */ React.createElement(
413
+ "p",
414
+ {
415
+ key: i,
416
+ className: classes.tooltipLineItem,
417
+ style: { color: item.fill }
418
+ },
419
+ `${item.name}: ${toCurrency(item.value, currency)}`
420
+ )));
421
+ }
422
+ return null;
423
+ };
424
+ return /* @__PURE__ */ React.createElement(ResponsiveContainer, { width: "100%", height }, /* @__PURE__ */ React.createElement(
425
+ BarChart,
426
+ {
427
+ data: barData,
428
+ margin: { top: 30, right: 30, left: 30, bottom: 12 }
429
+ },
430
+ /* @__PURE__ */ React.createElement(CartesianGrid, { strokeDasharray: "3 3" }),
431
+ /* @__PURE__ */ React.createElement(XAxis, { dataKey: "start" }),
432
+ /* @__PURE__ */ React.createElement(YAxis, null),
433
+ /* @__PURE__ */ React.createElement(Tooltip, { content: /* @__PURE__ */ React.createElement(CustomTooltip, null) }),
434
+ barLabels.map((barLabel, i) => /* @__PURE__ */ React.createElement(
435
+ Bar,
436
+ {
437
+ key: i,
438
+ dataKey: barLabel.dataKey,
439
+ stackId: "a",
440
+ fill: barLabel.fill
441
+ }
442
+ ))
443
+ ));
444
+ };
445
+
446
+ function toPieData(top, other, idle) {
447
+ const slices = [];
448
+ for (const i in top) {
449
+ if (Object.hasOwn(top, i)) {
450
+ const allocation = top[i];
451
+ const fill = allocation.name === "__unallocated__" ? "#212121" : primary[i % primary.length];
452
+ slices.push({
453
+ name: allocation.name,
454
+ value: allocation.totalCost,
455
+ fill
456
+ });
457
+ }
458
+ }
459
+ for (const i in other) {
460
+ if (Object.hasOwn(other, i)) {
461
+ const allocation = other[i];
462
+ const fill = browns[i % browns.length];
463
+ slices.push({
464
+ name: allocation.name,
465
+ value: allocation.totalCost,
466
+ fill
467
+ });
468
+ }
469
+ }
470
+ for (const i in idle) {
471
+ if (Object.hasOwn(idle, i)) {
472
+ const allocation = idle[i];
473
+ const fill = greyscale[i % greyscale.length];
474
+ slices.push({
475
+ name: allocation.name,
476
+ value: allocation.totalCost,
477
+ fill
478
+ });
479
+ }
480
+ }
481
+ return slices;
482
+ }
483
+ const SummaryChart = ({ top, other, idle, currency, height }) => {
484
+ const pieData = toPieData(top, other, idle);
485
+ const renderLabel = (params) => {
486
+ const { cx, cy, midAngle, outerRadius, percent, name, fill, value } = params;
487
+ const RADIAN = Math.PI / 180;
488
+ const radius = outerRadius * 1.1;
489
+ let x = cx + radius * Math.cos(-midAngle * RADIAN);
490
+ x += x > cx ? 2 : -2;
491
+ const y = cy + radius * Math.sin(-midAngle * RADIAN);
492
+ if (percent < 0.02) {
493
+ return void 0;
494
+ }
495
+ return /* @__PURE__ */ React.createElement(
496
+ "text",
497
+ {
498
+ x,
499
+ y,
500
+ fill,
501
+ textAnchor: x > cx ? "start" : "end",
502
+ dominantBaseline: "central"
503
+ },
504
+ `${name}: ${toCurrency(value, currency)} (${(percent * 100).toFixed(
505
+ 1
506
+ )}%)`
507
+ );
508
+ };
509
+ return /* @__PURE__ */ React.createElement(ResponsiveContainer, { width: "100%", height }, /* @__PURE__ */ React.createElement(PieChart, null, /* @__PURE__ */ React.createElement(
510
+ Pie,
511
+ {
512
+ data: pieData,
513
+ dataKey: "value",
514
+ nameKey: "name",
515
+ label: renderLabel,
516
+ labelLine: true,
517
+ animationDuration: 400,
518
+ cy: "90%",
519
+ outerRadius: "140%",
520
+ innerRadius: "60%",
521
+ startAngle: 180,
522
+ endAngle: 0
523
+ },
524
+ pieData.map((datum, i) => /* @__PURE__ */ React.createElement(Cell, { key: i, fill: datum.fill }))
525
+ )));
526
+ };
527
+
528
+ function agg(allocationSet, name) {
529
+ if (allocationSet.length === 0) {
530
+ return null;
531
+ }
532
+ return reduce(
533
+ allocationSet,
534
+ (agg2, cur) => ({
535
+ name: agg2.name,
536
+ aggregatedBy: cur.aggregatedBy,
537
+ properties: agg2.properties,
538
+ start: cur.start,
539
+ end: cur.end,
540
+ cpuCost: agg2.cpuCost + cur.cpuCost,
541
+ gpuCost: agg2.gpuCost + cur.gpuCost,
542
+ ramCost: agg2.ramCost + cur.ramCost,
543
+ pvCost: agg2.pvCost + cur.pvCost,
544
+ totalCost: agg2.totalCost + cur.totalCost,
545
+ count: agg2.count + 1
546
+ }),
547
+ {
548
+ name,
549
+ properties: null,
550
+ cpuCost: 0,
551
+ gpuCost: 0,
552
+ ramCost: 0,
553
+ pvCost: 0,
554
+ totalCost: 0,
555
+ count: 0
556
+ }
557
+ );
558
+ }
559
+ function isIdle(allocation) {
560
+ return allocation.name.indexOf("__idle__") >= 0;
561
+ }
562
+ function top(n, by) {
563
+ return (allocations) => {
564
+ if (isArray(allocations[0])) {
565
+ return map(allocations, top(n, by));
566
+ }
567
+ const sorted = reverse(sortBy(allocations, by));
568
+ const active = filter(sorted, (a) => !isIdle(a));
569
+ const idle = filter(sorted, (a) => isIdle(a));
570
+ const topn = active.slice(0, n);
571
+ const other = [];
572
+ if (active.length > n) {
573
+ other.push(agg(active.slice(n), "other"));
574
+ }
575
+ return {
576
+ top: topn,
577
+ other,
578
+ idle
579
+ };
580
+ };
581
+ }
582
+ const AllocationChart = ({ allocationRange, currency, n, height }) => {
583
+ if (allocationRange.length === 0) {
584
+ return /* @__PURE__ */ React.createElement(Typography, { variant: "body2" }, "No data");
585
+ }
586
+ if (allocationRange.length === 1) {
587
+ const datum = top(n, (alloc) => alloc.totalCost)(allocationRange[0]);
588
+ return /* @__PURE__ */ React.createElement(
589
+ SummaryChart,
590
+ {
591
+ top: datum.top,
592
+ other: datum.other,
593
+ idle: datum.idle,
594
+ currency,
595
+ height
596
+ }
597
+ );
598
+ }
599
+ const data = top(n, (alloc) => alloc.totalCost)(allocationRange);
600
+ return /* @__PURE__ */ React.createElement(RangeChart, { data, currency, height });
601
+ };
602
+ var AllocationChart$1 = React.memo(AllocationChart);
603
+
604
+ const useStyles$6 = makeStyles({
605
+ noResults: {
606
+ padding: 24
607
+ }
608
+ });
609
+ function descendingComparator(a, b, orderBy) {
610
+ if (get(b, orderBy) < get(a, orderBy)) {
611
+ return -1;
612
+ }
613
+ if (get(b, orderBy) > get(a, orderBy)) {
614
+ return 1;
615
+ }
616
+ return 0;
617
+ }
618
+ function getComparator(order, orderBy) {
619
+ return order === "desc" ? (a, b) => descendingComparator(a, b, orderBy) : (a, b) => -descendingComparator(a, b, orderBy);
620
+ }
621
+ function stableSort(array, comparator) {
622
+ const stabilizedThis = array.map((el, index) => [el, index]);
623
+ stabilizedThis.sort((a, b) => {
624
+ const order = comparator(a[0], b[0]);
625
+ if (order !== 0)
626
+ return order;
627
+ return a[1] - b[1];
628
+ });
629
+ return stabilizedThis.map((el) => el[0]);
630
+ }
631
+ const headCells = [
632
+ { id: "name", numeric: false, label: "Name", width: "auto" },
633
+ { id: "cpuCost", numeric: true, label: "CPU", width: 100 },
634
+ { id: "ramCost", numeric: true, label: "RAM", width: 100 },
635
+ { id: "pvCost", numeric: true, label: "PV", width: 100 },
636
+ { id: "totalEfficiency", numeric: true, label: "Efficiency", width: 130 },
637
+ { id: "totalCost", numeric: true, label: "Total cost", width: 130 }
638
+ ];
639
+ const AllocationReport = ({
640
+ allocationData,
641
+ cumulativeData,
642
+ totalData,
643
+ currency
644
+ }) => {
645
+ const classes = useStyles$6();
646
+ if (allocationData.length === 0) {
647
+ return /* @__PURE__ */ React.createElement(Typography, { variant: "body2", className: classes.noResults }, "No results");
648
+ }
649
+ const [order, setOrder] = React.useState("desc");
650
+ const [orderBy, setOrderBy] = React.useState("totalCost");
651
+ const [page, setPage] = useState(0);
652
+ const [rowsPerPage, setRowsPerPage] = useState(25);
653
+ const numData = cumulativeData.length;
654
+ useEffect(() => {
655
+ setPage(0);
656
+ }, [numData]);
657
+ const lastPage = Math.floor(numData / rowsPerPage);
658
+ const handleChangePage = (event, newPage) => setPage(newPage);
659
+ const handleChangeRowsPerPage = (event) => {
660
+ setRowsPerPage(parseInt(event.target.value, 10));
661
+ setPage(0);
662
+ };
663
+ const handleRequestSort = (event, property) => {
664
+ const isDesc = orderBy === property && order === "desc";
665
+ setOrder(isDesc ? "asc" : "desc");
666
+ setOrderBy(property);
667
+ };
668
+ const createSortHandler = (property) => (event) => handleRequestSort(event, property);
669
+ const orderedRows = stableSort(cumulativeData, getComparator(order, orderBy));
670
+ const pageRows = orderedRows.slice(
671
+ page * rowsPerPage,
672
+ page * rowsPerPage + rowsPerPage
673
+ );
674
+ return /* @__PURE__ */ React.createElement("div", { id: "report" }, /* @__PURE__ */ React.createElement(
675
+ AllocationChart$1,
676
+ {
677
+ allocationRange: allocationData,
678
+ currency,
679
+ n: 10,
680
+ height: 300
681
+ }
682
+ ), /* @__PURE__ */ React.createElement(TableContainer, null, /* @__PURE__ */ React.createElement(Table, null, /* @__PURE__ */ React.createElement(TableHead, null, /* @__PURE__ */ React.createElement(TableRow, null, headCells.map((cell) => /* @__PURE__ */ React.createElement(
683
+ TableCell,
684
+ {
685
+ key: cell.id,
686
+ colSpan: cell.colspan,
687
+ align: cell.numeric ? "right" : "left",
688
+ sortDirection: orderBy === cell.id ? order : false,
689
+ style: { width: cell.width }
690
+ },
691
+ /* @__PURE__ */ React.createElement(
692
+ TableSortLabel,
693
+ {
694
+ active: orderBy === cell.id,
695
+ direction: orderBy === cell.id ? order : "asc",
696
+ onClick: createSortHandler(cell.id)
697
+ },
698
+ cell.label
699
+ )
700
+ )))), /* @__PURE__ */ React.createElement(TableBody, null, /* @__PURE__ */ React.createElement(TableRow, null, headCells.map((cell) => {
701
+ return /* @__PURE__ */ React.createElement(
702
+ TableCell,
703
+ {
704
+ key: cell.id,
705
+ colSpan: cell.colspan,
706
+ align: cell.numeric ? "right" : "left",
707
+ style: { fontWeight: 500 }
708
+ },
709
+ cell.numeric ? cell.label === "Efficiency" ? totalData.totalEfficiency === 1 && totalData.cpuReqCoreHrs === 0 && totalData.ramReqByteHrs === 0 ? "Inf%" : `${round(totalData.totalEfficiency * 100, 1)}%` : toCurrency(totalData[cell.id], currency) : totalData[cell.id]
710
+ );
711
+ })), pageRows.map((row, key) => {
712
+ if (row.name === "__unmounted__") {
713
+ row.name = "Unmounted PVs";
714
+ }
715
+ const isIdle = row.name.indexOf("__idle__") >= 0;
716
+ const isUnallocated = row.name.indexOf("__unallocated__") >= 0;
717
+ const isUnmounted = row.name.indexOf("Unmounted PVs") >= 0;
718
+ let efficiency = round(row.totalEfficiency * 100, 1);
719
+ if (row.totalEfficiency === 1 && row.cpuReqCoreHrs === 0 && row.ramReqByteHrs === 0) {
720
+ efficiency = "Inf";
721
+ }
722
+ if (isIdle || isUnallocated || isUnmounted) {
723
+ return /* @__PURE__ */ React.createElement(TableRow, { key }, /* @__PURE__ */ React.createElement(TableCell, { align: "left" }, row.name), /* @__PURE__ */ React.createElement(TableCell, { align: "right" }, toCurrency(row.cpuCost, currency)), /* @__PURE__ */ React.createElement(TableCell, { align: "right" }, toCurrency(row.ramCost, currency)), /* @__PURE__ */ React.createElement(TableCell, { align: "right" }, toCurrency(row.pvCost, currency)), isIdle ? /* @__PURE__ */ React.createElement(TableCell, { align: "right" }, "\u2014") : /* @__PURE__ */ React.createElement(TableCell, { align: "right" }, efficiency, "%"), /* @__PURE__ */ React.createElement(TableCell, { align: "right" }, toCurrency(row.totalCost, currency)));
724
+ }
725
+ return /* @__PURE__ */ React.createElement(TableRow, { key }, /* @__PURE__ */ React.createElement(TableCell, { align: "left" }, row.name), /* @__PURE__ */ React.createElement(TableCell, { align: "right" }, toCurrency(row.cpuCost, currency)), /* @__PURE__ */ React.createElement(TableCell, { align: "right" }, toCurrency(row.ramCost, currency)), /* @__PURE__ */ React.createElement(TableCell, { align: "right" }, toCurrency(row.pvCost, currency)), /* @__PURE__ */ React.createElement(TableCell, { align: "right" }, efficiency, "%"), /* @__PURE__ */ React.createElement(TableCell, { align: "right" }, toCurrency(row.totalCost, currency)));
726
+ })))), /* @__PURE__ */ React.createElement(
727
+ TablePagination,
728
+ {
729
+ component: "div",
730
+ count: numData,
731
+ rowsPerPage,
732
+ rowsPerPageOptions: [10, 25, 50],
733
+ page: Math.min(page, lastPage),
734
+ onChangePage: handleChangePage,
735
+ onChangeRowsPerPage: handleChangeRowsPerPage
736
+ }
737
+ ));
738
+ };
739
+ var AllocationReport$1 = React.memo(AllocationReport);
740
+
741
+ class AllocationService {
742
+ async fetchAllocation(baseUrl, win, aggregate, options) {
743
+ const { accumulate } = options;
744
+ const params = {
745
+ window: win,
746
+ aggregate,
747
+ step: "1d"
748
+ };
749
+ if (typeof accumulate === "boolean") {
750
+ params.accumulate = accumulate;
751
+ }
752
+ const result = await axios.get(`${baseUrl}/allocation/compute`, { params });
753
+ return result.data;
754
+ }
755
+ }
756
+ var AllocationService$1 = new AllocationService();
757
+
758
+ const columns = [
759
+ {
760
+ head: "Name",
761
+ prop: "name",
762
+ currency: false
763
+ },
764
+ {
765
+ head: "CPU",
766
+ prop: "cpuCost",
767
+ currency: true
768
+ },
769
+ {
770
+ head: "GPU",
771
+ prop: "gpuCost",
772
+ currency: true
773
+ },
774
+ {
775
+ head: "RAM",
776
+ prop: "ramCost",
777
+ currency: true
778
+ },
779
+ {
780
+ head: "PV",
781
+ prop: "pvCost",
782
+ currency: true
783
+ },
784
+ {
785
+ head: "Network",
786
+ prop: "networkCost",
787
+ currency: true
788
+ },
789
+ {
790
+ head: "Shared",
791
+ prop: "sharedCost",
792
+ currency: true
793
+ },
794
+ {
795
+ head: "Total",
796
+ prop: "totalCost",
797
+ currency: true
798
+ }
799
+ ];
800
+ const toCSVLine = (datum) => {
801
+ const cols = [];
802
+ forEach(columns, (c) => {
803
+ if (c.currency) {
804
+ cols.push(round(get(datum, c.prop, 0), 2));
805
+ } else {
806
+ cols.push(`"${get(datum, c.prop, "")}"`);
807
+ }
808
+ });
809
+ return cols.join(",");
810
+ };
811
+ const DownloadControl = ({ cumulativeData, title }) => {
812
+ function downloadReport() {
813
+ const head = columns.map((c) => c.head).join(",");
814
+ const body = reverse(sortBy(cumulativeData, "totalCost")).map(toCSVLine).join("\r\n");
815
+ const csv = `${head}\r
816
+ ${body}`;
817
+ const a = document.createElement("a");
818
+ a.href = URL.createObjectURL(new Blob([csv], { type: "text/csv" }));
819
+ const filename = title.toLocaleLowerCase("en-US").replace(/\s/gi, "-");
820
+ a.setAttribute("download", `${filename}-${Date.now()}.csv`);
821
+ document.body.appendChild(a);
822
+ a.click();
823
+ document.body.removeChild(a);
824
+ }
825
+ return /* @__PURE__ */ React.createElement(Tooltip$1, { title: "Download CSV" }, /* @__PURE__ */ React.createElement(IconButton, { onClick: downloadReport }, /* @__PURE__ */ React.createElement(ExportIcon, null)));
826
+ };
827
+ var DownloadControl$1 = React.memo(DownloadControl);
828
+
829
+ const useStyles$5 = makeStyles({
830
+ dateContainer: {
831
+ paddingLeft: 18,
832
+ paddingRight: 18,
833
+ paddingTop: 6,
834
+ paddingBottom: 18,
835
+ display: "flex",
836
+ flexFlow: "row"
837
+ },
838
+ dateContainerColumn: {
839
+ display: "flex",
840
+ flexFlow: "column"
841
+ },
842
+ formControl: {
843
+ margin: 8,
844
+ width: 120
845
+ }
846
+ });
847
+ const SelectWindow = ({ windowOptions, window, setWindow }) => {
848
+ const classes = useStyles$5();
849
+ const [anchorEl, setAnchorEl] = useState(null);
850
+ const [startDate, setStartDate] = useState(null);
851
+ const [endDate, setEndDate] = useState(null);
852
+ const [intervalString, setIntervalString] = useState(null);
853
+ const handleClick = (event) => {
854
+ setAnchorEl(event.currentTarget);
855
+ };
856
+ const handleClose = () => {
857
+ setAnchorEl(null);
858
+ };
859
+ const handleStartDateChange = (date) => {
860
+ if (isValid(date.toJSDate())) {
861
+ setStartDate(date.startOf("day").toJSDate());
862
+ }
863
+ };
864
+ const handleEndDateChange = (date) => {
865
+ if (isValid(date.toJSDate())) {
866
+ setEndDate(date.endOf("day").toJSDate());
867
+ }
868
+ };
869
+ const handleSubmitPresetDates = (dateString) => {
870
+ setWindow(dateString);
871
+ setStartDate(null);
872
+ setEndDate(null);
873
+ handleClose();
874
+ };
875
+ const handleSubmitCustomDates = () => {
876
+ if (intervalString !== null) {
877
+ setWindow(intervalString);
878
+ handleClose();
879
+ }
880
+ };
881
+ useEffect(() => {
882
+ if (startDate !== null && endDate !== null) {
883
+ const adjustedStartDate = new Date(
884
+ startDate - startDate.getTimezoneOffset() * 6e4
885
+ );
886
+ const adjustedEndDate = new Date(
887
+ endDate - endDate.getTimezoneOffset() * 6e4
888
+ );
889
+ setIntervalString(
890
+ `${adjustedStartDate.toISOString().split(".")[0]}Z,${adjustedEndDate.toISOString().split(".")[0]}Z`
891
+ );
892
+ }
893
+ }, [startDate, endDate]);
894
+ const open = Boolean(anchorEl);
895
+ const id = open ? "date-range-popover" : void 0;
896
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(FormControl, { className: classes.formControl }, /* @__PURE__ */ React.createElement(
897
+ TextField,
898
+ {
899
+ id: "filled-read-only-input",
900
+ label: "Date Range",
901
+ value: get(find(windowOptions, { value: window }), "name", "Custom"),
902
+ onClick: (e) => handleClick(e),
903
+ inputProps: {
904
+ readOnly: true,
905
+ style: { cursor: "pointer" }
906
+ }
907
+ }
908
+ )), /* @__PURE__ */ React.createElement(
909
+ Popover,
910
+ {
911
+ id,
912
+ open,
913
+ anchorEl,
914
+ onClose: handleClose,
915
+ anchorOrigin: {
916
+ vertical: "bottom",
917
+ horizontal: "left"
918
+ },
919
+ transformOrigin: {
920
+ vertical: "top",
921
+ horizontal: "center"
922
+ }
923
+ },
924
+ /* @__PURE__ */ React.createElement("div", { className: classes.dateContainer }, /* @__PURE__ */ React.createElement("div", { className: classes.dateContainerColumn }, /* @__PURE__ */ React.createElement(MuiPickersUtilsProvider, { utils: LuxonUtils }, /* @__PURE__ */ React.createElement(
925
+ KeyboardDatePicker,
926
+ {
927
+ style: { width: "144px" },
928
+ autoOk: true,
929
+ disableToolbar: true,
930
+ variant: "inline",
931
+ format: "MM/dd/yyyy",
932
+ margin: "normal",
933
+ id: "date-picker-start",
934
+ label: "Start Date",
935
+ value: startDate,
936
+ maxDate: /* @__PURE__ */ new Date(),
937
+ maxDateMessage: "Date should not be after today.",
938
+ onChange: handleStartDateChange,
939
+ KeyboardButtonProps: {
940
+ "aria-label": "change date"
941
+ }
942
+ }
943
+ ), /* @__PURE__ */ React.createElement(
944
+ KeyboardDatePicker,
945
+ {
946
+ style: { width: "144px" },
947
+ autoOk: true,
948
+ disableToolbar: true,
949
+ variant: "inline",
950
+ format: "MM/dd/yyyy",
951
+ margin: "normal",
952
+ id: "date-picker-end",
953
+ label: "End Date",
954
+ value: endDate,
955
+ maxDate: /* @__PURE__ */ new Date(),
956
+ maxDateMessage: "Date should not be after today.",
957
+ onChange: handleEndDateChange,
958
+ KeyboardButtonProps: {
959
+ "aria-label": "change date"
960
+ }
961
+ }
962
+ )), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(
963
+ Button,
964
+ {
965
+ style: { marginTop: 16 },
966
+ variant: "contained",
967
+ color: "default",
968
+ onClick: handleSubmitCustomDates
969
+ },
970
+ "Apply"
971
+ ))), /* @__PURE__ */ React.createElement(
972
+ "div",
973
+ {
974
+ className: classes.dateContainerColumn,
975
+ style: { paddingTop: 12, marginLeft: 18 }
976
+ },
977
+ windowOptions.map((opt) => /* @__PURE__ */ React.createElement(Typography, { key: opt.value }, /* @__PURE__ */ React.createElement(
978
+ Link,
979
+ {
980
+ style: { cursor: "pointer" },
981
+ key: opt.value,
982
+ value: opt.value,
983
+ onClick: () => handleSubmitPresetDates(opt.value)
984
+ },
985
+ opt.name
986
+ )))
987
+ ))
988
+ ));
989
+ };
990
+ var SelectWindow$1 = React.memo(SelectWindow);
991
+
992
+ const useStyles$4 = makeStyles({
993
+ wrapper: {
994
+ display: "inline-flex"
995
+ },
996
+ formControl: {
997
+ margin: 8,
998
+ minWidth: 120
999
+ }
1000
+ });
1001
+ function EditControl({
1002
+ windowOptions,
1003
+ window,
1004
+ setWindow,
1005
+ aggregationOptions,
1006
+ aggregateBy,
1007
+ setAggregateBy,
1008
+ accumulateOptions,
1009
+ accumulate,
1010
+ setAccumulate,
1011
+ currencyOptions,
1012
+ currency,
1013
+ setCurrency
1014
+ }) {
1015
+ const classes = useStyles$4();
1016
+ return /* @__PURE__ */ React.createElement("div", { className: classes.wrapper }, /* @__PURE__ */ React.createElement(
1017
+ SelectWindow$1,
1018
+ {
1019
+ windowOptions,
1020
+ window,
1021
+ setWindow
1022
+ }
1023
+ ), /* @__PURE__ */ React.createElement(FormControl, { className: classes.formControl }, /* @__PURE__ */ React.createElement(InputLabel, { id: "aggregation-select-label" }, "Breakdown"), /* @__PURE__ */ React.createElement(
1024
+ Select,
1025
+ {
1026
+ id: "aggregation-select",
1027
+ value: aggregateBy,
1028
+ onChange: (e) => {
1029
+ setAggregateBy(e.target.value);
1030
+ }
1031
+ },
1032
+ aggregationOptions.map((opt) => /* @__PURE__ */ React.createElement(MenuItem, { key: opt.value, value: opt.value }, opt.name))
1033
+ )), /* @__PURE__ */ React.createElement(FormControl, { className: classes.formControl }, /* @__PURE__ */ React.createElement(InputLabel, { id: "accumulate-label" }, "Resolution"), /* @__PURE__ */ React.createElement(
1034
+ Select,
1035
+ {
1036
+ id: "accumulate",
1037
+ value: accumulate,
1038
+ onChange: (e) => setAccumulate(e.target.value)
1039
+ },
1040
+ accumulateOptions.map((opt) => /* @__PURE__ */ React.createElement(MenuItem, { key: opt.value, value: opt.value }, opt.name))
1041
+ )), /* @__PURE__ */ React.createElement(FormControl, { className: classes.formControl }, /* @__PURE__ */ React.createElement(InputLabel, { id: "currency-label" }, "Currency"), /* @__PURE__ */ React.createElement(
1042
+ Select,
1043
+ {
1044
+ id: "currency",
1045
+ value: currency,
1046
+ onChange: (e) => setCurrency(e.target.value)
1047
+ },
1048
+ currencyOptions == null ? void 0 : currencyOptions.map((currencyVal) => /* @__PURE__ */ React.createElement(MenuItem, { key: currencyVal, value: currencyVal }, currencyVal))
1049
+ )));
1050
+ }
1051
+ var EditControl$1 = React.memo(EditControl);
1052
+
1053
+ const Controls = ({
1054
+ windowOptions,
1055
+ window,
1056
+ setWindow,
1057
+ aggregationOptions,
1058
+ aggregateBy,
1059
+ setAggregateBy,
1060
+ accumulateOptions,
1061
+ accumulate,
1062
+ setAccumulate,
1063
+ title,
1064
+ cumulativeData,
1065
+ currency,
1066
+ currencyOptions,
1067
+ setCurrency
1068
+ }) => {
1069
+ return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(
1070
+ EditControl$1,
1071
+ {
1072
+ windowOptions,
1073
+ window,
1074
+ setWindow,
1075
+ aggregationOptions,
1076
+ aggregateBy,
1077
+ setAggregateBy,
1078
+ accumulateOptions,
1079
+ accumulate,
1080
+ setAccumulate,
1081
+ currency,
1082
+ currencyOptions,
1083
+ setCurrency
1084
+ }
1085
+ ), /* @__PURE__ */ React.createElement(DownloadControl$1, { cumulativeData, title }));
1086
+ };
1087
+ var Controls$1 = React.memo(Controls);
1088
+
1089
+ const useStyles$3 = makeStyles({
1090
+ wrapper: {
1091
+ display: "flex",
1092
+ flexFlow: "column",
1093
+ flexGrow: 1,
1094
+ margin: "20px 30px 0 30px",
1095
+ minWidth: 800
1096
+ },
1097
+ flexGrow: {
1098
+ display: "flex",
1099
+ flexFlow: "column",
1100
+ flexGrow: 1
1101
+ }
1102
+ });
1103
+ const Page = (props) => {
1104
+ const classes = useStyles$3();
1105
+ return /* @__PURE__ */ React.createElement("div", { className: classes.flexGrow }, /* @__PURE__ */ React.createElement("div", { className: classes.wrapper }, /* @__PURE__ */ React.createElement("div", { className: classes.flexGrow }, props.children)));
1106
+ };
1107
+
1108
+ const useStyles$2 = makeStyles({
1109
+ root: {
1110
+ "& > * + *": {
1111
+ marginTop: 2
1112
+ }
1113
+ },
1114
+ link: {
1115
+ cursor: "pointer"
1116
+ }
1117
+ });
1118
+ const Subtitle = ({ report }) => {
1119
+ const classes = useStyles$2();
1120
+ const { aggregateBy, window } = report;
1121
+ return /* @__PURE__ */ React.createElement("div", { className: classes.root }, /* @__PURE__ */ React.createElement(
1122
+ Breadcrumbs,
1123
+ {
1124
+ separator: /* @__PURE__ */ React.createElement(NavigateNextIcon, { fontSize: "small" }),
1125
+ "aria-label": "breadcrumb"
1126
+ },
1127
+ aggregateBy && aggregateBy.length > 0 ? /* @__PURE__ */ React.createElement(Typography, null, toVerboseTimeRange(window), " by ", upperFirst(aggregateBy)) : /* @__PURE__ */ React.createElement(Typography, null, toVerboseTimeRange(window))
1128
+ ));
1129
+ };
1130
+ var Subtitle$1 = React.memo(Subtitle);
1131
+
1132
+ const useStyles$1 = makeStyles({
1133
+ root: {}
1134
+ });
1135
+ const Warnings = ({ warnings }) => {
1136
+ const classes = useStyles$1();
1137
+ if (!warnings || warnings.length === 0) {
1138
+ return null;
1139
+ }
1140
+ return /* @__PURE__ */ React.createElement(Paper, { className: classes.root }, /* @__PURE__ */ React.createElement(List, null, warnings.map((warn, i) => /* @__PURE__ */ React.createElement(ListItem, { key: i }, /* @__PURE__ */ React.createElement(ListItemIcon, null, /* @__PURE__ */ React.createElement(WarningIcon, null)), /* @__PURE__ */ React.createElement(ListItemText, { primary: warn.primary, secondary: warn.secondary })))));
1141
+ };
1142
+
1143
+ const currencyCodes = [
1144
+ "AED",
1145
+ "AFN",
1146
+ "ALL",
1147
+ "AMD",
1148
+ "ANG",
1149
+ "AOA",
1150
+ "ARS",
1151
+ "AUD",
1152
+ "AWG",
1153
+ "AZN",
1154
+ "BAM",
1155
+ "BBD",
1156
+ "BDT",
1157
+ "BGN",
1158
+ "BHD",
1159
+ "BIF",
1160
+ "BMD",
1161
+ "BND",
1162
+ "BOB",
1163
+ "BOV",
1164
+ "BRL",
1165
+ "BSD",
1166
+ "BTN",
1167
+ "BWP",
1168
+ "BYR",
1169
+ "BZD",
1170
+ "CAD",
1171
+ "CDF",
1172
+ "CHE",
1173
+ "CHF",
1174
+ "CHW",
1175
+ "CLF",
1176
+ "CLP",
1177
+ "CNY",
1178
+ "COP",
1179
+ "COU",
1180
+ "CRC",
1181
+ "CUC",
1182
+ "CUP",
1183
+ "CVE",
1184
+ "CZK",
1185
+ "DJF",
1186
+ "DKK",
1187
+ "DOP",
1188
+ "DZD",
1189
+ "EGP",
1190
+ "ERN",
1191
+ "ETB",
1192
+ "EUR",
1193
+ "FJD",
1194
+ "FKP",
1195
+ "GBP",
1196
+ "GEL",
1197
+ "GHS",
1198
+ "GIP",
1199
+ "GMD",
1200
+ "GNF",
1201
+ "GTQ",
1202
+ "GYD",
1203
+ "HKD",
1204
+ "HNL",
1205
+ "HRK",
1206
+ "HTG",
1207
+ "HUF",
1208
+ "IDR",
1209
+ "ILS",
1210
+ "INR",
1211
+ "IQD",
1212
+ "IRR",
1213
+ "ISK",
1214
+ "JMD",
1215
+ "JOD",
1216
+ "JPY",
1217
+ "KES",
1218
+ "KGS",
1219
+ "KHR",
1220
+ "KMF",
1221
+ "KPW",
1222
+ "KRW",
1223
+ "KWD",
1224
+ "KYD",
1225
+ "KZT",
1226
+ "LAK",
1227
+ "LBP",
1228
+ "LKR",
1229
+ "LRD",
1230
+ "LSL",
1231
+ "LTL",
1232
+ "LVL",
1233
+ "LYD",
1234
+ "MAD",
1235
+ "MDL",
1236
+ "MGA",
1237
+ "MKD",
1238
+ "MMK",
1239
+ "MNT",
1240
+ "MOP",
1241
+ "MRO",
1242
+ "MUR",
1243
+ "MVR",
1244
+ "MWK",
1245
+ "MXN",
1246
+ "MXV",
1247
+ "MYR",
1248
+ "MZN",
1249
+ "NAD",
1250
+ "NGN",
1251
+ "NIO",
1252
+ "NOK",
1253
+ "NPR",
1254
+ "NZD",
1255
+ "OMR",
1256
+ "PAB",
1257
+ "PEN",
1258
+ "PGK",
1259
+ "PHP",
1260
+ "PKR",
1261
+ "PLN",
1262
+ "PYG",
1263
+ "QAR",
1264
+ "RON",
1265
+ "RSD",
1266
+ "RUB",
1267
+ "RWF",
1268
+ "SAR",
1269
+ "SBD",
1270
+ "SCR",
1271
+ "SDG",
1272
+ "SEK",
1273
+ "SGD",
1274
+ "SHP",
1275
+ "SLL",
1276
+ "SOS",
1277
+ "SRD",
1278
+ "SSP",
1279
+ "STD",
1280
+ "SYP",
1281
+ "SZL",
1282
+ "THB",
1283
+ "TJS",
1284
+ "TMT",
1285
+ "TND",
1286
+ "TOP",
1287
+ "TRY",
1288
+ "TTD",
1289
+ "TWD",
1290
+ "TZS",
1291
+ "UAH",
1292
+ "UGX",
1293
+ "USD",
1294
+ "USN",
1295
+ "USS",
1296
+ "UYI",
1297
+ "UYU",
1298
+ "UZS",
1299
+ "VEF",
1300
+ "VND",
1301
+ "VUV",
1302
+ "WST",
1303
+ "XAF",
1304
+ "XAG",
1305
+ "XAU",
1306
+ "XBA",
1307
+ "XBB",
1308
+ "XBC",
1309
+ "XBD",
1310
+ "XCD",
1311
+ "XDR",
1312
+ "XFU",
1313
+ "XOF",
1314
+ "XPD",
1315
+ "XPF",
1316
+ "XPT",
1317
+ "XTS",
1318
+ "XXX",
1319
+ "YER",
1320
+ "ZAR",
1321
+ "ZMW"
1322
+ ];
1323
+
1324
+ const windowOptions = [
1325
+ { name: "Today", value: "today" },
1326
+ { name: "Yesterday", value: "yesterday" },
1327
+ { name: "Week-to-date", value: "week" },
1328
+ { name: "Month-to-date", value: "month" },
1329
+ { name: "Last week", value: "lastweek" },
1330
+ { name: "Last month", value: "lastmonth" },
1331
+ { name: "Last 7 days", value: "6d" },
1332
+ { name: "Last 30 days", value: "29d" },
1333
+ { name: "Last 60 days", value: "59d" },
1334
+ { name: "Last 90 days", value: "89d" }
1335
+ ];
1336
+ const aggregationOptions = [
1337
+ { name: "Cluster", value: "cluster" },
1338
+ { name: "Node", value: "node" },
1339
+ { name: "Namespace", value: "namespace" },
1340
+ { name: "Controller kind", value: "controllerKind" },
1341
+ { name: "Controller", value: "controller" },
1342
+ { name: "Service", value: "service" },
1343
+ { name: "Pod", value: "pod" },
1344
+ { name: "Container", value: "container" }
1345
+ ];
1346
+ const accumulateOptions = [
1347
+ { name: "Entire window", value: true },
1348
+ { name: "Daily", value: false }
1349
+ ];
1350
+ const useStyles = makeStyles({
1351
+ reportHeader: {
1352
+ display: "flex",
1353
+ flexFlow: "row",
1354
+ padding: 24
1355
+ },
1356
+ titles: {
1357
+ flexGrow: 1
1358
+ }
1359
+ });
1360
+ function generateTitle({ window, aggregateBy, accumulate }) {
1361
+ let windowName = get(find(windowOptions, { value: window }), "name", "");
1362
+ if (windowName === "") {
1363
+ if (checkCustomWindow(window)) {
1364
+ windowName = toVerboseTimeRange(window);
1365
+ } else {
1366
+ console.warn(`unknown window: ${window}`);
1367
+ }
1368
+ }
1369
+ const aggregationName = get(
1370
+ find(aggregationOptions, { value: aggregateBy }),
1371
+ "name",
1372
+ ""
1373
+ ).toLocaleLowerCase("en-US");
1374
+ if (aggregationName === "") {
1375
+ console.warn(`unknown aggregation: ${aggregateBy}`);
1376
+ }
1377
+ let str = `${windowName} by ${aggregationName}`;
1378
+ if (!accumulate) {
1379
+ str = `${str} daily`;
1380
+ }
1381
+ return str;
1382
+ }
1383
+ const OpenCostReport = () => {
1384
+ const classes = useStyles();
1385
+ const [allocationData, setAllocationData] = useState([]);
1386
+ const [cumulativeData, setCumulativeData] = useState({});
1387
+ const [totalData, setTotalData] = useState({});
1388
+ useEffect(() => {
1389
+ const cumulative = rangeToCumulative(allocationData, aggregateBy);
1390
+ setCumulativeData(toArray(cumulative));
1391
+ setTotalData(cumulativeToTotals(cumulative));
1392
+ }, [allocationData]);
1393
+ const [window, setWindow] = useState(windowOptions[0].value);
1394
+ const [aggregateBy, setAggregateBy] = useState(aggregationOptions[0].value);
1395
+ const [accumulate, setAccumulate] = useState(accumulateOptions[0].value);
1396
+ const [currency, setCurrency] = useState("USD");
1397
+ const [title, setTitle] = useState("Last 7 days by namespace daily");
1398
+ useEffect(() => {
1399
+ setFetch(true);
1400
+ setTitle(generateTitle({ window, aggregateBy, accumulate }));
1401
+ }, [window, aggregateBy, accumulate]);
1402
+ const [init, setInit] = useState(false);
1403
+ const [fetch, setFetch] = useState(false);
1404
+ const [loading, setLoading] = useState(true);
1405
+ const [errors, setErrors] = useState([]);
1406
+ useEffect(() => {
1407
+ if (!init) {
1408
+ initialize();
1409
+ }
1410
+ if (init && fetch) {
1411
+ fetchData();
1412
+ }
1413
+ }, [init, fetch]);
1414
+ const routerLocation = useLocation();
1415
+ const searchParams = new URLSearchParams(routerLocation.search);
1416
+ const routerNavigate = useNavigate();
1417
+ useEffect(() => {
1418
+ setWindow(searchParams.get("window") || "6d");
1419
+ setAggregateBy(searchParams.get("agg") || "namespace");
1420
+ setAccumulate(searchParams.get("acc") === "true" || false);
1421
+ setCurrency(searchParams.get("currency") || "USD");
1422
+ }, [routerLocation]);
1423
+ async function initialize() {
1424
+ setInit(true);
1425
+ }
1426
+ const configApi = useApi(configApiRef);
1427
+ const baseUrl = configApi.getConfig("opencost").getString("baseUrl");
1428
+ console.log(`baseUrl:${baseUrl}`);
1429
+ async function fetchData() {
1430
+ setLoading(true);
1431
+ setErrors([]);
1432
+ try {
1433
+ const resp = await AllocationService$1.fetchAllocation(
1434
+ baseUrl,
1435
+ window,
1436
+ aggregateBy,
1437
+ { accumulate }
1438
+ );
1439
+ if (resp.data && resp.data.length > 0) {
1440
+ const allocationRange = resp.data;
1441
+ for (const i in allocationRange) {
1442
+ if (Object.hasOwn(allocationRange, i)) {
1443
+ allocationRange[i] = sortBy(allocationRange[i], (a) => a.totalCost);
1444
+ }
1445
+ }
1446
+ setAllocationData(allocationRange);
1447
+ } else {
1448
+ setAllocationData([]);
1449
+ }
1450
+ } catch (err) {
1451
+ if (err.message.indexOf("404") === 0) {
1452
+ setErrors([
1453
+ // @ts-ignore: not assignable to type 'never'
1454
+ {
1455
+ primary: "Failed to load report data",
1456
+ secondary: "Please update OpenCost to the latest version, then open an Issue on GitHub if problems persist."
1457
+ }
1458
+ ]);
1459
+ } else {
1460
+ let secondary = "Please open an OpenCost issue with a bug report if problems persist.";
1461
+ if (err.message.length > 0) {
1462
+ secondary = err.message;
1463
+ }
1464
+ setErrors([
1465
+ // @ts-ignore: not assignable to type 'never'
1466
+ {
1467
+ primary: "Failed to load report data",
1468
+ secondary
1469
+ }
1470
+ ]);
1471
+ }
1472
+ setAllocationData([]);
1473
+ }
1474
+ setLoading(false);
1475
+ setFetch(false);
1476
+ }
1477
+ return /* @__PURE__ */ React.createElement(Page, { active: "reports.html" }, !loading && errors.length > 0 && /* @__PURE__ */ React.createElement("div", { style: { marginBottom: 20 } }, /* @__PURE__ */ React.createElement(Warnings, { warnings: errors })), init && /* @__PURE__ */ React.createElement(Paper, { id: "report" }, /* @__PURE__ */ React.createElement("div", { className: classes.reportHeader }, /* @__PURE__ */ React.createElement("div", { className: classes.titles }, /* @__PURE__ */ React.createElement(Typography, { variant: "h5" }, title), /* @__PURE__ */ React.createElement(Subtitle$1, { report: { window, aggregateBy, accumulate } })), /* @__PURE__ */ React.createElement(IconButton, { "aria-label": "refresh", onClick: () => setFetch(true) }, /* @__PURE__ */ React.createElement(RefreshIcon, null)), /* @__PURE__ */ React.createElement(
1478
+ Controls$1,
1479
+ {
1480
+ windowOptions,
1481
+ window,
1482
+ setWindow: (win) => {
1483
+ searchParams.set("window", win);
1484
+ routerNavigate({
1485
+ search: `?${searchParams.toString()}`
1486
+ });
1487
+ },
1488
+ aggregationOptions,
1489
+ aggregateBy,
1490
+ setAggregateBy: (agg) => {
1491
+ searchParams.set("agg", agg);
1492
+ routerNavigate({
1493
+ search: `?${searchParams.toString()}`
1494
+ });
1495
+ },
1496
+ accumulateOptions,
1497
+ accumulate,
1498
+ setAccumulate: (acc) => {
1499
+ searchParams.set("acc", acc);
1500
+ routerNavigate({
1501
+ search: `?${searchParams.toString()}`
1502
+ });
1503
+ },
1504
+ title,
1505
+ cumulativeData,
1506
+ currency,
1507
+ currencyOptions: currencyCodes,
1508
+ setCurrency: (curr) => {
1509
+ searchParams.set("currency", curr);
1510
+ routerNavigate({
1511
+ search: `?${searchParams.toString()}`
1512
+ });
1513
+ }
1514
+ }
1515
+ )), loading && /* @__PURE__ */ React.createElement("div", { style: { display: "flex", justifyContent: "center" } }, /* @__PURE__ */ React.createElement("div", { style: { paddingTop: 100, paddingBottom: 100 } }, /* @__PURE__ */ React.createElement(CircularProgress, null))), !loading && /* @__PURE__ */ React.createElement(
1516
+ AllocationReport$1,
1517
+ {
1518
+ allocationData,
1519
+ cumulativeData,
1520
+ totalData,
1521
+ currency
1522
+ }
1523
+ )));
1524
+ };
1525
+
1526
+ const OpenCostPage = () => /* @__PURE__ */ React.createElement(Page$1, { themeId: "tool" }, /* @__PURE__ */ React.createElement(
1527
+ Header,
1528
+ {
1529
+ title: "OpenCost",
1530
+ subtitle: "Open source Kubernetes cloud cost monitoring"
1531
+ },
1532
+ /* @__PURE__ */ React.createElement("a", { href: "https://opencost.io" }, /* @__PURE__ */ React.createElement("img", { width: 68, height: 64, src: logo, alt: "OpenCost" }))
1533
+ ), /* @__PURE__ */ React.createElement(Content, null, /* @__PURE__ */ React.createElement(Grid, { container: true, spacing: 3, direction: "column" }, /* @__PURE__ */ React.createElement(Grid, { item: true }, /* @__PURE__ */ React.createElement(OpenCostReport, null)))));
1534
+
1535
+ export { OpenCostPage };
1536
+ //# sourceMappingURL=index-BQC8_PDN.esm.js.map