1
//! `update-transaction-logical` keeps the stored post date unless `:date` is given.
2

            
3
use chrono::{DateTime, TimeZone, Utc};
4
use sqlx::PgPool;
5
use uuid::Uuid;
6

            
7
use super::run_logical::run_update_transaction_logical;
8
use super::tests_logical_update::{seed_account, seed_commodity, seed_transaction, seed_user};
9

            
10
#[sqlx::test(migrator = "server::db::MIGRATOR")]
11
async fn logical_update_preserves_post_date_without_date(pool: PgPool) -> anyhow::Result<()> {
12
    let _guard = server::db::install_test_pool(pool.clone());
13
    let user_id = Uuid::new_v4();
14
    seed_user(&pool, user_id).await?;
15
    let usd_id = seed_commodity(user_id, "USD", "US Dollar").await?;
16
    let a_id = seed_account(user_id, "Assets").await?;
17
    let b_id = seed_account(user_id, "Expenses").await?;
18
    let c_id = seed_account(user_id, "Income").await?;
19

            
20
    let original = Utc.with_ymd_and_hms(2020, 1, 1, 0, 0, 0).single().unwrap();
21
    let tx_id = seed_transaction(user_id, a_id, b_id, usd_id, original).await?;
22

            
23
    // Split-only edit — no :date — must leave the stored post_date intact.
24
    let no_date_payload = format!(
25
        r#"(:transaction-id "{tx_id}"
26
           :splits ((:from "{a_id}" :to "{c_id}"
27
                     :from-commodity "{usd_id}" :to-commodity "{usd_id}"
28
                     :value 50)))"#
29
    );
30
    run_update_transaction_logical(user_id, Some(no_date_payload))
31
        .await
32
        .map_err(|e| anyhow::anyhow!("{e}"))?;
33

            
34
    let after_no_date =
35
        sqlx::query_scalar::<_, DateTime<Utc>>("SELECT post_date FROM transactions WHERE id = $1")
36
            .bind(tx_id)
37
            .fetch_one(&pool)
38
            .await?;
39
    assert_eq!(
40
        after_no_date, original,
41
        "a split-only edit must not rewrite post_date"
42
    );
43

            
44
    // Now supply :date — the stored post_date must change to it.
45
    let with_date_payload = format!(
46
        r#"(:transaction-id "{tx_id}"
47
           :date "2021-06-15"
48
           :splits ((:from "{a_id}" :to "{c_id}"
49
                     :from-commodity "{usd_id}" :to-commodity "{usd_id}"
50
                     :value 50)))"#
51
    );
52
    run_update_transaction_logical(user_id, Some(with_date_payload))
53
        .await
54
        .map_err(|e| anyhow::anyhow!("{e}"))?;
55

            
56
    let after_with_date =
57
        sqlx::query_scalar::<_, DateTime<Utc>>("SELECT post_date FROM transactions WHERE id = $1")
58
            .bind(tx_id)
59
            .fetch_one(&pool)
60
            .await?;
61
    let expected = Utc
62
        .with_ymd_and_hms(2021, 6, 15, 12, 0, 0)
63
        .single()
64
        .unwrap();
65
    assert_eq!(
66
        after_with_date, expected,
67
        "an explicit :date must rewrite post_date"
68
    );
69

            
70
    Ok(())
71
}