// Costs Page Module class CostsPage { constructor() { this.costData = null; this.period = '7d'; this.init(); } async init() { await Promise.all([ this.loadCostStats(), this.loadCostsChart(), this.loadBudgetTracking(), this.loadPricingTable() ]); this.setupEventListeners(); } /** Build query string from the current period. */ periodQuery() { if (this.period === 'custom') { const from = document.getElementById('costs-from')?.value; const to = document.getElementById('costs-to')?.value; let qs = '?period=custom'; if (from) qs += `&from=${from}T00:00:00Z`; if (to) qs += `&to=${to}T23:59:59Z`; return qs; } return `?period=${this.period}`; } async loadCostStats() { try { const qs = this.periodQuery(); const data = await window.api.get(`/usage/summary${qs}`); const totalCost = data.total_cost; const totalTokens = data.total_tokens || 0; const cacheReadTokens = data.total_cache_read_tokens || 0; const cacheWriteTokens = data.total_cache_write_tokens || 0; const todayCost = data.today_cost; const totalRequests = data.total_requests; // Compute days in the period for daily average let periodDays = 1; if (this.period === '7d') periodDays = 7; else if (this.period === '30d') periodDays = 30; else if (this.period === 'today') periodDays = 1; else if (this.period === 'all') periodDays = Math.max(1, 30); // rough fallback else if (this.period === 'custom') { const from = document.getElementById('costs-from')?.value; const to = document.getElementById('costs-to')?.value; if (from && to) { const diff = (new Date(to) - new Date(from)) / (1000 * 60 * 60 * 24); periodDays = Math.max(1, Math.ceil(diff)); } } this.costData = { totalCost, todayCost, totalRequests, avgDailyCost: totalCost / periodDays, cacheReadTokens, cacheWriteTokens, totalTokens, }; this.renderCostStats(); } catch (error) { console.error('Error loading cost stats:', error); } } renderCostStats() { const container = document.getElementById('cost-stats'); if (!container) return; const cacheHitRate = this.costData.totalTokens > 0 ? ((this.costData.cacheReadTokens / this.costData.totalTokens) * 100).toFixed(1) : '0.0'; const periodLabel = { 'today': 'Today', '7d': 'Past 7 Days', '30d': 'Past 30 Days', 'all': 'All Time', 'custom': 'Custom Range', }[this.period] || this.period; container.innerHTML = `
${row.id}