All files / components AccountBar.tsx

96.95% Statements 255/263
85.96% Branches 49/57
100% Functions 10/10
96.95% Lines 255/263

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 2641x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 52x 52x 52x 55x 55x 52x 52x 52x 55x 55x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 55x 55x 52x 52x 52x 52x 52x 52x 52x 52x 158x 158x 158x 3x 3x 3x 3x 2x 3x 3x 3x 1x 1x   1x 1x 3x 3x 3x 3x 158x 158x 2x 2x 2x 2x 2x 2x           2x 2x 2x 2x 158x 158x 56x 56x 56x 56x 56x 56x 56x 56x 5x 5x 5x 5x 5x 5x 56x 56x 56x 56x 102x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 13x 89x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 158x 89x 89x 89x 89x 89x 89x 89x 89x 89x 158x 158x 15x 15x 15x 15x 15x 15x 15x 15x 15x 158x 158x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 158x 158x 158x 158x 2x 2x 2x 158x 158x 158x 158x 1x 1x 1x 1x 1x 1x 102x 102x 102x 48x 48x 4x 4x 48x 8x     1x 9x 9x 9x 9x 9x 9x 9x 1x 1x 316x 316x 316x 112x 107x 107x 107x 5x 5x 316x 316x 316x  
import { useEffect, useId, useRef, useState } from "react";
import {
  fetchAccount,
  startCheckout,
  openBillingPortal,
  pollForUpgrade,
  AlreadyPremiumError,
  NoSubscriptionError,
  type AccountState,
} from "../services/accountService";
 
/** Companion web app origin (specs/004-web-companion-app), injected at build
 * time via wxt.config.ts's `define` — never hard-coded (Azure Static Web
 * Apps, not GitHub Pages; see constitution Principle V). */
declare const WXT_WEB_APP_URL: string;
 
/** Auto-retry delay for a failed initial load — transient blips (a brief
 * local backend restart, a dropped connection) self-heal without the user
 * having to reload the whole panel. */
const RETRY_DELAY_MS = 5000;
 
/** FR-028: hover tooltip and screen-reader description for the Web app button. */
const WEB_APP_NOTE =
  "Opens in a new tab. You'll be asked to sign in with Google.";
 
/**
 * Plan, usage, and renewal state — always visible, never requiring the user
 * to hunt for it (contracts/billing-api.md, FR-013). Fetched on mount and on
 * window focus (uncached, mirrors withAuth's revocation/activation
 * property); a checkout tab triggers short-interval polling until the
 * webhook flips tier (SC-004, ≤ 1 min typical).
 */
