import { useCreditExposure } from "../lib/use-analytics-exposure"; import type { OpenGeniBrowserClient } from "@opengeni/sdk/browser"; import { Link, usePage } from "../lib/navigation"; import { CreditCardIcon, Loader2Icon, SparklesIcon } from "lucide-react"; import type { BillingCheckoutStatus, WorkspaceModelCatalogModel } from "@opengeni/sdk"; import { useEffect, useState } from "react"; import { toast } from "../lib/toast"; import { CouponRedeem } from "./credits/coupon-redeem"; import { CreditsCelebrationDialog } from "./credits/checkout-credits-celebration"; import { Button } from "../../ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "../../ui/dialog"; import { CreditAmountPicker } from "./credit-amount-picker"; import { Notice } from "../../ui/notice"; import { useAppContext } from "../app-context"; import { useCreditBalance } from "./credits/use-credit-balance"; import { userErrorText } from "../../ui/api-error"; import { validTopupAmount } from "../lib/format"; import { isUpgradeRefusal } from "../../lib/format"; import { analyticsAction } from "../../ui/analytics-actions"; import { checkoutPageReturnUrl, checkoutTabReturnUrl } from "../lib/credit-checkout"; import { subscriptionAction } from "../lib/subscription-plans"; import type { PaymentRefusalCode } from "../lib/model-access"; const DEFAULT_TOPUP = "25.00"; type CreditRequiredPromptProps = { open: boolean; workspaceId: string; accountId: string | null; canBuyCredits: boolean; purpose?: "required" | "topup" | undefined; /** A refusal one action fixes (own-key fee, API use): no model choice applies. */ refusalCode?: PaymentRefusalCode | null | undefined; onOpenChange: (open: boolean) => void; /** * Runs before this page leaves for checkout, such as saving the composer's * draft now instead of after its autosave pause, so paying keeps it. */ beforeLeave?: (() => Promise) | undefined; }; export function CreditRequiredPrompt(props: CreditRequiredPromptProps) { return ; } export function CreditRequiredPromptView({ client, open, workspaceId, accountId, canBuyCredits, purpose = "required", refusalCode = null, onOpenChange, beforeLeave, }: CreditRequiredPromptProps & { client: OpenGeniBrowserClient }) { const page = usePage(); const [topupAmount, setTopupAmount] = useState(DEFAULT_TOPUP); const [busy, setBusy] = useState(false); // A redeemed coupon, celebrated in this dialog with its real amount. const [granted, setGranted] = useState(null); useEffect(() => { if (!open) setGranted(null); }, [open]); const [stripeEnabled, setStripeEnabled] = useState(false); const [upgradeAccountId, setUpgradeAccountId] = useState(null); const canUpgrade = open && canBuyCredits && accountId !== null && upgradeAccountId === accountId; useEffect(() => { setUpgradeAccountId(null); if (!open || !accountId || !canBuyCredits) { setStripeEnabled(false); return; } let active = true; setStripeEnabled(false); void client .getBilling({ accountId }) .then(async (billing) => { if (active) setStripeEnabled(billing.mode === "stripe"); if (!active || !billing.balance.plan || billing.mode !== "stripe") return; const catalog = await client.getBillingSubscriptionPlans({ accountId }).catch(() => null); if ( active && catalog?.plan && catalog.plans.some((target) => { const action = subscriptionAction(billing.balance.plan!, catalog.plans, target); return action === "checkout" || action === "upgrade"; }) ) setUpgradeAccountId(accountId); }) .catch(() => { if (active) setStripeEnabled(false); }); return () => { active = false; }; }, [accountId, canBuyCredits, client, open]); async function buyCredits(): Promise { if (!accountId || !validTopupAmount(topupAmount) || busy) return; setBusy(true); try { const session = await client.createBillingCheckout({ amountUsd: Number(topupAmount), accountId, // Beside an embed, checkout ends on a page that asks to go back to it. // Otherwise it returns to this page (the chat, with its draft), which // confirms the credits. successUrl: page.opensBeside ? checkoutTabReturnUrl(page.origin(), "success") : checkoutPageReturnUrl(page.href(), accountId, "success"), cancelUrl: page.opensBeside ? checkoutTabReturnUrl(page.origin(), "cancelled") : checkoutPageReturnUrl(page.href(), accountId, "cancelled"), }); // A failed save (a conflict, a dropped request) doesn't hold up checkout. if (!page.opensBeside) await beforeLeave?.().catch(() => undefined); page.assign(session.url); // The web app has left for checkout; an embed stays and can buy again. if (page.opensBeside) setBusy(false); } catch (error) { toast.error("Checkout failed", { description: userErrorText(error) }); setBusy(false); } } if (granted) { return ; } if (isUpgradeRefusal(refusalCode)) { // On the Free plan, own keys and own subscriptions need a paid plan: one action. return ( {refusalCode === "subscription_upgrade_required" ? "Upgrade to Pro to use your own subscription" : "Upgrade to Pro to use your own key"} {canBuyCredits ? "Upgrade to Pro on Billing." : "Ask an organization owner to upgrade to Pro."} {canBuyCredits ? ( ) : null} ); } return ( {purpose === "topup" ? "Add Opengeni credits" : refusalCode === "byok_paid_credit_required" ? "Add credits to use your own key" : refusalCode === "api_credits_required" ? "API usage uses credits, not your plan credit" : "Add Opengeni credits to continue"} {/* A refusal's title names its fix; the line below it says how. With only the Billing link to show, the link says it. */} {purpose === "topup" ? refusalCode === "byok_paid_credit_required" ? "Choose an amount and pay in Stripe Checkout." : "Choose an amount and pay in Stripe Checkout, or redeem a coupon code." : refusalCode ? canBuyCredits && stripeEnabled ? "Choose an amount and pay in Stripe Checkout." : canBuyCredits ? "Add credits on Billing." : "Ask an organization owner to add credits." : "Add credits to use this model, or choose another model."} {canBuyCredits && stripeEnabled ? (
{/* A coupon's credit can't pay the own-key fee, so it would not fix this refusal. */} {accountId && refusalCode !== "byok_paid_credit_required" ? (
) : null}
) : !canBuyCredits ? ( refusalCode ? null : (

Ask an organization owner to add credits, or an admin to connect a model.

) ) : refusalCode && purpose === "required" ? ( // Checkout isn't available here (yet): Billing still has the one fix. ) : null} {/* Own-key and API refusals have one fix: credits. */} {purpose === "required" && !refusalCode ? ( {/* Credits are the main action when they can be bought here. */} ) : null}
); } /** * Before the person types: the selected model is paid with Opengeni credits * and none are left. Says so once, in plain words, with the one action that * fixes it; using your own provider account stays as a quiet second choice. */ export function EmptyCreditsNotice({ workspaceId, accountId, canBuyCredits, canReadBilling, creditFunding, onAddCredits, }: { workspaceId: string; accountId: string | null; canBuyCredits: boolean; canReadBilling: boolean; creditFunding?: WorkspaceModelCatalogModel["creditFunding"] | undefined; /** Opens the add-credits prompt on this page; without it, Add credits opens billing. */ onAddCredits?: (() => void) | undefined; }) { const client = useAppContext().client; // The balance is positive but this model can't use it (for example free // credit for other models), so "you don't have any" would be untrue. Only // that much is known, so the words claim no more. The chat's refusal // notice words the same two states the same way. const { balance } = useCreditBalance(client, accountId, canReadBilling); const someCredit = balance?.someCredit ?? false; const stripeEnabled = balance?.stripeEnabled ?? false; const legacyEmpty = Boolean(balance?.billingEnabled && !balance.someCredit); const empty = stripeEnabled && (creditFunding === undefined ? legacyEmpty : creditFunding === "unavailable"); useCreditExposure(empty, workspaceId); if (!empty) return null; const canAdd = canBuyCredits && stripeEnabled; const body = someCredit ? canAdd ? "This model can't use the Opengeni credits you have right now. Add credits, or choose another model." : "This model can't use your organization's Opengeni credits right now. Choose another model, or ask an organization owner to add credits." : canAdd ? "Chats here are paid with Opengeni credits, and you don't have any right now." : "Chats here are paid with Opengeni credits, and there are none left. Ask an organization owner to add some."; return ( {body}
{canAdd ? ( onAddCredits ? ( ) : ( ) ) : null} {/* Beside Add credits it is a quiet link, flush with the text when it wraps. */}
); }