supermemory/apps/web/hooks/use-token-usage.ts
Prasanna721 694ad8123a fix: remove useQuery wrapper around synchronous billing checks (#805)
#### fix: billing subscription status race condition

 - **Bug fix**: Replaced `fetchSubscriptionStatus` (useQuery wrapper) with `getSubscriptionStatus` (pure function) — fixes intermittent "Upgrade to Pro"
  failures caused by stale cached billing state
  - **Anti-pattern**: Removed `fetchConnectionsFeature` useQuery wrapper, replaced with direct `autumn.customer?.features?.connections` read
  - **Dead code**: Removed unused `useMemoriesUsage` hook and `fetchMemoriesFeature`
2026-03-26 05:29:53 +00:00

50 lines
1.6 KiB
TypeScript

import { getSubscriptionStatus, 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 status = getSubscriptionStatus(autumn.customer?.products)
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
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,
}
}