The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Domain from "@alchemy.run/domain"; |
| 2 | import * as DateTime from "effect/DateTime"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import { Account } from "../Account/Account.aggregate.ts"; |
| 5 | import { TransferCredited } from "../Account/CreditTransfer.command.ts"; |
| 6 | import { TransferDebited } from "../Account/DebitTransfer.command.ts"; |
| 7 | import { MoneyDeposited } from "../Account/DepositMoney.command.ts"; |
| 8 | import { SettlementReceived } from "../Account/RecordSettlement.command.ts"; |
| 9 | import { TransferRefunded } from "../Account/RefundTransfer.command.ts"; |
| 10 | import { MoneyWithdrawn } from "../Account/WithdrawMoney.command.ts"; |
| 11 | import { LedgerStore } from "./LedgerStore.ts"; |
| 12 | |
| 13 | /** Every money movement, one row each, in a database outside the model. */ |
| 14 | export class Ledger extends Domain.Projection("Ledger", { |
| 15 | from: [Account], |
| 16 | key: Account, |
| 17 | on: [ |
| 18 | MoneyDeposited, |
| 19 | MoneyWithdrawn, |
| 20 | TransferDebited, |
| 21 | TransferCredited, |
| 22 | TransferRefunded, |
| 23 | SettlementReceived, |
| 24 | ], |
| 25 | }) {} |
| 26 | |
| 27 | /** Writes each batch of an account's movements in one database round-trip. */ |
| 28 | export const LedgerLive = Ledger.toLayer( |
| 29 | Effect.gen(function* () { |
| 30 | const store = yield* LedgerStore; |
| 31 | return Effect.fn(function* (batch) { |
| 32 | yield* store.record( |
| 33 | batch.map(({ key, event, envelope }) => ({ |
| 34 | id: `${envelope.stream}:${envelope.seq}`, |
| 35 | accountId: key.id, |
| 36 | kind: event._tag, |
| 37 | amount: event.amount, |
| 38 | balanceAfter: event.balanceAfter, |
| 39 | at: DateTime.toEpochMillis(envelope.at), |
| 40 | })), |
| 41 | ); |
| 42 | }); |
| 43 | }), |
| 44 | { batch: { size: 100, wait: "1 second" } }, |
| 45 | ); |