rustledger-wasm 0.7.5

Beancount WebAssembly bindings for JavaScript/TypeScript
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Helper functions for editor features.

use rustledger_core::Directive;
use rustledger_parser::ParseResult;

use crate::types::EditorRange;

/// Standard Beancount account types.
pub const ACCOUNT_TYPES: &[&str] = &["Assets", "Liabilities", "Equity", "Income", "Expenses"];

/// Standard Beancount directives.
pub const DIRECTIVES: &[(&str, &str)] = &[
    ("open", "Open an account"),
    ("close", "Close an account"),
    ("commodity", "Define a commodity/currency"),
    ("balance", "Assert account balance"),
    ("pad", "Pad account to target"),
    ("event", "Record an event"),
    ("query", "Define a named query"),
    ("note", "Add a note to an account"),
    ("document", "Link a document"),
    ("custom", "Custom directive"),
    ("price", "Record a price"),
    ("txn", "Transaction (complete)"),
    ("*", "Transaction (complete)"),
    ("!", "Transaction (incomplete)"),
];

/// Get a specific line from source.
pub fn get_line(source: &str, line_num: usize) -> &str {
    source.lines().nth(line_num).unwrap_or("")
}

/// Check if a string looks like a date (YYYY-MM-DD).
pub fn is_date_like(s: &str) -> bool {
    if s.len() != 10 {
        return false;
    }
    let chars: Vec<char> = s.chars().collect();
    chars[4] == '-'
        && chars[7] == '-'
        && chars.iter().enumerate().all(|(i, c)| {
            if i == 4 || i == 7 {
                *c == '-'
            } else {
                c.is_ascii_digit()
            }
        })
}

/// Get the word at a given position in the source.
pub fn get_word_at_position(source: &str, line: u32, character: u32) -> Option<String> {
    let line_text = source.lines().nth(line as usize)?;
    let col = character as usize;

    if col > line_text.len() {
        return None;
    }

    let chars: Vec<char> = line_text.chars().collect();

    // Find start of word
    let mut start = col;
    while start > 0 && is_word_char(chars.get(start - 1).copied()?) {
        start -= 1;
    }

    // Find end of word
    let mut end = col;
    while end < chars.len() && is_word_char(chars[end]) {
        end += 1;
    }

    if start == end {
        return None;
    }

    Some(chars[start..end].iter().collect())
}

/// Check if a character is part of a word (including account separators).
pub fn is_word_char(c: char) -> bool {
    c.is_alphanumeric() || c == ':' || c == '_' || c == '-'
}

/// Check if a string looks like an account type.
pub fn is_account_type(s: &str) -> bool {
    matches!(
        s,
        "Assets" | "Liabilities" | "Equity" | "Income" | "Expenses"
    )
}

/// Check if a string looks like a currency (all uppercase, 2-5 chars).
pub fn is_currency_like(s: &str) -> bool {
    s.len() >= 2
        && s.len() <= 5
        && s.chars()
            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
}

/// Extract all account names from parse result.
pub fn extract_accounts(parse_result: &ParseResult) -> Vec<String> {
    let mut accounts = Vec::new();

    for spanned_directive in &parse_result.directives {
        match &spanned_directive.value {
            Directive::Open(open) => accounts.push(open.account.to_string()),
            Directive::Close(close) => accounts.push(close.account.to_string()),
            Directive::Balance(bal) => accounts.push(bal.account.to_string()),
            Directive::Pad(pad) => {
                accounts.push(pad.account.to_string());
                accounts.push(pad.source_account.to_string());
            }
            Directive::Transaction(txn) => {
                for posting in &txn.postings {
                    accounts.push(posting.account.to_string());
                }
            }
            _ => {}
        }
    }

    accounts.sort();
    accounts.dedup();
    accounts
}

