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 Schema from "effect/Schema"; |
| 4 | import { Account } from "../Account/Account.aggregate.ts"; |
| 5 | import { Cents } from "../Money.ts"; |
| 6 | |
| 7 | /** Daily outflow above which an account's activity is reviewed, in cents. */ |
| 8 | export const REVIEW_THRESHOLD = 50_000; |
| 9 | |
| 10 | /** An account's money out today crossed {@link REVIEW_THRESHOLD}. */ |
| 11 | export class DailyOutflowExceeded extends Domain.Event("DailyOutflowExceeded", { |
| 12 | day: Schema.String, |
| 13 | total: Cents, |
| 14 | }) {} |
| 15 | |
| 16 | const add = ( |
| 17 | s: { readonly day: string; readonly total: number }, |
| 18 | amount: number, |
| 19 | at: DateTime.Utc, |
| 20 | ) => { |
| 21 | const day = DateTime.formatIsoDateUtc(at); |
| 22 | return { day, total: (s.day === day ? s.total : 0) + amount }; |
| 23 | }; |
| 24 | |
| 25 | const crossed = ( |
| 26 | _: unknown, |
| 27 | { |
| 28 | before, |
| 29 | after, |
| 30 | }: { |
| 31 | readonly before: { readonly total: number }; |
| 32 | readonly after: { readonly day: string; readonly total: number } | null; |
| 33 | }, |
| 34 | ) => |
| 35 | after && before.total < REVIEW_THRESHOLD && after.total >= REVIEW_THRESHOLD |
| 36 | ? new DailyOutflowExceeded({ day: after.day, total: after.total }) |
| 37 | : undefined; |
| 38 | |
| 39 | /** |
| 40 | * Money out of an account per day. It emits a synthetic event when the day's |
| 41 | * total crosses the threshold, so split withdrawals are caught too. |
| 42 | */ |
| 43 | export class DailyOutflow extends Domain.View("DailyOutflow", { |
| 44 | from: [Account], |
| 45 | key: Account, |
| 46 | state: Schema.Struct({ day: Schema.String, total: Cents }), |
| 47 | initial: { day: "", total: 0 }, |
| 48 | evolve: { |
| 49 | MoneyWithdrawn: (s, e, { at }) => add(s, e.amount, at), |
| 50 | TransferDebited: (s, e, { at }) => add(s, e.amount, at), |
| 51 | }, |
| 52 | events: [DailyOutflowExceeded], |
| 53 | emit: { |
| 54 | MoneyWithdrawn: crossed, |
| 55 | TransferDebited: crossed, |
| 56 | }, |
| 57 | }) {} |