Skip to content

Open source CapCut alternative.

TypeScript
5.5 KB
Raw Blame
"use client";

import { useMutation, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";

import type { CreditPriceSheet } from "@/lib/credits/price-sheet";
import { apiFetch } from "@/queries/apiClient";

export const creditBalanceQueryKey = ["credits", "balance"] as const;
export const accountQueryKey = ["account", "me"] as const;
export const subscribeBonusQueryKey = ["credits", "subscribe-bonus"] as const;

export type CreditBalance = {
  balance: string;
  balanceMicros: string;
  lifetimeCharged: string;
  lifetimeGranted: string;
  recentUsageTotals: {
    count: number;
    creditsCharged: string;
    failedCount: number;
    model: string;
    provider: string;
    route: string;
  }[];
};

export type Account = {
  userId: string;
  email: string | null;
  superUser: boolean;
};

const readCreditBalance = () => apiFetch<CreditBalance>("/api/credits/balance");

// How long a read balance stands in for the account's before it is read again.
const BALANCE_FRESH_MS = 60_000;

// How a mount treats a cached balance: "refetch" reads it again, "reuse"
// keeps a read younger than BALANCE_FRESH_MS (a panel that remounts on every
// tab switch).
export type BalanceFreshness = "refetch" | "reuse";

export function useCreditBalance(options: { enabled?: boolean; freshness?: BalanceFreshness } = {}) {
  return useQuery({
    enabled: options.enabled ?? true,
    queryFn: readCreditBalance,
    queryKey: creditBalanceQueryKey,
    staleTime: options.freshness === "reuse" ? BALANCE_FRESH_MS : 0,
  });
}

/** The balance through the shared cache: a fresh read is reused, a stale one
 * is read again. */
export function fetchCreditBalance(queryClient: QueryClient): Promise<CreditBalance> {
  return queryClient.fetchQuery({ queryKey: creditBalanceQueryKey, queryFn: readCreditBalance, staleTime: BALANCE_FRESH_MS });
}

export type SubscribeBonus = {
  // Where the offer reached the person: the app opened the bonus on its own,
  // a promotion came by email.
  origin: "app" | "email";
  // USD, as a credit string.
  dollars: string;
  openedAt: string;
  closesAt: string;
  // The credit's life once it lands: a fixed last moment, or days from the
  // claim. Both null keeps it forever.
  creditsExpireAt: string | null;
  creditsLifetimeDays: number | null;
  status: "open" | "closed" | "claimed";
};

// The account's subscribe bonus offer. The read is what opens it, so the
// query keeps asking while the app is up: a poll between charges, and a
// refetch when the tab comes back.
export function useSubscribeBonus(options: { enabled?: boolean } = {}) {
  return useQuery({
    enabled: options.enabled ?? true,
    queryFn: () => apiFetch<{ offer: SubscribeBonus | null }>("/api/credits/subscribe-bonus"),
    queryKey: subscribeBonusQueryKey,
    refetchInterval: 60_000,
    refetchOnWindowFocus: true,
    select: (data) => data.offer,
  });
}

export function useAccount() {
  return useQuery({
    queryFn: () => apiFetch<Account>("/api/account/me"),
    queryKey: accountQueryKey,
  });
}

export const creditOfferQueryKey = (token: string) => ["credits", "offer", token] as const;

export type CreditOffer = {
  // What lands the credit: the Claim button, or a Pro subscription started
  // inside the window.
  claim: "link" | "subscribe";
  claimed: boolean;
  // The last moment the offer can be claimed; null keeps it open.
  closesAt: string | null;
  // The amount in USD, "5"; the dialog words it as credits.
  dollars: string;
  // When the claimed credit expires; null before the claim and for a credit
  // that keeps forever.
  expiresAt: string | null;
  // How many days the claimed credit lasts; null when it keeps forever.
  lifetimeDays: number | null;
};

// The offer a claim link names. 404 is a link that no longer opens anything;
// 403 is an offer made to another account; 410 is a claim window that closed;
// 409 is a subscribe offer read by an account that already holds Pro.
export function useCreditOffer(token: string, options: { enabled?: boolean } = {}) {
  return useQuery({
    enabled: options.enabled ?? true,
    queryFn: () => apiFetch<CreditOffer>(`/api/credits/offers/claim?token=${encodeURIComponent(token)}`),
    queryKey: creditOfferQueryKey(token),
    retry: false,
  });
}

// Lands the offer on the signed-in account. The balance re-reads so the top
// bar shows the credit at once, and the offer's own entry records the claim,
// so a dialog that opens on the same token again presents the landed credit.
export function useClaimCreditOffer() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (token: string) =>
      apiFetch<{ balance: string; credits: string; expiresAt: string | null }>(
        "/api/credits/offers/claim",
        { body: JSON.stringify({ token }), method: "POST" },
      ),
    onSuccess: (landed, token) => {
      queryClient.setQueryData<CreditOffer>(creditOfferQueryKey(token), (offer) =>
        offer ? { ...offer, claimed: true, expiresAt: landed.expiresAt } : offer,
      );
      void queryClient.invalidateQueries({ queryKey: creditBalanceQueryKey });
    },
  });
}

export const creditPriceSheetQueryKey = ["credits", "prices"] as const;

// Prices move with a deploy or a rate change, so a read holds for an hour.
const PRICE_SHEET_FRESH_MS = 60 * 60_000;

export function useCreditPriceSheet(options: { enabled?: boolean } = {}) {
  return useQuery({
    enabled: options.enabled ?? true,
    queryFn: () => apiFetch<CreditPriceSheet>("/api/credits/prices"),
    queryKey: creditPriceSheetQueryKey,
    staleTime: PRICE_SHEET_FRESH_MS,
  });
}