1
//web/src/pages/transaction/util.rs - Shared utility functions for transaction operations
2

            
3
use axum::{Json, http::StatusCode};
4
use chrono::{Local, NaiveDateTime};
5
use finance::price::Price;
6
use num_rational::Rational64;
7
use serde::Deserialize;
8
use server::command::{CmdResult, FinanceEntity, commodity::GetCommodity};
9
use sqlx::types::Uuid;
10
use std::collections::HashMap;
11

            
12
/// Common `SplitData` structure used by both create and edit
13
#[derive(Deserialize, Debug)]
14
pub struct SplitData {
15
    pub split_id: Option<String>, // Only used by edit
16
    pub amount: String,
17
    pub amount_converted: String,
18
    pub from_account: String,
19
    pub to_account: String,
20
    pub from_commodity: String,
21
    pub to_commodity: String,
22
    pub from_tags: Option<Vec<TagData>>,
23
    pub to_tags: Option<Vec<TagData>>,
24
}
25

            
26
#[derive(Deserialize, Debug)]
27
pub struct TagData {
28
    pub name: String,
29
    pub value: String,
30
    pub description: Option<String>,
31
}
32

            
33
/// Result of processing a single split
34
pub struct ProcessedSplit {
35
    pub from_split: finance::split::Split,
36
    pub to_split: finance::split::Split,
37
    pub price: Option<Price>,
38
    pub from_split_tags: Option<Vec<TagData>>,
39
    pub to_split_tags: Option<Vec<TagData>>,
40
}
41

            
42
/// Get account name by ID
43
pub async fn get_account_name(
44
    user_id: Uuid,
45
    account_id: Uuid,
46
) -> Result<String, Box<dyn std::error::Error>> {
47
    match server::command::account::GetAccount::new()
48
        .user_id(user_id)
49
        .account_id(account_id)
50
        .run()
51
        .await?
52
    {
53
        Some(CmdResult::TaggedEntities { entities, .. }) => {
54
            if let Some((FinanceEntity::Account(_account), tags)) = entities.first() {
55
                if let Some(FinanceEntity::Tag(name_tag)) = tags.get("name") {
56
                    Ok(name_tag.tag_value.clone())
57
                } else {
58
                    Ok("Unnamed Account".to_string())
59
                }
60
            } else {
61
                Ok("Unknown Account".to_string())
62
            }
63
        }
64
        _ => Ok("Unknown Account".to_string()),
65
    }
66
}
67

            
68
/// Get commodity symbol (or name as fallback) by ID
69
pub async fn get_commodity_name(
70
    user_id: Uuid,
71
    commodity_id: Uuid,
72
) -> Result<String, Box<dyn std::error::Error>> {
73
    match GetCommodity::new()
74
        .user_id(user_id)
75
        .commodity_id(commodity_id)
76
        .run()
77
        .await?
78
    {
79
        Some(CmdResult::TaggedEntities { entities, .. }) => {
80
            if let Some((FinanceEntity::Commodity(_commodity), tags)) = entities.first() {
81
                if let Some(FinanceEntity::Tag(symbol_tag)) = tags.get("symbol") {
82
                    Ok(symbol_tag.tag_value.clone())
83
                } else if let Some(FinanceEntity::Tag(name_tag)) = tags.get("name") {
84
                    Ok(name_tag.tag_value.clone())
85
                } else {
86
                    Ok("Unknown Currency".to_string())
87
                }
88
            } else {
89
                Ok("Unknown Currency".to_string())
90
            }
91
        }
92
        _ => Ok("Unknown Currency".to_string()),
93
    }
94
}
95

            
96
/// Parse RFC3339 date string from browser (via `toISOString()`) or return current time.
97
#[must_use]
98
7
pub fn parse_transaction_date(date_str: Option<&str>) -> NaiveDateTime {
99
7
    date_str
100
7
        .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
101
7
        .map_or_else(|| Local::now().naive_utc(), |dt| dt.naive_utc())
102
7
}
103

            
104
/// Parse and validate UUID with custom error message
105
13
pub fn parse_uuid(
106
13
    uuid_str: &str,
107
13
    field_name: &str,
108
13
) -> Result<Uuid, (StatusCode, Json<serde_json::Value>)> {
109
13
    Uuid::parse_str(uuid_str).map_err(|_| {
110
1
        let error_response = serde_json::json!({
111
1
            "status": "fail",
112
1
            "message": format!("Invalid {}: {}", field_name, uuid_str),
113
        });
114
1
        (StatusCode::BAD_REQUEST, Json(error_response))
115
1
    })
116
13
}
117

            
118
/// Validate basic amount parsing and positivity (without precision checking)
119
26
pub fn validate_basic_amount(
120
26
    amount_str: &str,
121
26
) -> Result<f64, (StatusCode, Json<serde_json::Value>)> {
122
26
    let amount_value = amount_str.parse::<f64>().map_err(|_| {
123
1
        let error_response = serde_json::json!({
124
1
            "status": "fail",
125
1
            "message": format!("Invalid amount: {}", amount_str),
126
        });
127
1
        (StatusCode::BAD_REQUEST, Json(error_response))
128
1
    })?;
129

            
130
25
    if amount_value <= 0.0 {
131
2
        let error_response = serde_json::json!({
132
2
            "status": "fail",
133
2
            "message": t!("Split amount must be positive"),
134
        });
135
2
        return Err((StatusCode::BAD_REQUEST, Json(error_response)));
136
23
    }
137

            
138
23
    Ok(amount_value)
139
26
}
140

            
141
/// Parse a decimal string directly into an exact rational (numerator, denominator).
142
///
143
/// `"153.81"` becomes `(15381, 100)` — no floating-point intermediary.
144
19
pub fn parse_amount_to_rational(
145
19
    amount_str: &str,
146
19
) -> Result<(i64, i64), (StatusCode, Json<serde_json::Value>)> {
147
19
    validate_basic_amount(amount_str)?;
148

            
149
19
    let trimmed = amount_str.trim();
150
19
    let (numer, denom) = if let Some(dot_pos) = trimmed.find('.') {
151
11
        let decimals = trimmed.len() - dot_pos - 1;
152
62
        let without_dot: String = trimmed.chars().filter(|c| *c != '.').collect();
153
11
        let n = without_dot.parse::<i64>().map_err(|_| {
154
            let error_response = serde_json::json!({
155
                "status": "fail",
156
                "message": format!("Cannot represent amount as rational: {}", amount_str),
157
            });
158
            (StatusCode::BAD_REQUEST, Json(error_response))
159
        })?;
160
11
        (n, 10_i64.pow(decimals as u32))
161
    } else {
162
8
        let n = trimmed.parse::<i64>().map_err(|_| {
163
            let error_response = serde_json::json!({
164
                "status": "fail",
165
                "message": format!("Cannot represent amount as rational: {}", amount_str),
166
            });
167
            (StatusCode::BAD_REQUEST, Json(error_response))
168
        })?;
169
8
        (n, 1)
170
    };
171

            
172
19
    let r = Rational64::new(numer, denom);
173
19
    Ok((*r.numer(), *r.denom()))
174
19
}
175

            
176
/// Process a single split data into finance entities
177
7
pub async fn process_split_data(
178
7
    tx_id: Uuid,
179
7
    split_data: SplitData,
180
7
) -> Result<ProcessedSplit, (StatusCode, Json<serde_json::Value>)> {
181
7
    validate_basic_amount(&split_data.amount)?;
182

            
183
4
    let from_account_id = parse_uuid(&split_data.from_account, "from account ID")?;
184
3
    let to_account_id = parse_uuid(&split_data.to_account, "to account ID")?;
185
3
    let from_commodity = parse_uuid(&split_data.from_commodity, "from commodity ID")?;
186
3
    let to_commodity = parse_uuid(&split_data.to_commodity, "to commodity ID")?;
187

            
188
    // Only validate amount_converted if currency conversion is needed
189
3
    let conversion = from_commodity != to_commodity;
190
3
    if conversion {
191
        validate_basic_amount(&split_data.amount_converted)?;
192
3
    }
193

            
194
3
    let (from_num, from_denom) = parse_amount_to_rational(&split_data.amount)?;
195

            
196
3
    let from_split_id = Uuid::new_v4();
197
3
    let to_split_id = Uuid::new_v4();
198

            
199
3
    let (to_num, to_denom, price) = if conversion {
200
        let (to_num, to_denom) = parse_amount_to_rational(&split_data.amount_converted)?;
201

            
202
        let price = build_conversion_price(
203
            from_split_id,
204
            to_split_id,
205
            from_commodity,
206
            to_commodity,
207
            from_num,
208
            from_denom,
209
            to_num,
210
            to_denom,
211
        );
212

            
213
        (to_num, to_denom, Some(price))
214
    } else {
215
3
        (from_num, from_denom, None)
216
    };
217

            
218
    // Create split entities
219
3
    let from_split = finance::split::Split {
220
3
        id: from_split_id,
221
3
        tx_id,
222
3
        account_id: from_account_id,
223
3
        commodity_id: from_commodity,
224
3
        value_num: -from_num,
225
3
        value_denom: from_denom,
226
3
        reconcile_state: None,
227
3
        reconcile_date: None,
228
3
        lot_id: None,
229
3
    };
230

            
231
3
    let to_split = finance::split::Split {
232
3
        id: to_split_id,
233
3
        tx_id,
234
3
        account_id: to_account_id,
235
3
        commodity_id: to_commodity,
236
3
        value_num: to_num,
237
3
        value_denom: to_denom,
238
3
        reconcile_state: None,
239
3
        reconcile_date: None,
240
3
        lot_id: None,
241
3
    };
242

            
243
3
    Ok(ProcessedSplit {
244
3
        from_split,
245
3
        to_split,
246
3
        price,
247
3
        from_split_tags: split_data.from_tags,
248
3
        to_split_tags: split_data.to_tags,
249
3
    })
250
7
}
251

            
252
/// Create transaction tags from note
253
#[must_use]
254
pub fn create_transaction_tags(note: Option<&str>) -> HashMap<String, FinanceEntity> {
255
    let mut tags = HashMap::new();
256
    if let Some(note_str) = note
257
        && !note_str.trim().is_empty()
258
    {
259
        let tag = finance::tag::Tag {
260
            id: Uuid::new_v4(),
261
            tag_name: "note".to_string(),
262
            tag_value: note_str.to_string(),
263
            description: None,
264
        };
265
        tags.insert("note".to_string(), FinanceEntity::Tag(tag));
266
    }
267
    tags
268
}
269

            
270
/// Build a Price for a multi-currency split from rational components.
271
///
272
/// `from` is the spent amount (will be negated in the split),
273
/// `to` is the received amount in a different commodity.
274
/// Returns a Price whose rate converts `to` back to `from` units.
275
#[must_use]
276
6
pub fn build_conversion_price(
277
6
    from_split_id: Uuid,
278
6
    to_split_id: Uuid,
279
6
    from_commodity: Uuid,
280
6
    to_commodity: Uuid,
281
6
    from_num: i64,
282
6
    from_denom: i64,
283
6
    to_num: i64,
284
6
    to_denom: i64,
285
6
) -> Price {
286
6
    Price {
287
6
        id: Uuid::new_v4(),
288
6
        date: chrono::Utc::now(),
289
6
        commodity_id: to_commodity,
290
6
        currency_id: from_commodity,
291
6
        commodity_split: Some(to_split_id),
292
6
        currency_split: Some(from_split_id),
293
6
        value_num: from_num * to_denom,
294
6
        value_denom: from_denom * to_num,
295
6
    }
296
6
}
297

            
298
/// Validate that splits are not empty
299
8
pub fn validate_splits_not_empty<T>(
300
8
    splits: &[T],
301
8
) -> Result<(), (StatusCode, Json<serde_json::Value>)> {
302
8
    if splits.is_empty() {
303
1
        let error_response = serde_json::json!({
304
1
            "status": "fail",
305
1
            "message": t!("At least one split is required for a transaction"),
306
        });
307
1
        return Err((StatusCode::BAD_REQUEST, Json(error_response)));
308
7
    }
309
7
    Ok(())
310
8
}
311

            
312
#[cfg(test)]
313
mod tests {
314
    use super::*;
315
    use num_rational::Rational64;
316

            
317
    #[test]
318
2
    fn test_parse_amount_integer() {
319
2
        let (num, denom) = parse_amount_to_rational("25584").unwrap();
320
2
        assert_eq!(Rational64::new(num, denom), Rational64::from_integer(25584));
321
2
    }
322

            
323
    #[test]
324
2
    fn test_parse_amount_fractional() {
325
2
        let (num, denom) = parse_amount_to_rational("153.81").unwrap();
326
2
        let r = Rational64::new(num, denom);
327
2
        assert_eq!(r, Rational64::new(15381, 100));
328
2
    }
329

            
330
    #[test]
331
2
    fn test_conversion_price_jpy_usd() {
332
2
        let from_id = Uuid::new_v4();
333
2
        let to_id = Uuid::new_v4();
334
2
        let from_commodity = Uuid::new_v4();
335
2
        let to_commodity = Uuid::new_v4();
336

            
337
2
        let (from_num, from_denom) = parse_amount_to_rational("25584").unwrap();
338
2
        let (to_num, to_denom) = parse_amount_to_rational("153.81").unwrap();
339

            
340
2
        let price = build_conversion_price(
341
2
            from_id,
342
2
            to_id,
343
2
            from_commodity,
344
2
            to_commodity,
345
2
            from_num,
346
2
            from_denom,
347
2
            to_num,
348
2
            to_denom,
349
        );
350

            
351
2
        let from_val = Rational64::new(-from_num, from_denom);
352
2
        let to_val = Rational64::new(to_num, to_denom);
353
2
        let conv_rate = Rational64::new(price.value_num, price.value_denom);
354

            
355
        // commodity_split is to_split, so to_val * conv_rate must cancel from_val
356
2
        assert_eq!(from_val + to_val * conv_rate, Rational64::from_integer(0));
357
2
    }
358

            
359
    #[test]
360
2
    fn test_conversion_price_integer_amounts() {
361
2
        let from_id = Uuid::new_v4();
362
2
        let to_id = Uuid::new_v4();
363
2
        let from_commodity = Uuid::new_v4();
364
2
        let to_commodity = Uuid::new_v4();
365

            
366
2
        let (from_num, from_denom) = parse_amount_to_rational("1000").unwrap();
367
2
        let (to_num, to_denom) = parse_amount_to_rational("7").unwrap();
368

            
369
2
        let price = build_conversion_price(
370
2
            from_id,
371
2
            to_id,
372
2
            from_commodity,
373
2
            to_commodity,
374
2
            from_num,
375
2
            from_denom,
376
2
            to_num,
377
2
            to_denom,
378
        );
379

            
380
2
        let from_val = Rational64::new(-from_num, from_denom);
381
2
        let to_val = Rational64::new(to_num, to_denom);
382
2
        let conv_rate = Rational64::new(price.value_num, price.value_denom);
383

            
384
2
        assert_eq!(from_val + to_val * conv_rate, Rational64::from_integer(0));
385
2
    }
386

            
387
    #[test]
388
2
    fn test_conversion_price_both_fractional() {
389
2
        let from_id = Uuid::new_v4();
390
2
        let to_id = Uuid::new_v4();
391
2
        let from_commodity = Uuid::new_v4();
392
2
        let to_commodity = Uuid::new_v4();
393

            
394
2
        let (from_num, from_denom) = parse_amount_to_rational("99.50").unwrap();
395
2
        let (to_num, to_denom) = parse_amount_to_rational("85.23").unwrap();
396

            
397
2
        let price = build_conversion_price(
398
2
            from_id,
399
2
            to_id,
400
2
            from_commodity,
401
2
            to_commodity,
402
2
            from_num,
403
2
            from_denom,
404
2
            to_num,
405
2
            to_denom,
406
        );
407

            
408
2
        let from_val = Rational64::new(-from_num, from_denom);
409
2
        let to_val = Rational64::new(to_num, to_denom);
410
2
        let conv_rate = Rational64::new(price.value_num, price.value_denom);
411

            
412
2
        assert_eq!(from_val + to_val * conv_rate, Rational64::from_integer(0));
413
2
    }
414
}