1use crate::command::connection;
2use finance::{commodity::Commodity, tag::Tag};
3use num_rational::Rational64;
4use sqlx::types::Uuid;
5use std::{collections::HashMap, fmt::Debug};
6use supp_macro::command;
7
8use super::{CmdError, CmdResult};
9use crate::{command::FinanceEntity, user::User};
10
11command! {
12 GetCommodity {
13 #[required]
14 user_id: Uuid,
15 #[required]
16 commodity_id: Uuid,
17 } => {
18 let user = User { id: user_id };
19
20 let mut conn = connection(&user).await?;
21
22 let comm = sqlx::query_file_as!(Commodity, "sql/select/commodities/by_id.sql", &commodity_id)
23 .fetch_one(&mut *conn)
24 .await?;
25
26 let mut tagged_entities = Vec::new();
28 let tags: HashMap<String, FinanceEntity> =
29 sqlx::query_file!("sql/select/tags/by_commodity.sql", &commodity_id)
30 .fetch_all(&mut *conn)
31 .await?
32 .into_iter()
33 .map(|row| {
34 (
35 row.tag_name.clone(),
36 FinanceEntity::Tag(Tag {
37 id: row.id,
38 tag_name: row.tag_name,
39 tag_value: row.tag_value,
40 description: row.description,
41 }),
42 )
43 })
44 .collect();
45
46 tagged_entities.push((FinanceEntity::Commodity(comm), tags));
47 Ok(Some(CmdResult::TaggedEntities {
48 entities: tagged_entities,
49 pagination: None,
50 }))
51 }
52}
53
54command! {
55 CreateCommodity {
56 #[required]
57 symbol: String,
58 #[required]
59 name: String,
60 #[required]
61 user_id: Uuid,
62 } => {
63 let user = User { id: user_id };
64
65 Ok(Some(
66 user.create_commodity(symbol, name)
67 .await?
68 .id
69 .to_string()
70 .into(),
71 ))
72 }
73}
74
75command! {
76 ListCommodities {
77 #[required]
78 user_id: Uuid,
79 } => {
80 let user = User { id: user_id };
81 let mut conn = connection(&user).await?;
82
83 let commodities: Vec<Commodity> = sqlx::query_file!("sql/select/commodities/all.sql")
85 .fetch_all(&mut *conn)
86 .await?
87 .into_iter()
88 .map(|row| Commodity { id: row.id })
89 .collect();
90
91 let mut tagged_entities = Vec::new();
93 for commodity in commodities {
94 let tags: HashMap<String, FinanceEntity> =
95 sqlx::query_file!("sql/select/tags/by_commodity.sql", &commodity.id)
96 .fetch_all(&mut *conn)
97 .await?
98 .into_iter()
99 .map(|row| {
100 (
101 row.tag_name.clone(),
102 FinanceEntity::Tag(Tag {
103 id: row.id,
104 tag_name: row.tag_name,
105 tag_value: row.tag_value,
106 description: row.description,
107 }),
108 )
109 })
110 .collect();
111
112 tagged_entities.push((FinanceEntity::Commodity(commodity), tags));
113 }
114 Ok(Some(CmdResult::TaggedEntities {
115 entities: tagged_entities,
116 pagination: None,
117 }))
118 }
119}
120
121fn checked_ratio_mul(a: Rational64, b: Rational64) -> Option<Rational64> {
127 fn gcd_i128(mut x: i128, mut y: i128) -> i128 {
128 while y != 0 {
129 (x, y) = (y, x % y);
130 }
131 x.abs()
132 }
133 let num = i128::from(*a.numer()) * i128::from(*b.numer());
134 let den = i128::from(*a.denom()) * i128::from(*b.denom());
135 let g = gcd_i128(num, den).max(1);
136 let num = i64::try_from(num / g).ok()?;
137 let den = i64::try_from(den / g).ok()?;
138 Some(Rational64::new(num, den))
139}
140
141command! {
146 ConvertCommodity {
147 #[required]
148 user_id: Uuid,
149 #[required]
150 amount_num: i64,
151 #[required]
152 amount_denom: i64,
153 #[required]
154 source_commodity_id: Uuid,
155 #[required]
156 target_commodity_id: Uuid,
157 } => {
158 let user = User { id: user_id };
159 let mut conn = connection(&user).await?;
160
161 if amount_denom == 0 {
162 return Err(CmdError::Args(
163 "convert-commodity: amount has zero denominator".to_string(),
164 ));
165 }
166 let amount = Rational64::new(amount_num, amount_denom);
167
168 if source_commodity_id == target_commodity_id {
169 return Ok(Some(CmdResult::Rational(amount)));
170 }
171
172 if let Some(row) = sqlx::query_file!(
173 "sql/select/prices/latest_between.sql",
174 &source_commodity_id,
175 &target_commodity_id,
176 )
177 .fetch_optional(&mut *conn)
178 .await? {
179 let price = Rational64::new(row.value_num, row.value_denom);
180 let converted = checked_ratio_mul(amount, price).ok_or_else(|| {
181 CmdError::Args("convert-commodity: conversion overflow".to_string())
182 })?;
183 return Ok(Some(CmdResult::Rational(converted)));
184 }
185
186 if let Some(row) = sqlx::query_file!(
187 "sql/select/prices/latest_between.sql",
188 &target_commodity_id,
189 &source_commodity_id,
190 )
191 .fetch_optional(&mut *conn)
192 .await? {
193 let inverse = Rational64::new(row.value_denom, row.value_num);
194 let converted = checked_ratio_mul(amount, inverse).ok_or_else(|| {
195 CmdError::Args("convert-commodity: conversion overflow".to_string())
196 })?;
197 return Ok(Some(CmdResult::Rational(converted)));
198 }
199
200 Err(CmdError::NoPrice {
201 from: source_commodity_id,
202 to: target_commodity_id,
203 })
204 }
205}
206
207#[cfg(test)]
208mod command_tests {
209 use super::*;
210 use crate::db::install_test_pool;
211 use sqlx::PgPool;
212 use supp_macro::local_db_sqlx_test;
213 use tokio::sync::OnceCell;
214
215 static CONTEXT: OnceCell<()> = OnceCell::const_new();
217 static USER: OnceCell<User> = OnceCell::const_new();
218
219 async fn setup() {
220 CONTEXT
221 .get_or_init(|| async {
222 crate::telemetry::init_test_logging();
223 })
224 .await;
225 USER.get_or_init(|| async { User { id: Uuid::new_v4() } })
226 .await;
227 }
228
229 #[test]
230 fn checked_ratio_mul_normal_case_reduces() {
231 let got = checked_ratio_mul(Rational64::new(100, 1), Rational64::new(9, 10));
232 assert_eq!(got, Some(Rational64::new(90, 1)));
233 }
234
235 #[test]
236 fn checked_ratio_mul_overflow_returns_none() {
237 let huge = Rational64::new(i64::MAX, 1);
238 assert_eq!(checked_ratio_mul(huge, Rational64::new(i64::MAX, 1)), None);
239 }
240
241 #[test]
242 fn checked_ratio_mul_zero_numerator_is_zero() {
243 let got = checked_ratio_mul(Rational64::new(0, 1), Rational64::new(7, 3));
244 assert_eq!(got, Some(Rational64::new(0, 1)));
245 }
246
247 #[local_db_sqlx_test]
248 async fn test_list_commodities_empty(pool: PgPool) -> anyhow::Result<()> {
249 let user = USER.get().unwrap();
250 user.commit()
251 .await
252 .expect("Failed to commit user to database");
253
254 if let Some(CmdResult::TaggedEntities { entities, .. }) =
255 ListCommodities::new().user_id(user.id).run().await?
256 {
257 assert!(
258 entities.is_empty(),
259 "Expected no commodities in empty database"
260 );
261 } else {
262 panic!("Expected TaggedEntities result");
263 }
264 }
265
266 #[local_db_sqlx_test]
267 async fn test_list_commodities_with_data(pool: PgPool) -> anyhow::Result<()> {
268 let user = USER.get().unwrap();
269 user.commit()
270 .await
271 .expect("Failed to commit user to database");
272
273 CreateCommodity::new()
275 .symbol("TST".to_string())
276 .name("Test Commodity".to_string())
277 .user_id(user.id)
278 .run()
279 .await?;
280
281 if let Some(CmdResult::TaggedEntities { entities, .. }) =
283 ListCommodities::new().user_id(user.id).run().await?
284 {
285 assert_eq!(entities.len(), 1, "Expected one commodity");
286
287 let (entity, tags) = &entities[0];
288 if let FinanceEntity::Commodity(_c) = entity {
289 assert_eq!(tags.len(), 2); for tag in tags.values() {
292 if let FinanceEntity::Tag(t) = tag {
293 match t.tag_name.as_str() {
294 "symbol" => assert_eq!(t.tag_value, "TST"),
295 "name" => assert_eq!(t.tag_value, "Test Commodity"),
296 _ => panic!("Unexpected tag: {}", t.tag_name),
297 }
298 }
299 }
300 } else {
301 panic!("Expected Commodity entity");
302 }
303 } else {
304 panic!("Expected TaggedEntities result");
305 }
306 }
307
308 #[local_db_sqlx_test]
309 async fn test_get_commodity(pool: PgPool) -> anyhow::Result<()> {
310 let user = USER.get().unwrap();
311 user.commit()
312 .await
313 .expect("Failed to commit user to database");
314
315 let commodity_result = CreateCommodity::new()
317 .symbol("TST".to_string())
318 .name("Test Commodity".to_string())
319 .user_id(user.id)
320 .run()
321 .await?;
322
323 let commodity_id = if let Some(CmdResult::String(id)) = commodity_result {
325 uuid::Uuid::parse_str(&id)?
326 } else {
327 panic!("Expected commodity ID string result");
328 };
329
330 if let Some(CmdResult::TaggedEntities { entities, .. }) = GetCommodity::new()
332 .user_id(user.id)
333 .commodity_id(commodity_id)
334 .run()
335 .await?
336 {
337 assert_eq!(entities.len(), 1, "Expected one commodity");
338
339 let (entity, tags) = &entities[0];
340 if let FinanceEntity::Commodity(c) = entity {
341 assert_eq!(c.id, commodity_id);
342
343 assert_eq!(tags.len(), 2); for tag in tags.values() {
346 if let FinanceEntity::Tag(t) = tag {
347 match t.tag_name.as_str() {
348 "symbol" => assert_eq!(t.tag_value, "TST"),
349 "name" => assert_eq!(t.tag_value, "Test Commodity"),
350 _ => panic!("Unexpected tag: {}", t.tag_name),
351 }
352 }
353 }
354 } else {
355 panic!("Expected Commodity entity");
356 }
357 } else {
358 panic!("Expected TaggedEntities result");
359 }
360
361 let result = GetCommodity::new()
363 .user_id(user.id)
364 .commodity_id(Uuid::new_v4())
365 .run()
366 .await;
367 assert!(result.is_err(), "Expected error for non-existent commodity");
368 }
369
370 #[local_db_sqlx_test]
371 async fn convert_without_a_price_row_is_no_price(pool: PgPool) {
372 let user = USER.get().unwrap();
373 user.commit()
374 .await
375 .expect("Failed to commit user to database");
376 let (source, target) = (Uuid::new_v4(), Uuid::new_v4());
377
378 let result = ConvertCommodity::new()
379 .user_id(user.id)
380 .amount_num(1)
381 .amount_denom(1)
382 .source_commodity_id(source)
383 .target_commodity_id(target)
384 .run()
385 .await;
386
387 assert!(matches!(
388 result,
389 Err(CmdError::NoPrice { from, to }) if from == source && to == target
390 ));
391 }
392}