/// Extract all currencies from parse result.
pub fn extract_currencies(parse_result: &ParseResult) -> Vec<String> {
    let mut currencies = Vec::new();

    for spanned_directive in &parse_result.directives {
        match &spanned_directive.value {
            Directive::Open(open) => {
                for currency in &open.currencies {
                    currencies.push(currency.to_string());
                }
            }
            Directive::Commodity(comm) => currencies.push(comm.currency.to_string()),
            Directive::Balance(bal) => currencies.push(bal.amount.currency.to_string()),
            Directive::Transaction(txn) => {
                for posting in &txn.postings {
                    if let Some(ref units) = posting.units {
                        if let Some(currency) = units.currency() {
                            currencies.push(currency.to_string());
                        }
                    }
                }
            }
            _ => {}
        }
    }

    // Add common defaults
    currencies.push("USD".to_string());
    currencies.push("EUR".to_string());
    currencies.push("GBP".to_string());

    currencies.sort();
    currencies.dedup();
    currencies
}

/// Extract payees from transactions.
pub fn extract_payees(parse_result: &ParseResult) -> Vec<String> {
    let mut payees = Vec::new();

    for spanned_directive in &parse_result.directives {
        if let Directive::Transaction(txn) = &spanned_directive.value {
            if let Some(ref payee) = txn.payee {
                payees.push(payee.to_string());
            }
        }
    }

    payees.sort();
    payees.dedup();
    payees
}

/// Count how many times an account is used in postings.
pub fn count_account_usages(account: &str, parse_result: &ParseResult) -> usize {
    let mut count = 0;
    for spanned_directive in &parse_result.directives {
        if let Directive::Transaction(txn) = &spanned_directive.value {
            for posting in &txn.postings {
                if posting.account.as_ref() == account {
                    count += 1;
                }
            }
        }
    }
    count
}

/// Count how many times a currency is used.
#[allow(clippy::cmp_owned)]
pub fn count_currency_usages(currency: &str, parse_result: &ParseResult) -> usize {
    let mut count = 0;
    for spanned_directive in &parse_result.directives {
        match &spanned_directive.value {
            Directive::Transaction(txn) => {
                for posting in &txn.postings {
                    if let Some(ref units) = posting.units {
                        if let Some(c) = units.currency() {
                            if c.to_string() == currency {
                                count += 1;
                            }
                        }
                    }
                }
            }
            Directive::Balance(bal) => {
                if bal.amount.currency.as_ref() == currency {
                    count += 1;
                }
            }
            _ => {}
        }
    }
    count
}

/// Find a quoted string in a line and return its range (including quotes).
pub fn find_quoted_string_in_line(line: &str, text: &str, line_num: u32) -> Option<EditorRange> {
    // Look for the text within quotes
    let quoted = format!("\"{text}\"");
    if let Some(pos) = line.find(&quoted) {
        return Some(EditorRange {
            start_line: line_num,
            start_character: pos as u32,
            end_line: line_num,
            end_character: (pos + quoted.len()) as u32,
        });
    }
    None
}

/// Find a word in a line and return its range.
pub fn find_word_in_line(line: &str, word: &str, line_num: u32) -> Option<EditorRange> {
    find_nth_word_in_line(line, word, line_num, 0)
}

