Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

9.8 KB
Raw Blame
import { useRef } from "react";
import type { TFunction } from "i18next";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { authApi } from "@/lib/api";
import { toast } from "@/lib/toast";
import type { WorkBuddyCreditExpiry, WorkBuddyQuota } from "@/lib/api/auth";
import { isManualIdle, useQuotaPolicy } from "@/lib/query/quotaPolicy";
import {
  countdownStr,
  failedLines,
  formatRelativeTime,
  RESET_EXPIRING_SOON_MS,
  shortDate,
  toneForLeft,
  type QuotaBreakdownItem,
  type QuotaDisplay,
  type QuotaLine,
} from "@/components/quota/quotaRules";

export const WORKBUDDY_QUOTA_KEY = ["workbuddy-account-quota"] as const;

const REFETCH_INTERVAL = 5 * 60 * 1000;

let workbuddyForceRefreshEpoch = 0;

/** 授权中心「全部刷新」时调用:让下一次 WorkBuddy 额度重查同样跳过后端 5 分钟缓存。 */
export function markWorkBuddyQuotaForceRefresh() {
  workbuddyForceRefreshEpoch += 1;
}

/**
 * WorkBuddy 账号的套餐与积分。卡片、表单和授权中心共用一份缓存;后端 5 分钟内走缓存,
 * `refresh()` 与授权中心「全部刷新」跳过缓存重查。只有 WorkBuddy 正在运行时当前账号才查得到新的;
 * 查不到新的(没运行、不是当前号…)时后端立刻回上次结果,界面看着像没反应,所以弹一句原因。
 */
export function useWorkBuddyAccountQuota(
  accountId: string | null,
  options: { autoRefresh?: boolean } = {},
) {
  const { t } = useTranslation();
  const force = useRef(false);
  const seenForceEpoch = useRef(workbuddyForceRefreshEpoch);
  const policy = useQuotaPolicy();
  const autoAllowed = policy.autoAllowed;
  const query = useQuery({
    queryKey: [...WORKBUDDY_QUOTA_KEY, accountId],
    queryFn: () => {
      const skipCache =
        force.current || seenForceEpoch.current !== workbuddyForceRefreshEpoch;
      force.current = false;
      seenForceEpoch.current = workbuddyForceRefreshEpoch;
      return authApi.workbuddyAccountQuota(accountId!, skipCache);
    },
    enabled: autoAllowed && Boolean(accountId),
    staleTime: REFETCH_INTERVAL,
    refetchInterval:
      autoAllowed && options.autoRefresh ? REFETCH_INTERVAL : false,
    refetchOnWindowFocus: false,
    retry: false,
  });
  const refresh = async () => {
    force.current = true;
    const result = await query.refetch();
    const quota = result.data;
    const note = quota?.snapshot ? workbuddyStaleNote(t, quota) : undefined;
    if (note) toast.info(note);
    return result;
  };
  return { ...query, refresh, manualIdle: isManualIdle(policy, query) };
}

/** 积分数:一万以上用紧凑写法(「12.3万」「12.3K」) */
export function formatCredits(value: number, locale: string): string {
  try {
    return new Intl.NumberFormat(
      locale,
      value >= 10_000
        ? { notation: "compact", maximumFractionDigits: 1 }
        : { maximumFractionDigits: value < 100 ? 2 : 0 },
    ).format(value);
  } catch {
    return String(Math.round(value));
  }
}

/** 没刷新成时补的一句说明(显示的是上次结果时) */
export function workbuddyStaleNote(
  t: TFunction,
  quota: WorkBuddyQuota,
): string | undefined {
  switch (quota.unavailable) {
    case "not_running":
      return t("workbuddy.quota.staleNotRunning");
    case "not_current":
      return t("workbuddy.quota.staleNotCurrent");
    case "not_signed_in":
      return t("workbuddy.quota.staleNotSignedIn");
    case "failed":
      return t("workbuddy.quota.staleFailed");
    default:
      return undefined;
  }
}

export interface WorkBuddyCreditsLine {
  line: QuotaLine;
  /** 套餐名;后端没给时为 undefined */
  planName?: string;
}

/** 积分那一行:剩余(或按设置写已用)/ 总量,条按剩余比例画,悬停写全剩余 / 总量 / 已用。 */
export function workbuddyCreditsLine(
  t: TFunction,
  quota: WorkBuddyQuota,
  locale: string,
  display: QuotaDisplay = "left",
): WorkBuddyCreditsLine | null {
  const snapshot = quota.snapshot;
  if (!snapshot) return null;
  const remaining = formatCredits(snapshot.remaining, locale);
  const used = formatCredits(snapshot.used, locale);
  const total = formatCredits(snapshot.total, locale);
  const planName = snapshot.planName?.trim() || undefined;
  if (snapshot.unlimited) {
    // 不限额的企业号:没有比例可画,只写已用
    const unlimited = t("workbuddy.quota.unlimited");
    const text = t("workbuddy.quota.unlimitedUsed", { used });
    return {
      planName,
      line: {
        key: "workbuddy_credits",
        left: Infinity,
        tone: toneForLeft(Infinity),
        text,
        value: unlimited,
        caption: unlimited,
        detail: [planName, text, workbuddyStaleNote(t, quota)]
          .filter(Boolean)
          .join(" · "),
      },
    };
  }
  const leftPct =
    snapshot.total > 0
      ? Math.max(0, Math.min(100, (snapshot.remaining / snapshot.total) * 100))
      : 0;
  const usedUp = snapshot.remaining <= 0;
  const showUsed = display === "used";
  const value = usedUp ? t("quota.usedUp") : showUsed ? used : remaining;
  const text = usedUp
    ? t("workbuddy.quota.usedUp", { total })
    : showUsed
      ? t("workbuddy.quota.usedOf", { used, total })
      : t("workbuddy.quota.leftOf", { remaining, total });
  const detail = [
    planName,
    t("workbuddy.quota.detail", { remaining, total, used }),
    workbuddyStaleNote(t, quota),
  ]
    .filter(Boolean)
    .join(" · ");
  return {
    planName,
    line: {
      key: "workbuddy_credits",
      left: leftPct,
      bar: showUsed ? 100 - leftPct : leftPct,
      tone: toneForLeft(usedUp ? 0 : leftPct),
      text,
      value,
      detail,
    },
  };
}

