1
//! A stored account as the account-edit form holds it: its parent and every
2
//! tag, the `name` tag among them, with the revision digesting them.
3

            
4
use finance::tag::Tag;
5
use sqlx::{Connection, PgConnection, types::Uuid};
6

            
7
use crate::error::ServerError;
8
use crate::logical::hex_digest;
9
use crate::snapshot::db_error;
10
use crate::user::User;
11

            
12
/// The error text of an account edit whose expected revision no longer matches.
13
pub const STALE_ACCOUNT: &str = "the account changed since it was loaded; reload it";
14

            
15
#[derive(Debug, Clone)]
16
pub struct StoredAccount {
17
    pub parent: Option<Uuid>,
18
    /// Every tag of the account, sorted by name and value.
19
    pub tags: Vec<Tag>,
20
}
21

            
22
impl StoredAccount {
23
    /// Digest of the parent and the tags, the name tag included.
24
    #[must_use]
25
14071
    pub fn revision(&self) -> String {
26
33892
        let tags = self.tags.iter().map(|tag| {
27
33892
            format!(
28
                "tag {:?}",
29
33892
                (&tag.tag_name, &tag.tag_value, &tag.description)
30
            )
31
33892
        });
32
14071
        hex_digest(
33
14071
            std::iter::once(format!("parent {:?}", self.parent))
34
14071
                .chain(tags)
35
14071
                .collect(),
36
14071
        )
37
14071
    }
38
}
39

            
40
/// The account as stored, `None` when the user has no such account.
41
27962
pub(crate) async fn read_account(
42
27962
    conn: &mut PgConnection,
43
27962
    account_id: Uuid,
44
27962
) -> Result<Option<StoredAccount>, sqlx::Error> {
45
8167
    let Some(row) = sqlx::query_file!("sql/select/accounts/by_id.sql", account_id)
46
8167
        .fetch_optional(&mut *conn)
47
8167
        .await?
48
    else {
49
4
        return Ok(None);
50
    };
51
    let mut tags: Vec<Tag> =
52
8163
        sqlx::query_file_as!(Tag, "sql/select/tags/by_account.sql", account_id)
53
8163
            .fetch_all(conn)
54
8163
            .await?;
55
8252
    tags.sort_by(|a, b| (&a.tag_name, &a.tag_value).cmp(&(&b.tag_name, &b.tag_value)));
56
8163
    Ok(Some(StoredAccount {
57
8163
        parent: row.parent,
58
8163
        tags,
59
8163
    }))
60
8167
}
61

            
62
impl User {
63
    /// The account's parent and tags as of one instant; `None` when the user
64
    /// has no such account.
65
    ///
66
    /// # Errors
67
    /// The connection or a query failing.
68
18568
    pub async fn account_snapshot(
69
18568
        &self,
70
18568
        account_id: Uuid,
71
18568
    ) -> Result<Option<StoredAccount>, ServerError> {
72
5696
        let mut conn = self.get_connection().await?;
73
5696
        let mut tx = conn
74
5696
            .begin_with("BEGIN ISOLATION LEVEL REPEATABLE READ, READ ONLY")
75
5696
            .await
76
5696
            .map_err(db_error)?;
77
5696
        let account = read_account(&mut tx, account_id).await.map_err(db_error)?;
78
5696
        tx.rollback().await.map_err(db_error)?;
79
5696
        Ok(account)
80
5696
    }
81
}