1
//! The reference preflight: ambiguous and bare names are listed, clean data
2
//! passes and the tenant is left as it was.
3

            
4
use server::user::User;
5
use sqlx::PgPool;
6
use uuid::Uuid;
7

            
8
use super::test_edit::{Fx, create, fx};
9
use super::test_seed::{seed_account, seed_child_account};
10
use crate::references::{
11
    Source, Subject, TenantReport, check_references, check_tenant, load_sources as load,
12
};
13

            
14
const POSTED: &str = "2026-10-27T12:00:00Z";
15

            
16
6
async fn template(user: Uuid, source: &str) -> anyhow::Result<Uuid> {
17
6
    Ok(User { id: user }
18
6
        .create_template(source.to_string(), Some("t".to_string()))
19
6
        .await?)
20
6
}
21

            
22
5
fn reasons(report: &TenantReport) -> Vec<&str> {
23
7
    report.findings.iter().map(|f| f.reason.as_str()).collect()
24
5
}
25

            
26
3
fn source(code: &str) -> anyhow::Result<Source> {
27
3
    let dir = tempfile::tempdir()?;
28
3
    std::fs::write(dir.path().join("x.nms"), code)?;
29
3
    let (mut sources, findings) = load(dir.path());
30
3
    anyhow::ensure!(findings.is_empty(), "{findings:?}");
31
3
    sources.pop().ok_or_else(|| anyhow::anyhow!("no source"))
32
3
}
33

            
34
#[sqlx::test(migrator = "server::db::MIGRATOR")]
35
async fn clean_references_pass_and_are_counted(pool: PgPool) -> anyhow::Result<()> {
36
    let _guard = server::db::install_test_pool(pool.clone());
37
    let fx = fx(&pool).await?;
38
    let by_id = format!("(get-account \"{}\")", fx.cash);
39
    template(
40
        fx.user,
41
        &format!("{by_id}(get-account \"Food\")(get-commodity \"usd\")"),
42
    )
43
    .await?;
44

            
45
    let report = check_tenant(fx.user, &[]).await;
46

            
47
    assert_eq!(report.findings, []);
48
    assert_eq!(
49
        (
50
            report.coverage.templates,
51
            report.coverage.lookups,
52
            report.coverage.resolved
53
        ),
54
        (1, 3, 3)
55
    );
56
    Ok(())
57
}
58

            
59
#[sqlx::test(migrator = "server::db::MIGRATOR")]
60
async fn an_ambiguous_name_is_listed(pool: PgPool) -> anyhow::Result<()> {
61
    let _guard = server::db::install_test_pool(pool.clone());
62
    let fx = fx(&pool).await?;
63
    seed_account(fx.user, "Dup").await?;
64
    seed_account(fx.user, "Dup").await?;
65
    let id = template(fx.user, "(get-account \"Dup\")").await?;
66

            
67
    let report = check_tenant(fx.user, &[]).await;
68

            
69
    assert_eq!(
70
        reasons(&report),
71
        ["get-account: account 'Dup' is ambiguous (2 matches)"]
72
    );
73
    assert_eq!(
74
        report.findings[0].subject,
75
        Subject::Template(id, Some("t".to_string()))
76
    );
77
    assert_eq!(report.coverage.resolved, 0);
78
    Ok(())
79
}
80

            
81
#[sqlx::test(migrator = "server::db::MIGRATOR")]
82
async fn a_bare_name_is_listed_with_its_path(pool: PgPool) -> anyhow::Result<()> {
83
    let _guard = server::db::install_test_pool(pool.clone());
84
    let fx = fx(&pool).await?;
85
    seed_child_account(fx.user, "Cafe", fx.food).await?;
86
    template(
87
        fx.user,
88
        "(get-account \"Cafe\")(get-account \"Cafe\")(get-account \"Food:Cafe\")",
89
    )
90
    .await?;
91

            
92
    let report = check_tenant(fx.user, &[]).await;
93

            
94
    assert_eq!(
95
        reasons(&report),
96
        ["get-account: account 'Cafe' is a bare name: use the path 'Food:Cafe' or the id"]
97
    );
98
    assert_eq!((report.coverage.lookups, report.coverage.resolved), (3, 1));
99
    Ok(())
100
}
101

            
102
#[sqlx::test(migrator = "server::db::MIGRATOR")]
103
async fn an_unknown_commodity_and_a_broken_template_are_listed(pool: PgPool) -> anyhow::Result<()> {
104
    let _guard = server::db::install_test_pool(pool.clone());
105
    let fx = fx(&pool).await?;
106
    template(fx.user, "(get-commodity \"XXX\")").await?;
107
    template(fx.user, "(set-draft-note").await?;
108

            
109
    let report = check_tenant(fx.user, &[]).await;
110

            
111
    assert_eq!(report.findings.len(), 2, "{:?}", report.findings);
112
    assert!(
113
        reasons(&report)
114
            .iter()
115
2
            .any(|r| r.contains("commodity 'XXX' matches no entity"))
116
    );
117
    Ok(())
118
}
119

            
120
#[sqlx::test(migrator = "server::db::MIGRATOR")]
121
async fn a_source_is_judged_by_its_lookup_keys(pool: PgPool) -> anyhow::Result<()> {
122
    let _guard = server::db::install_test_pool(pool.clone());
123
    let fx = fx(&pool).await?;
124
    seed_child_account(fx.user, "Cafe", fx.food).await?;
125
    let declared = [source(
126
        "(string= (split-account-name s) \"Cafe\")(get-account \"Cash\")(get-account \"Food:Cafe\")\
127
         (get-commodity \"usd\")(get-account \"Cafe\")",
128
    )?];
129

            
130
    let report = check_tenant(fx.user, &declared).await;
131

            
132
    assert_eq!(
133
        reasons(&report),
134
        ["get-account: account 'Cafe' is a bare name: use the path 'Food:Cafe' or the id"]
135
    );
136
    assert_eq!(
137
        report.findings[0].subject,
138
        Subject::Source(declared[0].name.clone())
139
    );
140
    assert_eq!(
141
        (
142
            report.coverage.sources,
143
            report.coverage.lookups,
144
            report.coverage.resolved
145
        ),
146
        (1, 4, 3)
147
    );
148
    Ok(())
149
}
150

            
151
#[sqlx::test(migrator = "server::db::MIGRATOR")]
152
async fn a_run_over_the_directory_is_clean_or_fails(pool: PgPool) -> anyhow::Result<()> {
153
    let _guard = server::db::install_test_pool(pool.clone());
154
    let fx = fx(&pool).await?;
155
    let dir = tempfile::tempdir()?;
156
    std::fs::write(dir.path().join("ok.nms"), "(get-account \"Cash\")")?;
157
    let admin = Uuid::new_v4();
158

            
159
    let clean = check_references(admin, Some(dir.path())).await?;
160
    std::fs::write(dir.path().join("bad.nms"), "(get-account \"Nope\")")?;
161
    let failing = check_references(admin, Some(dir.path())).await?;
162

            
163
    assert_eq!(clean.findings().count(), 0);
164
    assert_eq!(clean.tenants.len(), 1);
165
    assert_eq!(clean.tenants[0].user, fx.user);
166
    assert!(clean.trigger_imports > 0);
167
1
    let found: Vec<_> = failing.findings().map(|f| f.reason.as_str()).collect();
168
    assert_eq!(
169
        found,
170
        ["get-account: account 'Nope' matches no entity of the user"]
171
    );
172
    Ok(())
173
}
174

            
175
2
async fn dump(pool: &PgPool) -> anyhow::Result<Vec<String>> {
176
2
    Ok(sqlx::query_scalar(
177
2
        "SELECT t::text FROM (SELECT 'tx' AS k, id::text FROM transactions \
178
2
         UNION ALL SELECT 'ac', id::text FROM accounts \
179
2
         UNION ALL SELECT 'tg', id::text || tag_value FROM tags \
180
2
         UNION ALL SELECT 'ar', id::text FROM artifacts) t ORDER BY 1",
181
2
    )
182
2
    .fetch_all(pool)
183
2
    .await?)
184
2
}
185

            
186
#[sqlx::test(migrator = "server::db::MIGRATOR")]
187
async fn a_logical_row_key_must_be_an_id(pool: PgPool) -> anyhow::Result<()> {
188
    let _guard = server::db::install_test_pool(pool.clone());
189
    let fx = fx(&pool).await?;
190
    let code = format!(
191
        "(get-account \"Cash\")(g '(:from \"{}\" :to \"Food\" :from-commodity \"USD\" \
192
         :to-commodity \"{}\"))",
193
        fx.cash, fx.eur
194
    );
195
    let declared = [source(&code)?];
196

            
197
    let report = check_tenant(fx.user, &declared).await;
198

            
199
    let mut found = reasons(&report);
200
    found.sort_unstable();
201
    assert_eq!(
202
        found,
203
        [
204
            format!("row key account 'Food' must be an id: use '{}'", fx.food),
205
            format!("row key commodity 'USD' must be an id: use '{}'", fx.usd),
206
        ]
207
    );
208
    assert_eq!(report.coverage.resolved, 3);
209
    Ok(())
210
}
211

            
212
1
async fn seeded(pool: &PgPool) -> anyhow::Result<Fx> {
213
1
    let fx = fx(pool).await?;
214
1
    create(&fx, POSTED, &[fx.row("10", "")]).await?;
215
1
    seed_child_account(fx.user, "Cafe", fx.food).await?;
216
1
    template(fx.user, "(get-account \"Cafe\")(get-commodity \"USD\")").await?;
217
1
    Ok(fx)
218
1
}
219

            
220
#[sqlx::test(migrator = "server::db::MIGRATOR")]
221
async fn the_tenant_is_unchanged(pool: PgPool) -> anyhow::Result<()> {
222
    let _guard = server::db::install_test_pool(pool.clone());
223
    let fx = seeded(&pool).await?;
224
    let before = dump(&pool).await?;
225

            
226
    let report = check_tenant(fx.user, &[source("(get-account \"Nope\")")?]).await;
227

            
228
    assert_eq!(report.findings.len(), 2);
229
    assert_eq!(dump(&pool).await?, before);
230
    assert!(before.len() > 4);
231
    Ok(())
232
}