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 mut ors = Vec::new();
97 for ext in &args.ext {
98 ors.push("lower(source_path) LIKE lower(?) ESCAPE '\\'".to_string());
99 params.push(Box::new(format!("%.{}", escape_like(ext))));
100 }
101 where_clauses.push(format!("({})", ors.join(" OR ")));
102 }
103
104 if let Some(path_substr) = &args.path {
106 where_clauses.push("path LIKE ?".to_string());
107 params.push(Box::new(format!("%{path_substr}%")));
108 }
109
110 let where_sql = if where_clauses.is_empty() {
111 String::new()
112 } else {
113 format!("WHERE {}", where_clauses.join(" AND "))
114 };
115
116 let (query, output_format) = match (args.field.as_str(), args.op.as_str()) {
118 ("date", "min") => (
119 format!(
120 "SELECT MIN(json_extract(metadata, '$.dates[0]')) FROM chunks {where_sql}"
121 ),
122 "date",
123 ),
124 ("date", "max") => (
125 format!(
126 "SELECT MAX(json_extract(metadata, '$.dates[0]')) FROM chunks {where_sql}"
127 ),
128 "date",
129 ),
130 ("date", "count") => (
131 format!(
132 "SELECT COUNT(*) FROM chunks {where_sql} AND json_type(metadata, '$.dates') = 'array' AND json_array_length(metadata, '$.dates') > 0"
133 ),
134 "count",
135 ),
136 ("amount", "sum") => (
137 format!(
138 "SELECT SUM(json_extract(value, '$.amount')) FROM chunks {where_sql}, json_each(metadata, '$.amounts')"
139 ),
140 "amount",
141 ),
142 ("amount", "avg") => (
143 format!(
144 "SELECT AVG(json_extract(value, '$.amount')) FROM chunks {where_sql}, json_each(metadata, '$.amounts')"
145 ),
146 "amount",
147 ),
148 ("amount", "count") => (
149 format!(
150 "SELECT COUNT(*) FROM chunks {where_sql} AND json_type(metadata, '$.amounts') = 'array' AND json_array_length(metadata, '$.amounts') > 0"
151 ),
152 "count",
153 ),
154 _ => {
155 eprintln!("invalid field/op combination: {}/{}", args.field, args.op);
156 return Ok(EXIT_ERROR);
157 }
158 };
159
160 let param_refs: Vec<&dyn rusqlite::ToSql> = params.iter().map(|p| p.as_ref()).collect();
162
163 let result: Option<String> = conn
164 .inner()
165 .query_row(
166 &query,
167 rusqlite::params_from_iter(param_refs.iter()),
168 |row| row.get(0),
169 )
170 .optional()?;
171
172 match result {
173 Some(val) => {
174 match output_format {
175 "date" => println!("{}", val),
176 "amount" => {
177 if let Ok(num) = val.parse::<f64>() {
178 println!("{:.2}", num);
179 } else {
180 println!("{}", val);
181 }
182 }
183 "count" => println!("{}", val),
184 _ => println!("{}", val),
185 }
186 Ok(EXIT_FOUND)
187 }
188 None => {
189 eprintln!("no matching chunks");
190 Ok(EXIT_NOT_FOUND)
191 }
192 }
193}
194
195fn parse_date_to_millis(date: &str) -> Result<i64> {
196 let naive = chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d")
198 .with_context(|| format!("invalid date format: {date} (expected YYYY-MM-DD)"))?;
199 let datetime = naive.and_hms_opt(0, 0, 0).unwrap();
200 let timestamp = datetime.and_utc().timestamp_millis();
201 Ok(timestamp)
202}
203
204fn escape_like(s: &str) -> String {
207 let mut out = String::with_capacity(s.len());
208 for c in s.chars() {
209 match c {
210 '%' | '_' | '\\' => {
211 out.push('\\');
212 out.push(c);
213 }
214 c => out.push(c),
215 }
216 }
217 out
218}