1use crate::ocuse::db::Row;
9use crate::ocuse::zen::Catalog;
10
11pub const FIVE_HOUR_SECS: i64 = 5 * 3600;
12pub const WEEKLY_SECS: i64 = 7 * 86_400;
13pub const LOOKBACK_SECS: i64 = 120 * 86_400;
15
16#[derive(Debug, Clone, Default)]
17pub struct Totals {
18 pub cost: f64,
19 pub requests: u64,
20 pub input: u64,
21 pub output: u64,
22 pub cache_read: u64,
23}
24
25impl Totals {
26 pub fn add(&mut self, row: &Row, cost: f64) {
31 self.cost += cost;
32 self.requests += 1;
33 self.input += row.input;
34 self.output += row.output + row.reasoning;
35 self.cache_read += row.cache_read;
36 }
37
38 pub fn tokens(&self) -> u64 {
39 self.input + self.output + self.cache_read
40 }
41}
42
43#[derive(Debug, Clone)]
44pub struct ModelUsage {
45 pub id: String,
46 pub provider: String,
47 pub limit: Option<f64>,
48 pub month: Totals,
49 pub five_hour: Totals,
50 pub weekly: Totals,
51}
52
53impl ModelUsage {
54 pub fn month_use(&self) -> Option<f64> {
56 self.limit.filter(|l| *l > 0.0).map(|l| self.month.cost / l)
57 }
58}
59
60pub fn over_window(model: &ModelUsage) -> Option<&'static str> {
66 let limit = model.limit.filter(|l| *l > 0.0)?;
67 let shares = &crate::ocuse::zen::catalog().go.window_share;
68 if model.five_hour.cost > limit * shares.five_hour {
69 Some("5-hour")
70 } else if model.weekly.cost > limit * shares.weekly {
71 Some("weekly")
72 } else if model.month.cost > limit * shares.monthly {
73 Some("monthly")
74 } else {
75 None
76 }
77}
78
79#[derive(Debug, Clone)]
80pub struct Report {
81 pub period_label: String,
83 pub now_ms: i64,
84 pub since_ms: i64,
85 pub period_end_ms: Option<i64>,
89 pub month_inferred: bool,
90 pub account: Option<crate::ocuse::api::Usage>,
96 pub account_error: Option<String>,
102 pub five_hour: Totals,
103 pub weekly: Totals,
104 pub month: Totals,
105 pub models: Vec<ModelUsage>,
107}
108
109fn day_of_month(epoch_secs: i64) -> u32 {
112 civil(epoch_secs).2 as u32
113}
114
115pub fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
116 let y = if m <= 2 { y - 1 } else { y };
117 let era = y.div_euclid(400);
118 let yoe = y - era * 400;
119 let mp = if m > 2 { m - 3 } else { m + 9 };
120 let doy = (153 * mp + 2) / 5 + d - 1;
121 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
122 era * 146_097 + doe - 719_468
123}
124
125fn civil(epoch_secs: i64) -> (i64, i64, i64) {
126 let days = epoch_secs.div_euclid(86_400);
127 let z = days + 719_468;
128 let era = z.div_euclid(146_097);
129 let doe = z.rem_euclid(146_097);
130 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
131 let y = yoe + era * 400;
132 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
133 let mp = (5 * doy + 2) / 153;
134 let d = doy - (153 * mp + 2) / 5 + 1;
135 let m = if mp < 10 { mp + 3 } else { mp - 9 };
136 (if m <= 2 { y + 1 } else { y }, m, d)
137}
138
139pub fn now_ms() -> i64 {
141 std::time::SystemTime::now()
142 .duration_since(std::time::UNIX_EPOCH)
143 .map(|d| d.as_millis() as i64)
144 .unwrap_or(0)
145}
146
147pub fn calendar_month_start(now_ms: i64) -> i64 {
150 let (year, month, _) = civil(now_ms / 1000);
151 days_from_civil(year, month, 1) * 86_400_000
152}
153
154pub fn next_month(ms: i64) -> i64 {
159 let (year, month, day) = civil(ms / 1000);
160 let (ny, nm) = if month == 12 {
161 (year + 1, 1)
162 } else {
163 (year, month + 1)
164 };
165 days_from_civil(ny, nm, day.min(28)) * 86_400_000
166}
167
168pub fn prev_month(ms: i64) -> i64 {
173 let (year, month, day) = civil(ms / 1000);
174 let (py, pm) = if month == 1 {
175 (year - 1, 12)
176 } else {
177 (year, month - 1)
178 };
179 days_from_civil(py, pm, day.min(28)) * 86_400_000 + ms.rem_euclid(86_400_000)
180}
181
182pub fn month_start(rows: &[Row], now_ms: i64) -> (i64, bool) {
185 let now_secs = now_ms / 1000;
186 let (year, month, _day) = civil(now_secs);
189 let earliest_go = rows
190 .iter()
191 .filter(|r| r.provider == "opencode-go")
192 .map(|r| r.at_ms)
193 .min();
194 let anniversary = earliest_go
195 .or_else(|| rows.iter().map(|r| r.at_ms).min())
196 .map(|ms| day_of_month(ms / 1000));
197 if let Some(day_wanted) = anniversary {
198 let candidate = days_from_civil(year, month, day_wanted.min(28) as i64) * 86_400;
199 if candidate <= now_secs {
200 return (candidate * 1000, true);
201 }
202 let (py, pm) = if month == 1 {
203 (year - 1, 12)
204 } else {
205 (year, month - 1)
206 };
207 return (
208 days_from_civil(py, pm, day_wanted.min(28) as i64) * 86_400 * 1000,
209 true,
210 );
211 }
212 let current = civil(now_secs);
214 let days = days_from_civil(current.0, current.1, 1);
215 (days * 86_400 * 1000, false)
216}
217
218pub fn build(
226 rows: &[Row],
227 catalog: &Catalog,
228 plan_id: &str,
229 now_ms: i64,
230 since_override: Option<i64>,
231 account: Option<&crate::ocuse::api::Usage>,
232) -> Report {
233 let (inferred_start, month_inferred) = month_start(rows, now_ms);
234 let since_ms = since_override.unwrap_or(inferred_start);
235 let (five_start, five_end) = match account.and_then(|a| a.rolling.reset_ms()) {
244 Some(reset) => (reset - FIVE_HOUR_SECS * 1000, reset),
245 None => (now_ms - FIVE_HOUR_SECS * 1000, i64::MAX),
246 };
247 let (week_start, week_end) = match account.and_then(|a| a.weekly.reset_ms()) {
248 Some(reset) => (reset - WEEKLY_SECS * 1000, reset),
249 None => (now_ms - WEEKLY_SECS * 1000, i64::MAX),
250 };
251
252 let mut report = Report {
253 period_label: "calendar month".into(),
254 now_ms,
255 since_ms,
256 period_end_ms: None,
257 month_inferred: since_override.is_none() && month_inferred,
258 account: None,
259 account_error: None,
260 five_hour: Totals::default(),
261 weekly: Totals::default(),
262 month: Totals::default(),
263 models: Vec::new(),
264 };
265 let mut by_model: std::collections::BTreeMap<String, ModelUsage> = Default::default();
266
267 for row in rows {
268 let in_month = row.at_ms >= since_ms;
273 let in_week = row.at_ms >= week_start && row.at_ms < week_end;
274 let in_five = row.at_ms >= five_start && row.at_ms < five_end;
275 if !in_month && !in_week && !in_five {
276 continue;
277 }
278 let cost = catalog
283 .price(
284 &row.model,
285 row.at_ms,
286 row.input,
287 row.output,
288 row.reasoning,
289 row.cache_read,
290 row.cache_write,
291 )
292 .unwrap_or(row.cost_usd);
293 if in_month {
294 report.month.add(row, cost);
295 }
296 if in_week {
297 report.weekly.add(row, cost);
298 }
299 if in_five {
300 report.five_hour.add(row, cost);
301 }
302 let entry = by_model
303 .entry(row.model.clone())
304 .or_insert_with(|| ModelUsage {
305 id: row.model.clone(),
306 provider: row.provider.clone(),
307 limit: catalog.go_limit(plan_id, &row.model),
308 month: Totals::default(),
309 five_hour: Totals::default(),
310 weekly: Totals::default(),
311 });
312 if in_month {
313 entry.month.add(row, cost);
314 }
315 if in_week {
316 entry.weekly.add(row, cost);
317 }
318 if in_five {
319 entry.five_hour.add(row, cost);
320 }
321 }
322
323 report.models = by_model.into_values().collect();
324 report.models.sort_by(|a, b| {
325 b.month
326 .cost
327 .partial_cmp(&a.month.cost)
328 .unwrap_or(std::cmp::Ordering::Equal)
329 .then_with(|| a.id.cmp(&b.id))
330 });
331 report
332}
333
334#[cfg(test)]
335mod tests {
336 use super::*;
337 use crate::ocuse::db::Row;
338
339 fn row(at_s: i64, model: &str, cost: f64) -> Row {
340 Row {
341 at_ms: at_s * 1000,
342 provider: "opencode-go".into(),
343 model: model.into(),
344 cost_usd: cost,
345 ..Default::default()
346 }
347 }
348
349 fn meter(status: &str, percent: f64, resets_at: &str) -> crate::ocuse::api::Meter {
351 crate::ocuse::api::Meter {
352 status: status.into(),
353 percent,
354 resets_at: Some(resets_at.into()),
355 }
356 }
357
358 fn iso(secs: i64) -> String {
361 let rem = secs.rem_euclid(86_400);
362 let (y, m, d) = civil(secs - rem);
363 format!(
364 "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.000Z",
365 rem / 3600,
366 (rem % 3600) / 60,
367 rem % 60
368 )
369 }
370
371 #[test]
372 fn civil_helpers_round_trip() {
373 let secs = days_from_civil(2026, 9, 27) * 86_400;
375 assert_eq!(civil(secs), (2026, 9, 27));
376 assert_eq!(day_of_month(secs), 27);
377 }
378
379 #[test]
380 fn next_month_keeps_the_day_and_wraps_the_year() {
381 let dec15 = days_from_civil(2026, 12, 15) * 86_400_000;
383 assert_eq!(civil(next_month(dec15) / 1000), (2027, 1, 15));
384 let jan1 = days_from_civil(2026, 1, 1) * 86_400_000;
386 assert_eq!(civil(next_month(jan1) / 1000), (2026, 2, 1));
387 let jan31 = days_from_civil(2026, 1, 31) * 86_400_000;
389 assert_eq!(civil(next_month(jan31) / 1000), (2026, 2, 28));
390 }
391
392 #[test]
393 fn prev_month_inverts_next_month_and_keeps_the_clock() {
394 let reset = 1_794_604_475_000; let start = prev_month(reset);
397 assert_eq!(civil(start / 1000), (2026, 10, 13));
398 assert_eq!(start % 86_400_000, reset % 86_400_000, "time of day kept");
399 assert_eq!(civil(next_month(start) / 1000), (2026, 11, 13));
401 let dec13 = days_from_civil(2026, 12, 13) * 86_400_000;
403 assert_eq!(civil(prev_month(dec13) / 1000), (2026, 11, 13));
404 let mar31 = days_from_civil(2026, 3, 31) * 86_400_000;
405 assert_eq!(civil(prev_month(mar31) / 1000), (2026, 2, 28));
406 }
407
408 #[test]
409 fn windows_are_rolling_and_the_month_is_inferred() {
410 let now = days_from_civil(2026, 9, 27) * 86_400 + 12 * 3600;
411 let rows = vec![
412 row(now - 60, "glm-5.3-flash", 1.0), row(now - 2 * 3600, "glm-5.3-flash", 2.0), row(now - 3 * 86_400, "kimi-k3", 4.0), row(now - 40 * 86_400, "glm-5.3-flash", 8.0), ];
417 let catalog = crate::ocuse::zen::catalog();
418 let report = build(
419 &rows,
420 &catalog,
421 crate::ocuse::zen::DEFAULT_PLAN,
422 now * 1000,
423 None,
424 None,
425 );
426 assert!(
427 report.month_inferred,
428 "anniversary inferred from the earliest row"
429 );
430 assert!((report.five_hour.cost - 3.0).abs() < 1e-9);
431 assert!((report.weekly.cost - 7.0).abs() < 1e-9);
432 assert!(
434 (report.month.cost - 7.0).abs() < 1e-9,
435 "month cost {}",
436 report.month.cost
437 );
438 let flash = report
439 .models
440 .iter()
441 .find(|m| m.id == "glm-5.3-flash")
442 .unwrap();
443 assert_eq!(flash.limit, Some(60.0));
444 assert!((flash.five_hour.cost - 3.0).abs() < 1e-9);
445 }
446
447 #[test]
453 fn the_accounts_bounds_cut_the_windows_when_it_answered() {
454 let now = days_from_civil(2026, 10, 19) * 86_400 + 12 * 3600; let week_reset = now + 6 * 86_400 + 12 * 3600; let five_reset = now + 3 * 3600;
457 let five_start = five_reset - FIVE_HOUR_SECS;
458 let rows = vec![
459 row(now - 6 * 86_400, "glm-5.3-flash", 9.0),
461 row(now - 3 * 3600, "glm-5.3-flash", 2.0),
464 row(five_start + 60, "glm-5.3-flash", 1.0),
466 ];
467 let account = crate::ocuse::api::Usage {
468 rolling: meter("ok", 6.0, &iso(five_reset)),
469 weekly: meter("ok", 3.0, &iso(week_reset)),
470 monthly: meter("ok", 51.0, &iso(now + 20 * 86_400)),
471 };
472 let report = build(
473 &rows,
474 &crate::ocuse::zen::catalog(),
475 crate::ocuse::zen::DEFAULT_PLAN,
476 now * 1000,
477 None,
478 Some(&account),
479 );
480 assert!(
483 (report.weekly.cost - 3.0).abs() < 1e-9,
484 "weekly {}",
485 report.weekly.cost
486 );
487 assert!(
488 (report.five_hour.cost - 1.0).abs() < 1e-9,
489 "5h {}",
490 report.five_hour.cost
491 );
492 let flash = report
494 .models
495 .iter()
496 .find(|m| m.id == "glm-5.3-flash")
497 .unwrap();
498 assert!((flash.weekly.cost - 3.0).abs() < 1e-9);
499 assert!((flash.five_hour.cost - 1.0).abs() < 1e-9);
500 assert!((report.month.cost - 12.0).abs() < 1e-9);
503 }
504
505 #[test]
506 fn models_sort_by_month_spend() {
507 let now = days_from_civil(2026, 9, 27) * 86_400;
508 let rows = vec![row(now - 60, "cheap", 0.1), row(now - 60, "pricey", 5.0)];
509 let report = build(
510 &rows,
511 &crate::ocuse::zen::catalog(),
512 crate::ocuse::zen::DEFAULT_PLAN,
513 now * 1000,
514 None,
515 None,
516 );
517 assert_eq!(report.models[0].id, "pricey");
518 }
519}