1use cli_core::{CliRunnable, CommandError};
2use server::command::data_findings::DataFinding;
3use server::command::{Argument, CmdResult, FinanceEntity};
4use std::collections::HashMap;
5
6pub async fn run_and_print(
10 runnable: &dyn CliRunnable,
11 args: HashMap<&str, Argument>,
12) -> Result<(), CommandError> {
13 let args_ref: HashMap<&str, &Argument> = args.iter().map(|(k, v)| (*k, v)).collect();
14 let result = runnable.run(&args_ref).await?;
15 if let Some(r) = result {
16 print_result(r);
17 }
18 Ok(())
19}
20
21fn entity_identifier(entity: &FinanceEntity) -> String {
22 match entity {
23 FinanceEntity::Tag(t) => t.tag_value.clone(),
24 FinanceEntity::Commodity(c) => c.id.to_string(),
25 FinanceEntity::Account(a) => a.id.to_string(),
26 FinanceEntity::Transaction(t) => t.id.to_string(),
27 FinanceEntity::Split(s) => s.id.to_string(),
28 FinanceEntity::Price(p) => p.id.to_string(),
29 }
30}
31
32fn tag_fields(tags: &HashMap<String, FinanceEntity>) -> Vec<String> {
33 tags.iter()
34 .filter_map(|(k, v)| match v {
35 FinanceEntity::Tag(t) => Some(format!("{k}={}", t.tag_value)),
36 _ => None,
37 })
38 .collect()
39}
40
41fn finding_lines(findings: &[DataFinding]) -> Vec<String> {
42 if findings.is_empty() {
43 return vec!["no findings".to_string()];
44 }
45 let mut lines = Vec::new();
46 let mut current_kind: Option<&str> = None;
47 for finding in findings {
48 if current_kind != Some(finding.kind.as_str()) {
49 let count = findings.iter().filter(|f| f.kind == finding.kind).count();
50 lines.push(format!("{} ({count})", finding.kind));
51 current_kind = Some(finding.kind.as_str());
52 }
53 let subjects = finding
54 .subjects
55 .iter()
56 .map(ToString::to_string)
57 .collect::<Vec<_>>()
58 .join(",");
59 lines.push(format!(
60 " {}\t{subjects}\t{}\t{}",
61 finding.id,
62 finding.detail,
63 finding.created_at.to_rfc3339()
64 ));
65 }
66 lines
67}
68
69fn merged_line(into: sqlx::types::Uuid, moved: i64) -> String {
70 format!("{into}\t{moved}")
71}
72
73fn print_result(result: CmdResult) {
74 match result {
75 CmdResult::Lines(lines) => {
76 for line in lines {
77 println!("{line}");
78 }
79 }
80 CmdResult::String(s) => println!("{s}"),
81 CmdResult::Rational(r) => println!("{r}"),
82 CmdResult::Timezone(zone) => println!("{zone}"),
83 CmdResult::ScriptRun(run) => println!("{run}"),
84 CmdResult::Data(bytes) => {
85 use std::io::Write;
86 let _ = std::io::stdout().write_all(&bytes);
87 }
88 CmdResult::Entity(entity) => println!("{}", entity_identifier(&entity)),
89 CmdResult::Entities(entities) => {
90 for entity in entities {
91 println!("{}", entity_identifier(&entity));
92 }
93 }
94 CmdResult::MultiCurrencyBalance(items) => {
95 for (commodity, balance) in items {
96 println!("{balance} {}", commodity.id);
97 }
98 }
99 CmdResult::CommodityInfoList(items) => {
100 for info in items {
101 println!("{}\t{}\t{}", info.commodity_id, info.symbol, info.name);
102 }
103 }
104 CmdResult::SingleCommodities(held) => {
105 for (account, commodity) in held {
106 println!("{account}\t{commodity}");
107 }
108 }
109 CmdResult::Templates(templates) => {
110 for template in templates {
111 println!("{}\t{}", template.id, template.name.unwrap_or_default());
112 }
113 }
114 CmdResult::TaggedEntities { entities, .. } => {
115 for (entity, tags) in entities {
116 let name = entity_identifier(&entity);
117 let fields = tag_fields(&tags);
118 if fields.is_empty() {
119 println!("{name}");
120 } else {
121 println!("{name}\t{}", fields.join("\t"));
122 }
123 }
124 }
125 CmdResult::TaggedSplits { entities } => {
126 for (split, tags) in entities {
127 let fields: Vec<String> = tags
128 .iter()
129 .map(|t| format!("{}={}", t.tag_name, t.tag_value))
130 .collect();
131 if fields.is_empty() {
132 println!("{}", split.id);
133 } else {
134 println!("{}\t{}", split.id, fields.join("\t"));
135 }
136 }
137 }
138 CmdResult::TaggedTransactions { entities, .. } => {
139 for (entity, tags, amount) in entities {
140 let name = entity_identifier(&entity);
141 let mut fields = tag_fields(&tags);
142 if let Some(amount) = amount {
143 fields.push(format!("amount={amount}"));
144 }
145 if fields.is_empty() {
146 println!("{name}");
147 } else {
148 println!("{name}\t{}", fields.join("\t"));
149 }
150 }
151 }
152 CmdResult::Report(_) | CmdResult::Activity(_) | CmdResult::Breakdown(_) => {
153 eprintln!("(structured report; use `reports` subcommand for rendered output)");
154 }
155 CmdResult::Uuid(id) => println!("{id}"),
156 CmdResult::Bool(b) => println!("{b}"),
157 CmdResult::Count(n) => println!("{n}"),
158 CmdResult::Merged { into, moved } => println!("{}", merged_line(into, moved)),
159 CmdResult::DataFindings(findings) => {
160 for line in finding_lines(&findings) {
161 println!("{line}");
162 }
163 }
164 CmdResult::ConfigEntries(entries) => {
165 for (name, value) in entries {
166 println!("{name}\t{value}");
167 }
168 }
169 CmdResult::SshKeys(keys) => {
170 for k in keys {
171 let last_used = k
172 .last_used_at
173 .map_or_else(|| "never".to_string(), |d| d.to_rfc3339());
174 println!(
175 "{}\t{}\t{}\t{}\t{}",
176 k.fingerprint, k.key_type, k.annotation, k.created_at, last_used
177 );
178 }
179 }
180 }
181}
182
183#[cfg(test)]
184#[path = "dispatch_tests.rs"]
185mod tests;