Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Add YC plan checkout and dynamic paid-plan detection (#660)
Ben Senescu700acc0cf51b
diff --git a/src/client/features/billing/PlanOfferCard.tsx b/src/client/features/billing/PlanOfferCard.tsxnew file mode 100644index 00000000..612054d2--- /dev/null+++ b/src/client/features/billing/PlanOfferCard.tsx@@ -0,0 +1,55 @@+import type { ReactNode } from "react";+import type { PlanOffer } from "@/client/features/billing/plan-offers";++const SUPPORT_EMAIL = "[email protected]";++// Shared card for the full-page checkout screens (/subscribe, /yc). Callers+// pass the CTA and any extra notes as children.+export function PlanOfferCard({+ offer,+ features,+ afterFeatures,+ children,+}: {+ offer: PlanOffer;+ features: string[];+ afterFeatures?: ReactNode;+ children: ReactNode;+}) {+ return (+ <div className="rounded-lg border border-base-300 p-5 space-y-4">+ <div className="flex items-baseline justify-between gap-4">+ <span className="font-semibold">{offer.name}</span>+ <span className="text-lg font-semibold tabular-nums">+ ${offer.priceUsd}/month+ </span>+ </div>++ <ul className="space-y-2">+ {features.map((item) => (+ <li key={item} className="flex gap-2.5 text-sm text-base-content/70">+ <span className="text-base-content/40 mt-[2px] shrink-0">+ —+ </span>+ {item}+ </li>+ ))}+ {afterFeatures}+ </ul>++ {children}++ <p className="text-center text-xs text-base-content/50">+ <span+ className="tooltip before:max-w-60 before:whitespace-normal"+ data-tip={`Not for you yet? Email ${SUPPORT_EMAIL} within 30 days of your charge and we'll refund your subscription.`}+ >+ <span className="cursor-help underline decoration-dotted">+ 30-day money-back guarantee+ </span>+ </span>+ . Cancel anytime. Powered by Stripe.+ </p>+ </div>+ );+}diff --git a/src/client/features/billing/PlanPageAccountMenu.tsx b/src/client/features/billing/PlanPageAccountMenu.tsxnew file mode 100644index 00000000..859f49a0--- /dev/null+++ b/src/client/features/billing/PlanPageAccountMenu.tsx@@ -0,0 +1,53 @@+import { Link } from "@tanstack/react-router";+import { Settings, User } from "lucide-react";+import { ThemePreferenceMenuItems } from "@/client/components/ThemePreferenceMenuItems";+import { signOutAndRedirect } from "@/lib/auth-client";++// Account dropdown for the standalone plan pages (/subscribe, /yc), which+// render outside the app shell and so have no other way to sign out.+export function PlanPageAccountMenu({ email }: { email: string | undefined }) {+ if (!email) return null;++ const handleSignOut = () => signOutAndRedirect();++ return (+ <div className="fixed top-4 right-4">+ <div className="dropdown dropdown-end">+ <button+ type="button"+ tabIndex={0}+ className="btn btn-ghost btn-circle"+ aria-label="Open account menu"+ >+ <User className="h-5 w-5" />+ </button>+ <ul+ tabIndex={0}+ className="dropdown-content z-20 menu mt-3 min-w-56 rounded-box border border-base-300 bg-base-100 p-2 shadow-lg"+ >+ <li className="menu-title max-w-full">+ <span className="truncate text-base-content" data-ph-mask>+ {email}+ </span>+ </li>+ <li>+ <Link to="/settings" className="flex items-center gap-2">+ <Settings className="h-4 w-4" />+ Settings+ </Link>+ </li>+ <ThemePreferenceMenuItems />+ <li>+ <button+ type="button"+ className="text-error"+ onClick={handleSignOut}+ >+ Sign out+ </button>+ </li>+ </ul>+ </div>+ </div>+ );+}diff --git a/src/client/features/billing/plan-detection.test.ts b/src/client/features/billing/plan-detection.test.tsindex d8bc9d30..b50ae338 100644--- a/src/client/features/billing/plan-detection.test.ts+++ b/src/client/features/billing/plan-detection.test.ts@@ -1,6 +1,10 @@import { describe, expect, it } from "vitest";import { AUTUMN_PAID_PLAN_FEATURE_ID } from "@/shared/billing";-import { getCustomerPlanStatus } from "./plan-detection";+import {+ getCustomerPaidPlan,+ getCustomerPaidPlanId,+ getCustomerPlanStatus,+} from "./plan-detection";describe("getCustomerPlanStatus", () => {it("treats a customer without the paid entitlement as free", () => {@@ -20,3 +24,34 @@ describe("getCustomerPlanStatus", () => {).toBe("paid");});});++describe("getCustomerPaidPlanId", () => {+ it("returns the plan that granted the paid entitlement", () => {+ expect(+ getCustomerPaidPlanId({+ flags: { [AUTUMN_PAID_PLAN_FEATURE_ID]: { planId: "yc-plan" } },+ }),+ ).toBe("yc-plan");+ expect(getCustomerPaidPlanId({ flags: {} })).toBeNull();+ });+});++describe("getCustomerPaidPlan", () => {+ it("reads the name from the expanded subscription and credits from balances", () => {+ expect(+ getCustomerPaidPlan({+ flags: { [AUTUMN_PAID_PLAN_FEATURE_ID]: { planId: "yc-plan" } },+ subscriptions: [{ planId: "yc-plan", plan: { name: "YC Plan" } }],+ balances: { usage_credits: { granted: 50000 } },+ }),+ ).toEqual({ id: "yc-plan", name: "YC Plan", monthlyCreditsUsd: 50 });+ });++ it("falls back to the plan ID when the plan is not expanded", () => {+ expect(+ getCustomerPaidPlan({+ flags: { [AUTUMN_PAID_PLAN_FEATURE_ID]: { planId: "yc-plan" } },+ })?.name,+ ).toBe("yc-plan");+ });+});diff --git a/src/client/features/billing/plan-detection.ts b/src/client/features/billing/plan-detection.tsindex 668e68ed..37f179c5 100644--- a/src/client/features/billing/plan-detection.ts+++ b/src/client/features/billing/plan-detection.ts@@ -1,9 +1,47 @@-import { AUTUMN_PAID_PLAN_FEATURE_ID } from "@/shared/billing";+import {+ AUTUMN_PAID_PLAN_FEATURE_ID,+ AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,+ autumnSeoDataCreditsToUsd,+} from "@/shared/billing";export type PlanStatus = "free" | "paid";+// The slice of the Autumn customer we read. Structural so tests and both+// the SDK's React and server shapes fit without casts.+type CustomerLike = {+ flags?: Record<string, { planId?: string | null } | undefined>;+ subscriptions?: Array<{ planId: string; plan?: { name: string } }>;+ balances?: Record<string, { granted: number } | undefined>;+};+export function getCustomerPlanStatus(- customer: { flags?: Record<string, unknown> } | undefined,+ customer: CustomerLike | undefined,): PlanStatus {return customer?.flags?.[AUTUMN_PAID_PLAN_FEATURE_ID] ? "paid" : "free";}++// Autumn records which plan granted the paid entitlement, so any plan that+// grants paid_plan is recognized without listing plan IDs here.+export function getCustomerPaidPlanId(+ customer: CustomerLike | undefined,+): string | null {+ return customer?.flags?.[AUTUMN_PAID_PLAN_FEATURE_ID]?.planId ?? null;+}++// Display details for the plan a paid customer is on. `name` needs the+// customer fetched with `expand: ["subscriptions.plan"]`; it falls back to+// the plan ID otherwise.+export function getCustomerPaidPlan(customer: CustomerLike | undefined) {+ const planId = getCustomerPaidPlanId(customer);+ if (!planId) return null;+ const subscription = customer?.subscriptions?.find(+ (s) => s.planId === planId,+ );+ return {+ id: planId,+ name: subscription?.plan?.name ?? planId,+ monthlyCreditsUsd: autumnSeoDataCreditsToUsd(+ customer?.balances?.[AUTUMN_SEO_DATA_BALANCE_FEATURE_ID]?.granted ?? 0,+ ),+ };+}diff --git a/src/client/features/billing/plan-offers.ts b/src/client/features/billing/plan-offers.tsnew file mode 100644index 00000000..c703dff5--- /dev/null+++ b/src/client/features/billing/plan-offers.ts@@ -0,0 +1,37 @@+import {+ AUTUMN_CHECKOUT_SESSION_PARAMS,+ AUTUMN_PAID_PLAN_ID,+ AUTUMN_YC_CHECKOUT_SESSION_PARAMS,+ AUTUMN_YC_PLAN_ID,+} from "@/shared/billing";++// What a checkout page advertises before the customer holds the plan. Once+// they do, the Autumn customer is the source of truth (see plan-detection.ts),+// so these numbers only need to match the Autumn plan they sell.+export type PlanOffer = {+ planId: string;+ name: string;+ priceUsd: number;+ monthlyCreditsUsd: number;+ checkoutSessionParams: Record<string, unknown>;+};++export const BASE_PLAN_OFFER: PlanOffer = {+ planId: AUTUMN_PAID_PLAN_ID,+ name: "Base Plan",+ priceUsd: 10,+ monthlyCreditsUsd: 10,+ checkoutSessionParams: AUTUMN_CHECKOUT_SESSION_PARAMS,+};++export const YC_PLAN_OFFER: PlanOffer = {+ planId: AUTUMN_YC_PLAN_ID,+ name: "YC Plan",+ priceUsd: 50,+ monthlyCreditsUsd: 50,+ checkoutSessionParams: AUTUMN_YC_CHECKOUT_SESSION_PARAMS,+};++export function monthlyCreditsFeature(offer: PlanOffer) {+ return `Includes $${offer.monthlyCreditsUsd.toFixed(2)} of Usage Credits each month`;+}diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.tsindex e6d170b0..16245297 100644--- a/src/routeTree.gen.ts+++ b/src/routeTree.gen.ts@@ -21,6 +21,7 @@ import { Route as AppIndexRouteImport } from './routes/_app/index'import { Route as RReportIdRouteImport } from './routes/r/$reportId'import { Route as ApiHealthRouteImport } from './routes/api/health'import { Route as AcceptInvitationIdRouteImport } from './routes/accept-invitation.$id'+import { Route as AuthenticatedYcRouteImport } from './routes/_authenticated.yc'import { Route as AuthenticatedSubscribeRouteImport } from './routes/_authenticated.subscribe'import { Route as AuthenticatedOauthConsentRouteImport } from './routes/_authenticated.oauth-consent'import { Route as AuthSignUpRouteImport } from './routes/_auth.sign-up'@@ -125,6 +126,11 @@ const AcceptInvitationIdRoute = AcceptInvitationIdRouteImport.update({path: '/accept-invitation/$id',getParentRoute: () => rootRouteImport,} as any)+const AuthenticatedYcRoute = AuthenticatedYcRouteImport.update({+ id: '/yc',+ path: '/yc',+ getParentRoute: () => AuthenticatedRoute,+} as any)const AuthenticatedSubscribeRoute = AuthenticatedSubscribeRouteImport.update({id: '/subscribe',path: '/subscribe',@@ -399,6 +405,7 @@ export interface FileRoutesByFullPath {'/sign-up': typeof AuthSignUpRoute'/oauth-consent': typeof AuthenticatedOauthConsentRoute'/subscribe': typeof AuthenticatedSubscribeRoute+ '/yc': typeof AuthenticatedYcRoute'/accept-invitation/$id': typeof AcceptInvitationIdRoute'/api/health': typeof ApiHealthRoute'/r/$reportId': typeof RReportIdRoute@@ -455,6 +462,7 @@ export interface FileRoutesByTo {'/sign-up': typeof AuthSignUpRoute'/oauth-consent': typeof AuthenticatedOauthConsentRoute'/subscribe': typeof AuthenticatedSubscribeRoute+ '/yc': typeof AuthenticatedYcRoute'/accept-invitation/$id': typeof AcceptInvitationIdRoute'/api/health': typeof ApiHealthRoute'/r/$reportId': typeof RReportIdRoute@@ -512,6 +520,7 @@ export interface FileRoutesById {'/_auth/sign-up': typeof AuthSignUpRoute'/_authenticated/oauth-consent': typeof AuthenticatedOauthConsentRoute'/_authenticated/subscribe': typeof AuthenticatedSubscribeRoute+ '/_authenticated/yc': typeof AuthenticatedYcRoute'/accept-invitation/$id': typeof AcceptInvitationIdRoute'/api/health': typeof ApiHealthRoute'/r/$reportId': typeof RReportIdRoute@@ -572,6 +581,7 @@ export interface FileRouteTypes {| '/sign-up'| '/oauth-consent'| '/subscribe'+ | '/yc'| '/accept-invitation/$id'| '/api/health'| '/r/$reportId'@@ -628,6 +638,7 @@ export interface FileRouteTypes {| '/sign-up'| '/oauth-consent'| '/subscribe'+ | '/yc'| '/accept-invitation/$id'| '/api/health'| '/r/$reportId'@@ -684,6 +695,7 @@ export interface FileRouteTypes {| '/_auth/sign-up'| '/_authenticated/oauth-consent'| '/_authenticated/subscribe'+ | '/_authenticated/yc'| '/accept-invitation/$id'| '/api/health'| '/r/$reportId'@@ -834,6 +846,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AcceptInvitationIdRouteImportparentRoute: typeof rootRouteImport}+ '/_authenticated/yc': {+ id: '/_authenticated/yc'+ path: '/yc'+ fullPath: '/yc'+ preLoaderRoute: typeof AuthenticatedYcRouteImport+ parentRoute: typeof AuthenticatedRoute+ }'/_authenticated/subscribe': {id: '/_authenticated/subscribe'path: '/subscribe'@@ -1338,12 +1357,14 @@ const AuthRouteWithChildren = AuthRoute._addFileChildren(AuthRouteChildren)interface AuthenticatedRouteChildren {AuthenticatedOauthConsentRoute: typeof AuthenticatedOauthConsentRouteAuthenticatedSubscribeRoute: typeof AuthenticatedSubscribeRoute+ AuthenticatedYcRoute: typeof AuthenticatedYcRouteAuthenticatedOnboardingIndexRoute: typeof AuthenticatedOnboardingIndexRoute}const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {AuthenticatedOauthConsentRoute: AuthenticatedOauthConsentRoute,AuthenticatedSubscribeRoute: AuthenticatedSubscribeRoute,+ AuthenticatedYcRoute: AuthenticatedYcRoute,AuthenticatedOnboardingIndexRoute: AuthenticatedOnboardingIndexRoute,}diff --git a/src/routes/_app/billing.tsx b/src/routes/_app/billing.tsxindex d64c0d48..e988c6b9 100644--- a/src/routes/_app/billing.tsx+++ b/src/routes/_app/billing.tsx@@ -11,10 +11,16 @@ import { BillingUsageChart } from "@/client/features/billing/BillingUsageChart";import { BillingFeatureBreakdown } from "@/client/features/billing/BillingFeatureBreakdown";import { parseTopUpAmount } from "@/client/features/billing/HostedBillingContentUtils";import { getBillingRouteState } from "@/client/features/billing/route-state";-import { getCustomerPlanStatus } from "@/client/features/billing/plan-detection";+import {+ getCustomerPaidPlan,+ getCustomerPlanStatus,+} from "@/client/features/billing/plan-detection";+import {+ BASE_PLAN_OFFER,+ monthlyCreditsFeature,+} from "@/client/features/billing/plan-offers";import {AUTUMN_CHECKOUT_SESSION_PARAMS,- AUTUMN_PAID_PLAN_ID,BILLING_ROUTE,AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,LOW_CREDITS_THRESHOLD_USD,@@ -40,6 +46,8 @@ function BillingPage() {const [error, setError] = useState<string | null>(null);const customerQuery = useCustomer({+ // Expanded so the plan card can show the subscribed plan's name.+ expand: ["subscriptions.plan"],queryOptions: {enabled: Boolean(session?.user?.id),},@@ -51,6 +59,7 @@ function BillingPage() {const planStatus = getCustomerPlanStatus(customerQuery.data);const isFreePlan = planStatus === "free";+ const paidPlan = getCustomerPaidPlan(customerQuery.data);const billingRouteState = getBillingRouteState({hasSession: Boolean(session?.user?.id),isSessionPending,@@ -101,10 +110,10 @@ function BillingPage() {function startUpgradeCheckout() {captureClientEvent("billing:checkout_start");return customerQuery.attach({- planId: AUTUMN_PAID_PLAN_ID,+ planId: BASE_PLAN_OFFER.planId,redirectMode: "always",successUrl: buildCheckoutSuccessUrl(BILLING_ROUTE),- checkoutSessionParams: AUTUMN_CHECKOUT_SESSION_PARAMS,+ checkoutSessionParams: BASE_PLAN_OFFER.checkoutSessionParams,});}@@ -168,7 +177,7 @@ function BillingPage() {<p className="mt-2 text-xs text-amber-600">You’re running low on credits.{" "}{isFreePlan- ? "Upgrade to get $10/month."+ ? `Upgrade to get $${BASE_PLAN_OFFER.monthlyCreditsUsd}/month.`: "Buy more credits below."}</p>) : null}@@ -177,8 +186,15 @@ function BillingPage() {<div className="text-sm"><span className="font-medium">Plan</span>{" "}<span className="text-base-content/50">- {isFreePlan ? "Free Plan" : "Base Plan"}+ {paidPlan?.name ?? "Free Plan"}</span>+ {paidPlan ? (+ <span className="text-base-content/50">+ {" "}+ · ${paidPlan.monthlyCreditsUsd.toFixed(2)} of Usage+ Credits each month+ </span>+ ) : null}</div>{!canManageBilling ? (@@ -189,15 +205,17 @@ function BillingPage() {) : isFreePlan ? (<div className="space-y-3 border-t border-base-300 pt-3"><div className="flex items-baseline justify-between gap-4">- <span className="text-sm font-medium">Base Plan</span>+ <span className="text-sm font-medium">+ {BASE_PLAN_OFFER.name}+ </span><span className="text-sm font-medium tabular-nums">- $10/month+ ${BASE_PLAN_OFFER.priceUsd}/month</span></div><ul className="space-y-1.5">{["Access to all OpenSEO features",- "Includes $10.00 of Usage Credits each month",+ monthlyCreditsFeature(BASE_PLAN_OFFER),].map((item) => (<likey={item}diff --git a/src/routes/_authenticated.subscribe.tsx b/src/routes/_authenticated.subscribe.tsxindex 37326f08..c645fa3a 100644--- a/src/routes/_authenticated.subscribe.tsx+++ b/src/routes/_authenticated.subscribe.tsx@@ -1,21 +1,22 @@-import { Link, createFileRoute, useNavigate } from "@tanstack/react-router";+import { createFileRoute, useNavigate } from "@tanstack/react-router";import { useCustomer } from "autumn-js/react";import { useEffect, useState } from "react";-import { ArrowRight, Settings, User } from "lucide-react";-import { ThemePreferenceMenuItems } from "@/client/components/ThemePreferenceMenuItems";+import { ArrowRight } from "lucide-react";+import { PlanPageAccountMenu } from "@/client/features/billing/PlanPageAccountMenu";+import { PlanOfferCard } from "@/client/features/billing/PlanOfferCard";+import {+ BASE_PLAN_OFFER,+ monthlyCreditsFeature,+} from "@/client/features/billing/plan-offers";import { captureClientEvent } from "@/client/lib/posthog";-import { signOutAndRedirect, useSession } from "@/lib/auth-client";+import { useSession } from "@/lib/auth-client";import { isHostedClientAuthMode } from "@/lib/auth-mode";import { getStandardErrorMessage } from "@/client/lib/error-messages";import { getSubscribeRouteState } from "@/client/features/billing/route-state";import { getCustomerPlanStatus } from "@/client/features/billing/plan-detection";import { normalizeAuthRedirect } from "@/lib/auth-redirect";import { useCanManageBilling } from "@/client/features/team/organizationQueries";-import {- AUTUMN_CHECKOUT_SESSION_PARAMS,- AUTUMN_MANAGED_ACCESS_FEATURE_ID,- AUTUMN_PAID_PLAN_ID,-} from "@/shared/billing";+import { AUTUMN_MANAGED_ACCESS_FEATURE_ID } from "@/shared/billing";const SUPPORT_EMAIL = "[email protected]";@@ -23,7 +24,7 @@ const PLAN_FEATURES = ["Keyword research, backlinks, rank tracking, and site audits","MCP server and agent skills for Claude, Cursor, and ChatGPT","Google Search Console Integration",- "Includes $10.00 of Usage Credits each month",+ monthlyCreditsFeature(BASE_PLAN_OFFER),];// How long the post-checkout "finalizing" screen polls Autumn before giving@@ -198,10 +199,10 @@ function SubscribePage() {const successUrl = new URL(window.location.href);successUrl.searchParams.set("checkout", "success");await customerQuery.attach({- planId: AUTUMN_PAID_PLAN_ID,+ planId: BASE_PLAN_OFFER.planId,redirectMode: "always",successUrl: successUrl.toString(),- checkoutSessionParams: AUTUMN_CHECKOUT_SESSION_PARAMS,+ checkoutSessionParams: BASE_PLAN_OFFER.checkoutSessionParams,});} catch (err) {setError(@@ -218,7 +219,7 @@ function SubscribePage() {return (<div className="w-full max-w-sm space-y-6">- <SubscribePageAccountMenu email={session?.user?.email} />+ <PlanPageAccountMenu email={session?.user?.email} /><div className="text-center space-y-3"><img@@ -238,25 +239,11 @@ function SubscribePage() {</p></div>- <div className="rounded-lg border border-base-300 p-5 space-y-4">- <div className="flex items-baseline justify-between gap-4">- <span className="font-semibold">Base Plan</span>- <span className="text-lg font-semibold tabular-nums">$10/month</span>- </div>-- <ul className="space-y-2">- {PLAN_FEATURES.map((item) => (- <li- key={item}- className="flex gap-2.5 text-sm text-base-content/70"- >- <span className="text-base-content/40 mt-[2px] shrink-0">- —- </span>- {item}- </li>- ))}- {/* Sub-bullet of the Usage Credits line above. */}+ <PlanOfferCard+ offer={BASE_PLAN_OFFER}+ features={PLAN_FEATURES}+ afterFeatures={+ /* Sub-bullet of the Usage Credits line above. */<li className="-mt-1 pl-6 text-xs"><aclassName="text-base-content/60 underline decoration-base-content/40 decoration-dotted underline-offset-4 transition-colors hover:text-base-content"@@ -271,8 +258,8 @@ function SubscribePage() {<span aria-hidden="true">↗</span></a></li>- </ul>-+ }+ >{error ? <p className="text-sm text-error">{error}</p> : null}{canManageBilling ? (@@ -289,19 +276,7 @@ function SubscribePage() {organization.</p>)}-- <p className="text-center text-xs text-base-content/50">- <span- className="tooltip before:max-w-60 before:whitespace-normal"- data-tip={`Not for you yet? Email ${SUPPORT_EMAIL} within 30 days of your charge and we'll refund your subscription.`}- >- <span className="cursor-help underline decoration-dotted">- 30-day money-back guarantee- </span>- </span>- . Cancel anytime. Powered by Stripe.- </p>- </div>+ </PlanOfferCard><div className="text-center space-y-2"><p className="text-sm text-base-content/60">@@ -321,50 +296,3 @@ function SubscribePage() {</div>);}--function SubscribePageAccountMenu({ email }: { email: string | undefined }) {- if (!email) return null;-- const handleSignOut = () => signOutAndRedirect();-- return (- <div className="fixed top-4 right-4">- <div className="dropdown dropdown-end">- <button- type="button"- tabIndex={0}- className="btn btn-ghost btn-circle"- aria-label="Open account menu"- >- <User className="h-5 w-5" />- </button>- <ul- tabIndex={0}- className="dropdown-content z-20 menu mt-3 min-w-56 rounded-box border border-base-300 bg-base-100 p-2 shadow-lg"- >- <li className="menu-title max-w-full">- <span className="truncate text-base-content" data-ph-mask>- {email}- </span>- </li>- <li>- <Link to="/settings" className="flex items-center gap-2">- <Settings className="h-4 w-4" />- Settings- </Link>- </li>- <ThemePreferenceMenuItems />- <li>- <button- type="button"- className="text-error"- onClick={handleSignOut}- >- Sign out- </button>- </li>- </ul>- </div>- </div>- );-}diff --git a/src/routes/_authenticated.yc.tsx b/src/routes/_authenticated.yc.tsxnew file mode 100644index 00000000..e125aed5--- /dev/null+++ b/src/routes/_authenticated.yc.tsx@@ -0,0 +1,212 @@+import { Link, createFileRoute, notFound } from "@tanstack/react-router";+import { useCustomer } from "autumn-js/react";+import { useState } from "react";+import { ArrowRight, Tag } from "lucide-react";+import { PlanPageAccountMenu } from "@/client/features/billing/PlanPageAccountMenu";+import { PlanOfferCard } from "@/client/features/billing/PlanOfferCard";+import {+ YC_PLAN_OFFER,+ monthlyCreditsFeature,+} from "@/client/features/billing/plan-offers";+import { buildCheckoutSuccessUrl } from "@/client/features/billing/checkout-url";+import {+ getCustomerPaidPlanId,+ getCustomerPlanStatus,+} from "@/client/features/billing/plan-detection";+import { getBillingRouteState } from "@/client/features/billing/route-state";+import { useCanManageBilling } from "@/client/features/team/organizationQueries";+import { getStandardErrorMessage } from "@/client/lib/error-messages";+import { captureClientEvent } from "@/client/lib/posthog";+import { useSession } from "@/lib/auth-client";+import { isHostedClientAuthMode } from "@/lib/auth-mode";+import { BILLING_ROUTE } from "@/shared/billing";++const SUPPORT_EMAIL = "[email protected]";++const PLAN_FEATURES = [+ "Keyword research, backlinks, rank tracking, and site audits",+ "MCP server and agent skills for Claude, Cursor, and ChatGPT",+ "Google Search Console Integration",+ monthlyCreditsFeature(YC_PLAN_OFFER),+];++export const Route = createFileRoute("/_authenticated/yc")({+ beforeLoad: () => {+ if (!isHostedClientAuthMode()) {+ throw notFound();+ }+ },+ component: YcPlanPage,+});++function YcPlanPage() {+ const { data: session, isPending: isSessionPending } = useSession();+ const [isAttaching, setIsAttaching] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const hasSession = Boolean(session?.user?.id);+ const customerQuery = useCustomer({+ queryOptions: {+ enabled: hasSession,+ },+ });++ // Checkout is owner-only; other members are pointed at their organization+ // owner instead of a button that would 403.+ const canManageBilling = useCanManageBilling();++ const routeState = getBillingRouteState({+ hasSession,+ isSessionPending,+ isCustomerLoading: customerQuery.isLoading,+ isCustomerError: customerQuery.isError,+ });++ const isPaid = getCustomerPlanStatus(customerQuery.data) === "paid";+ const isOnYcPlan =+ getCustomerPaidPlanId(customerQuery.data) === YC_PLAN_OFFER.planId;++ if (routeState === "loading") {+ return null;+ }++ if (routeState === "error") {+ return (+ <div className="w-full max-w-xs space-y-4">+ <div className="text-center space-y-3">+ <img+ src="/transparent-logo.png"+ alt="OpenSEO"+ className="mx-auto size-10 rounded-lg"+ />+ <h1 className="text-xl font-semibold">Billing unavailable</h1>+ </div>++ <p className="text-sm text-center text-base-content/70">+ {getStandardErrorMessage(+ customerQuery.error,+ "We couldn't verify your billing status right now. Please try again.",+ )}+ </p>++ <button+ type="button"+ className="btn btn-soft w-full"+ onClick={() => {+ void customerQuery.refetch();+ }}+ >+ Try again+ </button>+ </div>+ );+ }++ async function handleSubscribe() {+ setError(null);+ setIsAttaching(true);++ try {+ captureClientEvent("billing:checkout_start", {+ planId: YC_PLAN_OFFER.planId,+ });+ // Existing subscribers switching plans land on Billing so they can see+ // the new plan; new subscribers go into the app.+ await customerQuery.attach({+ planId: YC_PLAN_OFFER.planId,+ redirectMode: "always",+ successUrl: buildCheckoutSuccessUrl(isPaid ? BILLING_ROUTE : "/"),+ checkoutSessionParams: YC_PLAN_OFFER.checkoutSessionParams,+ });+ } catch (err) {+ setError(+ getStandardErrorMessage(+ err,+ "We couldn't start the checkout. Please try again.",+ ),+ );+ setIsAttaching(false);+ }+ }++ return (+ <div className="w-full max-w-sm space-y-6">+ <PlanPageAccountMenu email={session?.user?.email} />++ <div className="text-center space-y-3">+ <img+ src="/transparent-logo.png"+ alt="OpenSEO"+ className="mx-auto size-10 rounded-lg"+ />+ <h1 className="text-xl font-semibold">OpenSEO for YC founders</h1>+ <p className="text-sm text-base-content/60">+ A bigger monthly credit pool for teams doing serious SEO work, with+ your first month free through the YC deal.+ </p>+ </div>++ <PlanOfferCard offer={YC_PLAN_OFFER} features={PLAN_FEATURES}>+ <div className="flex gap-2.5 rounded-md bg-base-200 p-3 text-sm">+ <Tag className="mt-0.5 size-4 shrink-0 text-base-content/60" />+ <p className="text-base-content/70">+ <span className="font-medium text-base-content">+ Don’t forget your promo code.+ </span>{" "}+ Enter the code from the YC deal under “Add promotion+ code” on the checkout page to get your first month free.+ </p>+ </div>++ {error ? <p className="text-sm text-error">{error}</p> : null}++ {isOnYcPlan ? (+ <p className="text-sm text-base-content/60">+ You’re already on the {YC_PLAN_OFFER.name}.{" "}+ <Link to={BILLING_ROUTE} className="link">+ Manage it on Billing+ </Link>+ .+ </p>+ ) : canManageBilling ? (+ <div className="space-y-2">+ <button+ className="btn btn-soft w-full"+ disabled={isAttaching}+ onClick={() => void handleSubscribe()}+ >+ {isAttaching+ ? "Redirecting..."+ : isPaid+ ? `Switch to the ${YC_PLAN_OFFER.name}`+ : `Get the ${YC_PLAN_OFFER.name}`}+ </button>+ {isPaid ? (+ <p className="text-center text-xs text-base-content/50">+ Replaces your current subscription.+ </p>+ ) : null}+ </div>+ ) : (+ <p className="text-sm text-base-content/60">+ Only the organization owner can change the plan. Ask them to switch+ this organization to the {YC_PLAN_OFFER.name}.+ </p>+ )}+ </PlanOfferCard>++ <div className="text-center space-y-2">+ <p className="text-sm text-base-content/60">+ Questions? Email {SUPPORT_EMAIL}.+ </p>+ <Link+ to="/"+ className="inline-flex items-center gap-1.5 text-sm font-medium text-base-content/70 hover:text-base-content transition-colors"+ >+ <ArrowRight className="size-3.5 rotate-180" />+ Back to app+ </Link>+ </div>+ </div>+ );+}diff --git a/src/server/billing/customer-status-model.test.ts b/src/server/billing/customer-status-model.test.tsindex 6b262544..d5b3c323 100644--- a/src/server/billing/customer-status-model.test.ts+++ b/src/server/billing/customer-status-model.test.ts@@ -1,18 +1,23 @@import { describe, expect, it } from "vitest";-import { AUTUMN_PAID_PLAN_ID } from "@/shared/billing";+import { AUTUMN_PAID_PLAN_FEATURE_ID } from "@/shared/billing";import { deriveBillingCustomerStatusSnapshot } from "./customer-status-model";+const paidFlags = (planId: string) => ({+ [AUTUMN_PAID_PLAN_FEATURE_ID]: { planId },+});+describe("deriveBillingCustomerStatusSnapshot", () => {- it("marks customers with an active paid subscription as paying", () => {+ it("marks customers whose paid plan is active as paying", () => {const snapshot = deriveBillingCustomerStatusSnapshot({id: "org_123",- subscriptions: [{ planId: AUTUMN_PAID_PLAN_ID, status: "active" }],+ flags: paidFlags("yc-plan"),+ subscriptions: [{ planId: "yc-plan", status: "active" }],});expect(snapshot).toMatchObject({organizationId: "org_123",isPaying: true,- paidPlanId: AUTUMN_PAID_PLAN_ID,+ paidPlanId: "yc-plan",paidPlanStatus: "active",});});@@ -22,7 +27,6 @@ describe("deriveBillingCustomerStatusSnapshot", () => {id: "org_123",email: "[email protected]",stripeId: "cus_123",- subscriptions: [{ planId: AUTUMN_PAID_PLAN_ID, status: "active" }],});expect(JSON.parse(snapshot.customerJson)).toMatchObject({@@ -32,9 +36,10 @@ describe("deriveBillingCustomerStatusSnapshot", () => {});});- it("keeps non-paid customers queryable but not paying", () => {+ it("keeps customers without the paid entitlement queryable but not paying", () => {const snapshot = deriveBillingCustomerStatusSnapshot({id: "org_123",+ flags: {},subscriptions: [{ planId: "free", status: "active" }],});@@ -43,31 +48,31 @@ describe("deriveBillingCustomerStatusSnapshot", () => {expect(snapshot.paidPlanStatus).toBeNull();});- it("records a scheduled (not-yet-active) paid plan as not paying", () => {+ it("records a past-due paid plan as not paying", () => {const snapshot = deriveBillingCustomerStatusSnapshot({id: "org_456",- subscriptions: [{ planId: AUTUMN_PAID_PLAN_ID, status: "scheduled" }],+ flags: paidFlags("base-plan"),+ subscriptions: [{ planId: "base-plan", status: "past_due" }],});expect(snapshot).toMatchObject({- organizationId: "org_456",isPaying: false,- paidPlanId: AUTUMN_PAID_PLAN_ID,- paidPlanStatus: "scheduled",+ paidPlanId: "base-plan",+ paidPlanStatus: "past_due",});});- it("prefers an active paid subscription when multiple paid rows exist", () => {+ it("prefers the active row when the plan has several subscriptions", () => {const snapshot = deriveBillingCustomerStatusSnapshot({id: "org_789",+ flags: paidFlags("base-plan"),subscriptions: [- { planId: AUTUMN_PAID_PLAN_ID, status: "scheduled" },- { planId: AUTUMN_PAID_PLAN_ID, status: "active" },+ { planId: "base-plan", status: "scheduled" },+ { planId: "base-plan", status: "active" },],});expect(snapshot.isPaying).toBe(true);- expect(snapshot.paidPlanId).toBe(AUTUMN_PAID_PLAN_ID);expect(snapshot.paidPlanStatus).toBe("active");});});diff --git a/src/server/billing/customer-status-model.ts b/src/server/billing/customer-status-model.tsindex 6d032b99..d4e7748b 100644--- a/src/server/billing/customer-status-model.ts+++ b/src/server/billing/customer-status-model.ts@@ -1,4 +1,4 @@-import { AUTUMN_PAID_PLAN_ID } from "@/shared/billing";+import { AUTUMN_PAID_PLAN_FEATURE_ID } from "@/shared/billing";// The subset of the Autumn SDK's `Customer` we read. The SDK already validates// and returns camelCase, so we type against it structurally instead of@@ -11,6 +11,7 @@ type AutumnSubscriptionInput = {type AutumnCustomerInput = {id?: string | null;subscriptions?: AutumnSubscriptionInput[];+ flags?: Record<string, { planId?: string | null } | undefined>;[key: string]: unknown;};@@ -31,12 +32,19 @@ export function deriveBillingCustomerStatusSnapshot(throw new Error("Autumn customer is missing an id");}- const subscription = selectPaidSubscription(customer.subscriptions ?? []);+ // Autumn names the plan that granted `paid_plan`, so every plan configured+ // to grant it counts as paid without listing plan IDs here. A flag with no+ // plan (granted by hand) has no subscription to report on.+ const paidPlanId =+ customer.flags?.[AUTUMN_PAID_PLAN_FEATURE_ID]?.planId ?? null;+ const subscription = paidPlanId+ ? selectSubscription(customer.subscriptions ?? [], paidPlanId)+ : null;return {organizationId,isPaying: subscription?.status === "active",- paidPlanId: subscription?.planId ?? null,+ paidPlanId,paidPlanStatus: subscription?.status ?? null,// Full payload kept verbatim — query rarely-used fields via json_extract.customerJson: JSON.stringify(customer),@@ -44,9 +52,12 @@ export function deriveBillingCustomerStatusSnapshot(};}-// A customer is "paying" when they hold the base paid plan. Prefer an active-// row, but fall back to any paid row so a not-yet-active plan still records its id.-function selectPaidSubscription(subscriptions: AutumnSubscriptionInput[]) {- const paid = subscriptions.filter((s) => s.planId === AUTUMN_PAID_PLAN_ID);- return paid.find((s) => s.status === "active") ?? paid[0] ?? null;+// Prefer the active row; fall back to any row for the plan so a past-due or+// scheduled state is still recorded.+function selectSubscription(+ subscriptions: AutumnSubscriptionInput[],+ planId: string,+) {+ const rows = subscriptions.filter((s) => s.planId === planId);+ return rows.find((s) => s.status === "active") ?? rows[0] ?? null;}diff --git a/src/shared/billing.ts b/src/shared/billing.tsindex b672b688..f5cfe524 100644--- a/src/shared/billing.ts+++ b/src/shared/billing.ts@@ -2,6 +2,8 @@ export const BILLING_ROUTE = "/billing";export const SUBSCRIBE_ROUTE = "/subscribe";export const AUTUMN_PAID_PLAN_ID = "base-plan";+// YC deal: same entitlements as the base plan with $50 of monthly credits.+export const AUTUMN_YC_PLAN_ID = "yc-plan";export const AUTUMN_SEO_DATA_TOP_UP_PLAN_ID = "credit-top-up";export const AUTUMN_PAID_PLAN_FEATURE_ID = "paid_plan";// Granted by both the free plan (now the Autumn Default, so every non-paid@@ -26,6 +28,13 @@ export const AUTUMN_CHECKOUT_SESSION_PARAMS = {customer_update: { name: "auto", address: "auto" },} as const;+// YC checkout additionally shows Stripe's promotion code field so founders+// can redeem the YC deal code for their first month.+export const AUTUMN_YC_CHECKOUT_SESSION_PARAMS = {+ ...AUTUMN_CHECKOUT_SESSION_PARAMS,+ allow_promotion_codes: true,+} as const;+export function roundUsdForBilling(value: number) {return Math.round(value * 100000) / 100000;}