1
use super::*;
2
use crate::command::account::SetAccountTag;
3
use crate::command::account_tag::ClearAccountTag;
4
use crate::command::commodity_tag::ClearCommodityTag;
5
use crate::command::{CmdError, transaction::CreateTransaction};
6
use finance::{account::Account, commodity::Commodity};
7

            
8
3
async fn stored_pairs(fx: &Fixture) -> anyhow::Result<Vec<(String, String)>> {
9
3
    let mut pairs: Vec<_> = fx
10
3
        .user
11
3
        .list_tags()
12
3
        .await?
13
        .into_iter()
14
19
        .map(|t| (t.tag_name, t.tag_value))
15
19
        .filter(|(name, _)| !matches!(name.as_str(), "name" | "symbol"))
16
        .collect();
17
3
    pairs.sort();
18
3
    Ok(pairs)
19
3
}
20

            
21
4
fn padded(name: &str, value: &str) -> Tag {
22
4
    tag(name, value)
23
4
}
24

            
25
#[local_db_sqlx_test]
26
async fn create_transaction_stores_padded_tags_trimmed(pool: PgPool) -> anyhow::Result<()> {
27
    let fx = fixture().await?;
28
    let tx_id = Uuid::new_v4();
29
    let now = Utc::now();
30
    let first = fx.splits(tx_id, 10);
31
    let first_id = first_split_id(&first)?;
32
    CreateTransaction::new()
33
        .user_id(fx.user.id)
34
        .splits(first)
35
        .id(tx_id)
36
        .post_date(now)
37
        .enter_date(now)
38
        .tags(tag_map(&[(" cat ", "\tfood ")]))
39
        .split_tags(vec![(first_id, padded(" memo", "m "))])
40
        .run()
41
        .await?;
42
    assert_eq!(fx.tx_tags(tx_id).await?, vec![pair("cat", "food")]);
43
    assert_eq!(fx.split_tag_values(first_id).await?, vec!["m"]);
44
    assert_eq!(
45
        stored_pairs(&fx).await?,
46
        vec![pair("cat", "food"), pair("memo", "m")]
47
    );
48
}
49

            
50
#[local_db_sqlx_test]
51
async fn create_transaction_refuses_whitespace_only_tags(pool: PgPool) -> anyhow::Result<()> {
52
    let fx = fixture().await?;
53
    let tx_id = Uuid::new_v4();
54
    let now = Utc::now();
55
    for tags in [tag_map(&[("  ", "v")]), tag_map(&[("k", " \t")])] {
56
        let refused = CreateTransaction::new()
57
            .user_id(fx.user.id)
58
            .splits(fx.splits(tx_id, 10))
59
            .id(tx_id)
60
            .post_date(now)
61
            .enter_date(now)
62
            .tags(tags)
63
            .run()
64
            .await;
65
        assert!(matches!(refused, Err(CmdError::Args(_))));
66
    }
67
    assert!(fx.tx_tags(tx_id).await?.is_empty());
68
}
69

            
70
#[local_db_sqlx_test]
71
async fn update_transaction_stores_padded_tags_trimmed(pool: PgPool) -> anyhow::Result<()> {
72
    let fx = fixture().await?;
73
    let tx_id = fx.create_tx(None).await?;
74
    let split_id = fx.split_ids(tx_id).await?[0];
75
    UpdateTransaction::new()
76
        .user_id(fx.user.id)
77
        .transaction_id(tx_id)
78
        .tags(tag_map(&[(" cat ", " food ")]))
79
        .split_tags(vec![(split_id, padded(" memo ", " m "))])
80
        .run()
81
        .await?;
82
    assert_eq!(fx.tx_tags(tx_id).await?, vec![pair("cat", "food")]);
83
    assert_eq!(fx.split_tag_values(split_id).await?, vec!["m"]);
84
    assert_eq!(
85
        stored_pairs(&fx).await?,
86
        vec![pair("cat", "food"), pair("memo", "m")]
87
    );
88
}
89

            
90
#[local_db_sqlx_test]
91
async fn update_transaction_refuses_a_padded_note_name(pool: PgPool) -> anyhow::Result<()> {
92
    let fx = fixture().await?;
93
    let tx_id = fx.create_tx(None).await?;
94
    let refused = UpdateTransaction::new()
95
        .user_id(fx.user.id)
96
        .transaction_id(tx_id)
97
        .tags(tag_map(&[(" note ", "v")]))
98
        .run()
99
        .await;
100
    assert!(matches!(refused, Err(CmdError::Args(_))));
101
    assert!(fx.tx_tags(tx_id).await?.is_empty());
102
}
103

            
104
#[local_db_sqlx_test]
105
async fn set_tag_commands_store_trimmed_and_refuse_blank(pool: PgPool) -> anyhow::Result<()> {
106
    let fx = fixture().await?;
107
    let tx_id = fx.create_tx(None).await?;
108
    let split_id = fx.split_ids(tx_id).await?[0];
109
    SetTransactionTag::new()
110
        .user_id(fx.user.id)
111
        .transaction_id(tx_id)
112
        .tag_name(" a ".to_string())
113
        .tag_value(" 1 ".to_string())
114
        .run()
115
        .await?;
116
    SetSplitTag::new()
117
        .user_id(fx.user.id)
118
        .split_id(split_id)
119
        .tag_name(" b ".to_string())
120
        .tag_value(" 2 ".to_string())
121
        .run()
122
        .await?;
123
    SetAccountTag::new()
124
        .user_id(fx.user.id)
125
        .account_id(fx.accounts[0])
126
        .tag_name(" c ".to_string())
127
        .tag_value(" 3 ".to_string())
128
        .run()
129
        .await?;
130
    assert_eq!(fx.tx_tags(tx_id).await?, vec![pair("a", "1")]);
131
    assert_eq!(fx.split_tag_values(split_id).await?, vec!["2"]);
132
    let account = Account {
133
        id: fx.accounts[0],
134
        parent: None,
135
    };
136
    let account_tags = fx.user.get_account_tags(&account).await?;
137
    assert!(
138
        account_tags
139
            .iter()
140
2
            .any(|t| (&*t.tag_name, &*t.tag_value) == ("c", "3"))
141
    );
142

            
143
    for (name, value) in [("  ", "v"), ("k", " \t")] {
144
        let on_tx = SetTransactionTag::new()
145
            .user_id(fx.user.id)
146
            .transaction_id(tx_id)
147
            .tag_name(name.to_string())
148
            .tag_value(value.to_string())
149
            .run()
150
            .await;
151
        let on_split = SetSplitTag::new()
152
            .user_id(fx.user.id)
153
            .split_id(split_id)
154
            .tag_name(name.to_string())
155
            .tag_value(value.to_string())
156
            .run()
157
            .await;
158
        let on_account = SetAccountTag::new()
159
            .user_id(fx.user.id)
160
            .account_id(fx.accounts[0])
161
            .tag_name(name.to_string())
162
            .tag_value(value.to_string())
163
            .run()
164
            .await;
165
        assert!(on_tx.is_err() && on_split.is_err() && on_account.is_err());
166
    }
167
    assert!(
168
        stored_pairs(&fx)
169
            .await?
170
            .iter()
171
3
            .all(|(n, v)| n == n.trim() && v == v.trim() && !n.is_empty() && !v.is_empty())
172
    );
173
}
174

            
175
#[local_db_sqlx_test]
176
async fn tag_helpers_store_trimmed_and_refuse_whitespace_only(pool: PgPool) -> anyhow::Result<()> {
177
    let fx = fixture().await?;
178
    let tx_id = fx.create_tx(None).await?;
179
    let split_id = fx.split_ids(tx_id).await?[0];
180
    fx.user
181
        .create_transaction_tag(tx_id, " k ".to_string(), " v ".to_string(), None)
182
        .await?;
183
    fx.user
184
        .create_split_tag(split_id, " s ".to_string(), " w ".to_string(), None)
185
        .await?;
186
    let free = fx
187
        .user
188
        .create_tag(" f ".to_string(), " g ".to_string(), None)
189
        .await?;
190
    assert_eq!(fx.tx_tags(tx_id).await?, vec![pair("k", "v")]);
191
    assert_eq!(fx.split_tag_values(split_id).await?, vec!["w"]);
192
    assert_eq!(fx.user.stored_tag(free).await?.tag_name, "f");
193

            
194
    let blank = fx
195
        .user
196
        .create_tag("k".to_string(), "  ".to_string(), None)
197
        .await;
198
    assert!(blank.is_err());
199
}
200

            
201
#[local_db_sqlx_test]
202
async fn update_tag_stores_trimmed_and_refuses_whitespace_only(pool: PgPool) -> anyhow::Result<()> {
203
    let fx = fixture().await?;
204
    let id = fx
205
        .user
206
        .create_tag("a".to_string(), "b".to_string(), None)
207
        .await?;
208
    fx.user
209
        .rename_tag(id, " c ".to_string(), " d ".to_string(), None)
210
        .await?;
211
    let stored = fx.user.stored_tag(id).await?;
212
    assert_eq!(
213
        (stored.tag_name.as_str(), stored.tag_value.as_str()),
214
        ("c", "d")
215
    );
216

            
217
    let blank = fx
218
        .user
219
        .rename_tag(id, " ".to_string(), "d".to_string(), None)
220
        .await;
221
    assert!(blank.is_err());
222
    let blank_value = fx
223
        .user
224
        .rename_tag(id, "c".to_string(), "\t".to_string(), None)
225
        .await;
226
    assert!(blank_value.is_err());
227
    let stored = fx.user.stored_tag(id).await?;
228
    assert_eq!(
229
        (stored.tag_name.as_str(), stored.tag_value.as_str()),
230
        ("c", "d")
231
    );
232
}
233

            
234
#[local_db_sqlx_test]
235
async fn commodity_tags_store_trimmed_and_refuse_whitespace_only(
236
    pool: PgPool,
237
) -> anyhow::Result<()> {
238
    let fx = fixture().await?;
239
    let commodity = Commodity { id: fx.commodity };
240
    fx.user
241
        .set_commodity_tag(&commodity, &padded(" region ", " eu "))
242
        .await?;
243
    let stored = fx.user.get_commodity_tags(&commodity).await?;
244
    assert!(
245
        stored
246
            .iter()
247
3
            .any(|t| (&*t.tag_name, &*t.tag_value) == ("region", "eu"))
248
    );
249
    assert!(
250
        fx.user
251
            .set_commodity_tag(&commodity, &padded("region", "  "))
252
            .await
253
            .is_err()
254
    );
255
}
256

            
257
#[local_db_sqlx_test]
258
async fn created_account_stores_its_name_trimmed(pool: PgPool) -> anyhow::Result<()> {
259
    let fx = fixture().await?;
260
    let account = fx.user.create_account("  Bank \t", None).await?;
261
    let tags = fx.user.get_account_tags(&account).await?;
262
    assert!(
263
        tags.iter()
264
1
            .any(|t| (&*t.tag_name, &*t.tag_value) == ("name", "Bank"))
265
    );
266
    assert!(fx.user.create_account(" \t", None).await.is_err());
267
}
268

            
269
const PADDINGS: [(&str, &str); 2] = [("\t", "one"), ("\u{a0}", "two")];
270

            
271
5
async fn link_padded(
272
5
    pool: &PgPool,
273
5
    link_sql: &'static str,
274
5
    owner: Uuid,
275
5
    name: &str,
276
5
) -> anyhow::Result<()> {
277
5
    for (padding, value) in PADDINGS {
278
10
        let tag_id = Uuid::new_v4();
279
10
        sqlx::query("INSERT INTO tags (id, tag_name, tag_value) VALUES ($1, $2, $3)")
280
10
            .bind(tag_id)
281
10
            .bind(format!("{name}{padding}"))
282
10
            .bind(value)
283
10
            .execute(pool)
284
10
            .await?;
285
10
        sqlx::query(link_sql)
286
10
            .bind(owner)
287
10
            .bind(tag_id)
288
10
            .execute(pool)
289
10
            .await?;
290
    }
291
5
    Ok(())
292
5
}
293

            
294
3
fn values_named(tags: Vec<Tag>, name: &str) -> Vec<String> {
295
3
    tags.into_iter()
296
5
        .filter(|t| t.tag_name.trim() == name)
297
1
        .map(|t| t.tag_value)
298
        .collect()
299
3
}
300

            
301
#[local_db_sqlx_test]
302
async fn set_matches_a_stored_name_padded_with_any_whitespace(pool: PgPool) -> anyhow::Result<()> {
303
    let fx = fixture().await?;
304
    let account = Account {
305
        id: fx.accounts[0],
306
        parent: None,
307
    };
308
    link_padded(
309
        &pool,
310
        "INSERT INTO account_tags (account_id, tag_id) VALUES ($1, $2)",
311
        account.id,
312
        "kind",
313
    )
314
    .await?;
315
    fx.user
316
        .set_account_tag(&account, &tag("kind", "three"))
317
        .await?;
318
    let stored = fx.user.get_account_tags(&account).await?;
319
    assert_eq!(values_named(stored, "kind"), ["three"]);
320
}
321

            
322
#[local_db_sqlx_test]
323
async fn clear_matches_an_account_name_padded_with_any_whitespace(
324
    pool: PgPool,
325
) -> anyhow::Result<()> {
326
    let fx = fixture().await?;
327
    let account = Account {
328
        id: fx.accounts[0],
329
        parent: None,
330
    };
331
    link_padded(
332
        &pool,
333
        "INSERT INTO account_tags (account_id, tag_id) VALUES ($1, $2)",
334
        account.id,
335
        "kind",
336
    )
337
    .await?;
338
    ClearAccountTag::new()
339
        .user_id(fx.user.id)
340
        .account_id(account.id)
341
        .tag_name("kind".to_string())
342
        .run()
343
        .await?;
344
    let stored = fx.user.get_account_tags(&account).await?;
345
    assert!(values_named(stored, "kind").is_empty());
346
}
347

            
348
#[local_db_sqlx_test]
349
async fn clear_matches_a_commodity_name_padded_with_any_whitespace(
350
    pool: PgPool,
351
) -> anyhow::Result<()> {
352
    let fx = fixture().await?;
353
    let commodity = Commodity { id: fx.commodity };
354
    link_padded(
355
        &pool,
356
        "INSERT INTO commodity_tags (commodity_id, tag_id) VALUES ($1, $2)",
357
        commodity.id,
358
        "kind",
359
    )
360
    .await?;
361
    ClearCommodityTag::new()
362
        .user_id(fx.user.id)
363
        .commodity_id(commodity.id)
364
        .tag_name("kind".to_string())
365
        .run()
366
        .await?;
367
    let stored = fx.user.get_commodity_tags(&commodity).await?;
368
    assert!(values_named(stored, "kind").is_empty());
369
}
370

            
371
#[local_db_sqlx_test]
372
async fn set_tag_replaces_a_padded_stored_name_on_transaction_and_split(
373
    pool: PgPool,
374
) -> anyhow::Result<()> {
375
    let fx = fixture().await?;
376
    let tx_id = fx.create_tx(None).await?;
377
    let split_id = fx.split_ids(tx_id).await?[0];
378
    link_padded(
379
        &pool,
380
        "INSERT INTO transaction_tags (tx_id, tag_id) VALUES ($1, $2)",
381
        tx_id,
382
        "type",
383
    )
384
    .await?;
385
    link_padded(
386
        &pool,
387
        "INSERT INTO split_tags (split_id, tag_id) VALUES ($1, $2)",
388
        split_id,
389
        "memo",
390
    )
391
    .await?;
392

            
393
    fx.user
394
        .set_transaction_tag(tx_id, &tag("type", "new"))
395
        .await?;
396
    fx.user.set_split_tag(split_id, &tag("memo", "new")).await?;
397

            
398
    assert_eq!(fx.tx_tags(tx_id).await?, vec![pair("type", "new")]);
399
    assert_eq!(fx.split_tag_values(split_id).await?, vec!["new"]);
400
}