| 1 | import type { Invite, InvitesOverview, User } from "@g1t/contracts"; |
| 2 | |
| 3 | import { type BringInto, bringIntoChoices } from "./invites"; |
| 4 | import { readCookie } from "./mission"; |
| 5 | import { billing, identity } from "./services.server"; |
| 6 | import { WORKSPACE_COOKIE, chosenWorkspace } from "./workspace-choice"; |
| 7 | |
| 8 | /** What the Invites section's forms answer. */ |
| 9 | export type InviteActionData = { inviteCreated?: Invite; inviteError?: string; inviteRevoked?: boolean } | null; |
| 10 | |
| 11 | /** The Invites section's "Bring them into" choices (`bringIntoChoices`). */ |
| 12 | export type BringIntoChoices = { options: BringInto[]; chosen: string; note: string | null }; |
| 13 | |
| 14 | /** A person's invites, or null when they cannot make any yet (email unconfirmed). */ |
| 15 | export async function loadInvites(user: User): Promise<InvitesOverview | null> { |
| 16 | if (!user.verified) return null; |
| 17 | return identity.listInvites(user).catch(() => null); |
| 18 | } |
| 19 | |
| 20 | /** |
| 21 | * The workspaces an invite can bring its person into, with the one the |
| 22 | * person is in (the shell's current workspace, from its cookie) chosen |
| 23 | * when it is one of them. A workspace whose plan cannot be checked is not |
| 24 | * offered: identity would refuse it. |
| 25 | */ |
| 26 | export async function loadBringInto(user: User, request: Request): Promise<BringIntoChoices> { |
| 27 | const memberships = user.workspaces ?? []; |
| 28 | const owned = memberships.filter((m) => m.role === "owner").map((m) => m.slug); |
| 29 | const free = owned.length > 0 ? await billing.freeWorkspaces(owned).catch(() => owned) : []; |
| 30 | const current = chosenWorkspace(memberships, readCookie(request.headers.get("cookie"), WORKSPACE_COOKIE))?.slug ?? null; |
| 31 | return bringIntoChoices(memberships, free, current); |
| 32 | } |
| 33 | |
| 34 | /** Handles the Invites section's intents; null for any other intent. */ |
| 35 | export async function inviteAction(user: User, form: FormData): Promise<InviteActionData | undefined> { |
| 36 | switch (form.get("intent")) { |
| 37 | case "create-invite": { |
| 38 | const email = String(form.get("email") ?? "").trim(); |
| 39 | const workspace = String(form.get("charge") ?? "").trim(); |
| 40 | const join = String(form.get("join") ?? "").trim(); |
| 41 | const result = await identity.createInvite(user, { |
| 42 | email: email || null, |
| 43 | workspace: workspace && workspace !== "mine" ? workspace : null, |
| 44 | join: join || null, |
| 45 | }); |
| 46 | return result.ok ? { inviteCreated: result.value } : { inviteError: result.error.message }; |
| 47 | } |
| 48 | case "revoke-invite": { |
| 49 | const result = await identity.revokeInvite(user, String(form.get("id") ?? "")); |
| 50 | return result.ok ? { inviteRevoked: true } : { inviteError: result.error.message }; |
| 51 | } |
| 52 | } |
| 53 | return undefined; |
| 54 | } |