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

main
ts 69 lines 2.44 KB
Raw
1 import * as Domain from "@alchemy.run/domain";
2 import * as Effect from "effect/Effect";
3 import * as Schema from "effect/Schema";
4 import { AccountId } from "../Account/Account.id.ts";
5 import { AccountSummary } from "../Account/AccountSummary.view.ts";
6 import { CurrentActor } from "../CurrentActor.context.ts";
7 import { Forbidden } from "../Forbidden.rejection.ts";
8 import { Cents } from "../Money.ts";
9 import { Session } from "../Session.middleware.ts";
10 import { Customer } from "./Customer.aggregate.ts";
11
12 type Balances = Readonly<Record<AccountId, number>>;
13
14 const without = (balances: Balances, id: AccountId): Balances => {
15 const { [id]: _removed, ...rest } = balances;
16 return rest;
17 };
18
19 /**
20 * A customer's accounts and balances, built from AccountSummary's events and
21 * the summary after each. An ownership change moves the account between
22 * dashboards.
23 */
24 export class CustomerDashboard extends Domain.View("CustomerDashboard", {
25 from: [Customer, AccountSummary],
26 key: Customer,
27 middleware: [Session],
28 rejects: [Forbidden],
29 keyOf: {
30 AccountSummary: ({ state }) => (state?.customerId ? Customer.ref(state.customerId) : undefined),
31 OwnerChanged: {
32 previous: ({ event }) => Customer.ref(event.previous),
33 current: ({ event }) => Customer.ref(event.customerId),
34 },
35 },
36 state: Schema.Struct({
37 name: Schema.NullOr(Schema.String),
38 balances: Schema.Record(AccountId, Cents),
39 }),
40 initial: { name: null, balances: {} },
41 evolve: {
42 CustomerRegistered: (d, e) => ({ ...d, name: e.name }),
43 OwnerChanged: {
44 previous: (d, _, { source }) => ({ ...d, balances: without(d.balances, source.id) }),
45 current: (d, _, { source, state }) => ({
46 ...d,
47 balances: { ...d.balances, [source.id]: state?.balance ?? 0 },
48 }),
49 },
50 AccountSummary: (d, _, { source, state }) => ({
51 ...d,
52 balances:
53 state && !state.closed
54 ? { ...d.balances, [source.id]: state.balance }
55 : without(d.balances, source.id),
56 }),
57 },
58 // Keyed by customer, so the key alone decides who may read it.
59 validate: Effect.fn(function* (request) {
60 const actor = yield* CurrentActor;
61 if (actor._tag === "Agent") return;
62 if (actor._tag !== "Customer" || request.key.id !== actor.customerId) {
63 return yield* new Forbidden({ reason: "that is not your dashboard" });
64 }
65 }),
66 computed: {
67 totalBalance: (d) => Object.values<number>(d.balances).reduce((a, b) => a + b, 0),
68 },
69 }) {}