export function AccountBar() {
  const [account, setAccount] = useState<AccountState | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [checkoutBusy, setCheckoutBusy] = useState(false);
  const [portalBusy, setPortalBusy] = useState(false);
  const [retryTick, setRetryTick] = useState(0);
  const stopPollRef = useRef<(() => void) | null>(null);
  const webAppNoteId = useId();
 
  const checkoutPending = useDelayedPending(checkoutBusy);
  const portalPending = useDelayedPending(portalBusy);
 
  useEffect(() => {
    let mounted = true;
    let retryTimeout: ReturnType<typeof setTimeout> | null = null;
    const load = () => {
      fetchAccount()
        .then((next) => {
          if (!mounted) return;
          setAccount(next);
          setError(null);
        })
        .catch(() => {
          if (!mounted) return;
          // Only surface a blocking error when there's no cached data to
          // fall back on. Once the panel has loaded successfully once, a
          // later background refresh failure (focus/retry) retries quietly
          // instead of alarming the user over data that's still correct.
          setAccount((current) => {
            if (current === null) setError("Couldn't load your account.");
            return current;
          });
          retryTimeout = setTimeout(load, RETRY_DELAY_MS);
        });
    };
    load();
    window.addEventListener("focus", load);
    return () => {
      mounted = false;
      window.removeEventListener("focus", load);
      stopPollRef.current?.();
      if (retryTimeout) clearTimeout(retryTimeout);
    };
  }, [retryTick]);
 
  const handleUpgrade = async () => {
    setCheckoutBusy(true);
    setError(null);
    try {
      const { checkoutUrl } = await startCheckout();
      window.open(checkoutUrl, "_blank", "noopener,noreferrer");
      stopPollRef.current?.();
      stopPollRef.current = pollForUpgrade((next) => setAccount(next));
    } catch (err) {
      setError(
        err instanceof AlreadyPremiumError
          ? "You're already on Premium."
          : "Couldn't open checkout. Try again."
      );
    } finally {
      setCheckoutBusy(false);
    }
  };
 
  const handleManage = async () => {
    setPortalBusy(true);
    setError(null);
    try {
      const { portalUrl } = await openBillingPortal();
      window.open(portalUrl, "_blank", "noopener,noreferrer");
    } catch (err) {
      setError(
        err instanceof NoSubscriptionError
          ? "No subscription to manage yet."
          : "Couldn't open the portal. Try again."
      );
    } finally {
      setPortalBusy(false);
    }
  };
 
  if (!account) {
    return (
      <div
        role="status"
        aria-label="Loading account"
        className="flex items-center gap-2 border-b border-gray-200/70 bg-white px-3 py-1.5 text-xs text-gray-400 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-500"
      >
        {error ?? "Loading…"}
        {error && (
          <button
            onClick={() => setRetryTick((tick) => tick + 1)}
            className="font-medium text-blue-600 underline hover:text-blue-700 dark:text-blue-400"
          >
            Retry
          </button>
        )}
      </div>
    );
  }
 
  const planLabel = account.tier === "premium" ? "Premium" : "Free";
 
  return (
    <div className="flex flex-col gap-1 border-b border-gray-200/70 bg-white px-3 py-1.5 text-xs dark:border-gray-800 dark:bg-gray-900">
      <div className="flex items-center justify-between gap-2">
        <div className="flex min-w-0 flex-col">
          <div className="flex items-center gap-1.5">
            <span
              aria-label={`Plan: ${planLabel}`}
              className={`rounded-full px-1.5 py-0.5 text-[10px] font-semibold ${
                account.tier === "premium"
                  ? "bg-blue-100 text-blue-800 dark:bg-blue-950/60 dark:text-blue-300"
                  : "bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300"
              }`}
            >
              {planLabel}
            </span>
            <span className="text-gray-500 dark:text-gray-400">
              {account.usage.count} of {account.usage.limit} analyses this month
            </span>
          </div>
          <span className="text-[10px] text-gray-400 dark:text-gray-500">
            {describeSubscription(account)}
          </span>
        </div>
        <div className="flex shrink-0 items-center gap-1.5">
          {account.tier === "free" && (
            <button
              onClick={() => void handleUpgrade()}
              aria-label="Upgrade to Premium"
              aria-busy={checkoutPending}
              disabled={checkoutBusy}
              className="rounded-md bg-blue-600 px-2 py-1 text-[11px] font-semibold text-white transition-colors hover:bg-blue-700 disabled:cursor-wait disabled:opacity-70"
            >
              {checkoutPending ? "Opening…" : "Upgrade"}
            </button>
          )}
          {account.subscription && (
            <button
              onClick={() => void handleManage()}
              aria-label="Manage subscription"
              aria-busy={portalPending}
              disabled={portalBusy}
              className="rounded-md px-2 py-1 text-[11px] font-medium text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 disabled:cursor-wait disabled:opacity-70 dark:text-gray-400 dark:hover:bg-gray-800"
            >
              {portalPending ? "Opening…" : "Manage subscription"}
            </button>
          )}
          {WXT_WEB_APP_URL && (
            <>
              <a
                href={WXT_WEB_APP_URL}
                target="_blank"
                rel="noopener noreferrer"
                title={WEB_APP_NOTE}
                aria-describedby={webAppNoteId}
                className="inline-flex min-h-6 min-w-6 shrink-0 items-center gap-1 rounded-md border border-gray-200 px-2 py-1 text-[11px] font-medium text-gray-600 transition-colors hover:bg-gray-100 hover:text-gray-800 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="11"
                  height="11"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2.5"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  aria-hidden="true"
                >
                  <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
                  <path d="M15 3h6v6" />
                  <path d="M10 14 21 3" />
                </svg>
                Web app
              </a>
              <span id={webAppNoteId} className="sr-only">
                {WEB_APP_NOTE}
              </span>
            </>
          )}
        </div>
      </div>
      {error && (
        <p role="alert" className="text-[10px] text-red-600 dark:text-red-400">
          {error}
        </p>
      )}
    </div>
  );
}
 
/** Stable display vocabulary (Principle III, contracts/billing-api.md).
 * Keyed off account.tier first — the backend keeps a subscription record
 * around after full cancellation (subscriptionStatus stays a truthy
 * "canceled" string), so subscription presence alone can't distinguish a
 * downgraded account from an active one. */
function describeSubscription(account: AccountState): string {
  const sub = account.subscription;
  if (account.tier !== "premium") return "Free plan";
  if (!sub) return "Premium";
  if (sub.status === "past_due") {
    return "Payment problem — update your payment method";
  }
  if (sub.endsAt) return `Premium until ${formatDate(sub.endsAt)}`;
  if (sub.renewsAt) return `Renews on ${formatDate(sub.renewsAt)}`;
  return "Premium";
}
 
function formatDate(iso: string): string {
  return new Date(iso).toLocaleDateString("en-US", {
    month: "long",
    day: "numeric",
    timeZone: "UTC",
  });
}
 
/** True only once `active` has held for more than delayMs (>300ms feedback contract). */
function useDelayedPending(active: boolean, delayMs = 300): boolean {
  const [pending, setPending] = useState(false);
  useEffect(() => {
    if (!active) {
      setPending(false);
      return;
    }
    const id = setTimeout(() => setPending(true), delayMs);
    return () => clearTimeout(id);
  }, [active, delayMs]);
  return pending;
}