1use crate::cli::{Workspace, EXIT_ERROR, EXIT_FOUND, EXIT_NOT_FOUND};
2use anyhow::{Context, Result};
3use clap::Args;
4use rusqlite::OptionalExtension;
5
6#[derive(Args)]
7pub struct AggregateArgs {
8 #[arg(long, value_parser = ["date", "amount"])]
10 pub field: String,
11
12 #[arg(long, value_parser = ["min", "max", "count", "sum", "avg"])]
14 pub op: String,
15
16 #[arg(long)]
18 pub filter: Option<String>,
19
20 #[arg(long)]
22 pub after: Option<String>,
23
24 #[arg(long)]
26 pub before: Option<String>,
27
28 #[arg(long, value_delimiter = ',')]
30 pub ext: Vec<String>,
31
32 #[arg(long)]
34 pub path: Option<String>,
35
36 #[arg(long, short)]
38 pub root: Vec<String>,
39}
40
41pub async fn run(args: AggregateArgs) -> Result<i32> {
42 let ws = Workspace::new();
43 let conn = ws.open_index()?;
44
45 let roots = ws.roots(&args.root);
46 let root_paths: Vec<String> = roots
47 .iter()
48 .map(|p| p.to_string_lossy().to_string())
49 .collect();
50
51 let mut where_clauses = Vec::new();
53 let mut params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
54
55 if !root_paths.is_empty() {
57 let placeholders = root_paths.iter().map(|_| "?").collect::<Vec<_>>().join(",");
58 where_clauses.push(format!("source_path IN ({placeholders})"));
59 for rp in &root_paths {
60 params.push(Box::new(rp.clone()));
61 }
62 }
63
64 if let Some(filter) = &args.filter {
66 if filter.starts_with("kind=") {
67 let kind = filter.strip_prefix("kind=").unwrap_or(filter);
68 match kind {
69 "warranty" | "receipt" | "invoice" | "contract" => {
70 where_clauses.push("json_extract(metadata, '$.kind') = ?".to_string());
71 params.push(Box::new(kind.to_string()));
72 }
73 _ => {
74 eprintln!("invalid kind filter: {kind} (must be warranty, receipt, invoice, or contract)");
75 return Ok(EXIT_ERROR);
76 }
77 }
78 } else {
79 eprintln!("invalid filter format: {filter} (expected kind=...)");
80 return Ok(EXIT_ERROR);
81 }
82 }
83
84 if let Some(after) = &args.after {
86 where_clauses.push("mtime >= ?".to_string());
87 params.push(Box::new(parse_date_to_millis(after)?));
88 }
89 if let Some(before) = &args.before {
90 where_clauses.push("mtime <= ?".to_string());
91 params.push(Box::new(parse_date_to_millis(before)?));
92 }
93
94 if !args.ext.is_empty() {
96 let _placeholders = args.ext.iter().map(|_| "?").collect::<Vec<_>>().join(",");
97 where_clauses.push("path LIKE ?".to_string());
98 for ext in &args.ext {
99 params.push(Box::new(format!("%.{ext}")));
100 }
101 }
102
103 if let Some(path_substr) = &args.path {
105 where_clauses.push("path LIKE ?".to_string());
106 params.push(Box::new(format!("%{path_substr}%")));
107 }
108
109 let where_sql = if where_clauses.is_empty() {
110 String::new()
111 } else {
112 format!("WHERE {}", where_clauses.join(" AND "))
113 };
114
115 let (query, output_format) = match (args.field.as_str(), args.op.as_str()) {
117 ("date", "min") => (
118 format!(
119 "SELECT MIN(json_extract(metadata, '$.dates[0]')) FROM chunks {where_sql}"
120 ),
121 "date",
122 ),
123 ("date", "max") => (
124 format!(
125 "SELECT MAX(json_extract(metadata, '$.dates[0]')) FROM chunks {where_sql}"
126 ),
127 "date",
128 ),
129 ("date", "count") => (
130 format!(
131 "SELECT COUNT(*) FROM chunks {where_sql} AND json_type(metadata, '$.dates') = 'array' AND json_array_length(metadata, '$.dates') > 0"
132 ),
133 "count",
134 ),
135 ("amount", "sum") => (
136 format!(
137 "SELECT SUM(json_extract(value, '$.amount')) FROM chunks {where_sql}, json_each(metadata, '$.amounts')"
138 ),
139 "amount",
140 ),
141 ("amount", "avg") => (
142 format!(
143 "SELECT AVG(json_extract(value, '$.amount')) FROM chunks {where_sql}, json_each(metadata, '$.amounts')"
144 ),
145 "amount",
146 ),
147 ("amount", "count") => (
148 format!(
149 "SELECT COUNT(*) FROM chunks {where_sql} AND json_type(metadata, '$.amounts') = 'array' AND json_array_length(metadata, '$.amounts') > 0"
150 ),
151 "count",
152 ),
153 _ => {
154 eprintln!("invalid field/op combination: {}/{}", args.field, args.op);
155 return Ok(EXIT_ERROR);
156 }
157 };
158
159 let param_refs: Vec<&dyn rusqlite::ToSql> = params.iter().map(|p| p.as_ref()).collect();
161
162 let result: Option<String> = conn
163 .inner()
164 .query_row(
165 &query,
166 rusqlite::params_from_iter(param_refs.iter()),
167 |row| row.get(0),
168 )
169 .optional()?;
170
171 match result {
172 Some(val) => {
173 match output_format {
174 "date" => println!("{}", val),
175 "amount" => {
176 if let Ok(num) = val.parse::<f64>() {
177 println!("{:.2}", num);
178 } else {
179 println!("{}", val);
180 }
181 }
182 "count" => println!("{}", val),
183 _ => println!("{}", val),
184 }
185 Ok(EXIT_FOUND)
186 }
187 None => {
188 eprintln!("no matching chunks");
189 Ok(EXIT_NOT_FOUND)
190 }
191 }
192}
193
194fn parse_date_to_millis(date: &str) -> Result<i64> {
195 let naive = chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d")
197 .with_context(|| format!("invalid date format: {date} (expected YYYY-MM-DD)"))?;
198 let datetime = naive.and_hms_opt(0, 0, 0).unwrap();
199 let timestamp = datetime.and_utc().timestamp_millis();
200 Ok(timestamp)
201}