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 { CurrentActor } from "../CurrentActor.context.ts"; |
| 5 | import { ConfirmRegistration, CustomerRegistered } from "./ConfirmRegistration.command.ts"; |
| 6 | import { CustomerId } from "./Customer.id.ts"; |
| 7 | import { |
| 8 | AlreadyRegistered, |
| 9 | NotTheCustomer, |
| 10 | RegisterCustomer, |
| 11 | RegistrationRequested, |
| 12 | } from "./RegisterCustomer.command.ts"; |
| 13 | import { RegistrationRejected, RejectRegistration } from "./RejectRegistration.command.ts"; |
| 14 | import { Username } from "./Username.ts"; |
| 15 | |
| 16 | const Profile = { name: Schema.String, username: Username }; |
| 17 | |
| 18 | /** |
| 19 | * A customer. Registration is a small saga: the request records the profile, |
| 20 | * `UsernameReservation` claims the username, then the registration is |
| 21 | * confirmed or rejected. |
| 22 | */ |
| 23 | export class Customer extends Domain.Aggregate("Customer", { |
| 24 | id: CustomerId, |
| 25 | state: Schema.Union([ |
| 26 | Schema.TaggedStruct("New", {}), |
| 27 | Schema.TaggedStruct("Pending", Profile), |
| 28 | Schema.TaggedStruct("Registered", Profile), |
| 29 | ]), |
| 30 | initial: { _tag: "New" }, |
| 31 | commands: [RegisterCustomer, ConfirmRegistration, RejectRegistration], |
| 32 | decide: { |
| 33 | RegisterCustomer: Effect.fn(function* (s, cmd, { id }) { |
| 34 | const actor = yield* CurrentActor; |
| 35 | if (actor._tag === "Customer" && actor.customerId !== id) return yield* new NotTheCustomer(); |
| 36 | if (s._tag !== "New") return yield* new AlreadyRegistered(); |
| 37 | return [new RegistrationRequested({ name: cmd.name, username: cmd.username })]; |
| 38 | }), |
| 39 | ConfirmRegistration: (s) => |
| 40 | s._tag === "Pending" ? [new CustomerRegistered({ name: s.name, username: s.username })] : [], |
| 41 | RejectRegistration: (s, cmd) => |
| 42 | s._tag === "Pending" |
| 43 | ? [new RegistrationRejected({ username: s.username, reason: cmd.reason })] |
| 44 | : [], |
| 45 | }, |
| 46 | evolve: { |
| 47 | RegistrationRequested: (_, e) => ({ |
| 48 | _tag: "Pending" as const, |
| 49 | name: e.name, |
| 50 | username: e.username, |
| 51 | }), |
| 52 | CustomerRegistered: (_, e) => ({ |
| 53 | _tag: "Registered" as const, |
| 54 | name: e.name, |
| 55 | username: e.username, |
| 56 | }), |
| 57 | RegistrationRejected: () => ({ _tag: "New" as const }), |
| 58 | }, |
| 59 | }) {} |