1use std::collections::HashMap;
5
6use chrono::{DateTime, Utc};
7use finance::price::Price;
8use finance::split::Split;
9use finance::tag::Tag;
10use num_rational::Rational64;
11use sqlx::PgPool;
12use sqlx::types::Uuid;
13
14use crate::command::account::CreateAccount;
15use crate::command::commodity::CreateCommodity;
16use crate::command::transaction::CreateTransaction;
17use crate::command::{CmdError, CmdResult, FinanceEntity};
18use crate::logical::{LogicalSplit, lower_logical_transaction};
19
20pub const POST_DATE: &str = "2026-10-27T09:15:42.123456Z";
22pub const PRICE_DATE: &str = "2026-10-20T08:30:15.654321Z";
24pub const NOTE: &str = "first line\nsecond \"quoted\" back\\slash";
25pub const EDITED_NOTE: &str = "edited\nnote";
27
28pub struct Lossless {
29 pub user: Uuid,
30 pub transaction: Uuid,
31}
32
33fn tag(name: &str, value: &str, description: Option<&str>) -> Tag {
34 Tag {
35 id: Uuid::new_v4(),
36 tag_name: name.to_string(),
37 tag_value: value.to_string(),
38 description: description.map(str::to_string),
39 }
40}
41
42fn instant(text: &str) -> Result<DateTime<Utc>, CmdError> {
43 DateTime::parse_from_rfc3339(text)
44 .map(|date| date.with_timezone(&Utc))
45 .map_err(|err| CmdError::Args(err.to_string()))
46}
47
48pub(crate) async fn commodity(user: Uuid, symbol: &str) -> Result<Uuid, CmdError> {
49 let created = CreateCommodity::new()
50 .symbol(symbol.to_string())
51 .name(symbol.to_string())
52 .user_id(user)
53 .run()
54 .await?;
55 match created {
56 Some(CmdResult::String(id)) => {
57 Uuid::parse_str(&id).map_err(|err| CmdError::Args(err.to_string()))
58 }
59 other => Err(CmdError::Args(format!("commodity: {other:?}"))),
60 }
61}
62
63pub(crate) async fn account(user: Uuid, name: &str) -> Result<Uuid, CmdError> {
64 let created = CreateAccount::new()
65 .name(name.to_string())
66 .user_id(user)
67 .run()
68 .await?;
69 match created {
70 Some(CmdResult::Entity(FinanceEntity::Account(account))) => Ok(account.id),
71 other => Err(CmdError::Args(format!("account: {other:?}"))),
72 }
73}
74
75fn rows(cash: Uuid, food: Uuid, usd: Uuid, eur: Uuid) -> [LogicalSplit; 2] {
78 [
79 LogicalSplit {
80 from: cash,
81 to: food,
82 from_commodity: usd,
83 to_commodity: eur,
84 value: Rational64::new(10, 1),
85 to_amount: Some(Rational64::new(9, 1)),
86 from_reconcile: Some(false),
87 to_reconcile: Some(false),
88 },
89 LogicalSplit {
90 from: cash,
91 to: food,
92 from_commodity: usd,
93 to_commodity: usd,
94 value: Rational64::new(1, 3),
95 to_amount: None,
96 from_reconcile: None,
97 to_reconcile: None,
98 },
99 ]
100}
101
102fn split_entity(split: &crate::logical::PhysicalSplit, tx_id: Uuid) -> FinanceEntity {
103 FinanceEntity::Split(Split {
104 id: split.id,
105 tx_id,
106 account_id: split.account_id,
107 commodity_id: split.commodity_id,
108 value_num: *split.value.numer(),
109 value_denom: *split.value.denom(),
110 reconcile_state: split.reconcile_state,
111 reconcile_date: None,
112 lot_id: None,
113 })
114}
115
116fn transaction_tags(carriage_returns: bool) -> HashMap<String, FinanceEntity> {
117 [
118 tag("trip", "japan", Some("spring \"trip\" \\ notes\nday two")),
119 tag("project", "nomisync", Some("client forms")),
120 tag("cleared", "yes", None),
121 tag("windows", "crlf", Some("dos\r\nline\rmac end")),
122 tag("blank", "empty", Some("")),
123 ]
124 .into_iter()
125 .filter(|tag| carriage_returns || tag.tag_name != "windows")
126 .map(|tag| (tag.tag_name.clone(), FinanceEntity::Tag(tag)))
127 .collect()
128}
129
130pub async fn seed(pool: &PgPool) -> Result<Lossless, CmdError> {
137 let user = Uuid::new_v4();
138 sqlx::query_file!(
139 "sql/insert/users/fixture.sql",
140 user,
141 format!("u{user}"),
142 format!("{user}@test.com")
143 )
144 .execute(pool)
145 .await?;
146 let transaction = seed_transaction(user).await?;
147 Ok(Lossless { user, transaction })
148}
149
150pub async fn seed_transaction(user: Uuid) -> Result<Uuid, CmdError> {
155 seed_with(user, true).await
156}
157
158pub async fn seed_transaction_without_cr(user: Uuid) -> Result<Uuid, CmdError> {
164 seed_with(user, false).await
165}
166
167async fn seed_with(user: Uuid, carriage_returns: bool) -> Result<Uuid, CmdError> {
168 let (usd, eur) = (commodity(user, "USD").await?, commodity(user, "EUR").await?);
169 let (cash, food) = (account(user, "Cash").await?, account(user, "Food").await?);
170 let (splits, mut prices) = lower_logical_transaction(&rows(cash, food, usd, eur))?;
171 let price_date = instant(PRICE_DATE)?;
172 prices
173 .iter_mut()
174 .for_each(|price| price.date = Some(price_date));
175 let transaction = Uuid::new_v4();
176 let split_tags = splits
177 .iter()
178 .enumerate()
179 .map(|(index, split)| match index / 2 {
180 0 => (
181 split.id,
182 tag("memo", "m\\x", Some("split memo\nsecond line")),
183 ),
184 _ => (split.id, tag("category", "food", None)),
185 })
186 .collect();
187 let prices = prices
188 .into_iter()
189 .map(|price| {
190 FinanceEntity::Price(Price {
191 id: Uuid::new_v4(),
192 date: price_date,
193 commodity_id: price.commodity_id,
194 currency_id: price.currency_id,
195 commodity_split: Some(price.commodity_split),
196 currency_split: Some(price.currency_split),
197 value_num: price.value_num,
198 value_denom: price.value_denom,
199 })
200 })
201 .collect();
202 CreateTransaction::new()
203 .user_id(user)
204 .id(transaction)
205 .post_date(instant(POST_DATE)?)
206 .enter_date(Utc::now())
207 .splits(
208 splits
209 .iter()
210 .map(|s| split_entity(s, transaction))
211 .collect(),
212 )
213 .prices(prices)
214 .note(NOTE.to_string())
215 .tags(transaction_tags(carriage_returns))
216 .split_tags(split_tags)
217 .run()
218 .await?;
219 Ok(transaction)
220}
221
222pub async fn snapshot<'e>(
228 executor: impl sqlx::PgExecutor<'e>,
229 transaction: Uuid,
230) -> Result<Vec<String>, sqlx::Error> {
231 let facts = sqlx::query_file_scalar!("sql/select/transactions/snapshot.sql", transaction)
232 .fetch_all(executor)
233 .await?;
234 Ok(facts.into_iter().flatten().collect())
235}
236
237#[must_use]
239pub fn without_note(snapshot: &[String]) -> Vec<String> {
240 snapshot
241 .iter()
242 .filter(|fact| !fact.starts_with("tag note "))
243 .cloned()
244 .collect()
245}
246
247#[must_use]
249pub fn first_row_tag(loaded: &str) -> Option<&str> {
250 let (_, rest) = loaded.split_once("(:row \"r1\" :name \"")?;
251 rest.split('"').next()
252}
253
254fn facts<'a>(snapshot: &'a [String], kind: &str) -> impl Iterator<Item = &'a String> {
255 let prefix = format!("{kind} ");
256 snapshot
257 .iter()
258 .filter(move |fact| fact.starts_with(&prefix))
259}
260
261#[must_use]
263pub fn split_tag_facts(snapshot: &[String], name: &str) -> Vec<String> {
264 let name = format!(" {name} ");
265 facts(snapshot, "split-tag")
266 .filter(|fact| fact.contains(&name))
267 .cloned()
268 .collect()
269}
270
271#[must_use]
273pub fn tag_facts(snapshot: &[String]) -> Vec<String> {
274 let mut facts: Vec<_> = without_note(snapshot)
275 .into_iter()
276 .filter(|fact| fact.starts_with("tag "))
277 .collect();
278 facts.sort();
279 facts
280}
281
282#[must_use]
286pub fn kept_only(snapshot: &[String], kept: &[String]) -> bool {
287 !kept.is_empty()
288 && facts(snapshot, "split").count() == 6
289 && facts(snapshot, "split-tag").eq(kept.iter())
290}