supermemory/apps/web/hooks/use-token-usage.ts
Prasanna721 55ef8ab899 fix: billing gate broke for scale/enterprise and downgraded users (#794)
The subscription check on plugins, connections, and usage pages was hardcoded to only look at `api_pro`. Users on scale or enterprise plans saw "Upgrade to Pro" and couldn't create plugin keys or manage connections.

Also, the check only looked at product `status` but not the `allowed` flag from autumn — so users who downgraded but were still in their billing period got locked out early.
2026-03-22 16:05:08 +00:00

57 lines
1.7 KiB
TypeScript

import {
DEFAULT_SUBSCRIPTION_STATUS,
fetchSubscriptionStatus,
isAllowedFrom,
} from "@lib/queries"
import type { useCustomer } from "autumn-js/react"
import { calculateUsagePercent, getDaysRemaining } from "@/lib/billing-utils"
export type PlanType = "free" | "pro" | "scale" | "enterprise"
export function useTokenUsage(autumn: ReturnType<typeof useCustomer>) {
const {
data: status = DEFAULT_SUBSCRIPTION_STATUS,
isLoading: isCheckingStatus,
} = fetchSubscriptionStatus(autumn, !autumn.isLoading)
let currentPlan: PlanType = "free"
if (isAllowedFrom(status, "api_enterprise")) {
currentPlan = "enterprise"
} else if (isAllowedFrom(status, "api_scale")) {
currentPlan = "scale"
} else if (isAllowedFrom(status, "api_pro")) {
currentPlan = "pro"
}
const hasPaidPlan = currentPlan !== "free"
// Get token usage from autumn customer features
const tokensFeature = autumn.customer?.features?.api_tokens
const tokensUsed = tokensFeature?.usage ?? 0
const tokensLimit = tokensFeature?.included_usage ?? 0
const tokensResetAt = tokensFeature?.next_reset_at
// Get search queries usage from autumn customer features
const searchesFeature = autumn.customer?.features?.api_search_queries
const searchesUsed = searchesFeature?.usage ?? 0
const searchesLimit = searchesFeature?.included_usage ?? 0
const isLoading = autumn.isLoading || isCheckingStatus
const tokensPercent = calculateUsagePercent(tokensUsed, tokensLimit)
const searchesPercent = calculateUsagePercent(searchesUsed, searchesLimit)
const daysRemaining = getDaysRemaining(tokensResetAt)
return {
tokensUsed,
tokensLimit,
tokensPercent,
searchesUsed,
searchesLimit,
searchesPercent,
currentPlan,
hasPaidPlan,
isLoading,
daysRemaining,
}
}