Lines
100 %
Functions
Branches
//! Fixtures of the `transaction-edit` tests.
use chrono::{DateTime, Utc};
use forms::escape_str;
use nomiscript::{Value, format_value};
use scripting::runtime::HostCondition;
use sqlx::PgPool;
use uuid::Uuid;
use super::test_seed::submit_create;
use super::test_seed::{seed_account, seed_commodity, seed_user};
pub(super) struct Fx {
pub(super) user: Uuid,
pub(super) usd: Uuid,
pub(super) eur: Uuid,
pub(super) cash: Uuid,
pub(super) food: Uuid,
}
pub(super) async fn fx(pool: &PgPool) -> anyhow::Result<Fx> {
let user = seed_user(pool).await?;
Ok(Fx {
user,
usd: seed_commodity(user, "USD").await?,
eur: seed_commodity(user, "EUR").await?,
cash: seed_account(user, "Cash").await?,
food: seed_account(user, "Food").await?,
})
pub(super) fn row(from: &str, to: &str, commodity: &str, value: &str, extra: &str) -> String {
let [from, to, commodity, value] = [from, to, commodity, value].map(escape_str);
format!("(:from {from} :to {to} :from-commodity {commodity} :value {value} {extra})")
impl Fx {
/// A `Cash` to `Food` row in `USD`.
pub(super) fn row(&self, value: &str, extra: &str) -> String {
let [cash, food, usd] = [self.cash, self.food, self.usd].map(|id| id.to_string());
row(&cash, &food, &usd, value, extra)
/// The same row converted to `EUR` at an amount of 9.
pub(super) fn fx_row(&self, value: &str) -> String {
self.row(
value,
&format!(":to-commodity \"{}\" :to-amount \"9\"", self.eur),
)
pub(super) async fn create(fx: &Fx, date: &str, rows: &[String]) -> anyhow::Result<Uuid> {
let payload = format!(
"(:date \"{date}\" :note \"n\" :splits ({}))",
rows.join(" ")
);
let id = submit_create(fx.user, &payload).await?;
Ok(Uuid::parse_str(&id)?)
pub(super) fn condition(err: &wasmtime::Error) -> HostCondition {
err.downcast_ref::<HostCondition>()
.cloned()
.expect("host condition")
pub(super) fn detail_text(condition: &HostCondition) -> String {
condition
.detail
.clone()
.map(|detail| format_value(&Value::from(detail)))
.unwrap_or_default()
pub(super) fn fields(detail: &str) -> Vec<String> {
detail
.split("(:FIELD \"")
.skip(1)
.filter_map(|part| part.split('"').next().map(str::to_string))
.collect()
pub(super) fn replace_once(text: &str, from: &str, to: &str) -> String {
assert_eq!(text.matches(from).count(), 1, "{from} in {text}");
text.replace(from, to)
pub(super) async fn price_dates(pool: &PgPool) -> anyhow::Result<Vec<DateTime<Utc>>> {
Ok(sqlx::query_scalar("SELECT price_date FROM prices")
.fetch_all(pool)
.await?)
pub(super) async fn set_price_date(pool: &PgPool, date: &str) -> anyhow::Result<()> {
sqlx::query("UPDATE prices SET price_date = $1::timestamptz")
.bind(date)
.execute(pool)
.await?;
Ok(())
pub(super) async fn post_date(pool: &PgPool, tx: Uuid) -> anyhow::Result<DateTime<Utc>> {
Ok(
sqlx::query_scalar("SELECT post_date FROM transactions WHERE id = $1")
.bind(tx)
.fetch_one(pool)
.await?,
pub(super) async fn split_accounts(pool: &PgPool, tx: Uuid) -> anyhow::Result<Vec<Uuid>> {
Ok(sqlx::query_scalar(
"SELECT account_id FROM splits WHERE tx_id = $1 ORDER BY value_num, account_id",
pub(super) async fn split_tag_pairs(pool: &PgPool, tx: Uuid) -> anyhow::Result<Vec<String>> {
"SELECT t.tag_name || '=' || t.tag_value FROM split_tags st \
JOIN tags t ON t.id = st.tag_id JOIN splits s ON s.id = st.split_id \
WHERE s.tx_id = $1 ORDER BY 1",
pub(super) async fn rename_symbol(pool: &PgPool, from: &str, to: &str) -> anyhow::Result<()> {
sqlx::query("UPDATE tags SET tag_value = $2 WHERE tag_name = 'symbol' AND tag_value = $1")
.bind(from)
.bind(to)
pub(super) async fn split_commodities(pool: &PgPool, tx: Uuid) -> anyhow::Result<Vec<Uuid>> {
"SELECT commodity_id FROM splits WHERE tx_id = $1 ORDER BY value_num, commodity_id",
/// The loaded payload as its head, split rows text and split-tags tail.
fn parts(payload: &str) -> (&str, &str, &str) {
let (head, rest) = payload.split_once(" :splits (").unwrap_or((payload, ""));
let (rows, tail) = rest.rsplit_once(") :split-tags ").unwrap_or((rest, "()"));
(head, rows, tail)
/// The loaded payload with its rows replaced by `rows` (each row text whole);
/// its split tags stay.
pub(super) fn with_rows(payload: &str, rows: &[String]) -> String {
let (head, _, tail) = parts(payload);
format!("{head} :splits ({}) :split-tags {tail}", rows.join(" "))
/// The row texts of a loaded payload.
pub(super) fn rows_of(payload: &str) -> Vec<String> {
let (_, body, _) = parts(payload);
body.split(" (:key ")
.enumerate()
.map(|(index, row)| match index {
0 => row.to_string(),
_ => format!("(:key {row}"),
/// The payload without its `:revision`, for comparing loads across edits.
pub(super) fn without_revision(payload: &str) -> String {
let start = payload.find(" :revision \"").unwrap_or_default();
let tail = &payload[start + 12..];
let end = tail.find('"').unwrap_or_default();
format!("{}{}", &payload[..start], &tail[end + 1..])
/// A loaded payload as it was emitted before UUID cells: names in the cells
/// and labelled hidden data. The fixture's entities are `Cash`, `Food`,
/// `USD` and `EUR`.
pub(super) fn legacy_loaded(payload: &str, fx: &Fx) -> String {
let names = [
(fx.cash, "Cash"),
(fx.food, "Food"),
(fx.usd, "USD"),
(fx.eur, "EUR"),
];
let name_of = |id: Uuid| names.iter().find(|(known, _)| *known == id).map(|e| e.1);
let hidden_id = |key: &str, text: &str| {
let start = format!(":{key} \\\"");
let at = text.find(&start)? + start.len();
Uuid::parse_str(text.get(at..at + 36)?).ok()
};
let labels = ["from-id", "to-id", "from-commodity-id", "to-commodity-id"].map(|key| {
hidden_id(key, payload)
.and_then(name_of)
});
let mut text = payload.to_string();
for (id, name) in names {
text = text.replace(&format!(" \"{id}\" :"), &format!(" \"{name}\" :"));
let [from, to, from_commodity, to_commodity] = labels;
replace_once(
&text,
" :value \\\"",
&format!(
" :from-label \\\"{from}\\\" :to-label \\\"{to}\\\" \
:from-commodity-label \\\"{from_commodity}\\\" \
:to-commodity-label \\\"{to_commodity}\\\" :value \\\""
),