1use std::collections::HashMap;
2
3use chrono::{DateTime, TimeZone, Utc};
4use finance::{price::Price, split::Split};
5use sqlx::types::Uuid;
6
7use super::super::super::{CmdResult, commodity::CreateCommodity, transaction::CreateTransaction};
8use super::super::super::{FinanceEntity, account::CreateAccount, account::SetAccountTag};
9use crate::user::User;
10
11pub fn at(y: i32, mo: u32, d: u32, h: u32, mi: u32, s: u32) -> DateTime<Utc> {
12 Utc.with_ymd_and_hms(y, mo, d, h, mi, s)
13 .single()
14 .unwrap_or(DateTime::<Utc>::MIN_UTC)
15}
16
17pub struct Ledger {
19 pub user: User,
20 commodities: HashMap<&'static str, Uuid>,
21 accounts: HashMap<&'static str, Uuid>,
22}
23
24pub type Leg = (&'static str, &'static str, i64, i64);
25
26impl Ledger {
27 pub fn commodity(&self, symbol: &str) -> Uuid {
28 self.commodities.get(symbol).copied().unwrap_or_default()
29 }
30
31 pub fn account(&self, name: &str) -> Uuid {
32 self.accounts.get(name).copied().unwrap_or_default()
33 }
34
35 pub fn symbol(&self, id: Uuid) -> String {
36 self.commodities
37 .iter()
38 .find_map(|(symbol, cid)| (*cid == id).then(|| (*symbol).to_owned()))
39 .unwrap_or_else(|| "<unknown>".to_owned())
40 }
41
42 async fn commodity_new(&mut self, symbol: &'static str) -> anyhow::Result<()> {
43 let result = CreateCommodity::new()
44 .symbol(symbol.to_owned())
45 .name(symbol.to_owned())
46 .user_id(self.user.id)
47 .run()
48 .await?;
49 let Some(CmdResult::String(id)) = result else {
50 anyhow::bail!("commodity {symbol} not created");
51 };
52 self.commodities.insert(symbol, Uuid::parse_str(&id)?);
53 Ok(())
54 }
55
56 async fn account_new(
57 &mut self,
58 name: &'static str,
59 parent: Option<&str>,
60 kind: Option<&str>,
61 ) -> anyhow::Result<()> {
62 let mut cmd = CreateAccount::new()
63 .name(name.to_owned())
64 .user_id(self.user.id);
65 if let Some(parent) = parent {
66 cmd = cmd.parent(self.account(parent));
67 }
68 let Some(CmdResult::Entity(FinanceEntity::Account(account))) = cmd.run().await? else {
69 anyhow::bail!("account {name} not created");
70 };
71 self.accounts.insert(name, account.id);
72 if let Some(kind) = kind {
73 SetAccountTag::new()
74 .user_id(self.user.id)
75 .account_id(account.id)
76 .tag_name("type".to_owned())
77 .tag_value(kind.to_owned())
78 .run()
79 .await?;
80 }
81 Ok(())
82 }
83
84 pub async fn post(
86 &self,
87 when: DateTime<Utc>,
88 legs: &[Leg],
89 ) -> anyhow::Result<(Uuid, Vec<Uuid>)> {
90 let tx_id = Uuid::new_v4();
91 let splits: Vec<Split> = legs
92 .iter()
93 .map(|&(account, commodity, value_num, value_denom)| Split {
94 id: Uuid::new_v4(),
95 tx_id,
96 account_id: self.account(account),
97 commodity_id: self.commodity(commodity),
98 value_num,
99 value_denom,
100 reconcile_state: None,
101 reconcile_date: None,
102 lot_id: None,
103 })
104 .collect();
105 let split_ids = splits.iter().map(|s| s.id).collect();
106 CreateTransaction::new()
107 .user_id(self.user.id)
108 .splits(splits.into_iter().map(FinanceEntity::Split).collect())
109 .id(tx_id)
110 .post_date(when)
111 .enter_date(when)
112 .run()
113 .await?;
114 Ok((tx_id, split_ids))
115 }
116
117 async fn tag_tx(&self, tx_id: Uuid, name: &str, value: &str) -> anyhow::Result<()> {
118 self.user
119 .create_transaction_tag(tx_id, name.to_owned(), value.to_owned(), None)
120 .await?;
121 Ok(())
122 }
123
124 async fn tag_split(&self, split_id: Uuid, value: &str) -> anyhow::Result<()> {
125 self.user
126 .create_split_tag(split_id, "category".to_owned(), value.to_owned(), None)
127 .await?;
128 Ok(())
129 }
130
131 async fn price_eur_usd(&self, split_id: Uuid, when: DateTime<Utc>) -> anyhow::Result<()> {
132 let price = Price {
133 id: Uuid::new_v4(),
134 date: when,
135 commodity_id: self.commodity("EUR"),
136 currency_id: self.commodity("USD"),
137 commodity_split: Some(split_id),
138 currency_split: None,
139 value_num: 6,
140 value_denom: 5,
141 };
142 let mut conn = self.user.get_connection().await?;
143 sqlx::query_file!(
144 "sql/insert/prices/price.sql",
145 price.id,
146 price.commodity_id,
147 price.currency_id,
148 price.commodity_split,
149 price.currency_split,
150 price.date,
151 price.value_num,
152 price.value_denom
153 )
154 .execute(&mut *conn)
155 .await?;
156 Ok(())
157 }
158}
159
160pub async fn seed(user: User) -> anyhow::Result<Ledger> {
163 let mut l = Ledger {
164 user,
165 commodities: HashMap::new(),
166 accounts: HashMap::new(),
167 };
168 for symbol in ["USD", "EUR", "JPY"] {
169 l.commodity_new(symbol).await?;
170 }
171 let tree = [
172 ("Assets", None, Some("asset")),
173 ("Bank", Some("Assets"), Some("asset")),
174 ("Checking", Some("Bank"), Some("asset")),
175 ("Savings", Some("Bank"), Some("asset")),
176 ("Income", None, Some("income")),
177 ("Work", Some("Income"), Some("income")),
178 ("Salary", Some("Work"), Some("income")),
179 ("Expenses", None, Some("expense")),
180 ("Living", Some("Expenses"), Some("expense")),
181 ("Food", Some("Living"), Some("expense")),
182 ("Rent", Some("Living"), Some("expense")),
183 ("Leisure", Some("Expenses"), Some("expense")),
184 ("Equity", None, None),
185 ("Opening", Some("Equity"), None),
186 ];
187 for (name, parent, kind) in tree {
188 l.account_new(name, parent, kind).await?;
189 }
190
191 l.post(
192 at(2024, 12, 31, 23, 59, 59),
193 &[("Checking", "USD", 1000, 1), ("Opening", "USD", -1000, 1)],
194 )
195 .await?;
196
197 let (tx, _) = l
198 .post(
199 at(2025, 1, 1, 0, 0, 0),
200 &[("Checking", "USD", 3000, 1), ("Salary", "USD", -3000, 1)],
201 )
202 .await?;
203 l.tag_tx(tx, "category", "salary").await?;
204
205 let (tx, splits) = l
206 .post(
207 at(2025, 1, 15, 12, 0, 0),
208 &[
209 ("Food", "USD", 12050, 100),
210 ("Checking", "USD", -12050, 100),
211 ],
212 )
213 .await?;
214 l.tag_tx(tx, "category", "groceries").await?;
215 l.tag_split(splits[0], "food").await?;
216
217 let (tx, _) = l
218 .post(
219 at(2025, 1, 31, 23, 59, 59),
220 &[("Rent", "USD", 800, 1), ("Checking", "USD", -800, 1)],
221 )
222 .await?;
223 l.tag_tx(tx, "category", "housing").await?;
224 l.tag_tx(tx, "project", "home").await?;
225
226 l.post(
227 at(2025, 2, 1, 0, 0, 0),
228 &[("Food", "USD", 45, 1), ("Checking", "USD", -45, 1)],
229 )
230 .await?;
231
232 l.post(
233 at(2025, 2, 5, 9, 0, 0),
234 &[("Savings", "USD", 500, 1), ("Checking", "USD", -500, 1)],
235 )
236 .await?;
237
238 let when = at(2025, 2, 10, 12, 0, 0);
239 let (tx, splits) = l
240 .post(
241 when,
242 &[("Leisure", "EUR", 60, 1), ("Savings", "EUR", -60, 1)],
243 )
244 .await?;
245 l.tag_tx(tx, "category", "fun").await?;
246 for split in splits {
247 l.price_eur_usd(split, when).await?;
248 }
249
250 let (_, splits) = l
251 .post(
252 at(2025, 3, 31, 23, 59, 59),
253 &[("Food", "USD", 30, 1), ("Checking", "USD", -30, 1)],
254 )
255 .await?;
256 l.tag_split(splits[0], "food").await?;
257
258 let (tx, _) = l
259 .post(
260 at(2025, 4, 1, 0, 0, 0),
261 &[("Checking", "USD", 3000, 1), ("Salary", "USD", -3000, 1)],
262 )
263 .await?;
264 l.tag_tx(tx, "category", "salary").await?;
265
266 let (tx, _) = l
267 .post(
268 at(2025, 6, 15, 12, 0, 0),
269 &[("Rent", "USD", 800, 1), ("Checking", "USD", -800, 1)],
270 )
271 .await?;
272 l.tag_tx(tx, "category", "housing").await?;
273 l.tag_tx(tx, "project", "home").await?;
274
275 let (tx, _) = l
276 .post(
277 at(2025, 12, 20, 12, 0, 0),
278 &[("Leisure", "JPY", 5000, 1), ("Savings", "JPY", -5000, 1)],
279 )
280 .await?;
281 l.tag_tx(tx, "category", "fun").await?;
282
283 let (tx, _) = l
284 .post(
285 at(2026, 1, 1, 0, 0, 0),
286 &[("Food", "USD", 10, 1), ("Checking", "USD", -10, 1)],
287 )
288 .await?;
289 l.tag_tx(tx, "category", "food").await?;
290 Ok(l)
291}