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
|
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use ulid::{Generator, Ulid};
use super::*;
#[derive(Debug, thiserror::Error)]
pub enum RepoError {
#[error("parent account {0} not found")]
ParentNotFound(AccountId),
#[error(transparent)]
Invalid(#[from] InvalidJournalEntry),
}
#[async_trait]
pub trait AccountRepository: Send + Sync {
async fn create(&self, new: NewAccount) -> Result<Account, RepoError>;
async fn get(&self, id: AccountId) -> Result<Option<Account>, RepoError>;
}
#[async_trait]
pub trait JournalEntryRepository: Send + Sync {
async fn create(&self, new: NewJournalEntry) -> Result<JournalEntry, RepoError>;
async fn get(&self, id: JournalEntryId) -> Result<Option<JournalEntry>, RepoError>;
}
#[derive(Default)]
pub struct InMemoryAccountRepository {
accounts: Mutex<HashMap<AccountId, Account>>,
generator: Mutex<Generator>,
}
pub struct InMemoryJournalEntryRepository {
account_repository: Arc<dyn AccountRepository>,
journal_entries: Mutex<HashMap<JournalEntryId, JournalEntry>>,
generator: Mutex<Generator>,
}
#[async_trait]
impl AccountRepository for InMemoryAccountRepository {
async fn create(&self, new: NewAccount) -> Result<Account, RepoError> {
let id = {
let mut generator = self.generator.lock().unwrap();
// generate() is monotonic; on the rare same-tick random overflow,
// recover into a valid (incremented) Ulid rather than failing.
let ulid = generator
.generate()
.unwrap_or_else(|overflow| overflow.commit_overflow_increment());
AccountId::from_ulid(ulid)
};
let mut accounts = self.accounts.lock().unwrap();
let path = match new.parent {
Some(parent_id) => accounts
.get(&parent_id)
.ok_or(RepoError::ParentNotFound(parent_id))?
.path
.with_child(id),
None => MaterializedPath::root(id),
};
let account =
Account::from_parts(id, new.account_type, new.name, new.description, path);
accounts.insert(id, account.clone());
Ok(account)
}
async fn get(&self, id: AccountId) -> Result<Option<Account>, RepoError> {
Ok(self.accounts.lock().unwrap().get(&id).cloned())
}
}
impl InMemoryJournalEntryRepository {
pub fn new(account_repository: Arc<dyn AccountRepository>) -> Self {
InMemoryJournalEntryRepository {
account_repository,
journal_entries: Mutex::new(HashMap::new()),
generator: Mutex::new(Generator::new()),
}
}
// Mint the next monotonic ULID, recovering from a same-tick random overflow.
fn next_ulid(&self) -> Ulid {
self.generator
.lock()
.unwrap()
.generate()
.unwrap_or_else(|overflow| overflow.commit_overflow_increment())
}
}
#[async_trait]
impl JournalEntryRepository for InMemoryJournalEntryRepository {
async fn create(&self, new: NewJournalEntry) -> Result<JournalEntry, RepoError> {
// 1. pure validation: balance, posting count, amounts
new.validate()?;
// 2. every referenced account must exist (no lock held across awaits)
for posting in &new.postings {
self.account_repository
.get(posting.account_id)
.await?
.ok_or(InvalidJournalEntry::AccountNotFound(posting.account_id))?;
}
// 3. mint ids and assemble the persisted entry
let id = JournalEntryId::from_ulid(self.next_ulid());
let postings: Vec<Posting> = new
.postings
.iter()
.map(|p| {
Posting::from_parts(
PostingId::from_ulid(self.next_ulid()),
p.posting_type,
p.account_id,
p.amount,
)
})
.collect();
let entry = JournalEntry::from_parts(id, new.date, postings, new.description);
// 4. persist — lock only now, after all awaits are done
self.journal_entries
.lock()
.unwrap()
.insert(id, entry.clone());
Ok(entry)
}
async fn get(&self, id: JournalEntryId) -> Result<Option<JournalEntry>, RepoError> {
Ok(self.journal_entries.lock().unwrap().get(&id).cloned())
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::DateTime;
fn new_account(
account_type: AccountType,
name: &str,
parent: Option<AccountId>,
) -> NewAccount {
NewAccount {
account_type,
name: name.into(),
description: String::new(),
parent,
}
}
// Seed the five standard chart-of-accounts roots, each with no parent.
async fn seed_roots(repo: &InMemoryAccountRepository) -> Vec<Account> {
let roots = [
(AccountType::Asset, "Assets"),
(AccountType::Liability, "Liabilities"),
(AccountType::Equity, "Equity"),
(AccountType::Revenue, "Revenue"),
(AccountType::Expense, "Expenses"),
];
let mut created = Vec::new();
for (account_type, name) in roots {
let account = repo
.create(new_account(account_type, name, None))
.await
.unwrap();
created.push(account);
}
created
}
#[tokio::test]
async fn seeds_five_distinct_root_accounts() {
let repo = InMemoryAccountRepository::default();
let roots = seed_roots(&repo).await;
assert_eq!(roots.len(), 5);
// each root's path is just its own id — depth 1, no parent segment
for root in &roots {
assert_eq!(root.path.depth(), 1);
}
// all five ids are distinct
let mut ids: Vec<AccountId> = roots.iter().map(|a| a.id()).collect();
ids.sort();
ids.dedup();
assert_eq!(ids.len(), 5);
}
#[tokio::test]
async fn child_nests_under_its_parent() {
let repo = InMemoryAccountRepository::default();
let roots = seed_roots(&repo).await;
let assets = &roots[0];
let cash = repo
.create(new_account(AccountType::Asset, "Cash", Some(assets.id())))
.await
.unwrap();
// the child's path was built from the parent's
assert!(assets.path.is_ancestor_of(&cash.path));
assert_eq!(cash.path.depth(), assets.path.depth() + 1);
// and a grandchild nests under both
let checking = repo
.create(new_account(AccountType::Asset, "Checking", Some(cash.id())))
.await
.unwrap();
assert!(assets.path.is_ancestor_of(&checking.path));
assert!(cash.path.is_ancestor_of(&checking.path));
assert_eq!(checking.path.depth(), 3);
}
#[tokio::test]
async fn get_returns_a_created_account() {
let repo = InMemoryAccountRepository::default();
let roots = seed_roots(&repo).await;
let assets = &roots[0];
let fetched = repo.get(assets.id()).await.unwrap();
assert_eq!(fetched.map(|a| a.id()), Some(assets.id()));
}
#[tokio::test]
async fn create_under_missing_parent_fails() {
let repo = InMemoryAccountRepository::default();
seed_roots(&repo).await;
// an id minted by a *different* repo is guaranteed absent from `repo`
let other = InMemoryAccountRepository::default();
let stranger = other
.create(new_account(AccountType::Asset, "Elsewhere", None))
.await
.unwrap();
let result = repo
.create(new_account(AccountType::Asset, "Orphan", Some(stranger.id())))
.await;
assert!(matches!(result, Err(RepoError::ParentNotFound(_))));
}
// ---- JournalEntryRepository ----
fn debit(account_id: AccountId, amount: u64) -> NewPosting {
NewPosting {
posting_type: PostingType::Debit,
account_id,
amount,
}
}
fn credit(account_id: AccountId, amount: u64) -> NewPosting {
NewPosting {
posting_type: PostingType::Credit,
account_id,
amount,
}
}
fn journal(postings: Vec<NewPosting>) -> NewJournalEntry {
NewJournalEntry {
date: DateTime::from_timestamp(0, 0).unwrap(),
description: "test".into(),
postings,
}
}
#[tokio::test]
async fn posts_and_retrieves_a_balanced_entry() {
let account_repo = Arc::new(InMemoryAccountRepository::default());
let cash = account_repo
.create(new_account(AccountType::Asset, "Cash", None))
.await
.unwrap();
let revenue = account_repo
.create(new_account(AccountType::Revenue, "Revenue", None))
.await
.unwrap();
let journal_repo = InMemoryJournalEntryRepository::new(account_repo.clone());
let entry = journal_repo
.create(journal(vec![
debit(cash.id(), 500_000),
credit(revenue.id(), 500_000),
]))
.await
.unwrap();
assert_eq!(entry.postings.len(), 2);
// round-trips through get by its minted id
let fetched = journal_repo.get(entry.id()).await.unwrap();
assert_eq!(fetched.map(|e| e.id()), Some(entry.id()));
}
#[tokio::test]
async fn unbalanced_entry_is_rejected() {
let account_repo = Arc::new(InMemoryAccountRepository::default());
let cash = account_repo
.create(new_account(AccountType::Asset, "Cash", None))
.await
.unwrap();
let revenue = account_repo
.create(new_account(AccountType::Revenue, "Revenue", None))
.await
.unwrap();
let journal_repo = InMemoryJournalEntryRepository::new(account_repo.clone());
let result = journal_repo
.create(journal(vec![
debit(cash.id(), 500_000),
credit(revenue.id(), 499_999),
]))
.await;
assert!(matches!(
result,
Err(RepoError::Invalid(InvalidJournalEntry::Unbalanced))
));
}
#[tokio::test]
async fn posting_to_unknown_account_is_rejected() {
let account_repo = Arc::new(InMemoryAccountRepository::default());
let cash = account_repo
.create(new_account(AccountType::Asset, "Cash", None))
.await
.unwrap();
// an id minted by a different repo is absent from account_repo
let other = InMemoryAccountRepository::default();
let stranger = other
.create(new_account(AccountType::Revenue, "Elsewhere", None))
.await
.unwrap();
let journal_repo = InMemoryJournalEntryRepository::new(account_repo.clone());
let result = journal_repo
.create(journal(vec![
debit(cash.id(), 100),
credit(stranger.id(), 100),
]))
.await;
assert!(matches!(
result,
Err(RepoError::Invalid(InvalidJournalEntry::AccountNotFound(_)))
));
}
}
|