Skip to main content

systemprompt_cli/commands/analytics/costs/
summary.rs

1//! `analytics costs summary` command.
2//!
3//! Copyright (c) systemprompt.io — Business Source License 1.1.
4//! See <https://systemprompt.io> for licensing details.
5
6use anyhow::Result;
7use chrono::{DateTime, Duration, Utc};
8use clap::Args;
9use std::future::Future;
10use std::path::PathBuf;
11use systemprompt_analytics::CostAnalyticsRepository;
12use systemprompt_analytics::models::reporting::CostSummaryRow;
13use systemprompt_logging::CliService;
14use systemprompt_runtime::DatabaseContext;
15
16use super::CostSummaryOutput;
17use crate::CliConfig;
18use crate::commands::analytics::shared::{
19    export_single_to_csv, parse_time_range, resolve_export_path,
20};
21use crate::shared::CommandOutput;
22
23#[derive(Debug, Args)]
24pub struct SummaryArgs {
25    #[arg(
26        long,
27        alias = "from",
28        help = "Time range (e.g., '1h', '24h', '7d'). Defaults to 24h, widening to 7d then 30d \
29                while that window holds no requests."
30    )]
31    pub since: Option<String>,
32
33    #[arg(long, alias = "to", help = "End time for range")]
34    pub until: Option<String>,
35
36    #[arg(long, help = "Export results to CSV file")]
37    pub export: Option<PathBuf>,
38}
39
40pub(super) async fn execute_with_pool(
41    args: SummaryArgs,
42    db_ctx: &DatabaseContext,
43    _config: &CliConfig,
44) -> Result<CommandOutput> {
45    let repo = CostAnalyticsRepository::new(db_ctx.db_pool())?;
46    execute_internal(args, &repo).await
47}
48
49#[derive(Debug, Clone, Copy)]
50pub struct ResolvedWindow {
51    pub start: DateTime<Utc>,
52    pub end: DateTime<Utc>,
53    pub summary: CostSummaryRow,
54    pub widened_to: Option<&'static str>,
55}
56
57const WIDEN_LADDER: [(&str, i64); 2] = [("7d", 7), ("30d", 30)];
58
59pub async fn resolve_window<F, Fut>(
60    since: Option<&String>,
61    until: Option<&String>,
62    fetch: F,
63) -> Result<ResolvedWindow>
64where
65    F: Fn(DateTime<Utc>, DateTime<Utc>) -> Fut,
66    Fut: Future<Output = Result<CostSummaryRow>>,
67{
68    let (start, end) = parse_time_range(since, until)?;
69    let summary = fetch(start, end).await?;
70
71    let explicit = since.is_some() || until.is_some();
72    if explicit || summary.requests > 0 {
73        return Ok(ResolvedWindow {
74            start,
75            end,
76            summary,
77            widened_to: None,
78        });
79    }
80
81    for (label, days) in WIDEN_LADDER {
82        let widened_start = end - Duration::days(days);
83        let widened = fetch(widened_start, end).await?;
84        if widened.requests > 0 {
85            return Ok(ResolvedWindow {
86                start: widened_start,
87                end,
88                summary: widened,
89                widened_to: Some(label),
90            });
91        }
92    }
93
94    Ok(ResolvedWindow {
95        start,
96        end,
97        summary,
98        widened_to: None,
99    })
100}
101
102async fn execute_internal(
103    args: SummaryArgs,
104    repo: &CostAnalyticsRepository,
105) -> Result<CommandOutput> {
106    let ResolvedWindow {
107        start,
108        end,
109        summary: current,
110        widened_to,
111    } = resolve_window(
112        args.since.as_ref(),
113        args.until.as_ref(),
114        |start, end| async move { repo.get_summary(start, end).await.map_err(Into::into) },
115    )
116    .await?;
117
118    let period_duration = end - start;
119    let prev_start = start - period_duration;
120
121    let previous = repo.get_previous_cost(prev_start, start).await?;
122
123    let total_cost = current.cost.unwrap_or(0);
124    let prev_cost = previous.cost.unwrap_or(0);
125    let change_percent = if prev_cost > 0 {
126        Some(((total_cost - prev_cost) as f64 / prev_cost as f64) * 100.0)
127    } else {
128        None
129    };
130
131    let avg_cost = if current.requests > 0 {
132        total_cost as f64 / current.requests as f64
133    } else {
134        0.0
135    };
136
137    let output = CostSummaryOutput {
138        period: format!(
139            "{} to {}",
140            start.format("%Y-%m-%d %H:%M"),
141            end.format("%Y-%m-%d %H:%M")
142        ),
143        total_cost_microdollars: total_cost,
144        total_requests: current.requests,
145        total_tokens: current.tokens.unwrap_or(0),
146        avg_cost_per_request_microdollars: avg_cost,
147        change_percent,
148        auto_widened_to: widened_to.map(str::to_owned),
149    };
150
151    if let Some(ref path) = args.export {
152        let resolved_path = resolve_export_path(path)?;
153        export_single_to_csv(&output, &resolved_path)?;
154        CliService::success(&format!("Exported to {}", resolved_path.display()));
155        return Ok(CommandOutput::card_value("Cost Summary", &output).with_skip_render());
156    }
157
158    Ok(CommandOutput::card_value("Cost Summary", &output))
159}