feat(dashboard): add time-frame filtering and used-models-only pricing
Some checks failed
CI / Check (push) Has been cancelled
CI / Clippy (push) Has been cancelled
CI / Formatting (push) Has been cancelled
CI / Test (push) Has been cancelled
CI / Release Build (push) Has been cancelled

- All usage endpoints now accept ?period=today|24h|7d|30d|all|custom
  with optional &from=ISO&to=ISO for custom ranges
- Time-series chart adapts granularity: hourly for today/24h, daily for
  7d/30d/all
- Analytics and Costs pages have period selector buttons with custom
  date-range picker
- Pricing table on Costs page now only shows models that have actually
  been used (GET /models?used_only=true)
- Cache-bust version bumped to v=6
This commit is contained in:
2026-03-02 15:29:23 -05:00
parent 54c45cbfca
commit 5bf41be343
7 changed files with 498 additions and 144 deletions

View File

@@ -3,42 +3,73 @@
class CostsPage {
constructor() {
this.costData = null;
this.period = '7d';
this.init();
}
async init() {
// Load data
await Promise.all([
this.loadCostStats(),
this.loadCostsChart(),
this.loadBudgetTracking(),
this.loadPricingTable()
]);
// Setup event listeners
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 data = await window.api.get('/usage/summary');
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: data.total_cost,
todayCost: data.today_cost,
weekCost: data.total_cost * 0.4, // Placeholder for weekly logic
monthCost: data.total_cost,
avgDailyCost: data.total_cost / 30, // Simplified
costTrend: 5.2,
budgetUsed: Math.min(Math.round((data.total_cost / 100) * 100), 100), // Assuming $100 budget
projectedMonthEnd: data.today_cost * 30,
cacheReadTokens: data.total_cache_read_tokens || 0,
cacheWriteTokens: data.total_cache_write_tokens || 0,
totalTokens: data.total_tokens || 0,
totalCost,
todayCost,
totalRequests,
avgDailyCost: totalCost / periodDays,
cacheReadTokens,
cacheWriteTokens,
totalTokens,
};
this.renderCostStats();
} catch (error) {
console.error('Error loading cost stats:', error);
}
@@ -51,7 +82,15 @@ class CostsPage {
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 = `
<div class="stat-card">
<div class="stat-icon warning">
@@ -66,21 +105,34 @@ class CostsPage {
</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon success">
<i class="fas fa-calendar-alt"></i>
</div>
<div class="stat-content">
<div class="stat-value">${window.api.formatCurrency(this.costData.monthCost)}</div>
<div class="stat-label">This Month</div>
<div class="stat-value">${periodLabel}</div>
<div class="stat-label">Period</div>
<div class="stat-change">
<i class="fas fa-chart-line"></i>
${window.api.formatCurrency(this.costData.avgDailyCost)}/day avg
${this.costData.totalRequests.toLocaleString()} requests
</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon primary">
<i class="fas fa-chart-line"></i>
</div>
<div class="stat-content">
<div class="stat-value">${window.api.formatCurrency(this.costData.avgDailyCost)}</div>
<div class="stat-label">Daily Average</div>
<div class="stat-change">
<i class="fas fa-bolt"></i>
${cacheHitRate}% cache hit rate
</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon primary">
<i class="fas fa-bolt"></i>
@@ -93,19 +145,6 @@ class CostsPage {
</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon danger">
<i class="fas fa-piggy-bank"></i>
</div>
<div class="stat-content">
<div class="stat-value">${this.costData.budgetUsed}%</div>
<div class="stat-label">Budget Used</div>
<div class="stat-change">
$${this.costData.projectedMonthEnd.toFixed(2)} projected
</div>
</div>
</div>
`;
}
@@ -114,13 +153,14 @@ class CostsPage {
const cm = window.chartManager || await window.waitForChartManager();
if (!cm) { this.showEmptyChart('costs-chart', 'Chart system unavailable'); return; }
const data = await window.api.get('/usage/providers');
const qs = this.periodQuery();
const data = await window.api.get(`/usage/providers${qs}`);
if (!data || data.length === 0) {
this.showEmptyChart('costs-chart', 'No provider spending data yet');
this.showEmptyChart('costs-chart', 'No provider spending data for this period');
return;
}
const chartData = {
labels: data.map(item => item.provider),
datasets: [{
@@ -129,9 +169,9 @@ class CostsPage {
color: '#fe8019'
}]
};
cm.createBarChart('costs-chart', chartData);
} catch (error) {
console.error('Error loading costs chart:', error);
this.showEmptyChart('costs-chart', 'Failed to load spending data');
@@ -158,15 +198,15 @@ class CostsPage {
async loadBudgetTracking() {
const container = document.getElementById('budget-progress');
if (!container) return;
try {
const providers = await window.api.get('/providers');
container.innerHTML = providers.filter(p => p.id !== 'ollama').map(provider => {
const used = provider.low_credit_threshold; // Not quite right but using available fields
const used = provider.low_credit_threshold;
const balance = provider.credit_balance;
const percentage = balance > 0 ? Math.max(0, Math.min(100, (1 - (used / balance)) * 100)) : 0;
return `
<div class="budget-item" style="margin-bottom: 1.5rem;">
<div class="budget-header" style="display: flex; justify-content: space-between; margin-bottom: 0.5rem;">
@@ -190,7 +230,8 @@ class CostsPage {
async loadPricingTable() {
try {
const data = await window.api.get('/models');
// Only show models that have actually been used
const data = await window.api.get('/models?used_only=true');
this.renderPricingTable(data);
} catch (error) {
console.error('Error loading pricing data:', error);
@@ -200,7 +241,12 @@ class CostsPage {
renderPricingTable(data) {
const tableBody = document.querySelector('#pricing-table tbody');
if (!tableBody) return;
if (!data || data.length === 0) {
tableBody.innerHTML = '<tr><td colspan="6" class="text-center" style="color:var(--fg4);">No models have been used yet</td></tr>';
return;
}
tableBody.innerHTML = data.map(row => {
const cacheRead = row.cache_read_cost != null
? `${window.api.formatCurrency(row.cache_read_cost)} / 1M`
@@ -222,14 +268,42 @@ class CostsPage {
}
setupEventListeners() {
// ...
// Period selector buttons
const periodContainer = document.getElementById('costs-period');
if (periodContainer) {
periodContainer.querySelectorAll('[data-period]').forEach(btn => {
btn.onclick = () => {
periodContainer.querySelectorAll('[data-period]').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const period = btn.dataset.period;
this.period = period;
// Show/hide custom range inputs
const customRange = document.getElementById('costs-custom-range');
if (customRange) {
customRange.style.display = period === 'custom' ? 'flex' : 'none';
}
if (period !== 'custom') {
this.refresh();
}
};
});
}
// Custom range apply button
const applyCustom = document.getElementById('costs-apply-custom');
if (applyCustom) {
applyCustom.onclick = () => this.refresh();
}
}
refresh() {
this.loadCostStats();
this.loadCostsChart();
this.loadBudgetTracking();
this.loadPricingTable();
// Pricing table doesn't change with period (it's model metadata, not usage)
}
}