Lines
97.83 %
Functions
95.45 %
Branches
100 %
use super::account::{CreateAccount, GetBalance, SetAccountTag};
use super::account_merge::{MergeAccounts, PreviewMergeAccounts};
use super::commodity::CreateCommodity;
use super::transaction::CreateTransaction;
use super::{CmdError, CmdResult, FinanceEntity};
use crate::{db::install_test_pool, user::User};
use chrono::Utc;
use finance::{account::Account, split::Split};
use num_rational::Rational64;
use sqlx::PgPool;
use supp_macro::local_db_sqlx_test;
use tokio::sync::OnceCell;
use uuid::Uuid;
mod balances;
mod gone;
mod kept;
mod moves;
mod previews;
mod pure;
mod refusals;
static USER: OnceCell<User> = OnceCell::const_new();
async fn setup() {
USER.get_or_init(|| async { User { id: Uuid::new_v4() } })
.await;
}
type SplitFacts = (
Uuid,
Option<bool>,
Option<chrono::DateTime<Utc>>,
Option<Uuid>,
);
struct Fixture {
user: &'static User,
commodity: Uuid,
async fn fixture() -> anyhow::Result<Fixture> {
let user = USER.get().ok_or_else(|| anyhow::anyhow!("no user"))?;
user.commit().await?;
let Some(CmdResult::String(id)) = CreateCommodity::new()
.symbol("TST".to_string())
.name("Test".to_string())
.user_id(user.id)
.run()
.await?
else {
anyhow::bail!("commodity");
};
Ok(Fixture {
user,
commodity: Uuid::parse_str(&id)?,
})
impl Fixture {
async fn account(&self, name: &str, parent: Option<Uuid>) -> anyhow::Result<Uuid> {
let mut cmd = CreateAccount::new()
.name(name.to_string())
.user_id(self.user.id);
if let Some(parent) = parent {
cmd = cmd.parent(parent);
match cmd.run().await? {
Some(CmdResult::Entity(FinanceEntity::Account(account))) => Ok(account.id),
other => anyhow::bail!("unexpected CreateAccount result {other:?}"),
async fn transfer(&self, from: Uuid, to: Uuid, amount: i64) -> anyhow::Result<Uuid> {
let tx_id = Uuid::new_v4();
let splits = [(from, -amount), (to, amount)]
.into_iter()
.map(|(account_id, value_num)| {
FinanceEntity::Split(Split {
id: Uuid::new_v4(),
tx_id,
account_id,
commodity_id: self.commodity,
value_num,
value_denom: 1,
reconcile_state: None,
reconcile_date: None,
lot_id: None,
.collect();
let now = Utc::now();
CreateTransaction::new()
.user_id(self.user.id)
.splits(splits)
.id(tx_id)
.post_date(now)
.enter_date(now)
.await?;
Ok(tx_id)
async fn merge(&self, into: Uuid, from: Uuid) -> Result<Option<CmdResult>, CmdError> {
MergeAccounts::new()
.into(into)
.from(from)
.await
async fn tag(&self, account: Uuid, name: &str, value: &str) -> anyhow::Result<()> {
SetAccountTag::new()
.account_id(account)
.tag_name(name.to_string())
.tag_value(value.to_string())
Ok(())
async fn tags(&self, account: Uuid) -> anyhow::Result<Vec<(String, String)>> {
let mut pairs: Vec<_> = self
.user
.get_account_tags(&Account {
id: account,
parent: None,
.map(|tag| (tag.tag_name, tag.tag_value))
pairs.sort();
Ok(pairs)
async fn balance(&self, account: Uuid) -> anyhow::Result<Rational64> {
match GetBalance::new()
{
Some(CmdResult::Rational(balance)) => Ok(balance),
other => anyhow::bail!("unexpected GetBalance result {other:?}"),
async fn split_count(&self, account: Uuid) -> anyhow::Result<i64> {
self.referencing("splits", "account_id", account).await
async fn preview(&self, into: Uuid, from: Uuid) -> Result<Option<CmdResult>, CmdError> {
PreviewMergeAccounts::new()
/// `(split id, reconcile state, reconcile date, lot)` of the account's
/// splits, sorted.
async fn split_facts(&self, account: Uuid) -> anyhow::Result<Vec<SplitFacts>> {
let mut conn = self.user.get_connection().await?;
let mut facts: Vec<SplitFacts> = sqlx::query_as(
"SELECT id, reconcile_state, reconcile_date, lot_id FROM splits WHERE account_id = $1",
)
.bind(account)
.fetch_all(&mut *conn)
facts.sort_by_key(|fact| fact.0);
Ok(facts)
async fn exists(&self, account: Uuid) -> anyhow::Result<bool> {
Ok(sqlx::query("SELECT 1 FROM accounts WHERE id = $1")
.fetch_optional(&mut *conn)
.is_some())
/// How many rows of `table` reference `account` through `key`.
async fn referencing(
&self,
table: &'static str,
key: &'static str,
account: Uuid,
) -> anyhow::Result<i64> {
let query = format!("SELECT count(*) FROM {table} WHERE {key} = $1");
Ok(sqlx::query_scalar(sqlx::AssertSqlSafe(query))
.fetch_one(&mut *conn)
.await?)
async fn execute(&self, sql: &'static str, ids: &[Uuid]) -> anyhow::Result<()> {
let mut query = sqlx::query(sql);
for id in ids {
query = query.bind(*id);
query.execute(&mut *conn).await?;
async fn add_lot(&self, account: Uuid) -> anyhow::Result<()> {
self.execute(
"INSERT INTO lots (id, account_id, is_closed) VALUES (gen_random_uuid(), $1, 0)",
&[account],
async fn add_budget(&self) -> anyhow::Result<Uuid> {
let budget = Uuid::new_v4();
"INSERT INTO budgets (id, periods) VALUES ($1, 12)",
&[budget],
Ok(budget)
async fn add_budget_amount(&self, budget: Uuid, account: Uuid) -> anyhow::Result<()> {
"INSERT INTO budget_amounts (budget_id, account_id, period_num, amount_num, amount_denom)
VALUES ($1, $2, 1, 100, 1)",
&[budget, account],
async fn add_book(&self, root: Uuid) -> anyhow::Result<()> {
"INSERT INTO books (id, root_account_id) VALUES (gen_random_uuid(), $1)",
&[root],
fn pair(name: &str, value: &str) -> (String, String) {
(name.to_string(), value.to_string())
fn refusal(result: Result<Option<CmdResult>, CmdError>) -> String {
match result {
Err(CmdError::Refused(message) | CmdError::NotFound(message)) => message,
other => format!("not a refusal: {other:?}"),