Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

6.1 KB
Raw Blame
import { fireAndForget } from '@core/util/fireAndForget';
import { throwOnErr } from '@core/util/result';
import type { AiPlanTier, PaidPlan } from '@service-auth/ai-billing-types';
import { authServiceClient } from '@service-auth/client';
import { useMutation, useQuery } from '@tanstack/solid-query';
import { queryClient } from '../client';
import { queryReadyGate } from '../gate';
import { authKeys } from './keys';
import { invalidateUserInfo } from './user-info';

const AI_BILLING_SUMMARY_STALE_TIME = 30_000; // 30 seconds
const AI_BILLING_PLANS_STALE_TIME = 60 * 60 * 1000; // 1 hour

type UseAiBillingSummaryQueryOptions = {
  /** Whether the query should be enabled. Can be a boolean or accessor for reactivity. */
  enabled?: boolean | (() => boolean);
};

function aiBillingSummaryQueryOptions(enabled: boolean) {
  return {
    queryKey: authKeys.aiBillingSummary.queryKey,
    queryFn: async () =>
      await throwOnErr(
        async () => await authServiceClient.getAiBillingSummary()
      ),
    staleTime: AI_BILLING_SUMMARY_STALE_TIME,
    throwOnError: false,
    retry: 1,
    enabled,
  };
}

/**
 * The signed-in user's AI usage position for the current billing period:
 * included allowance, usage, credits, and overage settings. The backend
 * settles pending credits/overage before answering, so this is authoritative.
 */
export function useAiBillingSummaryQuery(
  options?: UseAiBillingSummaryQueryOptions
) {
  return useQuery(() =>
    aiBillingSummaryQueryOptions(
      typeof options?.enabled === 'function'
        ? options.enabled()
        : (options?.enabled ?? true)
    )
  );
}

const aiBillingPlansQueryOptions = {
  queryKey: authKeys.aiBillingPlans.queryKey,
  queryFn: async () =>
    await throwOnErr(async () => await authServiceClient.getAiBillingPlans()),
  staleTime: AI_BILLING_PLANS_STALE_TIME,
  throwOnError: false,
};

/** The plan catalog, credit packs, and overage cap bounds. */
export function useAiBillingPlansQuery() {
  return useQuery(() => aiBillingPlansQueryOptions);
}

/**
 * Included AI per seat per period from the plan catalog, in cents at provider
 * cost, keyed by tier. The backend owns the amount; this is the only place the
 * frontend should get it from. Empty until the catalog has loaded.
 */
export function useIncludedAiCentsByTier(): () => Partial<
  Record<AiPlanTier, number>
> {
  const plans = useAiBillingPlansQuery();
  return () =>
    Object.fromEntries(
      (queryReadyGate(plans) ? plans.data.plans : []).map((plan) => [
        plan.tier,
        plan.included_ai_cents_per_seat,
      ])
    );
}

export function invalidateAiBillingSummary() {
  return queryClient.invalidateQueries({
    queryKey: authKeys.aiBillingSummary.queryKey,
  });
}

/** Renewal and scheduled downgrade, read only while Billing settings needs it. */
function subscriptionStatusQueryOptions(enabled: boolean) {
  return {
    queryKey: authKeys.subscriptionStatus.queryKey,
    queryFn: async () =>
      await throwOnErr(() => authServiceClient.getSubscriptionStatus()),
    enabled,
    staleTime: AI_BILLING_SUMMARY_STALE_TIME,
    throwOnError: false,
    retry: 1,
  };
}

export function useSubscriptionStatusQuery(
  options?: UseAiBillingSummaryQueryOptions
) {
  return useQuery(() =>
    subscriptionStatusQueryOptions(
      typeof options?.enabled === 'function'
        ? options.enabled()
        : (options?.enabled ?? true)
    )
  );
}

export function invalidateSubscriptionStatus() {
  return queryClient.invalidateQueries({
    queryKey: authKeys.subscriptionStatus.queryKey,
  });
}

/** Turn usage billing (overage) on or off with a per-period cap. */
export function useUpdateAiOverageMutation() {
  return useMutation(() => ({
    mutationFn: async (args: { enabled: boolean; limitCents: number }) =>
      await throwOnErr(
        async () => await authServiceClient.updateAiOverage(args)
      ),
    onSuccess: (snapshot) => {
      queryClient.setQueryData(authKeys.aiBillingSummary.queryKey, snapshot);
    },
  }));
}

/**
 * Turn automatic credit reloads (and with them, usage billing) on or off and
 * set the balance thresholds and optional monthly spend limit.
 */
export function useUpdateAiAutoReloadMutation() {
  return useMutation(() => ({
    mutationFn: async (args: {
      enabled: boolean;
      minimumBalanceCents: number;
      targetBalanceCents: number;
      monthlySpendLimitCents: number | null;
    }) =>
      await throwOnErr(
        async () => await authServiceClient.updateAiAutoReload(args)
      ),
    onSuccess: (snapshot) => {
      queryClient.setQueryData(authKeys.aiBillingSummary.queryKey, snapshot);
    },
  }));
}

/** Buy a credit pack on the payer's card on file; updates the summary. */
export function usePurchaseAiCreditsMutation() {
  return useMutation(() => ({
    mutationFn: async (args: { amountCents: number }) =>
      await throwOnErr(
        async () => await authServiceClient.purchaseAiCredits(args)
      ),
    onSuccess: (result) => {
      if (result.snapshot) {
        queryClient.setQueryData(
          authKeys.aiBillingSummary.queryKey,
          result.snapshot
        );
        return;
      }
      // The purchase happened but its summary could not be read.
      fireAndForget(invalidateAiBillingSummary(), 'ai-billing');
    },
  }));
}

/** Start a Stripe Checkout for a credit pack; resolves to the hosted URL. */
export function useCreateAiCreditCheckoutMutation() {
  return useMutation(() => ({
    mutationFn: async (args: {
      amountCents: number;
      successUrl: string;
      cancelUrl: string;
    }) =>
      await throwOnErr(
        async () => await authServiceClient.createAiCreditCheckout(args)
      ),
  }));
}

/** Move the active subscription to another paid plan. */
export function useChangePlanMutation() {
  return useMutation(() => ({
    mutationFn: async (args: { plan: PaidPlan }) =>
      await throwOnErr(async () => await authServiceClient.changePlan(args)),
    onSuccess: async () => {
      // Roles flip via webhook; the scheduled change is available immediately.
      fireAndForget(invalidateUserInfo(), 'ai-billing');
      fireAndForget(invalidateAiBillingSummary(), 'ai-billing');
      await invalidateSubscriptionStatus();
    },
  }));
}