-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbilling_reporter.js
More file actions
44 lines (40 loc) · 1.45 KB
/
billing_reporter.js
File metadata and controls
44 lines (40 loc) · 1.45 KB
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
const { BigQuery } = require('@google-cloud/bigquery');
const query = (billingAccountId,billingDataset) => `
SELECT
ROUND(SUM(cost),2) AS total,
FORMAT_DATE('%Y-%m-%d', DATE(usage_end_time)) AS day,
(
SELECT value
FROM UNNEST(project.labels)
WHERE KEY='env') AS environment
FROM \`${billingDataset}.gcp_billing_export_resource_v1_${billingAccountId}\`
WHERE
FORMAT_DATE('%Y-%m-%d', DATE(usage_end_time)) = FORMAT_DATE('%Y-%m-%d', CURRENT_DATE()) OR
FORMAT_DATE('%Y-%m-%d', DATE(usage_end_time)) = FORMAT_DATE('%Y-%m-%d', DATE_ADD(CURRENT_DATE(), INTERVAL -1 DAY)) OR
FORMAT_DATE('%Y-%m-%d', DATE(usage_end_time)) = FORMAT_DATE('%Y-%m-%d', DATE_ADD(CURRENT_DATE(), INTERVAL -7 DAY))
GROUP BY
environment,
day
ORDER BY
day DESC
;
`;
const billingReport = data => data[0].map(row => `*Date:* ${row.day} *Environment:* ${row.environment} *Cost:* ${row.total}`).join('\n');
class BillingReporter {
constructor(projectId, billingAccountId, billingDataset) {
this.bigquery = new BigQuery({
projectId: projectId,
});
this.billingAccountId = billingAccountId;
this.billingDataset = billingDataset;
}
query() {
return this.bigquery.query({
query: query(this.billingAccountId,this.billingDataset),
useLegacySql: false,
}).then(data => new Promise(
resolve => resolve(billingReport(data))
));
}
}
module.exports = BillingReporter;