Skip to main content

server/command/transaction/
read.rs

1//! Listing and reading transactions.
2
3use crate::command::connection;
4use finance::{tag::Tag, transaction::Transaction};
5use num_rational::Rational64;
6use sqlx::{
7    types::Uuid,
8    types::chrono::{DateTime, Utc},
9};
10use std::{collections::HashMap, fmt::Debug};
11use supp_macro::command;
12
13use crate::user::User;
14
15use crate::command::transaction_edit::transaction_prices;
16use crate::command::{CmdError, CmdResult, FinanceEntity, PaginationInfo};
17
18pub(super) struct SplitAmountRow {
19    pub(super) tx_id: Uuid,
20    pub(super) commodity_id: Uuid,
21    pub(super) value_num: i64,
22    pub(super) value_denom: i64,
23    pub(super) symbol: String,
24}
25
26/// Aggregate split values into per-commodity amounts per transaction: the
27/// positive side, or the signed sum of one account when the list is filtered.
28///
29/// Grouping is by commodity **identity**, not symbol — two distinct commodities
30/// that happen to share a `symbol` tag stay separate. The symbol is carried only
31/// for display. Returns a map from tx id to a formatted `"amt sym; amt sym"`
32/// display string, ordered by symbol then commodity id for determinism.
33pub(super) fn aggregate_split_amounts(rows: Vec<SplitAmountRow>) -> HashMap<Uuid, String> {
34    let mut tx_map: HashMap<Uuid, HashMap<Uuid, (String, Rational64)>> = HashMap::new();
35    for row in rows {
36        if row.value_denom == 0 {
37            continue;
38        }
39        let r = Rational64::new(row.value_num, row.value_denom);
40        let entry = tx_map
41            .entry(row.tx_id)
42            .or_default()
43            .entry(row.commodity_id)
44            .or_insert_with(|| (row.symbol, Rational64::from(0)));
45        entry.1 += r;
46    }
47    tx_map
48        .into_iter()
49        .map(|(tx_id, commodities)| {
50            let mut pairs: Vec<(Uuid, String, Rational64)> = commodities
51                .into_iter()
52                .map(|(commodity_id, (symbol, amount))| (commodity_id, symbol, amount))
53                .collect();
54            pairs.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)));
55            let formatted = pairs
56                .into_iter()
57                .map(|(_, symbol, amount)| format!("{} {}", format_split_amount(amount), symbol))
58                .collect::<Vec<_>>()
59                .join("; ");
60            (tx_id, formatted)
61        })
62        .collect()
63}
64
65fn format_split_amount(r: Rational64) -> String {
66    amount::display(*r.numer(), *r.denom())
67}
68
69/// Aggregate per-transaction amount summaries for the given ids in one query.
70async fn load_split_amounts(
71    conn: &mut sqlx::PgConnection,
72    tx_ids: &[Uuid],
73    account: Option<&Uuid>,
74) -> Result<HashMap<Uuid, String>, sqlx::Error> {
75    if tx_ids.is_empty() {
76        return Ok(HashMap::new());
77    }
78    let rows = sqlx::query_file!("sql/select/splits/for_list.sql", tx_ids, account)
79        .fetch_all(conn)
80        .await?
81        .into_iter()
82        .map(|r| SplitAmountRow {
83            tx_id: r.tx_id,
84            commodity_id: r.commodity_id,
85            value_num: r.value_num,
86            value_denom: r.value_denom,
87            symbol: r.symbol,
88        })
89        .collect();
90    Ok(aggregate_split_amounts(rows))
91}
92
93command! {
94    ListTransactions {
95        #[required]
96        user_id: Uuid,
97        #[optional]
98        account: Uuid,
99        #[optional]
100        limit: i64,
101        #[optional]
102        offset: i64,
103        #[optional]
104        date_from: DateTime<Utc>,
105        #[optional]
106        date_to: DateTime<Utc>,
107    } => {
108        let user = User { id: user_id };
109        let mut conn = connection(&user).await?;
110
111        let account_uuid = account.as_ref();
112        let effective_limit = limit.unwrap_or(20);
113        let effective_offset = offset.unwrap_or(0);
114        let date_from_ref = date_from.as_ref();
115        let date_to_ref = date_to.as_ref();
116
117        let count_result = sqlx::query_file!(
118            "sql/count/transactions/filtered.sql",
119            account_uuid,
120            date_from_ref,
121            date_to_ref
122        )
123        .fetch_one(&mut *conn)
124        .await?;
125
126        let total_count = count_result.count.unwrap_or(0);
127
128        let transactions = sqlx::query_file!(
129            "sql/select/transactions/paginated.sql",
130            account_uuid,
131            date_from_ref,
132            date_to_ref,
133            effective_limit,
134            effective_offset
135        )
136        .fetch_all(&mut *conn)
137        .await?;
138
139        let tx_ids: Vec<Uuid> = transactions.iter().map(|r| r.id).collect();
140        let split_amounts = load_split_amounts(&mut conn, &tx_ids, account_uuid).await?;
141
142        let mut tagged_transactions = Vec::new();
143        for tx_row in transactions {
144            let transaction = Transaction {
145                id: tx_row.id,
146                post_date: tx_row.post_date,
147                enter_date: tx_row.enter_date,
148            };
149
150            let tags: HashMap<String, FinanceEntity> =
151                sqlx::query_file!("sql/select/tags/by_transaction.sql", &transaction.id)
152                    .fetch_all(&mut *conn)
153                    .await?
154                    .into_iter()
155                    .map(|row| {
156                        (
157                            row.tag_name.clone(),
158                            FinanceEntity::Tag(Tag {
159                                id: row.id,
160                                tag_name: row.tag_name,
161                                tag_value: row.tag_value,
162                                description: row.description,
163                            }),
164                        )
165                    })
166                    .collect();
167
168            let amount = split_amounts.get(&transaction.id).cloned();
169            tagged_transactions.push((FinanceEntity::Transaction(transaction), tags, amount));
170        }
171
172        let pagination = PaginationInfo {
173            total_count,
174            limit: effective_limit,
175            offset: effective_offset,
176            has_more: effective_offset + (tagged_transactions.len() as i64) < total_count,
177        };
178
179        Ok(Some(CmdResult::TaggedTransactions {
180            entities: tagged_transactions,
181            pagination: Some(pagination),
182        }))
183    }
184}
185
186command! {
187    GetTransaction {
188        #[required]
189        user_id: Uuid,
190        #[required]
191        transaction_id: Uuid,
192    } => {
193        let user = User { id: user_id };
194        let mut conn = connection(&user).await?;
195
196        let tx_row = sqlx::query_file!("sql/select/transactions/by_id.sql", transaction_id)
197            .fetch_optional(&mut *conn)
198            .await?;
199
200        if let Some(tx_row) = tx_row {
201            let transaction = Transaction {
202                id: tx_row.id,
203                post_date: tx_row.post_date,
204                enter_date: tx_row.enter_date,
205            };
206
207            let tags: HashMap<String, FinanceEntity> =
208                sqlx::query_file!("sql/select/tags/by_transaction.sql", &transaction.id)
209                    .fetch_all(&mut *conn)
210                    .await?
211                    .into_iter()
212                    .map(|row| {
213                        (
214                            row.tag_name.clone(),
215                            FinanceEntity::Tag(Tag {
216                                id: row.id,
217                                tag_name: row.tag_name,
218                                tag_value: row.tag_value,
219                                description: row.description,
220                            }),
221                        )
222                    })
223                    .collect();
224
225            let amount = load_split_amounts(&mut conn, &[transaction.id], None)
226                .await?
227                .remove(&transaction.id);
228
229            Ok(Some(CmdResult::TaggedTransactions {
230                entities: vec![(FinanceEntity::Transaction(transaction), tags, amount)],
231                pagination: None,
232            }))
233        } else {
234            Ok(None)
235        }
236    }
237}
238
239command! {
240    GetTransactionDetail {
241        #[required]
242        user_id: Uuid,
243        #[required]
244        transaction_id: Uuid,
245    } => {
246        let user = User { id: user_id };
247        let mut conn = connection(&user).await?;
248
249        let tx_row = sqlx::query_file!("sql/select/transactions/by_id.sql", transaction_id)
250            .fetch_optional(&mut *conn)
251            .await?;
252
253        if let Some(tx_row) = tx_row {
254            let transaction = Transaction {
255                id: tx_row.id,
256                post_date: tx_row.post_date,
257                enter_date: tx_row.enter_date,
258            };
259
260            let tags: HashMap<String, FinanceEntity> =
261                sqlx::query_file!("sql/select/tags/by_transaction.sql", &transaction.id)
262                    .fetch_all(&mut *conn)
263                    .await?
264                    .into_iter()
265                    .map(|row| {
266                        (
267                            row.tag_name.clone(),
268                            FinanceEntity::Tag(Tag {
269                                id: row.id,
270                                tag_name: row.tag_name,
271                                tag_value: row.tag_value,
272                                description: row.description,
273                            }),
274                        )
275                    })
276                    .collect();
277
278            let split_entities: Vec<(FinanceEntity, HashMap<String, FinanceEntity>)> =
279                sqlx::query_file!("sql/select/splits/by_transaction.sql", transaction_id)
280                    .fetch_all(&mut *conn)
281                    .await?
282                    .into_iter()
283                    .map(|row| {
284                        (
285                            FinanceEntity::Split(finance::split::Split {
286                                id: row.id,
287                                tx_id: row.tx_id,
288                                account_id: row.account_id,
289                                commodity_id: row.commodity_id,
290                                value_num: row.value_num,
291                                value_denom: row.value_denom,
292                                reconcile_state: row.reconcile_state,
293                                reconcile_date: row.reconcile_date,
294                                lot_id: row.lot_id,
295                            }),
296                            HashMap::new(),
297                        )
298                    })
299                    .collect();
300
301            let price_entities: Vec<(FinanceEntity, HashMap<String, FinanceEntity>)> =
302                transaction_prices(&mut conn, transaction_id)
303                    .await?
304                    .into_iter()
305                    .map(|price| (FinanceEntity::Price(price), HashMap::new()))
306                    .collect();
307
308            let mut entities: Vec<(FinanceEntity, HashMap<String, FinanceEntity>)> =
309                vec![(FinanceEntity::Transaction(transaction), tags)];
310            entities.extend(split_entities);
311            entities.extend(price_entities);
312
313            Ok(Some(CmdResult::TaggedEntities {
314                entities,
315                pagination: None,
316            }))
317        } else {
318            Ok(None)
319        }
320    }
321}
322
323#[cfg(test)]
324#[path = "../transaction_tests/aggregate.rs"]
325mod aggregate_tests;