1
//! Detach operations delete the tag rows they leave unreferenced, and only
2
//! those.
3

            
4
use super::*;
5
use crate::script::load_transaction_state;
6
use crate::script_tags::write_one;
7

            
8
3
fn described(name: &str, value: &str, description: &str) -> HashMap<String, FinanceEntity> {
9
3
    let tag = Tag {
10
3
        description: Some(description.to_string()),
11
3
        ..tag(name, value)
12
3
    };
13
3
    HashMap::from([(format!("{name}={value}"), FinanceEntity::Tag(tag))])
14
3
}
15

            
16
impl Fixture {
17
4
    async fn descriptions(&self, value: &str) -> anyhow::Result<Vec<Option<String>>> {
18
4
        let mut conn = self.user.get_connection().await?;
19
4
        Ok(sqlx::query_file!("sql/select/tags/all.sql")
20
4
            .fetch_all(&mut *conn)
21
4
            .await?
22
            .into_iter()
23
20
            .filter(|row| row.tag_value == value)
24
3
            .map(|row| row.description)
25
            .collect())
26
4
    }
27

            
28
8
    async fn retag(&self, tx_id: Uuid, tags: HashMap<String, FinanceEntity>) -> anyhow::Result<()> {
29
8
        UpdateTransaction::new()
30
8
            .user_id(self.user.id)
31
8
            .transaction_id(tx_id)
32
8
            .tags(tags)
33
8
            .run()
34
8
            .await?;
35
8
        Ok(())
36
8
    }
37
}
38

            
39
#[local_db_sqlx_test]
40
async fn test_blank_description_after_unlink_stores_none(
41
    pool: PgPool,
42
) -> Result<(), anyhow::Error> {
43
    let fx = fixture().await?;
44
    let tx_id = fx.create_tx(None).await?;
45
    fx.retag(tx_id, described("trip", "kyoto", "old text"))
46
        .await?;
47
    fx.retag(tx_id, HashMap::new()).await?;
48
    assert!(fx.descriptions("kyoto").await?.is_empty());
49

            
50
    fx.retag(tx_id, tag_map(&[("trip", "kyoto")])).await?;
51
    assert_eq!(fx.descriptions("kyoto").await?, vec![None]);
52
}
53

            
54
#[local_db_sqlx_test]
55
async fn test_unlinked_tag_still_used_elsewhere_is_kept(pool: PgPool) -> Result<(), anyhow::Error> {
56
    let fx = fixture().await?;
57
    let [first, second] = [fx.create_tx(None).await?, fx.create_tx(None).await?];
58
    for tx_id in [first, second] {
59
        fx.retag(tx_id, described("trip", "osaka", "kept")).await?;
60
    }
61
    fx.retag(first, HashMap::new()).await?;
62
    assert_eq!(
63
        fx.descriptions("osaka").await?,
64
        vec![Some("kept".to_string())]
65
    );
66
}
67

            
68
#[local_db_sqlx_test]
69
async fn test_standalone_created_tag_survives_detaches(pool: PgPool) -> Result<(), anyhow::Error> {
70
    let fx = fixture().await?;
71
    fx.user
72
        .create_tag(
73
            "trip".to_string(),
74
            "nara".to_string(),
75
            Some("solo".to_string()),
76
        )
77
        .await?;
78
    let tx_id = fx.create_tx(Some("first note")).await?;
79
    fx.retag(tx_id, tag_map(&[("trip", "kobe")])).await?;
80
    fx.retag(tx_id, HashMap::new()).await?;
81
    assert_eq!(
82
        fx.descriptions("nara").await?,
83
        vec![Some("solo".to_string())]
84
    );
85
}
86

            
87
#[local_db_sqlx_test]
88
async fn test_replaced_splits_and_note_leave_no_orphans(pool: PgPool) -> Result<(), anyhow::Error> {
89
    let fx = fixture().await?;
90
    let tx_id = fx.create_tx(Some("old note")).await?;
91
    let split_id = fx.split_ids(tx_id).await?[0];
92
    UpdateTransaction::new()
93
        .user_id(fx.user.id)
94
        .transaction_id(tx_id)
95
        .split_tags(vec![(split_id, tag("memo", "split-memo"))])
96
        .run()
97
        .await?;
98
    UpdateTransaction::new()
99
        .user_id(fx.user.id)
100
        .transaction_id(tx_id)
101
        .splits(fx.splits(tx_id, 30))
102
        .note("new note".to_string())
103
        .run()
104
        .await?;
105
    assert_eq!(fx.tag_rows_with_value("split-memo").await?, 0);
106
    assert_eq!(fx.tag_rows_with_value("old note").await?, 0);
107
    assert_eq!(fx.tag_rows_with_value("new note").await?, 1);
108
}
109

            
110
#[local_db_sqlx_test]
111
async fn test_set_tag_replacing_a_value_deletes_the_old_row(
112
    pool: PgPool,
113
) -> Result<(), anyhow::Error> {
114
    let fx = fixture().await?;
115
    let tx_id = fx.create_tx(None).await?;
116
    let split_id = fx.split_ids(tx_id).await?[0];
117
    for value in ["v-old", "v-new"] {
118
        SetTransactionTag::new()
119
            .user_id(fx.user.id)
120
            .transaction_id(tx_id)
121
            .tag_name("zone".to_string())
122
            .tag_value(value.to_string())
123
            .run()
124
            .await?;
125
        SetSplitTag::new()
126
            .user_id(fx.user.id)
127
            .split_id(split_id)
128
            .tag_name("leg".to_string())
129
            .tag_value(format!("leg-{value}"))
130
            .run()
131
            .await?;
132
    }
133
    assert_eq!(fx.tag_rows_with_value("v-old").await?, 0);
134
    assert_eq!(fx.tag_rows_with_value("leg-v-old").await?, 0);
135
    assert_eq!(fx.tx_tags(tx_id).await?, vec![pair("zone", "v-new")]);
136
}
137

            
138
#[local_db_sqlx_test]
139
async fn test_script_detach_deletes_the_orphan(pool: PgPool) -> Result<(), anyhow::Error> {
140
    let fx = fixture().await?;
141
    let tx_id = fx.create_tx(None).await?;
142
    let split_id = fx.split_ids(tx_id).await?[0];
143
    UpdateTransaction::new()
144
        .user_id(fx.user.id)
145
        .transaction_id(tx_id)
146
        .tags(tag_map(&[("trip", "sapporo")]))
147
        .split_tags(vec![(split_id, tag("memo", "script-memo"))])
148
        .run()
149
        .await?;
150
    let mut state = load_transaction_state(fx.user.id, tx_id)
151
        .await?
152
        .ok_or_else(|| anyhow::anyhow!("not loaded"))?;
153
    let trip = state.transaction_tags.remove(0);
154
    state.deleted_transaction_tags.insert(trip.id);
155
    let (_, memo) = state.split_tags.remove(0);
156
    state.deleted_split_tags.insert((split_id, memo.id));
157

            
158
    write_one(fx.user, tx_id, &state).await?;
159
    assert_eq!(fx.tag_rows_with_value("sapporo").await?, 0);
160
    assert_eq!(fx.tag_rows_with_value("script-memo").await?, 0);
161
}