/** WorkBuddy 账号最早到期的积分,见 {@link creditExpiryLine}。 */
export function workbuddyExpiryLine(
  t: TFunction,
  quota: WorkBuddyQuota,
  locale: string,
  now = Date.now(),
): QuotaLine | null {
  return creditExpiryLine(
    t,
    quota.snapshot?.expiries,
    locale,
    "workbuddy_expiry",
    now,
  );
}

/**
 * 积分最早哪天到期:「496 积分 11月30日到期」,三天内到期时标橙。按日期合并,不止一个日期时
 * 可以点开逐条看。没有会到期的积分(或这次没查到套餐明细)时为 null。缓存的结果里已经过了
 * 到期时间的那几笔不再算。WorkBuddy 和 CodeBuddy 共用同一套计费后端,到期明细形状一样。
 */
export function creditExpiryLine(
  t: TFunction,
  expiries: readonly WorkBuddyCreditExpiry[] | null | undefined,
  locale: string,
  lineKey: string,
  now = Date.now(),
): QuotaLine | null {
  const groups: { key: string; at: number | null; credits: number }[] = [];
  // 后端已按到期先后排好,不会过期的在最后
  for (const { credits, expiresAt } of expiries ?? []) {
    if (expiresAt !== null && expiresAt <= now) continue;
    const key =
      expiresAt === null
        ? "no_expiry"
        : shortDate(new Date(expiresAt).toISOString(), locale);
    const last = groups[groups.length - 1];
    if (last?.key === key) last.credits += credits;
    else groups.push({ key, at: expiresAt, credits });
  }
  const first = groups[0];
  if (!first || first.at === null) return null;

  const soon = (at: number | null) =>
    at !== null && at - now < RESET_EXPIRING_SOON_MS;
  const credits = formatCredits(first.credits, locale);
  const date = first.key;
  const items: QuotaBreakdownItem[] = groups.map(({ key, at, credits }) => {
    const countdown =
      at === null ? null : countdownStr(new Date(at).toISOString(), now);
    return {
      key,
      label: at === null ? t("workbuddy.quota.noExpiry") : key,
      hint: countdown
        ? t("workbuddy.quota.inTime", { time: countdown })
        : undefined,
      value: formatCredits(credits, locale),
      tone: soon(at) ? "warning" : "plain",
    };
  });
  return {
    key: lineKey,
    left: Infinity,
    tone: soon(first.at) ? "warning" : "plain",
    emphasis: date,
    text: t("workbuddy.quota.expiresOn", { credits, date }),
    value: credits,
    caption: t("workbuddy.quota.expiresOnShort", { date }),
    breakdown:
      groups.length > 1
        ? {
            title: t("workbuddy.quota.expiryTitle"),
            openLabel: t("workbuddy.quota.expiryShowAll"),
            items,
          }
        : undefined,
  };
}

/**
 * 卡片右侧的额度列:积分一行;第二行写最早到期的积分,显示的是上次结果(WorkBuddy 没在运行等)
 * 时改写「xx 更新」,除非积分三天内就到期。
 * 还没有任何结果时:当前账号且 WorkBuddy 没运行 → 提示打开它;查询失败 → 「额度没查到」;其余不显示。
 */
export function workbuddyCardLines(
  t: TFunction,
  quota: WorkBuddyQuota | undefined,
  locale: string,
  display: QuotaDisplay = "left",
  now = Date.now(),
): QuotaLine[] | null {
  if (!quota) return null;
  const credits = workbuddyCreditsLine(t, quota, locale, display);
  if (credits) {
    const lines = [credits.line];
    const expiry = workbuddyExpiryLine(t, quota, locale, now);
    if (expiry && (expiry.tone === "warning" || !quota.unavailable)) {
      lines.push(expiry);
    } else if (quota.unavailable && quota.snapshot) {
      lines.push({
        key: "workbuddy_stale",
        left: Infinity,
        tone: "muted",
        text: t("quota.updatedAt", {
          time: formatRelativeTime(quota.snapshot.queriedAt, now, t),
        }),
        detail: workbuddyStaleNote(t, quota),
      });
    }
    return lines;
  }
  if (quota.unavailable === "not_running" && quota.current) {
    return [
      {
        key: "workbuddy_not_running",
        left: Infinity,
        tone: "muted",
        text: t("workbuddy.quota.openToQuery"),
        detail: t("workbuddy.quota.onlyWhileRunning"),
      },
    ];
  }
  if (quota.unavailable === "failed") {
    return failedLines(t, quota.error || t("workbuddy.quota.unavailable"));
  }
  return null;
}