Files
descrybe/apps/web/src/lib/stripe-billing.ts
T
2026-10-16 00:34:06 +02:00

122 lines
3.4 KiB
TypeScript

import { api, ApiError } from "$lib/api";
import {
buildCreditPackEcommerce,
buildSubscriptionEcommerce,
trackEcommerceEvent,
trackEvent
} from "$lib/analytics";
import { CONTACT_SALES_HREF, SALES_CALENDLY_URL } from "$lib/components/pricing/pricing-data";
import { CREDIT_PACKS } from "$lib/components/pricing/credit-packs";
import { isSelfServeCheckoutPlan } from "$lib/billing-display";
export type StripeStatus = {
configured: boolean;
mock: boolean;
has_customer: boolean;
has_subscription: boolean;
customer_id?: string;
subscription_id?: string;
subscription_status?: string;
};
/** Live Stripe for all company admins; mock checkout only for platform admins. */
export function canSelfServePurchase(
stripe: StripeStatus | null | undefined,
opts?: { isPlatformAdmin?: boolean }
): boolean {
if (!stripe) return false;
if (stripe.configured && !stripe.mock) return true;
if (stripe.mock && opts?.isPlatformAdmin) return true;
return false;
}
export type CheckoutResult = {
url: string;
mock?: boolean;
applied?: boolean;
message?: string;
};
export type PortalResult = {
url: string;
mock?: boolean;
};
export { isSelfServeCheckoutPlan, SALES_CALENDLY_URL, CONTACT_SALES_HREF };
export async function fetchStripeStatus(): Promise<StripeStatus | null> {
try {
return await api<StripeStatus>("/api/billing/stripe");
} catch (err) {
if (err instanceof ApiError && (err.status === 404 || err.status === 501)) return null;
throw err;
}
}
export async function startCheckout(
plan: string,
term: "monthly" | "yearly" = "monthly"
): Promise<CheckoutResult> {
const key = plan.trim().toLowerCase();
if (!isSelfServeCheckoutPlan(key)) {
throw new Error(
"This plan is not available for self-serve checkout. Contact sales for Enterprise."
);
}
const { ecommerce, extra } = buildSubscriptionEcommerce(key, term);
trackEcommerceEvent("begin_checkout", ecommerce, extra);
return api<CheckoutResult>("/api/billing/checkout", {
method: "POST",
body: { plan: key, term }
});
}
export type CreditPack = {
id: string;
name: string;
description: string;
credits: number;
price_eur: number;
ai_products: number;
};
export async function fetchCreditPacks(): Promise<CreditPack[]> {
try {
const res = await api<{ packs?: CreditPack[] }>("/api/billing/credit-packs");
return Array.isArray(res?.packs) ? res.packs : [];
} catch (err) {
if (err instanceof ApiError && (err.status === 404 || err.status === 501)) return [];
throw err;
}
}
/** One-time AI credit top-up via Stripe Checkout (mode=payment). */
export async function startCreditPackCheckout(packId: string): Promise<CheckoutResult> {
const pack = packId.trim().toLowerCase();
if (!pack) {
throw new Error("Choose a credit pack.");
}
const marketing = CREDIT_PACKS.find((p) => p.id === pack);
const { ecommerce, extra } = buildCreditPackEcommerce(pack, {
priceEur: marketing?.priceEUR,
itemName: marketing?.name
});
trackEcommerceEvent("begin_checkout", ecommerce, extra);
return api<CheckoutResult>("/api/billing/checkout", {
method: "POST",
body: { pack }
});
}
export async function openBillingPortal(): Promise<PortalResult> {
trackEvent("billing_portal_opened");
return api<PortalResult>("/api/billing/portal", { method: "POST", body: {} });
}
/** Navigate to checkout URL (or mock success redirect). */
export function redirectToCheckout(result: CheckoutResult): void {
if (result.url) {
window.location.assign(result.url);
}
}