/// Find the nth occurrence of a word in a line and return its range.
pub fn find_nth_word_in_line(
    line: &str,
    word: &str,
    line_num: u32,
    n: usize,
) -> Option<EditorRange> {
    let mut count = 0;
    let mut start = 0;

    while let Some(pos) = line[start..].find(word) {
        let abs_pos = start + pos;
        // Check word boundaries
        let before_ok = abs_pos == 0 || !is_word_char(line.chars().nth(abs_pos - 1)?);
        let after_ok = abs_pos + word.len() >= line.len()
            || !is_word_char(line.chars().nth(abs_pos + word.len())?);

        if before_ok && after_ok {
            if count == n {
                return Some(EditorRange {
                    start_line: line_num,
                    start_character: abs_pos as u32,
                    end_line: line_num,
                    end_character: (abs_pos + word.len()) as u32,
                });
            }
            count += 1;
        }
        start = abs_pos + 1;
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use rustledger_parser::parse;

    #[test]
    fn test_get_word_at_position() {
        let source = "2024-01-01 open Assets:Bank USD";

        let word = get_word_at_position(source, 0, 11);
        assert_eq!(word, Some("open".to_string()));

        let word = get_word_at_position(source, 0, 20);
        assert_eq!(word, Some("Assets:Bank".to_string()));

        let word = get_word_at_position(source, 0, 28);
        assert_eq!(word, Some("USD".to_string()));
    }

    #[test]
    fn test_get_word_at_position_out_of_bounds() {
        let source = "hello";
        let word = get_word_at_position(source, 0, 100);
        assert!(word.is_none());
    }

    #[test]
    fn test_get_word_at_position_at_space() {
        let source = "hello world";
        let word = get_word_at_position(source, 0, 5);
        // Position 5 is 'o' in "hello", still part of word
        assert_eq!(word, Some("hello".to_string()));
    }

    #[test]
    fn test_is_date_like() {
        assert!(is_date_like("2024-01-15"));
        assert!(is_date_like("1999-12-31"));
        assert!(!is_date_like("2024-1-15")); // Wrong format (too short)
        assert!(!is_date_like("not-a-date"));
        // Note: is_date_like only checks format, not validity
        assert!(is_date_like("2024-13-99")); // Pattern matches
    }

    #[test]
    fn test_is_currency_like() {
        assert!(is_currency_like("USD"));
        assert!(is_currency_like("EUR"));
        assert!(is_currency_like("BTC"));
        assert!(is_currency_like("AAPL"));
        assert!(!is_currency_like("U")); // Too short
        assert!(!is_currency_like("VERYLONGCURRENCY")); // Too long
        assert!(!is_currency_like("usd")); // Lowercase
    }

    #[test]
    fn test_is_account_type() {
        assert!(is_account_type("Assets"));
        assert!(is_account_type("Liabilities"));
        assert!(is_account_type("Equity"));
        assert!(is_account_type("Income"));
        assert!(is_account_type("Expenses"));
        assert!(!is_account_type("Other"));
        assert!(!is_account_type("assets")); // Case-sensitive
    }

    #[test]
    fn test_extract_accounts() {
        let source = r#"2024-01-01 open Assets:Bank USD
2024-01-01 open Expenses:Food USD
2024-01-15 * "Coffee"
  Assets:Bank  -5.00 USD
  Expenses:Food  5.00 USD
"#;
        let result = parse(source);
        let accounts = extract_accounts(&result);

        assert!(accounts.contains(&"Assets:Bank".to_string()));
        assert!(accounts.contains(&"Expenses:Food".to_string()));
    }

    #[test]
    fn test_extract_currencies() {
        let source = r#"2024-01-01 open Assets:Bank USD
2024-01-01 commodity EUR
2024-01-15 balance Assets:Bank 100.00 GBP
"#;
        let result = parse(source);
        let currencies = extract_currencies(&result);

        assert!(currencies.contains(&"USD".to_string()));
        assert!(currencies.contains(&"EUR".to_string()));
        assert!(currencies.contains(&"GBP".to_string()));
    }

    #[test]
    fn test_extract_payees() {
        let source = r#"2024-01-15 * "Coffee Shop" "Morning coffee"
  Assets:Bank  -5.00 USD
  Expenses:Food
2024-01-16 * "Restaurant" "Lunch"
  Assets:Bank  -20.00 USD
  Expenses:Food
"#;
        let result = parse(source);
        let payees = extract_payees(&result);

        assert!(payees.contains(&"Coffee Shop".to_string()));
        assert!(payees.contains(&"Restaurant".to_string()));
    }

    #[test]
    fn test_find_word_in_line() {
        let line = "2024-01-01 open Assets:Bank USD";
        let range = find_word_in_line(line, "open", 5);
        assert!(range.is_some());
        let r = range.unwrap();
        assert_eq!(r.start_line, 5);
        assert_eq!(r.start_character, 11);
        assert_eq!(r.end_character, 15);
    }

    #[test]
    fn test_find_nth_word_in_line() {
        let line = "USD EUR USD GBP";
        let first = find_nth_word_in_line(line, "USD", 0, 0);
        assert!(first.is_some());
        assert_eq!(first.unwrap().start_character, 0);

        let second = find_nth_word_in_line(line, "USD", 0, 1);
        assert!(second.is_some());
        assert_eq!(second.unwrap().start_character, 8);
    }

    #[test]
    fn test_find_quoted_string_in_line() {
        let line = r#"2024-01-15 * "Coffee Shop" "Morning coffee""#;
        let range = find_quoted_string_in_line(line, "Coffee Shop", 0);
        assert!(range.is_some());
        let r = range.unwrap();
        assert_eq!(r.start_character, 13);
        assert_eq!(r.end_character, 26);
    }
}