@odla-ai/chapter 0.20.2 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/worker.ts","../../src/worker-context.ts","../../src/auth.ts","../../src/worker-routes.ts","../../src/clerk.ts","../../src/member.ts","../../src/network.ts","../../src/scheduling.ts","../../src/session.ts","../../src/email.ts","../../src/notify.ts","../../src/worker-routes-schedule.ts","../../src/pipeline.ts","../../src/payments.ts","../../src/payments-stripe.ts","../../src/worker-routes-payments.ts","../../src/worker-routes-admin.ts","../../src/reconcile.ts","../../src/clerk-roles.ts","../../src/crm-sync.ts","../../src/worker-routes-admin-people.ts","../../src/series.ts","../../src/worker-routes-admin-dashboard.ts","../../src/worker-routes-admin-lifecycle.ts","../../src/worker-routes-admin-comms.ts","../../src/worker-routes-network.ts"],"sourcesContent":["// chapterWorker — the Cloudflare Worker for a chapter/hub site. This entry\n// (@odla-ai/chapter/worker) is separate from the core so the CLI can load\n// odla.config.mjs without pulling in worker-runtime deps.\n//\n// The worker is the ONLY thing that talks to odla-db, using the app key\n// (ODLA_API_KEY), which bypasses the deny-all rules. Browsers never receive a\n// db credential. Access is admin-only: a request is authorized when its Clerk\n// session JWT verifies AND the user's role (a JWT claim, or a row in the\n// Studio-seeded `admins` allowlist) is an admin rung.\n//\n// The env typing + auth plumbing live in ./worker-context; the route handlers in\n// ./worker-routes. This entry only builds the context and runs the routes in\n// order — first match wins, else the static site (ASSETS).\n//\n// hub mode routes: GET /api/config, GET /api/me, /api/crm/*, POST\n// /api/network/shared, else ASSETS. chapter mode adds the public member surface:\n// GET /api/join-config and POST /api/applications (idempotent).\nimport { createWorkerContext } from \"./worker-context\";\nimport type { ChapterEnv, ChapterWorkerOptions, Route } from \"./worker-context\";\nimport { handleConfig, handleCrm, handleHealth, handleMe, handleMember, handleNetworkShared } from \"./worker-routes\";\nimport { handleSchedule } from \"./worker-routes-schedule\";\nimport { handlePayments } from \"./worker-routes-payments\";\nimport { handleAdminMeetings, handleAdminScheduling } from \"./worker-routes-admin\";\nimport { handleAdminCrmSync, handleAdminPeople, handleAdminPeopleAccess, handleAdminPeopleRole } from \"./worker-routes-admin-people\";\nimport { handleAdminDashboard, handleAdminBilling } from \"./worker-routes-admin-dashboard\";\nimport { handleAdminMeetingReschedule, handleAdminMeetingCancel, handleAdminApprove, handleAdminRefund, handleAdminApplicationPatch } from \"./worker-routes-admin-lifecycle\";\nimport { handleAdminGroupEmail, handleAdminEmailLog, handleAdminEmailTest, handleAdminComms } from \"./worker-routes-admin-comms\";\nimport { handleAdminNetworkPush, handleAdminNetworkTargets } from \"./worker-routes-network\";\n\n// The route seam: a wrapping worker can build its own routes + reuse chapter's\n// auth by composing against these.\nexport { createWorkerContext } from \"./worker-context\";\nexport type { ChapterEnv, ChapterWorkerOptions, WorkerContext, Route } from \"./worker-context\";\n\n// First-match-wins order. Host routes (options.routes) run BEFORE these.\nconst BUILTIN_ROUTES: Route[] = [\n handleHealth,\n handleConfig,\n handleMe,\n handleCrm,\n handleNetworkShared,\n handleMember,\n handleSchedule,\n handlePayments,\n handleAdminMeetings,\n handleAdminScheduling,\n // Roster + identity\n handleAdminPeople,\n handleAdminPeopleAccess,\n handleAdminPeopleRole,\n handleAdminCrmSync,\n // Aggregation\n handleAdminDashboard,\n handleAdminBilling,\n // Lifecycle actions\n handleAdminMeetingReschedule,\n handleAdminMeetingCancel,\n handleAdminApprove,\n handleAdminRefund,\n handleAdminApplicationPatch,\n // Email + comms\n handleAdminGroupEmail,\n handleAdminEmailLog,\n handleAdminEmailTest,\n handleAdminComms,\n // Leader → follower record delivery\n handleAdminNetworkTargets,\n handleAdminNetworkPush,\n];\n\n/**\n * Build the Cloudflare `ExportedHandler` for a chapter/hub site: Clerk-JWT\n * verification, the source-aware admin gate, the mounted @odla-ai/crm routes, the\n * hub→chapter network projection, and the static-asset fallback. Hub mode serves\n * /api/health, /api/config, /api/me, /api/crm/*, /api/network/shared; chapter mode\n * adds the public member surface (join/apply/pay/book) and the admin surface\n * (/api/admin/*).\n *\n * A wrapping site adds its own routes via `options.routes` — each receives the\n * same {@link WorkerContext} the built-ins get (so it reuses chapter's JWT\n * verify, db client, and role resolution instead of duplicating them), and runs\n * BEFORE the built-ins so it can override or alias a path.\n *\n * Observability is a host concern, not a chapter dependency. To trace, wrap the\n * result in your worker entry — `export default withObservability(chapterWorker(\n * { chapter }))` — with `withObservability` from `@odla-ai/o11y`. Sites that\n * don't run o11y bundle `@odla-ai/chapter/worker` without installing it.\n */\nexport function chapterWorker(options: ChapterWorkerOptions) {\n const ctx = createWorkerContext(options);\n const routes: Route[] = [...(options.routes ?? []), ...BUILTIN_ROUTES];\n return {\n async fetch(req: Request, env: ChapterEnv): Promise<Response> {\n const url = new URL(req.url);\n for (const route of routes) {\n const res = await route(req, url, env, ctx);\n if (res) return res;\n }\n // Everything else is the static site.\n return env.ASSETS.fetch(req);\n },\n };\n}\n","// Shared context for the chapter Worker: env typing, the odla-db admin client,\n// Clerk-JWT verification, and the source-aware auth helpers. Split out of\n// worker.ts so the route modules share ONE construction of the caches (public\n// config + JWKS) per site, and the worker entry stays a thin composer under the\n// per-file LOC cap. Nothing here is re-exported from the worker entry, so the\n// public `@odla-ai/chapter/worker` surface is unchanged by the split.\nimport { initAdmin } from \"@odla-ai/db\";\nimport { createRemoteJWKSet, jwtVerify } from \"jose\";\nimport { isAdminRole, roleFromClaim } from \"./auth\";\nimport type { Chapter } from \"./types\";\n\n/** The Cloudflare SEND_EMAIL binding payload. */\nexport interface EmailPayload {\n from: string;\n to: string[];\n subject: string;\n text?: string;\n html?: string;\n replyTo?: string;\n headers?: Record<string, string>;\n}\n\n/** The Worker env a chapter site provides (wrangler vars + the ODLA_API_KEY\n * secret pushed by provision). */\nexport interface ChapterEnv {\n ASSETS: { fetch(req: Request): Promise<Response> };\n ODLA_ENDPOINT: string;\n ODLA_TENANT: string;\n ODLA_PLATFORM: string;\n ODLA_APP_ID: string;\n ODLA_ENV: string;\n ODLA_API_KEY: string;\n SEND_EMAIL?: { send(payload: EmailPayload): Promise<{ messageId: string }> };\n EMAIL_FROM?: string;\n}\n\n/** Options for `chapterWorker`. */\nexport interface ChapterWorkerOptions {\n chapter: Chapter;\n /** CRM mount point. Default \"/api/crm\". */\n crmBasePath?: string;\n /** Host routes, tried BEFORE the built-ins — so a wrapping site can add its own\n * routes (or override/alias a built-in path) and reuse chapter's auth via the\n * shared {@link WorkerContext}, instead of re-verifying JWTs itself. */\n routes?: Route[];\n}\n\n/** The registry public-config a site reads to boot Clerk sign-in. */\nexport type PublicConfig = { env?: string; clerkPublishableKey?: string | null; issuer?: string | null };\n/** The odla-db admin client type. */\nexport type Db = ReturnType<typeof initAdmin>;\n\n/** A verified session: the Clerk `sub`, optional email, and the raw JWT payload\n * (so the role claim can be read for auth source \"claim\"). */\nexport interface Verified {\n userId: string;\n email?: string;\n payload: Record<string, unknown>;\n}\n\n/** JSON response helper. */\nexport const json = (body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } });\n\n/**\n * Build the per-site Worker context: env-independent helpers closing over the\n * public-config and JWKS caches, plus the source-aware auth gate (JWT claim or\n * the odla-db `admins` allowlist). Constructed once per `chapterWorker` and\n * shared by every route module.\n */\nexport function createWorkerContext(options: ChapterWorkerOptions) {\n const { chapter } = options;\n const auth = chapter.auth;\n const crmBase = options.crmBasePath ?? \"/api/crm\";\n\n let publicConfigCache: { value: PublicConfig; at: number } | null = null;\n const jwksByIssuer = new Map<string, ReturnType<typeof createRemoteJWKSet>>();\n\n async function getPublicConfig(env: ChapterEnv): Promise<PublicConfig> {\n if (publicConfigCache && Date.now() - publicConfigCache.at < 5 * 60_000) return publicConfigCache.value;\n const res = await fetch(`${env.ODLA_PLATFORM}/registry/apps/${env.ODLA_APP_ID}/public-config?env=${env.ODLA_ENV}`);\n if (!res.ok) throw new Error(`public-config fetch failed: ${res.status}`);\n const value = (await res.json()) as PublicConfig;\n publicConfigCache = { value, at: Date.now() };\n return value;\n }\n\n async function verifyUser(req: Request, env: ChapterEnv): Promise<Verified | null> {\n const header = req.headers.get(\"authorization\") ?? \"\";\n if (!header.startsWith(\"Bearer \")) return null;\n const token = header.slice(7);\n const { issuer } = await getPublicConfig(env);\n if (!issuer) return null;\n let jwks = jwksByIssuer.get(issuer);\n if (!jwks) {\n jwks = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`));\n jwksByIssuer.set(issuer, jwks);\n }\n try {\n const { payload } = await jwtVerify(token, jwks, { issuer });\n if (!payload.sub) return null;\n return {\n userId: payload.sub,\n email: typeof payload.email === \"string\" ? payload.email : undefined,\n payload: payload as Record<string, unknown>,\n };\n } catch {\n return null;\n }\n }\n\n function makeDb(env: ChapterEnv): Db {\n return initAdmin({ appId: env.ODLA_TENANT, adminToken: env.ODLA_API_KEY, endpoint: env.ODLA_ENDPOINT });\n }\n\n // The `admins` allowlist gate (auth source \"table\"): no route ever writes it, so\n // membership can only be granted by a human in odla Studio.\n async function isAdminEmail(db: Db, email: string | undefined): Promise<boolean> {\n if (!email) return false;\n const { admins } = await db.query({ admins: { $: { where: { email: email.toLowerCase() }, limit: 1 } } });\n return Array.isArray(admins) && admins.length > 0;\n }\n\n // The read-only `superAdmins` tier — queried, never written (Studio-only).\n async function isSuperAdminEmail(db: Db, email: string | undefined): Promise<boolean> {\n if (!auth.superAdmins || !email) return false;\n const { superAdmins } = await db.query({ superAdmins: { $: { where: { email: email.toLowerCase() }, limit: 1 } } });\n return Array.isArray(superAdmins) && superAdmins.length > 0;\n }\n\n // The user's role, resolved per the auth source: a JWT claim, or the `admins`\n // allowlist synthesized to the admin rung / the lowest one.\n async function roleFor(db: Db, u: Verified): Promise<string> {\n if (auth.source === \"claim\") return roleFromClaim(u.payload, auth);\n return (await isAdminEmail(db, u.email)) ? auth.adminRole : (auth.ladder[0] as string);\n }\n\n // Admin authorization — the boolean gate used by /api/me and the CRM surface.\n async function isAdmin(db: Db, u: Verified): Promise<boolean> {\n if (auth.source === \"claim\") return isAdminRole(roleFromClaim(u.payload, auth), auth);\n return isAdminEmail(db, u.email);\n }\n\n function crmSender(env: ChapterEnv) {\n if (!env.SEND_EMAIL || !env.EMAIL_FROM) return undefined;\n const binding = env.SEND_EMAIL;\n return {\n async send(payload: EmailPayload): Promise<{ messageId: string }> {\n return binding.send(payload);\n },\n };\n }\n\n return { chapter, auth, crmBase, getPublicConfig, verifyUser, makeDb, isAdminEmail, isSuperAdminEmail, roleFor, isAdmin, crmSender };\n}\n\n/** The value returned by {@link createWorkerContext}, threaded to every route. */\nexport type WorkerContext = ReturnType<typeof createWorkerContext>;\n\n/** A worker route handler: owns the request (returns a Response) or falls through\n * (returns null). Host routes passed to `chapterWorker` compose against the same\n * {@link WorkerContext} the built-ins receive. */\nexport type Route = (req: Request, url: URL, env: ChapterEnv, ctx: WorkerContext) => Promise<Response | null>;\n","// Identity + authorization for a chapter/hub site — the pieces every membership\n// site needs and none should re-derive: a resolved role policy, role resolution\n// from a JWT claim, the privilege-escalation guard, and a tenant-vault read.\n// Everything here is pure or structural (no runtime @odla-ai/db import), so it is\n// trivially testable and the worker stays the only thing that talks to odla-db.\nimport type { ChapterAuth, ChapterMode, ResolvedAuth } from \"./types\";\n\n/**\n * Apply defaults + validate the auth config into a {@link ResolvedAuth}. Defaults\n * by mode: `chapter` → the `provisional/member/admin` claim ladder with the\n * `superAdmins` tier (Silver & Salt); `hub` → the `admins` allowlist table, no\n * super tier (Built Not Found). Throws at import on a bad policy.\n */\nexport function resolveAuth(mode: ChapterMode, auth: ChapterAuth | undefined): ResolvedAuth {\n const a = auth ?? {};\n const source = a.source ?? (mode === \"hub\" ? \"table\" : \"claim\");\n if (source !== \"claim\" && source !== \"table\") {\n throw new Error(`defineChapter.auth.source: must be \"claim\" or \"table\" — got ${JSON.stringify(a.source)}`);\n }\n const claim = a.claim ?? \"role\";\n if (typeof claim !== \"string\" || claim === \"\") {\n throw new Error(\"defineChapter.auth.claim: must be a non-empty string\");\n }\n const ladder = a.ladder ?? [\"provisional\", \"member\", \"admin\"];\n if (!Array.isArray(ladder) || ladder.length === 0 || !ladder.every((r) => typeof r === \"string\" && r !== \"\")) {\n throw new Error(\"defineChapter.auth.ladder: must be a non-empty array of role strings\");\n }\n const adminRole = ladder[ladder.length - 1] as string;\n const superAdmins = a.superAdmins ?? source === \"claim\";\n return { source, claim, ladder, adminRole, superAdmins };\n}\n\n/** The role from a verified JWT payload, per the resolved policy. An unknown or\n * missing claim falls back to the lowest ladder rung (fail safe, never admin). */\nexport function roleFromClaim(payload: Record<string, unknown>, auth: ResolvedAuth): string {\n const raw = payload[auth.claim];\n return typeof raw === \"string\" && auth.ladder.includes(raw) ? raw : (auth.ladder[0] as string);\n}\n\n/** Does a role meet the admin bar (the highest ladder rung)? */\nexport function isAdminRole(role: string, auth: ResolvedAuth): boolean {\n return role === auth.adminRole;\n}\n\n/** Inputs to the role-change guard — resolved by the caller (route) from the\n * identity provider + the read-only `superAdmins` table. */\nexport interface RoleChangeContext {\n actorId: string;\n actorIsSuper: boolean;\n targetId: string;\n targetCurrentRole: string;\n targetIsSuper: boolean;\n newRole: string;\n auth: ResolvedAuth;\n}\n\n/** The result of {@link canChangeRole}: allow, or deny with the HTTP status +\n * message the route should return. */\nexport type GuardResult = { ok: true } | { ok: false; status: number; error: string };\n\n/**\n * The privilege-escalation guard — package-enforced so every site gets it and\n * none re-derives it. Denies: an out-of-ladder role; changing your own role;\n * touching a super-admin unless you are one; and (when a `superAdmins` tier\n * exists) creating or altering an admin unless you are a super-admin. Note the\n * super-admin tier itself is never writable here — it lives in the read-only\n * `superAdmins` table, set only in odla Studio.\n */\nexport function canChangeRole(ctx: RoleChangeContext): GuardResult {\n const { auth } = ctx;\n if (!auth.ladder.includes(ctx.newRole)) {\n return { ok: false, status: 400, error: `role must be one of: ${auth.ladder.join(\", \")}` };\n }\n if (ctx.actorId === ctx.targetId) {\n return { ok: false, status: 400, error: \"you cannot change your own role\" };\n }\n if (ctx.targetIsSuper && !ctx.actorIsSuper) {\n return { ok: false, status: 403, error: \"this person is a super-admin; their access is managed in odla Studio\" };\n }\n const touchesAdmin = ctx.newRole === auth.adminRole || ctx.targetCurrentRole === auth.adminRole;\n if (auth.superAdmins && touchesAdmin && !ctx.actorIsSuper) {\n return { ok: false, status: 403, error: `only super-admins can create or change an ${auth.adminRole}` };\n }\n return { ok: true };\n}\n\n/** Structural view of odla-db's tenant-vault read, so chapter takes no runtime\n * dependency on @odla-ai/db. The worker's admin client satisfies this. */\nexport interface SecretStore {\n secrets: { get(name: string): Promise<string> };\n}\n\n/**\n * Read a tenant-vault secret by name; `undefined` when it is absent or the vault\n * errors, so callers degrade gracefully (e.g. `paymentsReady: false`) rather than\n * throwing. Never logs the value.\n */\nexport async function getVaultSecret(db: SecretStore, name: string): Promise<string | undefined> {\n try {\n const value = await db.secrets.get(name);\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n } catch {\n return undefined;\n }\n}\n","// Route handlers for the chapter Worker. Each returns a Response when it owns the\n// request, or null to fall through to the next handler (finally ASSETS). Split\n// out of worker.ts so the entry stays a thin composer under the per-file LOC cap;\n// behaviour and route order are unchanged from the original single-file handler.\nimport { createCrmRoutes } from \"@odla-ai/crm\";\nimport { getVaultSecret, isAdminRole } from \"./auth\";\nimport { createClerkInvitation, createClerkUser } from \"./clerk\";\nimport { applicantProfile, joinConfig, submitApplication } from \"./member\";\nimport { normalizeSharedRecord, projectApplicant, projectSharedRecord } from \"./network\";\nimport { resolveScheduling } from \"./scheduling\";\nimport { memberApplication } from \"./session\";\nimport type { ApplicationRecord, MeetingRecord, MemberApplication } from \"./session\";\nimport { emailGroupFrom, sendTemplated } from \"./notify\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, Route } from \"./worker-context\";\nimport type { Chapter, ChapterDb, ChapterScheduling } from \"./types\";\n\nexport type { Route };\n\n// Apply-time provisioning (both best-effort — never fail the application):\n// project the applicant into crm_record, and mint a Clerk invitation so they get\n// a path into their member area (only when a clerk_secret_key is in the vault).\nasync function provisionApplicant(\n db: ChapterDb,\n chapter: Chapter,\n applicationId: string,\n fields: Record<string, unknown>,\n): Promise<void> {\n const email = typeof fields.email === \"string\" ? fields.email : \"\";\n if (!email) return;\n const s = (v: unknown): string | undefined => (typeof v === \"string\" ? v : undefined);\n // Carry the site-configured crmFields (present values only) into the projection\n // as enrichment on top of the built-in identity/contact set.\n const extra: Record<string, unknown> = {};\n for (const f of chapter.application.crmFields) {\n if (fields[f] !== undefined) extra[f] = fields[f];\n }\n try {\n await projectApplicant(\n { crm: chapter.crm, db, now: () => Date.now(), newId: () => crypto.randomUUID() },\n { applicationId, email, firstName: s(fields.firstName), lastName: s(fields.lastName), phone: s(fields.phone), linkedin: s(fields.linkedin), extra },\n );\n } catch {\n // CRM projection is best-effort\n }\n if (chapter.account !== \"none\") {\n try {\n const secret = await getVaultSecret(db, \"clerk_secret_key\");\n if (secret) {\n // Carry the applicant's own fields onto the account under\n // `public_metadata.profile`, plus the application id that produced it, so\n // the account is self-describing under either account model. The 422 heal\n // refreshes this on an account an earlier missed create never wrote.\n const profile = applicantProfile(chapter, fields);\n const publicMetadata = { applicationId, ...(profile ? { profile } : {}) };\n if (chapter.account === \"create\") {\n await createClerkUser(secret, { email, firstName: s(fields.firstName), lastName: s(fields.lastName), publicMetadata });\n } else {\n await createClerkInvitation(secret, { email, publicMetadata });\n }\n }\n } catch {\n // account provisioning is best-effort\n }\n }\n}\n\n// Best-effort admin notification when an application arrives, so a human sees it\n// even before payment. Exactly-once per application via the dedupeKey.\nasync function notifyAdminOfApplication(\n db: ChapterDb,\n env: ChapterEnv,\n chapterId: string,\n applicationId: string,\n fields: Record<string, unknown>,\n): Promise<void> {\n try {\n const groups = (await db.query({ groups: { $: { where: { id: chapterId }, limit: 1 } } })).groups;\n const group = Array.isArray(groups) ? groups[0] : undefined;\n if (!group || typeof group.notificationEmail !== \"string\" || !group.notificationEmail) return;\n const s = (v: unknown): string => (typeof v === \"string\" ? v : \"\");\n await sendTemplated(\n { db, envName: env.ODLA_ENV, sender: env.SEND_EMAIL, from: env.EMAIL_FROM, now: () => Date.now(), newId: () => crypto.randomUUID() },\n {\n group: emailGroupFrom(group),\n template: \"adminNotification\",\n to: group.notificationEmail,\n vars: { firstName: s(fields.firstName), lastName: s(fields.lastName), email: s(fields.email), phone: s(fields.phone), state: s(fields.state) },\n dedupeKey: `apply:${applicationId}:admin`,\n applicationId,\n },\n );\n } catch {\n // never fail the application on a notification error\n }\n}\n\n// The signed-in member's own application (chapter mode): the latest by email,\n// folded with its latest scheduled meeting and rendered in the group's timezone.\n// The meetings row is canonical, so no live-calendar reconcile is needed here.\nasync function memberSessionApplication(db: ChapterDb, chapterId: string, email: string): Promise<MemberApplication | null> {\n const apps = (await db.query({ applications: { $: { where: { email }, order: { createdAt: \"desc\" }, limit: 1 } } })).applications;\n const app = Array.isArray(apps) ? apps[0] : undefined;\n if (!app) return null;\n const meetings = (\n await db.query({ meetings: { $: { where: { applicationId: app.id, status: \"scheduled\" }, order: { createdAt: \"desc\" }, limit: 1 } } })\n ).meetings;\n const meeting = Array.isArray(meetings) ? meetings[0] : undefined;\n const groups = (await db.query({ groups: { $: { where: { id: chapterId }, limit: 1 } } })).groups;\n const group = Array.isArray(groups) ? groups[0] : undefined;\n const timezone = resolveScheduling(group?.schedulingJson as ChapterScheduling | undefined).timezone;\n return memberApplication(app as unknown as ApplicationRecord, meeting as unknown as MeetingRecord | undefined, timezone);\n}\n\n/** GET /api/health — a public liveness probe (what deploy checks hit). */\nexport const handleHealth: Route = async (_req, url) => (url.pathname === \"/api/health\" ? json({ ok: true }) : null);\n\n/** GET /api/config — the public Clerk publishable key, so the SPA can boot sign-in. */\nexport const handleConfig: Route = async (_req, url, env, ctx) => {\n if (url.pathname !== \"/api/config\") return null;\n try {\n const { clerkPublishableKey } = await ctx.getPublicConfig(env);\n return json({ clerkPublishableKey: clerkPublishableKey ?? null, env: env.ODLA_ENV });\n } catch {\n return json({ clerkPublishableKey: null, env: env.ODLA_ENV });\n }\n};\n\n/** GET /api/me — the signed-in user's role, admin authorization, and super-admin\n * tier. In chapter mode it also carries the member's own `application` (their\n * status + booked call), so the member area renders from one call. */\nexport const handleMe: Route = async (req, url, env, ctx) => {\n if (url.pathname !== \"/api/me\") return null;\n const u = await ctx.verifyUser(req, env);\n if (!u) return json({ authorized: false }, 401);\n const db = ctx.makeDb(env);\n const role = await ctx.roleFor(db, u);\n const superAdmin = await ctx.isSuperAdminEmail(db, u.email);\n const base = { authorized: isAdminRole(role, ctx.auth), role, superAdmin, email: u.email ?? null };\n if (ctx.chapter.mode !== \"chapter\" || !u.email) return json(base);\n const application = await memberSessionApplication(db as unknown as ChapterDb, ctx.chapter.id, u.email);\n return json({ ...base, application });\n};\n\n/** /api/crm/* — the CRM admin surface (mounted at ctx.crmBase). */\nexport const handleCrm: Route = async (req, url, env, ctx) => {\n const crmBase = ctx.crmBase;\n if (url.pathname !== crmBase && !url.pathname.startsWith(crmBase + \"/\")) return null;\n const db = ctx.makeDb(env);\n const routes = createCrmRoutes({\n crm: ctx.chapter.crm,\n db: db as never,\n authorize: async (r: Request) => {\n const u = await ctx.verifyUser(r, env);\n if (!u || !(await ctx.isAdmin(db, u))) return null;\n return u.email ? { userId: u.userId, email: u.email } : { userId: u.userId };\n },\n sender: ctx.crmSender(env),\n from: env.EMAIL_FROM,\n envName: env.ODLA_ENV,\n baseUrl: url.origin,\n basePath: crmBase,\n });\n const res = await routes(req);\n if (res) return res;\n return json({ error: \"not found\" }, 404);\n};\n\n/** POST /api/network/shared — leader push projection into this site's\n * crm_record (vault-secret gated, works in both modes). Accepts the original\n * person shape and the versioned generic person/company/deal envelope. */\nexport const handleNetworkShared: Route = async (req, url, env, ctx) => {\n if (req.method !== \"POST\" || url.pathname !== \"/api/network/shared\") return null;\n const db = ctx.makeDb(env);\n const secret = await getVaultSecret(db as unknown as ChapterDb, \"network_share_secret\");\n const provided = (req.headers.get(\"authorization\") ?? \"\").replace(/^Bearer /, \"\");\n if (!secret || provided.length !== secret.length || provided !== secret) {\n return json({ error: \"unauthorized\" }, 401);\n }\n let payload: Record<string, unknown>;\n try {\n payload = JSON.parse(await req.text()) as Record<string, unknown>;\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n if (typeof payload.hubRecordId !== \"string\" || !payload.hubRecordId.trim()) {\n return json({ error: \"hubRecordId is required\" }, 400);\n }\n if (\"input\" in payload) {\n if (\n payload.version !== 1 ||\n typeof payload.type !== \"string\" ||\n !payload.type.trim() ||\n !payload.input ||\n typeof payload.input !== \"object\" ||\n Array.isArray(payload.input)\n ) {\n return json({ error: \"version 1, type, and input are required\" }, 400);\n }\n } else if (payload.type !== \"company\" && typeof payload.email !== \"string\") {\n return json({ error: \"legacy person shares require email\" }, 400);\n } else if (payload.type === \"company\" && typeof payload.name !== \"string\") {\n return json({ error: \"business shares require name\" }, 400);\n }\n try {\n const record = normalizeSharedRecord(payload as never);\n const { recordId } = await projectSharedRecord(\n { crm: ctx.chapter.crm, db: db as unknown as ChapterDb, now: () => Date.now(), newId: () => crypto.randomUUID() },\n record,\n );\n return json({ recordId, type: record.type });\n } catch (err) {\n const message = err instanceof Error ? err.message : \"invalid shared record\";\n return json({ error: message }, 400);\n }\n};\n\n/** Chapter-mode public member surface: GET /api/join-config, POST /api/applications.\n * Returns null in hub mode so those paths fall through to ASSETS. */\nexport const handleMember: Route = async (req, url, env, ctx) => {\n const chapter = ctx.chapter;\n if (chapter.mode !== \"chapter\") return null;\n\n // Public join config: prices + policy copy + payment readiness (B1/C2).\n if (req.method === \"GET\" && url.pathname === \"/api/join-config\") {\n const db = ctx.makeDb(env);\n const groupId = url.searchParams.get(\"group\") ?? chapter.id;\n const { groups } = await db.query({ groups: { $: { where: { id: groupId }, limit: 1 } } });\n const group = Array.isArray(groups) ? groups[0] : undefined;\n if (!group) return json({ error: \"not found\" }, 404);\n const stripeKey = await getVaultSecret(db as unknown as ChapterDb, \"stripe_secret_key\");\n const paymentsReady = Boolean(group.stripePublishableKey && group.stripePriceId && stripeKey);\n return json(joinConfig(group as never, paymentsReady));\n }\n\n // Public application submit — validated, body-capped, idempotent (B2/B3).\n if (req.method === \"POST\" && url.pathname === \"/api/applications\") {\n const raw = await req.text();\n if (raw.length > chapter.application.bodyCap) return json({ error: \"request body too large\" }, 413);\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n const submissionId = typeof parsed.submissionId === \"string\" ? parsed.submissionId : undefined;\n const db = ctx.makeDb(env) as unknown as ChapterDb;\n const result = await submitApplication(db, chapter, parsed, {\n submissionId,\n groupId: chapter.id,\n now: Date.now(),\n newId: () => crypto.randomUUID(),\n });\n if (!result.ok) return json({ error: result.error }, 400);\n if (!result.duplicate) {\n // The trigger is declarative (sends.adminNotification); addressing + copy\n // stay owner-editable on the group row.\n if (chapter.sends.adminNotification === \"submit\") {\n await notifyAdminOfApplication(db, env, chapter.id, result.id, parsed);\n }\n await provisionApplicant(db, chapter, result.id, parsed);\n }\n return json({\n id: result.id,\n duplicate: result.duplicate,\n status: result.status,\n // Echoed so a site can see (and assert in an integration test) whether its\n // join page actually posted the ack. Absent consent is otherwise invisible.\n disclaimerAckAt: result.disclaimerAckAt,\n });\n }\n\n return null;\n};\n","// Apply-time account provisioning. When an application arrives, the worker mints\n// a Clerk invitation so the applicant gets a path into their member area — the\n// server-side account step S&S does by hand, generalized. Chapter calls the Clerk\n// Backend API directly over fetch (vault clerk_secret_key), mirroring\n// @odla-ai/auth-clerk's createInvitation but self-contained, so it never pulls the\n// auth-clerk UI package into the worker bundle. Best-effort at the call site: a\n// provisioning failure never fails the application.\n\n/** The outcome of a Clerk provisioning call. `existed` marks the heal case: Clerk\n * rejected it because the account/invitation is already there, which is the end\n * state we wanted anyway. */\nexport interface ClerkResult {\n ok: boolean;\n status: number;\n existed?: boolean;\n /** Set when an `existed` heal also refreshed the account's public_metadata. */\n refreshed?: boolean;\n}\n\n// Clerk answers 422 when the email already has a user (or a pending invitation).\n// For apply-time provisioning that's success, not failure — the account exists.\nconst heal = (status: number): ClerkResult =>\n status === 422 ? { ok: true, status, existed: true } : { ok: false, status };\n\n/** Inputs for a Clerk invitation. */\nexport interface ClerkInviteInput {\n email: string;\n /** Where the accept-invitation link lands (usually the member area). */\n redirectUrl?: string;\n /** Written to the invitation's `public_metadata`, so the accepted account\n * carries your own profile fields. */\n publicMetadata?: Record<string, unknown>;\n}\n\n/** Build the Clerk Backend API invitation request (path + JSON body). Pure, so\n * the wire shape is testable without a network call. */\nexport function clerkInviteRequest(input: ClerkInviteInput): { path: string; body: Record<string, unknown> } {\n return {\n path: \"/v1/invitations\",\n body: {\n email_address: input.email,\n notify: true,\n ...(input.redirectUrl ? { redirect_url: input.redirectUrl } : {}),\n ...(input.publicMetadata ? { public_metadata: input.publicMetadata } : {}),\n },\n };\n}\n\n/** POST the invitation to the Clerk Backend API. A repeat invite for an\n * already-invited email heals to `{ ok: true, existed: true }` rather than\n * reporting a failure the caller would have to special-case. */\nexport async function createClerkInvitation(\n secretKey: string,\n input: ClerkInviteInput,\n fetchImpl: typeof fetch = fetch,\n): Promise<ClerkResult> {\n const { path, body } = clerkInviteRequest(input);\n const res = await fetchImpl(`https://api.clerk.com${path}`, {\n method: \"POST\",\n headers: { authorization: `Bearer ${secretKey}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n return res.ok ? { ok: true, status: res.status } : heal(res.status);\n}\n\n/** Inputs for a server-side Clerk user create. */\nexport interface ClerkUserInput {\n email: string;\n firstName?: string;\n lastName?: string;\n /** Written to the user's `public_metadata` — the site's own profile fields\n * (role, tier, whatever the member area reads). */\n publicMetadata?: Record<string, unknown>;\n}\n\n/** Build the Clerk Backend API user-create request. The account is created\n * passwordless (the member signs in via the site's Clerk flow), so join step 3\n * can say the account is ready — the \"create\" alternative to an invitation. */\nexport function clerkUserRequest(input: ClerkUserInput): { path: string; body: Record<string, unknown> } {\n return {\n path: \"/v1/users\",\n body: {\n email_address: [input.email],\n skip_password_requirement: true,\n ...(input.firstName ? { first_name: input.firstName } : {}),\n ...(input.lastName ? { last_name: input.lastName } : {}),\n ...(input.publicMetadata ? { public_metadata: input.publicMetadata } : {}),\n },\n };\n}\n\n// Look the account up by email and PATCH its public_metadata. Used by the heal\n// path so a re-application REPAIRS a profile that an earlier missed create never\n// wrote, instead of just reporting \"already exists\".\nasync function refreshUserMetadata(\n secretKey: string,\n email: string,\n publicMetadata: Record<string, unknown>,\n fetchImpl: typeof fetch,\n): Promise<boolean> {\n const auth = { authorization: `Bearer ${secretKey}` };\n const found = await fetchImpl(`https://api.clerk.com/v1/users?email_address=${encodeURIComponent(email)}&limit=1`, { headers: auth });\n if (!found.ok) return false;\n const users = (await found.json().catch(() => null)) as Array<{ id?: unknown }> | null;\n const id = Array.isArray(users) && typeof users[0]?.id === \"string\" ? users[0].id : undefined;\n if (!id) return false;\n const patched = await fetchImpl(`https://api.clerk.com/v1/users/${id}/metadata`, {\n method: \"PATCH\",\n headers: { ...auth, \"content-type\": \"application/json\" },\n body: JSON.stringify({ public_metadata: publicMetadata }),\n });\n return patched.ok;\n}\n\n/** Create the applicant's Clerk account server-side. A repeat for an email that\n * already has an account heals to `{ ok: true, existed: true }` — the account\n * exists, which is the state apply-time provisioning wanted — and, when\n * `publicMetadata` was supplied, refreshes it on the existing account so a\n * re-application repairs a previously missed create (`refreshed: true`). */\nexport async function createClerkUser(\n secretKey: string,\n input: ClerkUserInput,\n fetchImpl: typeof fetch = fetch,\n): Promise<ClerkResult> {\n const { path, body } = clerkUserRequest(input);\n const res = await fetchImpl(`https://api.clerk.com${path}`, {\n method: \"POST\",\n headers: { authorization: `Bearer ${secretKey}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (res.ok) return { ok: true, status: res.status };\n const healed = heal(res.status);\n if (!healed.existed || !input.publicMetadata) return healed;\n const refreshed = await refreshUserMetadata(secretKey, input.email, input.publicMetadata, fetchImpl).catch(() => false);\n return { ...healed, refreshed };\n}\n","// The public member surface logic: the join config a site's join page reads (B1)\n// and the idempotent application submit (B2 validation + B3 exactly-once). Both\n// take the structural ChapterDb, so they're tested against an in-memory fake and\n// carry no runtime @odla-ai/db import. The worker builds the real db client, does\n// Clerk verification, enforces the body cap, and mounts these on chapter routes.\nimport type { Chapter, ChapterApplication, ChapterDb, ResolvedApplication } from \"./types\";\n\n// Silver & Salt's join form. `focus` (a json field) is always accepted.\nconst DEFAULT_REQUIRED = [\"firstName\", \"lastName\", \"email\", \"referral\", \"whoYouAre\", \"message\"];\nconst DEFAULT_OPTIONAL = [\"referralName\", \"linkedin\", \"phone\", \"state\"];\n\n/** Apply defaults + validate the application config. Throws at import on bad shape. */\nexport function resolveApplication(a: ChapterApplication | undefined): ResolvedApplication {\n const required = a?.required ?? DEFAULT_REQUIRED;\n const optional = a?.optional ?? DEFAULT_OPTIONAL;\n for (const [name, arr] of [[\"required\", required], [\"optional\", optional]] as const) {\n if (!Array.isArray(arr) || !arr.every((f) => typeof f === \"string\" && f !== \"\")) {\n throw new Error(`defineChapter.application.${name}: must be an array of field-name strings`);\n }\n }\n if (a?.profileFields !== undefined && (!Array.isArray(a.profileFields) || !a.profileFields.every((f) => typeof f === \"string\" && f !== \"\"))) {\n throw new Error(\"defineChapter.application.profileFields: must be an array of field-name strings\");\n }\n if (a?.crmFields !== undefined && (!Array.isArray(a.crmFields) || !a.crmFields.every((f) => typeof f === \"string\" && f !== \"\"))) {\n throw new Error(\"defineChapter.application.crmFields: must be an array of field-name strings\");\n }\n return {\n required,\n optional,\n maxLen: a?.maxLen ?? {},\n defaultMaxLen: a?.defaultMaxLen ?? 2000,\n bodyCap: a?.bodyCap ?? 32768,\n requireDisclaimerAck: a?.requireDisclaimerAck ?? false,\n profileFields: a?.profileFields ?? null,\n crmFields: a?.crmFields ?? [],\n maxArrayLen: a?.maxArrayLen ?? 100,\n validateEmail: a?.validateEmail ?? true,\n };\n}\n\n// A permissive email shape check: one @, a dot-bearing domain, no whitespace.\n// Deliberately not RFC-exhaustive — the goal is to reject \"notanemail\" before it\n// fails the downstream Clerk create, not to adjudicate exotic-but-valid addresses.\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/** Whether a string looks like an email address (see {@link EMAIL_RE}). Exported\n * so a site building its own submit path applies the same rule chapter does. */\nexport function isValidEmail(value: unknown): boolean {\n return typeof value === \"string\" && EMAIL_RE.test(value);\n}\n\n/** Bound an array-valued field: drop non-primitive elements and cap the length,\n * so a client cannot post an unbounded array. Non-arrays pass through unchanged. */\nexport function clampArray(value: unknown, max: number): unknown {\n if (!Array.isArray(value)) return value;\n return value.filter((x) => typeof x === \"string\" || typeof x === \"number\" || typeof x === \"boolean\").slice(0, max);\n}\n\n/** Whether a submit body carries a genuine disclaimer acknowledgement. Accepts\n * the boolean an API client sends and the string a plain HTML form posts. */\nexport function hasDisclaimerAck(fields: Record<string, unknown>): boolean {\n return fields.disclaimerAck === true || fields.disclaimerAck === \"true\";\n}\n\n// Clerk carries these as first-class user fields, so repeating them in\n// public_metadata would be duplicated state that can drift.\nconst IDENTITY_FIELDS = new Set([\"email\", \"firstName\", \"lastName\"]);\n\n/**\n * The applicant profile written to the Clerk account's client-readable\n * `public_metadata.profile`. Projects each configured non-identity field, plus\n * `focus` (clamped) — but ONLY those in `application.profileFields` when that\n * allowlist is set, so a site keeps confidential fields (`message`, `referral`)\n * db-only. Derived from config, so a site's own field names project without this\n * package knowing them. Pure; returns `undefined` when there is nothing to write.\n */\nexport function applicantProfile(\n chapter: Chapter,\n fields: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const app = chapter.application;\n const allowed = (f: string): boolean => app.profileFields === null || app.profileFields.includes(f);\n const profile: Record<string, unknown> = {};\n for (const f of [...app.required, ...app.optional]) {\n if (IDENTITY_FIELDS.has(f) || !allowed(f)) continue;\n const v = fields[f];\n if (typeof v === \"string\" && v.trim() !== \"\") profile[f] = v.trim();\n }\n if (fields.focus !== undefined && allowed(\"focus\")) profile.focus = clampArray(fields.focus, app.maxArrayLen);\n return Object.keys(profile).length > 0 ? profile : undefined;\n}\n\n/** A validated submission, or a 400-worthy validation error the route returns.\n * `disclaimerAckAt` reports what THIS request recorded — a number when consent\n * was stamped, `null` when none was supplied. It is always present so a missing\n * consent record is visible in the response rather than silently absent from a\n * row nobody reads until an audit. */\nexport type SubmitResult =\n | { ok: true; id: string; duplicate: boolean; status: string; disclaimerAckAt: number | null }\n | { ok: false; error: string };\n\n/**\n * Submit a membership application (B2 + B3). Validates the configured required\n * fields + max lengths, writes the `applications` row at the pipeline's initial\n * status, and — when the client supplies a `submissionId` — stamps it as the\n * transaction's mutationId (`join:${submissionId}`) so a double-tap can never\n * create two applications (the second returns `duplicate: true`). Idempotency is\n * package-enforced. `now`/`newId` are injected (deterministic in tests).\n */\nexport async function submitApplication(\n db: ChapterDb,\n chapter: Chapter,\n fields: Record<string, unknown>,\n opts: { submissionId?: string; groupId?: string; now: number; newId: () => string },\n): Promise<SubmitResult> {\n const app = chapter.application;\n for (const f of app.required) {\n const v = fields[f];\n if (typeof v !== \"string\" || v.trim() === \"\") return { ok: false, error: `${f} is required` };\n }\n for (const f of [...app.required, ...app.optional]) {\n const v = fields[f];\n const cap = app.maxLen[f] ?? app.defaultMaxLen;\n if (typeof v === \"string\" && v.length > cap) return { ok: false, error: `${f} exceeds ${cap} characters` };\n }\n // A malformed email can only fail the downstream Clerk create; reject it here\n // as a clean 400. A valid application always has a valid email, so no genuine\n // submission is newly rejected.\n if (app.validateEmail && typeof fields.email === \"string\" && !isValidEmail(fields.email)) {\n return { ok: false, error: \"email must be a valid email address\" };\n }\n\n const acked = hasDisclaimerAck(fields);\n if (app.requireDisclaimerAck && !acked) {\n return { ok: false, error: \"disclaimerAck is required\" };\n }\n\n const id = opts.newId();\n const row: Record<string, unknown> = { id, status: chapter.pipeline.initial, createdAt: opts.now };\n for (const f of [...app.required, ...app.optional]) {\n if (typeof fields[f] === \"string\") row[f] = (fields[f] as string).trim();\n }\n if (fields.focus !== undefined) row.focus = clampArray(fields.focus, app.maxArrayLen);\n if (opts.groupId) row.groupId = opts.groupId;\n // The disclaimer acknowledgement is a compliance record, so it is stamped from\n // the server clock on a genuine ack and left absent otherwise — a client-supplied\n // timestamp would be forgeable, and a row that always carries one would record\n // consent nobody gave.\n if (acked) row.disclaimerAckAt = opts.now;\n\n const { duplicate } = await db.transact(\n [{ t: \"update\", ns: \"applications\", id, attrs: row }],\n opts.submissionId ? { mutationId: `join:${opts.submissionId}` } : undefined,\n );\n return { ok: true, id, duplicate, status: chapter.pipeline.initial, disclaimerAckAt: acked ? opts.now : null };\n}\n\n/** The `groups`-row fields the join config exposes. */\nexport interface JoinConfigGroup {\n id: string;\n name: string;\n standardPriceCents?: number;\n foundingDiscountCents?: number;\n disclaimerText?: string;\n refundPolicyText?: string;\n trustCopy?: string;\n commitmentText?: string;\n normsText?: string;\n}\n\n/**\n * The public join config (B1) a site's join page reads: copy + prices from the\n * group row plus `paymentsReady`. When payments aren't wired the join flow drops\n * the payment step (C2) — the worker computes `paymentsReady` from the group's\n * Stripe keys + vault secret. Pure.\n */\nexport function joinConfig(group: JoinConfigGroup, paymentsReady: boolean): Record<string, unknown> {\n return {\n id: group.id,\n name: group.name,\n standardPriceCents: group.standardPriceCents ?? 0,\n foundingDiscountCents: group.foundingDiscountCents ?? 0,\n disclaimerText: group.disclaimerText ?? \"\",\n refundPolicyText: group.refundPolicyText ?? \"\",\n trustCopy: group.trustCopy ?? \"\",\n commitmentText: group.commitmentText ?? \"\",\n normsText: group.normsText ?? \"\",\n paymentsReady,\n };\n}\n","// The leader → follower CRM projection (push model). The leader curates people,\n// businesses, and other configured CRM records and pushes a deliberately\n// allowlisted field set into THIS follower's crm_record.\n//\n// Invariants (package-enforced so no site re-derives them):\n// - One-way: the chapter never writes back to the hub through this path.\n// - Idempotent: every received record carries the leader's stable record id. A\n// provenance tag maps that id to the local CRM record, so a re-share updates\n// instead of duplicating even after an email/domain changes.\n// - Natural-key convergence: a person unifies by primary email and a business\n// by its configured domain slot (then name), so an arriving applicant and a\n// prior leader share compose into one person.\n// - Operational state stays local. Pipeline/account/billing state is not copied\n// into another site's authority; the push transfers the shared record fields.\n//\n// Reuses @odla-ai/crm's record ops (full validation via crm.prepare), driven by\n// the resolved chapter CRM engine + the structural ChapterDb.\nimport { createRecord, updateRecord } from \"@odla-ai/crm\";\nimport type { Crm, CrmRecord } from \"@odla-ai/crm\";\nimport type { ChapterDb, ResolvedNetworkTarget } from \"./types\";\n\n/** The contact data the hub shares for a prospect. `hubRecordId` is the stable\n * idempotency key (the hub's crm_record id). */\nexport interface SharedPerson {\n email: string;\n name?: string;\n firstName?: string;\n lastName?: string;\n phone?: string;\n linkedin?: string;\n hubRecordId: string;\n}\n\n/** Convenience wire shape for sharing the default `company` CRM type. */\nexport interface SharedBusiness {\n type: \"company\";\n name: string;\n domain?: string;\n industry?: string;\n location?: string;\n linkedin?: string;\n notes?: string;\n hubRecordId: string;\n}\n\n/** Versioned generic wire shape. `input` is validated against the follower's\n * own CRM type before any write, so a leader cannot smuggle undeclared fields. */\nexport interface SharedRecord {\n version: 1;\n type: string;\n hubRecordId: string;\n input: Record<string, unknown>;\n}\n\n/** Safe defaults when a target does not declare an explicit field allowlist. */\nexport const DEFAULT_SHARE_FIELDS: Readonly<Record<string, readonly string[]>> = {\n person: [\"name\", \"email\", \"firstName\", \"lastName\", \"phone\", \"linkedin\"],\n company: [\"name\", \"domain\", \"industry\", \"location\", \"linkedin\", \"notes\"],\n};\n\n/** Map a shared prospect to a crm `person` input (only the fields the default\n * person type accepts). Name falls back to first+last, then the email. */\nexport function sharedPersonInput(person: SharedPerson): Record<string, unknown> {\n const email = person.email.toLowerCase();\n const fullName = [person.firstName, person.lastName].filter(Boolean).join(\" \").trim();\n const input: Record<string, unknown> = { name: person.name ?? fullName ?? email, email };\n if (input.name === \"\") input.name = email;\n if (person.firstName) input.firstName = person.firstName;\n if (person.lastName) input.lastName = person.lastName;\n if (person.phone) input.phone = person.phone;\n if (person.linkedin) input.linkedin = person.linkedin;\n return input;\n}\n\n/** Deps for the projection — the resolved CRM engine, the structural db, and\n * injected clock/id (deterministic in tests). */\nexport interface ProjectionDeps {\n crm: Crm;\n db: ChapterDb;\n now: () => number;\n newId: () => string;\n}\n\nfunction shortHash(value: string): string {\n let a = 0x811c9dc5;\n let b = 0x9e3779b9;\n for (let i = 0; i < value.length; i += 1) {\n const n = value.charCodeAt(i);\n a = Math.imul(a ^ n, 0x01000193);\n b = Math.imul(b ^ n, 0x85ebca6b);\n }\n return `${(a >>> 0).toString(36)}${(b >>> 0).toString(36)}`;\n}\n\n/** CRM provenance tag used as the durable leader-id → local-record mapping. */\nexport function networkSourceTag(type: string, hubRecordId: string): string {\n const typeKey = type.toLowerCase();\n const readable = /^[a-z0-9_-]+$/.test(hubRecordId);\n const raw = `network:${typeKey}:${hubRecordId}`;\n if (readable && raw.length <= 64) return raw;\n return `network:${typeKey.slice(0, 20)}:${shortHash(`${type}\\u0000${hubRecordId}`)}`;\n}\n\n/** Normalize the backwards-compatible person/business shapes into the versioned\n * generic record envelope the receiver writes. */\nexport function normalizeSharedRecord(record: SharedPerson | SharedBusiness | SharedRecord): SharedRecord {\n if (\"input\" in record) return { version: 1, type: record.type, hubRecordId: record.hubRecordId, input: record.input };\n if (\"type\" in record && record.type === \"company\") {\n const input: Record<string, unknown> = { name: record.name };\n for (const key of [\"domain\", \"industry\", \"location\", \"linkedin\", \"notes\"] as const) {\n if (record[key]) input[key] = record[key];\n }\n return { version: 1, type: \"company\", hubRecordId: record.hubRecordId, input };\n }\n return { version: 1, type: \"person\", hubRecordId: record.hubRecordId, input: sharedPersonInput(record) };\n}\n\n/** Build the allowlisted payload sent from one leader CRM record to a target.\n * A target with an explicit `fields` map only accepts the types it lists. */\nexport function sharedRecordFromCrm(crm: Crm, record: CrmRecord, target: ResolvedNetworkTarget): SharedRecord {\n if (target.fields && !target.fields[record.type]) {\n throw new Error(`${target.name} does not accept \"${record.type}\" records`);\n }\n const def = crm.type(record.type);\n const fields = target.fields?.[record.type] ?? DEFAULT_SHARE_FIELDS[record.type];\n if (!fields) {\n throw new Error(`${target.name} requires an explicit field allowlist for \"${record.type}\" records`);\n }\n const nameField = def.nameField ?? \"name\";\n const input: Record<string, unknown> = {};\n for (const field of new Set([nameField, ...fields])) {\n const value = record.fields?.[field];\n if (value !== undefined) input[field] = value;\n }\n if (input[nameField] === undefined) input[nameField] = record.name;\n return { version: 1, type: record.type, hubRecordId: record.id, input };\n}\n\n// Resolve an existing crm_record person by lowercased primaryEmail and update it,\n// else create one under the given mutationId. The shared core of every one-way\n// person projection (hub share, arriving applicant).\nasync function upsertPerson(\n deps: ProjectionDeps,\n opts: { email: string; input: Record<string, unknown>; mutationId: string },\n): Promise<{ recordId: string }> {\n const email = opts.email.toLowerCase();\n const crmDeps = { crm: deps.crm, db: deps.db as never, now: deps.now, newId: deps.newId };\n const { crm_record } = await deps.db.query({ crm_record: { $: { where: { type: \"person\", primaryEmail: email }, limit: 1 } } });\n const existing = crm_record?.[0];\n if (existing && typeof existing.id === \"string\") {\n await updateRecord(crmDeps, { id: existing.id, input: opts.input });\n return { recordId: existing.id };\n }\n const created = await createRecord(crmDeps, { type: \"person\", input: opts.input, mutationId: opts.mutationId });\n return { recordId: created.id };\n}\n\nasync function findSharedRecord(\n deps: ProjectionDeps,\n record: SharedRecord,\n tag: string,\n): Promise<Record<string, unknown> | undefined> {\n const mapped = await deps.db.query({ crm_tag: { $: { where: { tag }, limit: 1 } } });\n const mappedId = mapped.crm_tag?.[0]?.recordId;\n if (typeof mappedId === \"string\") {\n const found = await deps.db.query({ crm_record: { $: { where: { id: mappedId }, limit: 1 } } });\n if (found.crm_record?.[0]) return found.crm_record[0];\n }\n const def = deps.crm.type(record.type);\n const emailField = def.emailField;\n if (emailField && typeof record.input[emailField] === \"string\") {\n const primaryEmail = record.input[emailField].toLowerCase();\n const found = await deps.db.query({\n crm_record: { $: { where: { type: record.type, primaryEmail }, limit: 1 } },\n });\n if (found.crm_record?.[0]) return found.crm_record[0];\n }\n const domain = record.input.domain;\n const domainSlot = def.fields.domain?.slot;\n if (typeof domain === \"string\" && domainSlot) {\n const found = await deps.db.query({\n crm_record: { $: { where: { type: record.type, [domainSlot]: domain }, limit: 1 } },\n });\n if (found.crm_record?.[0]) return found.crm_record[0];\n }\n const nameField = def.nameField ?? \"name\";\n const name = record.input[nameField];\n if (record.type === \"company\" && typeof name === \"string\" && name.trim()) {\n const found = await deps.db.query({\n crm_record: { $: { where: { type: record.type, name: name.trim() }, limit: 1 } },\n });\n if (found.crm_record?.[0]) return found.crm_record[0];\n }\n return undefined;\n}\n\n/**\n * Upsert a leader-shared CRM record into this follower. Accepts the original\n * person wire shape plus the versioned generic shape. Re-shares resolve through\n * a durable provenance tag; people/businesses also converge by natural key.\n */\nexport async function projectSharedRecord(\n deps: ProjectionDeps,\n shared: SharedPerson | SharedBusiness | SharedRecord,\n): Promise<{ recordId: string }> {\n const record = normalizeSharedRecord(shared);\n if (!record.type.trim() || !record.hubRecordId.trim()) {\n throw new Error(\"type and hubRecordId must be non-empty\");\n }\n const tag = networkSourceTag(record.type, record.hubRecordId);\n const crmDeps = { crm: deps.crm, db: deps.db as never, now: deps.now, newId: deps.newId };\n const existing = await findSharedRecord(deps, record, tag);\n let recordId: string;\n if (existing && typeof existing.id === \"string\") {\n // Do not use one permanent mutation id for updates: a later leader edit is a\n // new desired state and must not be mistaken for a retry of an older push.\n await updateRecord(crmDeps, { id: existing.id, input: record.input });\n recordId = existing.id;\n } else {\n // A deterministic id makes concurrent first deliveries converge even when\n // both requests observe no provenance row before either transaction lands.\n recordId = `network_${shortHash(`${record.type}\\u0000${record.hubRecordId}`)}`;\n await createRecord({ ...crmDeps, newId: () => recordId }, {\n type: record.type,\n input: record.input,\n mutationId: `share-create:${tag}`,\n });\n }\n await deps.db.transact(\n [{ t: \"update\", ns: \"crm_tag\", id: tag, attrs: { key: `${recordId}:${tag}`, recordId, tag, createdAt: deps.now() } }],\n { mutationId: `share-map:${tag}:${recordId}` },\n );\n return { recordId };\n}\n\n/** An arriving applicant, as far as the CRM projection cares. `extra` carries the\n * site-configured `crmFields` (values from the application), merged on top of the\n * built-in identity/contact set. */\nexport interface Applicant {\n applicationId: string;\n email: string;\n firstName?: string;\n lastName?: string;\n phone?: string;\n linkedin?: string;\n extra?: Record<string, unknown>;\n}\n\n/**\n * Project an arriving applicant into this chapter's `crm_record`, so a new\n * application shows up in the CRM immediately, unified by email with any prior\n * record. Idempotent per application (`apply:${applicationId}`). Best-effort at\n * the call site — a projection failure never fails the application.\n *\n * `extra` fields (a site's `crmFields`) are merged on top of the base person. If\n * an extra field is not on the crm person type, crm validation throws — so the\n * projection retries with the base person alone, ensuring a misconfigured\n * enrichment never silently drops the applicant from the CRM entirely.\n */\nexport async function projectApplicant(deps: ProjectionDeps, applicant: Applicant): Promise<{ recordId: string }> {\n const base = sharedPersonInput({\n email: applicant.email,\n firstName: applicant.firstName,\n lastName: applicant.lastName,\n phone: applicant.phone,\n linkedin: applicant.linkedin,\n hubRecordId: applicant.applicationId,\n });\n const mutationId = `apply:${applicant.applicationId}`;\n const extra = applicant.extra ?? {};\n if (Object.keys(extra).length === 0) return upsertPerson(deps, { email: applicant.email, input: base, mutationId });\n try {\n return await upsertPerson(deps, { email: applicant.email, input: { ...base, ...extra }, mutationId });\n } catch {\n return upsertPerson(deps, { email: applicant.email, input: base, mutationId });\n }\n}\n","// Scheduling core — config resolution + the booking invariants, ported from the\n// proven Silver & Salt worker. Everything here is PURE (no @odla-ai/calendar, no\n// db), so the correctness properties are unit-testable and package-enforced; the\n// worker route owns only the I/O (FreeBusy, computeBookableSlots, calendar\n// create/reschedule, the db writes) and calls these.\n//\n// Package-enforced invariants:\n// - the `meetings` row is canonical; applications.meetingAt and the calendar\n// event are projections written from it.\n// - one intro event per application, forever: a rebooking RESCHEDULES the\n// existing event (preserving its Meet link + invite thread), never creates a\n// second — see {@link bookingDecision} + {@link introIdempotencyKey}.\n// - status never moves backward on booking; you can only book from a pipeline\n// stage in `bookableFrom` — see `canBook` in ./pipeline + applicationBookingUpdate.\n// - endAt is always derived server-side, never client-supplied — see\n// {@link endForSlot}.\nimport type { ChapterScheduling } from \"./types\";\n\n/** A fully-resolved scheduling config (every field present). */\nexport interface ResolvedScheduling {\n slotMinutes: number;\n days: readonly number[];\n startHour: number;\n endHour: number;\n timezone: string;\n minNoticeHours: number;\n windowDays: number;\n summaryTemplate: string;\n}\n\n/** The S&S-proven defaults: 45-minute weekday slots, 9–5 Pacific, 24h notice,\n * a 14-day window. The summary is generic (a chapter's group seed supplies a\n * name-branded one). */\nexport const SCHEDULING_DEFAULTS: ResolvedScheduling = {\n slotMinutes: 45,\n days: [1, 2, 3, 4, 5],\n startHour: 9,\n endHour: 17,\n timezone: \"America/Los_Angeles\",\n minNoticeHours: 24,\n windowDays: 14,\n summaryTemplate: \"Introduction call with {{firstName}} {{lastName}}\",\n};\n\nfunction isValidTimeZone(tz: string): boolean {\n try {\n new Intl.DateTimeFormat(undefined, { timeZone: tz });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve a group's scheduling config against the defaults, validating every\n * bound the way S&S does at config-write time (throws on a bad config, so a\n * misconfiguration surfaces immediately rather than yielding empty slots).\n * `windowDays` is capped at 62 because Google FreeBusy is.\n */\nexport function resolveScheduling(config?: ChapterScheduling): ResolvedScheduling {\n const result = validateScheduling(config);\n if (result.ok) return result.value;\n const detail = Object.entries(result.errors)\n .map(([field, message]) => `${field}: ${message}`)\n .join(\" \");\n throw new Error(`scheduling: ${detail}`);\n}\n\n/** Validation messages keyed by form field. */\nexport type SchedulingErrors = Record<string, string>;\n\n/**\n * Validate a scheduling config field by field, collecting owner-readable messages\n * rather than throwing on the first problem. An admin settings form needs to say\n * *which* field is wrong and why — \"pick at least one day\" beats a stack trace —\n * so the admin route returns these directly. {@link resolveScheduling} is the\n * throwing wrapper for internal/config-time use.\n */\nexport function validateScheduling(\n config?: ChapterScheduling,\n): { ok: true; value: ResolvedScheduling } | { ok: false; errors: SchedulingErrors } {\n const d = config ?? {};\n const c: ResolvedScheduling = {\n slotMinutes: d.slotMinutes ?? SCHEDULING_DEFAULTS.slotMinutes,\n days: d.days ?? SCHEDULING_DEFAULTS.days,\n startHour: d.startHour ?? SCHEDULING_DEFAULTS.startHour,\n endHour: d.endHour ?? SCHEDULING_DEFAULTS.endHour,\n timezone: d.timezone ?? SCHEDULING_DEFAULTS.timezone,\n minNoticeHours: d.minNoticeHours ?? SCHEDULING_DEFAULTS.minNoticeHours,\n windowDays: d.windowDays ?? SCHEDULING_DEFAULTS.windowDays,\n summaryTemplate: d.summaryTemplate ?? SCHEDULING_DEFAULTS.summaryTemplate,\n };\n const errors: SchedulingErrors = {};\n if (!(c.slotMinutes >= 15 && c.slotMinutes <= 240)) {\n errors.slotMinutes = \"Slot length must be between 15 and 240 minutes.\";\n }\n if (!(c.windowDays >= 1 && c.windowDays <= 62)) {\n errors.windowDays = \"Booking window must be between 1 and 62 days (the calendar caps look-ahead at 62).\";\n }\n if (!(c.minNoticeHours >= 0 && c.minNoticeHours <= 336)) {\n errors.minNoticeHours = \"Minimum notice must be between 0 and 336 hours.\";\n }\n if (!(c.startHour >= 0 && c.startHour < c.endHour && c.endHour <= 24)) {\n errors.hours = \"Hours must satisfy 0 ≤ start < end ≤ 24.\";\n }\n const days = [...c.days];\n if (!days.length) errors.days = \"Pick at least one day.\";\n else if (!days.every((n) => Number.isInteger(n) && n >= 0 && n <= 6)) {\n errors.days = \"Days must be weekday numbers, 0 (Sunday) through 6 (Saturday).\";\n }\n if (typeof c.timezone !== \"string\" || !isValidTimeZone(c.timezone)) {\n errors.timezone = `\"${String(c.timezone)}\" is not a valid IANA timezone (for example \"America/Los_Angeles\").`;\n }\n if (typeof c.summaryTemplate !== \"string\") errors.summaryTemplate = \"Calendar summary template must be text.\";\n return Object.keys(errors).length > 0 ? { ok: false, errors } : { ok: true, value: { ...c, days } };\n}\n\n/** Statuses a member may book/reschedule from (early pipeline only). */\n// Booking eligibility is answered by the configured pipeline — canBook(status,\n// pipeline) in ./pipeline — not a hardcoded status list, so a chapter that\n// customizes its stages gets one consistent answer.\n\n/** The availability window: `[now, now + windowDays]` in epoch ms. */\nexport function slotWindow(now: number, windowDays: number): { from: number; to: number } {\n return { from: now, to: now + windowDays * 86_400_000 };\n}\n\n/** The slot's end instant, always derived from its start (never client-supplied). */\nexport function endForSlot(startAt: number, slotMinutes: number): number {\n return startAt + slotMinutes * 60_000;\n}\n\n/** Double-book pre-check: the requested start must land exactly on a currently\n * bookable slot boundary. */\nexport function isSlotAvailable(slots: readonly { startAt: number }[], startAt: number): boolean {\n return slots.some((s) => s.startAt === startAt);\n}\n\n/** Render a meeting summary from its template (`{{firstName}}`/`{{lastName}}`). */\nexport function renderSummary(template: string, app: { firstName?: string | null; lastName?: string | null }): string {\n return template.replace(\"{{firstName}}\", app.firstName ?? \"\").replace(\"{{lastName}}\", app.lastName ?? \"\");\n}\n\n/** The prior scheduled meeting for an application, as far as booking cares. */\nexport interface ExistingMeeting {\n id: string;\n googleEventId?: string | null;\n meetUrl?: string | null;\n htmlLink?: string | null;\n}\n\n/** Decide reschedule-vs-create: reschedule iff there's an existing event to move,\n * so the Meet link + invite thread survive and no second event is minted. */\nexport function bookingDecision(existing: ExistingMeeting | null | undefined): { reschedule: boolean; eventId: string | null } {\n const eventId = existing?.googleEventId ?? null;\n return { reschedule: Boolean(eventId), eventId };\n}\n\n/** The create idempotency key — one intro event per application, forever, so a\n * retried create returns the same booking rather than a duplicate. */\nexport function introIdempotencyKey(applicationId: string): string {\n return `application:${applicationId}:intro`;\n}\n\n/** The canonical `meetings` row for a first booking. A `type` (not `interface`)\n * so it stays assignable to a db op's `attrs` (Record<string, unknown>). */\nexport type NewMeetingRow = {\n id: string;\n applicationId: string;\n groupId: string;\n startAt: number;\n endAt: number;\n timezone: string;\n status: \"scheduled\";\n googleEventId: string;\n meetUrl?: string;\n htmlLink?: string;\n drift: \"none\";\n createdAt: number;\n};\n\n/** Build the new `meetings` row after the calendar created the event. Optional\n * scalars are omitted (never null), per the odla-db porting rule. */\nexport function meetingCreateRow(i: {\n meetingId: string;\n applicationId: string;\n groupId: string;\n startAt: number;\n endAt: number;\n timezone: string;\n googleEventId: string;\n meetUrl?: string | null;\n htmlLink?: string | null;\n createdAt: number;\n}): NewMeetingRow {\n return {\n id: i.meetingId,\n applicationId: i.applicationId,\n groupId: i.groupId,\n startAt: i.startAt,\n endAt: i.endAt,\n timezone: i.timezone,\n status: \"scheduled\",\n googleEventId: i.googleEventId,\n ...(i.meetUrl ? { meetUrl: i.meetUrl } : {}),\n ...(i.htmlLink ? { htmlLink: i.htmlLink } : {}),\n drift: \"none\",\n createdAt: i.createdAt,\n };\n}\n\n/** The `meetings`-row patch for a reschedule (same row id, moved in place). */\nexport type MeetingReschedulePatch = {\n startAt: number;\n endAt: number;\n drift: \"none\";\n};\n\n/** Patch to move an existing meeting to a new window. */\nexport function meetingRescheduleUpdate(startAt: number, endAt: number): MeetingReschedulePatch {\n return { startAt, endAt, drift: \"none\" };\n}\n\n/** The `applications`-row patch after a booking. */\nexport type ApplicationBookingPatch = {\n meetingAt: number;\n meetingLink?: string;\n status?: \"call_scheduled\";\n};\n\n/** Project the booking onto the application row: cache the time, adopt the\n * calendar link if any, and advance the status to `call_scheduled` unless it is\n * already there (never backward). */\nexport function applicationBookingUpdate(\n currentStatus: string,\n startAt: number,\n htmlLink?: string | null,\n): ApplicationBookingPatch {\n return {\n meetingAt: startAt,\n ...(htmlLink ? { meetingLink: htmlLink } : {}),\n ...(currentStatus !== \"call_scheduled\" ? { status: \"call_scheduled\" as const } : {}),\n };\n}\n","// The member session — what GET /api/me returns to a signed-in applicant/member.\n// Ported from Silver & Salt's applicationSummary + /api/me reconciliation. The\n// SHAPING is pure and package-enforced so no site re-derives it; the worker owns\n// only the I/O around it (locating the application by email, reconciling the\n// meeting against the calendar) and hands the resolved rows here.\n//\n// Two invariants live here, not in a site:\n// - `paid` is DERIVED, never a stored flag: a subscription exists and the\n// application wasn't refunded. Sites can't drift a stale boolean out of sync\n// with Stripe.\n// - the live meeting row wins: its startAt/meetUrl/timezone override whatever\n// the application row cached, and a non-scheduled meeting (a cancellation\n// adopted from the calendar) forces meetingAt back to null.\n\n/** An application row, as far as the session cares about it. */\nexport interface ApplicationRecord {\n id: string;\n firstName?: string | null;\n lastName?: string | null;\n email?: string | null;\n status: string;\n meetingAt?: number | null;\n meetingLink?: string | null;\n createdAt?: number | null;\n stripeSubscriptionId?: string | null;\n renewalAt?: number | null;\n canceled?: boolean;\n}\n\n/** The reconciled meeting row (already adopted against the calendar), or null. */\nexport interface MeetingRecord {\n status: string;\n startAt?: number | null;\n meetUrl?: string | null;\n timezone?: string | null;\n}\n\n/** The stable, non-meeting fields of an application (safe to expose to its own\n * owner). */\nexport interface ApplicationSummary {\n id: string;\n firstName: string | null;\n lastName: string | null;\n email: string | null;\n status: string;\n createdAt: number | null;\n meetingLink: string | null;\n paid: boolean;\n renewalAt: number | null;\n canceled: boolean;\n}\n\n/** A summary plus the reconciled meeting fields — the `application` the member\n * area renders. */\nexport interface MemberApplication extends ApplicationSummary {\n meetingAt: number | null;\n meetUrl: string | null;\n timezone: string;\n}\n\n/** The full GET /api/me payload for a signed-in user. */\nexport interface MemberSession {\n userId: string;\n email: string | null;\n role: string;\n superAdmin: boolean;\n application: MemberApplication | null;\n}\n\n/** Derive the summary fields from an application row. `paid` is computed, not\n * read, so it can never contradict Stripe. */\nexport function applicationSummary(app: ApplicationRecord): ApplicationSummary {\n return {\n id: app.id,\n firstName: app.firstName ?? null,\n lastName: app.lastName ?? null,\n email: app.email ?? null,\n status: app.status,\n createdAt: app.createdAt ?? null,\n meetingLink: app.meetingLink ?? null,\n paid: Boolean(app.stripeSubscriptionId) && app.status !== \"refunded\",\n renewalAt: app.renewalAt ?? null,\n canceled: app.canceled === true,\n };\n}\n\n/** Fold a (possibly absent, already-reconciled) meeting into the application the\n * member area renders. The live meeting overrides the application's cached\n * meeting fields; a non-`scheduled` meeting clears the booking. */\nexport function memberApplication(\n app: ApplicationRecord,\n meeting: MeetingRecord | null | undefined,\n defaultTimezone: string,\n): MemberApplication {\n const summary = applicationSummary(app);\n let meetingAt = app.meetingAt ?? null;\n let meetUrl: string | null = null;\n let timezone = defaultTimezone;\n if (meeting) {\n timezone = meeting.timezone ?? timezone;\n if (meeting.status === \"scheduled\") {\n meetingAt = meeting.startAt ?? null;\n meetUrl = meeting.meetUrl ?? null;\n } else {\n meetingAt = null;\n }\n }\n return { ...summary, meetingAt, meetUrl, timezone };\n}\n\n/** Identity of the signed-in user, from the verified session. */\nexport interface SessionUser {\n userId: string;\n email?: string | null;\n role: string;\n}\n\n/** Assemble the GET /api/me payload. `application` is null when the user has no\n * application on file (an admin who never applied, or a brand-new account). */\nexport function memberSession(\n user: SessionUser,\n opts: { application: MemberApplication | null; superAdmin: boolean },\n): MemberSession {\n return {\n userId: user.userId,\n email: user.email ?? null,\n role: user.role,\n superAdmin: opts.superAdmin,\n application: opts.application,\n };\n}\n","// The chapter email pipeline: exactly-once delivery, a non-production fail-safe,\n// and template rendering. Every property here is easy to get wrong and expensive\n// to get wrong, so the correctness-critical decisions — the dedupe check (E1),\n// the dev-redirect / log-only fail-safe (E2), and template rendering (E4) — are\n// PURE and fully tested in this module. The worker supplies the transport +\n// odla-db and performs the actual send + emailLog write around these decisions.\n//\n// Chapter's operational templates ({ subject, text, enabled? }) are\n// transactional lifecycle mail by construction — a site owner edits the copy in\n// Settings but cannot reclassify one as marketing. Consent-gated marketing blasts\n// go through @odla-ai/crm, which owns the transactional-vs-marketing template\n// class as code (E3), so relabeling copy can never bypass the consent gate.\n\n/** One owner-editable template row on the group. `enabled` absent = enabled. */\nexport interface EmailTemplateRow {\n subject: string;\n text: string;\n enabled?: boolean;\n}\n\n/** The `groups`-row fields the email pipeline reads. */\nexport interface EmailGroup {\n id: string;\n name: string;\n replyTo: string;\n /** Non-prod debug inbox: all mail redirects here outside prod (E2). */\n debugEmail?: string;\n refundPolicyText?: string;\n commitmentText?: string;\n normsText?: string;\n emailTemplates: Record<string, EmailTemplateRow>;\n}\n\n/** `{{placeholder}}` substitution; unknown placeholders render empty. */\nexport function render(template: string, vars: Record<string, string>): string {\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (_, key: string) => vars[key] ?? \"\");\n}\n\n/** Group-level vars every template receives, under the caller's vars. */\nfunction groupVars(group: EmailGroup, vars: Record<string, string>): Record<string, string> {\n return {\n ...vars,\n refundPolicyText: group.refundPolicyText ?? \"\",\n commitmentText: group.commitmentText ?? \"\",\n normsText: group.normsText ?? \"\",\n };\n}\n\n/**\n * Re-render a template's body for history/preview (E4): the CRM comms history\n * reads back emails whose body predates `emailLog.body` by rendering the current\n * template with the recipient's vars. Same substitution + group vars as the send\n * path. `null` for an unknown template. Reflects the copy as it reads today, not\n * necessarily the exact bytes originally sent (only `emailLog.body` is byte-exact).\n */\nexport function renderTemplateBody(group: EmailGroup, template: string, vars: Record<string, string>): string | null {\n const tpl = group.emailTemplates?.[template];\n if (!tpl) return null;\n return render(tpl.text, groupVars(group, vars));\n}\n\n/**\n * E1 (exactly-once): given the prior `emailLog` rows for a `dedupeKey`, has the\n * mail already been delivered? A prior row with **no error** means yes — the\n * caller short-circuits the resend. Failure rows (which carry an `error` and are\n * written without the dedupe mutationId) do not count, so a retry after a failure\n * can still succeed.\n */\nexport function isAlreadySent(priorRows: ReadonlyArray<{ error?: unknown }>): boolean {\n return priorRows.some((row) => !row.error);\n}\n\n/** The pure delivery decision produced by {@link planDelivery}. */\nexport type DeliveryDecision =\n | { deliver: false; reason: \"template-missing\" | \"disabled\" }\n | {\n deliver: true;\n /** Which transport to use — `log-only` records the send but delivers nothing. */\n transport: \"cloudflare\" | \"log-only\";\n to: string;\n subject: string;\n text: string;\n /** True when redirected to the non-prod debug inbox. */\n redirected: boolean;\n };\n\n/**\n * The pure delivery decision (E2 fail-safe + E3 enabled). Given the env, group,\n * template, recipient, and whether a real Cloudflare transport is wired:\n * - missing template → not delivered (`template-missing`);\n * - disabled template and not forced → not delivered (`disabled`);\n * - **non-prod with a debug inbox** → REDIRECT to it, `\"[dev] \"` subject prefix,\n * a dev-redirect note in the body, so test applicants never receive real mail;\n * - **non-prod with NO debug inbox** → force `log-only` (deliver nothing) — the\n * fail-safe that protects every site's test data;\n * - prod → deliver via the real transport (`cloudflare` if wired, else `log-only`).\n */\nexport function planDelivery(input: {\n envName: string;\n group: EmailGroup;\n template: string;\n to: string;\n vars: Record<string, string>;\n /** Whether a Cloudflare Email Service transport (binding + verified from) is wired. */\n cloudflareReady: boolean;\n /** The admin test route may send a disabled template. */\n force?: boolean;\n}): DeliveryDecision {\n const tpl = input.group.emailTemplates?.[input.template];\n if (!tpl) return { deliver: false, reason: \"template-missing\" };\n if (tpl.enabled === false && !input.force) return { deliver: false, reason: \"disabled\" };\n\n const vars = groupVars(input.group, input.vars);\n const isProd = input.envName === \"prod\";\n const redirect = !isProd && !!input.group.debugEmail;\n const transport: \"cloudflare\" | \"log-only\" =\n !isProd && !redirect ? \"log-only\" : input.cloudflareReady ? \"cloudflare\" : \"log-only\";\n const to = redirect ? (input.group.debugEmail as string) : input.to;\n const subject = (redirect ? \"[dev] \" : \"\") + render(tpl.subject, vars);\n const text = redirect\n ? `(dev redirect; original recipient: ${input.to})\\n\\n` + render(tpl.text, vars)\n : render(tpl.text, vars);\n return { deliver: true, transport, to, subject, text, redirected: redirect };\n}\n","// sendTemplated — the operational-email orchestration that wires the pure email\n// decisions (./email: isAlreadySent E1, planDelivery E2/E3) to odla-db + a\n// transport. Structural (takes a ChapterDb + a sender), so it's FakeDb-testable\n// like submitApplication/projectSharedRecord. The worker's lifecycle routes call\n// it to send the prep / payment-confirmation / admin-alert mail.\n//\n// Exactly-once is enforced twice: a prior successful emailLog row short-circuits\n// the resend (query + isAlreadySent), AND the success row is written under the\n// `email:${dedupeKey}` mutationId so a racing double-send dedupes at the db layer.\n// Failure rows omit the mutationId, so a retry after a transient failure can send.\nimport { isAlreadySent, planDelivery } from \"./email\";\nimport type { EmailGroup } from \"./email\";\nimport type { ChapterDb } from \"./types\";\n\n/** The canonical lifecycle email templates chapter fires, in send-order. Owner-\n * editable copy lives on the group row; this is the fixed set the admin email\n * editor + test route iterate. */\nexport const EMAIL_TEMPLATE_NAMES = [\"adminNotification\", \"paymentConfirmation\", \"prepEmail\", \"onboardingInvite\"] as const;\n\n/** One of {@link EMAIL_TEMPLATE_NAMES}. */\nexport type EmailTemplateName = (typeof EMAIL_TEMPLATE_NAMES)[number];\n\n/** The mail transport (the worker's Cloudflare SEND_EMAIL binding). */\nexport interface MailSender {\n send(payload: { from: string; to: string[]; subject: string; text?: string; replyTo?: string }): Promise<{ messageId: string }>;\n}\n\n/** Deps for {@link sendTemplated} — the db, the env name (drives the fail-safe),\n * the transport + from (absent ⇒ log-only), and injected clock/id. */\nexport interface NotifyDeps {\n db: ChapterDb;\n envName: string;\n sender?: MailSender;\n from?: string;\n now: () => number;\n newId: () => string;\n}\n\n/** One templated send. `dedupeKey` is the exactly-once key. */\nexport interface NotifyInput {\n group: EmailGroup;\n template: string;\n to: string;\n vars: Record<string, string>;\n dedupeKey: string;\n applicationId?: string;\n /** The admin test route may send a disabled template. */\n force?: boolean;\n}\n\n/** The outcome. `sent:true` includes the already-sent short-circuit. */\nexport interface NotifyResult {\n sent: boolean;\n reason?: string;\n}\n\n/**\n * Send a templated lifecycle email exactly once. Short-circuits on a prior\n * successful send; otherwise plans delivery (dev fail-safe applies), sends via the\n * transport when one is wired and the plan calls for it, and records an emailLog\n * row either way (success keyed for exactly-once, failure unkeyed for retry).\n */\nexport async function sendTemplated(deps: NotifyDeps, input: NotifyInput): Promise<NotifyResult> {\n const { emailLog } = await deps.db.query({ emailLog: { $: { where: { dedupeKey: input.dedupeKey } } } });\n const prior = (Array.isArray(emailLog) ? emailLog : []) as Array<{ error?: unknown }>;\n if (isAlreadySent(prior)) return { sent: true, reason: \"already-sent\" };\n\n const cloudflareReady = Boolean(deps.sender && deps.from);\n const decision = planDelivery({\n envName: deps.envName,\n group: input.group,\n template: input.template,\n to: input.to,\n vars: input.vars,\n cloudflareReady,\n force: input.force,\n });\n if (!decision.deliver) return { sent: false, reason: decision.reason };\n\n let error: string | undefined;\n let messageId: string | undefined;\n if (decision.transport === \"cloudflare\" && deps.sender && deps.from) {\n try {\n const res = await deps.sender.send({\n from: deps.from,\n to: [decision.to],\n subject: decision.subject,\n text: decision.text,\n replyTo: input.group.replyTo,\n });\n messageId = res.messageId;\n } catch (e) {\n error = e instanceof Error ? e.message : String(e);\n }\n }\n\n const id = deps.newId();\n const row: Record<string, unknown> = {\n id,\n groupId: input.group.id,\n to: decision.to,\n template: input.template,\n subject: decision.subject,\n body: decision.text,\n transport: decision.transport,\n redirected: decision.redirected,\n dedupeKey: input.dedupeKey,\n sentAt: deps.now(),\n ...(input.applicationId ? { applicationId: input.applicationId } : {}),\n ...(messageId ? { messageId } : {}),\n ...(error ? { error } : {}),\n };\n await deps.db.transact([{ t: \"update\", ns: \"emailLog\", id, attrs: row }], error ? undefined : { mutationId: `email:${input.dedupeKey}` });\n return error ? { sent: false, reason: error } : { sent: true };\n}\n\n/** Project a `groups` row into the {@link EmailGroup} the email pipeline reads. */\nexport function emailGroupFrom(row: Record<string, unknown>): EmailGroup {\n const str = (v: unknown): string | undefined => (typeof v === \"string\" ? v : undefined);\n const templates = row.emailTemplates && typeof row.emailTemplates === \"object\" ? row.emailTemplates : {};\n return {\n id: String(row.id),\n name: String(row.name ?? \"\"),\n replyTo: str(row.replyTo) ?? \"\",\n debugEmail: str(row.debugEmail),\n refundPolicyText: str(row.refundPolicyText),\n commitmentText: str(row.commitmentText),\n normsText: str(row.normsText),\n emailTemplates: templates as EmailGroup[\"emailTemplates\"],\n };\n}\n","// Scheduling routes: GET /api/schedule/slots + POST /api/schedule/book. This\n// file owns the I/O — Google FreeBusy, the pure computeBookableSlots, the\n// calendar create/reschedule, and the db writes — and delegates every\n// correctness rule to ./scheduling. Calendar is RUNTIME-optional: a chapter with\n// no connected calendar has freeBusy throw, so /slots answers\n// { schedulingReady: false } (200) and the join flow degrades to \"we'll reach\n// out by email\" rather than erroring.\nimport { computeBookableSlots, initCalendar } from \"@odla-ai/calendar\";\nimport { emailGroupFrom, sendTemplated } from \"./notify\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, WorkerContext } from \"./worker-context\";\nimport type { Route } from \"./worker-routes\";\nimport type { ChapterDb, ChapterScheduling, DbOp } from \"./types\";\nimport { canBook } from \"./pipeline\";\nimport {\n applicationBookingUpdate,\n bookingDecision,\n endForSlot,\n introIdempotencyKey,\n isSlotAvailable,\n meetingCreateRow,\n meetingRescheduleUpdate,\n renderSummary,\n resolveScheduling,\n slotWindow,\n} from \"./scheduling\";\nimport type { ExistingMeeting, ResolvedScheduling } from \"./scheduling\";\n\ntype Cal = ReturnType<typeof initCalendar>;\ntype Row = Record<string, unknown>;\n\n/** The stable `.code` off an OdlaError/provider error, else a safe default. */\nfunction errCode(err: unknown): string {\n if (err && typeof err === \"object\") {\n const code = (err as { code?: unknown }).code;\n if (typeof code === \"string\") return code;\n }\n return \"calendar_unavailable\";\n}\n\nfunction makeCalendar(env: ChapterEnv): Cal {\n // Calendar uses ODLA_APP_ID + ODLA_PLATFORM — distinct from the db client's\n // ODLA_TENANT + ODLA_ENDPOINT.\n return initCalendar({ appId: env.ODLA_APP_ID, env: env.ODLA_ENV, adminToken: env.ODLA_API_KEY, endpoint: env.ODLA_PLATFORM });\n}\n\nasync function firstRow(db: ChapterDb, ns: string, q: Record<string, unknown>): Promise<Row | undefined> {\n const res = await db.query({ [ns]: { $: q } });\n const rows = res[ns];\n return Array.isArray(rows) ? rows[0] : undefined;\n}\n\nasync function computeSlots(cal: Cal, cfg: ResolvedScheduling): Promise<Array<{ startAt: number; endAt: number }>> {\n const { from, to } = slotWindow(Date.now(), cfg.windowDays);\n const fb = await cal.availability.freeBusy({ timeMin: from, timeMax: to });\n return computeBookableSlots(fb.busy, {\n from: fb.timeMin,\n to: fb.timeMax,\n timezone: cfg.timezone,\n slotMinutes: cfg.slotMinutes,\n businessHours: { days: [...cfg.days], startHour: cfg.startHour, endHour: cfg.endHour },\n minNoticeMs: cfg.minNoticeHours * 3_600_000,\n });\n}\n\nasync function bookSlot(req: Request, env: ChapterEnv, ctx: WorkerContext): Promise<Response> {\n let body: Row;\n try {\n body = JSON.parse(await req.text()) as Row;\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n const applicationId = typeof body.applicationId === \"string\" ? body.applicationId : \"\";\n const startAt = Number(body.startAt);\n if (!applicationId || !Number.isFinite(startAt)) return json({ error: \"applicationId and startAt required\" }, 400);\n\n const db = ctx.makeDb(env) as unknown as ChapterDb;\n const app = await firstRow(db, \"applications\", { where: { id: applicationId }, limit: 1 });\n if (!app) return json({ error: \"not found\" }, 404);\n const status = String(app.status ?? \"\");\n if (!canBook(status, ctx.chapter.pipeline)) return json({ error: `cannot book from status \"${status}\"` }, 409);\n\n const group = await firstRow(db, \"groups\", { where: { id: String(app.groupId ?? ctx.chapter.id) }, limit: 1 });\n if (!group) return json({ error: \"group not found\" }, 500);\n const cfg = resolveScheduling(group.schedulingJson as ChapterScheduling | undefined);\n const endAt = endForSlot(startAt, cfg.slotMinutes);\n const cal = makeCalendar(env);\n\n // Double-book guard, layer 1: the requested start must still be a live slot.\n let slots: Array<{ startAt: number }>;\n try {\n slots = await computeSlots(cal, cfg);\n } catch (err) {\n return json({ error: \"scheduling unavailable\", code: errCode(err) }, 503);\n }\n if (!isSlotAvailable(slots, startAt)) return json({ error: \"slot no longer available\", code: \"calendar_slot_unavailable\" }, 409);\n\n const summary = renderSummary(cfg.summaryTemplate, { firstName: app.firstName as string, lastName: app.lastName as string });\n const existing = (await firstRow(db, \"meetings\", {\n where: { applicationId, status: \"scheduled\" },\n order: { createdAt: \"desc\" },\n limit: 1,\n })) as ExistingMeeting | undefined;\n const decision = bookingDecision(existing);\n\n let meetUrl: string | null = null;\n let htmlLink: string | null = null;\n let meetingOp: DbOp;\n try {\n if (decision.reschedule && decision.eventId) {\n // Reschedule the SAME event — the Meet link + invite thread survive.\n await cal.actions.reschedule(decision.eventId, { startAt, endAt });\n meetUrl = (existing?.meetUrl as string | undefined) ?? null;\n htmlLink = (existing?.htmlLink as string | undefined) ?? null;\n meetingOp = { t: \"update\", ns: \"meetings\", id: String(existing?.id), attrs: meetingRescheduleUpdate(startAt, endAt) };\n } else {\n const { booking } = await cal.actions.create(\n { summary, startAt, endAt, attendees: [String(app.email)], timezone: cfg.timezone, meet: true },\n { idempotencyKey: introIdempotencyKey(applicationId) },\n );\n meetUrl = booking.meetUrl ?? null;\n htmlLink = booking.htmlLink ?? null;\n const meetingId = crypto.randomUUID();\n meetingOp = {\n t: \"update\",\n ns: \"meetings\",\n id: meetingId,\n attrs: meetingCreateRow({\n meetingId,\n applicationId,\n groupId: String(group.id),\n startAt,\n endAt,\n timezone: cfg.timezone,\n googleEventId: booking.eventId,\n meetUrl: booking.meetUrl,\n htmlLink: booking.htmlLink,\n createdAt: Date.now(),\n }),\n };\n }\n } catch (err) {\n const code = errCode(err);\n // Double-book guard, layer 2 (authoritative): the provider rejected under lease.\n if (code === \"calendar_slot_unavailable\") return json({ error: \"slot no longer available\", code }, 409);\n return json({ error: \"booking failed\", code }, 502);\n }\n\n // meetings row is canonical; the application row is the projection.\n const appOp: DbOp = { t: \"update\", ns: \"applications\", id: applicationId, attrs: applicationBookingUpdate(status, startAt, htmlLink) };\n await db.transact([meetingOp, appOp]);\n\n // Prep email — best-effort, exactly-once per application (never fails the booking).\n if (typeof app.email === \"string\" && app.email) {\n await sendTemplated(\n { db, envName: env.ODLA_ENV, sender: env.SEND_EMAIL, from: env.EMAIL_FROM, now: () => Date.now(), newId: () => crypto.randomUUID() },\n { group: emailGroupFrom(group), template: \"prepEmail\", to: app.email, vars: { firstName: String(app.firstName ?? \"\") }, dedupeKey: `prep:${applicationId}`, applicationId },\n ).catch(() => undefined);\n }\n\n return json({ ok: true, startAt, endAt, meetUrl, rescheduled: decision.reschedule });\n}\n\n/** GET /api/schedule/slots + POST /api/schedule/book (chapter mode only). */\nexport const handleSchedule: Route = async (req, url, env, ctx) => {\n if (ctx.chapter.mode !== \"chapter\") return null;\n\n if (req.method === \"GET\" && url.pathname === \"/api/schedule/slots\") {\n const db = ctx.makeDb(env) as unknown as ChapterDb;\n const group = await firstRow(db, \"groups\", { where: { id: url.searchParams.get(\"group\") ?? ctx.chapter.id }, limit: 1 });\n if (!group) return json({ error: \"not found\" }, 404);\n const cfg = resolveScheduling(group.schedulingJson as ChapterScheduling | undefined);\n try {\n const slots = await computeSlots(makeCalendar(env), cfg);\n return json({ schedulingReady: true, timezone: cfg.timezone, slotMinutes: cfg.slotMinutes, slots });\n } catch (err) {\n return json({ schedulingReady: false, code: errCode(err) });\n }\n }\n\n if (req.method === \"POST\" && url.pathname === \"/api/schedule/book\") {\n return bookSlot(req, env, ctx);\n }\n\n return null;\n};\n","// The application status pipeline — config, not code. Which statuses exist, which\n// a member can book an intro call from, and which an admin can approve from\n// differ per site; the one invariant every site wants is that status never moves\n// backwards. All of this is pure + tested here; the worker enforces it on every\n// status write, and the CRM record.stage mirrors application.status (never the\n// reverse). Defaults reproduce Silver & Salt's pipeline exactly.\nimport type { ChapterPipeline, ResolvedPipeline } from \"./types\";\n\nconst DEFAULT_STAGES = [\n \"submitted\",\n \"paid_pending_vetting\",\n \"call_scheduled\",\n \"interviewed\",\n \"approved\",\n \"declined\",\n \"refunded\",\n] as const;\nconst DEFAULT_BOOKABLE = [\"submitted\", \"paid_pending_vetting\", \"call_scheduled\"] as const;\nconst DEFAULT_APPROVABLE = [\"paid_pending_vetting\", \"call_scheduled\", \"interviewed\"] as const;\n\n/**\n * Apply defaults + validate the pipeline config. With no config, the full Silver\n * & Salt pipeline. With `stages` given but the subsets omitted, the subsets\n * default to empty (a site opts in to bookable/approvable states explicitly).\n * Throws at import on a bad pipeline (empty/duplicate stages, an initial or a\n * subset entry not on the ladder).\n */\nexport function resolvePipeline(p: ChapterPipeline | undefined): ResolvedPipeline {\n const usingDefaults = !p?.stages;\n const stages = p?.stages ?? [...DEFAULT_STAGES];\n if (!Array.isArray(stages) || stages.length === 0 || !stages.every((s) => typeof s === \"string\" && s !== \"\")) {\n throw new Error(\"defineChapter.pipeline.stages: must be a non-empty array of status strings\");\n }\n if (new Set(stages).size !== stages.length) {\n throw new Error(\"defineChapter.pipeline.stages: statuses must be unique\");\n }\n const initial = p?.initial ?? (stages[0] as string);\n if (!stages.includes(initial)) {\n throw new Error(`defineChapter.pipeline.initial: \"${initial}\" is not one of the stages`);\n }\n const bookableFrom = p?.bookableFrom ?? (usingDefaults ? [...DEFAULT_BOOKABLE] : []);\n const approvableFrom = p?.approvableFrom ?? (usingDefaults ? [...DEFAULT_APPROVABLE] : []);\n for (const [name, subset] of [\n [\"bookableFrom\", bookableFrom],\n [\"approvableFrom\", approvableFrom],\n ] as const) {\n for (const s of subset) {\n if (!stages.includes(s)) throw new Error(`defineChapter.pipeline.${name}: \"${s}\" is not one of the stages`);\n }\n }\n return { stages, bookableFrom, approvableFrom, initial };\n}\n\n/** The ordinal of a status in the ladder, or -1 if unknown. */\nexport function stageIndex(status: string, p: ResolvedPipeline): number {\n return p.stages.indexOf(status);\n}\n\n/**\n * The status-never-moves-backwards invariant: a transition is allowed only when\n * both statuses are on the ladder and `to` is at or ahead of `from`. The worker\n * calls this before every status write; a violation is a 409, never a silent\n * downgrade.\n */\nexport function canTransition(from: string, to: string, p: ResolvedPipeline): boolean {\n const fi = p.stages.indexOf(from);\n const ti = p.stages.indexOf(to);\n return fi >= 0 && ti >= 0 && ti >= fi;\n}\n\n/** May an intro call be booked from this status? */\nexport function canBook(status: string, p: ResolvedPipeline): boolean {\n return p.bookableFrom.includes(status);\n}\n\n/** May an application be approved (→ member) from this status? */\nexport function canApprove(status: string, p: ResolvedPipeline): boolean {\n return p.approvableFrom.includes(status);\n}\n","// Payments primitives. The webhook-integrity check below is security-critical and\n// easy to get wrong, so it is pure and tested here; the worker wires a payments\n// provider (Stripe first — subscription create, webhook ingest, refund) around\n// it, and every resulting db write carries an event-derived mutationId for\n// exactly-once. Sites that don't charge omit payments entirely (paymentsReady:\n// false), so nothing here is imported unless a chapter runs the payment flow.\n\n/** Parse a Stripe-style `Stripe-Signature` header (`t=<unix>,v1=<hex>`). */\nfunction parseSigHeader(header: string): { t?: string; v1?: string } {\n const parts: Record<string, string> = {};\n for (const p of header.split(\",\")) {\n const [k, v] = p.split(\"=\", 2);\n if (k && v !== undefined) parts[k] = v;\n }\n return { t: parts.t, v1: parts.v1 };\n}\n\nfunction toHex(buf: ArrayBuffer): string {\n return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/** Constant-time compare of two equal-length hex strings. */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n return diff === 0;\n}\n\n/**\n * Verify a Stripe webhook signature (C3): HMAC-SHA256 over `` `${t}.${payload}` ``\n * with the endpoint signing secret, a replay window (default 5 minutes), and a\n * constant-time compare. Package-enforced — never left to a site. Returns `false`\n * (never throws) on a malformed header, a non-numeric or stale timestamp, or a\n * signature mismatch. `now`/`toleranceSec` are injectable for tests.\n */\nexport async function verifyStripeSignature(\n payload: string,\n header: string,\n secret: string,\n opts: { now?: number; toleranceSec?: number } = {},\n): Promise<boolean> {\n const { t, v1 } = parseSigHeader(header);\n if (!t || !v1) return false;\n const ts = Number(t);\n if (!Number.isFinite(ts)) return false;\n const nowSec = (opts.now ?? Date.now()) / 1000;\n const tolerance = opts.toleranceSec ?? 300;\n if (Math.abs(nowSec - ts) > tolerance) return false;\n\n const enc = new TextEncoder();\n const key = await crypto.subtle.importKey(\"raw\", enc.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n const mac = await crypto.subtle.sign(\"HMAC\", key, enc.encode(`${t}.${payload}`));\n return timingSafeEqual(toHex(mac), v1);\n}\n\n// ── readiness + Stripe wire helpers ──\n\n/** A group row's payment configuration, as far as readiness cares. */\nexport interface PaymentsGroup {\n stripePublishableKey?: string | null;\n stripePriceId?: string | null;\n}\n\n/** Whether a group can take payment: a publishable key + a price id (both on the\n * group row) AND a secret key (the vault). Anything missing drops the join\n * flow's payment step (paymentsReady:false) rather than half-charging. */\nexport function paymentsReady(group: PaymentsGroup, hasSecretKey: boolean): boolean {\n return Boolean(group.stripePublishableKey && group.stripePriceId && hasSecretKey);\n}\n\n/** Form-encode params for Stripe's x-www-form-urlencoded API, expanding one level\n * of nested objects into bracket syntax (`metadata[applicationId]=...`). */\nexport function stripeForm(params: Record<string, unknown>): string {\n const out = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v === undefined || v === null) continue;\n if (typeof v === \"object\") {\n for (const [k2, v2] of Object.entries(v as Record<string, unknown>)) {\n if (v2 !== undefined && v2 !== null) out.append(`${k}[${k2}]`, String(v2));\n }\n } else {\n out.append(k, String(v));\n }\n }\n return out.toString();\n}\n\n/** The Stripe idempotency key for creating an application's subscription — one\n * per application, so a client retry can't orphan a second subscription (S&S\n * lacked this; the package enforces it). */\nexport function subscriptionIdempotencyKey(applicationId: string): string {\n return `sub:${applicationId}`;\n}\n\n/** The db mutationId for a webhook-driven write — exactly-once per Stripe event,\n * so replays are deduped at the db layer. */\nexport function webhookMutationId(eventId: string): string {\n return `stripe:${eventId}`;\n}\n\n// ── webhook normalization (pure; the worker owns the db lookup + writes) ──\n\n/** A raw Stripe event, as far as normalization cares. */\nexport interface StripeEvent {\n id: string;\n type: string;\n data?: { object?: Record<string, unknown> };\n}\n\n/** A normalized, provider-agnostic webhook event. `kind` drives the db write;\n * the application is resolved from `applicationId` (metadata) or `customerId`. */\nexport type WebhookEvent =\n | { kind: \"first_payment\"; applicationId?: string; customerId?: string; renewalAt?: number }\n | { kind: \"renewal\"; applicationId?: string; customerId?: string; renewalAt?: number }\n | { kind: \"refunded\"; applicationId?: string; customerId?: string }\n | { kind: \"canceled\"; applicationId?: string; customerId?: string }\n | { kind: \"ignored\"; type: string };\n\n/** Resolve the application reference on a Stripe object: `applicationId` from\n * metadata (direct, then subscription_details, then nested\n * parent.subscription_details), plus the customer id for the db fallback. */\nexport function findApplicationRef(obj: Record<string, unknown>): { applicationId?: string; customerId?: string } {\n const metaOf = (v: unknown): Record<string, unknown> =>\n v && typeof v === \"object\" ? ((v as Record<string, unknown>).metadata as Record<string, unknown>) ?? {} : {};\n const pick = (m: Record<string, unknown>): string | undefined =>\n typeof m.applicationId === \"string\" ? m.applicationId : undefined;\n const applicationId =\n pick(metaOf(obj)) ?? pick(metaOf(obj.subscription_details)) ?? pick(metaOf((obj.parent as Record<string, unknown> | undefined)?.subscription_details));\n const customerId = typeof obj.customer === \"string\" ? obj.customer : undefined;\n return { ...(applicationId ? { applicationId } : {}), ...(customerId ? { customerId } : {}) };\n}\n\n/** Normalize a verified Stripe event into a {@link WebhookEvent}. `invoice.paid`\n * splits into first_payment vs renewal by `billing_reason`; refunds and\n * cancellations map directly; everything else is ignored (acked, not retried). */\nexport function normalizeWebhookEvent(event: StripeEvent): WebhookEvent {\n const obj = event.data?.object ?? {};\n const ref = findApplicationRef(obj);\n switch (event.type) {\n case \"invoice.paid\": {\n const lines = ((obj.lines as Record<string, unknown> | undefined)?.data as Array<Record<string, unknown>> | undefined) ?? [];\n const periodEnd = (lines[0]?.period as Record<string, unknown> | undefined)?.end;\n const renewalAt = typeof periodEnd === \"number\" ? periodEnd * 1000 : undefined;\n const kind = obj.billing_reason === \"subscription_create\" ? \"first_payment\" : \"renewal\";\n return { kind, ...ref, ...(renewalAt !== undefined ? { renewalAt } : {}) };\n }\n case \"charge.refunded\":\n return { kind: \"refunded\", ...ref };\n case \"customer.subscription.deleted\":\n return { kind: \"canceled\", ...ref };\n default:\n return { kind: \"ignored\", type: event.type };\n }\n}\n\n// ── webhook write-set builders (the authoritative writers of paid/refunded) ──\n\n/** First-payment patch: advance submitted→paid_pending_vetting (never any other\n * transition) and record the renewal date. Empty when nothing changed, so the\n * caller can skip the write. */\nexport function firstPaymentPatch(currentStatus: string, renewalAt?: number): { status?: \"paid_pending_vetting\"; renewalAt?: number } {\n return {\n ...(currentStatus === \"submitted\" ? { status: \"paid_pending_vetting\" as const } : {}),\n ...(renewalAt !== undefined ? { renewalAt } : {}),\n };\n}\n\n/** Renewal-invoice patch: just the new renewal date. */\nexport function renewalPatch(renewalAt: number): { renewalAt: number } {\n return { renewalAt };\n}\n\n/** Refund patch — the SOLE writer of status \"refunded\" (the admin refund route\n * issues the Stripe refund but never sets this; the webhook does). */\nexport function refundedPatch(): { status: \"refunded\" } {\n return { status: \"refunded\" };\n}\n\n/** Subscription-cancellation patch. */\nexport function canceledPatch(): { canceled: true } {\n return { canceled: true };\n}\n","// The Stripe payments provider — the only I/O half of payments. Talks to the\n// Stripe REST API over fetch (no SDK), and maps 1:1 onto the pure helpers in\n// ./payments (form encoding, signature verify, event normalization). The worker\n// resolves secrets from the vault per request and constructs this; the routes own\n// every db write so idempotency stays at the db layer.\nimport { normalizeWebhookEvent, stripeForm, verifyStripeSignature } from \"./payments\";\nimport type { StripeEvent, WebhookEvent } from \"./payments\";\n\n/** Inputs to create an application's founding-member subscription. */\nexport interface CreateSubscriptionInput {\n applicationId: string;\n groupId: string;\n email: string;\n name: string;\n priceId: string;\n existingCustomerId?: string;\n}\n\n/** The client secret to confirm card entry, plus the ids to persist. */\nexport interface CreateSubscriptionResult {\n customerId: string;\n subscriptionId: string;\n clientSecret: string;\n}\n\n/** The outcome of a full refund. */\nexport interface RefundResult {\n refundedCents: number | null;\n subscriptionCanceled: boolean;\n}\n\n/** The capabilities the payment routes depend on — Stripe is one impl. */\nexport interface PaymentsProvider {\n createSubscription(input: CreateSubscriptionInput): Promise<CreateSubscriptionResult>;\n ingestWebhook(\n rawBody: string,\n sigHeader: string,\n ): Promise<{ ok: true; eventId: string; event: WebhookEvent } | { ok: false; reason: \"bad_signature\" }>;\n refund(input: { customerId: string; subscriptionId: string }): Promise<RefundResult>;\n}\n\n/** The result of a Stripe Backend API call: ok + status + parsed JSON body. */\nexport type StripeResult = { ok: boolean; status: number; body: Record<string, unknown> };\n\n/** Call the Stripe Backend API (form-encoded, Bearer sk_). Exposed so the admin\n * billing/dashboard reads and the refund route share one Stripe client instead\n * of each re-deriving the auth + encoding. */\nexport async function stripeCall(\n sk: string,\n method: \"GET\" | \"POST\" | \"DELETE\",\n path: string,\n params?: Record<string, unknown>,\n idempotencyKey?: string,\n): Promise<StripeResult> {\n const qs = method === \"GET\" && params ? `?${stripeForm(params)}` : \"\";\n const headers: Record<string, string> = { authorization: `Bearer ${sk}` };\n if (idempotencyKey) headers[\"idempotency-key\"] = idempotencyKey;\n const init: RequestInit = { method, headers };\n if (method === \"POST\" && params) {\n headers[\"content-type\"] = \"application/x-www-form-urlencoded\";\n init.body = stripeForm(params);\n }\n const res = await fetch(`https://api.stripe.com${path}${qs}`, init);\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n return { ok: res.ok, status: res.status, body };\n}\n\nfunction fail(op: string, r: StripeResult): never {\n const err = new Error(`stripe ${op} failed: ${r.status}`) as Error & { code: string };\n err.code = \"stripe_error\";\n throw err;\n}\n\nfunction clientSecretOf(sub: Record<string, unknown>): string | undefined {\n const inv = sub.latest_invoice as Record<string, unknown> | undefined;\n const confirmation = inv?.confirmation_secret as Record<string, unknown> | undefined;\n const intent = inv?.payment_intent as Record<string, unknown> | undefined;\n const secret = confirmation?.client_secret ?? intent?.client_secret;\n return typeof secret === \"string\" ? secret : undefined;\n}\n\nfunction requireSecret(secretKey: string | undefined): string {\n if (!secretKey) {\n const err = new Error(\"stripe secret key missing\") as Error & { code: string };\n err.code = \"not_configured\";\n throw err;\n }\n return secretKey;\n}\n\n/** Build the Stripe provider. `secretKey` powers charging/refunds; `webhookSecret`\n * powers webhook ingest. Each is resolved from the vault per request, so the\n * webhook route can construct an ingest-only provider without the secret key. */\nexport function createStripeProvider(config: { secretKey?: string; webhookSecret?: string }): PaymentsProvider {\n const { secretKey, webhookSecret } = config;\n return {\n async createSubscription(input) {\n const sk = requireSecret(secretKey);\n const meta = { applicationId: input.applicationId, groupId: input.groupId, email: input.email };\n let customerId = input.existingCustomerId;\n if (!customerId) {\n const cust = await stripeCall(\n sk,\n \"POST\",\n \"/v1/customers\",\n { email: input.email, name: input.name, metadata: meta },\n `cus:${input.applicationId}`,\n );\n if (!cust.ok) fail(\"customer create\", cust);\n customerId = String(cust.body.id);\n }\n const sub = await stripeCall(\n sk,\n \"POST\",\n \"/v1/subscriptions\",\n {\n customer: customerId,\n \"items[0][price]\": input.priceId,\n payment_behavior: \"default_incomplete\",\n \"payment_settings[save_default_payment_method]\": \"on_subscription\",\n \"payment_settings[payment_method_types][0]\": \"card\",\n \"expand[0]\": \"latest_invoice.confirmation_secret\",\n metadata: meta,\n },\n // The hardening S&S lacked: one subscription per application, so a client\n // retry between create and the db write can't orphan a second one.\n `sub:${input.applicationId}`,\n );\n if (!sub.ok) fail(\"subscription create\", sub);\n const clientSecret = clientSecretOf(sub.body);\n if (!clientSecret) fail(\"subscription confirmation-secret missing\", sub);\n return { customerId, subscriptionId: String(sub.body.id), clientSecret };\n },\n\n async ingestWebhook(rawBody, sigHeader) {\n if (!webhookSecret || !(await verifyStripeSignature(rawBody, sigHeader, webhookSecret))) {\n return { ok: false, reason: \"bad_signature\" };\n }\n const event = JSON.parse(rawBody) as StripeEvent;\n return { ok: true, eventId: event.id, event: normalizeWebhookEvent(event) };\n },\n\n async refund(input) {\n const sk = requireSecret(secretKey);\n const charges = await stripeCall(sk, \"GET\", \"/v1/charges\", { customer: input.customerId, limit: 100 });\n if (!charges.ok) fail(\"charges list\", charges);\n const rows = (charges.body.data as Array<Record<string, unknown>> | undefined) ?? [];\n const paid = rows.filter((c) => c.status === \"succeeded\" && c.refunded !== true);\n const charge = paid[paid.length - 1]; // Stripe returns newest-first; refund the earliest.\n if (!charge) {\n const err = new Error(\"no paid charge to refund\") as Error & { code: string };\n err.code = \"no_charge\";\n throw err;\n }\n const refund = await stripeCall(sk, \"POST\", \"/v1/refunds\", { charge: String(charge.id) });\n if (!refund.ok) fail(\"refund\", refund);\n const cancel = await stripeCall(sk, \"DELETE\", `/v1/subscriptions/${input.subscriptionId}`);\n const amount = refund.body.amount;\n return { refundedCents: typeof amount === \"number\" ? amount : null, subscriptionCanceled: cancel.ok };\n },\n };\n}\n","// Payment routes: POST /api/payments/subscription (start a founding-member\n// subscription), POST /api/webhooks/stripe (the AUTHORITATIVE writer of\n// paid/refunded/canceled, exactly-once per event id), and POST\n// /api/admin/applications/:id/refund (admin-gated; issues the refund but never\n// writes status — the charge.refunded webhook does). I/O only; the correctness\n// rules live in ./payments and the provider in ./payments-stripe.\nimport { getVaultSecret } from \"./auth\";\nimport { emailGroupFrom, sendTemplated } from \"./notify\";\nimport { canceledPatch, firstPaymentPatch, refundedPatch, renewalPatch, webhookMutationId } from \"./payments\";\nimport type { WebhookEvent } from \"./payments\";\nimport { createStripeProvider } from \"./payments-stripe\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, WorkerContext } from \"./worker-context\";\nimport type { Route } from \"./worker-routes\";\nimport type { ChapterDb } from \"./types\";\n\ntype Row = Record<string, unknown>;\n\nconst codeOf = (err: unknown): string =>\n err && typeof err === \"object\" && typeof (err as { code?: unknown }).code === \"string\" ? (err as { code: string }).code : \"unknown\";\n\nasync function firstRow(db: ChapterDb, ns: string, q: Record<string, unknown>): Promise<Row | undefined> {\n const res = await db.query({ [ns]: { $: q } });\n const rows = res[ns];\n return Array.isArray(rows) ? rows[0] : undefined;\n}\n\nfunction lineItems(group: Row): { standardCents: number; discountCents: number; dueTodayCents: number } {\n const standard = Number(group.standardPriceCents ?? 0);\n const discount = Number(group.foundingDiscountCents ?? 0);\n return { standardCents: standard, discountCents: discount, dueTodayCents: standard - discount };\n}\n\n// Resolve the application an event targets: by metadata applicationId, else the\n// newest row for the Stripe customer.\nasync function findApplication(db: ChapterDb, event: WebhookEvent): Promise<Row | undefined> {\n if (\"applicationId\" in event && event.applicationId) {\n return firstRow(db, \"applications\", { where: { id: event.applicationId }, limit: 1 });\n }\n if (\"customerId\" in event && event.customerId) {\n return firstRow(db, \"applications\", { where: { stripeCustomerId: event.customerId }, order: { createdAt: \"desc\" }, limit: 1 });\n }\n return undefined;\n}\n\n// Best-effort payment-confirmation to the applicant on the first successful\n// invoice. Exactly-once per Stripe event via the dedupeKey.\nasync function notifyPaymentConfirmed(db: ChapterDb, env: ChapterEnv, eventId: string, app: Row): Promise<void> {\n try {\n if (typeof app.email !== \"string\" || !app.email) return;\n const group = await firstRow(db, \"groups\", { where: { id: String(app.groupId ?? \"\") }, limit: 1 });\n if (!group) return;\n await sendTemplated(\n { db, envName: env.ODLA_ENV, sender: env.SEND_EMAIL, from: env.EMAIL_FROM, now: () => Date.now(), newId: () => crypto.randomUUID() },\n {\n group: emailGroupFrom(group),\n template: \"paymentConfirmation\",\n to: app.email,\n vars: { firstName: typeof app.firstName === \"string\" ? app.firstName : \"\" },\n dedupeKey: `${eventId}:confirm`,\n applicationId: String(app.id),\n },\n );\n } catch {\n // never let a confirmation-email failure affect the webhook 200\n }\n}\n\n// Best-effort admin notification at PAYMENT time — the alternative trigger to\n// notifying on submit (sends.adminNotification: \"payment\"). Same template, same\n// exactly-once dedupe, different moment.\nasync function notifyAdminOfPayment(db: ChapterDb, env: ChapterEnv, eventId: string, app: Row): Promise<void> {\n try {\n const group = await firstRow(db, \"groups\", { where: { id: String(app.groupId ?? \"\") }, limit: 1 });\n if (!group || typeof group.notificationEmail !== \"string\" || !group.notificationEmail) return;\n const s = (v: unknown): string => (typeof v === \"string\" ? v : \"\");\n await sendTemplated(\n { db, envName: env.ODLA_ENV, sender: env.SEND_EMAIL, from: env.EMAIL_FROM, now: () => Date.now(), newId: () => crypto.randomUUID() },\n {\n group: emailGroupFrom(group),\n template: \"adminNotification\",\n to: group.notificationEmail,\n vars: { firstName: s(app.firstName), lastName: s(app.lastName), email: s(app.email), phone: s(app.phone), state: s(app.state) },\n dedupeKey: `${eventId}:admin`,\n applicationId: String(app.id),\n },\n );\n } catch {\n // never let a notification failure affect the webhook 200\n }\n}\n\n// The application-row patch for a resolved event (empty = skip the write).\nfunction webhookPatch(event: WebhookEvent, status: string): Record<string, unknown> {\n switch (event.kind) {\n case \"first_payment\":\n return firstPaymentPatch(status, event.renewalAt);\n case \"renewal\":\n return event.renewalAt !== undefined ? renewalPatch(event.renewalAt) : {};\n case \"refunded\":\n return refundedPatch();\n case \"canceled\":\n return canceledPatch();\n default:\n return {};\n }\n}\n\nasync function startSubscription(req: Request, env: ChapterEnv, ctx: WorkerContext): Promise<Response> {\n let body: Row;\n try {\n body = JSON.parse(await req.text()) as Row;\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n const applicationId = typeof body.applicationId === \"string\" ? body.applicationId : \"\";\n if (!applicationId) return json({ error: \"applicationId required\" }, 400);\n if (body.refundPolicyAck !== true) return json({ error: \"refundPolicyAck required\" }, 400);\n\n const db = ctx.makeDb(env) as unknown as ChapterDb;\n const app = await firstRow(db, \"applications\", { where: { id: applicationId }, limit: 1 });\n if (!app) return json({ error: \"not found\" }, 404);\n // Single-charge guard: only from the initial state, so a re-post can't double-subscribe.\n if (app.status !== \"submitted\") return json({ error: \"already processed\" }, 409);\n\n const group = await firstRow(db, \"groups\", { where: { id: String(app.groupId ?? ctx.chapter.id) }, limit: 1 });\n const priceId = group?.stripePriceId;\n const secretKey = await getVaultSecret(db, \"stripe_secret_key\");\n if (!group || !priceId || !secretKey) return json({ error: \"payments not configured\" }, 503);\n\n const provider = createStripeProvider({ secretKey });\n let result;\n try {\n result = await provider.createSubscription({\n applicationId,\n groupId: String(group.id),\n email: String(app.email ?? \"\"),\n name: `${app.firstName ?? \"\"} ${app.lastName ?? \"\"}`.trim(),\n priceId: String(priceId),\n existingCustomerId: typeof app.stripeCustomerId === \"string\" ? app.stripeCustomerId : undefined,\n });\n } catch (err) {\n return json({ error: \"payment setup failed\", code: codeOf(err) }, 502);\n }\n\n await db.transact([\n {\n t: \"update\",\n ns: \"applications\",\n id: applicationId,\n attrs: { stripeCustomerId: result.customerId, stripeSubscriptionId: result.subscriptionId, refundPolicyAckAt: Date.now() },\n },\n ]);\n return json({ clientSecret: result.clientSecret, publishableKey: group.stripePublishableKey ?? null, lineItems: lineItems(group) });\n}\n\nasync function ingestWebhook(req: Request, env: ChapterEnv, ctx: WorkerContext): Promise<Response> {\n const db = ctx.makeDb(env) as unknown as ChapterDb;\n const webhookSecret = await getVaultSecret(db, \"stripe_webhook_secret\");\n if (!webhookSecret) return json({ error: \"webhook not configured\" }, 503);\n\n const rawBody = await req.text();\n const ingest = await createStripeProvider({ webhookSecret }).ingestWebhook(rawBody, req.headers.get(\"stripe-signature\") ?? \"\");\n if (!ingest.ok) return json({ error: \"invalid signature\" }, 400);\n const { eventId, event } = ingest;\n if (event.kind === \"ignored\") return json({ ok: true, ignored: event.type });\n\n const app = await findApplication(db, event);\n if (!app) return json({ ok: true, matched: false });\n\n const patch = webhookPatch(event, String(app.status ?? \"\"));\n if (Object.keys(patch).length) {\n await db.transact([{ t: \"update\", ns: \"applications\", id: String(app.id), attrs: patch }], { mutationId: webhookMutationId(eventId) });\n }\n if (event.kind === \"first_payment\") {\n await notifyPaymentConfirmed(db, env, eventId, app);\n if (ctx.chapter.sends.adminNotification === \"payment\") await notifyAdminOfPayment(db, env, eventId, app);\n }\n return json({ ok: true });\n}\n\nasync function refundApplication(req: Request, url: URL, env: ChapterEnv, ctx: WorkerContext): Promise<Response> {\n const rawDb = ctx.makeDb(env);\n const u = await ctx.verifyUser(req, env);\n if (!u || !(await ctx.isAdmin(rawDb, u))) return json({ error: \"forbidden\" }, 403);\n\n const id = url.pathname.split(\"/\")[4] ?? \"\";\n const db = rawDb as unknown as ChapterDb;\n const app = await firstRow(db, \"applications\", { where: { id }, limit: 1 });\n if (!app) return json({ error: \"not found\" }, 404);\n if (app.status === \"refunded\") return json({ error: \"already refunded\" }, 409);\n if (app.status === \"approved\") return json({ error: \"approved memberships are non-refundable\" }, 409);\n if (!app.stripeSubscriptionId) return json({ error: \"no subscription on file\" }, 409);\n if (!app.stripeCustomerId) return json({ error: \"no customer on file\" }, 409);\n\n const secretKey = await getVaultSecret(db, \"stripe_secret_key\");\n if (!secretKey) return json({ error: \"payments not configured\" }, 503);\n\n try {\n const result = await createStripeProvider({ secretKey }).refund({\n customerId: String(app.stripeCustomerId),\n subscriptionId: String(app.stripeSubscriptionId),\n });\n // Note: status \"refunded\" is NOT written here — the charge.refunded webhook is\n // the single writer, keeping Stripe the source of truth.\n return json({ ok: true, refundedCents: result.refundedCents, subscriptionCanceled: result.subscriptionCanceled });\n } catch (err) {\n const code = codeOf(err);\n return json({ error: \"refund failed\", code }, code === \"no_charge\" ? 409 : 502);\n }\n}\n\nconst REFUND_PATH = /^\\/api\\/admin\\/applications\\/[^/]+\\/refund$/;\n\n/** The payment routes (chapter mode). Webhook + subscription are public\n * (capability-guarded by the unguessable application id / the signed payload);\n * refund is admin-gated. */\nexport const handlePayments: Route = async (req, url, env, ctx) => {\n if (ctx.chapter.mode !== \"chapter\") return null;\n if (req.method === \"POST\" && url.pathname === \"/api/payments/subscription\") return startSubscription(req, env, ctx);\n if (req.method === \"POST\" && url.pathname === \"/api/webhooks/stripe\") return ingestWebhook(req, env, ctx);\n if (req.method === \"POST\" && REFUND_PATH.test(url.pathname)) return refundApplication(req, url, env, ctx);\n return null;\n};\n","// Admin operational routes. GET /api/admin/meetings is the admin agenda,\n// reconciled against the live platform calendar: it reads upcoming events through\n// @odla-ai/calendar (chapter never calls Google directly) and adopts any\n// owner-side move/cancel onto the canonical meetings row + the application\n// projection, via the pure ./reconcile logic. Admin-gated; the read still\n// succeeds (serving canonical rows) if the calendar is unavailable.\nimport { initCalendar } from \"@odla-ai/calendar\";\nimport { reconcileMeetings } from \"./reconcile\";\nimport type { LiveEvent, MeetingForReconcile, ReconcileDecision } from \"./reconcile\";\nimport { resolveScheduling, validateScheduling } from \"./scheduling\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, WorkerContext } from \"./worker-context\";\nimport type { Route } from \"./worker-routes\";\nimport type { ChapterDb, ChapterScheduling, DbOp } from \"./types\";\n\n// Load the admin's target group (query param `group`, else the chapter), gated on\n// an admin session. Returns [db, group] or a Response to short-circuit.\nasync function adminGroup(\n req: Request,\n env: ChapterEnv,\n ctx: WorkerContext,\n url: URL,\n): Promise<{ db: ChapterDb; group: Record<string, unknown> } | Response> {\n const rawDb = ctx.makeDb(env);\n const u = await ctx.verifyUser(req, env);\n if (!u || !(await ctx.isAdmin(rawDb, u))) return json({ error: \"forbidden\" }, 403);\n const db = rawDb as unknown as ChapterDb;\n const groupId = url.searchParams.get(\"group\") ?? ctx.chapter.id;\n const group = (await db.query({ groups: { $: { where: { id: groupId }, limit: 1 } } })).groups?.[0];\n if (!group) return json({ error: \"not found\" }, 404);\n return { db, group };\n}\n\n/** GET/PUT /api/admin/scheduling — read the group's booking rules, or replace\n * them (validated via resolveScheduling; a bad config is a 400, never persisted).\n * The backend for the availability-editor section. */\nexport const handleAdminScheduling: Route = async (req, url, env, ctx) => {\n if (url.pathname !== \"/api/admin/scheduling\" || (req.method !== \"GET\" && req.method !== \"PUT\")) return null;\n const got = await adminGroup(req, env, ctx, url);\n if (got instanceof Response) return got;\n const { db, group } = got;\n\n if (req.method === \"GET\") {\n return json({ scheduling: resolveScheduling(group.schedulingJson as ChapterScheduling | undefined) });\n }\n let body: unknown;\n try {\n body = JSON.parse(await req.text());\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n // Field-keyed messages, not a thrown string: an owner-facing settings form needs\n // to say which field is wrong and why.\n const checked = validateScheduling(body as ChapterScheduling);\n if (!checked.ok) return json({ error: \"invalid scheduling config\", errors: checked.errors }, 400);\n await db.transact([{ t: \"update\", ns: \"groups\", id: String(group.id), attrs: { schedulingJson: checked.value } }]);\n return json({ scheduling: checked.value });\n};\n\nasync function upcomingEvents(env: ChapterEnv): Promise<LiveEvent[]> {\n const cal = initCalendar({ appId: env.ODLA_APP_ID, env: env.ODLA_ENV, adminToken: env.ODLA_API_KEY, endpoint: env.ODLA_PLATFORM });\n const res = await cal.availability.upcoming();\n return res.events.map((e) => ({ eventId: e.eventId, status: e.status, startAt: e.startAt, endAt: e.endAt }));\n}\n\nfunction toReconcile(rows: Array<Record<string, unknown>>): MeetingForReconcile[] {\n return rows.map((m) => ({\n id: String(m.id),\n applicationId: String(m.applicationId),\n googleEventId: typeof m.googleEventId === \"string\" ? m.googleEventId : null,\n status: String(m.status ?? \"\"),\n startAt: typeof m.startAt === \"number\" ? m.startAt : null,\n endAt: typeof m.endAt === \"number\" ? m.endAt : null,\n }));\n}\n\n/** GET /api/admin/meetings — the scheduled agenda, reconciled against the live\n * calendar (adopts owner moves/cancellations onto the canonical rows). */\nexport const handleAdminMeetings: Route = async (req, url, env, ctx) => {\n if (req.method !== \"GET\" || url.pathname !== \"/api/admin/meetings\") return null;\n const rawDb = ctx.makeDb(env);\n const u = await ctx.verifyUser(req, env);\n if (!u || !(await ctx.isAdmin(rawDb, u))) return json({ error: \"forbidden\" }, 403);\n const db = rawDb as unknown as ChapterDb;\n\n // ?all=1 includes cancelled/past rows; from/to bound the window (epoch ms).\n const all = url.searchParams.get(\"all\") === \"1\";\n const from = Number(url.searchParams.get(\"from\"));\n const to = Number(url.searchParams.get(\"to\"));\n\n const query = await db.query({\n meetings: { $: { where: all ? {} : { status: \"scheduled\" }, order: { startAt: \"asc\" }, limit: 500 } },\n });\n let rows = (Array.isArray(query.meetings) ? query.meetings : []) as Array<Record<string, unknown>>;\n if (Number.isFinite(from)) rows = rows.filter((m) => Number(m.startAt ?? 0) >= from);\n if (Number.isFinite(to)) rows = rows.filter((m) => Number(m.startAt ?? 0) <= to);\n\n let decisions: ReconcileDecision[] = [];\n try {\n decisions = reconcileMeetings(toReconcile(rows), await upcomingEvents(env), Date.now());\n } catch {\n // Calendar unavailable — serve the canonical rows without adopting edits.\n }\n\n // Apply adopt decisions (best-effort; the read still succeeds if a write fails).\n const patched = new Map<string, Record<string, unknown>>();\n for (const d of decisions) {\n const ops: DbOp[] = [\n { t: \"update\", ns: \"meetings\", id: d.meetingId, attrs: d.meetingPatch },\n { t: \"update\", ns: \"applications\", id: d.applicationId, attrs: d.applicationPatch },\n ];\n try {\n await db.transact(ops);\n patched.set(d.meetingId, d.meetingPatch);\n } catch {\n // leave the row as-is if the write fails\n }\n }\n\n // Join the applicant onto each row, and return the group timezone, so an admin\n // console can label and render the agenda without a second round trip. One\n // query, indexed by id — not N+1.\n const appQuery = await db.query({ applications: { $: { limit: 1000 } } });\n const byId = new Map<string, Record<string, unknown>>();\n for (const a of Array.isArray(appQuery.applications) ? appQuery.applications : []) {\n byId.set(String(a.id), a);\n }\n const applicantOf = (m: Record<string, unknown>): Record<string, unknown> | null => {\n const a = byId.get(String(m.applicationId));\n if (!a) return null;\n return { id: a.id, firstName: a.firstName, lastName: a.lastName, email: a.email, status: a.status };\n };\n\n const group = (await db.query({ groups: { $: { where: { id: ctx.chapter.id }, limit: 1 } } })).groups?.[0];\n const timezone = resolveScheduling(group?.schedulingJson as ChapterScheduling | undefined).timezone;\n\n // Reflect adopted patches; the row carries drift (drift, driftGoogleStartAt,\n // adoptedFromGoogleAt) and the Meet/Calendar links (meetUrl, htmlLink) already.\n const meetings = rows\n .map((m): Record<string, unknown> => ({ ...m, ...(patched.get(String(m.id)) ?? {}), applicant: applicantOf(m) }))\n .filter((m) => all || m.status === \"scheduled\");\n return json({ meetings, adopted: decisions.length, timezone });\n};\n","// The Google → chapter half of the bidirectional calendar sync. Booking writes\n// events TO the platform calendar (0.4.0's create/reschedule); this ADOPTS edits\n// FROM it: when the owner moves or cancels the intro call directly in Google,\n// reconcile mirrors that onto our canonical `meetings` row and the `application`\n// projection. Chapter never calls Google — the worker reads live events through\n// @odla-ai/calendar's upcoming() (platform-brokered) and applies the ops this\n// returns. Pure + testable; adoption policy (owner edits win) matches the shipped\n// Silver & Salt worker.\n\n/** A `meetings` row, as far as reconciliation cares. */\nexport interface MeetingForReconcile {\n id: string;\n applicationId: string;\n googleEventId?: string | null;\n status: string;\n startAt?: number | null;\n endAt?: number | null;\n}\n\n/** One live calendar event (a subset of @odla-ai/calendar's Booking). */\nexport interface LiveEvent {\n eventId: string;\n status?: string;\n startAt?: number;\n endAt?: number;\n}\n\n/** An adopt decision: mirror a Google move/cancel onto our rows. */\nexport interface ReconcileDecision {\n meetingId: string;\n applicationId: string;\n kind: \"cancelled\" | \"moved\";\n /** Attrs to write onto the `meetings` row. */\n meetingPatch: Record<string, unknown>;\n /** Attrs to write onto the `applications` row (the projection). */\n applicationPatch: Record<string, unknown>;\n}\n\n/** Meetings still worth reconciling: a scheduled booking with a Google event that\n * starts in the future (or within the last hour, to catch a just-passed edit). */\nexport function isReconcilable(meeting: MeetingForReconcile, now: number): boolean {\n return meeting.status === \"scheduled\" && Boolean(meeting.googleEventId) && (meeting.startAt ?? 0) > now - 3_600_000;\n}\n\n/**\n * Diff canonical `meetings` against the live calendar events and return the adopt\n * decisions — only for meetings that actually changed (a still-matching meeting\n * is omitted). A meeting whose event vanished or is `cancelled` in Google is\n * adopted as cancelled (application `meetingAt` zeroed — 0 means \"was booked,\n * then cancelled\"); a meeting whose event moved adopts the new window (duration\n * preserved when the event omits `endAt`).\n */\nexport function reconcileMeetings(\n meetings: readonly MeetingForReconcile[],\n events: readonly LiveEvent[],\n now: number,\n): ReconcileDecision[] {\n const byEvent = new Map(events.map((e) => [e.eventId, e]));\n const decisions: ReconcileDecision[] = [];\n for (const m of meetings) {\n if (!isReconcilable(m, now) || !m.googleEventId) continue;\n const g = byEvent.get(m.googleEventId);\n if (!g || g.status === \"cancelled\") {\n decisions.push({\n meetingId: m.id,\n applicationId: m.applicationId,\n kind: \"cancelled\",\n meetingPatch: { status: \"cancelled\", drift: \"none\", adoptedFromGoogleAt: now },\n applicationPatch: { meetingAt: 0, meetingLink: \"\" },\n });\n } else if (g.startAt !== undefined && g.startAt !== m.startAt) {\n const duration = (m.endAt ?? 0) - (m.startAt ?? 0);\n decisions.push({\n meetingId: m.id,\n applicationId: m.applicationId,\n kind: \"moved\",\n meetingPatch: { startAt: g.startAt, endAt: g.endAt ?? g.startAt + duration, drift: \"none\", adoptedFromGoogleAt: now },\n applicationPatch: { meetingAt: g.startAt },\n });\n }\n }\n return decisions;\n}\n","// The odla->Clerk write half: server-side Clerk role read/list/write, the gap\n// beside clerk.ts's create/invite/heal. Roles live in `public_metadata.role`; an\n// absent role means the lowest rung (\"provisional\") — chapter never writes it at\n// create. The role write is a MERGE-PATCH of only `{ role }`, so it never clobbers\n// the separately-written `public_metadata.profile` (Clerk merges public_metadata\n// per key; proven in the reference site's running role-change route). Chapter\n// calls the Clerk Backend API over fetch with the vault `clerk_secret_key`.\n\nconst CLERK_API = \"https://api.clerk.com\";\nconst DEFAULT_ROLE = \"provisional\";\nconst PAGE = 100;\n\n/** A Clerk user as chapter's role layer sees it. `role` defaults to the lowest\n * rung when `public_metadata` carries none; `publicMetadata` is returned raw so a\n * site with a custom ladder can re-derive it. */\nexport interface ClerkUserRecord {\n id: string;\n email?: string;\n role: string;\n publicMetadata: Record<string, unknown>;\n}\n\n// The Clerk Backend API user object — only the fields chapter reads.\ninterface ClerkApiUser {\n id?: unknown;\n email_addresses?: Array<{ email_address?: unknown }>;\n public_metadata?: Record<string, unknown>;\n}\n\nfunction toRecord(u: ClerkApiUser): ClerkUserRecord | null {\n if (typeof u.id !== \"string\") return null;\n const pm = (u.public_metadata ?? {}) as Record<string, unknown>;\n const role = typeof pm.role === \"string\" && pm.role ? pm.role : DEFAULT_ROLE;\n const email = u.email_addresses?.[0]?.email_address;\n return { id: u.id, email: typeof email === \"string\" ? email : undefined, role, publicMetadata: pm };\n}\n\nasync function clerkGet(path: string, secretKey: string, fetchImpl: typeof fetch): Promise<unknown> {\n const res = await fetchImpl(`${CLERK_API}${path}`, { headers: { authorization: `Bearer ${secretKey}` } });\n if (!res.ok) throw new Error(`clerk GET ${path} → ${res.status}`);\n return res.json();\n}\n\n/** Look a Clerk user up by email. `null` when no such user — or when the lookup\n * fails (a role gate treats an unresolvable user as absent, matching the site's\n * own fallback). Role defaults to provisional when unset. */\nexport async function clerkGetUserByEmail(secretKey: string, email: string, fetchImpl: typeof fetch = fetch): Promise<ClerkUserRecord | null> {\n const data = await clerkGet(`/v1/users?email_address=${encodeURIComponent(email)}&limit=1`, secretKey, fetchImpl).catch(() => null);\n const user = Array.isArray(data) ? (data[0] as ClerkApiUser | undefined) : undefined;\n return user ? toRecord(user) : null;\n}\n\n/** Fetch a Clerk user by id, for role-change gating. `null` when missing or on a\n * failed lookup. Role defaults to provisional when unset. */\nexport async function clerkGetUser(secretKey: string, id: string, fetchImpl: typeof fetch = fetch): Promise<ClerkUserRecord | null> {\n const data = await clerkGet(`/v1/users/${encodeURIComponent(id)}`, secretKey, fetchImpl).catch(() => null);\n return data ? toRecord(data as ClerkApiUser) : null;\n}\n\n/** List ALL Clerk users with their roles, auto-paginating. A membership community\n * outgrows one page, and a fixed `limit=100` would silently drop members from the\n * admin roster with no error — so this pages (offset in steps of {@link PAGE})\n * until a short page. A page fetch that fails THROWS rather than returning a\n * partial list, so the caller never mistakes a truncated roster for the whole. */\nexport async function clerkListUsers(secretKey: string, fetchImpl: typeof fetch = fetch): Promise<ClerkUserRecord[]> {\n const out: ClerkUserRecord[] = [];\n for (let offset = 0; ; offset += PAGE) {\n const data = await clerkGet(`/v1/users?limit=${PAGE}&offset=${offset}`, secretKey, fetchImpl);\n const page = Array.isArray(data) ? (data as ClerkApiUser[]) : [];\n for (const u of page) {\n const record = toRecord(u);\n if (record) out.push(record);\n }\n if (page.length < PAGE) break;\n }\n return out;\n}\n\n/** Write a user's role: a MERGE-PATCH of only `{ role }` on `public_metadata`, so\n * it leaves a separately-written `profile` untouched. Returns whether it stuck. */\nexport async function clerkSetRole(secretKey: string, id: string, role: string, fetchImpl: typeof fetch = fetch): Promise<boolean> {\n const res = await fetchImpl(`${CLERK_API}/v1/users/${encodeURIComponent(id)}/metadata`, {\n method: \"PATCH\",\n headers: { authorization: `Bearer ${secretKey}`, \"content-type\": \"application/json\" },\n body: JSON.stringify({ public_metadata: { role } }),\n });\n return res.ok;\n}\n","// The OPERATIONAL slice of the one-way person projection: applications + $users\n// -> crm_record, mirroring pipeline stage, a billing snapshot, and the Clerk\n// identity link. `network.ts` projects identity/contact on submit; this adds the\n// operational state the admin surface and the hub read from, so the pipeline\n// stays authoritative in `applications.status` while the CRM carries one\n// relationship surface over the person. Fired AFTER the authoritative write and\n// wrapped in `.catch` at every call site: a CRM hiccup never 5xxs a lifecycle op.\n//\n// Idempotent by construction — every sync resolves the person by lowercased\n// primary email first, so re-running (including the backfill route) updates in\n// place. Generalized from the reference site: the field set is the site's\n// configured `crmFields`, not a hardcoded list.\nimport { createRecord, updateRecord, setStage, linkIdentity } from \"@odla-ai/crm\";\nimport { sharedPersonInput } from \"./network\";\nimport type { ProjectionDeps } from \"./network\";\nimport type { Chapter } from \"./types\";\n\nconst str = (v: unknown): string => (typeof v === \"string\" ? v : v == null ? \"\" : String(v));\n\n/** The crm `person` input for one application row: the built-in identity/contact\n * fields plus each configured `crmFields` value present on the row. */\nexport function personInputFromApp(chapter: Chapter, app: Record<string, unknown>): Record<string, unknown> {\n const input = sharedPersonInput({\n email: str(app.email),\n firstName: str(app.firstName) || undefined,\n lastName: str(app.lastName) || undefined,\n phone: str(app.phone) || undefined,\n linkedin: str(app.linkedin) || undefined,\n hubRecordId: str(app.id),\n });\n for (const f of chapter.application.crmFields) {\n if (app[f] !== undefined) input[f] = app[f];\n }\n if (app.id !== undefined) input.applicationId = str(app.id);\n return input;\n}\n\n// Promoted billing-facet columns derived from the application's Stripe fields +\n// status. Written directly (not through createRecord/updateRecord, which never\n// touch promoted columns), so they never clobber the person input.\nfunction billingColumns(app: Record<string, unknown>): Record<string, unknown> {\n const status = str(app.status);\n const paid = Boolean(app.stripeSubscriptionId) && status !== \"refunded\";\n const billingStatus = status === \"refunded\" ? \"refunded\" : app.canceled === true ? \"canceled\" : paid ? \"active\" : \"none\";\n const cols: Record<string, unknown> = { billingStatus };\n if (app.stripeCustomerId) cols.stripeCustomerId = str(app.stripeCustomerId);\n if (app.stripeSubscriptionId) cols.subscriptionId = str(app.stripeSubscriptionId);\n if (typeof app.renewalAt === \"number\") cols.renewalAt = app.renewalAt;\n return cols;\n}\n\n/** Upsert the person record for one application (or a synthetic `{ email,\n * firstName }` account row) and mirror its stage, billing snapshot, and Clerk\n * identity. `stage` is the `applications.status` to mirror — omit for\n * account-only rows not in the pipeline. Throws on failure (the backfill route\n * counts; the operational call sites wrap in `.catch`). */\nexport async function syncApplicationToCrm(\n deps: ProjectionDeps & { chapter: Chapter },\n opts: { app: Record<string, unknown>; stage?: string },\n): Promise<string | null> {\n const emailKey = str(opts.app.email).toLowerCase();\n if (!emailKey) return null;\n const crmDeps = { crm: deps.crm, db: deps.db as never, now: deps.now, newId: deps.newId };\n const input = personInputFromApp(deps.chapter, opts.app);\n\n const { crm_record } = await deps.db.query({\n crm_record: { $: { where: { type: \"person\", primaryEmail: emailKey }, limit: 1 } },\n });\n const existing = crm_record?.[0] ?? null;\n const stage = opts.stage || undefined;\n\n let recordId: string;\n if (existing && typeof existing.id === \"string\") {\n recordId = existing.id;\n await updateRecord(crmDeps, { id: recordId, input });\n } else {\n const created = await createRecord(crmDeps, { type: \"person\", input, ...(stage ? { stage } : {}) });\n recordId = created.id;\n }\n\n // Stage mirror: move only on an actual change, under a stable mutationId so a\n // replay never piles up duplicate stage_change activities. Best-effort — a\n // stage not on the crm person type must not fail the whole sync.\n if (existing && stage && existing.stage !== stage) {\n await setStage(crmDeps, { id: recordId, to: stage, authorId: \"system\", mutationId: `crm:stage:${recordId}:${stage}` }).catch(() => undefined);\n }\n\n await deps.db.transact([{ t: \"update\", ns: \"crm_record\", id: recordId, attrs: billingColumns(opts.app) }]);\n\n // Identity link: stamps clerkUserId when a $users row matches the email; a\n // no-op until the person has an account. Best-effort — a just-created record\n // can briefly lag the read, and the link retries on the next sync.\n await linkIdentity(crmDeps, { recordId, email: emailKey, mutationId: `crm:link:${recordId}:${emailKey}` }).catch(() => undefined);\n\n return recordId;\n}\n\n/** Backfill / repair: project every application (newest per person) and every\n * account-only `$users` row into the CRM. Idempotent (safe to re-run). Dev\n * volumes fit one 1000-row page. Returns `{ synced, errors }`. */\nexport async function backfillCrm(deps: ProjectionDeps & { chapter: Chapter }): Promise<{ synced: number; errors: Array<{ email: string; error: string }> }> {\n const [appsRes, usersRes] = await Promise.all([\n deps.db.query({ applications: { $: { order: { createdAt: \"desc\" }, limit: 1000 } } }),\n deps.db.query({ $users: { $: { limit: 1000 } } }),\n ]);\n const seen = new Set<string>();\n let synced = 0;\n const errors: Array<{ email: string; error: string }> = [];\n\n const run = async (app: Record<string, unknown>, stage?: string): Promise<void> => {\n const key = str(app.email).toLowerCase();\n if (!key || seen.has(key)) return; // newest-first: one record per person\n seen.add(key);\n try {\n await syncApplicationToCrm(deps, { app, stage });\n synced += 1;\n } catch (err) {\n errors.push({ email: key, error: err instanceof Error ? err.message : String(err) });\n }\n };\n\n for (const a of (appsRes.applications ?? []) as Array<Record<string, unknown>>) await run(a, str(a.status));\n for (const u of (usersRes.$users ?? []) as Array<Record<string, unknown>>) {\n if (u.deleted === true) continue;\n await run({ email: u.email, firstName: str(u.name) });\n }\n return { synced, errors };\n}\n","// Admin roster + identity routes: the union people list, one person's access,\n// role changes, and the CRM backfill. Role changes wire chapter's package-\n// enforced canChangeRole guard (super-admin tier + self-demotion lockout) rather\n// than re-deriving the rules per site. All admin-gated.\nimport { canChangeRole, getVaultSecret } from \"./auth\";\nimport { clerkGetUser, clerkListUsers, clerkSetRole } from \"./clerk-roles\";\nimport { backfillCrm } from \"./crm-sync\";\nimport { applicationSummary } from \"./session\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, WorkerContext } from \"./worker-context\";\nimport type { Route } from \"./worker-routes\";\nimport type { ChapterDb } from \"./types\";\n\n// Gate + shape the verified admin identity. Returns { db, actor } or a Response.\nasync function adminGate(\n req: Request,\n env: ChapterEnv,\n ctx: WorkerContext,\n): Promise<{ db: ChapterDb; actor: { userId: string; email?: string } } | Response> {\n const rawDb = ctx.makeDb(env);\n const u = await ctx.verifyUser(req, env);\n if (!u) return json({ error: \"unauthorized\" }, 401);\n if (!(await ctx.isAdmin(rawDb, u))) return json({ error: \"forbidden\" }, 403);\n return { db: rawDb as unknown as ChapterDb, actor: { userId: u.userId, email: u.email ?? undefined } };\n}\n\nconst crmDeps = (db: ChapterDb, ctx: WorkerContext) => ({\n crm: ctx.chapter.crm,\n db,\n now: () => Date.now(),\n newId: () => crypto.randomUUID(),\n chapter: ctx.chapter,\n});\n\n/** POST /api/admin/crm/sync — backfill/reproject every person into the CRM.\n * Idempotent by email, so it doubles as migration and repair. */\nexport const handleAdminCrmSync: Route = async (req, url, env, ctx) => {\n if (req.method !== \"POST\" || url.pathname !== \"/api/admin/crm/sync\") return null;\n const gate = await adminGate(req, env, ctx);\n if (gate instanceof Response) return gate;\n const result = await backfillCrm(crmDeps(gate.db, ctx));\n return json({ ok: true, ...result });\n};\n\n/** GET /api/admin/people — one row per person, joined by lowercased email: the\n * `$users` mirror (accounts), applications (pipeline), and Clerk roles.\n * Applications first (newest on top), account-only rows after. */\nexport const handleAdminPeople: Route = async (req, url, env, ctx) => {\n if (req.method !== \"GET\" || url.pathname !== \"/api/admin/people\") return null;\n const gate = await adminGate(req, env, ctx);\n if (gate instanceof Response) return gate;\n const { db } = gate;\n\n const sk = await getVaultSecret(db, \"clerk_secret_key\");\n const [appsRes, usersRes, roleList] = await Promise.all([\n db.query({ applications: { $: { order: { createdAt: \"desc\" }, limit: 200 } } }),\n db.query({ $users: { $: { limit: 200 } } }),\n sk ? clerkListUsers(sk).catch(() => []) : Promise.resolve([]),\n ]);\n const roleByUserId = new Map(roleList.map((u) => [u.id, u.role]));\n\n type PersonRow = { email: string; name: string; userId: string | null; role: string | null; application: ReturnType<typeof applicationSummary> | null };\n const people = new Map<string, PersonRow>();\n\n for (const u of (usersRes.$users ?? []) as Array<Record<string, unknown>>) {\n if (u.deleted === true) continue; // tombstoned Clerk users are not accounts\n const email = typeof u.email === \"string\" ? u.email : \"\";\n if (!email) continue;\n people.set(email.toLowerCase(), {\n email,\n name: typeof u.name === \"string\" ? u.name : \"\",\n userId: typeof u.id === \"string\" ? u.id : null,\n role: roleByUserId.get(String(u.id)) ?? \"provisional\",\n application: null,\n });\n }\n for (const a of (appsRes.applications ?? []) as Array<Record<string, unknown>>) {\n const key = String(a.email ?? \"\").toLowerCase();\n if (!key) continue;\n const name = `${a.firstName ?? \"\"} ${a.lastName ?? \"\"}`.trim();\n const row = people.get(key);\n if (row) {\n if (!row.application) row.application = applicationSummary(a as unknown as Parameters<typeof applicationSummary>[0]); // newest-first: keep the latest\n if (!row.name) row.name = name;\n } else {\n people.set(key, { email: String(a.email), name, userId: null, role: null, application: applicationSummary(a as unknown as Parameters<typeof applicationSummary>[0]) });\n }\n }\n const rows = [...people.values()].sort(\n (x, y) => ((y.application?.createdAt as number) ?? -1) - ((x.application?.createdAt as number) ?? -1),\n );\n return json({ people: rows });\n};\n\n/** GET /api/admin/people/access?userId= — a person's Clerk role + super-admin\n * flag, for the record panel's Access card. */\nexport const handleAdminPeopleAccess: Route = async (req, url, env, ctx) => {\n if (req.method !== \"GET\" || url.pathname !== \"/api/admin/people/access\") return null;\n const gate = await adminGate(req, env, ctx);\n if (gate instanceof Response) return gate;\n const { db } = gate;\n const targetId = url.searchParams.get(\"userId\") ?? \"\";\n if (!targetId.startsWith(\"user_\")) return json({ error: \"invalid userId\" }, 400);\n const sk = await getVaultSecret(db, \"clerk_secret_key\");\n if (!sk) return json({ error: \"role management unavailable: clerk_secret_key missing from vault\" }, 503);\n const info = await clerkGetUser(sk, targetId);\n if (!info) return json({ error: \"user lookup unavailable\" }, 502);\n return json({ userId: targetId, role: info.role, email: info.email ?? null, superAdmin: await ctx.isSuperAdminEmail(db as never, info.email) });\n};\n\n/** POST /api/admin/people/role — change a person's Clerk role. The escalation\n * rules (super-admin tier, self-demotion lockout) are enforced by chapter's\n * canChangeRole, not re-derived here. */\nexport const handleAdminPeopleRole: Route = async (req, url, env, ctx) => {\n if (req.method !== \"POST\" || url.pathname !== \"/api/admin/people/role\") return null;\n const gate = await adminGate(req, env, ctx);\n if (gate instanceof Response) return gate;\n const { db, actor } = gate;\n\n let body: Record<string, unknown>;\n try {\n body = (await req.json()) as Record<string, unknown>;\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n const targetId = typeof body.userId === \"string\" ? body.userId : \"\";\n const newRole = typeof body.role === \"string\" ? body.role : \"\";\n if (!targetId.startsWith(\"user_\")) return json({ error: \"invalid userId\" }, 400);\n\n const sk = await getVaultSecret(db, \"clerk_secret_key\");\n if (!sk) return json({ error: \"role management unavailable: clerk_secret_key missing from vault\" }, 503);\n const target = await clerkGetUser(sk, targetId);\n\n const guard = canChangeRole({\n actorId: actor.userId,\n actorIsSuper: await ctx.isSuperAdminEmail(db as never, actor.email),\n targetId,\n targetCurrentRole: target?.role ?? \"provisional\",\n targetIsSuper: await ctx.isSuperAdminEmail(db as never, target?.email),\n newRole,\n auth: ctx.chapter.auth,\n });\n if (!guard.ok) return json({ error: guard.error }, guard.status);\n\n if (!(await clerkSetRole(sk, targetId, newRole))) return json({ error: \"role update failed upstream\" }, 502);\n return json({ ok: true });\n};\n","// Pure aggregation helpers for the admin dashboard: a weekly time-series bucketer\n// and the annualized-run-rate math for a Stripe subscription. Kept out of the\n// route so both dashboard and billing share one definition and it is unit-tested\n// without a network call.\n\n/** Bucket `{ t, v }` points into the last `weeks` weekly buckets ending at `now`\n * (epoch ms), summing `v` per bucket. Returns oldest→newest `{ weekStart, value\n * }`, so a caller renders a sparkline directly. Points outside the window are\n * ignored. */\nexport function bucketSeries(\n points: Array<{ t: number; v: number }>,\n now: number,\n weeks = 12,\n): Array<{ weekStart: number; value: number }> {\n const WEEK = 7 * 86_400_000;\n const end = now;\n const start = end - weeks * WEEK;\n const buckets = Array.from({ length: weeks }, (_, i) => ({ weekStart: start + i * WEEK, value: 0 }));\n for (const p of points) {\n if (!Number.isFinite(p.t) || p.t < start || p.t > end) continue;\n const idx = Math.min(weeks - 1, Math.floor((p.t - start) / WEEK));\n const bucket = buckets[idx];\n if (bucket) bucket.value += Number.isFinite(p.v) ? p.v : 0;\n }\n return buckets;\n}\n\n/** Annualized cents for a Stripe subscription: sum each item's\n * `unit_amount * quantity`, ×12 for monthly intervals. A yearly interval is\n * taken as-is. Returns 0 for a shape with no priced items. */\nexport function subAnnualCents(sub: Record<string, unknown>): number {\n const items = ((sub.items as { data?: Array<Record<string, unknown>> } | undefined)?.data ?? []);\n let cents = 0;\n for (const it of items) {\n const price = (it.price ?? {}) as { unit_amount?: number; recurring?: { interval?: string } };\n const per = (price.unit_amount ?? 0) * ((it.quantity as number) ?? 1);\n cents += price.recurring?.interval === \"month\" ? per * 12 : per;\n }\n return cents;\n}\n","// Admin aggregation routes: the dashboard overview and the billing table. Both\n// join db rows with live Stripe reads (Stripe is the source of truth for money),\n// keyed by the vault stripe_secret_key, and degrade to `billingReady: false`\n// when no key is vaulted — so a hub that runs no membership billing simply drops\n// the section. Admin-gated.\nimport { getVaultSecret } from \"./auth\";\nimport { stripeCall } from \"./payments-stripe\";\nimport { resolveScheduling } from \"./scheduling\";\nimport { bucketSeries, subAnnualCents } from \"./series\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, WorkerContext } from \"./worker-context\";\nimport type { Route } from \"./worker-routes\";\nimport type { ChapterDb, ChapterScheduling } from \"./types\";\n\nasync function gate(req: Request, env: ChapterEnv, ctx: WorkerContext): Promise<ChapterDb | Response> {\n const rawDb = ctx.makeDb(env);\n const u = await ctx.verifyUser(req, env);\n if (!u) return json({ error: \"unauthorized\" }, 401);\n if (!(await ctx.isAdmin(rawDb, u))) return json({ error: \"forbidden\" }, 403);\n return rawDb as unknown as ChapterDb;\n}\n\nconst rows = <T = Record<string, unknown>>(v: unknown): T[] => (Array.isArray(v) ? (v as T[]) : []);\n\n/** GET /api/admin/dashboard — application flow counts, pipeline stage counts +\n * weekly delta, the upcoming call agenda, and (when billing is wired) live\n * revenue series. One call powers the overview. */\nexport const handleAdminDashboard: Route = async (req, url, env, ctx) => {\n if (req.method !== \"GET\" || url.pathname !== \"/api/admin/dashboard\") return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n\n const now = Date.now();\n const d7 = now - 7 * 86_400_000;\n const d30 = now - 30 * 86_400_000;\n const [appsRes, meetingsRes, recsRes, groupRes] = await Promise.all([\n db.query({ applications: { $: { order: { createdAt: \"desc\" }, limit: 1000 } } }),\n db.query({ meetings: { $: { where: { status: \"scheduled\" }, order: { startAt: \"asc\" }, limit: 500 } } }),\n db.query({ crm_record: { $: { where: { type: \"person\" }, limit: 1000 } } }),\n db.query({ groups: { $: { where: { id: ctx.chapter.id }, limit: 1 } } }),\n ]);\n const apps = rows(appsRes.applications);\n const applications = {\n total: apps.length,\n last7: apps.filter((a) => (a.createdAt as number) >= d7).length,\n last30: apps.filter((a) => (a.createdAt as number) >= d30).length,\n };\n const pipeline: Record<string, number> = {};\n const pipelineDelta: Record<string, number> = {};\n for (const s of ctx.chapter.pipeline.stages) {\n pipeline[s] = 0;\n pipelineDelta[s] = 0;\n }\n for (const r of rows(recsRes.crm_record)) {\n const s = r.stage as string;\n if (s in pipeline) {\n pipeline[s] = (pipeline[s] ?? 0) + 1;\n const sc = typeof r.stageChangedAt === \"number\" ? r.stageChangedAt : Date.parse(String(r.stageChangedAt));\n if (Number.isFinite(sc) && sc >= d7) pipelineDelta[s] = (pipelineDelta[s] ?? 0) + 1;\n }\n }\n\n const meetings = rows(meetingsRes.meetings);\n const appById = new Map(apps.map((a) => [a.id, a]));\n const upcoming = meetings.filter((m) => (m.startAt as number) >= now - 3_600_000);\n const calls = { upcoming: upcoming.length, needsAttention: meetings.filter((m) => m.drift && m.drift !== \"none\").length };\n const agenda = upcoming.slice(0, 8).map((m) => {\n const a = appById.get(m.applicationId);\n return {\n id: m.id,\n startAt: m.startAt,\n meetUrl: m.meetUrl ?? null,\n htmlLink: m.htmlLink ?? null,\n drift: m.drift ?? \"none\",\n name: a ? `${a.firstName} ${a.lastName}` : \"(unknown)\",\n email: (a?.email as string) ?? null,\n };\n });\n const group = groupRes.groups?.[0];\n const timezone = resolveScheduling(group?.schedulingJson as ChapterScheduling | undefined).timezone;\n\n let revenue: Record<string, unknown> = { billingReady: false };\n let revenueSeries: unknown = null;\n let membersSeries: unknown = null;\n const sk = await getVaultSecret(db, \"stripe_secret_key\");\n if (sk) {\n const subsRes = await stripeCall(sk, \"GET\", \"/v1/subscriptions\", { limit: 100, status: \"all\" });\n if (subsRes.ok) {\n const subs = rows(subsRes.body.data);\n const subMs = (s: Record<string, unknown>) => ((s.created as number) ?? 0) * 1000;\n membersSeries = bucketSeries(subs.map((s) => ({ t: subMs(s), v: 1 })), now);\n revenueSeries = bucketSeries(subs.map((s) => ({ t: subMs(s), v: subAnnualCents(s) })), now);\n const active = subs.filter((s) => s.status === \"active\");\n revenue = {\n billingReady: true,\n testMode: String(group?.stripePublishableKey ?? \"\").startsWith(\"pk_test\"),\n activeCount: active.length,\n annualRunRateCents: active.reduce((sum, s) => sum + subAnnualCents(s), 0),\n newPaid7: subs.filter((s) => subMs(s) >= d7).length,\n newPaid30: subs.filter((s) => subMs(s) >= d30).length,\n };\n }\n }\n const applicationsSeries = bucketSeries(apps.map((a) => ({ t: (a.createdAt as number) || 0, v: 1 })), now);\n return json({ applications, applicationsSeries, pipeline, pipelineDelta, calls, agenda, timezone, revenue, revenueSeries, membersSeries });\n};\n\ninterface SubItem {\n price?: { unit_amount?: number; recurring?: { interval?: string } };\n quantity?: number;\n current_period_end?: number;\n}\n\n/** GET /api/admin/billing — applications joined with live Stripe subscription\n * state. `truncated` flags a >100-subscription page instead of silently losing\n * rows. `billingReady: false` when no stripe_secret_key is vaulted. */\nexport const handleAdminBilling: Route = async (req, url, env, ctx) => {\n if (req.method !== \"GET\" || url.pathname !== \"/api/admin/billing\") return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n\n const sk = await getVaultSecret(db, \"stripe_secret_key\");\n if (!sk) return json({ billingReady: false, rows: [], summary: null });\n const [appsRes, subsRes, groupRes] = await Promise.all([\n db.query({ applications: { $: { order: { createdAt: \"desc\" }, limit: 200 } } }),\n stripeCall(sk, \"GET\", \"/v1/subscriptions\", { limit: 100, status: \"all\" }),\n db.query({ groups: { $: { where: { id: ctx.chapter.id }, limit: 1 } } }),\n ]);\n const testMode = String(groupRes.groups?.[0]?.stripePublishableKey ?? \"\").startsWith(\"pk_test\");\n if (!subsRes.ok) return json({ error: \"billing lookup failed upstream\" }, 502);\n const subById = new Map(rows(subsRes.body.data).map((s) => [s.id as string, s]));\n\n const billingRows = [];\n for (const a of rows(appsRes.applications)) {\n if (!a.stripeCustomerId && !a.stripeSubscriptionId) continue;\n const sub = a.stripeSubscriptionId ? subById.get(a.stripeSubscriptionId as string) : undefined;\n const items = (sub?.items as { data?: SubItem[] } | undefined)?.data ?? [];\n let amountCents = 0;\n let interval = \"year\";\n for (const it of items) {\n amountCents += (it.price?.unit_amount ?? 0) * (it.quantity ?? 1);\n interval = it.price?.recurring?.interval ?? interval;\n }\n const periodEnd = (sub?.current_period_end as number | undefined) ?? items[0]?.current_period_end;\n billingRows.push({\n id: a.id as string,\n name: `${a.firstName} ${a.lastName}`,\n email: a.email as string,\n applicationStatus: a.status as string,\n subscriptionStatus: (sub?.status as string) ?? null,\n cancelAtPeriodEnd: sub?.cancel_at_period_end === true,\n amountCents,\n interval,\n renewalAt: periodEnd ? periodEnd * 1000 : ((a.renewalAt as number) ?? null),\n });\n }\n const renewing = billingRows.filter((r) => r.subscriptionStatus === \"active\" && !r.cancelAtPeriodEnd);\n const soonCutoff = Date.now() + 60 * 86_400_000;\n const summary = {\n activeCount: billingRows.filter((r) => r.subscriptionStatus === \"active\").length,\n annualizedCents: renewing.reduce((s, r) => s + r.amountCents * (r.interval === \"month\" ? 12 : 1), 0),\n renewingSoonCount: renewing.filter((r) => r.renewalAt && r.renewalAt < soonCutoff).length,\n pastDueCount: billingRows.filter((r) => r.subscriptionStatus === \"past_due\").length,\n canceledCount: billingRows.filter((r) => r.subscriptionStatus === \"canceled\" || r.cancelAtPeriodEnd).length,\n refundedCount: billingRows.filter((r) => r.applicationStatus === \"refunded\").length,\n };\n return json({\n billingReady: true,\n testMode,\n truncated: subsRes.body.has_more === true,\n rows: billingRows,\n summary,\n });\n};\n","// Admin lifecycle routes: meeting reschedule/cancel and application\n// approve/refund/manual-patch. These are the operational actions; each wires a\n// chapter primitive (canApprove, meetingRescheduleUpdate, refundedPatch) and the\n// operations policy seams (onApprove.promoteTo/send, refund.allowedFrom/\n// cancelSubscription), and mirrors the change into the CRM. Admin-gated.\nimport { computeBookableSlots, initCalendar } from \"@odla-ai/calendar\";\nimport { getVaultSecret } from \"./auth\";\nimport { clerkGetUserByEmail, clerkSetRole } from \"./clerk-roles\";\nimport { syncApplicationToCrm } from \"./crm-sync\";\nimport { sendTemplated, emailGroupFrom } from \"./notify\";\nimport { stripeCall } from \"./payments-stripe\";\nimport { canApprove } from \"./pipeline\";\nimport { canTransition } from \"./pipeline\";\nimport { resolveScheduling, endForSlot, isSlotAvailable, meetingRescheduleUpdate, slotWindow } from \"./scheduling\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, WorkerContext } from \"./worker-context\";\nimport type { Route } from \"./worker-routes\";\nimport type { ChapterDb, ChapterScheduling } from \"./types\";\n\nasync function gate(req: Request, env: ChapterEnv, ctx: WorkerContext): Promise<ChapterDb | Response> {\n const rawDb = ctx.makeDb(env);\n const u = await ctx.verifyUser(req, env);\n if (!u) return json({ error: \"unauthorized\" }, 401);\n if (!(await ctx.isAdmin(rawDb, u))) return json({ error: \"forbidden\" }, 403);\n return rawDb as unknown as ChapterDb;\n}\n\nconst calFor = (env: ChapterEnv) =>\n initCalendar({ appId: env.ODLA_APP_ID, env: env.ODLA_ENV, adminToken: env.ODLA_API_KEY, endpoint: env.ODLA_PLATFORM });\nconst crmDeps = (db: ChapterDb, ctx: WorkerContext) => ({ crm: ctx.chapter.crm, db, now: () => Date.now(), newId: () => crypto.randomUUID(), chapter: ctx.chapter });\nconst readJson = async (req: Request): Promise<Record<string, unknown> | null> => {\n try {\n return (await req.json()) as Record<string, unknown>;\n } catch {\n return null;\n }\n};\nasync function loadApp(db: ChapterDb, id: string): Promise<Record<string, unknown> | null> {\n const { applications } = await db.query({ applications: { $: { where: { id }, limit: 1 } } });\n return applications?.[0] ?? null;\n}\nasync function loadGroup(db: ChapterDb, id: string): Promise<Record<string, unknown> | null> {\n const { groups } = await db.query({ groups: { $: { where: { id }, limit: 1 } } });\n return groups?.[0] ?? null;\n}\n\n/** POST /api/admin/meetings/:id/reschedule — move an intro call to an open slot;\n * the Google event moves (Meet link + invite thread survive). */\nexport const handleAdminMeetingReschedule: Route = async (req, url, env, ctx) => {\n const m = url.pathname.match(/^\\/api\\/admin\\/meetings\\/([0-9a-f-]+)\\/reschedule$/);\n if (req.method !== \"POST\" || !m) return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n const body = await readJson(req);\n const startAt = Number(body?.startAt);\n if (!Number.isFinite(startAt)) return json({ error: \"startAt required\" }, 400);\n\n const { meetings } = await db.query({ meetings: { $: { where: { id: m[1] }, limit: 1 } } });\n const meeting = meetings?.[0];\n if (!meeting) return json({ error: \"not found\" }, 404);\n if (meeting.status !== \"scheduled\") return json({ error: \"meeting is cancelled\" }, 409);\n if (!meeting.googleEventId) return json({ error: \"no calendar event on file\" }, 409);\n\n const cfg = resolveScheduling((await loadGroup(db, String(meeting.groupId ?? ctx.chapter.id)))?.schedulingJson as ChapterScheduling | undefined);\n const endAt = endForSlot(startAt, cfg.slotMinutes);\n const cal = calFor(env);\n try {\n const { from, to } = slotWindow(Date.now(), cfg.windowDays);\n const fb = await cal.availability.freeBusy({ timeMin: from, timeMax: to });\n const slots = computeBookableSlots(fb.busy, {\n from: fb.timeMin,\n to: fb.timeMax,\n timezone: cfg.timezone,\n slotMinutes: cfg.slotMinutes,\n businessHours: { days: [...cfg.days], startHour: cfg.startHour, endHour: cfg.endHour },\n minNoticeMs: cfg.minNoticeHours * 3_600_000,\n });\n if (!isSlotAvailable(slots, startAt)) return json({ error: \"slot no longer available\", code: \"calendar_slot_unavailable\" }, 409);\n await cal.actions.reschedule(String(meeting.googleEventId), { startAt, endAt });\n } catch {\n return json({ error: \"reschedule failed upstream\" }, 502);\n }\n await db.transact([{ t: \"update\", ns: \"meetings\", id: String(meeting.id), attrs: meetingRescheduleUpdate(startAt, endAt) }]);\n await db.transact([{ t: \"update\", ns: \"applications\", id: String(meeting.applicationId), attrs: { meetingAt: startAt } }]);\n return json({ ok: true, startAt, endAt });\n};\n\n/** POST /api/admin/meetings/:id/cancel — cancel an intro call; the Google event\n * is removed (Google notifies the attendee). */\nexport const handleAdminMeetingCancel: Route = async (req, url, env, ctx) => {\n const m = url.pathname.match(/^\\/api\\/admin\\/meetings\\/([0-9a-f-]+)\\/cancel$/);\n if (req.method !== \"POST\" || !m) return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n\n const { meetings } = await db.query({ meetings: { $: { where: { id: m[1] }, limit: 1 } } });\n const meeting = meetings?.[0];\n if (!meeting) return json({ error: \"not found\" }, 404);\n if (meeting.status !== \"scheduled\") return json({ error: \"already cancelled\" }, 409);\n if (meeting.googleEventId) {\n try {\n await calFor(env).actions.cancel(String(meeting.googleEventId));\n } catch {\n return json({ error: \"cancel failed upstream\" }, 502);\n }\n }\n await db.transact([{ t: \"update\", ns: \"meetings\", id: String(meeting.id), attrs: { status: \"cancelled\", drift: \"none\" } }]);\n await db.transact([{ t: \"update\", ns: \"applications\", id: String(meeting.applicationId), attrs: { meetingAt: 0, meetingLink: \"\" } }]);\n return json({ ok: true });\n};\n\n/** POST /api/admin/applications/:id/approve — the deliberate approval: advance to\n * the approvable target, promote the Clerk role (operations.onApprove.promoteTo),\n * and send the approve template (operations.onApprove.send). Mirrors to CRM. */\nexport const handleAdminApprove: Route = async (req, url, env, ctx) => {\n const m = url.pathname.match(/^\\/api\\/admin\\/applications\\/([0-9a-f-]+)\\/approve$/);\n if (req.method !== \"POST\" || !m) return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n const id = m[1] as string;\n\n const app = await loadApp(db, id);\n if (!app) return json({ error: \"not found\" }, 404);\n if (!canApprove(String(app.status), ctx.chapter.pipeline)) return json({ error: `cannot approve from status \"${String(app.status)}\"` }, 409);\n const target = \"approved\";\n\n await db.transact([{ t: \"update\", ns: \"applications\", id, attrs: { status: target } }]);\n await syncApplicationToCrm(crmDeps(db, ctx), { app: { ...app, status: target }, stage: target }).catch(() => undefined);\n\n const { promoteTo, send } = ctx.chapter.operations.onApprove;\n let rolePromoted = false;\n const sk = await getVaultSecret(db, \"clerk_secret_key\");\n if (promoteTo !== false && sk) {\n let userId = (app.clerkUserId as string) || null;\n if (!userId) {\n const found = await clerkGetUserByEmail(sk, String(app.email));\n userId = found?.id ?? null;\n if (userId) await db.transact([{ t: \"update\", ns: \"applications\", id, attrs: { clerkUserId: userId } }]);\n }\n if (userId) rolePromoted = await clerkSetRole(sk, userId, promoteTo);\n }\n\n let emailLogged = false;\n const group = await loadGroup(db, String(app.groupId ?? ctx.chapter.id));\n if (send !== false && group) {\n const res = await sendTemplated(\n { db, envName: env.ODLA_ENV, sender: env.SEND_EMAIL, from: env.EMAIL_FROM, now: () => Date.now(), newId: () => crypto.randomUUID() },\n { group: emailGroupFrom(group), template: send, to: String(app.email), vars: { firstName: String(app.firstName ?? \"\"), membersUrl: `${url.origin}/members/` }, applicationId: id, dedupeKey: `approve:${id}` },\n );\n emailLogged = res.sent;\n }\n return json({ ok: true, status: target, rolePromoted, emailLogged });\n};\n\n/** POST /api/admin/applications/:id/refund — refund the first paid charge and\n * (per operations.refund) cancel the subscription. The status flip to \"refunded\"\n * comes from the charge.refunded webhook, so Stripe stays the source of truth. */\nexport const handleAdminRefund: Route = async (req, url, env, ctx) => {\n const m = url.pathname.match(/^\\/api\\/admin\\/applications\\/([0-9a-f-]+)\\/refund$/);\n if (req.method !== \"POST\" || !m) return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n\n const app = await loadApp(db, m[1] as string);\n if (!app) return json({ error: \"not found\" }, 404);\n if (app.status === \"refunded\") return json({ error: \"already refunded\" }, 409);\n const allowedFrom = ctx.chapter.operations.refund.allowedFrom;\n if (allowedFrom && !allowedFrom.includes(String(app.status))) {\n return json({ error: `cannot refund from status \"${String(app.status)}\"` }, 409);\n }\n const subscriptionId = app.stripeSubscriptionId as string | undefined;\n const customerId = app.stripeCustomerId as string | undefined;\n if (!customerId) return json({ error: \"no customer on file\" }, 409);\n const sk = await getVaultSecret(db, \"stripe_secret_key\");\n if (!sk) return json({ error: \"payments not configured\" }, 503);\n\n const charges = await stripeCall(sk, \"GET\", \"/v1/charges\", { customer: customerId, limit: 100 });\n if (!charges.ok) return json({ error: \"refund failed upstream\" }, 502);\n const succeeded = ((charges.body.data as Array<Record<string, unknown>>) ?? []).filter((c) => c.status === \"succeeded\" && c.refunded !== true);\n const firstCharge = succeeded[succeeded.length - 1];\n if (!firstCharge) return json({ error: \"no paid charge to refund\" }, 409);\n\n const refund = await stripeCall(sk, \"POST\", \"/v1/refunds\", { charge: String(firstCharge.id) });\n if (!refund.ok) return json({ error: \"refund failed upstream\" }, 502);\n let subscriptionCanceled = false;\n if (ctx.chapter.operations.refund.cancelSubscription && subscriptionId) {\n const cancel = await stripeCall(sk, \"DELETE\", `/v1/subscriptions/${subscriptionId}`);\n subscriptionCanceled = cancel.ok;\n }\n return json({ ok: true, refundedCents: (refund.body.amount as number) ?? null, subscriptionCanceled });\n};\n\n/** PATCH /api/admin/applications/:id — manual correction escape hatch. Sets\n * `status` (gated by canTransition) and/or `meetingAt`. Mirrors a status move to\n * the CRM. */\nexport const handleAdminApplicationPatch: Route = async (req, url, env, ctx) => {\n const m = url.pathname.match(/^\\/api\\/admin\\/applications\\/([0-9a-f-]+)$/);\n if (req.method !== \"PATCH\" || !m) return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n const id = m[1] as string;\n const body = await readJson(req);\n if (!body) return json({ error: \"invalid JSON body\" }, 400);\n\n const app = await loadApp(db, id);\n if (!app) return json({ error: \"not found\" }, 404);\n\n const attrs: Record<string, unknown> = {};\n if (body.status !== undefined) {\n const to = String(body.status);\n if (!ctx.chapter.pipeline.stages.includes(to)) return json({ error: `status must be one of: ${ctx.chapter.pipeline.stages.join(\", \")}` }, 400);\n if (!canTransition(String(app.status), to, ctx.chapter.pipeline)) return json({ error: `cannot move from \"${String(app.status)}\" to \"${to}\"` }, 409);\n attrs.status = to;\n }\n if (body.meetingAt !== undefined) {\n if (typeof body.meetingAt !== \"number\" || !Number.isFinite(body.meetingAt)) return json({ error: \"meetingAt must be epoch milliseconds\" }, 400);\n attrs.meetingAt = body.meetingAt;\n }\n if (Object.keys(attrs).length === 0) return json({ error: \"nothing to update\" }, 400);\n\n await db.transact([{ t: \"update\", ns: \"applications\", id, attrs }]);\n if (attrs.status !== undefined) {\n await syncApplicationToCrm(crmDeps(db, ctx), { app: { ...app, ...attrs }, stage: String(attrs.status) }).catch(() => undefined);\n }\n return json({ ok: true });\n};\n","// Admin email + comms routes: read/write the group's owner-editable email config,\n// the send audit log, an owner-triggered test send, and one person's comms\n// timeline (sent lifecycle mail + the Google calendar invitations reconstructed\n// from meeting rows). Admin-gated.\nimport { renderTemplateBody } from \"./email\";\nimport { sendTemplated, emailGroupFrom, EMAIL_TEMPLATE_NAMES } from \"./notify\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, WorkerContext } from \"./worker-context\";\nimport type { Route } from \"./worker-routes\";\nimport type { ChapterDb } from \"./types\";\n\nasync function gate(req: Request, env: ChapterEnv, ctx: WorkerContext): Promise<ChapterDb | Response> {\n const rawDb = ctx.makeDb(env);\n const u = await ctx.verifyUser(req, env);\n if (!u) return json({ error: \"unauthorized\" }, 401);\n if (!(await ctx.isAdmin(rawDb, u))) return json({ error: \"forbidden\" }, 403);\n return rawDb as unknown as ChapterDb;\n}\nasync function loadGroup(db: ChapterDb, id: string): Promise<Record<string, unknown> | null> {\n const { groups } = await db.query({ groups: { $: { where: { id }, limit: 1 } } });\n return groups?.[0] ?? null;\n}\nconst str = (v: unknown, d = \"\"): string => (typeof v === \"string\" ? v : d);\nconst notifyDeps = (db: ChapterDb, env: ChapterEnv) => ({\n db,\n envName: env.ODLA_ENV,\n sender: env.SEND_EMAIL,\n from: env.EMAIL_FROM,\n now: () => Date.now(),\n newId: () => crypto.randomUUID(),\n});\n\n/** GET/PUT /api/admin/group/email — read the owner-editable email config\n * (templates + addresses + read-only delivery wiring), or replace it. */\nexport const handleAdminGroupEmail: Route = async (req, url, env, ctx) => {\n if (url.pathname !== \"/api/admin/group/email\" || (req.method !== \"GET\" && req.method !== \"PUT\")) return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n const group = await loadGroup(db, ctx.chapter.id);\n if (!group) return json({ error: \"not found\" }, 404);\n\n if (req.method === \"GET\") {\n const stored = (group.emailTemplates ?? {}) as Record<string, { subject?: string; text?: string; enabled?: boolean }>;\n const emailTemplates: Record<string, { subject: string; text: string; enabled: boolean }> = {};\n for (const key of EMAIL_TEMPLATE_NAMES) {\n const t = stored[key];\n if (t) emailTemplates[key] = { subject: str(t.subject), text: str(t.text), enabled: t.enabled !== false };\n }\n return json({\n groupId: group.id,\n name: group.name,\n replyTo: str(group.replyTo),\n notificationEmail: str(group.notificationEmail),\n debugEmail: str(group.debugEmail),\n emailTemplates,\n commitmentText: str(group.commitmentText),\n normsText: str(group.normsText),\n refundPolicyText: str(group.refundPolicyText),\n // Read-only delivery wiring — surfaced so \"why did this not send?\" is\n // answerable without logs.\n envName: env.ODLA_ENV,\n transport: env.SEND_EMAIL && env.EMAIL_FROM ? \"cloudflare\" : \"log-only\",\n fromEmail: env.EMAIL_FROM ?? null,\n });\n }\n\n let body: Record<string, unknown>;\n try {\n body = (await req.json()) as Record<string, unknown>;\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n const templates = body.emailTemplates;\n if (!templates || typeof templates !== \"object\") return json({ error: \"emailTemplates object required\" }, 400);\n const clean: Record<string, { subject: string; text: string; enabled: boolean }> = {};\n for (const key of EMAIL_TEMPLATE_NAMES) {\n const t = (templates as Record<string, { subject?: unknown; text?: unknown; enabled?: unknown }>)[key];\n const subject = typeof t?.subject === \"string\" ? t.subject.trim() : \"\";\n const text = typeof t?.text === \"string\" ? t.text : \"\";\n if (!subject || !text.trim()) return json({ error: `template \"${key}\" needs a subject and a body` }, 400);\n if (/[\\r\\n]/.test(subject) || subject.length > 200) return json({ error: `template \"${key}\" subject must be a single line under 200 characters` }, 400);\n if (text.length > 10_000) return json({ error: `template \"${key}\" body is too long` }, 400);\n clean[key] = { subject, text, enabled: t?.enabled !== false };\n }\n const emailish = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n const notificationEmail = str(body.notificationEmail).trim();\n const replyTo = str(body.replyTo).trim();\n const debugEmail = str(body.debugEmail).trim();\n if (!emailish.test(notificationEmail)) return json({ error: \"notification address must be a valid email\" }, 400);\n if (!emailish.test(replyTo)) return json({ error: \"reply-to address must be a valid email\" }, 400);\n if (debugEmail && !emailish.test(debugEmail)) return json({ error: \"debug address must be a valid email\" }, 400);\n const commitmentText = str(body.commitmentText);\n const normsText = str(body.normsText);\n if (commitmentText.length > 5000 || normsText.length > 5000) return json({ error: \"commitment/norms text is too long\" }, 400);\n\n await db.transact([{ t: \"update\", ns: \"groups\", id: ctx.chapter.id, attrs: { emailTemplates: clean, commitmentText, normsText, notificationEmail, replyTo, debugEmail } }]);\n return json({ ok: true });\n};\n\n/** GET /api/admin/email/log — the send audit: every attempted send. */\nexport const handleAdminEmailLog: Route = async (req, url, env, ctx) => {\n if (req.method !== \"GET\" || url.pathname !== \"/api/admin/email/log\") return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const { emailLog } = await got.query({ emailLog: { $: { order: { sentAt: \"desc\" }, limit: 50 } } });\n const sends = ((emailLog ?? []) as Array<Record<string, unknown>>).map((r) => ({\n id: r.id,\n template: r.template,\n to: r.to,\n subject: r.subject,\n transport: r.transport,\n redirected: r.redirected === true,\n error: (r.error as string) ?? null,\n sentAt: r.sentAt,\n }));\n return json({ sends });\n};\n\n/** POST /api/admin/email/test — send one template with sample data to the\n * notification address, ignoring the `enabled` flag (the admin asked). */\nexport const handleAdminEmailTest: Route = async (req, url, env, ctx) => {\n if (req.method !== \"POST\" || url.pathname !== \"/api/admin/email/test\") return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n let body: Record<string, unknown>;\n try {\n body = (await req.json()) as Record<string, unknown>;\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n const template = str(body.template);\n if (!(EMAIL_TEMPLATE_NAMES as readonly string[]).includes(template)) {\n return json({ error: `template must be one of: ${EMAIL_TEMPLATE_NAMES.join(\", \")}` }, 400);\n }\n const group = await loadGroup(db, ctx.chapter.id);\n if (!group) return json({ error: \"not found\" }, 404);\n const res = await sendTemplated(notifyDeps(db, env), {\n group: emailGroupFrom(group),\n template,\n to: str(group.notificationEmail),\n vars: { firstName: \"Sample\", lastName: \"Person\", email: \"sample@example.com\", phone: \"(555) 010-0100\", state: \"CA\", adminUrl: `${url.origin}/admin/`, membersUrl: `${url.origin}/members/` },\n dedupeKey: `test:${template}:${Date.now()}`,\n force: true,\n });\n return json({ ok: res.sent, reason: res.reason ?? null, to: str(group.notificationEmail), redirected: env.ODLA_ENV !== \"prod\" && !!group.debugEmail });\n};\n\n/** GET /api/admin/people/:applicationId/comms — one person's timeline: sent\n * lifecycle mail (adminNotification dropped — it goes to the team) plus the\n * Google calendar invitations reconstructed from their meeting rows. */\nexport const handleAdminComms: Route = async (req, url, env, ctx) => {\n const m = url.pathname.match(/^\\/api\\/admin\\/people\\/([0-9a-fA-F-]+)\\/comms$/);\n if (req.method !== \"GET\" || !m) return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n const appId = m[1] as string;\n\n const [emailRes, meetingRes, appRes] = await Promise.all([\n db.query({ emailLog: { $: { where: { applicationId: appId }, order: { sentAt: \"desc\" }, limit: 100 } } }),\n db.query({ meetings: { $: { where: { applicationId: appId } } } }),\n db.query({ applications: { $: { where: { id: appId }, limit: 1 } } }),\n ]);\n const app = appRes.applications?.[0] ?? null;\n const group = await loadGroup(db, str(app?.groupId, ctx.chapter.id));\n const vars: Record<string, string> | null = app\n ? { firstName: str(app.firstName), lastName: str(app.lastName), email: str(app.email), phone: str(app.phone), state: str(app.state), adminUrl: `${url.origin}/admin/`, membersUrl: `${url.origin}/members/` }\n : null;\n\n const emails = ((emailRes.emailLog ?? []) as Array<Record<string, unknown>>)\n .filter((r) => r.template !== \"adminNotification\")\n .map((r): Record<string, unknown> => {\n let mailBody: string | null = typeof r.body === \"string\" ? r.body : null;\n if (!mailBody && group && vars) mailBody = renderTemplateBody(emailGroupFrom(group), String(r.template), vars);\n const channel = r.error ? \"email (failed)\" : r.redirected ? \"email (dev-redirected)\" : r.transport === \"log-only\" ? \"email (not delivered)\" : \"email\";\n return { kind: \"email\", channel, label: String(r.template), subject: str(r.subject), to: (r.to as string) ?? null, body: mailBody, at: r.sentAt as number, error: (r.error as string) ?? null };\n });\n const calendar = ((meetingRes.meetings ?? []) as Array<Record<string, unknown>>).map((m2): Record<string, unknown> => ({\n kind: \"calendar\",\n channel: \"Google Calendar\",\n label: m2.status === \"cancelled\" ? \"Invitation (call later cancelled)\" : \"Meeting invitation\",\n subject: \"Introduction call invitation\",\n to: null,\n at: (m2.createdAt as number) ?? (m2.startAt as number),\n error: null,\n }));\n const items = [...emails, ...calendar].sort((a, b) => ((b.at as number) ?? 0) - ((a.at as number) ?? 0));\n return json({ items });\n};\n","// Leader-side network routes. The receiving route lives in worker-routes.ts;\n// these admin-gated routes expose configured targets and fan one CRM record out\n// to selected followers with per-target vaulted credentials.\nimport { addTag, getRecord } from \"@odla-ai/crm\";\nimport type { CrmRecord } from \"@odla-ai/crm\";\nimport { getVaultSecret } from \"./auth\";\nimport { DEFAULT_SHARE_FIELDS, sharedRecordFromCrm } from \"./network\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, Db, Route, Verified, WorkerContext } from \"./worker-context\";\nimport type { ChapterDb, ResolvedNetworkTarget } from \"./types\";\n\nasync function gate(\n req: Request,\n env: ChapterEnv,\n ctx: WorkerContext,\n): Promise<{ response: Response } | { db: Db; user: Verified }> {\n const db = ctx.makeDb(env);\n const user = await ctx.verifyUser(req, env);\n if (!user) return { response: json({ error: \"unauthorized\" }, 401) };\n if (!(await ctx.isAdmin(db, user))) return { response: json({ error: \"forbidden\" }, 403) };\n return { db, user };\n}\n\n/** GET /api/admin/network/targets — non-secret target metadata for the UI. */\nexport const handleAdminNetworkTargets: Route = async (req, url, env, ctx) => {\n if (req.method !== \"GET\" || url.pathname !== \"/api/admin/network/targets\") return null;\n const got = await gate(req, env, ctx);\n if (\"response\" in got) return got.response;\n return json({\n targets: ctx.chapter.network.targets.map(({ id, name, url: targetUrl, fields }) => ({\n id,\n name,\n url: targetUrl,\n types: Object.keys(fields ?? DEFAULT_SHARE_FIELDS),\n })),\n });\n};\n\ninterface PushResult {\n id: string;\n name: string;\n ok: boolean;\n status?: number;\n recordId?: string;\n error?: string;\n}\n\nasync function pushOne(\n db: ChapterDb,\n ctx: WorkerContext,\n target: ResolvedNetworkTarget,\n record: CrmRecord,\n): Promise<PushResult> {\n const secret = await getVaultSecret(db, target.secretName);\n if (!secret) return { id: target.id, name: target.name, ok: false, error: `vault secret \"${target.secretName}\" is missing` };\n let payload;\n try {\n payload = sharedRecordFromCrm(ctx.chapter.crm, record, target);\n } catch (err) {\n return { id: target.id, name: target.name, ok: false, error: err instanceof Error ? err.message : \"record is not shareable\" };\n }\n try {\n const res = await fetch(new URL(\"/api/network/shared\", target.url), {\n method: \"POST\",\n headers: { authorization: `Bearer ${secret}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(10_000),\n });\n const body = (await res.json().catch(() => ({}))) as { recordId?: string; error?: string };\n if (!res.ok) {\n return { id: target.id, name: target.name, ok: false, status: res.status, error: body.error ?? \"follower rejected the record\" };\n }\n await addTag(\n { crm: ctx.chapter.crm, db: db as never },\n { recordId: record.id, tag: `shared:${target.id}`, mutationId: `network-delivered:${record.id}:${target.id}` },\n );\n return { id: target.id, name: target.name, ok: true, status: res.status, recordId: body.recordId };\n } catch (err) {\n return { id: target.id, name: target.name, ok: false, error: err instanceof Error ? err.message : \"delivery failed\" };\n }\n}\n\n/** POST /api/admin/network/push `{ recordId, targetIds }` — push one leader CRM\n * record to one or more configured followers. Each follower receives an\n * independently validated, allowlisted projection; partial failure is explicit. */\nexport const handleAdminNetworkPush: Route = async (req, url, env, ctx) => {\n if (req.method !== \"POST\" || url.pathname !== \"/api/admin/network/push\") return null;\n const got = await gate(req, env, ctx);\n if (\"response\" in got) return got.response;\n let body: { recordId?: unknown; targetIds?: unknown };\n try {\n body = (await req.json()) as typeof body;\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n if (typeof body.recordId !== \"string\" || !Array.isArray(body.targetIds) || body.targetIds.length === 0) {\n return json({ error: \"recordId and a non-empty targetIds array are required\" }, 400);\n }\n const requested = new Set(body.targetIds.filter((id): id is string => typeof id === \"string\"));\n if (requested.size !== body.targetIds.length) return json({ error: \"targetIds must contain unique strings\" }, 400);\n const targets = ctx.chapter.network.targets.filter((target) => requested.has(target.id));\n if (targets.length !== requested.size) return json({ error: \"one or more targetIds are not configured\" }, 400);\n\n const record = await getRecord({ crm: ctx.chapter.crm, db: got.db as never }, body.recordId);\n if (!record) return json({ error: \"record not found\" }, 404);\n const results = await Promise.all(\n targets.map((target) => pushOne(got.db as unknown as ChapterDb, ctx, target, record)),\n );\n return json({ ok: results.every((result) => result.ok), results });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMA,gBAA0B;AAC1B,kBAA8C;;;AC2BvC,SAAS,cAAc,SAAkC,MAA4B;AAC1F,QAAM,MAAM,QAAQ,KAAK,KAAK;AAC9B,SAAO,OAAO,QAAQ,YAAY,KAAK,OAAO,SAAS,GAAG,IAAI,MAAO,KAAK,OAAO,CAAC;AACpF;AAGO,SAAS,YAAY,MAAc,MAA6B;AACrE,SAAO,SAAS,KAAK;AACvB;AA0BO,SAAS,cAAc,KAAqC;AACjE,QAAM,EAAE,KAAK,IAAI;AACjB,MAAI,CAAC,KAAK,OAAO,SAAS,IAAI,OAAO,GAAG;AACtC,WAAO,EAAE,IAAI,OAAO,QAAQ,KAAK,OAAO,wBAAwB,KAAK,OAAO,KAAK,IAAI,CAAC,GAAG;AAAA,EAC3F;AACA,MAAI,IAAI,YAAY,IAAI,UAAU;AAChC,WAAO,EAAE,IAAI,OAAO,QAAQ,KAAK,OAAO,kCAAkC;AAAA,EAC5E;AACA,MAAI,IAAI,iBAAiB,CAAC,IAAI,cAAc;AAC1C,WAAO,EAAE,IAAI,OAAO,QAAQ,KAAK,OAAO,uEAAuE;AAAA,EACjH;AACA,QAAM,eAAe,IAAI,YAAY,KAAK,aAAa,IAAI,sBAAsB,KAAK;AACtF,MAAI,KAAK,eAAe,gBAAgB,CAAC,IAAI,cAAc;AACzD,WAAO,EAAE,IAAI,OAAO,QAAQ,KAAK,OAAO,6CAA6C,KAAK,SAAS,GAAG;AAAA,EACxG;AACA,SAAO,EAAE,IAAI,KAAK;AACpB;AAaA,eAAsB,eAAe,IAAiB,MAA2C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","crmDeps","str","rows","rows","firstRow","rows","import_calendar","rows","import_crm","crmDeps","gate","rows","import_calendar","gate","crmDeps","gate","loadGroup","str","import_crm","gate"]}
1
+ {"version":3,"sources":["../../src/worker.ts","../../src/worker-context.ts","../../src/auth.ts","../../src/worker-routes.ts","../../src/clerk.ts","../../src/member.ts","../../src/network.ts","../../src/scheduling.ts","../../src/session.ts","../../src/email.ts","../../src/notify.ts","../../src/worker-routes-schedule.ts","../../src/pipeline.ts","../../src/payments.ts","../../src/payments-stripe.ts","../../src/worker-routes-payments.ts","../../src/worker-routes-admin.ts","../../src/reconcile.ts","../../src/clerk-roles.ts","../../src/crm-sync.ts","../../src/worker-routes-admin-people.ts","../../src/series.ts","../../src/worker-routes-admin-dashboard.ts","../../src/worker-routes-admin-lifecycle.ts","../../src/worker-routes-admin-comms.ts","../../src/worker-routes-network.ts"],"sourcesContent":["// chapterWorker — the Cloudflare Worker for a chapter/hub site. This entry\n// (@odla-ai/chapter/worker) is separate from the core so the CLI can load\n// odla.config.mjs without pulling in worker-runtime deps.\n//\n// The worker is the ONLY thing that talks to odla-db, using the app key\n// (ODLA_API_KEY), which bypasses the deny-all rules. Browsers never receive a\n// db credential. Access is admin-only: a request is authorized when its Clerk\n// session JWT verifies AND the user's role (a JWT claim, or a row in the\n// Studio-seeded `admins` allowlist) is an admin rung.\n//\n// The env typing + auth plumbing live in ./worker-context; the route handlers in\n// ./worker-routes. This entry only builds the context and runs the routes in\n// order — first match wins, else the static site (ASSETS).\n//\n// hub mode routes: GET /api/config, GET /api/me, /api/crm/*, POST\n// /api/network/shared, else ASSETS. chapter mode adds the public member surface:\n// GET /api/join-config and POST /api/applications (idempotent).\nimport { createWorkerContext } from \"./worker-context\";\nimport type { ChapterEnv, ChapterWorkerOptions, Route } from \"./worker-context\";\nimport { handleConfig, handleCrm, handleHealth, handleMe, handleMember, handleNetworkShared } from \"./worker-routes\";\nimport { handleSchedule } from \"./worker-routes-schedule\";\nimport { handlePayments } from \"./worker-routes-payments\";\nimport { handleAdminMeetings, handleAdminScheduling } from \"./worker-routes-admin\";\nimport { handleAdminCrmSync, handleAdminPeople, handleAdminPeopleAccess, handleAdminPeopleRole } from \"./worker-routes-admin-people\";\nimport { handleAdminDashboard, handleAdminBilling } from \"./worker-routes-admin-dashboard\";\nimport { handleAdminMeetingReschedule, handleAdminMeetingCancel, handleAdminApprove, handleAdminRefund, handleAdminApplicationPatch } from \"./worker-routes-admin-lifecycle\";\nimport { handleAdminGroupEmail, handleAdminEmailLog, handleAdminEmailTest, handleAdminComms } from \"./worker-routes-admin-comms\";\nimport { handleAdminNetworkPush, handleAdminNetworkTargets } from \"./worker-routes-network\";\n\n// The route seam: a wrapping worker can build its own routes + reuse chapter's\n// auth by composing against these.\nexport { createWorkerContext } from \"./worker-context\";\nexport type { ChapterEnv, ChapterWorkerOptions, WorkerContext, Route } from \"./worker-context\";\n\n// First-match-wins order. Host routes (options.routes) run BEFORE these.\nconst BUILTIN_ROUTES: Route[] = [\n handleHealth,\n handleConfig,\n handleMe,\n handleCrm,\n handleNetworkShared,\n handleMember,\n handleSchedule,\n handlePayments,\n handleAdminMeetings,\n handleAdminScheduling,\n // Roster + identity\n handleAdminPeople,\n handleAdminPeopleAccess,\n handleAdminPeopleRole,\n handleAdminCrmSync,\n // Aggregation\n handleAdminDashboard,\n handleAdminBilling,\n // Lifecycle actions\n handleAdminMeetingReschedule,\n handleAdminMeetingCancel,\n handleAdminApprove,\n handleAdminRefund,\n handleAdminApplicationPatch,\n // Email + comms\n handleAdminGroupEmail,\n handleAdminEmailLog,\n handleAdminEmailTest,\n handleAdminComms,\n // Leader → follower record delivery\n handleAdminNetworkTargets,\n handleAdminNetworkPush,\n];\n\n/**\n * Build the Cloudflare `ExportedHandler` for a chapter/hub site: Clerk-JWT\n * verification, the source-aware admin gate, the mounted @odla-ai/crm routes, the\n * hub→chapter network projection, and the static-asset fallback. Hub mode serves\n * /api/health, /api/config, /api/me, /api/crm/*, /api/network/shared; chapter mode\n * adds the public member surface (join/apply/pay/book) and the admin surface\n * (/api/admin/*).\n *\n * A wrapping site adds its own routes via `options.routes` — each receives the\n * same {@link WorkerContext} the built-ins get (so it reuses chapter's JWT\n * verify, db client, and role resolution instead of duplicating them), and runs\n * BEFORE the built-ins so it can override or alias a path.\n *\n * Observability is a host concern, not a chapter dependency. To trace, wrap the\n * result in your worker entry — `export default withObservability(chapterWorker(\n * { chapter }))` — with `withObservability` from `@odla-ai/o11y`. Sites that\n * don't run o11y bundle `@odla-ai/chapter/worker` without installing it.\n */\nexport function chapterWorker(options: ChapterWorkerOptions) {\n const ctx = createWorkerContext(options);\n const routes: Route[] = [...(options.routes ?? []), ...BUILTIN_ROUTES];\n return {\n async fetch(req: Request, env: ChapterEnv): Promise<Response> {\n const url = new URL(req.url);\n for (const route of routes) {\n const res = await route(req, url, env, ctx);\n if (res) return res;\n }\n // Everything else is the static site.\n return env.ASSETS.fetch(req);\n },\n };\n}\n","// Shared context for the chapter Worker: env typing, the odla-db admin client,\n// Clerk-JWT verification, and the source-aware auth helpers. Split out of\n// worker.ts so the route modules share ONE construction of the caches (public\n// config + JWKS) per site, and the worker entry stays a thin composer under the\n// per-file LOC cap. Nothing here is re-exported from the worker entry, so the\n// public `@odla-ai/chapter/worker` surface is unchanged by the split.\nimport { initAdmin } from \"@odla-ai/db\";\nimport { createRemoteJWKSet, jwtVerify } from \"jose\";\nimport { isAdminRole, roleFromClaim } from \"./auth\";\nimport type { Chapter } from \"./types\";\n\n/** The Cloudflare SEND_EMAIL binding payload. */\nexport interface EmailPayload {\n from: string;\n to: string[];\n subject: string;\n text?: string;\n html?: string;\n replyTo?: string;\n headers?: Record<string, string>;\n}\n\n/** The Worker env a chapter site provides (wrangler vars + the ODLA_API_KEY\n * secret pushed by provision). */\nexport interface ChapterEnv {\n ASSETS: { fetch(req: Request): Promise<Response> };\n ODLA_ENDPOINT: string;\n ODLA_TENANT: string;\n ODLA_PLATFORM: string;\n ODLA_APP_ID: string;\n ODLA_ENV: string;\n ODLA_API_KEY: string;\n SEND_EMAIL?: { send(payload: EmailPayload): Promise<{ messageId: string }> };\n EMAIL_FROM?: string;\n}\n\n/** Options for `chapterWorker`. */\nexport interface ChapterWorkerOptions {\n chapter: Chapter;\n /** CRM mount point. Default \"/api/crm\". */\n crmBasePath?: string;\n /** Host routes, tried BEFORE the built-ins — so a wrapping site can add its own\n * routes (or override/alias a built-in path) and reuse chapter's auth via the\n * shared {@link WorkerContext}, instead of re-verifying JWTs itself. */\n routes?: Route[];\n}\n\n/** The registry public-config a site reads to boot Clerk sign-in. */\nexport type PublicConfig = { env?: string; clerkPublishableKey?: string | null; issuer?: string | null };\n/** The odla-db admin client type. */\nexport type Db = ReturnType<typeof initAdmin>;\n\n/** A verified session: the Clerk `sub`, optional email, and the raw JWT payload\n * (so the role claim can be read for auth source \"claim\"). */\nexport interface Verified {\n userId: string;\n email?: string;\n payload: Record<string, unknown>;\n}\n\n/** JSON response helper. */\nexport const json = (body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } });\n\n/**\n * Build the per-site Worker context: env-independent helpers closing over the\n * public-config and JWKS caches, plus the source-aware auth gate (JWT claim or\n * the odla-db `admins` allowlist). Constructed once per `chapterWorker` and\n * shared by every route module.\n */\nexport function createWorkerContext(options: ChapterWorkerOptions) {\n const { chapter } = options;\n const auth = chapter.auth;\n const crmBase = options.crmBasePath ?? \"/api/crm\";\n\n let publicConfigCache: { value: PublicConfig; at: number } | null = null;\n const jwksByIssuer = new Map<string, ReturnType<typeof createRemoteJWKSet>>();\n\n async function getPublicConfig(env: ChapterEnv): Promise<PublicConfig> {\n if (publicConfigCache && Date.now() - publicConfigCache.at < 5 * 60_000) return publicConfigCache.value;\n const res = await fetch(`${env.ODLA_PLATFORM}/registry/apps/${env.ODLA_APP_ID}/public-config?env=${env.ODLA_ENV}`);\n if (!res.ok) throw new Error(`public-config fetch failed: ${res.status}`);\n const value = (await res.json()) as PublicConfig;\n publicConfigCache = { value, at: Date.now() };\n return value;\n }\n\n async function verifyUser(req: Request, env: ChapterEnv): Promise<Verified | null> {\n const header = req.headers.get(\"authorization\") ?? \"\";\n if (!header.startsWith(\"Bearer \")) return null;\n const token = header.slice(7);\n const { issuer } = await getPublicConfig(env);\n if (!issuer) return null;\n let jwks = jwksByIssuer.get(issuer);\n if (!jwks) {\n jwks = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`));\n jwksByIssuer.set(issuer, jwks);\n }\n try {\n const { payload } = await jwtVerify(token, jwks, { issuer });\n if (!payload.sub) return null;\n return {\n userId: payload.sub,\n email: typeof payload.email === \"string\" ? payload.email : undefined,\n payload: payload as Record<string, unknown>,\n };\n } catch {\n return null;\n }\n }\n\n function makeDb(env: ChapterEnv): Db {\n return initAdmin({ appId: env.ODLA_TENANT, adminToken: env.ODLA_API_KEY, endpoint: env.ODLA_ENDPOINT });\n }\n\n // The `admins` allowlist gate (auth source \"table\"): no route ever writes it, so\n // membership can only be granted by a human in odla Studio.\n async function isAdminEmail(db: Db, email: string | undefined): Promise<boolean> {\n if (!email) return false;\n const { admins } = await db.query({ admins: { $: { where: { email: email.toLowerCase() }, limit: 1 } } });\n return Array.isArray(admins) && admins.length > 0;\n }\n\n // The read-only `superAdmins` tier — queried, never written (Studio-only).\n async function isSuperAdminEmail(db: Db, email: string | undefined): Promise<boolean> {\n if (!auth.superAdmins || !email) return false;\n const { superAdmins } = await db.query({ superAdmins: { $: { where: { email: email.toLowerCase() }, limit: 1 } } });\n return Array.isArray(superAdmins) && superAdmins.length > 0;\n }\n\n // The user's role, resolved per the auth source: a JWT claim, or the `admins`\n // allowlist synthesized to the admin rung / the lowest one.\n async function roleFor(db: Db, u: Verified): Promise<string> {\n if (auth.source === \"claim\") return roleFromClaim(u.payload, auth);\n return (await isAdminEmail(db, u.email)) ? auth.adminRole : (auth.ladder[0] as string);\n }\n\n // Admin authorization — the boolean gate used by /api/me and the CRM surface.\n async function isAdmin(db: Db, u: Verified): Promise<boolean> {\n if (auth.source === \"claim\") return isAdminRole(roleFromClaim(u.payload, auth), auth);\n return isAdminEmail(db, u.email);\n }\n\n function crmSender(env: ChapterEnv) {\n if (!env.SEND_EMAIL || !env.EMAIL_FROM) return undefined;\n const binding = env.SEND_EMAIL;\n return {\n async send(payload: EmailPayload): Promise<{ messageId: string }> {\n return binding.send(payload);\n },\n };\n }\n\n return { chapter, auth, crmBase, getPublicConfig, verifyUser, makeDb, isAdminEmail, isSuperAdminEmail, roleFor, isAdmin, crmSender };\n}\n\n/** The value returned by {@link createWorkerContext}, threaded to every route. */\nexport type WorkerContext = ReturnType<typeof createWorkerContext>;\n\n/** A worker route handler: owns the request (returns a Response) or falls through\n * (returns null). Host routes passed to `chapterWorker` compose against the same\n * {@link WorkerContext} the built-ins receive. */\nexport type Route = (req: Request, url: URL, env: ChapterEnv, ctx: WorkerContext) => Promise<Response | null>;\n","// Identity + authorization for a chapter/hub site — the pieces every membership\n// site needs and none should re-derive: a resolved role policy, role resolution\n// from a JWT claim, the privilege-escalation guard, and a tenant-vault read.\n// Everything here is pure or structural (no runtime @odla-ai/db import), so it is\n// trivially testable and the worker stays the only thing that talks to odla-db.\nimport type { ChapterAuth, ChapterMode, ResolvedAuth } from \"./types\";\n\n/**\n * Apply defaults + validate the auth config into a {@link ResolvedAuth}. Defaults\n * by mode: `chapter` → the `provisional/member/admin` claim ladder with the\n * `superAdmins` tier; `hub` → the `admins` allowlist table with no super tier.\n * Throws at import on a bad policy.\n */\nexport function resolveAuth(mode: ChapterMode, auth: ChapterAuth | undefined): ResolvedAuth {\n const a = auth ?? {};\n const source = a.source ?? (mode === \"hub\" ? \"table\" : \"claim\");\n if (source !== \"claim\" && source !== \"table\") {\n throw new Error(`defineChapter.auth.source: must be \"claim\" or \"table\" — got ${JSON.stringify(a.source)}`);\n }\n const claim = a.claim ?? \"role\";\n if (typeof claim !== \"string\" || claim === \"\") {\n throw new Error(\"defineChapter.auth.claim: must be a non-empty string\");\n }\n const ladder = a.ladder ?? [\"provisional\", \"member\", \"admin\"];\n if (!Array.isArray(ladder) || ladder.length === 0 || !ladder.every((r) => typeof r === \"string\" && r !== \"\")) {\n throw new Error(\"defineChapter.auth.ladder: must be a non-empty array of role strings\");\n }\n const adminRole = ladder[ladder.length - 1] as string;\n const superAdmins = a.superAdmins ?? source === \"claim\";\n return { source, claim, ladder, adminRole, superAdmins };\n}\n\n/** The role from a verified JWT payload, per the resolved policy. An unknown or\n * missing claim falls back to the lowest ladder rung (fail safe, never admin). */\nexport function roleFromClaim(payload: Record<string, unknown>, auth: ResolvedAuth): string {\n const raw = payload[auth.claim];\n return typeof raw === \"string\" && auth.ladder.includes(raw) ? raw : (auth.ladder[0] as string);\n}\n\n/** Does a role meet the admin bar (the highest ladder rung)? */\nexport function isAdminRole(role: string, auth: ResolvedAuth): boolean {\n return role === auth.adminRole;\n}\n\n/** Inputs to the role-change guard — resolved by the caller (route) from the\n * identity provider + the read-only `superAdmins` table. */\nexport interface RoleChangeContext {\n actorId: string;\n actorIsSuper: boolean;\n targetId: string;\n targetCurrentRole: string;\n targetIsSuper: boolean;\n newRole: string;\n auth: ResolvedAuth;\n}\n\n/** The result of {@link canChangeRole}: allow, or deny with the HTTP status +\n * message the route should return. */\nexport type GuardResult = { ok: true } | { ok: false; status: number; error: string };\n\n/**\n * The privilege-escalation guard — package-enforced so every site gets it and\n * none re-derives it. Denies: an out-of-ladder role; changing your own role;\n * touching a super-admin unless you are one; and (when a `superAdmins` tier\n * exists) creating or altering an admin unless you are a super-admin. Note the\n * super-admin tier itself is never writable here — it lives in the read-only\n * `superAdmins` table, set only in odla Studio.\n */\nexport function canChangeRole(ctx: RoleChangeContext): GuardResult {\n const { auth } = ctx;\n if (!auth.ladder.includes(ctx.newRole)) {\n return { ok: false, status: 400, error: `role must be one of: ${auth.ladder.join(\", \")}` };\n }\n if (ctx.actorId === ctx.targetId) {\n return { ok: false, status: 400, error: \"you cannot change your own role\" };\n }\n if (ctx.targetIsSuper && !ctx.actorIsSuper) {\n return { ok: false, status: 403, error: \"this person is a super-admin; their access is managed in odla Studio\" };\n }\n const touchesAdmin = ctx.newRole === auth.adminRole || ctx.targetCurrentRole === auth.adminRole;\n if (auth.superAdmins && touchesAdmin && !ctx.actorIsSuper) {\n return { ok: false, status: 403, error: `only super-admins can create or change an ${auth.adminRole}` };\n }\n return { ok: true };\n}\n\n/** Structural view of odla-db's tenant-vault read, so chapter takes no runtime\n * dependency on @odla-ai/db. The worker's admin client satisfies this. */\nexport interface SecretStore {\n secrets: { get(name: string): Promise<string> };\n}\n\n/**\n * Read a tenant-vault secret by name; `undefined` when it is absent or the vault\n * errors, so callers degrade gracefully (e.g. `paymentsReady: false`) rather than\n * throwing. Never logs the value.\n */\nexport async function getVaultSecret(db: SecretStore, name: string): Promise<string | undefined> {\n try {\n const value = await db.secrets.get(name);\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n } catch {\n return undefined;\n }\n}\n","// Route handlers for the chapter Worker. Each returns a Response when it owns the\n// request, or null to fall through to the next handler (finally ASSETS). Split\n// out of worker.ts so the entry stays a thin composer under the per-file LOC cap;\n// behaviour and route order are unchanged from the original single-file handler.\nimport { createCrmRoutes } from \"@odla-ai/crm\";\nimport { getVaultSecret, isAdminRole } from \"./auth\";\nimport { createClerkInvitation, createClerkUser } from \"./clerk\";\nimport { applicantProfile, joinConfig, submitApplication } from \"./member\";\nimport { normalizeSharedRecord, projectApplicant, projectSharedRecord } from \"./network\";\nimport { resolveScheduling } from \"./scheduling\";\nimport { memberApplication } from \"./session\";\nimport type { ApplicationRecord, MeetingRecord, MemberApplication } from \"./session\";\nimport { emailGroupFrom, sendTemplated } from \"./notify\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, Route } from \"./worker-context\";\nimport type { Chapter, ChapterDb, ChapterScheduling } from \"./types\";\n\nexport type { Route };\n\n// Apply-time provisioning (both best-effort — never fail the application):\n// project the applicant into crm_record, and mint a Clerk invitation so they get\n// a path into their member area (only when a clerk_secret_key is in the vault).\nasync function provisionApplicant(\n db: ChapterDb,\n chapter: Chapter,\n applicationId: string,\n fields: Record<string, unknown>,\n): Promise<void> {\n const email = typeof fields.email === \"string\" ? fields.email : \"\";\n if (!email) return;\n const s = (v: unknown): string | undefined => (typeof v === \"string\" ? v : undefined);\n // Carry the site-configured crmFields (present values only) into the projection\n // as enrichment on top of the built-in identity/contact set.\n const extra: Record<string, unknown> = {};\n for (const f of chapter.application.crmFields) {\n if (fields[f] !== undefined) extra[f] = fields[f];\n }\n try {\n await projectApplicant(\n { crm: chapter.crm, db, now: () => Date.now(), newId: () => crypto.randomUUID() },\n { applicationId, email, firstName: s(fields.firstName), lastName: s(fields.lastName), phone: s(fields.phone), linkedin: s(fields.linkedin), extra },\n );\n } catch {\n // CRM projection is best-effort\n }\n if (chapter.account !== \"none\") {\n try {\n const secret = await getVaultSecret(db, \"clerk_secret_key\");\n if (secret) {\n // Carry the applicant's own fields onto the account under\n // `public_metadata.profile`, plus the application id that produced it, so\n // the account is self-describing under either account model. The 422 heal\n // refreshes this on an account an earlier missed create never wrote.\n const profile = applicantProfile(chapter, fields);\n const publicMetadata = { applicationId, ...(profile ? { profile } : {}) };\n if (chapter.account === \"create\") {\n await createClerkUser(secret, { email, firstName: s(fields.firstName), lastName: s(fields.lastName), publicMetadata });\n } else {\n await createClerkInvitation(secret, { email, publicMetadata });\n }\n }\n } catch {\n // account provisioning is best-effort\n }\n }\n}\n\n// Best-effort admin notification when an application arrives, so a human sees it\n// even before payment. Exactly-once per application via the dedupeKey.\nasync function notifyAdminOfApplication(\n db: ChapterDb,\n env: ChapterEnv,\n chapterId: string,\n applicationId: string,\n fields: Record<string, unknown>,\n): Promise<void> {\n try {\n const groups = (await db.query({ groups: { $: { where: { id: chapterId }, limit: 1 } } })).groups;\n const group = Array.isArray(groups) ? groups[0] : undefined;\n if (!group || typeof group.notificationEmail !== \"string\" || !group.notificationEmail) return;\n const s = (v: unknown): string => (typeof v === \"string\" ? v : \"\");\n await sendTemplated(\n { db, envName: env.ODLA_ENV, sender: env.SEND_EMAIL, from: env.EMAIL_FROM, now: () => Date.now(), newId: () => crypto.randomUUID() },\n {\n group: emailGroupFrom(group),\n template: \"adminNotification\",\n to: group.notificationEmail,\n vars: { firstName: s(fields.firstName), lastName: s(fields.lastName), email: s(fields.email), phone: s(fields.phone), state: s(fields.state) },\n dedupeKey: `apply:${applicationId}:admin`,\n applicationId,\n },\n );\n } catch {\n // never fail the application on a notification error\n }\n}\n\n// The signed-in member's own application (chapter mode): the latest by email,\n// folded with its latest scheduled meeting and rendered in the group's timezone.\n// The meetings row is canonical, so no live-calendar reconcile is needed here.\nasync function memberSessionApplication(db: ChapterDb, chapterId: string, email: string): Promise<MemberApplication | null> {\n const apps = (await db.query({ applications: { $: { where: { email }, order: { createdAt: \"desc\" }, limit: 1 } } })).applications;\n const app = Array.isArray(apps) ? apps[0] : undefined;\n if (!app) return null;\n const meetings = (\n await db.query({ meetings: { $: { where: { applicationId: app.id, status: \"scheduled\" }, order: { createdAt: \"desc\" }, limit: 1 } } })\n ).meetings;\n const meeting = Array.isArray(meetings) ? meetings[0] : undefined;\n const groups = (await db.query({ groups: { $: { where: { id: chapterId }, limit: 1 } } })).groups;\n const group = Array.isArray(groups) ? groups[0] : undefined;\n const timezone = resolveScheduling(group?.schedulingJson as ChapterScheduling | undefined).timezone;\n return memberApplication(app as unknown as ApplicationRecord, meeting as unknown as MeetingRecord | undefined, timezone);\n}\n\n/** GET /api/health — a public liveness probe (what deploy checks hit). */\nexport const handleHealth: Route = async (_req, url) => (url.pathname === \"/api/health\" ? json({ ok: true }) : null);\n\n/** GET /api/config — the public Clerk publishable key, so the SPA can boot sign-in. */\nexport const handleConfig: Route = async (_req, url, env, ctx) => {\n if (url.pathname !== \"/api/config\") return null;\n try {\n const { clerkPublishableKey } = await ctx.getPublicConfig(env);\n return json({ clerkPublishableKey: clerkPublishableKey ?? null, env: env.ODLA_ENV });\n } catch {\n return json({ clerkPublishableKey: null, env: env.ODLA_ENV });\n }\n};\n\n/** GET /api/me — the signed-in user's role, admin authorization, and super-admin\n * tier. In chapter mode it also carries the member's own `application` (their\n * status + booked call), so the member area renders from one call. */\nexport const handleMe: Route = async (req, url, env, ctx) => {\n if (url.pathname !== \"/api/me\") return null;\n const u = await ctx.verifyUser(req, env);\n if (!u) return json({ authorized: false }, 401);\n const db = ctx.makeDb(env);\n const role = await ctx.roleFor(db, u);\n const superAdmin = await ctx.isSuperAdminEmail(db, u.email);\n const base = { authorized: isAdminRole(role, ctx.auth), role, superAdmin, email: u.email ?? null };\n if (ctx.chapter.mode !== \"chapter\" || !u.email) return json(base);\n const application = await memberSessionApplication(db as unknown as ChapterDb, ctx.chapter.id, u.email);\n return json({ ...base, application });\n};\n\n/** /api/crm/* — the CRM admin surface (mounted at ctx.crmBase). */\nexport const handleCrm: Route = async (req, url, env, ctx) => {\n const crmBase = ctx.crmBase;\n if (url.pathname !== crmBase && !url.pathname.startsWith(crmBase + \"/\")) return null;\n const db = ctx.makeDb(env);\n const routes = createCrmRoutes({\n crm: ctx.chapter.crm,\n db: db as never,\n authorize: async (r: Request) => {\n const u = await ctx.verifyUser(r, env);\n if (!u || !(await ctx.isAdmin(db, u))) return null;\n return u.email ? { userId: u.userId, email: u.email } : { userId: u.userId };\n },\n sender: ctx.crmSender(env),\n from: env.EMAIL_FROM,\n envName: env.ODLA_ENV,\n baseUrl: url.origin,\n basePath: crmBase,\n });\n const res = await routes(req);\n if (res) return res;\n return json({ error: \"not found\" }, 404);\n};\n\n/** POST /api/network/shared — leader push projection into this site's\n * crm_record (vault-secret gated, works in both modes). Accepts the original\n * person shape and the versioned generic person/company/deal envelope. */\nexport const handleNetworkShared: Route = async (req, url, env, ctx) => {\n if (req.method !== \"POST\" || url.pathname !== \"/api/network/shared\") return null;\n const db = ctx.makeDb(env);\n const secret = await getVaultSecret(db as unknown as ChapterDb, \"network_share_secret\");\n const provided = (req.headers.get(\"authorization\") ?? \"\").replace(/^Bearer /, \"\");\n if (!secret || provided.length !== secret.length || provided !== secret) {\n return json({ error: \"unauthorized\" }, 401);\n }\n let payload: Record<string, unknown>;\n try {\n payload = JSON.parse(await req.text()) as Record<string, unknown>;\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n if (typeof payload.hubRecordId !== \"string\" || !payload.hubRecordId.trim()) {\n return json({ error: \"hubRecordId is required\" }, 400);\n }\n if (\"input\" in payload) {\n if (\n payload.version !== 1 ||\n typeof payload.type !== \"string\" ||\n !payload.type.trim() ||\n !payload.input ||\n typeof payload.input !== \"object\" ||\n Array.isArray(payload.input)\n ) {\n return json({ error: \"version 1, type, and input are required\" }, 400);\n }\n } else if (payload.type !== \"company\" && typeof payload.email !== \"string\") {\n return json({ error: \"legacy person shares require email\" }, 400);\n } else if (payload.type === \"company\" && typeof payload.name !== \"string\") {\n return json({ error: \"business shares require name\" }, 400);\n }\n try {\n const record = normalizeSharedRecord(payload as never);\n const { recordId } = await projectSharedRecord(\n { crm: ctx.chapter.crm, db: db as unknown as ChapterDb, now: () => Date.now(), newId: () => crypto.randomUUID() },\n record,\n );\n return json({ recordId, type: record.type });\n } catch (err) {\n const message = err instanceof Error ? err.message : \"invalid shared record\";\n return json({ error: message }, 400);\n }\n};\n\n/** Chapter-mode public member surface: GET /api/join-config, POST /api/applications.\n * Returns null in hub mode so those paths fall through to ASSETS. */\nexport const handleMember: Route = async (req, url, env, ctx) => {\n const chapter = ctx.chapter;\n if (chapter.mode !== \"chapter\") return null;\n\n // Public join config: prices + policy copy + payment readiness (B1/C2).\n if (req.method === \"GET\" && url.pathname === \"/api/join-config\") {\n const db = ctx.makeDb(env);\n const groupId = url.searchParams.get(\"group\") ?? chapter.id;\n const { groups } = await db.query({ groups: { $: { where: { id: groupId }, limit: 1 } } });\n const group = Array.isArray(groups) ? groups[0] : undefined;\n if (!group) return json({ error: \"not found\" }, 404);\n const stripeKey = await getVaultSecret(db as unknown as ChapterDb, \"stripe_secret_key\");\n const paymentsReady = Boolean(group.stripePublishableKey && group.stripePriceId && stripeKey);\n return json(joinConfig(group as never, paymentsReady));\n }\n\n // Public application submit — validated, body-capped, idempotent (B2/B3).\n if (req.method === \"POST\" && url.pathname === \"/api/applications\") {\n const raw = await req.text();\n if (raw.length > chapter.application.bodyCap) return json({ error: \"request body too large\" }, 413);\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n const submissionId = typeof parsed.submissionId === \"string\" ? parsed.submissionId : undefined;\n const db = ctx.makeDb(env) as unknown as ChapterDb;\n const result = await submitApplication(db, chapter, parsed, {\n submissionId,\n groupId: chapter.id,\n now: Date.now(),\n newId: () => crypto.randomUUID(),\n });\n if (!result.ok) return json({ error: result.error }, 400);\n if (!result.duplicate) {\n // The trigger is declarative (sends.adminNotification); addressing + copy\n // stay owner-editable on the group row.\n if (chapter.sends.adminNotification === \"submit\") {\n await notifyAdminOfApplication(db, env, chapter.id, result.id, parsed);\n }\n await provisionApplicant(db, chapter, result.id, parsed);\n }\n return json({\n id: result.id,\n duplicate: result.duplicate,\n status: result.status,\n // Echoed so a site can see (and assert in an integration test) whether its\n // join page actually posted the ack. Absent consent is otherwise invisible.\n disclaimerAckAt: result.disclaimerAckAt,\n });\n }\n\n return null;\n};\n","// Apply-time account provisioning. When an application arrives, the worker mints\n// a Clerk invitation so the applicant gets a path into their member area — the\n// generalized server-side account step. Chapter calls the Clerk\n// Backend API directly over fetch (vault clerk_secret_key), mirroring\n// @odla-ai/auth-clerk's createInvitation but self-contained, so it never pulls the\n// auth-clerk UI package into the worker bundle. Best-effort at the call site: a\n// provisioning failure never fails the application.\n\n/** The outcome of a Clerk provisioning call. `existed` marks the heal case: Clerk\n * rejected it because the account/invitation is already there, which is the end\n * state we wanted anyway. */\nexport interface ClerkResult {\n ok: boolean;\n status: number;\n existed?: boolean;\n /** Set when an `existed` heal also refreshed the account's public_metadata. */\n refreshed?: boolean;\n}\n\n// Clerk answers 422 when the email already has a user (or a pending invitation).\n// For apply-time provisioning that's success, not failure — the account exists.\nconst heal = (status: number): ClerkResult =>\n status === 422 ? { ok: true, status, existed: true } : { ok: false, status };\n\n/** Inputs for a Clerk invitation. */\nexport interface ClerkInviteInput {\n email: string;\n /** Where the accept-invitation link lands (usually the member area). */\n redirectUrl?: string;\n /** Written to the invitation's `public_metadata`, so the accepted account\n * carries your own profile fields. */\n publicMetadata?: Record<string, unknown>;\n}\n\n/** Build the Clerk Backend API invitation request (path + JSON body). Pure, so\n * the wire shape is testable without a network call. */\nexport function clerkInviteRequest(input: ClerkInviteInput): { path: string; body: Record<string, unknown> } {\n return {\n path: \"/v1/invitations\",\n body: {\n email_address: input.email,\n notify: true,\n ...(input.redirectUrl ? { redirect_url: input.redirectUrl } : {}),\n ...(input.publicMetadata ? { public_metadata: input.publicMetadata } : {}),\n },\n };\n}\n\n/** POST the invitation to the Clerk Backend API. A repeat invite for an\n * already-invited email heals to `{ ok: true, existed: true }` rather than\n * reporting a failure the caller would have to special-case. */\nexport async function createClerkInvitation(\n secretKey: string,\n input: ClerkInviteInput,\n fetchImpl: typeof fetch = fetch,\n): Promise<ClerkResult> {\n const { path, body } = clerkInviteRequest(input);\n const res = await fetchImpl(`https://api.clerk.com${path}`, {\n method: \"POST\",\n headers: { authorization: `Bearer ${secretKey}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n return res.ok ? { ok: true, status: res.status } : heal(res.status);\n}\n\n/** Inputs for a server-side Clerk user create. */\nexport interface ClerkUserInput {\n email: string;\n firstName?: string;\n lastName?: string;\n /** Written to the user's `public_metadata` — the site's own profile fields\n * (role, tier, whatever the member area reads). */\n publicMetadata?: Record<string, unknown>;\n}\n\n/** Build the Clerk Backend API user-create request. The account is created\n * passwordless (the member signs in via the site's Clerk flow), so join step 3\n * can say the account is ready — the \"create\" alternative to an invitation. */\nexport function clerkUserRequest(input: ClerkUserInput): { path: string; body: Record<string, unknown> } {\n return {\n path: \"/v1/users\",\n body: {\n email_address: [input.email],\n skip_password_requirement: true,\n ...(input.firstName ? { first_name: input.firstName } : {}),\n ...(input.lastName ? { last_name: input.lastName } : {}),\n ...(input.publicMetadata ? { public_metadata: input.publicMetadata } : {}),\n },\n };\n}\n\n// Look the account up by email and PATCH its public_metadata. Used by the heal\n// path so a re-application REPAIRS a profile that an earlier missed create never\n// wrote, instead of just reporting \"already exists\".\nasync function refreshUserMetadata(\n secretKey: string,\n email: string,\n publicMetadata: Record<string, unknown>,\n fetchImpl: typeof fetch,\n): Promise<boolean> {\n const auth = { authorization: `Bearer ${secretKey}` };\n const found = await fetchImpl(`https://api.clerk.com/v1/users?email_address=${encodeURIComponent(email)}&limit=1`, { headers: auth });\n if (!found.ok) return false;\n const users = (await found.json().catch(() => null)) as Array<{ id?: unknown }> | null;\n const id = Array.isArray(users) && typeof users[0]?.id === \"string\" ? users[0].id : undefined;\n if (!id) return false;\n const patched = await fetchImpl(`https://api.clerk.com/v1/users/${id}/metadata`, {\n method: \"PATCH\",\n headers: { ...auth, \"content-type\": \"application/json\" },\n body: JSON.stringify({ public_metadata: publicMetadata }),\n });\n return patched.ok;\n}\n\n/** Create the applicant's Clerk account server-side. A repeat for an email that\n * already has an account heals to `{ ok: true, existed: true }` — the account\n * exists, which is the state apply-time provisioning wanted — and, when\n * `publicMetadata` was supplied, refreshes it on the existing account so a\n * re-application repairs a previously missed create (`refreshed: true`). */\nexport async function createClerkUser(\n secretKey: string,\n input: ClerkUserInput,\n fetchImpl: typeof fetch = fetch,\n): Promise<ClerkResult> {\n const { path, body } = clerkUserRequest(input);\n const res = await fetchImpl(`https://api.clerk.com${path}`, {\n method: \"POST\",\n headers: { authorization: `Bearer ${secretKey}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (res.ok) return { ok: true, status: res.status };\n const healed = heal(res.status);\n if (!healed.existed || !input.publicMetadata) return healed;\n const refreshed = await refreshUserMetadata(secretKey, input.email, input.publicMetadata, fetchImpl).catch(() => false);\n return { ...healed, refreshed };\n}\n","// The public member surface logic: the join config a site's join page reads (B1)\n// and the idempotent application submit (B2 validation + B3 exactly-once). Both\n// take the structural ChapterDb, so they're tested against an in-memory fake and\n// carry no runtime @odla-ai/db import. The worker builds the real db client, does\n// Clerk verification, enforces the body cap, and mounts these on chapter routes.\nimport type { Chapter, ChapterApplication, ChapterDb, ResolvedApplication } from \"./types\";\n\n// The reference join form. `focus` (a json field) is always accepted.\nconst DEFAULT_REQUIRED = [\"firstName\", \"lastName\", \"email\", \"referral\", \"whoYouAre\", \"message\"];\nconst DEFAULT_OPTIONAL = [\"referralName\", \"linkedin\", \"phone\", \"state\"];\n\n/** Apply defaults + validate the application config. Throws at import on bad shape. */\nexport function resolveApplication(a: ChapterApplication | undefined): ResolvedApplication {\n const required = a?.required ?? DEFAULT_REQUIRED;\n const optional = a?.optional ?? DEFAULT_OPTIONAL;\n for (const [name, arr] of [[\"required\", required], [\"optional\", optional]] as const) {\n if (!Array.isArray(arr) || !arr.every((f) => typeof f === \"string\" && f !== \"\")) {\n throw new Error(`defineChapter.application.${name}: must be an array of field-name strings`);\n }\n }\n if (a?.profileFields !== undefined && (!Array.isArray(a.profileFields) || !a.profileFields.every((f) => typeof f === \"string\" && f !== \"\"))) {\n throw new Error(\"defineChapter.application.profileFields: must be an array of field-name strings\");\n }\n if (a?.crmFields !== undefined && (!Array.isArray(a.crmFields) || !a.crmFields.every((f) => typeof f === \"string\" && f !== \"\"))) {\n throw new Error(\"defineChapter.application.crmFields: must be an array of field-name strings\");\n }\n return {\n required,\n optional,\n maxLen: a?.maxLen ?? {},\n defaultMaxLen: a?.defaultMaxLen ?? 2000,\n bodyCap: a?.bodyCap ?? 32768,\n requireDisclaimerAck: a?.requireDisclaimerAck ?? false,\n profileFields: a?.profileFields ?? null,\n crmFields: a?.crmFields ?? [],\n maxArrayLen: a?.maxArrayLen ?? 100,\n validateEmail: a?.validateEmail ?? true,\n };\n}\n\n// A permissive email shape check: one @, a dot-bearing domain, no whitespace.\n// Deliberately not RFC-exhaustive — the goal is to reject \"notanemail\" before it\n// fails the downstream Clerk create, not to adjudicate exotic-but-valid addresses.\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/** Whether a string looks like an email address (see {@link EMAIL_RE}). Exported\n * so a site building its own submit path applies the same rule chapter does. */\nexport function isValidEmail(value: unknown): boolean {\n return typeof value === \"string\" && EMAIL_RE.test(value);\n}\n\n/** Bound an array-valued field: drop non-primitive elements and cap the length,\n * so a client cannot post an unbounded array. Non-arrays pass through unchanged. */\nexport function clampArray(value: unknown, max: number): unknown {\n if (!Array.isArray(value)) return value;\n return value.filter((x) => typeof x === \"string\" || typeof x === \"number\" || typeof x === \"boolean\").slice(0, max);\n}\n\n/** Whether a submit body carries a genuine disclaimer acknowledgement. Accepts\n * the boolean an API client sends and the string a plain HTML form posts. */\nexport function hasDisclaimerAck(fields: Record<string, unknown>): boolean {\n return fields.disclaimerAck === true || fields.disclaimerAck === \"true\";\n}\n\n// Clerk carries these as first-class user fields, so repeating them in\n// public_metadata would be duplicated state that can drift.\nconst IDENTITY_FIELDS = new Set([\"email\", \"firstName\", \"lastName\"]);\n\n/**\n * The applicant profile written to the Clerk account's client-readable\n * `public_metadata.profile`. Projects each configured non-identity field, plus\n * `focus` (clamped) — but ONLY those in `application.profileFields` when that\n * allowlist is set, so a site keeps confidential fields (`message`, `referral`)\n * db-only. Derived from config, so a site's own field names project without this\n * package knowing them. Pure; returns `undefined` when there is nothing to write.\n */\nexport function applicantProfile(\n chapter: Chapter,\n fields: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const app = chapter.application;\n const allowed = (f: string): boolean => app.profileFields === null || app.profileFields.includes(f);\n const profile: Record<string, unknown> = {};\n for (const f of [...app.required, ...app.optional]) {\n if (IDENTITY_FIELDS.has(f) || !allowed(f)) continue;\n const v = fields[f];\n if (typeof v === \"string\" && v.trim() !== \"\") profile[f] = v.trim();\n }\n if (fields.focus !== undefined && allowed(\"focus\")) profile.focus = clampArray(fields.focus, app.maxArrayLen);\n return Object.keys(profile).length > 0 ? profile : undefined;\n}\n\n/** A validated submission, or a 400-worthy validation error the route returns.\n * `disclaimerAckAt` reports what THIS request recorded — a number when consent\n * was stamped, `null` when none was supplied. It is always present so a missing\n * consent record is visible in the response rather than silently absent from a\n * row nobody reads until an audit. */\nexport type SubmitResult =\n | { ok: true; id: string; duplicate: boolean; status: string; disclaimerAckAt: number | null }\n | { ok: false; error: string };\n\n/**\n * Submit a membership application (B2 + B3). Validates the configured required\n * fields + max lengths, writes the `applications` row at the pipeline's initial\n * status, and — when the client supplies a `submissionId` — stamps it as the\n * transaction's mutationId (`join:${submissionId}`) so a double-tap can never\n * create two applications (the second returns `duplicate: true`). Idempotency is\n * package-enforced. `now`/`newId` are injected (deterministic in tests).\n */\nexport async function submitApplication(\n db: ChapterDb,\n chapter: Chapter,\n fields: Record<string, unknown>,\n opts: { submissionId?: string; groupId?: string; now: number; newId: () => string },\n): Promise<SubmitResult> {\n const app = chapter.application;\n for (const f of app.required) {\n const v = fields[f];\n if (typeof v !== \"string\" || v.trim() === \"\") return { ok: false, error: `${f} is required` };\n }\n for (const f of [...app.required, ...app.optional]) {\n const v = fields[f];\n const cap = app.maxLen[f] ?? app.defaultMaxLen;\n if (typeof v === \"string\" && v.length > cap) return { ok: false, error: `${f} exceeds ${cap} characters` };\n }\n // A malformed email can only fail the downstream Clerk create; reject it here\n // as a clean 400. A valid application always has a valid email, so no genuine\n // submission is newly rejected.\n if (app.validateEmail && typeof fields.email === \"string\" && !isValidEmail(fields.email)) {\n return { ok: false, error: \"email must be a valid email address\" };\n }\n\n const acked = hasDisclaimerAck(fields);\n if (app.requireDisclaimerAck && !acked) {\n return { ok: false, error: \"disclaimerAck is required\" };\n }\n\n const id = opts.newId();\n const row: Record<string, unknown> = { id, status: chapter.pipeline.initial, createdAt: opts.now };\n for (const f of [...app.required, ...app.optional]) {\n if (typeof fields[f] === \"string\") row[f] = (fields[f] as string).trim();\n }\n if (fields.focus !== undefined) row.focus = clampArray(fields.focus, app.maxArrayLen);\n if (opts.groupId) row.groupId = opts.groupId;\n // The disclaimer acknowledgement is a compliance record, so it is stamped from\n // the server clock on a genuine ack and left absent otherwise — a client-supplied\n // timestamp would be forgeable, and a row that always carries one would record\n // consent nobody gave.\n if (acked) row.disclaimerAckAt = opts.now;\n\n const { duplicate } = await db.transact(\n [{ t: \"update\", ns: \"applications\", id, attrs: row }],\n opts.submissionId ? { mutationId: `join:${opts.submissionId}` } : undefined,\n );\n return { ok: true, id, duplicate, status: chapter.pipeline.initial, disclaimerAckAt: acked ? opts.now : null };\n}\n\n/** The `groups`-row fields the join config exposes. */\nexport interface JoinConfigGroup {\n id: string;\n name: string;\n standardPriceCents?: number;\n foundingDiscountCents?: number;\n disclaimerText?: string;\n refundPolicyText?: string;\n trustCopy?: string;\n commitmentText?: string;\n normsText?: string;\n}\n\n/**\n * The public join config (B1) a site's join page reads: copy + prices from the\n * group row plus `paymentsReady`. When payments aren't wired the join flow drops\n * the payment step (C2) — the worker computes `paymentsReady` from the group's\n * Stripe keys + vault secret. Pure.\n */\nexport function joinConfig(group: JoinConfigGroup, paymentsReady: boolean): Record<string, unknown> {\n return {\n id: group.id,\n name: group.name,\n standardPriceCents: group.standardPriceCents ?? 0,\n foundingDiscountCents: group.foundingDiscountCents ?? 0,\n disclaimerText: group.disclaimerText ?? \"\",\n refundPolicyText: group.refundPolicyText ?? \"\",\n trustCopy: group.trustCopy ?? \"\",\n commitmentText: group.commitmentText ?? \"\",\n normsText: group.normsText ?? \"\",\n paymentsReady,\n };\n}\n","// The leader → follower CRM projection (push model). The leader curates people,\n// businesses, and other configured CRM records and pushes a deliberately\n// allowlisted field set into THIS follower's crm_record.\n//\n// Invariants (package-enforced so no site re-derives them):\n// - One-way: the chapter never writes back to the hub through this path.\n// - Idempotent: every received record carries the leader's stable record id. A\n// provenance tag maps that id to the local CRM record, so a re-share updates\n// instead of duplicating even after an email/domain changes.\n// - Natural-key convergence: a person unifies by primary email and a business\n// by its configured domain slot (then name), so an arriving applicant and a\n// prior leader share compose into one person.\n// - Operational state stays local. Pipeline/account/billing state is not copied\n// into another site's authority; the push transfers the shared record fields.\n//\n// Reuses @odla-ai/crm's record ops (full validation via crm.prepare), driven by\n// the resolved chapter CRM engine + the structural ChapterDb.\nimport { createRecord, updateRecord } from \"@odla-ai/crm\";\nimport type { Crm, CrmRecord } from \"@odla-ai/crm\";\nimport type { ChapterDb, ResolvedNetworkTarget } from \"./types\";\n\n/** The contact data the hub shares for a prospect. `hubRecordId` is the stable\n * idempotency key (the hub's crm_record id). */\nexport interface SharedPerson {\n email: string;\n name?: string;\n firstName?: string;\n lastName?: string;\n phone?: string;\n linkedin?: string;\n hubRecordId: string;\n}\n\n/** Convenience wire shape for sharing the default `company` CRM type. */\nexport interface SharedBusiness {\n type: \"company\";\n name: string;\n domain?: string;\n industry?: string;\n location?: string;\n linkedin?: string;\n notes?: string;\n hubRecordId: string;\n}\n\n/** Versioned generic wire shape. `input` is validated against the follower's\n * own CRM type before any write, so a leader cannot smuggle undeclared fields. */\nexport interface SharedRecord {\n version: 1;\n type: string;\n hubRecordId: string;\n input: Record<string, unknown>;\n}\n\n/** Safe defaults when a target does not declare an explicit field allowlist. */\nexport const DEFAULT_SHARE_FIELDS: Readonly<Record<string, readonly string[]>> = {\n person: [\"name\", \"email\", \"firstName\", \"lastName\", \"phone\", \"linkedin\"],\n company: [\"name\", \"domain\", \"industry\", \"location\", \"linkedin\", \"notes\"],\n};\n\n/** Map a shared prospect to a crm `person` input (only the fields the default\n * person type accepts). Name falls back to first+last, then the email. */\nexport function sharedPersonInput(person: SharedPerson): Record<string, unknown> {\n const email = person.email.toLowerCase();\n const fullName = [person.firstName, person.lastName].filter(Boolean).join(\" \").trim();\n const input: Record<string, unknown> = { name: person.name ?? fullName ?? email, email };\n if (input.name === \"\") input.name = email;\n if (person.firstName) input.firstName = person.firstName;\n if (person.lastName) input.lastName = person.lastName;\n if (person.phone) input.phone = person.phone;\n if (person.linkedin) input.linkedin = person.linkedin;\n return input;\n}\n\n/** Deps for the projection — the resolved CRM engine, the structural db, and\n * injected clock/id (deterministic in tests). */\nexport interface ProjectionDeps {\n crm: Crm;\n db: ChapterDb;\n now: () => number;\n newId: () => string;\n}\n\nfunction shortHash(value: string): string {\n let a = 0x811c9dc5;\n let b = 0x9e3779b9;\n for (let i = 0; i < value.length; i += 1) {\n const n = value.charCodeAt(i);\n a = Math.imul(a ^ n, 0x01000193);\n b = Math.imul(b ^ n, 0x85ebca6b);\n }\n return `${(a >>> 0).toString(36)}${(b >>> 0).toString(36)}`;\n}\n\n/** CRM provenance tag used as the durable leader-id → local-record mapping. */\nexport function networkSourceTag(type: string, hubRecordId: string): string {\n const typeKey = type.toLowerCase();\n const readable = /^[a-z0-9_-]+$/.test(hubRecordId);\n const raw = `network:${typeKey}:${hubRecordId}`;\n if (readable && raw.length <= 64) return raw;\n return `network:${typeKey.slice(0, 20)}:${shortHash(`${type}\\u0000${hubRecordId}`)}`;\n}\n\n/** Normalize the backwards-compatible person/business shapes into the versioned\n * generic record envelope the receiver writes. */\nexport function normalizeSharedRecord(record: SharedPerson | SharedBusiness | SharedRecord): SharedRecord {\n if (\"input\" in record) return { version: 1, type: record.type, hubRecordId: record.hubRecordId, input: record.input };\n if (\"type\" in record && record.type === \"company\") {\n const input: Record<string, unknown> = { name: record.name };\n for (const key of [\"domain\", \"industry\", \"location\", \"linkedin\", \"notes\"] as const) {\n if (record[key]) input[key] = record[key];\n }\n return { version: 1, type: \"company\", hubRecordId: record.hubRecordId, input };\n }\n return { version: 1, type: \"person\", hubRecordId: record.hubRecordId, input: sharedPersonInput(record) };\n}\n\n/** Build the allowlisted payload sent from one leader CRM record to a target.\n * A target with an explicit `fields` map only accepts the types it lists. */\nexport function sharedRecordFromCrm(crm: Crm, record: CrmRecord, target: ResolvedNetworkTarget): SharedRecord {\n if (target.fields && !target.fields[record.type]) {\n throw new Error(`${target.name} does not accept \"${record.type}\" records`);\n }\n const def = crm.type(record.type);\n const fields = target.fields?.[record.type] ?? DEFAULT_SHARE_FIELDS[record.type];\n if (!fields) {\n throw new Error(`${target.name} requires an explicit field allowlist for \"${record.type}\" records`);\n }\n const nameField = def.nameField ?? \"name\";\n const input: Record<string, unknown> = {};\n for (const field of new Set([nameField, ...fields])) {\n const value = record.fields?.[field];\n if (value !== undefined) input[field] = value;\n }\n if (input[nameField] === undefined) input[nameField] = record.name;\n return { version: 1, type: record.type, hubRecordId: record.id, input };\n}\n\n// Resolve an existing crm_record person by lowercased primaryEmail and update it,\n// else create one under the given mutationId. The shared core of every one-way\n// person projection (hub share, arriving applicant).\nasync function upsertPerson(\n deps: ProjectionDeps,\n opts: { email: string; input: Record<string, unknown>; mutationId: string },\n): Promise<{ recordId: string }> {\n const email = opts.email.toLowerCase();\n const crmDeps = { crm: deps.crm, db: deps.db as never, now: deps.now, newId: deps.newId };\n const { crm_record } = await deps.db.query({ crm_record: { $: { where: { type: \"person\", primaryEmail: email }, limit: 1 } } });\n const existing = crm_record?.[0];\n if (existing && typeof existing.id === \"string\") {\n await updateRecord(crmDeps, { id: existing.id, input: opts.input });\n return { recordId: existing.id };\n }\n const created = await createRecord(crmDeps, { type: \"person\", input: opts.input, mutationId: opts.mutationId });\n return { recordId: created.id };\n}\n\nasync function findSharedRecord(\n deps: ProjectionDeps,\n record: SharedRecord,\n tag: string,\n): Promise<Record<string, unknown> | undefined> {\n const mapped = await deps.db.query({ crm_tag: { $: { where: { tag }, limit: 1 } } });\n const mappedId = mapped.crm_tag?.[0]?.recordId;\n if (typeof mappedId === \"string\") {\n const found = await deps.db.query({ crm_record: { $: { where: { id: mappedId }, limit: 1 } } });\n if (found.crm_record?.[0]) return found.crm_record[0];\n }\n const def = deps.crm.type(record.type);\n const emailField = def.emailField;\n if (emailField && typeof record.input[emailField] === \"string\") {\n const primaryEmail = record.input[emailField].toLowerCase();\n const found = await deps.db.query({\n crm_record: { $: { where: { type: record.type, primaryEmail }, limit: 1 } },\n });\n if (found.crm_record?.[0]) return found.crm_record[0];\n }\n const domain = record.input.domain;\n const domainSlot = def.fields.domain?.slot;\n if (typeof domain === \"string\" && domainSlot) {\n const found = await deps.db.query({\n crm_record: { $: { where: { type: record.type, [domainSlot]: domain }, limit: 1 } },\n });\n if (found.crm_record?.[0]) return found.crm_record[0];\n }\n const nameField = def.nameField ?? \"name\";\n const name = record.input[nameField];\n if (record.type === \"company\" && typeof name === \"string\" && name.trim()) {\n const found = await deps.db.query({\n crm_record: { $: { where: { type: record.type, name: name.trim() }, limit: 1 } },\n });\n if (found.crm_record?.[0]) return found.crm_record[0];\n }\n return undefined;\n}\n\n/**\n * Upsert a leader-shared CRM record into this follower. Accepts the original\n * person wire shape plus the versioned generic shape. Re-shares resolve through\n * a durable provenance tag; people/businesses also converge by natural key.\n */\nexport async function projectSharedRecord(\n deps: ProjectionDeps,\n shared: SharedPerson | SharedBusiness | SharedRecord,\n): Promise<{ recordId: string }> {\n const record = normalizeSharedRecord(shared);\n if (!record.type.trim() || !record.hubRecordId.trim()) {\n throw new Error(\"type and hubRecordId must be non-empty\");\n }\n const tag = networkSourceTag(record.type, record.hubRecordId);\n const crmDeps = { crm: deps.crm, db: deps.db as never, now: deps.now, newId: deps.newId };\n const existing = await findSharedRecord(deps, record, tag);\n let recordId: string;\n if (existing && typeof existing.id === \"string\") {\n // Do not use one permanent mutation id for updates: a later leader edit is a\n // new desired state and must not be mistaken for a retry of an older push.\n await updateRecord(crmDeps, { id: existing.id, input: record.input });\n recordId = existing.id;\n } else {\n // A deterministic id makes concurrent first deliveries converge even when\n // both requests observe no provenance row before either transaction lands.\n recordId = `network_${shortHash(`${record.type}\\u0000${record.hubRecordId}`)}`;\n await createRecord({ ...crmDeps, newId: () => recordId }, {\n type: record.type,\n input: record.input,\n mutationId: `share-create:${tag}`,\n });\n }\n await deps.db.transact(\n [{ t: \"update\", ns: \"crm_tag\", id: tag, attrs: { key: `${recordId}:${tag}`, recordId, tag, createdAt: deps.now() } }],\n { mutationId: `share-map:${tag}:${recordId}` },\n );\n return { recordId };\n}\n\n/** An arriving applicant, as far as the CRM projection cares. `extra` carries the\n * site-configured `crmFields` (values from the application), merged on top of the\n * built-in identity/contact set. */\nexport interface Applicant {\n applicationId: string;\n email: string;\n firstName?: string;\n lastName?: string;\n phone?: string;\n linkedin?: string;\n extra?: Record<string, unknown>;\n}\n\n/**\n * Project an arriving applicant into this chapter's `crm_record`, so a new\n * application shows up in the CRM immediately, unified by email with any prior\n * record. Idempotent per application (`apply:${applicationId}`). Best-effort at\n * the call site — a projection failure never fails the application.\n *\n * `extra` fields (a site's `crmFields`) are merged on top of the base person. If\n * an extra field is not on the crm person type, crm validation throws — so the\n * projection retries with the base person alone, ensuring a misconfigured\n * enrichment never silently drops the applicant from the CRM entirely.\n */\nexport async function projectApplicant(deps: ProjectionDeps, applicant: Applicant): Promise<{ recordId: string }> {\n const base = sharedPersonInput({\n email: applicant.email,\n firstName: applicant.firstName,\n lastName: applicant.lastName,\n phone: applicant.phone,\n linkedin: applicant.linkedin,\n hubRecordId: applicant.applicationId,\n });\n const mutationId = `apply:${applicant.applicationId}`;\n const extra = applicant.extra ?? {};\n if (Object.keys(extra).length === 0) return upsertPerson(deps, { email: applicant.email, input: base, mutationId });\n try {\n return await upsertPerson(deps, { email: applicant.email, input: { ...base, ...extra }, mutationId });\n } catch {\n return upsertPerson(deps, { email: applicant.email, input: base, mutationId });\n }\n}\n","// Scheduling core — config resolution + the booking invariants, ported from the\n// proven production worker. Everything here is PURE (no @odla-ai/calendar, no\n// db), so the correctness properties are unit-testable and package-enforced; the\n// worker route owns only the I/O (FreeBusy, computeBookableSlots, calendar\n// create/reschedule, the db writes) and calls these.\n//\n// Package-enforced invariants:\n// - the `meetings` row is canonical; applications.meetingAt and the calendar\n// event are projections written from it.\n// - one intro event per application, forever: a rebooking RESCHEDULES the\n// existing event (preserving its Meet link + invite thread), never creates a\n// second — see {@link bookingDecision} + {@link introIdempotencyKey}.\n// - status never moves backward on booking; you can only book from a pipeline\n// stage in `bookableFrom` — see `canBook` in ./pipeline + applicationBookingUpdate.\n// - endAt is always derived server-side, never client-supplied — see\n// {@link endForSlot}.\nimport type { ChapterScheduling } from \"./types\";\n\n/** A fully-resolved scheduling config (every field present). */\nexport interface ResolvedScheduling {\n slotMinutes: number;\n days: readonly number[];\n startHour: number;\n endHour: number;\n timezone: string;\n minNoticeHours: number;\n windowDays: number;\n summaryTemplate: string;\n}\n\n/** Proven defaults: 45-minute weekday slots, 9–5 Pacific, 24h notice,\n * a 14-day window. The summary is generic (a chapter's group seed supplies a\n * name-branded one). */\nexport const SCHEDULING_DEFAULTS: ResolvedScheduling = {\n slotMinutes: 45,\n days: [1, 2, 3, 4, 5],\n startHour: 9,\n endHour: 17,\n timezone: \"America/Los_Angeles\",\n minNoticeHours: 24,\n windowDays: 14,\n summaryTemplate: \"Introduction call with {{firstName}} {{lastName}}\",\n};\n\nfunction isValidTimeZone(tz: string): boolean {\n try {\n new Intl.DateTimeFormat(undefined, { timeZone: tz });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve a group's scheduling config against the defaults, validating every\n * bound at config-write time (throws on a bad config, so a\n * misconfiguration surfaces immediately rather than yielding empty slots).\n * `windowDays` is capped at 62 because Google FreeBusy is.\n */\nexport function resolveScheduling(config?: ChapterScheduling): ResolvedScheduling {\n const result = validateScheduling(config);\n if (result.ok) return result.value;\n const detail = Object.entries(result.errors)\n .map(([field, message]) => `${field}: ${message}`)\n .join(\" \");\n throw new Error(`scheduling: ${detail}`);\n}\n\n/** Validation messages keyed by form field. */\nexport type SchedulingErrors = Record<string, string>;\n\n/**\n * Validate a scheduling config field by field, collecting owner-readable messages\n * rather than throwing on the first problem. An admin settings form needs to say\n * *which* field is wrong and why — \"pick at least one day\" beats a stack trace —\n * so the admin route returns these directly. {@link resolveScheduling} is the\n * throwing wrapper for internal/config-time use.\n */\nexport function validateScheduling(\n config?: ChapterScheduling,\n): { ok: true; value: ResolvedScheduling } | { ok: false; errors: SchedulingErrors } {\n const d = config ?? {};\n const c: ResolvedScheduling = {\n slotMinutes: d.slotMinutes ?? SCHEDULING_DEFAULTS.slotMinutes,\n days: d.days ?? SCHEDULING_DEFAULTS.days,\n startHour: d.startHour ?? SCHEDULING_DEFAULTS.startHour,\n endHour: d.endHour ?? SCHEDULING_DEFAULTS.endHour,\n timezone: d.timezone ?? SCHEDULING_DEFAULTS.timezone,\n minNoticeHours: d.minNoticeHours ?? SCHEDULING_DEFAULTS.minNoticeHours,\n windowDays: d.windowDays ?? SCHEDULING_DEFAULTS.windowDays,\n summaryTemplate: d.summaryTemplate ?? SCHEDULING_DEFAULTS.summaryTemplate,\n };\n const errors: SchedulingErrors = {};\n if (!(c.slotMinutes >= 15 && c.slotMinutes <= 240)) {\n errors.slotMinutes = \"Slot length must be between 15 and 240 minutes.\";\n }\n if (!(c.windowDays >= 1 && c.windowDays <= 62)) {\n errors.windowDays = \"Booking window must be between 1 and 62 days (the calendar caps look-ahead at 62).\";\n }\n if (!(c.minNoticeHours >= 0 && c.minNoticeHours <= 336)) {\n errors.minNoticeHours = \"Minimum notice must be between 0 and 336 hours.\";\n }\n if (!(c.startHour >= 0 && c.startHour < c.endHour && c.endHour <= 24)) {\n errors.hours = \"Hours must satisfy 0 ≤ start < end ≤ 24.\";\n }\n const days = [...c.days];\n if (!days.length) errors.days = \"Pick at least one day.\";\n else if (!days.every((n) => Number.isInteger(n) && n >= 0 && n <= 6)) {\n errors.days = \"Days must be weekday numbers, 0 (Sunday) through 6 (Saturday).\";\n }\n if (typeof c.timezone !== \"string\" || !isValidTimeZone(c.timezone)) {\n errors.timezone = `\"${String(c.timezone)}\" is not a valid IANA timezone (for example \"America/Los_Angeles\").`;\n }\n if (typeof c.summaryTemplate !== \"string\") errors.summaryTemplate = \"Calendar summary template must be text.\";\n return Object.keys(errors).length > 0 ? { ok: false, errors } : { ok: true, value: { ...c, days } };\n}\n\n/** Statuses a member may book/reschedule from (early pipeline only). */\n// Booking eligibility is answered by the configured pipeline — canBook(status,\n// pipeline) in ./pipeline — not a hardcoded status list, so a chapter that\n// customizes its stages gets one consistent answer.\n\n/** The availability window: `[now, now + windowDays]` in epoch ms. */\nexport function slotWindow(now: number, windowDays: number): { from: number; to: number } {\n return { from: now, to: now + windowDays * 86_400_000 };\n}\n\n/** The slot's end instant, always derived from its start (never client-supplied). */\nexport function endForSlot(startAt: number, slotMinutes: number): number {\n return startAt + slotMinutes * 60_000;\n}\n\n/** Double-book pre-check: the requested start must land exactly on a currently\n * bookable slot boundary. */\nexport function isSlotAvailable(slots: readonly { startAt: number }[], startAt: number): boolean {\n return slots.some((s) => s.startAt === startAt);\n}\n\n/** Render a meeting summary from its template (`{{firstName}}`/`{{lastName}}`). */\nexport function renderSummary(template: string, app: { firstName?: string | null; lastName?: string | null }): string {\n return template.replace(\"{{firstName}}\", app.firstName ?? \"\").replace(\"{{lastName}}\", app.lastName ?? \"\");\n}\n\n/** The prior scheduled meeting for an application, as far as booking cares. */\nexport interface ExistingMeeting {\n id: string;\n googleEventId?: string | null;\n meetUrl?: string | null;\n htmlLink?: string | null;\n}\n\n/** Decide reschedule-vs-create: reschedule iff there's an existing event to move,\n * so the Meet link + invite thread survive and no second event is minted. */\nexport function bookingDecision(existing: ExistingMeeting | null | undefined): { reschedule: boolean; eventId: string | null } {\n const eventId = existing?.googleEventId ?? null;\n return { reschedule: Boolean(eventId), eventId };\n}\n\n/** The create idempotency key — one intro event per application, forever, so a\n * retried create returns the same booking rather than a duplicate. */\nexport function introIdempotencyKey(applicationId: string): string {\n return `application:${applicationId}:intro`;\n}\n\n/** The canonical `meetings` row for a first booking. A `type` (not `interface`)\n * so it stays assignable to a db op's `attrs` (Record<string, unknown>). */\nexport type NewMeetingRow = {\n id: string;\n applicationId: string;\n groupId: string;\n startAt: number;\n endAt: number;\n timezone: string;\n status: \"scheduled\";\n googleEventId: string;\n meetUrl?: string;\n htmlLink?: string;\n drift: \"none\";\n createdAt: number;\n};\n\n/** Build the new `meetings` row after the calendar created the event. Optional\n * scalars are omitted (never null), per the odla-db porting rule. */\nexport function meetingCreateRow(i: {\n meetingId: string;\n applicationId: string;\n groupId: string;\n startAt: number;\n endAt: number;\n timezone: string;\n googleEventId: string;\n meetUrl?: string | null;\n htmlLink?: string | null;\n createdAt: number;\n}): NewMeetingRow {\n return {\n id: i.meetingId,\n applicationId: i.applicationId,\n groupId: i.groupId,\n startAt: i.startAt,\n endAt: i.endAt,\n timezone: i.timezone,\n status: \"scheduled\",\n googleEventId: i.googleEventId,\n ...(i.meetUrl ? { meetUrl: i.meetUrl } : {}),\n ...(i.htmlLink ? { htmlLink: i.htmlLink } : {}),\n drift: \"none\",\n createdAt: i.createdAt,\n };\n}\n\n/** The `meetings`-row patch for a reschedule (same row id, moved in place). */\nexport type MeetingReschedulePatch = {\n startAt: number;\n endAt: number;\n drift: \"none\";\n};\n\n/** Patch to move an existing meeting to a new window. */\nexport function meetingRescheduleUpdate(startAt: number, endAt: number): MeetingReschedulePatch {\n return { startAt, endAt, drift: \"none\" };\n}\n\n/** The `applications`-row patch after a booking. */\nexport type ApplicationBookingPatch = {\n meetingAt: number;\n meetingLink?: string;\n status?: \"call_scheduled\";\n};\n\n/** Project the booking onto the application row: cache the time, adopt the\n * calendar link if any, and advance the status to `call_scheduled` unless it is\n * already there (never backward). */\nexport function applicationBookingUpdate(\n currentStatus: string,\n startAt: number,\n htmlLink?: string | null,\n): ApplicationBookingPatch {\n return {\n meetingAt: startAt,\n ...(htmlLink ? { meetingLink: htmlLink } : {}),\n ...(currentStatus !== \"call_scheduled\" ? { status: \"call_scheduled\" as const } : {}),\n };\n}\n","// The member session — what GET /api/me returns to a signed-in applicant/member.\n// Ported from the reference application's summary + /api/me reconciliation. The\n// SHAPING is pure and package-enforced so no site re-derives it; the worker owns\n// only the I/O around it (locating the application by email, reconciling the\n// meeting against the calendar) and hands the resolved rows here.\n//\n// Two invariants live here, not in a site:\n// - `paid` is DERIVED, never a stored flag: a subscription exists and the\n// application wasn't refunded. Sites can't drift a stale boolean out of sync\n// with Stripe.\n// - the live meeting row wins: its startAt/meetUrl/timezone override whatever\n// the application row cached, and a non-scheduled meeting (a cancellation\n// adopted from the calendar) forces meetingAt back to null.\n\n/** An application row, as far as the session cares about it. */\nexport interface ApplicationRecord {\n id: string;\n firstName?: string | null;\n lastName?: string | null;\n email?: string | null;\n status: string;\n meetingAt?: number | null;\n meetingLink?: string | null;\n createdAt?: number | null;\n stripeSubscriptionId?: string | null;\n renewalAt?: number | null;\n canceled?: boolean;\n}\n\n/** The reconciled meeting row (already adopted against the calendar), or null. */\nexport interface MeetingRecord {\n status: string;\n startAt?: number | null;\n meetUrl?: string | null;\n timezone?: string | null;\n}\n\n/** The stable, non-meeting fields of an application (safe to expose to its own\n * owner). */\nexport interface ApplicationSummary {\n id: string;\n firstName: string | null;\n lastName: string | null;\n email: string | null;\n status: string;\n createdAt: number | null;\n meetingLink: string | null;\n paid: boolean;\n renewalAt: number | null;\n canceled: boolean;\n}\n\n/** A summary plus the reconciled meeting fields — the `application` the member\n * area renders. */\nexport interface MemberApplication extends ApplicationSummary {\n meetingAt: number | null;\n meetUrl: string | null;\n timezone: string;\n}\n\n/** The full GET /api/me payload for a signed-in user. */\nexport interface MemberSession {\n userId: string;\n email: string | null;\n role: string;\n superAdmin: boolean;\n application: MemberApplication | null;\n}\n\n/** Derive the summary fields from an application row. `paid` is computed, not\n * read, so it can never contradict Stripe. */\nexport function applicationSummary(app: ApplicationRecord): ApplicationSummary {\n return {\n id: app.id,\n firstName: app.firstName ?? null,\n lastName: app.lastName ?? null,\n email: app.email ?? null,\n status: app.status,\n createdAt: app.createdAt ?? null,\n meetingLink: app.meetingLink ?? null,\n paid: Boolean(app.stripeSubscriptionId) && app.status !== \"refunded\",\n renewalAt: app.renewalAt ?? null,\n canceled: app.canceled === true,\n };\n}\n\n/** Fold a (possibly absent, already-reconciled) meeting into the application the\n * member area renders. The live meeting overrides the application's cached\n * meeting fields; a non-`scheduled` meeting clears the booking. */\nexport function memberApplication(\n app: ApplicationRecord,\n meeting: MeetingRecord | null | undefined,\n defaultTimezone: string,\n): MemberApplication {\n const summary = applicationSummary(app);\n let meetingAt = app.meetingAt ?? null;\n let meetUrl: string | null = null;\n let timezone = defaultTimezone;\n if (meeting) {\n timezone = meeting.timezone ?? timezone;\n if (meeting.status === \"scheduled\") {\n meetingAt = meeting.startAt ?? null;\n meetUrl = meeting.meetUrl ?? null;\n } else {\n meetingAt = null;\n }\n }\n return { ...summary, meetingAt, meetUrl, timezone };\n}\n\n/** Identity of the signed-in user, from the verified session. */\nexport interface SessionUser {\n userId: string;\n email?: string | null;\n role: string;\n}\n\n/** Assemble the GET /api/me payload. `application` is null when the user has no\n * application on file (an admin who never applied, or a brand-new account). */\nexport function memberSession(\n user: SessionUser,\n opts: { application: MemberApplication | null; superAdmin: boolean },\n): MemberSession {\n return {\n userId: user.userId,\n email: user.email ?? null,\n role: user.role,\n superAdmin: opts.superAdmin,\n application: opts.application,\n };\n}\n","// The chapter email pipeline: exactly-once delivery, a non-production fail-safe,\n// and template rendering. Every property here is easy to get wrong and expensive\n// to get wrong, so the correctness-critical decisions — the dedupe check (E1),\n// the dev-redirect / log-only fail-safe (E2), and template rendering (E4) — are\n// PURE and fully tested in this module. The worker supplies the transport +\n// odla-db and performs the actual send + emailLog write around these decisions.\n//\n// Chapter's operational templates ({ subject, text, enabled? }) are\n// transactional lifecycle mail by construction — a site owner edits the copy in\n// Settings but cannot reclassify one as marketing. Consent-gated marketing blasts\n// go through @odla-ai/crm, which owns the transactional-vs-marketing template\n// class as code (E3), so relabeling copy can never bypass the consent gate.\n\n/** One owner-editable template row on the group. `enabled` absent = enabled. */\nexport interface EmailTemplateRow {\n subject: string;\n text: string;\n enabled?: boolean;\n}\n\n/** The `groups`-row fields the email pipeline reads. */\nexport interface EmailGroup {\n id: string;\n name: string;\n replyTo: string;\n /** Non-prod debug inbox: all mail redirects here outside prod (E2). */\n debugEmail?: string;\n refundPolicyText?: string;\n commitmentText?: string;\n normsText?: string;\n emailTemplates: Record<string, EmailTemplateRow>;\n}\n\n/** `{{placeholder}}` substitution; unknown placeholders render empty. */\nexport function render(template: string, vars: Record<string, string>): string {\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (_, key: string) => vars[key] ?? \"\");\n}\n\n/** Group-level vars every template receives, under the caller's vars. */\nfunction groupVars(group: EmailGroup, vars: Record<string, string>): Record<string, string> {\n return {\n ...vars,\n refundPolicyText: group.refundPolicyText ?? \"\",\n commitmentText: group.commitmentText ?? \"\",\n normsText: group.normsText ?? \"\",\n };\n}\n\n/**\n * Re-render a template's body for history/preview (E4): the CRM comms history\n * reads back emails whose body predates `emailLog.body` by rendering the current\n * template with the recipient's vars. Same substitution + group vars as the send\n * path. `null` for an unknown template. Reflects the copy as it reads today, not\n * necessarily the exact bytes originally sent (only `emailLog.body` is byte-exact).\n */\nexport function renderTemplateBody(group: EmailGroup, template: string, vars: Record<string, string>): string | null {\n const tpl = group.emailTemplates?.[template];\n if (!tpl) return null;\n return render(tpl.text, groupVars(group, vars));\n}\n\n/**\n * E1 (exactly-once): given the prior `emailLog` rows for a `dedupeKey`, has the\n * mail already been delivered? A prior row with **no error** means yes — the\n * caller short-circuits the resend. Failure rows (which carry an `error` and are\n * written without the dedupe mutationId) do not count, so a retry after a failure\n * can still succeed.\n */\nexport function isAlreadySent(priorRows: ReadonlyArray<{ error?: unknown }>): boolean {\n return priorRows.some((row) => !row.error);\n}\n\n/** The pure delivery decision produced by {@link planDelivery}. */\nexport type DeliveryDecision =\n | { deliver: false; reason: \"template-missing\" | \"disabled\" }\n | {\n deliver: true;\n /** Which transport to use — `log-only` records the send but delivers nothing. */\n transport: \"cloudflare\" | \"log-only\";\n to: string;\n subject: string;\n text: string;\n /** True when redirected to the non-prod debug inbox. */\n redirected: boolean;\n };\n\n/**\n * The pure delivery decision (E2 fail-safe + E3 enabled). Given the env, group,\n * template, recipient, and whether a real Cloudflare transport is wired:\n * - missing template → not delivered (`template-missing`);\n * - disabled template and not forced → not delivered (`disabled`);\n * - **non-prod with a debug inbox** → REDIRECT to it, `\"[dev] \"` subject prefix,\n * a dev-redirect note in the body, so test applicants never receive real mail;\n * - **non-prod with NO debug inbox** → force `log-only` (deliver nothing) — the\n * fail-safe that protects every site's test data;\n * - prod → deliver via the real transport (`cloudflare` if wired, else `log-only`).\n */\nexport function planDelivery(input: {\n envName: string;\n group: EmailGroup;\n template: string;\n to: string;\n vars: Record<string, string>;\n /** Whether a Cloudflare Email Service transport (binding + verified from) is wired. */\n cloudflareReady: boolean;\n /** The admin test route may send a disabled template. */\n force?: boolean;\n}): DeliveryDecision {\n const tpl = input.group.emailTemplates?.[input.template];\n if (!tpl) return { deliver: false, reason: \"template-missing\" };\n if (tpl.enabled === false && !input.force) return { deliver: false, reason: \"disabled\" };\n\n const vars = groupVars(input.group, input.vars);\n const isProd = input.envName === \"prod\";\n const redirect = !isProd && !!input.group.debugEmail;\n const transport: \"cloudflare\" | \"log-only\" =\n !isProd && !redirect ? \"log-only\" : input.cloudflareReady ? \"cloudflare\" : \"log-only\";\n const to = redirect ? (input.group.debugEmail as string) : input.to;\n const subject = (redirect ? \"[dev] \" : \"\") + render(tpl.subject, vars);\n const text = redirect\n ? `(dev redirect; original recipient: ${input.to})\\n\\n` + render(tpl.text, vars)\n : render(tpl.text, vars);\n return { deliver: true, transport, to, subject, text, redirected: redirect };\n}\n","// sendTemplated — the operational-email orchestration that wires the pure email\n// decisions (./email: isAlreadySent E1, planDelivery E2/E3) to odla-db + a\n// transport. Structural (takes a ChapterDb + a sender), so it's FakeDb-testable\n// like submitApplication/projectSharedRecord. The worker's lifecycle routes call\n// it to send the prep / payment-confirmation / admin-alert mail.\n//\n// Exactly-once is enforced twice: a prior successful emailLog row short-circuits\n// the resend (query + isAlreadySent), AND the success row is written under the\n// `email:${dedupeKey}` mutationId so a racing double-send dedupes at the db layer.\n// Failure rows omit the mutationId, so a retry after a transient failure can send.\nimport { isAlreadySent, planDelivery } from \"./email\";\nimport type { EmailGroup } from \"./email\";\nimport type { ChapterDb } from \"./types\";\n\n/** The canonical lifecycle email templates chapter fires, in send-order. Owner-\n * editable copy lives on the group row; this is the fixed set the admin email\n * editor + test route iterate. */\nexport const EMAIL_TEMPLATE_NAMES = [\"adminNotification\", \"paymentConfirmation\", \"prepEmail\", \"onboardingInvite\"] as const;\n\n/** One of {@link EMAIL_TEMPLATE_NAMES}. */\nexport type EmailTemplateName = (typeof EMAIL_TEMPLATE_NAMES)[number];\n\n/** The mail transport (the worker's Cloudflare SEND_EMAIL binding). */\nexport interface MailSender {\n send(payload: { from: string; to: string[]; subject: string; text?: string; replyTo?: string }): Promise<{ messageId: string }>;\n}\n\n/** Deps for {@link sendTemplated} — the db, the env name (drives the fail-safe),\n * the transport + from (absent ⇒ log-only), and injected clock/id. */\nexport interface NotifyDeps {\n db: ChapterDb;\n envName: string;\n sender?: MailSender;\n from?: string;\n now: () => number;\n newId: () => string;\n}\n\n/** One templated send. `dedupeKey` is the exactly-once key. */\nexport interface NotifyInput {\n group: EmailGroup;\n template: string;\n to: string;\n vars: Record<string, string>;\n dedupeKey: string;\n applicationId?: string;\n /** The admin test route may send a disabled template. */\n force?: boolean;\n}\n\n/** The outcome. `sent:true` includes the already-sent short-circuit. */\nexport interface NotifyResult {\n sent: boolean;\n reason?: string;\n}\n\n/**\n * Send a templated lifecycle email exactly once. Short-circuits on a prior\n * successful send; otherwise plans delivery (dev fail-safe applies), sends via the\n * transport when one is wired and the plan calls for it, and records an emailLog\n * row either way (success keyed for exactly-once, failure unkeyed for retry).\n */\nexport async function sendTemplated(deps: NotifyDeps, input: NotifyInput): Promise<NotifyResult> {\n const { emailLog } = await deps.db.query({ emailLog: { $: { where: { dedupeKey: input.dedupeKey } } } });\n const prior = (Array.isArray(emailLog) ? emailLog : []) as Array<{ error?: unknown }>;\n if (isAlreadySent(prior)) return { sent: true, reason: \"already-sent\" };\n\n const cloudflareReady = Boolean(deps.sender && deps.from);\n const decision = planDelivery({\n envName: deps.envName,\n group: input.group,\n template: input.template,\n to: input.to,\n vars: input.vars,\n cloudflareReady,\n force: input.force,\n });\n if (!decision.deliver) return { sent: false, reason: decision.reason };\n\n let error: string | undefined;\n let messageId: string | undefined;\n if (decision.transport === \"cloudflare\" && deps.sender && deps.from) {\n try {\n const res = await deps.sender.send({\n from: deps.from,\n to: [decision.to],\n subject: decision.subject,\n text: decision.text,\n replyTo: input.group.replyTo,\n });\n messageId = res.messageId;\n } catch (e) {\n error = e instanceof Error ? e.message : String(e);\n }\n }\n\n const id = deps.newId();\n const row: Record<string, unknown> = {\n id,\n groupId: input.group.id,\n to: decision.to,\n template: input.template,\n subject: decision.subject,\n body: decision.text,\n transport: decision.transport,\n redirected: decision.redirected,\n dedupeKey: input.dedupeKey,\n sentAt: deps.now(),\n ...(input.applicationId ? { applicationId: input.applicationId } : {}),\n ...(messageId ? { messageId } : {}),\n ...(error ? { error } : {}),\n };\n await deps.db.transact([{ t: \"update\", ns: \"emailLog\", id, attrs: row }], error ? undefined : { mutationId: `email:${input.dedupeKey}` });\n return error ? { sent: false, reason: error } : { sent: true };\n}\n\n/** Project a `groups` row into the {@link EmailGroup} the email pipeline reads. */\nexport function emailGroupFrom(row: Record<string, unknown>): EmailGroup {\n const str = (v: unknown): string | undefined => (typeof v === \"string\" ? v : undefined);\n const templates = row.emailTemplates && typeof row.emailTemplates === \"object\" ? row.emailTemplates : {};\n return {\n id: String(row.id),\n name: String(row.name ?? \"\"),\n replyTo: str(row.replyTo) ?? \"\",\n debugEmail: str(row.debugEmail),\n refundPolicyText: str(row.refundPolicyText),\n commitmentText: str(row.commitmentText),\n normsText: str(row.normsText),\n emailTemplates: templates as EmailGroup[\"emailTemplates\"],\n };\n}\n","// Scheduling routes: GET /api/schedule/slots + POST /api/schedule/book. This\n// file owns the I/O — Google FreeBusy, the pure computeBookableSlots, the\n// calendar create/reschedule, and the db writes — and delegates every\n// correctness rule to ./scheduling. Calendar is RUNTIME-optional: a chapter with\n// no connected calendar has freeBusy throw, so /slots answers\n// { schedulingReady: false } (200) and the join flow degrades to \"we'll reach\n// out by email\" rather than erroring.\nimport { computeBookableSlots, initCalendar } from \"@odla-ai/calendar\";\nimport { emailGroupFrom, sendTemplated } from \"./notify\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, WorkerContext } from \"./worker-context\";\nimport type { Route } from \"./worker-routes\";\nimport type { ChapterDb, ChapterScheduling, DbOp } from \"./types\";\nimport { canBook } from \"./pipeline\";\nimport {\n applicationBookingUpdate,\n bookingDecision,\n endForSlot,\n introIdempotencyKey,\n isSlotAvailable,\n meetingCreateRow,\n meetingRescheduleUpdate,\n renderSummary,\n resolveScheduling,\n slotWindow,\n} from \"./scheduling\";\nimport type { ExistingMeeting, ResolvedScheduling } from \"./scheduling\";\n\ntype Cal = ReturnType<typeof initCalendar>;\ntype Row = Record<string, unknown>;\n\n/** The stable `.code` off an OdlaError/provider error, else a safe default. */\nfunction errCode(err: unknown): string {\n if (err && typeof err === \"object\") {\n const code = (err as { code?: unknown }).code;\n if (typeof code === \"string\") return code;\n }\n return \"calendar_unavailable\";\n}\n\nfunction makeCalendar(env: ChapterEnv): Cal {\n // Calendar uses ODLA_APP_ID + ODLA_PLATFORM — distinct from the db client's\n // ODLA_TENANT + ODLA_ENDPOINT.\n return initCalendar({ appId: env.ODLA_APP_ID, env: env.ODLA_ENV, adminToken: env.ODLA_API_KEY, endpoint: env.ODLA_PLATFORM });\n}\n\nasync function firstRow(db: ChapterDb, ns: string, q: Record<string, unknown>): Promise<Row | undefined> {\n const res = await db.query({ [ns]: { $: q } });\n const rows = res[ns];\n return Array.isArray(rows) ? rows[0] : undefined;\n}\n\nasync function computeSlots(cal: Cal, cfg: ResolvedScheduling): Promise<Array<{ startAt: number; endAt: number }>> {\n const { from, to } = slotWindow(Date.now(), cfg.windowDays);\n const fb = await cal.availability.freeBusy({ timeMin: from, timeMax: to });\n return computeBookableSlots(fb.busy, {\n from: fb.timeMin,\n to: fb.timeMax,\n timezone: cfg.timezone,\n slotMinutes: cfg.slotMinutes,\n businessHours: { days: [...cfg.days], startHour: cfg.startHour, endHour: cfg.endHour },\n minNoticeMs: cfg.minNoticeHours * 3_600_000,\n });\n}\n\nasync function bookSlot(req: Request, env: ChapterEnv, ctx: WorkerContext): Promise<Response> {\n let body: Row;\n try {\n body = JSON.parse(await req.text()) as Row;\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n const applicationId = typeof body.applicationId === \"string\" ? body.applicationId : \"\";\n const startAt = Number(body.startAt);\n if (!applicationId || !Number.isFinite(startAt)) return json({ error: \"applicationId and startAt required\" }, 400);\n\n const db = ctx.makeDb(env) as unknown as ChapterDb;\n const app = await firstRow(db, \"applications\", { where: { id: applicationId }, limit: 1 });\n if (!app) return json({ error: \"not found\" }, 404);\n const status = String(app.status ?? \"\");\n if (!canBook(status, ctx.chapter.pipeline)) return json({ error: `cannot book from status \"${status}\"` }, 409);\n\n const group = await firstRow(db, \"groups\", { where: { id: String(app.groupId ?? ctx.chapter.id) }, limit: 1 });\n if (!group) return json({ error: \"group not found\" }, 500);\n const cfg = resolveScheduling(group.schedulingJson as ChapterScheduling | undefined);\n const endAt = endForSlot(startAt, cfg.slotMinutes);\n const cal = makeCalendar(env);\n\n // Double-book guard, layer 1: the requested start must still be a live slot.\n let slots: Array<{ startAt: number }>;\n try {\n slots = await computeSlots(cal, cfg);\n } catch (err) {\n return json({ error: \"scheduling unavailable\", code: errCode(err) }, 503);\n }\n if (!isSlotAvailable(slots, startAt)) return json({ error: \"slot no longer available\", code: \"calendar_slot_unavailable\" }, 409);\n\n const summary = renderSummary(cfg.summaryTemplate, { firstName: app.firstName as string, lastName: app.lastName as string });\n const existing = (await firstRow(db, \"meetings\", {\n where: { applicationId, status: \"scheduled\" },\n order: { createdAt: \"desc\" },\n limit: 1,\n })) as ExistingMeeting | undefined;\n const decision = bookingDecision(existing);\n\n let meetUrl: string | null = null;\n let htmlLink: string | null = null;\n let meetingOp: DbOp;\n try {\n if (decision.reschedule && decision.eventId) {\n // Reschedule the SAME event — the Meet link + invite thread survive.\n await cal.actions.reschedule(decision.eventId, { startAt, endAt });\n meetUrl = (existing?.meetUrl as string | undefined) ?? null;\n htmlLink = (existing?.htmlLink as string | undefined) ?? null;\n meetingOp = { t: \"update\", ns: \"meetings\", id: String(existing?.id), attrs: meetingRescheduleUpdate(startAt, endAt) };\n } else {\n const { booking } = await cal.actions.create(\n { summary, startAt, endAt, attendees: [String(app.email)], timezone: cfg.timezone, meet: true },\n { idempotencyKey: introIdempotencyKey(applicationId) },\n );\n meetUrl = booking.meetUrl ?? null;\n htmlLink = booking.htmlLink ?? null;\n const meetingId = crypto.randomUUID();\n meetingOp = {\n t: \"update\",\n ns: \"meetings\",\n id: meetingId,\n attrs: meetingCreateRow({\n meetingId,\n applicationId,\n groupId: String(group.id),\n startAt,\n endAt,\n timezone: cfg.timezone,\n googleEventId: booking.eventId,\n meetUrl: booking.meetUrl,\n htmlLink: booking.htmlLink,\n createdAt: Date.now(),\n }),\n };\n }\n } catch (err) {\n const code = errCode(err);\n // Double-book guard, layer 2 (authoritative): the provider rejected under lease.\n if (code === \"calendar_slot_unavailable\") return json({ error: \"slot no longer available\", code }, 409);\n return json({ error: \"booking failed\", code }, 502);\n }\n\n // meetings row is canonical; the application row is the projection.\n const appOp: DbOp = { t: \"update\", ns: \"applications\", id: applicationId, attrs: applicationBookingUpdate(status, startAt, htmlLink) };\n await db.transact([meetingOp, appOp]);\n\n // Prep email — best-effort, exactly-once per application (never fails the booking).\n if (typeof app.email === \"string\" && app.email) {\n await sendTemplated(\n { db, envName: env.ODLA_ENV, sender: env.SEND_EMAIL, from: env.EMAIL_FROM, now: () => Date.now(), newId: () => crypto.randomUUID() },\n { group: emailGroupFrom(group), template: \"prepEmail\", to: app.email, vars: { firstName: String(app.firstName ?? \"\") }, dedupeKey: `prep:${applicationId}`, applicationId },\n ).catch(() => undefined);\n }\n\n return json({ ok: true, startAt, endAt, meetUrl, rescheduled: decision.reschedule });\n}\n\n/** GET /api/schedule/slots + POST /api/schedule/book (chapter mode only). */\nexport const handleSchedule: Route = async (req, url, env, ctx) => {\n if (ctx.chapter.mode !== \"chapter\") return null;\n\n if (req.method === \"GET\" && url.pathname === \"/api/schedule/slots\") {\n const db = ctx.makeDb(env) as unknown as ChapterDb;\n const group = await firstRow(db, \"groups\", { where: { id: url.searchParams.get(\"group\") ?? ctx.chapter.id }, limit: 1 });\n if (!group) return json({ error: \"not found\" }, 404);\n const cfg = resolveScheduling(group.schedulingJson as ChapterScheduling | undefined);\n try {\n const slots = await computeSlots(makeCalendar(env), cfg);\n return json({ schedulingReady: true, timezone: cfg.timezone, slotMinutes: cfg.slotMinutes, slots });\n } catch (err) {\n return json({ schedulingReady: false, code: errCode(err) });\n }\n }\n\n if (req.method === \"POST\" && url.pathname === \"/api/schedule/book\") {\n return bookSlot(req, env, ctx);\n }\n\n return null;\n};\n","// The application status pipeline — config, not code. Which statuses exist, which\n// a member can book an intro call from, and which an admin can approve from\n// differ per site; the one invariant every site wants is that status never moves\n// backwards. All of this is pure + tested here; the worker enforces it on every\n// status write, and the CRM record.stage mirrors application.status (never the\n// reverse). Defaults reproduce the proven membership pipeline exactly.\nimport type { ChapterPipeline, ResolvedPipeline } from \"./types\";\n\nconst DEFAULT_STAGES = [\n \"submitted\",\n \"paid_pending_vetting\",\n \"call_scheduled\",\n \"interviewed\",\n \"approved\",\n \"declined\",\n \"refunded\",\n] as const;\nconst DEFAULT_BOOKABLE = [\"submitted\", \"paid_pending_vetting\", \"call_scheduled\"] as const;\nconst DEFAULT_APPROVABLE = [\"paid_pending_vetting\", \"call_scheduled\", \"interviewed\"] as const;\n\n/**\n * Apply defaults + validate the pipeline config. With no config, the complete\n * reference pipeline. With `stages` given but the subsets omitted, the subsets\n * default to empty (a site opts in to bookable/approvable states explicitly).\n * Throws at import on a bad pipeline (empty/duplicate stages, an initial or a\n * subset entry not on the ladder).\n */\nexport function resolvePipeline(p: ChapterPipeline | undefined): ResolvedPipeline {\n const usingDefaults = !p?.stages;\n const stages = p?.stages ?? [...DEFAULT_STAGES];\n if (!Array.isArray(stages) || stages.length === 0 || !stages.every((s) => typeof s === \"string\" && s !== \"\")) {\n throw new Error(\"defineChapter.pipeline.stages: must be a non-empty array of status strings\");\n }\n if (new Set(stages).size !== stages.length) {\n throw new Error(\"defineChapter.pipeline.stages: statuses must be unique\");\n }\n const initial = p?.initial ?? (stages[0] as string);\n if (!stages.includes(initial)) {\n throw new Error(`defineChapter.pipeline.initial: \"${initial}\" is not one of the stages`);\n }\n const bookableFrom = p?.bookableFrom ?? (usingDefaults ? [...DEFAULT_BOOKABLE] : []);\n const approvableFrom = p?.approvableFrom ?? (usingDefaults ? [...DEFAULT_APPROVABLE] : []);\n for (const [name, subset] of [\n [\"bookableFrom\", bookableFrom],\n [\"approvableFrom\", approvableFrom],\n ] as const) {\n for (const s of subset) {\n if (!stages.includes(s)) throw new Error(`defineChapter.pipeline.${name}: \"${s}\" is not one of the stages`);\n }\n }\n return { stages, bookableFrom, approvableFrom, initial };\n}\n\n/** The ordinal of a status in the ladder, or -1 if unknown. */\nexport function stageIndex(status: string, p: ResolvedPipeline): number {\n return p.stages.indexOf(status);\n}\n\n/**\n * The status-never-moves-backwards invariant: a transition is allowed only when\n * both statuses are on the ladder and `to` is at or ahead of `from`. The worker\n * calls this before every status write; a violation is a 409, never a silent\n * downgrade.\n */\nexport function canTransition(from: string, to: string, p: ResolvedPipeline): boolean {\n const fi = p.stages.indexOf(from);\n const ti = p.stages.indexOf(to);\n return fi >= 0 && ti >= 0 && ti >= fi;\n}\n\n/** May an intro call be booked from this status? */\nexport function canBook(status: string, p: ResolvedPipeline): boolean {\n return p.bookableFrom.includes(status);\n}\n\n/** May an application be approved (→ member) from this status? */\nexport function canApprove(status: string, p: ResolvedPipeline): boolean {\n return p.approvableFrom.includes(status);\n}\n","// Payments primitives. The webhook-integrity check below is security-critical and\n// easy to get wrong, so it is pure and tested here; the worker wires a payments\n// provider (Stripe first — subscription create, webhook ingest, refund) around\n// it, and every resulting db write carries an event-derived mutationId for\n// exactly-once. Sites that don't charge omit payments entirely (paymentsReady:\n// false), so nothing here is imported unless a chapter runs the payment flow.\n\n/** Parse a Stripe-style `Stripe-Signature` header (`t=<unix>,v1=<hex>`). */\nfunction parseSigHeader(header: string): { t?: string; v1?: string } {\n const parts: Record<string, string> = {};\n for (const p of header.split(\",\")) {\n const [k, v] = p.split(\"=\", 2);\n if (k && v !== undefined) parts[k] = v;\n }\n return { t: parts.t, v1: parts.v1 };\n}\n\nfunction toHex(buf: ArrayBuffer): string {\n return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/** Constant-time compare of two equal-length hex strings. */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n return diff === 0;\n}\n\n/**\n * Verify a Stripe webhook signature (C3): HMAC-SHA256 over `` `${t}.${payload}` ``\n * with the endpoint signing secret, a replay window (default 5 minutes), and a\n * constant-time compare. Package-enforced — never left to a site. Returns `false`\n * (never throws) on a malformed header, a non-numeric or stale timestamp, or a\n * signature mismatch. `now`/`toleranceSec` are injectable for tests.\n */\nexport async function verifyStripeSignature(\n payload: string,\n header: string,\n secret: string,\n opts: { now?: number; toleranceSec?: number } = {},\n): Promise<boolean> {\n const { t, v1 } = parseSigHeader(header);\n if (!t || !v1) return false;\n const ts = Number(t);\n if (!Number.isFinite(ts)) return false;\n const nowSec = (opts.now ?? Date.now()) / 1000;\n const tolerance = opts.toleranceSec ?? 300;\n if (Math.abs(nowSec - ts) > tolerance) return false;\n\n const enc = new TextEncoder();\n const key = await crypto.subtle.importKey(\"raw\", enc.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n const mac = await crypto.subtle.sign(\"HMAC\", key, enc.encode(`${t}.${payload}`));\n return timingSafeEqual(toHex(mac), v1);\n}\n\n// ── readiness + Stripe wire helpers ──\n\n/** A group row's payment configuration, as far as readiness cares. */\nexport interface PaymentsGroup {\n stripePublishableKey?: string | null;\n stripePriceId?: string | null;\n}\n\n/** Whether a group can take payment: a publishable key + a price id (both on the\n * group row) AND a secret key (the vault). Anything missing drops the join\n * flow's payment step (paymentsReady:false) rather than half-charging. */\nexport function paymentsReady(group: PaymentsGroup, hasSecretKey: boolean): boolean {\n return Boolean(group.stripePublishableKey && group.stripePriceId && hasSecretKey);\n}\n\n/** Form-encode params for Stripe's x-www-form-urlencoded API, expanding one level\n * of nested objects into bracket syntax (`metadata[applicationId]=...`). */\nexport function stripeForm(params: Record<string, unknown>): string {\n const out = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v === undefined || v === null) continue;\n if (typeof v === \"object\") {\n for (const [k2, v2] of Object.entries(v as Record<string, unknown>)) {\n if (v2 !== undefined && v2 !== null) out.append(`${k}[${k2}]`, String(v2));\n }\n } else {\n out.append(k, String(v));\n }\n }\n return out.toString();\n}\n\n/** The Stripe idempotency key for creating an application's subscription — one\n * per application, so a client retry can't orphan a second subscription. */\nexport function subscriptionIdempotencyKey(applicationId: string): string {\n return `sub:${applicationId}`;\n}\n\n/** The db mutationId for a webhook-driven write — exactly-once per Stripe event,\n * so replays are deduped at the db layer. */\nexport function webhookMutationId(eventId: string): string {\n return `stripe:${eventId}`;\n}\n\n// ── webhook normalization (pure; the worker owns the db lookup + writes) ──\n\n/** A raw Stripe event, as far as normalization cares. */\nexport interface StripeEvent {\n id: string;\n type: string;\n data?: { object?: Record<string, unknown> };\n}\n\n/** A normalized, provider-agnostic webhook event. `kind` drives the db write;\n * the application is resolved from `applicationId` (metadata) or `customerId`. */\nexport type WebhookEvent =\n | { kind: \"first_payment\"; applicationId?: string; customerId?: string; renewalAt?: number }\n | { kind: \"renewal\"; applicationId?: string; customerId?: string; renewalAt?: number }\n | { kind: \"refunded\"; applicationId?: string; customerId?: string }\n | { kind: \"canceled\"; applicationId?: string; customerId?: string }\n | { kind: \"ignored\"; type: string };\n\n/** Resolve the application reference on a Stripe object: `applicationId` from\n * metadata (direct, then subscription_details, then nested\n * parent.subscription_details), plus the customer id for the db fallback. */\nexport function findApplicationRef(obj: Record<string, unknown>): { applicationId?: string; customerId?: string } {\n const metaOf = (v: unknown): Record<string, unknown> =>\n v && typeof v === \"object\" ? ((v as Record<string, unknown>).metadata as Record<string, unknown>) ?? {} : {};\n const pick = (m: Record<string, unknown>): string | undefined =>\n typeof m.applicationId === \"string\" ? m.applicationId : undefined;\n const applicationId =\n pick(metaOf(obj)) ?? pick(metaOf(obj.subscription_details)) ?? pick(metaOf((obj.parent as Record<string, unknown> | undefined)?.subscription_details));\n const customerId = typeof obj.customer === \"string\" ? obj.customer : undefined;\n return { ...(applicationId ? { applicationId } : {}), ...(customerId ? { customerId } : {}) };\n}\n\n/** Normalize a verified Stripe event into a {@link WebhookEvent}. `invoice.paid`\n * splits into first_payment vs renewal by `billing_reason`; refunds and\n * cancellations map directly; everything else is ignored (acked, not retried). */\nexport function normalizeWebhookEvent(event: StripeEvent): WebhookEvent {\n const obj = event.data?.object ?? {};\n const ref = findApplicationRef(obj);\n switch (event.type) {\n case \"invoice.paid\": {\n const lines = ((obj.lines as Record<string, unknown> | undefined)?.data as Array<Record<string, unknown>> | undefined) ?? [];\n const periodEnd = (lines[0]?.period as Record<string, unknown> | undefined)?.end;\n const renewalAt = typeof periodEnd === \"number\" ? periodEnd * 1000 : undefined;\n const kind = obj.billing_reason === \"subscription_create\" ? \"first_payment\" : \"renewal\";\n return { kind, ...ref, ...(renewalAt !== undefined ? { renewalAt } : {}) };\n }\n case \"charge.refunded\":\n return { kind: \"refunded\", ...ref };\n case \"customer.subscription.deleted\":\n return { kind: \"canceled\", ...ref };\n default:\n return { kind: \"ignored\", type: event.type };\n }\n}\n\n// ── webhook write-set builders (the authoritative writers of paid/refunded) ──\n\n/** First-payment patch: advance submitted→paid_pending_vetting (never any other\n * transition) and record the renewal date. Empty when nothing changed, so the\n * caller can skip the write. */\nexport function firstPaymentPatch(currentStatus: string, renewalAt?: number): { status?: \"paid_pending_vetting\"; renewalAt?: number } {\n return {\n ...(currentStatus === \"submitted\" ? { status: \"paid_pending_vetting\" as const } : {}),\n ...(renewalAt !== undefined ? { renewalAt } : {}),\n };\n}\n\n/** Renewal-invoice patch: just the new renewal date. */\nexport function renewalPatch(renewalAt: number): { renewalAt: number } {\n return { renewalAt };\n}\n\n/** Refund patch — the SOLE writer of status \"refunded\" (the admin refund route\n * issues the Stripe refund but never sets this; the webhook does). */\nexport function refundedPatch(): { status: \"refunded\" } {\n return { status: \"refunded\" };\n}\n\n/** Subscription-cancellation patch. */\nexport function canceledPatch(): { canceled: true } {\n return { canceled: true };\n}\n","// The Stripe payments provider — the only I/O half of payments. Talks to the\n// Stripe REST API over fetch (no SDK), and maps 1:1 onto the pure helpers in\n// ./payments (form encoding, signature verify, event normalization). The worker\n// resolves secrets from the vault per request and constructs this; the routes own\n// every db write so idempotency stays at the db layer.\nimport { normalizeWebhookEvent, stripeForm, verifyStripeSignature } from \"./payments\";\nimport type { StripeEvent, WebhookEvent } from \"./payments\";\n\n/** Inputs to create an application's founding-member subscription. */\nexport interface CreateSubscriptionInput {\n applicationId: string;\n groupId: string;\n email: string;\n name: string;\n priceId: string;\n existingCustomerId?: string;\n}\n\n/** The client secret to confirm card entry, plus the ids to persist. */\nexport interface CreateSubscriptionResult {\n customerId: string;\n subscriptionId: string;\n clientSecret: string;\n}\n\n/** The outcome of a full refund. */\nexport interface RefundResult {\n refundedCents: number | null;\n subscriptionCanceled: boolean;\n}\n\n/** The capabilities the payment routes depend on — Stripe is one impl. */\nexport interface PaymentsProvider {\n createSubscription(input: CreateSubscriptionInput): Promise<CreateSubscriptionResult>;\n ingestWebhook(\n rawBody: string,\n sigHeader: string,\n ): Promise<{ ok: true; eventId: string; event: WebhookEvent } | { ok: false; reason: \"bad_signature\" }>;\n refund(input: { customerId: string; subscriptionId: string }): Promise<RefundResult>;\n}\n\n/** The result of a Stripe Backend API call: ok + status + parsed JSON body. */\nexport type StripeResult = { ok: boolean; status: number; body: Record<string, unknown> };\n\n/** Call the Stripe Backend API (form-encoded, Bearer sk_). Exposed so the admin\n * billing/dashboard reads and the refund route share one Stripe client instead\n * of each re-deriving the auth + encoding. */\nexport async function stripeCall(\n sk: string,\n method: \"GET\" | \"POST\" | \"DELETE\",\n path: string,\n params?: Record<string, unknown>,\n idempotencyKey?: string,\n): Promise<StripeResult> {\n const qs = method === \"GET\" && params ? `?${stripeForm(params)}` : \"\";\n const headers: Record<string, string> = { authorization: `Bearer ${sk}` };\n if (idempotencyKey) headers[\"idempotency-key\"] = idempotencyKey;\n const init: RequestInit = { method, headers };\n if (method === \"POST\" && params) {\n headers[\"content-type\"] = \"application/x-www-form-urlencoded\";\n init.body = stripeForm(params);\n }\n const res = await fetch(`https://api.stripe.com${path}${qs}`, init);\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n return { ok: res.ok, status: res.status, body };\n}\n\nfunction fail(op: string, r: StripeResult): never {\n const err = new Error(`stripe ${op} failed: ${r.status}`) as Error & { code: string };\n err.code = \"stripe_error\";\n throw err;\n}\n\nfunction clientSecretOf(sub: Record<string, unknown>): string | undefined {\n const inv = sub.latest_invoice as Record<string, unknown> | undefined;\n const confirmation = inv?.confirmation_secret as Record<string, unknown> | undefined;\n const intent = inv?.payment_intent as Record<string, unknown> | undefined;\n const secret = confirmation?.client_secret ?? intent?.client_secret;\n return typeof secret === \"string\" ? secret : undefined;\n}\n\nfunction requireSecret(secretKey: string | undefined): string {\n if (!secretKey) {\n const err = new Error(\"stripe secret key missing\") as Error & { code: string };\n err.code = \"not_configured\";\n throw err;\n }\n return secretKey;\n}\n\n/** Build the Stripe provider. `secretKey` powers charging/refunds; `webhookSecret`\n * powers webhook ingest. Each is resolved from the vault per request, so the\n * webhook route can construct an ingest-only provider without the secret key. */\nexport function createStripeProvider(config: { secretKey?: string; webhookSecret?: string }): PaymentsProvider {\n const { secretKey, webhookSecret } = config;\n return {\n async createSubscription(input) {\n const sk = requireSecret(secretKey);\n const meta = { applicationId: input.applicationId, groupId: input.groupId, email: input.email };\n let customerId = input.existingCustomerId;\n if (!customerId) {\n const cust = await stripeCall(\n sk,\n \"POST\",\n \"/v1/customers\",\n { email: input.email, name: input.name, metadata: meta },\n `cus:${input.applicationId}`,\n );\n if (!cust.ok) fail(\"customer create\", cust);\n customerId = String(cust.body.id);\n }\n const sub = await stripeCall(\n sk,\n \"POST\",\n \"/v1/subscriptions\",\n {\n customer: customerId,\n \"items[0][price]\": input.priceId,\n payment_behavior: \"default_incomplete\",\n \"payment_settings[save_default_payment_method]\": \"on_subscription\",\n \"payment_settings[payment_method_types][0]\": \"card\",\n \"expand[0]\": \"latest_invoice.confirmation_secret\",\n metadata: meta,\n },\n // Hardening: one subscription per application, so a client\n // retry between create and the db write can't orphan a second one.\n `sub:${input.applicationId}`,\n );\n if (!sub.ok) fail(\"subscription create\", sub);\n const clientSecret = clientSecretOf(sub.body);\n if (!clientSecret) fail(\"subscription confirmation-secret missing\", sub);\n return { customerId, subscriptionId: String(sub.body.id), clientSecret };\n },\n\n async ingestWebhook(rawBody, sigHeader) {\n if (!webhookSecret || !(await verifyStripeSignature(rawBody, sigHeader, webhookSecret))) {\n return { ok: false, reason: \"bad_signature\" };\n }\n const event = JSON.parse(rawBody) as StripeEvent;\n return { ok: true, eventId: event.id, event: normalizeWebhookEvent(event) };\n },\n\n async refund(input) {\n const sk = requireSecret(secretKey);\n const charges = await stripeCall(sk, \"GET\", \"/v1/charges\", { customer: input.customerId, limit: 100 });\n if (!charges.ok) fail(\"charges list\", charges);\n const rows = (charges.body.data as Array<Record<string, unknown>> | undefined) ?? [];\n const paid = rows.filter((c) => c.status === \"succeeded\" && c.refunded !== true);\n const charge = paid[paid.length - 1]; // Stripe returns newest-first; refund the earliest.\n if (!charge) {\n const err = new Error(\"no paid charge to refund\") as Error & { code: string };\n err.code = \"no_charge\";\n throw err;\n }\n const refund = await stripeCall(sk, \"POST\", \"/v1/refunds\", { charge: String(charge.id) });\n if (!refund.ok) fail(\"refund\", refund);\n const cancel = await stripeCall(sk, \"DELETE\", `/v1/subscriptions/${input.subscriptionId}`);\n const amount = refund.body.amount;\n return { refundedCents: typeof amount === \"number\" ? amount : null, subscriptionCanceled: cancel.ok };\n },\n };\n}\n","// Payment routes: POST /api/payments/subscription (start a founding-member\n// subscription), POST /api/webhooks/stripe (the AUTHORITATIVE writer of\n// paid/refunded/canceled, exactly-once per event id), and POST\n// /api/admin/applications/:id/refund (admin-gated; issues the refund but never\n// writes status — the charge.refunded webhook does). I/O only; the correctness\n// rules live in ./payments and the provider in ./payments-stripe.\nimport { getVaultSecret } from \"./auth\";\nimport { emailGroupFrom, sendTemplated } from \"./notify\";\nimport { canceledPatch, firstPaymentPatch, refundedPatch, renewalPatch, webhookMutationId } from \"./payments\";\nimport type { WebhookEvent } from \"./payments\";\nimport { createStripeProvider } from \"./payments-stripe\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, WorkerContext } from \"./worker-context\";\nimport type { Route } from \"./worker-routes\";\nimport type { ChapterDb } from \"./types\";\n\ntype Row = Record<string, unknown>;\n\nconst codeOf = (err: unknown): string =>\n err && typeof err === \"object\" && typeof (err as { code?: unknown }).code === \"string\" ? (err as { code: string }).code : \"unknown\";\n\nasync function firstRow(db: ChapterDb, ns: string, q: Record<string, unknown>): Promise<Row | undefined> {\n const res = await db.query({ [ns]: { $: q } });\n const rows = res[ns];\n return Array.isArray(rows) ? rows[0] : undefined;\n}\n\nfunction lineItems(group: Row): { standardCents: number; discountCents: number; dueTodayCents: number } {\n const standard = Number(group.standardPriceCents ?? 0);\n const discount = Number(group.foundingDiscountCents ?? 0);\n return { standardCents: standard, discountCents: discount, dueTodayCents: standard - discount };\n}\n\n// Resolve the application an event targets: by metadata applicationId, else the\n// newest row for the Stripe customer.\nasync function findApplication(db: ChapterDb, event: WebhookEvent): Promise<Row | undefined> {\n if (\"applicationId\" in event && event.applicationId) {\n return firstRow(db, \"applications\", { where: { id: event.applicationId }, limit: 1 });\n }\n if (\"customerId\" in event && event.customerId) {\n return firstRow(db, \"applications\", { where: { stripeCustomerId: event.customerId }, order: { createdAt: \"desc\" }, limit: 1 });\n }\n return undefined;\n}\n\n// Best-effort payment-confirmation to the applicant on the first successful\n// invoice. Exactly-once per Stripe event via the dedupeKey.\nasync function notifyPaymentConfirmed(db: ChapterDb, env: ChapterEnv, eventId: string, app: Row): Promise<void> {\n try {\n if (typeof app.email !== \"string\" || !app.email) return;\n const group = await firstRow(db, \"groups\", { where: { id: String(app.groupId ?? \"\") }, limit: 1 });\n if (!group) return;\n await sendTemplated(\n { db, envName: env.ODLA_ENV, sender: env.SEND_EMAIL, from: env.EMAIL_FROM, now: () => Date.now(), newId: () => crypto.randomUUID() },\n {\n group: emailGroupFrom(group),\n template: \"paymentConfirmation\",\n to: app.email,\n vars: { firstName: typeof app.firstName === \"string\" ? app.firstName : \"\" },\n dedupeKey: `${eventId}:confirm`,\n applicationId: String(app.id),\n },\n );\n } catch {\n // never let a confirmation-email failure affect the webhook 200\n }\n}\n\n// Best-effort admin notification at PAYMENT time — the alternative trigger to\n// notifying on submit (sends.adminNotification: \"payment\"). Same template, same\n// exactly-once dedupe, different moment.\nasync function notifyAdminOfPayment(db: ChapterDb, env: ChapterEnv, eventId: string, app: Row): Promise<void> {\n try {\n const group = await firstRow(db, \"groups\", { where: { id: String(app.groupId ?? \"\") }, limit: 1 });\n if (!group || typeof group.notificationEmail !== \"string\" || !group.notificationEmail) return;\n const s = (v: unknown): string => (typeof v === \"string\" ? v : \"\");\n await sendTemplated(\n { db, envName: env.ODLA_ENV, sender: env.SEND_EMAIL, from: env.EMAIL_FROM, now: () => Date.now(), newId: () => crypto.randomUUID() },\n {\n group: emailGroupFrom(group),\n template: \"adminNotification\",\n to: group.notificationEmail,\n vars: { firstName: s(app.firstName), lastName: s(app.lastName), email: s(app.email), phone: s(app.phone), state: s(app.state) },\n dedupeKey: `${eventId}:admin`,\n applicationId: String(app.id),\n },\n );\n } catch {\n // never let a notification failure affect the webhook 200\n }\n}\n\n// The application-row patch for a resolved event (empty = skip the write).\nfunction webhookPatch(event: WebhookEvent, status: string): Record<string, unknown> {\n switch (event.kind) {\n case \"first_payment\":\n return firstPaymentPatch(status, event.renewalAt);\n case \"renewal\":\n return event.renewalAt !== undefined ? renewalPatch(event.renewalAt) : {};\n case \"refunded\":\n return refundedPatch();\n case \"canceled\":\n return canceledPatch();\n default:\n return {};\n }\n}\n\nasync function startSubscription(req: Request, env: ChapterEnv, ctx: WorkerContext): Promise<Response> {\n let body: Row;\n try {\n body = JSON.parse(await req.text()) as Row;\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n const applicationId = typeof body.applicationId === \"string\" ? body.applicationId : \"\";\n if (!applicationId) return json({ error: \"applicationId required\" }, 400);\n if (body.refundPolicyAck !== true) return json({ error: \"refundPolicyAck required\" }, 400);\n\n const db = ctx.makeDb(env) as unknown as ChapterDb;\n const app = await firstRow(db, \"applications\", { where: { id: applicationId }, limit: 1 });\n if (!app) return json({ error: \"not found\" }, 404);\n // Single-charge guard: only from the initial state, so a re-post can't double-subscribe.\n if (app.status !== \"submitted\") return json({ error: \"already processed\" }, 409);\n\n const group = await firstRow(db, \"groups\", { where: { id: String(app.groupId ?? ctx.chapter.id) }, limit: 1 });\n const priceId = group?.stripePriceId;\n const secretKey = await getVaultSecret(db, \"stripe_secret_key\");\n if (!group || !priceId || !secretKey) return json({ error: \"payments not configured\" }, 503);\n\n const provider = createStripeProvider({ secretKey });\n let result;\n try {\n result = await provider.createSubscription({\n applicationId,\n groupId: String(group.id),\n email: String(app.email ?? \"\"),\n name: `${app.firstName ?? \"\"} ${app.lastName ?? \"\"}`.trim(),\n priceId: String(priceId),\n existingCustomerId: typeof app.stripeCustomerId === \"string\" ? app.stripeCustomerId : undefined,\n });\n } catch (err) {\n return json({ error: \"payment setup failed\", code: codeOf(err) }, 502);\n }\n\n await db.transact([\n {\n t: \"update\",\n ns: \"applications\",\n id: applicationId,\n attrs: { stripeCustomerId: result.customerId, stripeSubscriptionId: result.subscriptionId, refundPolicyAckAt: Date.now() },\n },\n ]);\n return json({ clientSecret: result.clientSecret, publishableKey: group.stripePublishableKey ?? null, lineItems: lineItems(group) });\n}\n\nasync function ingestWebhook(req: Request, env: ChapterEnv, ctx: WorkerContext): Promise<Response> {\n const db = ctx.makeDb(env) as unknown as ChapterDb;\n const webhookSecret = await getVaultSecret(db, \"stripe_webhook_secret\");\n if (!webhookSecret) return json({ error: \"webhook not configured\" }, 503);\n\n const rawBody = await req.text();\n const ingest = await createStripeProvider({ webhookSecret }).ingestWebhook(rawBody, req.headers.get(\"stripe-signature\") ?? \"\");\n if (!ingest.ok) return json({ error: \"invalid signature\" }, 400);\n const { eventId, event } = ingest;\n if (event.kind === \"ignored\") return json({ ok: true, ignored: event.type });\n\n const app = await findApplication(db, event);\n if (!app) return json({ ok: true, matched: false });\n\n const patch = webhookPatch(event, String(app.status ?? \"\"));\n if (Object.keys(patch).length) {\n await db.transact([{ t: \"update\", ns: \"applications\", id: String(app.id), attrs: patch }], { mutationId: webhookMutationId(eventId) });\n }\n if (event.kind === \"first_payment\") {\n await notifyPaymentConfirmed(db, env, eventId, app);\n if (ctx.chapter.sends.adminNotification === \"payment\") await notifyAdminOfPayment(db, env, eventId, app);\n }\n return json({ ok: true });\n}\n\nasync function refundApplication(req: Request, url: URL, env: ChapterEnv, ctx: WorkerContext): Promise<Response> {\n const rawDb = ctx.makeDb(env);\n const u = await ctx.verifyUser(req, env);\n if (!u || !(await ctx.isAdmin(rawDb, u))) return json({ error: \"forbidden\" }, 403);\n\n const id = url.pathname.split(\"/\")[4] ?? \"\";\n const db = rawDb as unknown as ChapterDb;\n const app = await firstRow(db, \"applications\", { where: { id }, limit: 1 });\n if (!app) return json({ error: \"not found\" }, 404);\n if (app.status === \"refunded\") return json({ error: \"already refunded\" }, 409);\n if (app.status === \"approved\") return json({ error: \"approved memberships are non-refundable\" }, 409);\n if (!app.stripeSubscriptionId) return json({ error: \"no subscription on file\" }, 409);\n if (!app.stripeCustomerId) return json({ error: \"no customer on file\" }, 409);\n\n const secretKey = await getVaultSecret(db, \"stripe_secret_key\");\n if (!secretKey) return json({ error: \"payments not configured\" }, 503);\n\n try {\n const result = await createStripeProvider({ secretKey }).refund({\n customerId: String(app.stripeCustomerId),\n subscriptionId: String(app.stripeSubscriptionId),\n });\n // Note: status \"refunded\" is NOT written here — the charge.refunded webhook is\n // the single writer, keeping Stripe the source of truth.\n return json({ ok: true, refundedCents: result.refundedCents, subscriptionCanceled: result.subscriptionCanceled });\n } catch (err) {\n const code = codeOf(err);\n return json({ error: \"refund failed\", code }, code === \"no_charge\" ? 409 : 502);\n }\n}\n\nconst REFUND_PATH = /^\\/api\\/admin\\/applications\\/[^/]+\\/refund$/;\n\n/** The payment routes (chapter mode). Webhook + subscription are public\n * (capability-guarded by the unguessable application id / the signed payload);\n * refund is admin-gated. */\nexport const handlePayments: Route = async (req, url, env, ctx) => {\n if (ctx.chapter.mode !== \"chapter\") return null;\n if (req.method === \"POST\" && url.pathname === \"/api/payments/subscription\") return startSubscription(req, env, ctx);\n if (req.method === \"POST\" && url.pathname === \"/api/webhooks/stripe\") return ingestWebhook(req, env, ctx);\n if (req.method === \"POST\" && REFUND_PATH.test(url.pathname)) return refundApplication(req, url, env, ctx);\n return null;\n};\n","// Admin operational routes. GET /api/admin/meetings is the admin agenda,\n// reconciled against the live platform calendar: it reads upcoming events through\n// @odla-ai/calendar (chapter never calls Google directly) and adopts any\n// owner-side move/cancel onto the canonical meetings row + the application\n// projection, via the pure ./reconcile logic. Admin-gated; the read still\n// succeeds (serving canonical rows) if the calendar is unavailable.\nimport { initCalendar } from \"@odla-ai/calendar\";\nimport { reconcileMeetings } from \"./reconcile\";\nimport type { LiveEvent, MeetingForReconcile, ReconcileDecision } from \"./reconcile\";\nimport { resolveScheduling, validateScheduling } from \"./scheduling\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, WorkerContext } from \"./worker-context\";\nimport type { Route } from \"./worker-routes\";\nimport type { ChapterDb, ChapterScheduling, DbOp } from \"./types\";\n\n// Load the admin's target group (query param `group`, else the chapter), gated on\n// an admin session. Returns [db, group] or a Response to short-circuit.\nasync function adminGroup(\n req: Request,\n env: ChapterEnv,\n ctx: WorkerContext,\n url: URL,\n): Promise<{ db: ChapterDb; group: Record<string, unknown> } | Response> {\n const rawDb = ctx.makeDb(env);\n const u = await ctx.verifyUser(req, env);\n if (!u || !(await ctx.isAdmin(rawDb, u))) return json({ error: \"forbidden\" }, 403);\n const db = rawDb as unknown as ChapterDb;\n const groupId = url.searchParams.get(\"group\") ?? ctx.chapter.id;\n const group = (await db.query({ groups: { $: { where: { id: groupId }, limit: 1 } } })).groups?.[0];\n if (!group) return json({ error: \"not found\" }, 404);\n return { db, group };\n}\n\n/** GET/PUT /api/admin/scheduling — read the group's booking rules, or replace\n * them (validated via resolveScheduling; a bad config is a 400, never persisted).\n * The backend for the availability-editor section. */\nexport const handleAdminScheduling: Route = async (req, url, env, ctx) => {\n if (url.pathname !== \"/api/admin/scheduling\" || (req.method !== \"GET\" && req.method !== \"PUT\")) return null;\n const got = await adminGroup(req, env, ctx, url);\n if (got instanceof Response) return got;\n const { db, group } = got;\n\n if (req.method === \"GET\") {\n return json({ scheduling: resolveScheduling(group.schedulingJson as ChapterScheduling | undefined) });\n }\n let body: unknown;\n try {\n body = JSON.parse(await req.text());\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n // Field-keyed messages, not a thrown string: an owner-facing settings form needs\n // to say which field is wrong and why.\n const checked = validateScheduling(body as ChapterScheduling);\n if (!checked.ok) return json({ error: \"invalid scheduling config\", errors: checked.errors }, 400);\n await db.transact([{ t: \"update\", ns: \"groups\", id: String(group.id), attrs: { schedulingJson: checked.value } }]);\n return json({ scheduling: checked.value });\n};\n\nasync function upcomingEvents(env: ChapterEnv): Promise<LiveEvent[]> {\n const cal = initCalendar({ appId: env.ODLA_APP_ID, env: env.ODLA_ENV, adminToken: env.ODLA_API_KEY, endpoint: env.ODLA_PLATFORM });\n const res = await cal.availability.upcoming();\n return res.events.map((e) => ({ eventId: e.eventId, status: e.status, startAt: e.startAt, endAt: e.endAt }));\n}\n\nfunction toReconcile(rows: Array<Record<string, unknown>>): MeetingForReconcile[] {\n return rows.map((m) => ({\n id: String(m.id),\n applicationId: String(m.applicationId),\n googleEventId: typeof m.googleEventId === \"string\" ? m.googleEventId : null,\n status: String(m.status ?? \"\"),\n startAt: typeof m.startAt === \"number\" ? m.startAt : null,\n endAt: typeof m.endAt === \"number\" ? m.endAt : null,\n }));\n}\n\n/** GET /api/admin/meetings — the scheduled agenda, reconciled against the live\n * calendar (adopts owner moves/cancellations onto the canonical rows). */\nexport const handleAdminMeetings: Route = async (req, url, env, ctx) => {\n if (req.method !== \"GET\" || url.pathname !== \"/api/admin/meetings\") return null;\n const rawDb = ctx.makeDb(env);\n const u = await ctx.verifyUser(req, env);\n if (!u || !(await ctx.isAdmin(rawDb, u))) return json({ error: \"forbidden\" }, 403);\n const db = rawDb as unknown as ChapterDb;\n\n // ?all=1 includes cancelled/past rows; from/to bound the window (epoch ms).\n const all = url.searchParams.get(\"all\") === \"1\";\n const from = Number(url.searchParams.get(\"from\"));\n const to = Number(url.searchParams.get(\"to\"));\n\n const query = await db.query({\n meetings: { $: { where: all ? {} : { status: \"scheduled\" }, order: { startAt: \"asc\" }, limit: 500 } },\n });\n let rows = (Array.isArray(query.meetings) ? query.meetings : []) as Array<Record<string, unknown>>;\n if (Number.isFinite(from)) rows = rows.filter((m) => Number(m.startAt ?? 0) >= from);\n if (Number.isFinite(to)) rows = rows.filter((m) => Number(m.startAt ?? 0) <= to);\n\n let decisions: ReconcileDecision[] = [];\n try {\n decisions = reconcileMeetings(toReconcile(rows), await upcomingEvents(env), Date.now());\n } catch {\n // Calendar unavailable — serve the canonical rows without adopting edits.\n }\n\n // Apply adopt decisions (best-effort; the read still succeeds if a write fails).\n const patched = new Map<string, Record<string, unknown>>();\n for (const d of decisions) {\n const ops: DbOp[] = [\n { t: \"update\", ns: \"meetings\", id: d.meetingId, attrs: d.meetingPatch },\n { t: \"update\", ns: \"applications\", id: d.applicationId, attrs: d.applicationPatch },\n ];\n try {\n await db.transact(ops);\n patched.set(d.meetingId, d.meetingPatch);\n } catch {\n // leave the row as-is if the write fails\n }\n }\n\n // Join the applicant onto each row, and return the group timezone, so an admin\n // console can label and render the agenda without a second round trip. One\n // query, indexed by id — not N+1.\n const appQuery = await db.query({ applications: { $: { limit: 1000 } } });\n const byId = new Map<string, Record<string, unknown>>();\n for (const a of Array.isArray(appQuery.applications) ? appQuery.applications : []) {\n byId.set(String(a.id), a);\n }\n const applicantOf = (m: Record<string, unknown>): Record<string, unknown> | null => {\n const a = byId.get(String(m.applicationId));\n if (!a) return null;\n return { id: a.id, firstName: a.firstName, lastName: a.lastName, email: a.email, status: a.status };\n };\n\n const group = (await db.query({ groups: { $: { where: { id: ctx.chapter.id }, limit: 1 } } })).groups?.[0];\n const timezone = resolveScheduling(group?.schedulingJson as ChapterScheduling | undefined).timezone;\n\n // Reflect adopted patches; the row carries drift (drift, driftGoogleStartAt,\n // adoptedFromGoogleAt) and the Meet/Calendar links (meetUrl, htmlLink) already.\n const meetings = rows\n .map((m): Record<string, unknown> => ({ ...m, ...(patched.get(String(m.id)) ?? {}), applicant: applicantOf(m) }))\n .filter((m) => all || m.status === \"scheduled\");\n return json({ meetings, adopted: decisions.length, timezone });\n};\n","// The Google → chapter half of the bidirectional calendar sync. Booking writes\n// events TO the platform calendar (0.4.0's create/reschedule); this ADOPTS edits\n// FROM it: when the owner moves or cancels the intro call directly in Google,\n// reconcile mirrors that onto our canonical `meetings` row and the `application`\n// projection. Chapter never calls Google — the worker reads live events through\n// @odla-ai/calendar's upcoming() (platform-brokered) and applies the ops this\n// returns. Pure + testable; adoption policy (owner edits win) matches the shipped\n// original production worker.\n\n/** A `meetings` row, as far as reconciliation cares. */\nexport interface MeetingForReconcile {\n id: string;\n applicationId: string;\n googleEventId?: string | null;\n status: string;\n startAt?: number | null;\n endAt?: number | null;\n}\n\n/** One live calendar event (a subset of @odla-ai/calendar's Booking). */\nexport interface LiveEvent {\n eventId: string;\n status?: string;\n startAt?: number;\n endAt?: number;\n}\n\n/** An adopt decision: mirror a Google move/cancel onto our rows. */\nexport interface ReconcileDecision {\n meetingId: string;\n applicationId: string;\n kind: \"cancelled\" | \"moved\";\n /** Attrs to write onto the `meetings` row. */\n meetingPatch: Record<string, unknown>;\n /** Attrs to write onto the `applications` row (the projection). */\n applicationPatch: Record<string, unknown>;\n}\n\n/** Meetings still worth reconciling: a scheduled booking with a Google event that\n * starts in the future (or within the last hour, to catch a just-passed edit). */\nexport function isReconcilable(meeting: MeetingForReconcile, now: number): boolean {\n return meeting.status === \"scheduled\" && Boolean(meeting.googleEventId) && (meeting.startAt ?? 0) > now - 3_600_000;\n}\n\n/**\n * Diff canonical `meetings` against the live calendar events and return the adopt\n * decisions — only for meetings that actually changed (a still-matching meeting\n * is omitted). A meeting whose event vanished or is `cancelled` in Google is\n * adopted as cancelled (application `meetingAt` zeroed — 0 means \"was booked,\n * then cancelled\"); a meeting whose event moved adopts the new window (duration\n * preserved when the event omits `endAt`).\n */\nexport function reconcileMeetings(\n meetings: readonly MeetingForReconcile[],\n events: readonly LiveEvent[],\n now: number,\n): ReconcileDecision[] {\n const byEvent = new Map(events.map((e) => [e.eventId, e]));\n const decisions: ReconcileDecision[] = [];\n for (const m of meetings) {\n if (!isReconcilable(m, now) || !m.googleEventId) continue;\n const g = byEvent.get(m.googleEventId);\n if (!g || g.status === \"cancelled\") {\n decisions.push({\n meetingId: m.id,\n applicationId: m.applicationId,\n kind: \"cancelled\",\n meetingPatch: { status: \"cancelled\", drift: \"none\", adoptedFromGoogleAt: now },\n applicationPatch: { meetingAt: 0, meetingLink: \"\" },\n });\n } else if (g.startAt !== undefined && g.startAt !== m.startAt) {\n const duration = (m.endAt ?? 0) - (m.startAt ?? 0);\n decisions.push({\n meetingId: m.id,\n applicationId: m.applicationId,\n kind: \"moved\",\n meetingPatch: { startAt: g.startAt, endAt: g.endAt ?? g.startAt + duration, drift: \"none\", adoptedFromGoogleAt: now },\n applicationPatch: { meetingAt: g.startAt },\n });\n }\n }\n return decisions;\n}\n","// The odla->Clerk write half: server-side Clerk role read/list/write, the gap\n// beside clerk.ts's create/invite/heal. Roles live in `public_metadata.role`; an\n// absent role means the lowest rung (\"provisional\") — chapter never writes it at\n// create. The role write is a MERGE-PATCH of only `{ role }`, so it never clobbers\n// the separately-written `public_metadata.profile` (Clerk merges public_metadata\n// per key; proven in the reference site's running role-change route). Chapter\n// calls the Clerk Backend API over fetch with the vault `clerk_secret_key`.\n\nconst CLERK_API = \"https://api.clerk.com\";\nconst DEFAULT_ROLE = \"provisional\";\nconst PAGE = 100;\n\n/** A Clerk user as chapter's role layer sees it. `role` defaults to the lowest\n * rung when `public_metadata` carries none; `publicMetadata` is returned raw so a\n * site with a custom ladder can re-derive it. */\nexport interface ClerkUserRecord {\n id: string;\n email?: string;\n role: string;\n publicMetadata: Record<string, unknown>;\n}\n\n// The Clerk Backend API user object — only the fields chapter reads.\ninterface ClerkApiUser {\n id?: unknown;\n email_addresses?: Array<{ email_address?: unknown }>;\n public_metadata?: Record<string, unknown>;\n}\n\nfunction toRecord(u: ClerkApiUser): ClerkUserRecord | null {\n if (typeof u.id !== \"string\") return null;\n const pm = (u.public_metadata ?? {}) as Record<string, unknown>;\n const role = typeof pm.role === \"string\" && pm.role ? pm.role : DEFAULT_ROLE;\n const email = u.email_addresses?.[0]?.email_address;\n return { id: u.id, email: typeof email === \"string\" ? email : undefined, role, publicMetadata: pm };\n}\n\nasync function clerkGet(path: string, secretKey: string, fetchImpl: typeof fetch): Promise<unknown> {\n const res = await fetchImpl(`${CLERK_API}${path}`, { headers: { authorization: `Bearer ${secretKey}` } });\n if (!res.ok) throw new Error(`clerk GET ${path} → ${res.status}`);\n return res.json();\n}\n\n/** Look a Clerk user up by email. `null` when no such user — or when the lookup\n * fails (a role gate treats an unresolvable user as absent, matching the site's\n * own fallback). Role defaults to provisional when unset. */\nexport async function clerkGetUserByEmail(secretKey: string, email: string, fetchImpl: typeof fetch = fetch): Promise<ClerkUserRecord | null> {\n const data = await clerkGet(`/v1/users?email_address=${encodeURIComponent(email)}&limit=1`, secretKey, fetchImpl).catch(() => null);\n const user = Array.isArray(data) ? (data[0] as ClerkApiUser | undefined) : undefined;\n return user ? toRecord(user) : null;\n}\n\n/** Fetch a Clerk user by id, for role-change gating. `null` when missing or on a\n * failed lookup. Role defaults to provisional when unset. */\nexport async function clerkGetUser(secretKey: string, id: string, fetchImpl: typeof fetch = fetch): Promise<ClerkUserRecord | null> {\n const data = await clerkGet(`/v1/users/${encodeURIComponent(id)}`, secretKey, fetchImpl).catch(() => null);\n return data ? toRecord(data as ClerkApiUser) : null;\n}\n\n/** List ALL Clerk users with their roles, auto-paginating. A membership community\n * outgrows one page, and a fixed `limit=100` would silently drop members from the\n * admin roster with no error — so this pages (offset in steps of {@link PAGE})\n * until a short page. A page fetch that fails THROWS rather than returning a\n * partial list, so the caller never mistakes a truncated roster for the whole. */\nexport async function clerkListUsers(secretKey: string, fetchImpl: typeof fetch = fetch): Promise<ClerkUserRecord[]> {\n const out: ClerkUserRecord[] = [];\n for (let offset = 0; ; offset += PAGE) {\n const data = await clerkGet(`/v1/users?limit=${PAGE}&offset=${offset}`, secretKey, fetchImpl);\n const page = Array.isArray(data) ? (data as ClerkApiUser[]) : [];\n for (const u of page) {\n const record = toRecord(u);\n if (record) out.push(record);\n }\n if (page.length < PAGE) break;\n }\n return out;\n}\n\n/** Write a user's role: a MERGE-PATCH of only `{ role }` on `public_metadata`, so\n * it leaves a separately-written `profile` untouched. Returns whether it stuck. */\nexport async function clerkSetRole(secretKey: string, id: string, role: string, fetchImpl: typeof fetch = fetch): Promise<boolean> {\n const res = await fetchImpl(`${CLERK_API}/v1/users/${encodeURIComponent(id)}/metadata`, {\n method: \"PATCH\",\n headers: { authorization: `Bearer ${secretKey}`, \"content-type\": \"application/json\" },\n body: JSON.stringify({ public_metadata: { role } }),\n });\n return res.ok;\n}\n","// The OPERATIONAL slice of the one-way person projection: applications + $users\n// -> crm_record, mirroring pipeline stage, a billing snapshot, and the Clerk\n// identity link. `network.ts` projects identity/contact on submit; this adds the\n// operational state the admin surface and the hub read from, so the pipeline\n// stays authoritative in `applications.status` while the CRM carries one\n// relationship surface over the person. Fired AFTER the authoritative write and\n// wrapped in `.catch` at every call site: a CRM hiccup never 5xxs a lifecycle op.\n//\n// Idempotent by construction — every sync resolves the person by lowercased\n// primary email first, so re-running (including the backfill route) updates in\n// place. Generalized from the reference site: the field set is the site's\n// configured `crmFields`, not a hardcoded list.\nimport { createRecord, updateRecord, setStage, linkIdentity } from \"@odla-ai/crm\";\nimport { sharedPersonInput } from \"./network\";\nimport type { ProjectionDeps } from \"./network\";\nimport type { Chapter } from \"./types\";\n\nconst str = (v: unknown): string => (typeof v === \"string\" ? v : v == null ? \"\" : String(v));\n\n/** The crm `person` input for one application row: the built-in identity/contact\n * fields plus each configured `crmFields` value present on the row. */\nexport function personInputFromApp(chapter: Chapter, app: Record<string, unknown>): Record<string, unknown> {\n const input = sharedPersonInput({\n email: str(app.email),\n firstName: str(app.firstName) || undefined,\n lastName: str(app.lastName) || undefined,\n phone: str(app.phone) || undefined,\n linkedin: str(app.linkedin) || undefined,\n hubRecordId: str(app.id),\n });\n for (const f of chapter.application.crmFields) {\n if (app[f] !== undefined) input[f] = app[f];\n }\n if (app.id !== undefined) input.applicationId = str(app.id);\n return input;\n}\n\n// Promoted billing-facet columns derived from the application's Stripe fields +\n// status. Written directly (not through createRecord/updateRecord, which never\n// touch promoted columns), so they never clobber the person input.\nfunction billingColumns(app: Record<string, unknown>): Record<string, unknown> {\n const status = str(app.status);\n const paid = Boolean(app.stripeSubscriptionId) && status !== \"refunded\";\n const billingStatus = status === \"refunded\" ? \"refunded\" : app.canceled === true ? \"canceled\" : paid ? \"active\" : \"none\";\n const cols: Record<string, unknown> = { billingStatus };\n if (app.stripeCustomerId) cols.stripeCustomerId = str(app.stripeCustomerId);\n if (app.stripeSubscriptionId) cols.subscriptionId = str(app.stripeSubscriptionId);\n if (typeof app.renewalAt === \"number\") cols.renewalAt = app.renewalAt;\n return cols;\n}\n\n/** Upsert the person record for one application (or a synthetic `{ email,\n * firstName }` account row) and mirror its stage, billing snapshot, and Clerk\n * identity. `stage` is the `applications.status` to mirror — omit for\n * account-only rows not in the pipeline. Throws on failure (the backfill route\n * counts; the operational call sites wrap in `.catch`). */\nexport async function syncApplicationToCrm(\n deps: ProjectionDeps & { chapter: Chapter },\n opts: { app: Record<string, unknown>; stage?: string },\n): Promise<string | null> {\n const emailKey = str(opts.app.email).toLowerCase();\n if (!emailKey) return null;\n const crmDeps = { crm: deps.crm, db: deps.db as never, now: deps.now, newId: deps.newId };\n const input = personInputFromApp(deps.chapter, opts.app);\n\n const { crm_record } = await deps.db.query({\n crm_record: { $: { where: { type: \"person\", primaryEmail: emailKey }, limit: 1 } },\n });\n const existing = crm_record?.[0] ?? null;\n const stage = opts.stage || undefined;\n\n let recordId: string;\n if (existing && typeof existing.id === \"string\") {\n recordId = existing.id;\n await updateRecord(crmDeps, { id: recordId, input });\n } else {\n const created = await createRecord(crmDeps, { type: \"person\", input, ...(stage ? { stage } : {}) });\n recordId = created.id;\n }\n\n // Stage mirror: move only on an actual change, under a stable mutationId so a\n // replay never piles up duplicate stage_change activities. Best-effort — a\n // stage not on the crm person type must not fail the whole sync.\n if (existing && stage && existing.stage !== stage) {\n await setStage(crmDeps, { id: recordId, to: stage, authorId: \"system\", mutationId: `crm:stage:${recordId}:${stage}` }).catch(() => undefined);\n }\n\n await deps.db.transact([{ t: \"update\", ns: \"crm_record\", id: recordId, attrs: billingColumns(opts.app) }]);\n\n // Identity link: stamps clerkUserId when a $users row matches the email; a\n // no-op until the person has an account. Best-effort — a just-created record\n // can briefly lag the read, and the link retries on the next sync.\n await linkIdentity(crmDeps, { recordId, email: emailKey, mutationId: `crm:link:${recordId}:${emailKey}` }).catch(() => undefined);\n\n return recordId;\n}\n\n/** Backfill / repair: project every application (newest per person) and every\n * account-only `$users` row into the CRM. Idempotent (safe to re-run). Dev\n * volumes fit one 1000-row page. Returns `{ synced, errors }`. */\nexport async function backfillCrm(deps: ProjectionDeps & { chapter: Chapter }): Promise<{ synced: number; errors: Array<{ email: string; error: string }> }> {\n const [appsRes, usersRes] = await Promise.all([\n deps.db.query({ applications: { $: { order: { createdAt: \"desc\" }, limit: 1000 } } }),\n deps.db.query({ $users: { $: { limit: 1000 } } }),\n ]);\n const seen = new Set<string>();\n let synced = 0;\n const errors: Array<{ email: string; error: string }> = [];\n\n const run = async (app: Record<string, unknown>, stage?: string): Promise<void> => {\n const key = str(app.email).toLowerCase();\n if (!key || seen.has(key)) return; // newest-first: one record per person\n seen.add(key);\n try {\n await syncApplicationToCrm(deps, { app, stage });\n synced += 1;\n } catch (err) {\n errors.push({ email: key, error: err instanceof Error ? err.message : String(err) });\n }\n };\n\n for (const a of (appsRes.applications ?? []) as Array<Record<string, unknown>>) await run(a, str(a.status));\n for (const u of (usersRes.$users ?? []) as Array<Record<string, unknown>>) {\n if (u.deleted === true) continue;\n await run({ email: u.email, firstName: str(u.name) });\n }\n return { synced, errors };\n}\n","// Admin roster + identity routes: the union people list, one person's access,\n// role changes, and the CRM backfill. Role changes wire chapter's package-\n// enforced canChangeRole guard (super-admin tier + self-demotion lockout) rather\n// than re-deriving the rules per site. All admin-gated.\nimport { canChangeRole, getVaultSecret } from \"./auth\";\nimport { clerkGetUser, clerkListUsers, clerkSetRole } from \"./clerk-roles\";\nimport { backfillCrm } from \"./crm-sync\";\nimport { applicationSummary } from \"./session\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, WorkerContext } from \"./worker-context\";\nimport type { Route } from \"./worker-routes\";\nimport type { ChapterDb } from \"./types\";\n\n// Gate + shape the verified admin identity. Returns { db, actor } or a Response.\nasync function adminGate(\n req: Request,\n env: ChapterEnv,\n ctx: WorkerContext,\n): Promise<{ db: ChapterDb; actor: { userId: string; email?: string } } | Response> {\n const rawDb = ctx.makeDb(env);\n const u = await ctx.verifyUser(req, env);\n if (!u) return json({ error: \"unauthorized\" }, 401);\n if (!(await ctx.isAdmin(rawDb, u))) return json({ error: \"forbidden\" }, 403);\n return { db: rawDb as unknown as ChapterDb, actor: { userId: u.userId, email: u.email ?? undefined } };\n}\n\nconst crmDeps = (db: ChapterDb, ctx: WorkerContext) => ({\n crm: ctx.chapter.crm,\n db,\n now: () => Date.now(),\n newId: () => crypto.randomUUID(),\n chapter: ctx.chapter,\n});\n\n/** POST /api/admin/crm/sync — backfill/reproject every person into the CRM.\n * Idempotent by email, so it doubles as migration and repair. */\nexport const handleAdminCrmSync: Route = async (req, url, env, ctx) => {\n if (req.method !== \"POST\" || url.pathname !== \"/api/admin/crm/sync\") return null;\n const gate = await adminGate(req, env, ctx);\n if (gate instanceof Response) return gate;\n const result = await backfillCrm(crmDeps(gate.db, ctx));\n return json({ ok: true, ...result });\n};\n\n/** GET /api/admin/people — one row per person, joined by lowercased email: the\n * `$users` mirror (accounts), applications (pipeline), and Clerk roles.\n * Applications first (newest on top), account-only rows after. */\nexport const handleAdminPeople: Route = async (req, url, env, ctx) => {\n if (req.method !== \"GET\" || url.pathname !== \"/api/admin/people\") return null;\n const gate = await adminGate(req, env, ctx);\n if (gate instanceof Response) return gate;\n const { db } = gate;\n\n const sk = await getVaultSecret(db, \"clerk_secret_key\");\n const [appsRes, usersRes, roleList] = await Promise.all([\n db.query({ applications: { $: { order: { createdAt: \"desc\" }, limit: 200 } } }),\n db.query({ $users: { $: { limit: 200 } } }),\n sk ? clerkListUsers(sk).catch(() => []) : Promise.resolve([]),\n ]);\n const roleByUserId = new Map(roleList.map((u) => [u.id, u.role]));\n\n type PersonRow = { email: string; name: string; userId: string | null; role: string | null; application: ReturnType<typeof applicationSummary> | null };\n const people = new Map<string, PersonRow>();\n\n for (const u of (usersRes.$users ?? []) as Array<Record<string, unknown>>) {\n if (u.deleted === true) continue; // tombstoned Clerk users are not accounts\n const email = typeof u.email === \"string\" ? u.email : \"\";\n if (!email) continue;\n people.set(email.toLowerCase(), {\n email,\n name: typeof u.name === \"string\" ? u.name : \"\",\n userId: typeof u.id === \"string\" ? u.id : null,\n role: roleByUserId.get(String(u.id)) ?? \"provisional\",\n application: null,\n });\n }\n for (const a of (appsRes.applications ?? []) as Array<Record<string, unknown>>) {\n const key = String(a.email ?? \"\").toLowerCase();\n if (!key) continue;\n const name = `${a.firstName ?? \"\"} ${a.lastName ?? \"\"}`.trim();\n const row = people.get(key);\n if (row) {\n if (!row.application) row.application = applicationSummary(a as unknown as Parameters<typeof applicationSummary>[0]); // newest-first: keep the latest\n if (!row.name) row.name = name;\n } else {\n people.set(key, { email: String(a.email), name, userId: null, role: null, application: applicationSummary(a as unknown as Parameters<typeof applicationSummary>[0]) });\n }\n }\n const rows = [...people.values()].sort(\n (x, y) => ((y.application?.createdAt as number) ?? -1) - ((x.application?.createdAt as number) ?? -1),\n );\n return json({ people: rows });\n};\n\n/** GET /api/admin/people/access?userId= — a person's Clerk role + super-admin\n * flag, for the record panel's Access card. */\nexport const handleAdminPeopleAccess: Route = async (req, url, env, ctx) => {\n if (req.method !== \"GET\" || url.pathname !== \"/api/admin/people/access\") return null;\n const gate = await adminGate(req, env, ctx);\n if (gate instanceof Response) return gate;\n const { db } = gate;\n const targetId = url.searchParams.get(\"userId\") ?? \"\";\n if (!targetId.startsWith(\"user_\")) return json({ error: \"invalid userId\" }, 400);\n const sk = await getVaultSecret(db, \"clerk_secret_key\");\n if (!sk) return json({ error: \"role management unavailable: clerk_secret_key missing from vault\" }, 503);\n const info = await clerkGetUser(sk, targetId);\n if (!info) return json({ error: \"user lookup unavailable\" }, 502);\n return json({ userId: targetId, role: info.role, email: info.email ?? null, superAdmin: await ctx.isSuperAdminEmail(db as never, info.email) });\n};\n\n/** POST /api/admin/people/role — change a person's Clerk role. The escalation\n * rules (super-admin tier, self-demotion lockout) are enforced by chapter's\n * canChangeRole, not re-derived here. */\nexport const handleAdminPeopleRole: Route = async (req, url, env, ctx) => {\n if (req.method !== \"POST\" || url.pathname !== \"/api/admin/people/role\") return null;\n const gate = await adminGate(req, env, ctx);\n if (gate instanceof Response) return gate;\n const { db, actor } = gate;\n\n let body: Record<string, unknown>;\n try {\n body = (await req.json()) as Record<string, unknown>;\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n const targetId = typeof body.userId === \"string\" ? body.userId : \"\";\n const newRole = typeof body.role === \"string\" ? body.role : \"\";\n if (!targetId.startsWith(\"user_\")) return json({ error: \"invalid userId\" }, 400);\n\n const sk = await getVaultSecret(db, \"clerk_secret_key\");\n if (!sk) return json({ error: \"role management unavailable: clerk_secret_key missing from vault\" }, 503);\n const target = await clerkGetUser(sk, targetId);\n\n const guard = canChangeRole({\n actorId: actor.userId,\n actorIsSuper: await ctx.isSuperAdminEmail(db as never, actor.email),\n targetId,\n targetCurrentRole: target?.role ?? \"provisional\",\n targetIsSuper: await ctx.isSuperAdminEmail(db as never, target?.email),\n newRole,\n auth: ctx.chapter.auth,\n });\n if (!guard.ok) return json({ error: guard.error }, guard.status);\n\n if (!(await clerkSetRole(sk, targetId, newRole))) return json({ error: \"role update failed upstream\" }, 502);\n return json({ ok: true });\n};\n","// Pure aggregation helpers for the admin dashboard: a weekly time-series bucketer\n// and the annualized-run-rate math for a Stripe subscription. Kept out of the\n// route so both dashboard and billing share one definition and it is unit-tested\n// without a network call.\n\n/** Bucket `{ t, v }` points into the last `weeks` weekly buckets ending at `now`\n * (epoch ms), summing `v` per bucket. Returns oldest→newest `{ weekStart, value\n * }`, so a caller renders a sparkline directly. Points outside the window are\n * ignored. */\nexport function bucketSeries(\n points: Array<{ t: number; v: number }>,\n now: number,\n weeks = 12,\n): Array<{ weekStart: number; value: number }> {\n const WEEK = 7 * 86_400_000;\n const end = now;\n const start = end - weeks * WEEK;\n const buckets = Array.from({ length: weeks }, (_, i) => ({ weekStart: start + i * WEEK, value: 0 }));\n for (const p of points) {\n if (!Number.isFinite(p.t) || p.t < start || p.t > end) continue;\n const idx = Math.min(weeks - 1, Math.floor((p.t - start) / WEEK));\n const bucket = buckets[idx];\n if (bucket) bucket.value += Number.isFinite(p.v) ? p.v : 0;\n }\n return buckets;\n}\n\n/** Labels and current/previous values for one dashboard comparison window. */\nexport interface DashboardMetricSeries {\n labels: string[];\n current: number[];\n previous: number[];\n}\n\n/** Week-over-week and month-over-month series consumed by MetricWidget. */\nexport interface DashboardMetricData {\n wow: DashboardMetricSeries;\n mom: DashboardMetricSeries;\n}\n\nfunction periodSeries(\n points: Array<{ t: number; v: number }>,\n now: number,\n count: number,\n periodMs: number,\n): DashboardMetricSeries {\n const start = now - count * periodMs;\n const previousStart = start - count * periodMs;\n const current = Array.from({ length: count }, () => 0);\n const previous = Array.from({ length: count }, () => 0);\n for (const point of points) {\n if (!Number.isFinite(point.t) || !Number.isFinite(point.v)) continue;\n if (point.t >= start && point.t <= now) {\n const index = Math.min(count - 1, Math.floor((point.t - start) / periodMs));\n current[index] = (current[index] ?? 0) + point.v;\n } else if (point.t >= previousStart && point.t < start) {\n const index = Math.min(count - 1, Math.floor((point.t - previousStart) / periodMs));\n previous[index] = (previous[index] ?? 0) + point.v;\n }\n }\n const labels = current.map((_, index) =>\n new Date(start + index * periodMs).toISOString().slice(5, 10));\n return { labels, current, previous };\n}\n\n/** MetricWidget-ready daily and weekly comparison windows. */\nexport function dashboardMetricData(\n points: Array<{ t: number; v: number }>,\n now: number,\n): DashboardMetricData {\n const DAY = 86_400_000;\n return {\n wow: periodSeries(points, now, 7, DAY),\n mom: periodSeries(points, now, 4, 7 * DAY),\n };\n}\n\n/** Annualized cents for a Stripe subscription: sum each item's\n * `unit_amount * quantity`, ×12 for monthly intervals. A yearly interval is\n * taken as-is. Returns 0 for a shape with no priced items. */\nexport function subAnnualCents(sub: Record<string, unknown>): number {\n const items = ((sub.items as { data?: Array<Record<string, unknown>> } | undefined)?.data ?? []);\n let cents = 0;\n for (const it of items) {\n const price = (it.price ?? {}) as { unit_amount?: number; recurring?: { interval?: string } };\n const per = (price.unit_amount ?? 0) * ((it.quantity as number) ?? 1);\n cents += price.recurring?.interval === \"month\" ? per * 12 : per;\n }\n return cents;\n}\n","// Admin aggregation routes: the dashboard overview and the billing table. Both\n// join db rows with live Stripe reads (Stripe is the source of truth for money),\n// keyed by the vault stripe_secret_key, and degrade to `billingReady: false`\n// when no key is vaulted — so a hub that runs no membership billing simply drops\n// the section. Admin-gated.\nimport { getVaultSecret } from \"./auth\";\nimport { stripeCall } from \"./payments-stripe\";\nimport { resolveScheduling } from \"./scheduling\";\nimport { dashboardMetricData, subAnnualCents } from \"./series\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, WorkerContext } from \"./worker-context\";\nimport type { Route } from \"./worker-routes\";\nimport type { ChapterDb, ChapterScheduling } from \"./types\";\n\nasync function gate(req: Request, env: ChapterEnv, ctx: WorkerContext): Promise<ChapterDb | Response> {\n const rawDb = ctx.makeDb(env);\n const u = await ctx.verifyUser(req, env);\n if (!u) return json({ error: \"unauthorized\" }, 401);\n if (!(await ctx.isAdmin(rawDb, u))) return json({ error: \"forbidden\" }, 403);\n return rawDb as unknown as ChapterDb;\n}\n\nconst rows = <T = Record<string, unknown>>(v: unknown): T[] => (Array.isArray(v) ? (v as T[]) : []);\n\n/** GET /api/admin/dashboard — application flow counts, pipeline stage counts +\n * weekly delta, the upcoming call agenda, and (when billing is wired) live\n * revenue series. One call powers the overview. */\nexport const handleAdminDashboard: Route = async (req, url, env, ctx) => {\n if (req.method !== \"GET\" || url.pathname !== \"/api/admin/dashboard\") return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n\n const now = Date.now();\n const d7 = now - 7 * 86_400_000;\n const d30 = now - 30 * 86_400_000;\n const [appsRes, meetingsRes, recsRes, groupRes] = await Promise.all([\n db.query({ applications: { $: { order: { createdAt: \"desc\" }, limit: 1000 } } }),\n db.query({ meetings: { $: { where: { status: \"scheduled\" }, order: { startAt: \"asc\" }, limit: 500 } } }),\n db.query({ crm_record: { $: { where: { type: \"person\" }, limit: 1000 } } }),\n db.query({ groups: { $: { where: { id: ctx.chapter.id }, limit: 1 } } }),\n ]);\n const apps = rows(appsRes.applications);\n const applications = {\n total: apps.length,\n last7: apps.filter((a) => (a.createdAt as number) >= d7).length,\n last30: apps.filter((a) => (a.createdAt as number) >= d30).length,\n };\n const pipeline: Record<string, number> = {};\n const pipelineDelta: Record<string, number> = {};\n for (const s of ctx.chapter.pipeline.stages) {\n pipeline[s] = 0;\n pipelineDelta[s] = 0;\n }\n for (const r of rows(recsRes.crm_record)) {\n const s = r.stage as string;\n if (s in pipeline) {\n pipeline[s] = (pipeline[s] ?? 0) + 1;\n const sc = typeof r.stageChangedAt === \"number\" ? r.stageChangedAt : Date.parse(String(r.stageChangedAt));\n if (Number.isFinite(sc) && sc >= d7) pipelineDelta[s] = (pipelineDelta[s] ?? 0) + 1;\n }\n }\n\n const meetings = rows(meetingsRes.meetings);\n const appById = new Map(apps.map((a) => [a.id, a]));\n const upcoming = meetings.filter((m) => (m.startAt as number) >= now - 3_600_000);\n const calls = { upcoming: upcoming.length, needsAttention: meetings.filter((m) => m.drift && m.drift !== \"none\").length };\n const agenda = upcoming.slice(0, 8).map((m) => {\n const a = appById.get(m.applicationId);\n return {\n id: m.id,\n startAt: m.startAt,\n meetUrl: m.meetUrl ?? null,\n htmlLink: m.htmlLink ?? null,\n drift: m.drift ?? \"none\",\n name: a ? `${a.firstName} ${a.lastName}` : \"(unknown)\",\n email: (a?.email as string) ?? null,\n };\n });\n const group = groupRes.groups?.[0];\n const timezone = resolveScheduling(group?.schedulingJson as ChapterScheduling | undefined).timezone;\n\n let revenue: Record<string, unknown> = { billingReady: false };\n let revenueSeries: unknown = null;\n let membersSeries: unknown = null;\n const sk = await getVaultSecret(db, \"stripe_secret_key\");\n if (sk) {\n const subsRes = await stripeCall(sk, \"GET\", \"/v1/subscriptions\", { limit: 100, status: \"all\" });\n if (subsRes.ok) {\n const subs = rows(subsRes.body.data);\n const subMs = (s: Record<string, unknown>) => ((s.created as number) ?? 0) * 1000;\n membersSeries = dashboardMetricData(subs.map((s) => ({ t: subMs(s), v: 1 })), now);\n revenueSeries = dashboardMetricData(subs.map((s) => ({ t: subMs(s), v: subAnnualCents(s) })), now);\n const active = subs.filter((s) => s.status === \"active\");\n revenue = {\n billingReady: true,\n testMode: String(group?.stripePublishableKey ?? \"\").startsWith(\"pk_test\"),\n activeCount: active.length,\n annualRunRateCents: active.reduce((sum, s) => sum + subAnnualCents(s), 0),\n newPaid7: subs.filter((s) => subMs(s) >= d7).length,\n newPaid30: subs.filter((s) => subMs(s) >= d30).length,\n };\n }\n }\n const applicationsSeries = dashboardMetricData(apps.map((a) => ({ t: (a.createdAt as number) || 0, v: 1 })), now);\n return json({ applications, applicationsSeries, pipeline, pipelineDelta, calls, agenda, timezone, revenue, revenueSeries, membersSeries });\n};\n\ninterface SubItem {\n price?: { unit_amount?: number; recurring?: { interval?: string } };\n quantity?: number;\n current_period_end?: number;\n}\n\n/** GET /api/admin/billing — applications joined with live Stripe subscription\n * state. `truncated` flags a >100-subscription page instead of silently losing\n * rows. `billingReady: false` when no stripe_secret_key is vaulted. */\nexport const handleAdminBilling: Route = async (req, url, env, ctx) => {\n if (req.method !== \"GET\" || url.pathname !== \"/api/admin/billing\") return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n\n const sk = await getVaultSecret(db, \"stripe_secret_key\");\n if (!sk) return json({ billingReady: false, rows: [], summary: null });\n const [appsRes, subsRes, groupRes] = await Promise.all([\n db.query({ applications: { $: { order: { createdAt: \"desc\" }, limit: 200 } } }),\n stripeCall(sk, \"GET\", \"/v1/subscriptions\", { limit: 100, status: \"all\" }),\n db.query({ groups: { $: { where: { id: ctx.chapter.id }, limit: 1 } } }),\n ]);\n const testMode = String(groupRes.groups?.[0]?.stripePublishableKey ?? \"\").startsWith(\"pk_test\");\n if (!subsRes.ok) return json({ error: \"billing lookup failed upstream\" }, 502);\n const subById = new Map(rows(subsRes.body.data).map((s) => [s.id as string, s]));\n\n const billingRows = [];\n for (const a of rows(appsRes.applications)) {\n if (!a.stripeCustomerId && !a.stripeSubscriptionId) continue;\n const sub = a.stripeSubscriptionId ? subById.get(a.stripeSubscriptionId as string) : undefined;\n const items = (sub?.items as { data?: SubItem[] } | undefined)?.data ?? [];\n let amountCents = 0;\n let interval = \"year\";\n for (const it of items) {\n amountCents += (it.price?.unit_amount ?? 0) * (it.quantity ?? 1);\n interval = it.price?.recurring?.interval ?? interval;\n }\n const periodEnd = (sub?.current_period_end as number | undefined) ?? items[0]?.current_period_end;\n billingRows.push({\n id: a.id as string,\n name: `${a.firstName} ${a.lastName}`,\n email: a.email as string,\n applicationStatus: a.status as string,\n subscriptionStatus: (sub?.status as string) ?? null,\n cancelAtPeriodEnd: sub?.cancel_at_period_end === true,\n amountCents,\n interval,\n renewalAt: periodEnd ? periodEnd * 1000 : ((a.renewalAt as number) ?? null),\n });\n }\n const renewing = billingRows.filter((r) => r.subscriptionStatus === \"active\" && !r.cancelAtPeriodEnd);\n const soonCutoff = Date.now() + 60 * 86_400_000;\n const summary = {\n activeCount: billingRows.filter((r) => r.subscriptionStatus === \"active\").length,\n annualizedCents: renewing.reduce((s, r) => s + r.amountCents * (r.interval === \"month\" ? 12 : 1), 0),\n renewingSoonCount: renewing.filter((r) => r.renewalAt && r.renewalAt < soonCutoff).length,\n pastDueCount: billingRows.filter((r) => r.subscriptionStatus === \"past_due\").length,\n canceledCount: billingRows.filter((r) => r.subscriptionStatus === \"canceled\" || r.cancelAtPeriodEnd).length,\n refundedCount: billingRows.filter((r) => r.applicationStatus === \"refunded\").length,\n };\n return json({\n billingReady: true,\n testMode,\n truncated: subsRes.body.has_more === true,\n rows: billingRows,\n summary,\n });\n};\n","// Admin lifecycle routes: meeting reschedule/cancel and application\n// approve/refund/manual-patch. These are the operational actions; each wires a\n// chapter primitive (canApprove, meetingRescheduleUpdate, refundedPatch) and the\n// operations policy seams (onApprove.promoteTo/send, refund.allowedFrom/\n// cancelSubscription), and mirrors the change into the CRM. Admin-gated.\nimport { computeBookableSlots, initCalendar } from \"@odla-ai/calendar\";\nimport { getVaultSecret } from \"./auth\";\nimport { clerkGetUserByEmail, clerkSetRole } from \"./clerk-roles\";\nimport { syncApplicationToCrm } from \"./crm-sync\";\nimport { sendTemplated, emailGroupFrom } from \"./notify\";\nimport { stripeCall } from \"./payments-stripe\";\nimport { canApprove } from \"./pipeline\";\nimport { canTransition } from \"./pipeline\";\nimport { resolveScheduling, endForSlot, isSlotAvailable, meetingRescheduleUpdate, slotWindow } from \"./scheduling\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, WorkerContext } from \"./worker-context\";\nimport type { Route } from \"./worker-routes\";\nimport type { ChapterDb, ChapterScheduling } from \"./types\";\n\nasync function gate(req: Request, env: ChapterEnv, ctx: WorkerContext): Promise<ChapterDb | Response> {\n const rawDb = ctx.makeDb(env);\n const u = await ctx.verifyUser(req, env);\n if (!u) return json({ error: \"unauthorized\" }, 401);\n if (!(await ctx.isAdmin(rawDb, u))) return json({ error: \"forbidden\" }, 403);\n return rawDb as unknown as ChapterDb;\n}\n\nconst calFor = (env: ChapterEnv) =>\n initCalendar({ appId: env.ODLA_APP_ID, env: env.ODLA_ENV, adminToken: env.ODLA_API_KEY, endpoint: env.ODLA_PLATFORM });\nconst crmDeps = (db: ChapterDb, ctx: WorkerContext) => ({ crm: ctx.chapter.crm, db, now: () => Date.now(), newId: () => crypto.randomUUID(), chapter: ctx.chapter });\nconst readJson = async (req: Request): Promise<Record<string, unknown> | null> => {\n try {\n return (await req.json()) as Record<string, unknown>;\n } catch {\n return null;\n }\n};\nasync function loadApp(db: ChapterDb, id: string): Promise<Record<string, unknown> | null> {\n const { applications } = await db.query({ applications: { $: { where: { id }, limit: 1 } } });\n return applications?.[0] ?? null;\n}\nasync function loadGroup(db: ChapterDb, id: string): Promise<Record<string, unknown> | null> {\n const { groups } = await db.query({ groups: { $: { where: { id }, limit: 1 } } });\n return groups?.[0] ?? null;\n}\n\n/** POST /api/admin/meetings/:id/reschedule — move an intro call to an open slot;\n * the Google event moves (Meet link + invite thread survive). */\nexport const handleAdminMeetingReschedule: Route = async (req, url, env, ctx) => {\n const m = url.pathname.match(/^\\/api\\/admin\\/meetings\\/([0-9a-f-]+)\\/reschedule$/);\n if (req.method !== \"POST\" || !m) return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n const body = await readJson(req);\n const startAt = Number(body?.startAt);\n if (!Number.isFinite(startAt)) return json({ error: \"startAt required\" }, 400);\n\n const { meetings } = await db.query({ meetings: { $: { where: { id: m[1] }, limit: 1 } } });\n const meeting = meetings?.[0];\n if (!meeting) return json({ error: \"not found\" }, 404);\n if (meeting.status !== \"scheduled\") return json({ error: \"meeting is cancelled\" }, 409);\n if (!meeting.googleEventId) return json({ error: \"no calendar event on file\" }, 409);\n\n const cfg = resolveScheduling((await loadGroup(db, String(meeting.groupId ?? ctx.chapter.id)))?.schedulingJson as ChapterScheduling | undefined);\n const endAt = endForSlot(startAt, cfg.slotMinutes);\n const cal = calFor(env);\n try {\n const { from, to } = slotWindow(Date.now(), cfg.windowDays);\n const fb = await cal.availability.freeBusy({ timeMin: from, timeMax: to });\n const slots = computeBookableSlots(fb.busy, {\n from: fb.timeMin,\n to: fb.timeMax,\n timezone: cfg.timezone,\n slotMinutes: cfg.slotMinutes,\n businessHours: { days: [...cfg.days], startHour: cfg.startHour, endHour: cfg.endHour },\n minNoticeMs: cfg.minNoticeHours * 3_600_000,\n });\n if (!isSlotAvailable(slots, startAt)) return json({ error: \"slot no longer available\", code: \"calendar_slot_unavailable\" }, 409);\n await cal.actions.reschedule(String(meeting.googleEventId), { startAt, endAt });\n } catch {\n return json({ error: \"reschedule failed upstream\" }, 502);\n }\n await db.transact([{ t: \"update\", ns: \"meetings\", id: String(meeting.id), attrs: meetingRescheduleUpdate(startAt, endAt) }]);\n await db.transact([{ t: \"update\", ns: \"applications\", id: String(meeting.applicationId), attrs: { meetingAt: startAt } }]);\n return json({ ok: true, startAt, endAt });\n};\n\n/** POST /api/admin/meetings/:id/cancel — cancel an intro call; the Google event\n * is removed (Google notifies the attendee). */\nexport const handleAdminMeetingCancel: Route = async (req, url, env, ctx) => {\n const m = url.pathname.match(/^\\/api\\/admin\\/meetings\\/([0-9a-f-]+)\\/cancel$/);\n if (req.method !== \"POST\" || !m) return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n\n const { meetings } = await db.query({ meetings: { $: { where: { id: m[1] }, limit: 1 } } });\n const meeting = meetings?.[0];\n if (!meeting) return json({ error: \"not found\" }, 404);\n if (meeting.status !== \"scheduled\") return json({ error: \"already cancelled\" }, 409);\n if (meeting.googleEventId) {\n try {\n await calFor(env).actions.cancel(String(meeting.googleEventId));\n } catch {\n return json({ error: \"cancel failed upstream\" }, 502);\n }\n }\n await db.transact([{ t: \"update\", ns: \"meetings\", id: String(meeting.id), attrs: { status: \"cancelled\", drift: \"none\" } }]);\n await db.transact([{ t: \"update\", ns: \"applications\", id: String(meeting.applicationId), attrs: { meetingAt: 0, meetingLink: \"\" } }]);\n return json({ ok: true });\n};\n\n/** POST /api/admin/applications/:id/approve — the deliberate approval: advance to\n * the approvable target, promote the Clerk role (operations.onApprove.promoteTo),\n * and send the approve template (operations.onApprove.send). Mirrors to CRM. */\nexport const handleAdminApprove: Route = async (req, url, env, ctx) => {\n const m = url.pathname.match(/^\\/api\\/admin\\/applications\\/([0-9a-f-]+)\\/approve$/);\n if (req.method !== \"POST\" || !m) return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n const id = m[1] as string;\n\n const app = await loadApp(db, id);\n if (!app) return json({ error: \"not found\" }, 404);\n if (!canApprove(String(app.status), ctx.chapter.pipeline)) return json({ error: `cannot approve from status \"${String(app.status)}\"` }, 409);\n const target = \"approved\";\n\n await db.transact([{ t: \"update\", ns: \"applications\", id, attrs: { status: target } }]);\n await syncApplicationToCrm(crmDeps(db, ctx), { app: { ...app, status: target }, stage: target }).catch(() => undefined);\n\n const { promoteTo, send } = ctx.chapter.operations.onApprove;\n let rolePromoted = false;\n const sk = await getVaultSecret(db, \"clerk_secret_key\");\n if (promoteTo !== false && sk) {\n let userId = (app.clerkUserId as string) || null;\n if (!userId) {\n const found = await clerkGetUserByEmail(sk, String(app.email));\n userId = found?.id ?? null;\n if (userId) await db.transact([{ t: \"update\", ns: \"applications\", id, attrs: { clerkUserId: userId } }]);\n }\n if (userId) rolePromoted = await clerkSetRole(sk, userId, promoteTo);\n }\n\n let emailLogged = false;\n const group = await loadGroup(db, String(app.groupId ?? ctx.chapter.id));\n if (send !== false && group) {\n const res = await sendTemplated(\n { db, envName: env.ODLA_ENV, sender: env.SEND_EMAIL, from: env.EMAIL_FROM, now: () => Date.now(), newId: () => crypto.randomUUID() },\n { group: emailGroupFrom(group), template: send, to: String(app.email), vars: { firstName: String(app.firstName ?? \"\"), membersUrl: `${url.origin}/members/` }, applicationId: id, dedupeKey: `approve:${id}` },\n );\n emailLogged = res.sent;\n }\n return json({ ok: true, status: target, rolePromoted, emailLogged });\n};\n\n/** POST /api/admin/applications/:id/refund — refund the first paid charge and\n * (per operations.refund) cancel the subscription. The status flip to \"refunded\"\n * comes from the charge.refunded webhook, so Stripe stays the source of truth. */\nexport const handleAdminRefund: Route = async (req, url, env, ctx) => {\n const m = url.pathname.match(/^\\/api\\/admin\\/applications\\/([0-9a-f-]+)\\/refund$/);\n if (req.method !== \"POST\" || !m) return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n\n const app = await loadApp(db, m[1] as string);\n if (!app) return json({ error: \"not found\" }, 404);\n if (app.status === \"refunded\") return json({ error: \"already refunded\" }, 409);\n const allowedFrom = ctx.chapter.operations.refund.allowedFrom;\n if (allowedFrom && !allowedFrom.includes(String(app.status))) {\n return json({ error: `cannot refund from status \"${String(app.status)}\"` }, 409);\n }\n const subscriptionId = app.stripeSubscriptionId as string | undefined;\n const customerId = app.stripeCustomerId as string | undefined;\n if (!customerId) return json({ error: \"no customer on file\" }, 409);\n const sk = await getVaultSecret(db, \"stripe_secret_key\");\n if (!sk) return json({ error: \"payments not configured\" }, 503);\n\n const charges = await stripeCall(sk, \"GET\", \"/v1/charges\", { customer: customerId, limit: 100 });\n if (!charges.ok) return json({ error: \"refund failed upstream\" }, 502);\n const succeeded = ((charges.body.data as Array<Record<string, unknown>>) ?? []).filter((c) => c.status === \"succeeded\" && c.refunded !== true);\n const firstCharge = succeeded[succeeded.length - 1];\n if (!firstCharge) return json({ error: \"no paid charge to refund\" }, 409);\n\n const refund = await stripeCall(sk, \"POST\", \"/v1/refunds\", { charge: String(firstCharge.id) });\n if (!refund.ok) return json({ error: \"refund failed upstream\" }, 502);\n let subscriptionCanceled = false;\n if (ctx.chapter.operations.refund.cancelSubscription && subscriptionId) {\n const cancel = await stripeCall(sk, \"DELETE\", `/v1/subscriptions/${subscriptionId}`);\n subscriptionCanceled = cancel.ok;\n }\n return json({ ok: true, refundedCents: (refund.body.amount as number) ?? null, subscriptionCanceled });\n};\n\n/** PATCH /api/admin/applications/:id — manual correction escape hatch. Sets\n * `status` (gated by canTransition) and/or `meetingAt`. Mirrors a status move to\n * the CRM. */\nexport const handleAdminApplicationPatch: Route = async (req, url, env, ctx) => {\n const m = url.pathname.match(/^\\/api\\/admin\\/applications\\/([0-9a-f-]+)$/);\n if (req.method !== \"PATCH\" || !m) return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n const id = m[1] as string;\n const body = await readJson(req);\n if (!body) return json({ error: \"invalid JSON body\" }, 400);\n\n const app = await loadApp(db, id);\n if (!app) return json({ error: \"not found\" }, 404);\n\n const attrs: Record<string, unknown> = {};\n if (body.status !== undefined) {\n const to = String(body.status);\n if (!ctx.chapter.pipeline.stages.includes(to)) return json({ error: `status must be one of: ${ctx.chapter.pipeline.stages.join(\", \")}` }, 400);\n if (!canTransition(String(app.status), to, ctx.chapter.pipeline)) return json({ error: `cannot move from \"${String(app.status)}\" to \"${to}\"` }, 409);\n attrs.status = to;\n }\n if (body.meetingAt !== undefined) {\n if (typeof body.meetingAt !== \"number\" || !Number.isFinite(body.meetingAt)) return json({ error: \"meetingAt must be epoch milliseconds\" }, 400);\n attrs.meetingAt = body.meetingAt;\n }\n if (Object.keys(attrs).length === 0) return json({ error: \"nothing to update\" }, 400);\n\n await db.transact([{ t: \"update\", ns: \"applications\", id, attrs }]);\n if (attrs.status !== undefined) {\n await syncApplicationToCrm(crmDeps(db, ctx), { app: { ...app, ...attrs }, stage: String(attrs.status) }).catch(() => undefined);\n }\n return json({ ok: true });\n};\n","// Admin email + comms routes: read/write the group's owner-editable email config,\n// the send audit log, an owner-triggered test send, and one person's comms\n// timeline (sent lifecycle mail + the Google calendar invitations reconstructed\n// from meeting rows). Admin-gated.\nimport { renderTemplateBody } from \"./email\";\nimport { sendTemplated, emailGroupFrom, EMAIL_TEMPLATE_NAMES } from \"./notify\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, WorkerContext } from \"./worker-context\";\nimport type { Route } from \"./worker-routes\";\nimport type { ChapterDb } from \"./types\";\n\nasync function gate(req: Request, env: ChapterEnv, ctx: WorkerContext): Promise<ChapterDb | Response> {\n const rawDb = ctx.makeDb(env);\n const u = await ctx.verifyUser(req, env);\n if (!u) return json({ error: \"unauthorized\" }, 401);\n if (!(await ctx.isAdmin(rawDb, u))) return json({ error: \"forbidden\" }, 403);\n return rawDb as unknown as ChapterDb;\n}\nasync function loadGroup(db: ChapterDb, id: string): Promise<Record<string, unknown> | null> {\n const { groups } = await db.query({ groups: { $: { where: { id }, limit: 1 } } });\n return groups?.[0] ?? null;\n}\nconst str = (v: unknown, d = \"\"): string => (typeof v === \"string\" ? v : d);\nconst notifyDeps = (db: ChapterDb, env: ChapterEnv) => ({\n db,\n envName: env.ODLA_ENV,\n sender: env.SEND_EMAIL,\n from: env.EMAIL_FROM,\n now: () => Date.now(),\n newId: () => crypto.randomUUID(),\n});\n\n/** GET/PUT /api/admin/group/email — read the owner-editable email config\n * (templates + addresses + read-only delivery wiring), or replace it. */\nexport const handleAdminGroupEmail: Route = async (req, url, env, ctx) => {\n if (url.pathname !== \"/api/admin/group/email\" || (req.method !== \"GET\" && req.method !== \"PUT\")) return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n const group = await loadGroup(db, ctx.chapter.id);\n if (!group) return json({ error: \"not found\" }, 404);\n\n if (req.method === \"GET\") {\n const stored = (group.emailTemplates ?? {}) as Record<string, { subject?: string; text?: string; enabled?: boolean }>;\n const emailTemplates: Record<string, { subject: string; text: string; enabled: boolean }> = {};\n for (const key of EMAIL_TEMPLATE_NAMES) {\n const t = stored[key];\n if (t) emailTemplates[key] = { subject: str(t.subject), text: str(t.text), enabled: t.enabled !== false };\n }\n return json({\n groupId: group.id,\n name: group.name,\n replyTo: str(group.replyTo),\n notificationEmail: str(group.notificationEmail),\n debugEmail: str(group.debugEmail),\n emailTemplates,\n commitmentText: str(group.commitmentText),\n normsText: str(group.normsText),\n refundPolicyText: str(group.refundPolicyText),\n // Read-only delivery wiring — surfaced so \"why did this not send?\" is\n // answerable without logs.\n envName: env.ODLA_ENV,\n transport: env.SEND_EMAIL && env.EMAIL_FROM ? \"cloudflare\" : \"log-only\",\n fromEmail: env.EMAIL_FROM ?? null,\n });\n }\n\n let body: Record<string, unknown>;\n try {\n body = (await req.json()) as Record<string, unknown>;\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n const templates = body.emailTemplates;\n if (!templates || typeof templates !== \"object\") return json({ error: \"emailTemplates object required\" }, 400);\n const clean: Record<string, { subject: string; text: string; enabled: boolean }> = {};\n for (const key of EMAIL_TEMPLATE_NAMES) {\n const t = (templates as Record<string, { subject?: unknown; text?: unknown; enabled?: unknown }>)[key];\n const subject = typeof t?.subject === \"string\" ? t.subject.trim() : \"\";\n const text = typeof t?.text === \"string\" ? t.text : \"\";\n if (!subject || !text.trim()) return json({ error: `template \"${key}\" needs a subject and a body` }, 400);\n if (/[\\r\\n]/.test(subject) || subject.length > 200) return json({ error: `template \"${key}\" subject must be a single line under 200 characters` }, 400);\n if (text.length > 10_000) return json({ error: `template \"${key}\" body is too long` }, 400);\n clean[key] = { subject, text, enabled: t?.enabled !== false };\n }\n const emailish = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n const notificationEmail = str(body.notificationEmail).trim();\n const replyTo = str(body.replyTo).trim();\n const debugEmail = str(body.debugEmail).trim();\n if (!emailish.test(notificationEmail)) return json({ error: \"notification address must be a valid email\" }, 400);\n if (!emailish.test(replyTo)) return json({ error: \"reply-to address must be a valid email\" }, 400);\n if (debugEmail && !emailish.test(debugEmail)) return json({ error: \"debug address must be a valid email\" }, 400);\n const commitmentText = str(body.commitmentText);\n const normsText = str(body.normsText);\n if (commitmentText.length > 5000 || normsText.length > 5000) return json({ error: \"commitment/norms text is too long\" }, 400);\n\n await db.transact([{ t: \"update\", ns: \"groups\", id: ctx.chapter.id, attrs: { emailTemplates: clean, commitmentText, normsText, notificationEmail, replyTo, debugEmail } }]);\n return json({ ok: true });\n};\n\n/** GET /api/admin/email/log — the send audit: every attempted send. */\nexport const handleAdminEmailLog: Route = async (req, url, env, ctx) => {\n if (req.method !== \"GET\" || url.pathname !== \"/api/admin/email/log\") return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const { emailLog } = await got.query({ emailLog: { $: { order: { sentAt: \"desc\" }, limit: 50 } } });\n const sends = ((emailLog ?? []) as Array<Record<string, unknown>>).map((r) => ({\n id: r.id,\n template: r.template,\n to: r.to,\n subject: r.subject,\n transport: r.transport,\n redirected: r.redirected === true,\n error: (r.error as string) ?? null,\n sentAt: r.sentAt,\n }));\n return json({ sends });\n};\n\n/** POST /api/admin/email/test — send one template with sample data to the\n * notification address, ignoring the `enabled` flag (the admin asked). */\nexport const handleAdminEmailTest: Route = async (req, url, env, ctx) => {\n if (req.method !== \"POST\" || url.pathname !== \"/api/admin/email/test\") return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n let body: Record<string, unknown>;\n try {\n body = (await req.json()) as Record<string, unknown>;\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n const template = str(body.template);\n if (!(EMAIL_TEMPLATE_NAMES as readonly string[]).includes(template)) {\n return json({ error: `template must be one of: ${EMAIL_TEMPLATE_NAMES.join(\", \")}` }, 400);\n }\n const group = await loadGroup(db, ctx.chapter.id);\n if (!group) return json({ error: \"not found\" }, 404);\n const res = await sendTemplated(notifyDeps(db, env), {\n group: emailGroupFrom(group),\n template,\n to: str(group.notificationEmail),\n vars: { firstName: \"Sample\", lastName: \"Person\", email: \"sample@example.com\", phone: \"(555) 010-0100\", state: \"CA\", adminUrl: `${url.origin}/admin/`, membersUrl: `${url.origin}/members/` },\n dedupeKey: `test:${template}:${Date.now()}`,\n force: true,\n });\n return json({ ok: res.sent, reason: res.reason ?? null, to: str(group.notificationEmail), redirected: env.ODLA_ENV !== \"prod\" && !!group.debugEmail });\n};\n\n/** GET /api/admin/people/:applicationId/comms — one person's timeline: sent\n * lifecycle mail (adminNotification dropped — it goes to the team) plus the\n * Google calendar invitations reconstructed from their meeting rows. */\nexport const handleAdminComms: Route = async (req, url, env, ctx) => {\n const m = url.pathname.match(/^\\/api\\/admin\\/people\\/([0-9a-fA-F-]+)\\/comms$/);\n if (req.method !== \"GET\" || !m) return null;\n const got = await gate(req, env, ctx);\n if (got instanceof Response) return got;\n const db = got;\n const appId = m[1] as string;\n\n const [emailRes, meetingRes, appRes] = await Promise.all([\n db.query({ emailLog: { $: { where: { applicationId: appId }, order: { sentAt: \"desc\" }, limit: 100 } } }),\n db.query({ meetings: { $: { where: { applicationId: appId } } } }),\n db.query({ applications: { $: { where: { id: appId }, limit: 1 } } }),\n ]);\n const app = appRes.applications?.[0] ?? null;\n const group = await loadGroup(db, str(app?.groupId, ctx.chapter.id));\n const vars: Record<string, string> | null = app\n ? { firstName: str(app.firstName), lastName: str(app.lastName), email: str(app.email), phone: str(app.phone), state: str(app.state), adminUrl: `${url.origin}/admin/`, membersUrl: `${url.origin}/members/` }\n : null;\n\n const emails = ((emailRes.emailLog ?? []) as Array<Record<string, unknown>>)\n .filter((r) => r.template !== \"adminNotification\")\n .map((r): Record<string, unknown> => {\n let mailBody: string | null = typeof r.body === \"string\" ? r.body : null;\n if (!mailBody && group && vars) mailBody = renderTemplateBody(emailGroupFrom(group), String(r.template), vars);\n const channel = r.error ? \"email (failed)\" : r.redirected ? \"email (dev-redirected)\" : r.transport === \"log-only\" ? \"email (not delivered)\" : \"email\";\n return { kind: \"email\", channel, label: String(r.template), subject: str(r.subject), to: (r.to as string) ?? null, body: mailBody, at: r.sentAt as number, error: (r.error as string) ?? null };\n });\n const calendar = ((meetingRes.meetings ?? []) as Array<Record<string, unknown>>).map((m2): Record<string, unknown> => ({\n kind: \"calendar\",\n channel: \"Google Calendar\",\n label: m2.status === \"cancelled\" ? \"Invitation (call later cancelled)\" : \"Meeting invitation\",\n subject: \"Introduction call invitation\",\n to: null,\n at: (m2.createdAt as number) ?? (m2.startAt as number),\n error: null,\n }));\n const items = [...emails, ...calendar].sort((a, b) => ((b.at as number) ?? 0) - ((a.at as number) ?? 0));\n return json({ items });\n};\n","// Leader-side network routes. The receiving route lives in worker-routes.ts;\n// these admin-gated routes expose configured targets and fan one CRM record out\n// to selected followers with per-target vaulted credentials.\nimport { addTag, getRecord } from \"@odla-ai/crm\";\nimport type { CrmRecord } from \"@odla-ai/crm\";\nimport { getVaultSecret } from \"./auth\";\nimport { DEFAULT_SHARE_FIELDS, sharedRecordFromCrm } from \"./network\";\nimport { json } from \"./worker-context\";\nimport type { ChapterEnv, Db, Route, Verified, WorkerContext } from \"./worker-context\";\nimport type { ChapterDb, ResolvedNetworkTarget } from \"./types\";\n\nasync function gate(\n req: Request,\n env: ChapterEnv,\n ctx: WorkerContext,\n): Promise<{ response: Response } | { db: Db; user: Verified }> {\n const db = ctx.makeDb(env);\n const user = await ctx.verifyUser(req, env);\n if (!user) return { response: json({ error: \"unauthorized\" }, 401) };\n if (!(await ctx.isAdmin(db, user))) return { response: json({ error: \"forbidden\" }, 403) };\n return { db, user };\n}\n\n/** GET /api/admin/network/targets — non-secret target metadata for the UI. */\nexport const handleAdminNetworkTargets: Route = async (req, url, env, ctx) => {\n if (req.method !== \"GET\" || url.pathname !== \"/api/admin/network/targets\") return null;\n const got = await gate(req, env, ctx);\n if (\"response\" in got) return got.response;\n return json({\n targets: ctx.chapter.network.targets.map(({ id, name, url: targetUrl, fields }) => ({\n id,\n name,\n url: targetUrl,\n types: Object.keys(fields ?? DEFAULT_SHARE_FIELDS),\n })),\n });\n};\n\ninterface PushResult {\n id: string;\n name: string;\n ok: boolean;\n status?: number;\n recordId?: string;\n error?: string;\n}\n\nasync function pushOne(\n db: ChapterDb,\n ctx: WorkerContext,\n target: ResolvedNetworkTarget,\n record: CrmRecord,\n): Promise<PushResult> {\n const secret = await getVaultSecret(db, target.secretName);\n if (!secret) return { id: target.id, name: target.name, ok: false, error: `vault secret \"${target.secretName}\" is missing` };\n let payload;\n try {\n payload = sharedRecordFromCrm(ctx.chapter.crm, record, target);\n } catch (err) {\n return { id: target.id, name: target.name, ok: false, error: err instanceof Error ? err.message : \"record is not shareable\" };\n }\n try {\n const res = await fetch(new URL(\"/api/network/shared\", target.url), {\n method: \"POST\",\n headers: { authorization: `Bearer ${secret}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(10_000),\n });\n const body = (await res.json().catch(() => ({}))) as { recordId?: string; error?: string };\n if (!res.ok) {\n return { id: target.id, name: target.name, ok: false, status: res.status, error: body.error ?? \"follower rejected the record\" };\n }\n await addTag(\n { crm: ctx.chapter.crm, db: db as never },\n { recordId: record.id, tag: `shared:${target.id}`, mutationId: `network-delivered:${record.id}:${target.id}` },\n );\n return { id: target.id, name: target.name, ok: true, status: res.status, recordId: body.recordId };\n } catch (err) {\n return { id: target.id, name: target.name, ok: false, error: err instanceof Error ? err.message : \"delivery failed\" };\n }\n}\n\n/** POST /api/admin/network/push `{ recordId, targetIds }` — push one leader CRM\n * record to one or more configured followers. Each follower receives an\n * independently validated, allowlisted projection; partial failure is explicit. */\nexport const handleAdminNetworkPush: Route = async (req, url, env, ctx) => {\n if (req.method !== \"POST\" || url.pathname !== \"/api/admin/network/push\") return null;\n const got = await gate(req, env, ctx);\n if (\"response\" in got) return got.response;\n let body: { recordId?: unknown; targetIds?: unknown };\n try {\n body = (await req.json()) as typeof body;\n } catch {\n return json({ error: \"invalid JSON body\" }, 400);\n }\n if (typeof body.recordId !== \"string\" || !Array.isArray(body.targetIds) || body.targetIds.length === 0) {\n return json({ error: \"recordId and a non-empty targetIds array are required\" }, 400);\n }\n const requested = new Set(body.targetIds.filter((id): id is string => typeof id === \"string\"));\n if (requested.size !== body.targetIds.length) return json({ error: \"targetIds must contain unique strings\" }, 400);\n const targets = ctx.chapter.network.targets.filter((target) => requested.has(target.id));\n if (targets.length !== requested.size) return json({ error: \"one or more targetIds are not configured\" }, 400);\n\n const record = await getRecord({ crm: ctx.chapter.crm, db: got.db as never }, body.recordId);\n if (!record) return json({ error: \"record not found\" }, 404);\n const results = await Promise.all(\n targets.map((target) => pushOne(got.db as unknown as ChapterDb, ctx, target, record)),\n );\n return json({ ok: results.every((result) => result.ok), results });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMA,gBAA0B;AAC1B,kBAA8C;;;AC2BvC,SAAS,cAAc,SAAkC,MAA4B;AAC1F,QAAM,MAAM,QAAQ,KAAK,KAAK;AAC9B,SAAO,OAAO,QAAQ,YAAY,KAAK,OAAO,SAAS,GAAG,IAAI,MAAO,KAAK,OAAO,CAAC;AACpF;AAGO,SAAS,YAAY,MAAc,MAA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IAAI,OAAO,MAAM,GAAG;AAAA,IAC7B;AAAA,EACF;AACF;","names":["import_crm","crmDeps","str","rows","rows","firstRow","rows","import_calendar","rows","import_crm","crmDeps","gate","rows","import_calendar","gate","crmDeps","gate","loadGroup","str","import_crm","gate"]}