#!/usr/bin/env node
const { spawn } = require('child_process');
async function getCloudWatchLast30Days() {
console.log('๐
CLOUDWATCH COSTS - LAST 30 DAYS');
console.log('Period: July 27, 2025 - August 26, 2025');
console.log('=' .repeat(60));
const server = spawn('node', ['dist/index.js'], {
stdio: ['pipe', 'pipe', 'pipe'],
cwd: process.cwd(),
env: {
...process.env,
UMBRELLA_API_BASE_URL: 'https://api-front.umbrellacost.io/api/v1'
}
});
const responses = [];
let requestId = 1;
server.stdout.on('data', (data) => {
const lines = data.toString().split('\n').filter(line => line.trim());
for (const line of lines) {
try {
const response = JSON.parse(line);
responses.push(response);
} catch (e) {}
}
});
server.stderr.on('data', (data) => {
// Suppress most server logs for cleaner output
const message = data.toString();
if (message.includes('Successfully authenticated') || message.includes('API RESPONSE')) {
console.log('SERVER:', message.trim());
}
});
// Wait for server startup
await new Promise(resolve => setTimeout(resolve, 3000));
// Authenticate
console.log('๐ Authenticating...');
const authRequest = {
jsonrpc: "2.0",
id: requestId++,
method: "tools/call",
params: {
name: 'authenticate_user',
arguments: {
username: 'david+saola@umbrellacost.com',
password: 'Dsamsung1!'
}
}
};
server.stdin.write(JSON.stringify(authRequest) + '\n');
await new Promise(resolve => setTimeout(resolve, 5000));
const authResponse = responses.find(r => r.id === authRequest.id);
if (authResponse?.result?.content?.[0]?.text?.includes('Successfully authenticated')) {
console.log('โ
Authentication successful\n');
// Get last 30 days of CloudWatch costs
console.log('๐ Fetching CloudWatch data for last 30 days...');
const costRequest = {
jsonrpc: "2.0",
id: requestId++,
method: "tools/call",
params: {
name: 'api___invoices_caui',
arguments: {
startDate: "2025-07-27", // Exactly 30 days before Aug 26
endDate: "2025-08-26", // Today
costType: ["cost", "discount"],
periodGranLevel: "day",
groupBy: "service",
isAmortized: true,
accountId: "932213950603"
}
}
};
server.stdin.write(JSON.stringify(costRequest) + '\n');
await new Promise(resolve => setTimeout(resolve, 20000)); // Give it more time
const costResponse = responses.find(r => r.id === costRequest.id);
if (costResponse?.result?.content?.[0]?.text) {
const text = costResponse.result.content[0].text;
const jsonMatch = text.match(/```json\n([\s\S]*?)\n```/);
if (jsonMatch) {
try {
const data = JSON.parse(jsonMatch[1]);
console.log(`๐ Total records received: ${data.length}`);
// Filter for CloudWatch services
const cloudwatchData = data.filter(item => {
const serviceName = (item.service_name || '').toLowerCase();
return serviceName === 'amazoncloudwatch';
});
console.log(`๐ CloudWatch records: ${cloudwatchData.length}\n`);
if (cloudwatchData.length === 0) {
console.log('โ No CloudWatch data found');
// Show available services for debugging
const uniqueServices = [...new Set(data.map(item => item.service_name || 'Unknown'))]
.filter(s => s !== 'Unknown')
.sort()
.slice(0, 10);
console.log('\n๐ Available services (sample):');
uniqueServices.forEach(service => {
console.log(` - ${service}`);
});
server.kill();
return;
}
// Process CloudWatch data by date
const dailyCosts = {};
let totalCost = 0;
cloudwatchData.forEach(item => {
const date = item.usage_date.split('T')[0];
const cost = item.total_cost || 0;
dailyCosts[date] = cost;
totalCost += cost;
});
// Sort dates and display complete breakdown
const sortedDates = Object.keys(dailyCosts).sort();
console.log('๐๏ธ COMPLETE 30-DAY CLOUDWATCH BREAKDOWN:');
console.log('='.repeat(55));
sortedDates.forEach((date, index) => {
const cost = dailyCosts[date];
const dateObj = new Date(date + 'T12:00:00Z');
const dayName = dateObj.toLocaleDateString('en-US', { weekday: 'short' });
const monthDay = dateObj.toLocaleDateString('en-US', { month: 'short', day: '2-digit' });
console.log(`${String(index + 1).padStart(2)}. ${monthDay} (${dayName}): $${cost.toFixed(2)}`);
});
console.log('='.repeat(55));
console.log(`๐ฐ TOTAL CLOUDWATCH (${sortedDates.length} days): $${totalCost.toFixed(2)}`);
// Calculate statistics
const costs = Object.values(dailyCosts);
const avgDaily = totalCost / sortedDates.length;
const maxCost = Math.max(...costs);
const minCost = Math.min(...costs);
const maxDate = sortedDates.find(date => dailyCosts[date] === maxCost);
const minDate = sortedDates.find(date => dailyCosts[date] === minCost);
console.log(`\n๐ STATISTICS:`);
console.log(` Average daily: $${avgDaily.toFixed(2)}`);
console.log(` Highest day: $${maxCost.toFixed(2)} (${new Date(maxDate + 'T12:00:00Z').toLocaleDateString('en-US', { month: 'short', day: '2-digit' })})`);
console.log(` Lowest day: $${minCost.toFixed(2)} (${new Date(minDate + 'T12:00:00Z').toLocaleDateString('en-US', { month: 'short', day: '2-digit' })})`);
console.log(` Daily range: $${(maxCost - minCost).toFixed(2)}`);
// Weekly averages
console.log(`\n๐
WEEKLY BREAKDOWN:`);
const weeklyTotals = {};
sortedDates.forEach(date => {
const dateObj = new Date(date + 'T12:00:00Z');
const weekStart = new Date(dateObj);
weekStart.setDate(dateObj.getDate() - dateObj.getDay()); // Start of week (Sunday)
const weekKey = weekStart.toISOString().split('T')[0];
weeklyTotals[weekKey] = (weeklyTotals[weekKey] || 0) + dailyCosts[date];
});
Object.entries(weeklyTotals)
.sort(([a], [b]) => new Date(a) - new Date(b))
.forEach(([weekStart, total], index) => {
const weekStartDate = new Date(weekStart + 'T12:00:00Z');
const weekStartFormatted = weekStartDate.toLocaleDateString('en-US', { month: 'short', day: '2-digit' });
console.log(` Week ${index + 1} (${weekStartFormatted}+): $${total.toFixed(2)}`);
});
} catch (e) {
console.log(`โ Error parsing JSON: ${e.message}`);
console.log('Response preview:', text.substring(0, 500));
}
} else {
console.log('โ No JSON data found in response');
console.log('Response preview:', text.substring(0, 500));
}
} else if (costResponse?.error) {
console.log('โ API Error:', JSON.stringify(costResponse.error, null, 2));
} else {
console.log('โ No response received - request may have timed out');
console.log(`Available responses: ${responses.length}`);
if (responses.length > 0) {
console.log('Latest response IDs:', responses.map(r => r.id));
}
}
} else {
console.log('โ Authentication failed');
if (authResponse?.result?.content?.[0]?.text) {
console.log('Auth response:', authResponse.result.content[0].text);
}
}
server.kill();
}
getCloudWatchLast30Days().catch(console.error);