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 Effect from "effect/Effect"; |
| 3 | import * as Schema from "effect/Schema"; |
| 4 | import { CustomerId } from "../Customer/Customer.id.ts"; |
| 5 | import { Cents } from "../Money.ts"; |
| 6 | import { Session } from "../Session.middleware.ts"; |
| 7 | import { Account } from "./Account.aggregate.ts"; |
| 8 | import { mustOwn } from "./mustOwn.ts"; |
| 9 | import { NotOwner } from "./NotOwner.rejection.ts"; |
| 10 | |
| 11 | const setBalance = <V extends { balance: number }>( |
| 12 | v: V, |
| 13 | e: { readonly balanceAfter: number }, |
| 14 | ): V => ({ |
| 15 | ...v, |
| 16 | balance: e.balanceAfter, |
| 17 | }); |
| 18 | |
| 19 | /** |
| 20 | * The current balance and status of one account. It declares no events, so |
| 21 | * it emits every event it applies, each with the summary after it. |
| 22 | */ |
| 23 | export class AccountSummary extends Domain.View("AccountSummary", { |
| 24 | from: [Account], |
| 25 | key: Account, |
| 26 | middleware: [Session], |
| 27 | rejects: [NotOwner], |
| 28 | state: Schema.Struct({ |
| 29 | customerId: Schema.NullOr(CustomerId), |
| 30 | owner: Schema.NullOr(Schema.String), |
| 31 | balance: Cents, |
| 32 | frozen: Schema.Boolean, |
| 33 | closed: Schema.Boolean, |
| 34 | }), |
| 35 | initial: { customerId: null, owner: null, balance: 0, frozen: false, closed: false }, |
| 36 | evolve: { |
| 37 | AccountOpened: (v, e) => ({ ...v, customerId: e.customerId, owner: e.owner }), |
| 38 | OwnerChanged: (v, e) => ({ ...v, customerId: e.customerId }), |
| 39 | MoneyDeposited: setBalance, |
| 40 | MoneyWithdrawn: setBalance, |
| 41 | TransferDebited: setBalance, |
| 42 | TransferCredited: setBalance, |
| 43 | TransferRefunded: setBalance, |
| 44 | SettlementReceived: setBalance, |
| 45 | AccountFrozen: (v) => ({ ...v, frozen: true }), |
| 46 | AccountClosed: (v) => ({ ...v, closed: true }), |
| 47 | }, |
| 48 | // Re-run on every change while watched: a reassigned account ends the watch with NotOwner. |
| 49 | validate: Effect.fn(function* (_request, summary) { |
| 50 | yield* mustOwn(summary?.customerId ?? null); |
| 51 | }), |
| 52 | }) {} |