Lines
98.68 %
Functions
95.65 %
Branches
100 %
use std::collections::HashMap;
use chrono::{DateTime, TimeZone, Utc};
use finance::{price::Price, split::Split};
use sqlx::types::Uuid;
use super::super::super::{CmdResult, commodity::CreateCommodity, transaction::CreateTransaction};
use super::super::super::{FinanceEntity, account::CreateAccount, account::SetAccountTag};
use crate::user::User;
pub fn at(y: i32, mo: u32, d: u32, h: u32, mi: u32, s: u32) -> DateTime<Utc> {
Utc.with_ymd_and_hms(y, mo, d, h, mi, s)
.single()
.unwrap_or(DateTime::<Utc>::MIN_UTC)
}
/// The one ledger every report fixture reads.
pub struct Ledger {
pub user: User,
commodities: HashMap<&'static str, Uuid>,
accounts: HashMap<&'static str, Uuid>,
pub type Leg = (&'static str, &'static str, i64, i64);
impl Ledger {
pub fn commodity(&self, symbol: &str) -> Uuid {
self.commodities.get(symbol).copied().unwrap_or_default()
pub fn account(&self, name: &str) -> Uuid {
self.accounts.get(name).copied().unwrap_or_default()
pub fn symbol(&self, id: Uuid) -> String {
self.commodities
.iter()
.find_map(|(symbol, cid)| (*cid == id).then(|| (*symbol).to_owned()))
.unwrap_or_else(|| "<unknown>".to_owned())
async fn commodity_new(&mut self, symbol: &'static str) -> anyhow::Result<()> {
let result = CreateCommodity::new()
.symbol(symbol.to_owned())
.name(symbol.to_owned())
.user_id(self.user.id)
.run()
.await?;
let Some(CmdResult::String(id)) = result else {
anyhow::bail!("commodity {symbol} not created");
};
self.commodities.insert(symbol, Uuid::parse_str(&id)?);
Ok(())
async fn account_new(
&mut self,
name: &'static str,
parent: Option<&str>,
kind: Option<&str>,
) -> anyhow::Result<()> {
let mut cmd = CreateAccount::new()
.name(name.to_owned())
.user_id(self.user.id);
if let Some(parent) = parent {
cmd = cmd.parent(self.account(parent));
let Some(CmdResult::Entity(FinanceEntity::Account(account))) = cmd.run().await? else {
anyhow::bail!("account {name} not created");
self.accounts.insert(name, account.id);
if let Some(kind) = kind {
SetAccountTag::new()
.account_id(account.id)
.tag_name("type".to_owned())
.tag_value(kind.to_owned())
/// Posts a balanced transaction of `legs` at `when`.
pub async fn post(
&self,
when: DateTime<Utc>,
legs: &[Leg],
) -> anyhow::Result<(Uuid, Vec<Uuid>)> {
let tx_id = Uuid::new_v4();
let splits: Vec<Split> = legs
.map(|&(account, commodity, value_num, value_denom)| Split {
id: Uuid::new_v4(),
tx_id,
account_id: self.account(account),
commodity_id: self.commodity(commodity),
value_num,
value_denom,
reconcile_state: None,
reconcile_date: None,
lot_id: None,
})
.collect();
let split_ids = splits.iter().map(|s| s.id).collect();
CreateTransaction::new()
.splits(splits.into_iter().map(FinanceEntity::Split).collect())
.id(tx_id)
.post_date(when)
.enter_date(when)
Ok((tx_id, split_ids))
async fn tag_tx(&self, tx_id: Uuid, name: &str, value: &str) -> anyhow::Result<()> {
self.user
.create_transaction_tag(tx_id, name.to_owned(), value.to_owned(), None)
async fn tag_split(&self, split_id: Uuid, value: &str) -> anyhow::Result<()> {
.create_split_tag(split_id, "category".to_owned(), value.to_owned(), None)
async fn price_eur_usd(&self, split_id: Uuid, when: DateTime<Utc>) -> anyhow::Result<()> {
let price = Price {
date: when,
commodity_id: self.commodity("EUR"),
currency_id: self.commodity("USD"),
commodity_split: Some(split_id),
currency_split: None,
value_num: 6,
value_denom: 5,
let mut conn = self.user.get_connection().await?;
sqlx::query_file!(
"sql/insert/prices/price.sql",
price.id,
price.commodity_id,
price.currency_id,
price.commodity_split,
price.currency_split,
price.date,
price.value_num,
price.value_denom
)
.execute(&mut *conn)
/// USD and EUR (priced EUR to USD at 6/5, per split), JPY (never priced),
/// three account levels, and dates on month, quarter and year edges.
pub async fn seed(user: User) -> anyhow::Result<Ledger> {
let mut l = Ledger {
user,
commodities: HashMap::new(),
accounts: HashMap::new(),
for symbol in ["USD", "EUR", "JPY"] {
l.commodity_new(symbol).await?;
let tree = [
("Assets", None, Some("asset")),
("Bank", Some("Assets"), Some("asset")),
("Checking", Some("Bank"), Some("asset")),
("Savings", Some("Bank"), Some("asset")),
("Income", None, Some("income")),
("Work", Some("Income"), Some("income")),
("Salary", Some("Work"), Some("income")),
("Expenses", None, Some("expense")),
("Living", Some("Expenses"), Some("expense")),
("Food", Some("Living"), Some("expense")),
("Rent", Some("Living"), Some("expense")),
("Leisure", Some("Expenses"), Some("expense")),
("Equity", None, None),
("Opening", Some("Equity"), None),
];
for (name, parent, kind) in tree {
l.account_new(name, parent, kind).await?;
l.post(
at(2024, 12, 31, 23, 59, 59),
&[("Checking", "USD", 1000, 1), ("Opening", "USD", -1000, 1)],
let (tx, _) = l
.post(
at(2025, 1, 1, 0, 0, 0),
&[("Checking", "USD", 3000, 1), ("Salary", "USD", -3000, 1)],
l.tag_tx(tx, "category", "salary").await?;
let (tx, splits) = l
at(2025, 1, 15, 12, 0, 0),
&[
("Food", "USD", 12050, 100),
("Checking", "USD", -12050, 100),
],
l.tag_tx(tx, "category", "groceries").await?;
l.tag_split(splits[0], "food").await?;
at(2025, 1, 31, 23, 59, 59),
&[("Rent", "USD", 800, 1), ("Checking", "USD", -800, 1)],
l.tag_tx(tx, "category", "housing").await?;
l.tag_tx(tx, "project", "home").await?;
at(2025, 2, 1, 0, 0, 0),
&[("Food", "USD", 45, 1), ("Checking", "USD", -45, 1)],
at(2025, 2, 5, 9, 0, 0),
&[("Savings", "USD", 500, 1), ("Checking", "USD", -500, 1)],
let when = at(2025, 2, 10, 12, 0, 0);
when,
&[("Leisure", "EUR", 60, 1), ("Savings", "EUR", -60, 1)],
l.tag_tx(tx, "category", "fun").await?;
for split in splits {
l.price_eur_usd(split, when).await?;
let (_, splits) = l
at(2025, 3, 31, 23, 59, 59),
&[("Food", "USD", 30, 1), ("Checking", "USD", -30, 1)],
at(2025, 4, 1, 0, 0, 0),
at(2025, 6, 15, 12, 0, 0),
at(2025, 12, 20, 12, 0, 0),
&[("Leisure", "JPY", 5000, 1), ("Savings", "JPY", -5000, 1)],
at(2026, 1, 1, 0, 0, 0),
&[("Food", "USD", 10, 1), ("Checking", "USD", -10, 1)],
l.tag_tx(tx, "category", "food").await?;
Ok(l)