-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathscheduled_report.pt
1198 lines (1046 loc) · 47.5 KB
/
scheduled_report.pt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
name "Scheduled Report"
rs_pt_ver 20180301
type "policy"
short_description "This policy allows you to configure scheduled reports that will provide summaries of cloud cost. See the [README](https://github.com/flexera-public/policy_templates/tree/master/cost/flexera/cco/scheduled_reports/) and [docs.flexera.com/flexera/EN/Automation](https://docs.flexera.com/flexera/EN/Automation/AutomationGS.htm) to learn more."
long_description ""
severity "low"
category "Cost"
default_frequency "monthly"
info(
version: "3.5.2",
provider: "Flexera",
service: "Cloud Cost Optimization",
policy_set: "Cloud Cost Optimization",
hide_skip_approvals: "true"
)
###############################################################################
# Parameters
###############################################################################
parameter "param_email" do
type "list"
category "Policy Settings"
label "Email Addresses"
description "Email addresses of the recipients you wish to send the scheduled report to."
default []
end
parameter "param_cost_metric" do
type "string"
category "Policy Settings"
label "Cost Metric"
description "Select the cost metric for your report. See the README file for more details"
allowed_values "Unamortized Unblended", "Amortized Unblended", "Unamortized Blended", "Amortized Blended"
default "Unamortized Unblended"
end
parameter "param_dimension_graph" do
type "string"
category "Policy Settings"
label "Graph Dimension"
description "Select which dimension you'd like to be broken out on the graph in the report. Select 'Custom' to specify the name of a custom dimension, such as a Custom Tag or Custom Rule-Based Dimension, or the name of any dimension not on the list."
allowed_values "Custom", "Category", "Billing Centers", "Instance Type", "Region", "Resource Group", "Resource Type", "Service", "Usage Type", "Usage Unit", "Cloud Vendor", "Cloud Vendor Account", "Cloud Vendor Account Name"
default "Category"
end
parameter "param_dimension_graph_custom" do
type "string"
category "Policy Settings"
label "Custom Graph Dimension"
description "Specify the name of the custom dimension you want to break costs out by. Spelling and capitalization must match what is shown in the Flexera CCO platform. Only applicable if 'Custom' is selected for the Graph Dimension."
default ""
end
parameter "param_dimension_graph_value_count" do
type "number"
category "Policy Settings"
label "Graph Dimension Value Count"
description "The number of values to display on the graph for the selected dimension. The top N values will be displayed based on the cost metric selected. Enter 0 to display all values."
min_value 0
default 10
end
parameter "param_dimension_filter" do
type "list"
category "Policy Settings"
label "Filter Dimensions"
description "Specify the names of the dimensions you wish to filter the costs by along with their values in dimension=value format. Spelling and capitalization must match what is shown in the Flexera CCO platform. Examples: Environment=Production, Cost Owner=John Doe"
allowed_pattern /^[^=]+=[^=]+$/
default []
end
parameter "param_dimension_filter_boolean" do
type "string"
category "Policy Settings"
label "Filter Functionality"
description "Whether to filter for costs that meet all of the criteria specified in 'Filter Dimensions' or costs that meet any of the criteria. Only applicable if at least two values are entered for 'Filter Dimensions'"
allowed_values "All", "Any"
default "All"
end
parameter "param_date_range" do
type "string"
category "Date/Time Settings"
label "Date Range"
description "Select the Date Range options you'd like to display on the graph in the report."
allowed_values "1 month", "3 month", "6 month", "12 month"
default "6 month"
end
parameter "param_billing_term" do
type "string"
category "Date/Time Settings"
label "Billing Term"
description "Select the unit of time you'd like to display on the graph in the report. See the README file for more details"
allowed_values "Day", "Week", "Month"
default "Month"
end
parameter "param_billing_centers" do
type "list"
category "Filters"
label "Billing Center List"
description "List of Billing Center names or IDs you want to report on. Leave blank to select all top level Billing Centers."
default []
end
parameter "param_percent_change_threshold" do
type "number"
category "Policy Settings"
label "Percent Change Threshold Value (%)"
description "The threshold (in percent) for the percent change in cost between time period(s) that will trigger the report. Default of `0` will send the report every time based on the applied policy schedule."
min_value 0
max_value 100
default 0
end
parameter "param_percent_change_consecutive_threshold" do
type "number"
category "Policy Settings"
label "Percent Change Consecutive Threshold"
description "The number of consecutive time period(s) where there was a percent change in cost between time period(s) that will trigger the report. Default of `1` will send the report every time based on the applied policy schedule."
min_value 1
default 1
end
parameter "param_percent_change_alert_metric" do
type "string"
category "Policy Settings"
label "Percent Change Alert Metric"
description "The metric to use for the percent change alert. Percent Change from Previous Time Period Daily Average is recommended to normalize between Month periods. This has no affect if Billing Term is set to 'Day'."
allowed_values "Percent Change from Previous Time Period Daily Average", "Percent Change from Previous Time Period"
default "Percent Change from Previous Time Period Daily Average"
end
parameter "param_percent_change_alert_direction" do
type "string"
category "Policy Settings"
label "Percent Change Alert Direction"
description "Select the direction of percent change that will trigger the report."
allowed_values "Increase", "Decrease", "Both"
default "Increase"
end
###############################################################################
# Authentication
###############################################################################
credentials "auth_flexera" do
schemes "oauth2"
label "flexera"
description "Select Flexera One OAuth2 credentials"
tags "provider=flexera"
end
###############################################################################
# Datasources & Scripts
###############################################################################
# Misc. immutable data used by other parts of the policy
datasource "ds_data_tables" do
run_script $js_data_tables
end
script "js_data_tables", type:"javascript" do
result "result"
code <<-EOS
result = {
cost_metrics: {
"Unamortized Unblended": "cost_nonamortized_unblended_adj",
"Amortized Unblended": "cost_amortized_unblended_adj",
"Unamortized Blended": "cost_nonamortized_blended_adj",
"Amortized Blended": "cost_amortized_blended_adj"
},
dimensions: {
"Category": "category",
"Billing Centers": "billing_center_id",
"Instance Type": "instance_type",
"Region": "region",
"Resource Group": "resource_group",
"Resource Type": "resource_type",
"Service": "service",
"Usage Type": "usage_type",
"Usage Unit": "usage_unit",
"Cloud Vendor": "vendor",
"Cloud Vendor Account": "vendor_account",
"Cloud Vendor Account Name": "vendor_account_name",
"Custom": ""
},
graph_colors: [
'D05A5A', 'F78741', 'FCC419', '007D76', '37AA77', '92DA71',
'0F77B3', '7BACD1', 'BCC7E1', 'B80C83', 'E06C96', 'FBB3BB',
'5F3DC4', '00A2F3', '99E9F2', '5C940D', '8EBF45', 'C0EB75',
'F2C80F', 'F7E7A8', 'F9D6B3', 'F2A0A1', 'F4C2C2', 'F8E0E0',
'A8A7A7', 'D9D8D8', 'EDEDED', '000000', '333333', '666666',
'999999', 'CCCCCC', 'FFFFFF', 'FF0000', '00FF00', '0000FF',
'FFFF00', 'FF00FF', '00FFFF', 'FF8000', 'FF0080', '80FF00',
'80FF00', '0080FF', '8000FF', 'FF8080', '80FF80', '8080FF'
],
months_short: [
'None', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
],
months_long: [
'None', 'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
]
}
EOS
end
# Store the Flexera domain name for links based on region
datasource "ds_flexera_domain" do
run_script $js_flexera_domain, rs_optima_host
end
script "js_flexera_domain", type: "javascript" do
parameters "rs_optima_host"
result "result"
code <<-EOS
domain_table = {
"api.optima.flexeraeng.com": "app.flexera.com",
"api.optima-eu.flexeraeng.com": "app.flexera.eu",
"api.optima-apac.flexeraeng.com": "app.flexera.au",
}
result = domain_table[rs_optima_host]
EOS
end
# Store details about graph dimension in datasource
datasource "ds_cost_dimensions" do
request do
auth $auth_flexera
host rs_optima_host
path join(["/bill-analysis/orgs/", rs_org_id, "/costs/dimensions"])
header "Api-Version", "1.0"
end
result do
encoding "json"
collect jmes_path(response, "dimensions[*]") do
field "id", jmes_path(col_item, "id")
field "name", jmes_path(col_item, "name")
field "type", jmes_path(col_item, "type")
end
end
end
datasource "ds_cost_dimension_table" do
run_script $js_cost_dimension_table, $ds_cost_dimensions
end
script "js_cost_dimension_table", type: "javascript" do
parameters "ds_cost_dimensions"
result "result"
code <<-EOS
result = {}
_.each(ds_cost_dimensions, function(item) {
result[item['name']] = item['id']
})
EOS
end
datasource "ds_graph_dimension" do
run_script $js_graph_dimension, $ds_cost_dimension_table, $ds_data_tables, $param_dimension_graph, $param_dimension_graph_custom
end
script "js_graph_dimension", type: "javascript" do
parameters "ds_cost_dimension_table", "ds_data_tables", "param_dimension_graph", "param_dimension_graph_custom"
result "result"
code <<-EOS
result = { id: "category", name: "Category" }
if (param_dimension_graph == 'Custom') {
id = ds_cost_dimension_table[param_dimension_graph_custom]
// Attempt to correct for possible user error when entering dimension names
if (id == undefined) { id = ds_cost_dimension_table[param_dimension_graph_custom.trim()] }
if (id == undefined) { id = ds_cost_dimension_table[param_dimension_graph_custom.toLowerCase()] }
if (id == undefined) { id = ds_cost_dimension_table[param_dimension_graph_custom.toLowerCase().trim()] }
if (id != undefined) {
result = {
id: ds_cost_dimension_table[param_dimension_graph_custom],
name: param_dimension_graph_custom
}
}
} else {
result = {
id: ds_data_tables['dimensions'][param_dimension_graph],
name: param_dimension_graph
}
}
EOS
end
# Gather applied policy metadata for use later
datasource "ds_applied_policy" do
request do
auth $auth_flexera
host rs_governance_host
path join(["/api/governance/projects/", rs_project_id, "/applied_policies/", policy_id])
header "Api-Version", "1.0"
end
end
datasource "ds_billing_centers" do
request do
auth $auth_flexera
host rs_optima_host
path join(["/analytics/orgs/", rs_org_id, "/billing_centers"])
query "view", "allocation_table"
header "Api-Version", "1.0"
header "User-Agent", "RS Policies"
ignore_status [403]
end
result do
encoding "json"
collect jmes_path(response, "[*]") do
field "href", jmes_path(col_item, "href")
field "id", jmes_path(col_item, "id")
field "name", jmes_path(col_item, "name")
field "parent_id", jmes_path(col_item, "parent_id")
field "ancestor_ids", jmes_path(col_item, "ancestor_ids")
field "allocation_table", jmes_path(col_item, "allocation_table")
end
end
end
# Filter billing centers based on parameter
datasource "ds_filtered_bcs" do
run_script $js_filtered_bcs, $ds_billing_centers, $param_billing_centers
end
script "js_filtered_bcs", type: "javascript" do
parameters "ds_billing_centers", "param_billing_centers"
result "result"
code <<-EOS
if (param_billing_centers.length > 0) {
result = _.filter(ds_billing_centers, function(bc) {
return _.contains(param_billing_centers, bc['name']) || _.contains(param_billing_centers, bc['name'].toLowerCase()) || _.contains(param_billing_centers, bc['id'])
})
} else {
result = _.filter(ds_billing_centers, function(bc) {
return bc['parent_id'] == null || bc['parent_id'] == undefined
})
}
EOS
end
datasource "ds_currency_reference" do
request do
host "raw.githubusercontent.com"
path "/flexera-public/policy_templates/master/data/currency/currency_reference.json"
header "User-Agent", "RS Policies"
end
end
datasource "ds_currency_code" do
request do
auth $auth_flexera
host rs_optima_host
path join(["/bill-analysis/orgs/", rs_org_id, "/settings/currency_code"])
header "Api-Version", "0.1"
header "User-Agent", "RS Policies"
ignore_status [403]
end
result do
encoding "json"
field "id", jmes_path(response, "id")
field "value", jmes_path(response, "value")
end
end
datasource "ds_currency" do
run_script $js_currency, $ds_currency_reference, $ds_currency_code
end
script "js_currency", type:"javascript" do
parameters "ds_currency_reference", "ds_currency_code"
result "result"
code <<-EOS
symbol = "$"
symbol_native = "$"
code = "USD"
separator = ","
if (ds_currency_code['value'] != undefined) {
if (ds_currency_reference[ds_currency_code['value']] != undefined) {
symbol = ds_currency_reference[ds_currency_code['value']]['symbol']
symbol_native = ds_currency_reference[ds_currency_code['value']]['symbol_native']
code = ds_currency_reference[ds_currency_code['value']]['code']
if (ds_currency_reference[ds_currency_code['value']]['t_separator'] != undefined) {
separator = ds_currency_reference[ds_currency_code['value']]['t_separator']
} else {
separator = ""
}
}
}
result = {
symbol: symbol,
symbol_native: symbol_native,
code: code,
separator: separator
}
EOS
end
datasource "ds_cost_request_list" do
run_script $js_cost_request_list, $ds_filtered_bcs, $ds_graph_dimension, $ds_cost_dimension_table, $ds_data_tables, $param_cost_metric, $param_date_range, $param_billing_term, $param_dimension_filter, $param_dimension_filter_boolean
end
script "js_cost_request_list", type: "javascript" do
parameters "ds_filtered_bcs", "ds_graph_dimension", "ds_cost_dimension_table", "ds_data_tables", "param_cost_metric", "param_date_range", "param_billing_term", "param_dimension_filter", "param_dimension_filter_boolean"
result "result"
code <<-EOS
// Function to take date object or YYYY-MM formatted string and move it backwards or forwards by month
function move_month(date_string, amount) {
clean_date = new Date(date_string).toISOString()
year = Number(clean_date.split('-')[0])
month = Number(clean_date.split('-')[1])
if (amount > 0) {
for (var i = 1; i <= amount; i++) {
if (month == 12) {
year += 1; month = 1
} else {
month += 1
}
}
} else {
for (var i = -1; i >= amount; i--) {
if (month == 1) {
year -= 1; month = 12
} else {
month -= 1
}
}
}
if (month < 10) { month = '0' + month }
return [year, month].join('-')
}
// Configure cost filters if specified by user
filter = {}
filter_expressions = []
boolean_table = { 'Any': 'or', 'All': 'and' }
_.each(param_dimension_filter, function(item) {
key = item.split('=')[0]
value = item.split('=')[1]
dimension_id = ds_cost_dimension_table[key]
// Attempt to correct for possible user error when entering dimension names
if (dimension_id == undefined) { dimension_id = ds_cost_dimension_table[key.trim()] }
if (dimension_id == undefined) { dimension_id = ds_cost_dimension_table[key.toLowerCase()] }
if (dimension_id == undefined) { dimension_id = ds_cost_dimension_table[key.toLowerCase().trim()] }
if (dimension_id != undefined) {
filter_expressions.push({ type: "equal", dimension: dimension_id, value: value })
}
})
if (filter_expressions.length == 1) { filter = filter_expressions[0] }
if (filter_expressions.length > 1) {
filter = {
"type": boolean_table[param_dimension_filter_boolean],
"expressions": filter_expressions
}
}
// Generate requests to send to API to pull costs
result = []
totalMonth = parseInt(param_date_range)
dimensions = [ ds_graph_dimension['id'] ]
metrics = [ ds_data_tables['cost_metrics'][param_cost_metric] ]
billing_center_ids = _.pluck(ds_filtered_bcs, 'id')
if (param_billing_term == "Day" || param_billing_term == "Week") {
for (var i = 0; i < totalMonth; i++) {
start_at = new Date().toISOString()
start_at = move_month(start_at, -i) + '-01'
end_at = move_month(start_at, 1) + '-01'
request = {
"billing_center_ids": billing_center_ids,
"dimensions": dimensions,
"metrics": metrics,
"filter": null,
"granularity": "day",
"start_at": start_at,
"end_at": end_at
}
if (filter['type'] != undefined) { request['filter'] = filter }
result.push(request)
}
} else {
end_at = new Date().toISOString()
end_at = move_month(end_at, 1)
start_at = move_month(end_at, -totalMonth)
request = {
"billing_center_ids": billing_center_ids,
"dimensions": dimensions,
"metrics": metrics,
"filter": null,
"granularity": "month",
"start_at": start_at,
"end_at": end_at
}
if (filter['type'] != undefined) { request['filter'] = filter }
result.push(request)
}
EOS
end
datasource "ds_pulled_costs" do
iterate $ds_cost_request_list
request do
auth $auth_flexera
verb "POST"
host rs_optima_host
path join(["/bill-analysis/orgs/", rs_org_id, "/costs/aggregated"])
header "Api-Version", "1.0"
header "Content-Type", "application/json"
body_field "dimensions", val(iter_item, "dimensions")
body_field "granularity", val(iter_item, "granularity")
body_field "start_at", val(iter_item, "start_at")
body_field "end_at", val(iter_item, "end_at")
body_field "metrics", val(iter_item, "metrics")
body_field "filter", val(iter_item, "filter")
body_field "billing_center_ids", val(iter_item, "billing_center_ids")
end
result do
encoding "json"
collect jmes_path(response, "rows[*]") do
field "dimensions", jmes_path(col_item, "dimensions")
field "metrics", jmes_path(col_item, "metrics")
field "timestamp", jmes_path(col_item, "timestamp")
end
end
end
datasource "ds_collated_data" do
run_script $js_collated_data, $ds_pulled_costs, $ds_billing_centers, $ds_graph_dimension, $ds_data_tables, $ds_currency, $param_cost_metric, $param_billing_term, $param_percent_change_threshold, $param_percent_change_consecutive_threshold, $param_percent_change_alert_metric, $param_percent_change_alert_direction
end
script "js_collated_data", type: "javascript" do
parameters "ds_pulled_costs", "ds_billing_centers", "ds_graph_dimension", "ds_data_tables", "ds_currency", "param_cost_metric", "param_billing_term", "param_percent_change_threshold", "param_percent_change_consecutive_threshold", "param_percent_change_alert_metric", "param_percent_change_alert_direction"
result "result"
code <<-'EOS'
result = []
// Set metric based on parameters
metric = ds_data_tables['cost_metrics'][param_cost_metric]
// Create table for finding billing center names based on id
bc_names = {}
_.each(ds_billing_centers, function(bc) { bc_names[bc['id']] = bc['name'] })
// Insert billing center names if we're reporting on that dimension.
// Otherwise, use the data as-is.
pulled_costs = ds_pulled_costs
if (ds_graph_dimension['id'] == "billing_center_id") {
pulled_costs = _.map(pulled_costs, function(row) {
return {
dimensions: {
billing_center_id: row['dimensions']['billing_center_id'],
billing_center_name: bc_names[row['dimensions']['billing_center_id']]
},
metrics: row['metrics'],
timestamp: row['timestamp']
}
})
}
// Sort pulled_costs by timestamp
// This ensures that the Percent Change calculations are accurate
pulled_costs = _.sortBy(pulled_costs, 'timestamp')
// Setup a placeholder for the previous period
// This is used to calculate percent change
// Each key is a graph dimension value and previous period is stored for each
var previousTimePeriod = {}
// Collate the pulled_costs data.
// Variables are mostly for keeping track of weeks to insert weekly data.
if (param_billing_term == 'Day' || param_billing_term == 'Month') {
_.each(pulled_costs, function(row) {
timestamp = new Date(row['timestamp'])
day = timestamp.toISOString().split('-')[2].split('T')[0]
year = timestamp.toISOString().split('-')[0]
month = timestamp.toISOString().split('-')[1]
stringMonth = ds_data_tables['months_short'][Number(timestamp.toISOString().split('-')[1])]
stringDay = stringMonth + "-" + day
// Get days in month for yearMonth
var daysinTimeUnit = new Date(year, month, 0).getDate()
category_id = ds_graph_dimension['id']
if (category_id == "billing_center_id") { category_id = "billing_center_name" }
category = row['dimensions'][category_id]
if (param_billing_term == 'Day') {
timeUnit = timestamp.toISOString().split('T')[0]
// Override daysinTimeUnit for daily average calculation
// At param_billing_term Day, this Average is not useful and will match the cost
daysinTimeUnit = 1
} else if (param_billing_term == 'Month') {
timeUnit = [year, month].join('-')
}
// For this graph dimension value, if not yet defined create an empty object
if (typeof previousTimePeriod[category] == "undefined") {
previousTimePeriod[category] = {}
}
// Calculate daily average cost
var dailyAverageCost = row['metrics'][metric] / daysinTimeUnit
// Check if we can calculate Percent Change from previous time period
var percentChange = null
var percentChangeDailyAverageCost = null
var isPercentChangeAboveThreshold = false
if (typeof previousTimePeriod[category]["row"] == "object") {
var previousCost = previousTimePeriod[category]["row"]['metrics'][metric]
var previousDailyAverageCost = previousTimePeriod[category]['dailyAverageCost']
if (previousCost > 0) {
var currentCost = row['metrics'][metric]
percentChange = Number((((currentCost - previousCost) / previousCost) * 100 ).toFixed(3))
percentChangeDailyAverageCost = Number((((dailyAverageCost - previousDailyAverageCost) / previousDailyAverageCost) * 100 ).toFixed(3))
} else {
percentChange = Number(row['metrics'][metric].toFixed(3))
percentChangeDailyAverageCost = Number(dailyAverageCost.toFixed(3))
}
// checkThreshold() function to handle the threshold check
// This is helpful because the same logic is used for both percentChange and percentChangeDailyAverageCost
function checkThreshold(percent_change_value, percent_change_threshold, percent_change_direction) {
if (percent_change_value != null) {
switch (percent_change_direction) {
case "Increase":
if (parseFloat(percent_change_value) > parseFloat(percent_change_threshold)) {
return true
}
break
case "Decrease":
if (parseFloat(percent_change_value) < parseFloat(percent_change_threshold)) {
return true
}
break
default:
// Default is detect both Increase or Decrease percent changes
// We take the absolute value of percent_change_value and compare that to the change threshold
if (parseFloat(Math.abs(percent_change_value)) > parseFloat(percent_change_threshold)) {
return true
}
}
}
return false
}
// See if the percent change is above the threshold
if (param_percent_change_alert_metric == "Percent Change from Previous Time Period Daily Average") {
isPercentChangeAboveThreshold = checkThreshold(percentChangeDailyAverageCost, param_percent_change_threshold, param_percent_change_alert_direction)
} else {
// Only two allowed param_percent_change_alert_metric values, so user selected "Percent Change from Previous Time Period"
isPercentChangeAboveThreshold = checkThreshold(percentChange, param_percent_change_threshold, param_percent_change_alert_direction)
}
}
// Store the current row for the next iteration
previousTimePeriod[category]["row"] = row
previousTimePeriod[category]["percentChange"] = percentChange
previousTimePeriod[category]["dailyAverageCost"] = dailyAverageCost
previousTimePeriod[category]["isPercentChangeAboveThreshold"] = isPercentChangeAboveThreshold
// Reset consecutivePercentChangeAboveThreshold if it is not above threshold
// This will also handle setting it to 0 if it is not defined (i.e. the first month)
if (!isPercentChangeAboveThreshold) {
previousTimePeriod[category]["consecutivePercentChangeAboveThreshold"] = 0
} else {
// Increment consecutivePercentChangeAboveThreshold if it is above threshold
previousTimePeriod[category]["consecutivePercentChangeAboveThreshold"] += 1
}
result.push({
stringMonth: stringMonth,
stringDay: stringDay,
timeUnit: timeUnit,
yearMonth: timestamp.toISOString().split('-')[0] + '-' + timestamp.toISOString().split('-')[1],
category: category,
cost: row['metrics'][metric],
displayCost: Number(row['metrics'][metric].toFixed(3)),
percentChange: percentChange,
dailyAverageCost: Number(dailyAverageCost.toFixed(3)),
percentChangeDailyAverageCost: percentChangeDailyAverageCost,
isPercentChangeAboveThreshold: isPercentChangeAboveThreshold,
consecutivePercentChangeAboveThreshold: previousTimePeriod[category]["consecutivePercentChangeAboveThreshold"],
currency: ds_currency['symbol'],
triggerAlert: false
})
})
}
if (param_billing_term == 'Week') {
count = -1
tempDayNo = 0
stringWeek = ""
data_list = {}
_.each(pulled_costs, function(row) {
timestamp = new Date(row['timestamp'])
day = timestamp.toISOString().split('-')[2].split('T')[0]
year = timestamp.toISOString().split('-')[0]
month = timestamp.toISOString().split('-')[1]
stringMonth = ds_data_tables['months_short'][Number(timestamp.toISOString().split('-')[1])]
// Get days in month for yearMonth
var daysInMonth = new Date(year, month, 0).getDate()
if (count == -1) { count = 0; tempDayNo = day; stringWeek = stringMonth + "-" + day }
if (day != tempDayNo) { count++; tempDayNo = day }
if (count >= 7) { count = 0; stringWeek = stringMonth + "-" + day }
category_id = ds_graph_dimension['id']
if (category_id == "billing_center_id") { category_id = "billing_center_name" }
category = row['dimensions'][category_id]
weekMonth = ds_data_tables['months_short'].indexOf(stringWeek.split('-')[0])
if (weekMonth < 10) { weekMonth = '0' + weekMonth }
weekDay = stringWeek.split('-')[1]
timeUnit = [year, weekMonth, weekDay].join('-')
if (data_list[stringWeek] == undefined) { data_list[stringWeek] = {} }
if (data_list[stringWeek][category] == undefined) { data_list[stringWeek][category] = [] }
data_list[stringWeek][category].push({
timeUnit: timeUnit,
yearMonth: timestamp.toISOString().split('-')[0] + '-' + timestamp.toISOString().split('-')[1],
cost: row['metrics'][metric]
})
})
_.each(_.keys(data_list), function(stringWeek) {
_.each(_.keys(data_list[stringWeek]), function(category) {
costs = _.pluck(data_list[stringWeek][category], 'cost')
sum = _.reduce(costs, function(memo, num) { return memo + num }, 0)
// Calculate Daily Average Cost
var dailyAverageCost = sum / 7
// For this graph value, if not yet defined create an empty object
if (typeof previousTimePeriod[category] == "undefined") {
previousTimePeriod[category] = {}
}
// Check if we can calcualte Percent Change from previous time period
var percentChange = null
var percentChangeDailyAverageCost = null
var isPercentChangeAboveThreshold = false
if (previousTimePeriod[category]["sum"] != undefined) {
var previousSum = previousTimePeriod[category]["sum"]
var previousDailyAverageCost = previousTimePeriod[category]["dailyAverageCost"]
if (previousSum > 0) {
percentChange = Number( (((sum - previousSum) / previousSum) * 100).toFixed(3) )
}
if (previousDailyAverageCost > 0) {
percentChangeDailyAverageCost = Number( (((dailyAverageCost - previousDailyAverageCost) / previousDailyAverageCost) * 100).toFixed(3) )
}
// See if the percent change is above the threshold
// Take the absolute value of percentChange so we can compare it to the threshold. Otherwise, by default and most use-cases any negative percent change would be below the threshold which would trigger a report which is not generally needed for downward change
if (param_percent_change_alert_metric == "Percent Change from Previous Time Period Daily Average") {
if (percentChangeDailyAverageCost != null && parseFloat(Math.abs(percentChangeDailyAverageCost)) >= parseFloat(param_percent_change_threshold)) {
isPercentChangeAboveThreshold = true
}
} else {
// Only two allowed param_percent_change_alert_metric values, so user selected "Percent Change from Previous Time Period"
if (percentChange != null && parseFloat(Math.abs(percentChange)) >= parseFloat(param_percent_change_threshold)) {
isPercentChangeAboveThreshold = true
}
}
}
// Store the current row for the next iteration
previousTimePeriod[category]["costs"] = costs
previousTimePeriod[category]["sum"] = sum
previousTimePeriod[category]["percentChange"] = percentChange
previousTimePeriod[category]["dailyAverageCost"] = dailyAverageCost
previousTimePeriod[category]["isPercentChangeAboveThreshold"] = isPercentChangeAboveThreshold
// Reset consecutivePercentChangeAboveThreshold if it is not above threshold
// This will also handle setting it to 0 if it is not defined (i.e. the first month)
if (!isPercentChangeAboveThreshold) {
previousTimePeriod[category]["consecutivePercentChangeAboveThreshold"] = 0
} else {
// Increment consecutivePercentChangeAboveThreshold if it is above threshold
previousTimePeriod[category]["consecutivePercentChangeAboveThreshold"] += 1
}
result.push({
stringWeek: stringWeek,
timeUnit: data_list[stringWeek][category][0]['timeUnit'],
yearMonth: data_list[stringWeek][category][0]['yearMonth'],
category: category,
cost: sum,
displayCost: Number(sum.toFixed(3)),
percentChange: percentChange,
dailyAverageCost: Number(dailyAverageCost.toFixed(3)),
percentChangeDailyAverageCost: percentChangeDailyAverageCost,
isPercentChangeAboveThreshold: isPercentChangeAboveThreshold,
consecutivePercentChangeAboveThreshold: previousTimePeriod[category]["consecutivePercentChangeAboveThreshold"],
currency: ds_currency['symbol'],
triggerAlert: false
})
})
})
}
if (param_percent_change_consecutive_threshold > 0) {
// Loop through all rows to determine if last n periods (param_percent_change_consecutive_threshold) for each category is above threshold
var rowsGroupedByCategory = _.groupBy(result, 'category')
// Sort each category by timeUnit
_.each(_.keys(rowsGroupedByCategory), function(category) {
rowsGroupedByCategory[category] = _.sortBy(rowsGroupedByCategory[category], 'timeUnit')
})
// Loop through all rows to determine if last n period (param_percent_change_consecutive_threshold) for category is above threshold
_.each(result, function(row) {
var category = row['category']
var lastNRows = _.last(rowsGroupedByCategory[category], param_percent_change_consecutive_threshold)
var triggerAlert = false
// Don't check if we have fewer than param_percent_change_consecutive_threshold time periods
if (lastNRows.length == param_percent_change_consecutive_threshold) {
// Check to see if the row matches the last of the lastNRows
var lastRow = _.last(lastNRows)
// Pluck the timeUnit from lastNRows
var lastNRowsTimeUnits = _.pluck(lastNRows, 'timeUnit')
// If this row is one of the last timeUnit in the lastNRows, check if all rows are above threshold
if (_.contains(lastNRowsTimeUnits, row['timeUnit'])) {
// Trigger alert if all these recent, consecutive time periods are above threshold
triggerAlert = _.every(lastNRows, function(lastRow) {
return lastRow['isPercentChangeAboveThreshold']
})
}
}
row['triggerAlert'] = triggerAlert
})
}
EOS
end
datasource "ds_generated_report" do
run_script $js_generated_report, $ds_collated_data, $ds_graph_dimension, $ds_data_tables, $ds_currency, $ds_applied_policy, $ds_flexera_domain, $param_cost_metric, $param_date_range, $param_billing_term, $param_billing_centers, $param_dimension_filter, $param_dimension_filter_boolean, $param_percent_change_threshold, $param_dimension_graph_value_count
end
script "js_generated_report", type: "javascript" do
parameters "ds_collated_data", "ds_graph_dimension", "ds_data_tables", "ds_currency", "ds_applied_policy", "ds_flexera_domain", "param_cost_metric", "param_date_range", "param_billing_term", "param_billing_centers", "param_dimension_filter", "param_dimension_filter_boolean", "param_percent_change_threshold", "param_dimension_graph_value_count"
result "result"
code <<-'EOS'
// Prepare date information for later use
now = new Date()
currentMonth = now.toISOString().split('-')[0] + '-' + now.toISOString().split('-')[1]
currentMonthName = ds_data_tables['months_long'][Number(now.toISOString().split('-')[1])]
totalMonth = parseInt(param_date_range)
// Top 10 categories
top_categories = _.filter(ds_collated_data, function(item) { return item['category'] != "" })
top_categories = _.sortBy(top_categories, 'cost').reverse()
categories = []
_.each(top_categories, function(item) {
if (!_.contains(categories, item['category']) && ((categories.length < param_dimension_graph_value_count) || (param_dimension_graph_value_count == 0))) {
categories.push(item['category'])
}
})
// Store data that is not in the top 10 categories for later use
otherData = []
bottom_data = _.reject(ds_collated_data, function(item) {
return _.contains(categories, item['category'])
})
if (param_billing_term == "Month") { group_by = "yearMonth" }
if (param_billing_term == "Day") { group_by = "stringDay" }
if (param_billing_term == "Week") { group_by = "stringWeek" }
bottom_data = _.groupBy(bottom_data, function(item) { return item[group_by] })
_.each(bottom_data, function(value, key) {
data_item = { cost: _.reduce(value, function(total, item) { return total + item['cost'] }, 0) }
if (param_billing_term == "Month") { data_item["yearMonth"] = key }
if (param_billing_term == "Day") { data_item["stringDay"] = key }
if (param_billing_term == "Week") { data_item["stringWeek"] = key }
otherData.push(data_item)
})
// get unique dates
previousMonths = _.compact(_.uniq(_.pluck(ds_collated_data, 'yearMonth')))
stringMonths = _.compact(_.uniq(_.pluck(ds_collated_data, 'stringMonth')))
stringDays = _.compact(_.uniq(_.pluck(ds_collated_data, 'stringDay')))
stringWeeks =_.compact(_.uniq(_.pluck(ds_collated_data, 'stringWeek')))
// get current month data
current_month_costs = _.filter(ds_collated_data, function(item) { return item['yearMonth'] == currentMonth })
current_month_totals = _.pluck(current_month_costs, 'cost')
current_month_total = _.reduce(current_month_totals, function (memo, num) { return memo + num }, 0)
// build out the chart data for the top categories
chartDataArray = []
if (param_billing_term == "Month") {
_.each(categories, function(category) {
seriesData = []
_.each(previousMonths, function(month) {
tempTotal = _.where(ds_collated_data, { yearMonth: month, category: category })
if (tempTotal.length == 0) { seriesData.push("_") }
if (tempTotal.length != 0) { seriesData.push(Math.round(tempTotal[0].cost)) }
})
chartDataArray.push(seriesData.join())
})
// Add the "Other" category and associated data
if (otherData.length > 0) {
categories.push("Other")
seriesData = []
_.each(previousMonths, function(month) {
var tempTotal = _.where(otherData, { yearMonth: month })
if (tempTotal.length == 0) { seriesData.push("_") }
if (tempTotal.length != 0) { seriesData.push(Math.round(tempTotal[0].cost)) }
})
chartDataArray.push(seriesData.join())
}
}
if (param_billing_term == "Day") {
_.each(categories, function(category) {
seriesData = []
_.each(stringDays, function(day) {
tempTotal = _.where(ds_collated_data, { stringDay: day, category: category })
if (tempTotal.length == 0) { seriesData.push("_") }
if (tempTotal.length != 0) { seriesData.push(Math.round(tempTotal[0].cost)) }
})
chartDataArray.push(seriesData.join())
})
// Add the "Other" category and associated data
if (otherData.length > 0) {
categories.push("Other")
seriesData = []
_.each(stringDays, function(day) {
var tempTotal = _.where(otherData, { stringDay: day })
if (tempTotal.length == 0) { seriesData.push("_") }
if (tempTotal.length != 0) { seriesData.push(Math.round(tempTotal[0].cost)) }
})
chartDataArray.push(seriesData.join())
}
}
if (param_billing_term == "Week") {
_.each(categories, function(category) {
seriesData = []
_.each(stringWeeks, function(week) {
tempTotal = _.where(ds_collated_data, { stringWeek: week, category: category })
if (tempTotal.length == 0) { seriesData.push("_") }
if (tempTotal.length != 0) { seriesData.push(Math.round(tempTotal[0].cost)) }
})
chartDataArray.push(seriesData.join())
})
// Add the "Other" category and associated data