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
//! Split expenses between multiple people.
//!
//! This plugin splits expense postings between multiple members.
//! Any expense account that doesn't already contain a member's name
//! will be split into multiple postings, one per member.
//!
//! Configuration: Space-separated list of member names, e.g., "Martin Caroline"
//!
//! Example:
//! ```beancount
//! plugin "beancount.plugins.split_expenses" "Martin Caroline"
//!
//! 2015-02-01 * "Aqua Viva Tulum"
//! Income:Caroline:CreditCard -269.00 USD
//! Expenses:Accommodation
//! ```
//!
//! Becomes:
//! ```beancount
//! 2015-02-01 * "Aqua Viva Tulum"
//! Income:Caroline:CreditCard -269.00 USD
//! Expenses:Accommodation:Martin 134.50 USD
//! Expenses:Accommodation:Caroline 134.50 USD
//! ```
use rust_decimal::Decimal;
use std::collections::HashSet;
use std::str::FromStr;
use crate::types::{
AmountData, DirectiveData, DirectiveWrapper, MetaValueData, OpenData, PluginInput,
PluginOutput, PostingData,
};
use super::super::NativePlugin;
/// Plugin for splitting expenses between multiple people.
pub struct SplitExpensesPlugin;
impl NativePlugin for SplitExpensesPlugin {
fn name(&self) -> &'static str {
"split_expenses"
}
fn description(&self) -> &'static str {
"Split expense postings between multiple members"
}
fn process(&self, input: PluginInput) -> PluginOutput {
// Parse configuration to get member names
let members: Vec<String> = match &input.config {
Some(config) => config.split_whitespace().map(String::from).collect(),
None => {
// No config provided, return unchanged
return PluginOutput {
directives: input.directives,
errors: Vec::new(),
};
}
};
if members.is_empty() {
return PluginOutput {
directives: input.directives,
errors: Vec::new(),
};
}
let num_members = Decimal::from(members.len());
let mut new_accounts: HashSet<String> = HashSet::new();
let mut earliest_date: Option<String> = None;
// Process directives
let directives: Vec<_> = input
.directives
.into_iter()
.map(|mut wrapper| {
// Track earliest date for creating Open directives
if earliest_date.is_none()
|| wrapper.date < *earliest_date.as_ref().unwrap_or(&String::new())
{
earliest_date = Some(wrapper.date.clone());
}
if wrapper.directive_type == "transaction"
&& let DirectiveData::Transaction(ref mut txn) = wrapper.data
{
let mut new_postings = Vec::new();
for posting in &txn.postings {
// Check if this is an expense account
let is_expense = posting.account.starts_with("Expenses:");
// Check if account already contains a member name
let has_member =
members.iter().any(|m| posting.account.contains(m.as_str()));
if is_expense && !has_member {
// Split this posting among members
if let Some(ref units) = posting.units {
// Parse the amount
if let Ok(amount) = Decimal::from_str(&units.number) {
let split_amount = amount / num_members;
for member in &members {
// Create subaccount with member name
let subaccount = format!("{}:{}", posting.account, member);
new_accounts.insert(subaccount.clone());
// Create new posting for this member
let mut new_metadata = posting.metadata.clone();
// Mark as automatically calculated
new_metadata.push((
"__automatic__".to_string(),
MetaValueData::String("True".to_string()),
));
new_postings.push(PostingData {
account: subaccount,
units: Some(AmountData {
number: split_amount.to_string(),
currency: units.currency.clone(),
}),
cost: posting.cost.clone(),
price: posting.price.clone(),
flag: posting.flag.clone(),
metadata: new_metadata,
});
}
} else {
// Couldn't parse amount, keep original
new_postings.push(posting.clone());
}
} else {
// No units, keep original
new_postings.push(posting.clone());
}
} else {
// Keep posting as is
new_postings.push(posting.clone());
}
}
txn.postings = new_postings;
}
wrapper
})
.collect();
// Create Open directives for new accounts
let mut open_directives: Vec<DirectiveWrapper> = Vec::new();
if let Some(date) = earliest_date {
for account in &new_accounts {
open_directives.push(DirectiveWrapper {
directive_type: "open".to_string(),
date: date.clone(),
filename: Some("<split_expenses>".to_string()),
lineno: Some(0),
data: DirectiveData::Open(OpenData {
account: account.clone(),
currencies: vec![],
booking: None,
metadata: vec![],
}),
});
}
}
// Combine open directives with original directives
let mut all_directives = open_directives;
all_directives.extend(directives);
PluginOutput {
directives: all_directives,
errors: Vec::new(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::*;
fn create_test_transaction(postings: Vec<PostingData>) -> DirectiveWrapper {
DirectiveWrapper {
directive_type: "transaction".to_string(),
date: "2024-01-15".to_string(),
filename: None,
lineno: None,
data: DirectiveData::Transaction(TransactionData {
flag: "*".to_string(),
payee: Some("Test".to_string()),
narration: "Test transaction".to_string(),
tags: vec![],
links: vec![],
metadata: vec![],
postings,
}),
}
}
#[test]
fn test_split_expenses_basic() {
let plugin = SplitExpensesPlugin;
let input = PluginInput {
directives: vec![create_test_transaction(vec![
PostingData {
account: "Income:Caroline:CreditCard".to_string(),
units: Some(AmountData {
number: "-269.00".to_string(),
currency: "USD".to_string(),
}),
cost: None,
price: None,
flag: None,
metadata: vec![],
},
PostingData {
account: "Expenses:Accommodation".to_string(),
units: Some(AmountData {
number: "269.00".to_string(),
currency: "USD".to_string(),
}),
cost: None,
price: None,
flag: None,
metadata: vec![],
},
])],
options: PluginOptions {
operating_currencies: vec!["USD".to_string()],
title: None,
},
config: Some("Martin Caroline".to_string()),
};
let output = plugin.process(input);
assert_eq!(output.errors.len(), 0);
// Should have 2 open directives + 1 transaction
assert_eq!(output.directives.len(), 3);
// Find the transaction
let txn = output
.directives
.iter()
.find(|d| d.directive_type == "transaction")
.unwrap();
if let DirectiveData::Transaction(txn_data) = &txn.data {
// Should have 3 postings: 1 income (unchanged) + 2 expenses (split)
assert_eq!(txn_data.postings.len(), 3);
// Check the split postings
let expense_postings: Vec<_> = txn_data
.postings
.iter()
.filter(|p| p.account.starts_with("Expenses:"))
.collect();
assert_eq!(expense_postings.len(), 2);
assert!(
expense_postings
.iter()
.any(|p| p.account == "Expenses:Accommodation:Martin")
);
assert!(
expense_postings
.iter()
.any(|p| p.account == "Expenses:Accommodation:Caroline")
);
// Each should have half the amount (134.50)
for p in expense_postings {
if let Some(units) = &p.units {
assert_eq!(units.number, "134.50");
}
}
} else {
panic!("Expected transaction");
}
}
#[test]
fn test_split_expenses_preserves_member_accounts() {
let plugin = SplitExpensesPlugin;
let input = PluginInput {
directives: vec![create_test_transaction(vec![
PostingData {
account: "Income:Martin:Cash".to_string(),
units: Some(AmountData {
number: "-100.00".to_string(),
currency: "USD".to_string(),
}),
cost: None,
price: None,
flag: None,
metadata: vec![],
},
PostingData {
account: "Expenses:Food:Martin".to_string(),
units: Some(AmountData {
number: "100.00".to_string(),
currency: "USD".to_string(),
}),
cost: None,
price: None,
flag: None,
metadata: vec![],
},
])],
options: PluginOptions {
operating_currencies: vec!["USD".to_string()],
title: None,
},
config: Some("Martin Caroline".to_string()),
};
let output = plugin.process(input);
// Should have only 1 directive (no new open directives since account already has member)
assert_eq!(output.directives.len(), 1);
if let DirectiveData::Transaction(txn_data) = &output.directives[0].data {
// Postings should be unchanged
assert_eq!(txn_data.postings.len(), 2);
assert!(
txn_data
.postings
.iter()
.any(|p| p.account == "Expenses:Food:Martin")
);
} else {
panic!("Expected transaction");
}
}
#[test]
fn test_split_expenses_no_config() {
let plugin = SplitExpensesPlugin;
let input = PluginInput {
directives: vec![create_test_transaction(vec![PostingData {
account: "Expenses:Food".to_string(),
units: Some(AmountData {
number: "100.00".to_string(),
currency: "USD".to_string(),
}),
cost: None,
price: None,
flag: None,
metadata: vec![],
}])],
options: PluginOptions {
operating_currencies: vec!["USD".to_string()],
title: None,
},
config: None,
};
let output = plugin.process(input);
// Should return unchanged
assert_eq!(output.directives.len(), 1);
if let DirectiveData::Transaction(txn_data) = &output.directives[0].data {
assert_eq!(txn_data.postings.len(), 1);
assert_eq!(txn_data.postings[0].account, "Expenses:Food");
} else {
panic!("Expected transaction");
}
}
}