@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 503 lines 18.3 KB
Raw
1 import { Story } from "@alchemy.run/domain/Story";
2 import { describe, expect, it } from "@effect/vitest";
3 import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import { Account } from "../src/Account/Account.aggregate.ts";
6 import { mainAccountId } from "../src/Account/Account.id.ts";
7 import { AccountActivity } from "../src/Account/AccountActivity.view.ts";
8 import { AccountCard, CardChanged } from "../src/Account/AccountCard.stream.ts";
9 import { AccountSummary } from "../src/Account/AccountSummary.view.ts";
10 import { ChangeOwner, NotPermitted, OwnerChanged } from "../src/Account/ChangeOwner.command.ts";
11 import { AccountClosed, CloseAccount } from "../src/Account/CloseAccount.command.ts";
12 import { TransferCredited } from "../src/Account/CreditTransfer.command.ts";
13 import { TransferDebited } from "../src/Account/DebitTransfer.command.ts";
14 import { MoneyDeposited } from "../src/Account/DepositMoney.command.ts";
15 import { AccountFrozen, FreezeAccount } from "../src/Account/FreezeAccount.command.ts";
16 import { Frozen } from "../src/Account/Frozen.rejection.ts";
17 import { InsufficientFunds } from "../src/Account/InsufficientFunds.rejection.ts";
18 import { NotOwner } from "../src/Account/NotOwner.rejection.ts";
19 import { AccountOpened } from "../src/Account/OpenAccount.command.ts";
20 import {
21 RecordSettlement,
22 SettlementOnClosedAccount,
23 } from "../src/Account/RecordSettlement.command.ts";
24 import { TransferRefunded } from "../src/Account/RefundTransfer.command.ts";
25 import { Statement } from "../src/Account/Statement.view.ts";
26 import {
27 DailyLimitExceeded,
28 MoneyWithdrawn,
29 WithdrawMoney,
30 } from "../src/Account/WithdrawMoney.command.ts";
31 import { type Actor, agent, customer, system } from "../src/Actor.ts";
32 import { Bank, BankHandlers } from "../src/Bank.model.ts";
33 import { CurrentActor } from "../src/CurrentActor.context.ts";
34 import { UsernameClaimed } from "../src/Customer/ClaimUsername.command.ts";
35 import { CustomerRegistered } from "../src/Customer/ConfirmRegistration.command.ts";
36 import { Customer } from "../src/Customer/Customer.aggregate.ts";
37 import { CustomerId } from "../src/Customer/Customer.id.ts";
38 import { CustomerDashboard } from "../src/Customer/CustomerDashboard.view.ts";
39 import {
40 RegisterCustomer,
41 RegistrationRequested,
42 } from "../src/Customer/RegisterCustomer.command.ts";
43 import { RegistrationRejected } from "../src/Customer/RejectRegistration.command.ts";
44 import { Username } from "../src/Customer/Username.ts";
45 import { UsernameClaim } from "../src/Customer/UsernameClaim.aggregate.ts";
46 import { DailyOutflow } from "../src/Fraud/DailyOutflow.view.ts";
47 import { FraudCheck } from "../src/Fraud/FraudCheck.external.ts";
48 import { MemoryLedgerStore, memoryLedger } from "../src/Ledger/LedgerStore.ts";
49 import { Payments } from "../src/Settlement/Payments.external.ts";
50 import { AccountTransfers } from "../src/Transfer/AccountTransfers.view.ts";
51 import {
52 ApproveTransfer,
53 NotAwaitingApproval,
54 TransferApproved,
55 } from "../src/Transfer/ApproveTransfer.command.ts";
56 import { TransferCompleted } from "../src/Transfer/CompleteTransfer.command.ts";
57 import { TransferFailed } from "../src/Transfer/FailTransfer.command.ts";
58 import { RequestTransfer, TransferRequested } from "../src/Transfer/RequestTransfer.command.ts";
59 import { Transfer } from "../src/Transfer/Transfer.aggregate.ts";
60 import { TransferStatus } from "../src/Transfer/TransferStatus.view.ts";
61
62 const {
63 call,
64 clock,
65 emitted,
66 given,
67 provide,
68 rejected,
69 replied,
70 succeed,
71 state,
72 streamed,
73 then,
74 view,
75 when,
76 } = Story;
77
78 /** Act as this actor for the following commands, as their session middleware would. */
79 const as = (actor: Actor) => provide(CurrentActor, actor);
80
81 const story = Story.make(Bank, {
82 layer: BankHandlers.pipe(Layer.provide(MemoryLedgerStore)),
83 stub: [FraudCheck, Payments],
84 });
85
86 const a1 = Account.ref("a-1");
87 const a2 = Account.ref("a-2");
88 const c1 = Customer.ref("c-1");
89 const c2 = Customer.ref("c-2");
90 const t1 = Transfer.ref("t-1");
91 const sam = customer("c-1");
92 const alex = customer("c-2");
93 const samsName = Username.make("sam");
94 const opened = (customerId = "c-1") =>
95 new AccountOpened({ customerId: CustomerId.make(customerId), owner: "sam" });
96
97 it.effect("registering claims the username, then opens a main account", () =>
98 story(
99 as(sam),
100 when(c1, new RegisterCustomer({ name: "sam", username: samsName })),
101 then(
102 c1,
103 new RegistrationRequested({ name: "sam", username: samsName }),
104 new CustomerRegistered({ name: "sam", username: samsName }),
105 ),
106 then(UsernameClaim.ref("sam"), new UsernameClaimed({ customerId: c1.id })),
107 then(
108 Account.ref(mainAccountId(CustomerId.make("c-1"))),
109 new AccountOpened({ customerId: c1.id, owner: "sam" }),
110 ),
111 view(AccountSummary, Account.ref("c-1-main"), {
112 customerId: c1.id,
113 owner: "sam",
114 balance: 0,
115 frozen: false,
116 }),
117 view(CustomerDashboard, c1, (d) => expect(d.balances).toEqual({ ["c-1-main"]: 0 } as any)),
118 ),
119 );
120
121 it.effect("a taken username rejects the registration, and nothing else happens", () =>
122 story(
123 given(UsernameClaim.ref("sam"), new UsernameClaimed({ customerId: c1.id })),
124 as(alex),
125 when(c2, new RegisterCustomer({ name: "alex", username: samsName })),
126 then(
127 c2,
128 new RegistrationRequested({ name: "alex", username: samsName }),
129 new RegistrationRejected({ username: samsName, reason: "username taken" }),
130 ),
131 then(Account.ref(mainAccountId(CustomerId.make("c-2")))),
132 // The customer can try again with another name.
133 when(c2, new RegisterCustomer({ name: "alex", username: Username.make("alex") })),
134 then(
135 c2,
136 new RegistrationRequested({ name: "alex", username: Username.make("alex") }),
137 new CustomerRegistered({ name: "alex", username: Username.make("alex") }),
138 ),
139 then(UsernameClaim.ref("alex"), new UsernameClaimed({ customerId: c2.id })),
140 then(
141 Account.ref(mainAccountId(CustomerId.make("c-2"))),
142 new AccountOpened({ customerId: c2.id, owner: "alex" }),
143 ),
144 ),
145 );
146
147 it.effect("withdraw replies with the new balance and updates projections", () =>
148 story(
149 given(a1, opened(), new MoneyDeposited({ amount: 100, balanceAfter: 100 })),
150 as(sam),
151 when(a1, new WithdrawMoney({ amount: 30 })),
152 then(a1, new MoneyWithdrawn({ amount: 30, balanceAfter: 70 })),
153 replied({ balance: 70 }),
154 view(AccountSummary, a1, { balance: 70 }),
155 emitted(Statement, a1, [
156 { kind: "deposit", amount: 100, balance: 100 },
157 { kind: "withdrawal", amount: 30, balance: 70 },
158 ]),
159 ),
160 );
161
162 it.effect("overdraft is rejected with evidence", () =>
163 story(
164 given(a1, opened(), new MoneyDeposited({ amount: 50, balanceAfter: 50 })),
165 as(sam),
166 when(a1, new WithdrawMoney({ amount: 80 })),
167 rejected(new InsufficientFunds({ balance: 50, requested: 80 })),
168 ),
169 );
170
171 it.effect("a customer can't withdraw from someone else's account", () =>
172 story(
173 given(a1, opened("c-1"), new MoneyDeposited({ amount: 100, balanceAfter: 100 })),
174 as(alex),
175 when(a1, new WithdrawMoney({ amount: 30 })),
176 rejected(new NotOwner()),
177 ),
178 );
179
180 it.effect("the daily limit uses the story clock", () =>
181 story(
182 clock("2026-10-09T09:00:00Z"),
183 given(a1, opened(), new MoneyDeposited({ amount: 300_000, balanceAfter: 300_000 })),
184 as(sam),
185 when(a1, new WithdrawMoney({ amount: 40_000 })),
186 when(a1, new WithdrawMoney({ amount: 40_000 })),
187 call(FraudCheck.score, { accountId: a1.id, amount: 80_000 }),
188 succeed(FraudCheck.score, { risk: 0.1 }),
189 when(a1, new WithdrawMoney({ amount: 30_000 })),
190 rejected(new DailyLimitExceeded({ remaining: 20_000 })),
191 clock("2026-10-10T00:00:01Z"),
192 when(a1, new WithdrawMoney({ amount: 30_000 })),
193 then(
194 a1,
195 new MoneyWithdrawn({ amount: 40_000, balanceAfter: 260_000 }),
196 new MoneyWithdrawn({ amount: 40_000, balanceAfter: 220_000 }),
197 new MoneyWithdrawn({ amount: 30_000, balanceAfter: 190_000 }),
198 ),
199 ),
200 );
201
202 it.effect("freezing twice records nothing", () =>
203 story(
204 given(a1, opened(), new AccountFrozen({ reason: "kyc", by: agent("support-7") })),
205 as(agent("support-7")),
206 when(a1, new FreezeAccount({ reason: "again" })),
207 then(a1),
208 state(a1, (s) => expect(s).toMatchObject({ frozen: "kyc" })),
209 ),
210 );
211
212 it.effect(
213 "a risky withdrawal freezes the account (an external system call suspends until answered)",
214 () =>
215 story(
216 given(a1, opened(), new MoneyDeposited({ amount: 90_000, balanceAfter: 90_000 })),
217 as(sam),
218 when(a1, new WithdrawMoney({ amount: 60_000 })),
219 then(a1, new MoneyWithdrawn({ amount: 60_000, balanceAfter: 30_000 })),
220 call(FraudCheck.score, { accountId: a1.id, amount: 60_000 }),
221 succeed(FraudCheck.score, { risk: 0.95 }),
222 then(a1, new AccountFrozen({ reason: "fraud risk 0.95", by: system("FraudReview") })),
223 when(a1, new WithdrawMoney({ amount: 10 })),
224 rejected(new Frozen({ reason: "fraud risk 0.95" })),
225 ),
226 );
227
228 it.effect(
229 "split withdrawals that cross the daily threshold are reviewed (a policy on a view)",
230 () =>
231 story(
232 given(a1, opened(), new MoneyDeposited({ amount: 90_000, balanceAfter: 90_000 })),
233 as(sam),
234 when(a1, new WithdrawMoney({ amount: 30_000 })),
235 when(a1, new WithdrawMoney({ amount: 30_000 })),
236 then(
237 a1,
238 new MoneyWithdrawn({ amount: 30_000, balanceAfter: 60_000 }),
239 new MoneyWithdrawn({ amount: 30_000, balanceAfter: 30_000 }),
240 ),
241 emitted(DailyOutflow, a1, [{ day: "2026-01-01", total: 60_000 }]),
242 call(FraudCheck.score, { accountId: a1.id, amount: 60_000 }),
243 succeed(FraudCheck.score, { risk: 0.1 }),
244 then(a1),
245 ),
246 );
247
248 it.effect("race: the account is closed while the fraud check is pending", () =>
249 story(
250 given(a1, opened(), new MoneyDeposited({ amount: 60_000, balanceAfter: 60_000 })),
251 as(sam),
252 when(a1, new WithdrawMoney({ amount: 60_000 })),
253 call(FraudCheck.score, { accountId: a1.id, amount: 60_000 }),
254 when(a1, new CloseAccount()),
255 then(a1, new MoneyWithdrawn({ amount: 60_000, balanceAfter: 0 }), new AccountClosed()),
256 succeed(FraudCheck.score, { risk: 0.95 }),
257 then(a1),
258 view(AccountSummary, a1, { closed: true }),
259 ),
260 );
261
262 it.effect("a transfer completes: the process manager drives both accounts", () =>
263 story(
264 given(a1, opened("c-1"), new MoneyDeposited({ amount: 100, balanceAfter: 100 })),
265 given(a2, opened("c-2")),
266 as(sam),
267 when(t1, new RequestTransfer({ from: a1.id, to: a2.id, amount: 40 })),
268 then(
269 t1,
270 new TransferRequested({
271 transferId: t1.id,
272 from: a1.id,
273 to: a2.id,
274 amount: 40,
275 requestedBy: sam,
276 needsApproval: false,
277 }),
278 ),
279 then(a1, new TransferDebited({ transferId: t1.id, amount: 40, balanceAfter: 60 })),
280 then(a2, new TransferCredited({ transferId: t1.id, amount: 40, balanceAfter: 40 })),
281 then(t1, new TransferCompleted({ transferId: t1.id })),
282 view(TransferStatus, t1, (v) => expect(TransferStatus.computed.status(v)).toBe("completed")),
283 emitted(AccountTransfers, a1, [{ transferId: t1.id, amount: 40, direction: "out" }]),
284 emitted(AccountTransfers, a2, [{ transferId: t1.id, amount: 40, direction: "in" }]),
285 ),
286 );
287
288 it.effect("a customer can't move money out of someone else's account with a transfer", () =>
289 story(
290 given(a1, opened("c-1"), new MoneyDeposited({ amount: 100, balanceAfter: 100 })),
291 given(a2, opened("c-2")),
292 as(alex),
293 when(t1, new RequestTransfer({ from: a1.id, to: a2.id, amount: 40 })),
294 then(
295 t1,
296 new TransferRequested({
297 transferId: t1.id,
298 from: a1.id,
299 to: a2.id,
300 amount: 40,
301 requestedBy: alex,
302 needsApproval: false,
303 }),
304 ),
305 then(a1),
306 then(t1, new TransferFailed({ transferId: t1.id, reason: "not your account" })),
307 ),
308 );
309
310 it.effect("a large transfer waits for a support agent's approval", () =>
311 story(
312 given(a1, opened("c-1"), new MoneyDeposited({ amount: 100_000, balanceAfter: 100_000 })),
313 given(a2, opened("c-2")),
314 as(sam),
315 when(t1, new RequestTransfer({ from: a1.id, to: a2.id, amount: 20_000 })),
316 then(
317 t1,
318 new TransferRequested({
319 transferId: t1.id,
320 from: a1.id,
321 to: a2.id,
322 amount: 20_000,
323 requestedBy: sam,
324 needsApproval: true,
325 }),
326 ),
327 then(a1),
328 view(TransferStatus, t1, (v) =>
329 expect(TransferStatus.computed.status(v)).toBe("awaiting-approval"),
330 ),
331 as(agent("support-7")),
332 when(t1, new ApproveTransfer()),
333 then(
334 t1,
335 new TransferApproved({
336 transferId: t1.id,
337 from: a1.id,
338 to: a2.id,
339 amount: 20_000,
340 requestedBy: sam,
341 approvedBy: agent("support-7"),
342 }),
343 new TransferCompleted({ transferId: t1.id }),
344 ),
345 then(a1, new TransferDebited({ transferId: t1.id, amount: 20_000, balanceAfter: 80_000 })),
346 then(a2, new TransferCredited({ transferId: t1.id, amount: 20_000, balanceAfter: 20_000 })),
347 ),
348 );
349
350 it.effect("an unapproved transfer expires when its approval window closes", () =>
351 story(
352 clock("2026-01-01T09:00:00Z"),
353 given(a1, opened("c-1"), new MoneyDeposited({ amount: 100_000, balanceAfter: 100_000 })),
354 given(a2, opened("c-2")),
355 as(sam),
356 when(t1, new RequestTransfer({ from: a1.id, to: a2.id, amount: 20_000 })),
357 then(
358 t1,
359 new TransferRequested({
360 transferId: t1.id,
361 from: a1.id,
362 to: a2.id,
363 amount: 20_000,
364 requestedBy: sam,
365 needsApproval: true,
366 }),
367 ),
368 clock("2026-01-02T08:59:00Z"),
369 then(t1),
370 clock("2026-01-02T09:00:00Z"),
371 then(t1, new TransferFailed({ transferId: t1.id, reason: "not approved in time" })),
372 // Approval and expiry race on the Transfer; expiry won, so approval is too late.
373 as(agent("support-7")),
374 when(t1, new ApproveTransfer()),
375 rejected(new NotAwaitingApproval()),
376 then(a1),
377 ),
378 );
379
380 it.effect("a transfer to a closed account is compensated", () =>
381 story(
382 given(a1, opened("c-1"), new MoneyDeposited({ amount: 100, balanceAfter: 100 })),
383 given(a2, opened("c-2"), new AccountClosed()),
384 as(sam),
385 when(t1, new RequestTransfer({ from: a1.id, to: a2.id, amount: 40 })),
386 then(
387 t1,
388 new TransferRequested({
389 transferId: t1.id,
390 from: a1.id,
391 to: a2.id,
392 amount: 40,
393 requestedBy: sam,
394 needsApproval: false,
395 }),
396 ),
397 then(
398 a1,
399 new TransferDebited({ transferId: t1.id, amount: 40, balanceAfter: 60 }),
400 new TransferRefunded({ transferId: t1.id, amount: 40, balanceAfter: 100 }),
401 ),
402 then(t1, new TransferFailed({ transferId: t1.id, reason: "destination account not open" })),
403 view(TransferStatus, t1, { amount: 40, debited: true, credited: false, refunded: true }),
404 ),
405 );
406
407 it.effect("a settlement on a closed account can't be rejected, so it is refunded", () =>
408 story(
409 given(a1, opened(), new AccountClosed()),
410 when(a1, new RecordSettlement({ settlementId: "st_1", amount: 500 })),
411 then(a1, new SettlementOnClosedAccount({ settlementId: "st_1", amount: 500 })),
412 call(Payments.refund, { settlementId: "st_1", amount: 500 }),
413 succeed(Payments.refund, { refundId: "re_1" }),
414 emitted(AccountActivity, a1, (entries) =>
415 expect(entries.at(-1)?.event._tag).toBe("SettlementOnClosedAccount"),
416 ),
417 ),
418 );
419
420 it.effect("only agents reassign accounts, and the dashboards re-key", () =>
421 story(
422 given(c1, new CustomerRegistered({ name: "sam", username: samsName })),
423 given(c2, new CustomerRegistered({ name: "alex", username: Username.make("alex") })),
424 given(a1, opened("c-1"), new MoneyDeposited({ amount: 100, balanceAfter: 100 })),
425 view(CustomerDashboard, c1, (d) => expect(d.balances).toEqual({ ["a-1"]: 100 } as any)),
426 as(sam),
427 when(a1, new ChangeOwner({ customerId: c2.id })),
428 rejected(new NotPermitted()),
429 as(agent("support-7")),
430 when(a1, new ChangeOwner({ customerId: c2.id })),
431 then(a1, new OwnerChanged({ previous: c1.id, customerId: c2.id, by: agent("support-7") })),
432 view(CustomerDashboard, c1, (d) => expect(d.balances).toEqual({} as any)),
433 view(CustomerDashboard, c2, (d) =>
434 expect(CustomerDashboard.computed.totalBalance(d)).toBe(100),
435 ),
436 ),
437 );
438
439 it.effect("an unasserted rejection fails the story", () =>
440 story(
441 given(a1, opened(), new MoneyDeposited({ amount: 1, balanceAfter: 1 })),
442 as(sam),
443 when(a1, new WithdrawMoney({ amount: 5 })),
444 ).pipe(
445 Effect.flip,
446 Effect.map((failure) => expect(failure.message).toMatch(/InsufficientFunds/)),
447 ),
448 );
449
450 it.effect("an unanswered external system call fails the story", () =>
451 story(
452 given(a1, opened(), new MoneyDeposited({ amount: 90_000, balanceAfter: 90_000 })),
453 as(sam),
454 when(a1, new WithdrawMoney({ amount: 60_000 })),
455 ).pipe(
456 Effect.flip,
457 Effect.map((failure) => expect(failure.message).toMatch(/unanswered external system calls/)),
458 ),
459 );
460
461 // ---------------------------------------------------------------- projections
462
463 /** A story whose projections write a ledger the test can read. */
464 const ledgerStory = Story.make(Bank, {
465 layer: BankHandlers,
466 stub: [FraudCheck, Payments],
467 });
468
469 it.effect("the Ledger projection records each movement in a store outside the model", () =>
470 Effect.gen(function* () {
471 const ledger = memoryLedger();
472 yield* ledgerStory(
473 given(a1, opened(), new MoneyDeposited({ amount: 10_000, balanceAfter: 10_000 })),
474 as(sam),
475 when(a1, new WithdrawMoney({ amount: 2_500 })),
476 then(a1, new MoneyWithdrawn({ amount: 2_500, balanceAfter: 7_500 })),
477 ).pipe(Effect.provide(ledger.layer));
478 const rows = yield* ledger.forAccount("a-1");
479 expect(rows.map((row) => [row.kind, row.amount, row.balanceAfter])).toEqual([
480 ["MoneyDeposited", 10_000, 10_000],
481 ["MoneyWithdrawn", 2_500, 7_500],
482 ]);
483 }),
484 );
485
486 it.effect("the AccountCards projection appends a card on every balance change", () =>
487 story(
488 given(a1, opened(), new MoneyDeposited({ amount: 10_000, balanceAfter: 10_000 })),
489 streamed(
490 AccountCard,
491 a1,
492 new CardChanged({ customerId: c1.id, owner: "sam", balance: 10_000, frozen: false }),
493 ),
494 as(sam),
495 when(a1, new WithdrawMoney({ amount: 2_500 })),
496 then(a1, new MoneyWithdrawn({ amount: 2_500, balanceAfter: 7_500 })),
497 streamed(
498 AccountCard,
499 a1,
500 new CardChanged({ customerId: c1.id, owner: "sam", balance: 7_500, frozen: false }),
501 ),
502 ),
503 );