| 1 | import type { User } from "@g1t/contracts"; |
| 2 | |
| 3 | import { planStatus, type UsageGlance, usageGlance } from "./billing"; |
| 4 | import { billing } from "./services.server"; |
| 5 | |
| 6 | /** The trial as published, when the price book cannot be read. */ |
| 7 | const DEFAULT_TRIAL_MICROS = 5_000_000; |
| 8 | |
| 9 | /** |
| 10 | * The month for the Usage card, for members only: what was spent, what |
| 11 | * pays first and what it went on. Fetched here, not with the sidebar, so |
| 12 | * only this page pays for it; a billing service that cannot answer leaves |
| 13 | * the card out rather than the page. |
| 14 | */ |
| 15 | export async function usageFor(slug: string, viewer: User | null): Promise<UsageGlance | null> { |
| 16 | const now = new Date(); |
| 17 | const monthStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString(); |
| 18 | const [account, usage, features, entitlements, limit, book] = await Promise.all([ |
| 19 | billing.account(slug, viewer).catch(() => null), |
| 20 | billing.usage(slug, viewer, monthStart).catch(() => null), |
| 21 | billing.features(slug, viewer).catch(() => null), |
| 22 | billing.entitlements(slug).catch(() => null), |
| 23 | billing.limit(slug, viewer).catch(() => null), |
| 24 | billing.prices().catch(() => null), |
| 25 | ]); |
| 26 | if (!account?.ok || !usage?.ok) return null; |
| 27 | // Without payments set up (a g1t run without billing), there is no plan to show. |
| 28 | if (!account.value.status.enabled && !usage.value.free) return null; |
| 29 | const plan = features?.ok ? (features.value.find((state) => state.plan.feature === "plan") ?? null) : null; |
| 30 | return usageGlance({ |
| 31 | usage: usage.value, |
| 32 | status: planStatus(plan, entitlements), |
| 33 | entitlements, |
| 34 | limit: limit?.ok ? limit.value : null, |
| 35 | trialMicros: book?.free?.trialWorkspaceMicros ?? DEFAULT_TRIAL_MICROS, |
| 36 | }); |
| 37 | } |
| 38 | |