Skip to main content

server/command/
split.rs

1use crate::command::connection;
2use finance::{split::Split, tag::Tag};
3use sqlx::types::Uuid;
4use std::fmt::Debug;
5use supp_macro::command;
6
7use super::{CmdError, CmdResult};
8use crate::split::{split_tags_of, tags_of_split};
9use crate::{db::DBError, error::ServerError, user::User};
10
11command! {
12    ListSplits {
13        #[required]
14        user_id: Uuid,
15        #[optional]
16        account: Uuid,
17        #[optional]
18        transaction: Uuid,
19    } => {
20        let user = User { id: user_id };
21        let mut conn = connection(&user).await?;
22
23        // Ensure at least one filter is provided
24        if account.is_none() && transaction.is_none() {
25            return Err(CmdError::Args(
26                "At least one filter (account or transaction) is required".to_string(),
27            ));
28        }
29
30        // Execute the appropriate query based on provided filters
31        let splits = match (account, transaction) {
32            (Some(account_id), Some(tx_id)) => {
33                // Filter by both account and transaction
34                sqlx::query_file_as!(
35                    Split,
36                    "sql/select/splits/by_account_and_transaction.sql",
37                    account_id,
38                    tx_id
39                )
40                .fetch_all(&mut *conn)
41                .await?
42            }
43            (Some(account_id), None) => {
44                // Filter by account only
45                sqlx::query_file_as!(
46                    Split,
47                    "sql/select/splits/by_account.sql",
48                    account_id
49                )
50                .fetch_all(&mut *conn)
51                .await?
52            }
53            (None, Some(tx_id)) => {
54                // Filter by transaction only
55                sqlx::query_file_as!(
56                    Split,
57                    "sql/select/splits/by_transaction.sql",
58                    tx_id
59                )
60                .fetch_all(&mut *conn)
61                .await?
62            }
63            _ => unreachable!(), // We already checked this case above
64        };
65
66        let mut all_tags = split_tags_of(&mut conn, &splits).await.map_err(db_error)?;
67        let tagged = splits
68            .into_iter()
69            .map(|split| {
70                let tags = all_tags.remove(&split.id).unwrap_or_default();
71                (split, tags)
72            })
73            .collect();
74
75        Ok(Some(CmdResult::TaggedSplits { entities: tagged }))
76    }
77}
78
79// Idempotent set: replace any existing (split, tag_name) link with
80// `tag_value`. Mirrors `SetAccountTag` so script-side `set-split-tag`
81// reads as the obvious analog.
82command! {
83    SetSplitTag {
84        #[required]
85        user_id: Uuid,
86        #[required]
87        split_id: Uuid,
88        #[required]
89        tag_name: String,
90        #[required]
91        tag_value: String,
92        #[optional]
93        description: String,
94    } => {
95        let user = User { id: user_id };
96        let desc = description.filter(|text| !text.trim().is_empty());
97        let tag = Tag {
98            id: Uuid::new_v4(),
99            tag_name,
100            tag_value,
101            description: desc,
102        };
103        user.set_split_tag(split_id, &tag)
104            .await
105            .map_err(map_server_err)?;
106        Ok(Some(CmdResult::String("ok".to_string())))
107    }
108}
109
110// Looks up a single tag value by name on a split. Returns the
111// `tag_value` as `CmdResult::String("")` when the tag isn't set —
112// keeps the wasm contract simple (`string` return type, no `Option`
113// boxing).
114command! {
115    GetSplitTag {
116        #[required]
117        user_id: Uuid,
118        #[required]
119        split_id: Uuid,
120        #[required]
121        tag_name: String,
122    } => {
123        let tags = held_split_tags(user_id, split_id).await?;
124        let value = tags
125            .into_iter()
126            .find(|t| t.tag_name == tag_name)
127            .map(|t| t.tag_value)
128            .unwrap_or_default();
129        Ok(Some(CmdResult::String(value)))
130    }
131}
132
133// Every value of one tag name on a split, ordered by value. Empty when
134// the name isn't set.
135command! {
136    GetSplitTagValues {
137        #[required]
138        user_id: Uuid,
139        #[required]
140        split_id: Uuid,
141        #[required]
142        tag_name: String,
143    } => {
144        let values = held_split_tags(user_id, split_id)
145            .await?
146            .into_iter()
147            .filter(|t| t.tag_name == tag_name)
148            .map(|t| t.tag_value)
149            .collect();
150        Ok(Some(CmdResult::Lines(values)))
151    }
152}
153
154async fn held_split_tags(user_id: Uuid, split_id: Uuid) -> Result<Vec<Tag>, CmdError> {
155    let user = User { id: user_id };
156    user.require_split(split_id).await.map_err(map_server_err)?;
157    let mut conn = user
158        .get_connection()
159        .await
160        .map_err(|err| map_server_err(err.into()))?;
161    tags_of_split(&mut conn, split_id).await.map_err(db_error)
162}
163
164fn db_error(err: sqlx::Error) -> CmdError {
165    map_server_err(ServerError::DB(DBError::Sqlx(err)))
166}
167
168/// Bridge from `ServerError` to the command-layer `CmdError`. The caller's
169/// own mistakes stay arguments or not-found; every other failure keeps its
170/// kind, so a busy lock or a database fault is not blamed on the caller.
171pub(crate) fn map_server_err(err: ServerError) -> CmdError {
172    match err {
173        ServerError::Creation => CmdError::Args("blank tag name or value".to_string()),
174        ServerError::DB(DBError::Sqlx(sqlx::Error::RowNotFound)) => {
175            CmdError::NotFound("Transaction or split not found".to_string())
176        }
177        err => {
178            tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
179            CmdError::Server(err)
180        }
181    }
182}
183
184#[cfg(test)]
185mod command_tests {
186    use super::*;
187    use crate::{
188        command::{
189            FinanceEntity, account::CreateAccount, commodity::CreateCommodity,
190            transaction::CreateTransaction,
191        },
192        db::install_test_pool,
193    };
194    use sqlx::{PgPool, types::chrono::Utc};
195    use supp_macro::local_db_sqlx_test;
196    use tokio::sync::OnceCell;
197
198    /// Context for keeping environment intact
199    static CONTEXT: OnceCell<()> = OnceCell::const_new();
200    static USER: OnceCell<User> = OnceCell::const_new();
201
202    async fn setup() {
203        CONTEXT
204            .get_or_init(|| async {
205                crate::telemetry::init_test_logging();
206            })
207            .await;
208        USER.get_or_init(|| async { User { id: Uuid::new_v4() } })
209            .await;
210    }
211
212    #[local_db_sqlx_test]
213    async fn test_list_splits(pool: PgPool) -> anyhow::Result<()> {
214        let user = USER.get().unwrap();
215        user.commit()
216            .await
217            .expect("Failed to commit user to database");
218
219        // First create a commodity
220        let commodity_result = CreateCommodity::new()
221            .symbol("TST".to_string())
222            .name("Test Commodity".to_string())
223            .user_id(user.id)
224            .run()
225            .await?;
226
227        // Get the commodity ID
228        let commodity_id = if let Some(CmdResult::String(id)) = commodity_result {
229            uuid::Uuid::parse_str(&id)?
230        } else {
231            panic!("Expected commodity ID string result");
232        };
233
234        // Create two accounts
235        let account1 = if let Some(CmdResult::Entity(FinanceEntity::Account(account))) =
236            CreateAccount::new()
237                .name("Account 1".to_string())
238                .user_id(user.id)
239                .run()
240                .await?
241        {
242            account
243        } else {
244            panic!("Expected account entity result");
245        };
246
247        let account2 = if let Some(CmdResult::Entity(FinanceEntity::Account(account))) =
248            CreateAccount::new()
249                .name("Account 2".to_string())
250                .user_id(user.id)
251                .run()
252                .await?
253        {
254            account
255        } else {
256            panic!("Expected account entity result");
257        };
258
259        // Create a transaction between the accounts
260        let tx_id = Uuid::new_v4();
261        let now = Utc::now();
262
263        let split1_id = Uuid::new_v4();
264        let split1 = Split {
265            id: split1_id,
266            tx_id,
267            account_id: account1.id,
268            commodity_id,
269            value_num: -100,
270            value_denom: 1,
271            reconcile_state: None,
272            reconcile_date: None,
273            lot_id: None,
274        };
275
276        let split2_id = Uuid::new_v4();
277        let split2 = Split {
278            id: split2_id,
279            tx_id,
280            account_id: account2.id,
281            commodity_id,
282            value_num: 100,
283            value_denom: 1,
284            reconcile_state: None,
285            reconcile_date: None,
286            lot_id: None,
287        };
288
289        let splits = vec![FinanceEntity::Split(split1), FinanceEntity::Split(split2)];
290        CreateTransaction::new()
291            .user_id(user.id)
292            .splits(splits)
293            .id(tx_id)
294            .post_date(now)
295            .enter_date(now)
296            .note("Test transaction".to_string())
297            .run()
298            .await?;
299
300        // List splits for account1
301        if let Some(CmdResult::TaggedSplits { entities }) = ListSplits::new()
302            .user_id(user.id)
303            .account(account1.id)
304            .run()
305            .await?
306        {
307            assert_eq!(entities.len(), 1, "Expected one split for account1");
308
309            let (split, _tags) = &entities[0];
310            assert_eq!(split.id, split1_id);
311            assert_eq!(split.account_id, account1.id);
312            assert_eq!(split.value_num, -100);
313            assert_eq!(split.value_denom, 1);
314        } else {
315            panic!("Expected TaggedSplits result");
316        }
317
318        // List splits for account2
319        if let Some(CmdResult::TaggedSplits { entities }) = ListSplits::new()
320            .user_id(user.id)
321            .account(account2.id)
322            .run()
323            .await?
324        {
325            assert_eq!(entities.len(), 1, "Expected one split for account2");
326
327            let (split, _tags) = &entities[0];
328            assert_eq!(split.id, split2_id);
329            assert_eq!(split.account_id, account2.id);
330            assert_eq!(split.value_num, 100);
331            assert_eq!(split.value_denom, 1);
332        } else {
333            panic!("Expected TaggedSplits result");
334        }
335
336        // List splits for non-existent account
337        if let Some(CmdResult::TaggedSplits { entities }) = ListSplits::new()
338            .user_id(user.id)
339            .account(Uuid::new_v4())
340            .run()
341            .await?
342        {
343            assert_eq!(
344                entities.len(),
345                0,
346                "Expected no splits for non-existent account"
347            );
348        } else {
349            panic!("Expected TaggedSplits result");
350        }
351    }
352
353    #[local_db_sqlx_test]
354    async fn test_list_splits_by_transaction(pool: PgPool) -> anyhow::Result<()> {
355        let user = USER.get().unwrap();
356        user.commit()
357            .await
358            .expect("Failed to commit user to database");
359
360        let commodity_result = CreateCommodity::new()
361            .symbol("TRX".to_string())
362            .name("Transaction Test Commodity".to_string())
363            .user_id(user.id)
364            .run()
365            .await?;
366
367        let commodity_id = if let Some(CmdResult::String(id)) = commodity_result {
368            uuid::Uuid::parse_str(&id)?
369        } else {
370            panic!("Expected commodity ID string result");
371        };
372
373        let account1 = if let Some(CmdResult::Entity(FinanceEntity::Account(account))) =
374            CreateAccount::new()
375                .name("TxTest Account 1".to_string())
376                .user_id(user.id)
377                .run()
378                .await?
379        {
380            account
381        } else {
382            panic!("Expected account entity result");
383        };
384
385        let account2 = if let Some(CmdResult::Entity(FinanceEntity::Account(account))) =
386            CreateAccount::new()
387                .name("TxTest Account 2".to_string())
388                .user_id(user.id)
389                .run()
390                .await?
391        {
392            account
393        } else {
394            panic!("Expected account entity result");
395        };
396
397        let tx_id = Uuid::new_v4();
398        let now = Utc::now();
399
400        let split1_id = Uuid::new_v4();
401        let split1 = Split {
402            id: split1_id,
403            tx_id,
404            account_id: account1.id,
405            commodity_id,
406            value_num: -200,
407            value_denom: 1,
408            reconcile_state: None,
409            reconcile_date: None,
410            lot_id: None,
411        };
412
413        let split2_id = Uuid::new_v4();
414        let split2 = Split {
415            id: split2_id,
416            tx_id,
417            account_id: account2.id,
418            commodity_id,
419            value_num: 200,
420            value_denom: 1,
421            reconcile_state: None,
422            reconcile_date: None,
423            lot_id: None,
424        };
425
426        let splits = vec![FinanceEntity::Split(split1), FinanceEntity::Split(split2)];
427        CreateTransaction::new()
428            .user_id(user.id)
429            .splits(splits)
430            .id(tx_id)
431            .post_date(now)
432            .enter_date(now)
433            .note("Transaction test".to_string())
434            .run()
435            .await?;
436
437        if let Some(CmdResult::TaggedSplits { entities }) = ListSplits::new()
438            .user_id(user.id)
439            .transaction(tx_id)
440            .run()
441            .await?
442        {
443            assert_eq!(entities.len(), 2, "Expected two splits for transaction");
444
445            let split_ids: Vec<Uuid> = entities.iter().map(|(s, _)| s.id).collect();
446
447            assert!(split_ids.contains(&split1_id));
448            assert!(split_ids.contains(&split2_id));
449        } else {
450            panic!("Expected TaggedSplits result");
451        }
452
453        if let Some(CmdResult::TaggedSplits { entities }) = ListSplits::new()
454            .user_id(user.id)
455            .transaction(Uuid::new_v4())
456            .run()
457            .await?
458        {
459            assert_eq!(
460                entities.len(),
461                0,
462                "Expected no splits for non-existent transaction"
463            );
464        } else {
465            panic!("Expected TaggedSplits result");
466        }
467    }
468}