Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

feat(billing): self-serve Enterprise upgrade + admin console entry (#1623)

Gabriel Steine03986111549
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index c39668adc..ae9c9d011 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -133,7 +133,10 @@ import { usePolicyModeOptions, usePolicySnapshot } from "../hooks/usePolicy";
import { usePolicyStore } from "../stores/policyStore";
import { canManageSystemAudioInApp } from "../utils/systemAudioAccess";
import WorkspaceSection from "./settings/WorkspaceSection";
+import { enterpriseTileCta, type EnterpriseTileCta } from "../lib/workspaceBilling";
import WorkspaceBillingOverview from "./settings/WorkspaceBillingOverview";
+import EnterpriseCheckoutDialog from "./settings/EnterpriseCheckoutDialog";
+import CreateWorkspaceDialog from "./CreateWorkspaceDialog";
import ProfileSection from "./settings/ProfileSection";
import { formatAmount } from "../utils/formatAmount";
import { getTranscriptionProvider } from "../models/ModelRegistry";
@@ -1047,6 +1050,16 @@ export default function SettingsPage({
const { theme, setTheme } = useTheme();
const usage = useUsage();
const billingWorkspaces = useWorkspaceStore((s) => s.workspaces);
+ const activeWorkspaceId = useWorkspaceStore((s) => s.activeWorkspaceId);
+ const billingWorkspacesLoaded = useWorkspaceStore((s) => s.loaded);
+ const [enterpriseCheckoutOpen, setEnterpriseCheckoutOpen] = useState(false);
+ const [enterpriseWorkspaceCreateOpen, setEnterpriseWorkspaceCreateOpen] = useState(false);
+ // Until the store resolves, an empty list would make enterpriseTileCta answer
+ // "createWorkspace" for everyone — including members who must never be routed
+ // into creating a workspace. Fall back to contact sales for that window.
+ const enterpriseCta: EnterpriseTileCta = billingWorkspacesLoaded
+ ? enterpriseTileCta(billingWorkspaces, activeWorkspaceId)
+ : { action: "contactSales", ownerName: null };
const coveringWorkspaces = billingWorkspaces.filter((workspace) =>
usage?.entitledWorkspaceIds?.includes(workspace.id)
);
@@ -2378,17 +2391,73 @@ export default function SettingsPage({
</li>
))}
</ul>
- <Button
- variant="outline"
- size="sm"
- className="mt-2 w-full h-6 text-[10px]"
- onClick={() =>
- window.electronAPI?.openExternal?.("https://openwhispr.com/contact-sales")
- }
- >
- <Mail size={10} />
- {t("settingsPage.account.pricing.enterprise.cta")}
- </Button>
+ {isSignedIn && enterpriseCta.action !== "contactSales" ? (
+ <div className="mt-2 space-y-1">
+ <Button
+ size="sm"
+ className="w-full h-6 text-[10px]"
+ onClick={() => {
+ if (enterpriseCta.action === "openDialog") {
+ setEnterpriseCheckoutOpen(true);
+ } else {
+ setEnterpriseWorkspaceCreateOpen(true);
+ }
+ }}
+ >
+ {t("settingsPage.account.pricing.enterprise.upgradeCta")}
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="w-full h-6 text-[10px] text-muted-foreground"
+ onClick={() =>
+ window.electronAPI?.openExternal?.(
+ "https://openwhispr.com/contact-sales"
+ )
+ }
+ >
+ <Mail size={10} />
+ {t("settingsPage.account.pricing.enterprise.cta")}
+ </Button>
+ </div>
+ ) : isSignedIn ? (
+ <div className="mt-2 space-y-1">
+ <Button
+ variant="outline"
+ size="sm"
+ className="w-full h-6 text-[10px]"
+ onClick={() =>
+ window.electronAPI?.openExternal?.(
+ "https://openwhispr.com/contact-sales"
+ )
+ }
+ >
+ <Mail size={10} />
+ {t("settingsPage.account.pricing.enterprise.cta")}
+ </Button>
+ {enterpriseCta.action === "contactSales" && enterpriseCta.ownerName && (
+ <p className="text-[10px] text-muted-foreground text-center">
+ {t("settingsPage.account.pricing.enterprise.askOwner", {
+ name: enterpriseCta.ownerName,
+ })}
+ </p>
+ )}
+ </div>
+ ) : (
+ <Button
+ variant="outline"
+ size="sm"
+ className="mt-2 w-full h-6 text-[10px]"
+ onClick={() =>
+ window.electronAPI?.openExternal?.(
+ "https://openwhispr.com/contact-sales"
+ )
+ }
+ >
+ <Mail size={10} />
+ {t("settingsPage.account.pricing.enterprise.cta")}
+ </Button>
+ )}
</div>
</div>
@@ -2478,6 +2547,18 @@ export default function SettingsPage({
</DialogFooter>
</DialogContent>
</Dialog>
+
+ <EnterpriseCheckoutDialog
+ open={enterpriseCheckoutOpen}
+ onOpenChange={setEnterpriseCheckoutOpen}
+ workspaces={billingWorkspaces}
+ onRefreshEntitlement={usage?.refetch}
+ />
+ <CreateWorkspaceDialog
+ open={enterpriseWorkspaceCreateOpen}
+ onOpenChange={setEnterpriseWorkspaceCreateOpen}
+ onCreated={() => setEnterpriseCheckoutOpen(true)}
+ />
</div>
</>
) : (
diff --git a/src/components/settings/EnterpriseCheckoutDialog.tsx b/src/components/settings/EnterpriseCheckoutDialog.tsx
new file mode 100644
index 000000000..168c05fbe
--- /dev/null
+++ b/src/components/settings/EnterpriseCheckoutDialog.tsx
@@ -0,0 +1,366 @@
+import React, { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Loader2, Mail } from "lucide-react";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "../ui/dialog";
+import { Button } from "../ui/button";
+import { Input } from "../ui/input";
+import { Label } from "../ui/label";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
+import { useToast } from "../ui/useToast";
+import { CloudApiError } from "../../services/cloudApi";
+import { WorkspacesService, type EnterpriseUpgradePreview } from "../../services/WorkspacesService";
+import { useBillingRefreshOnReturn } from "../../hooks/useBillingRefreshOnReturn";
+import { useWorkspaceStore } from "../../stores/workspaceStore";
+import {
+ canSelfServeEnterprise,
+ canUpgradeWorkspaceToEnterprise,
+} from "../../lib/workspaceBilling";
+import { formatAmount } from "../../utils/formatAmount";
+import { openExternalLink } from "../../utils/externalLinks";
+import type { Workspace } from "../../types/electron";
+
+const SEAT_LIMIT = 500;
+const CONTACT_SALES_URL = "https://openwhispr.com/contact-sales";
+
+// The API's coded billing refusals, localized; uncoded errors fall back to
+// the server's own message.
+const BILLING_ERROR_KEYS: Record<string, string> = {
+ workspace_already_enterprise: "settingsPage.enterpriseCheckout.errors.alreadyEnterprise",
+ workspace_subscription_inactive: "settingsPage.enterpriseCheckout.errors.subscriptionInactive",
+ price_not_configured: "settingsPage.enterpriseCheckout.errors.priceNotConfigured",
+};
+
+function billingErrorMessage(error: unknown, t: ReturnType<typeof useTranslation>["t"]): string {
+ const key =
+ error instanceof CloudApiError && error.code ? BILLING_ERROR_KEYS[error.code] : undefined;
+ if (key) return t(key);
+ return error instanceof Error && error.message ? error.message : t("common.unknownError");
+}
+
+interface Props {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ workspaces: Workspace[];
+ onRefreshEntitlement?: () => Promise<void> | void;
+}
+
+export default function EnterpriseCheckoutDialog({
+ open,
+ onOpenChange,
+ workspaces,
+ onRefreshEntitlement,
+}: Props) {
+ const { t } = useTranslation();
+ const { toast } = useToast();
+ const refresh = useWorkspaceStore((s) => s.refresh);
+ const armRefreshOnReturn = useBillingRefreshOnReturn(() => {
+ void refresh();
+ void onRefreshEntitlement?.();
+ });
+
+ // New workspaces go through Stripe Checkout; already-subscribed ones swap
+ // the subscription price in place (no browser round-trip).
+ const eligible = useMemo(
+ () =>
+ workspaces.filter(
+ (workspace) =>
+ canSelfServeEnterprise(workspace) || canUpgradeWorkspaceToEnterprise(workspace)
+ ),
+ [workspaces]
+ );
+ const [workspaceId, setWorkspaceId] = useState<string | null>(null);
+ const [billingInterval, setBillingInterval] = useState<"monthly" | "annual">("monthly");
+ const [submitting, setSubmitting] = useState(false);
+ const [upgradePreview, setUpgradePreview] = useState<EnterpriseUpgradePreview | null>(null);
+ const [previewLoading, setPreviewLoading] = useState(false);
+ const [previewError, setPreviewError] = useState<string | null>(null);
+ const [previewAttempt, setPreviewAttempt] = useState(0);
+
+ const selected = eligible.find((w) => w.id === workspaceId) ?? eligible[0] ?? null;
+ const isUpgrade = selected !== null && canUpgradeWorkspaceToEnterprise(selected);
+ const seatsInUse = Math.max(1, selected?.seats_used ?? 1);
+ const [seats, setSeats] = useState(seatsInUse);
+
+ useEffect(() => {
+ if (open) {
+ setWorkspaceId(null);
+ setBillingInterval("monthly");
+ setSeats(seatsInUse);
+ }
+ // Reset to defaults on every open; seatsInUse is read, not watched.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open]);
+
+ // Reset the seat count whenever the effective workspace changes.
+ useEffect(() => {
+ setSeats(seatsInUse);
+ // seatsInUse is read, not watched: a store refresh landing mid-dialog must
+ // not clobber a seat count the user already typed.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [selected?.id]);
+
+ // If a refresh raises the occupancy floor, lift the count to stay valid —
+ // never lower a higher value the user chose.
+ useEffect(() => {
+ setSeats((current) => Math.max(current, seatsInUse));
+ }, [seatsInUse]);
+
+ const selectedId = selected?.id ?? null;
+ useEffect(() => {
+ setUpgradePreview(null);
+ setPreviewError(null);
+ if (!open || !isUpgrade || !selectedId) return;
+ let stale = false;
+ setPreviewLoading(true);
+ WorkspacesService.previewEnterpriseUpgrade(selectedId)
+ .then((preview) => {
+ if (!stale) setUpgradePreview(preview);
+ })
+ .catch((error: unknown) => {
+ if (!stale) setPreviewError(billingErrorMessage(error, t));
+ })
+ .finally(() => {
+ if (!stale) setPreviewLoading(false);
+ });
+ return () => {
+ stale = true;
+ };
+ }, [open, isUpgrade, selectedId, previewAttempt, t]);
+
+ const seatsValid = Number.isInteger(seats) && seats >= seatsInUse && seats <= SEAT_LIMIT;
+
+ async function handleCheckout() {
+ if (submitting || !selected || !seatsValid) return;
+ setSubmitting(true);
+ try {
+ const url = await WorkspacesService.billingCheckout(selected.id, billingInterval, {
+ tier: "enterprise",
+ additionalSeats: seats - seatsInUse,
+ });
+ openExternalLink(url);
+ armRefreshOnReturn();
+ onOpenChange(false);
+ } catch (error) {
+ toast({
+ title: t("common.error"),
+ description: billingErrorMessage(error, t),
+ variant: "destructive",
+ });
+ } finally {
+ setSubmitting(false);
+ }
+ }
+
+ async function handleUpgrade() {
+ if (submitting || !selected) return;
+ setSubmitting(true);
+ try {
+ await WorkspacesService.upgradeToEnterprise(selected.id);
+ await refresh();
+ await onRefreshEntitlement?.();
+ toast({
+ title: t("settingsPage.enterpriseCheckout.upgradedTitle"),
+ description: t("settingsPage.enterpriseCheckout.upgradedDescription", {
+ workspace: selected.name,
+ }),
+ });
+ onOpenChange(false);
+ } catch (error) {
+ toast({
+ title: t("common.error"),
+ description: billingErrorMessage(error, t),
+ variant: "destructive",
+ });
+ } finally {
+ setSubmitting(false);
+ }
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={(next) => !submitting && onOpenChange(next)}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>{t("settingsPage.enterpriseCheckout.title")}</DialogTitle>
+ <DialogDescription>
+ {isUpgrade && selected
+ ? t("settingsPage.enterpriseCheckout.upgradeDescription", {
+ workspace: selected.name,
+ plan: t(`settingsPage.workspace.billing.planLabel.${selected.plan}`, {
+ defaultValue: selected.plan,
+ }),
+ })
+ : eligible.length > 0
+ ? t("settingsPage.enterpriseCheckout.description")
+ : t("settingsPage.enterpriseCheckout.allSubscribed")}
+ </DialogDescription>
+ </DialogHeader>
+
+ {eligible.length > 0 ? (
+ <div className="space-y-4">
+ {eligible.length > 1 && selected && (
+ <div className="space-y-1.5">
+ <Label className="text-xs font-medium">
+ {t("settingsPage.enterpriseCheckout.workspaceLabel")}
+ </Label>
+ <Select value={selected.id} onValueChange={setWorkspaceId}>
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {eligible.map((w) => (
+ <SelectItem key={w.id} value={w.id}>
+ {w.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ )}
+
+ {isUpgrade ? (
+ previewLoading ? (
+ <div className="flex justify-center py-4">
+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
+ </div>
+ ) : upgradePreview ? (
+ <>
+ <div className="rounded-lg border border-border/50 divide-y divide-border/40">
+ <div className="flex justify-between px-3 py-2 text-xs">
+ <span className="text-muted-foreground">
+ {t("settingsPage.enterpriseCheckout.proratedCharge")}
+ </span>
+ <span className="font-medium">
+ {formatAmount(upgradePreview.prorated_amount, upgradePreview.currency)}
+ </span>
+ </div>
+ <div className="flex justify-between px-3 py-2 text-xs">
+ <span className="text-muted-foreground">
+ {t("settingsPage.enterpriseCheckout.seatsLabel")}
+ </span>
+ <span className="font-medium">{upgradePreview.quantity}</span>
+ </div>
+ {upgradePreview.next_billing_date && (
+ <div className="flex justify-between px-3 py-2 text-xs">
+ <span className="text-muted-foreground">
+ {t("settingsPage.workspace.billing.nextInvoice")}
+ </span>
+ <span className="font-medium">
+ {new Date(upgradePreview.next_billing_date).toLocaleDateString()}
+ </span>
+ </div>
+ )}
+ </div>
+ <p className="text-[11px] text-muted-foreground">
+ {t("settingsPage.enterpriseCheckout.prorationNote")}
+ </p>
+ </>
+ ) : previewError ? (
+ <div className="space-y-2 rounded-lg border border-border/50 px-3 py-3">
+ <p className="text-xs font-medium">
+ {t("settingsPage.enterpriseCheckout.errors.previewFailed")}
+ </p>
+ <p className="text-[11px] text-muted-foreground">{previewError}</p>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setPreviewAttempt((attempt) => attempt + 1)}
+ >
+ {t("common.retry")}
+ </Button>
+ </div>
+ ) : null
+ ) : (
+ <>
+ <div className="space-y-1.5">
+ <Label htmlFor="enterprise-seats" className="text-xs font-medium">
+ {t("settingsPage.enterpriseCheckout.seatsLabel")}
+ </Label>
+ <Input
+ id="enterprise-seats"
+ type="number"
+ min={seatsInUse}
+ max={SEAT_LIMIT}
+ value={seats}
+ onChange={(e) => setSeats(Number(e.target.value))}
+ aria-invalid={!seatsValid}
+ />
+ <p className="text-[11px] text-muted-foreground">
+ {t("settingsPage.enterpriseCheckout.seatsHint", { count: seatsInUse })}
+ </p>
+ </div>
+
+ <div className="space-y-1.5">
+ <Label className="text-xs font-medium">
+ {t("settingsPage.enterpriseCheckout.intervalLabel")}
+ </Label>
+ <div className="flex gap-2">
+ {(["monthly", "annual"] as const).map((option) => (
+ <Button
+ key={option}
+ type="button"
+ size="sm"
+ variant={billingInterval === option ? "default" : "outline"}
+ onClick={() => setBillingInterval(option)}
+ >
+ {t(`settingsPage.enterpriseCheckout.interval.${option}`)}
+ </Button>
+ ))}
+ </div>
+ </div>
+
+ <p className="text-[11px] text-muted-foreground">
+ {t("settingsPage.enterpriseCheckout.priceNote")}
+ </p>
+ </>
+ )}
+ </div>
+ ) : null}
+
+ <DialogFooter>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={submitting}
+ onClick={() => onOpenChange(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ {eligible.length > 0 ? (
+ isUpgrade ? (
+ <Button
+ size="sm"
+ onClick={() => void handleUpgrade()}
+ disabled={submitting || !upgradePreview}
+ >
+ {submitting && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
+ {t("settingsPage.enterpriseCheckout.upgradeCta")}
+ </Button>
+ ) : (
+ <Button
+ size="sm"
+ onClick={() => void handleCheckout()}
+ disabled={submitting || !selected || !seatsValid}
+ >
+ {submitting && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
+ {t("settingsPage.enterpriseCheckout.continueCta")}
+ </Button>
+ )
+ ) : (
+ <Button size="sm" onClick={() => window.electronAPI?.openExternal?.(CONTACT_SALES_URL)}>
+ <Mail className="mr-1.5 h-3.5 w-3.5" />
+ {t("settingsPage.account.pricing.enterprise.cta")}
+ </Button>
+ )}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/settings/EnterpriseConsoleRow.tsx b/src/components/settings/EnterpriseConsoleRow.tsx
new file mode 100644
index 000000000..0a3e2da51
--- /dev/null
+++ b/src/components/settings/EnterpriseConsoleRow.tsx
@@ -0,0 +1,57 @@
+import React, { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { ExternalLink, Loader2, ShieldCheck } from "lucide-react";
+import { Button } from "../ui/button";
+import { openAdminConsole } from "../../lib/auth";
+import { isEnterpriseConsoleAvailable } from "../../lib/workspaceBilling";
+import type { Workspace } from "../../types/electron";
+
+/**
+ * Entry point to the web admin console (admin.openwhispr.com) for
+ * owners/admins of an Enterprise workspace. Renders nothing otherwise.
+ */
+export default function EnterpriseConsoleRow({ workspace }: { workspace: Workspace }) {
+ const { t } = useTranslation();
+ const [opening, setOpening] = useState(false);
+
+ if (!isEnterpriseConsoleAvailable(workspace)) return null;
+
+ async function handleOpen() {
+ setOpening(true);
+ try {
+ await openAdminConsole();
+ } finally {
+ setOpening(false);
+ }
+ }
+
+ return (
+ <div className="rounded-md border border-border/50 dark:border-border-subtle/60 bg-card/30 dark:bg-surface-2/30 p-3 flex items-center justify-between gap-3">
+ <div className="flex items-center gap-2 min-w-0">
+ <ShieldCheck className="h-4 w-4 text-primary shrink-0" />
+ <div className="min-w-0">
+ <p className="text-xs font-medium text-foreground">
+ {t("settingsPage.workspace.enterpriseConsole.title")}
+ </p>
+ <p className="text-[10px] text-muted-foreground">
+ {t("settingsPage.workspace.enterpriseConsole.description")}
+ </p>
+ </div>
+ </div>
+ <Button
+ onClick={() => void handleOpen()}
+ disabled={opening}
+ size="sm"
+ variant="outline"
+ className="shrink-0"
+ >
+ {opening ? (
+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <ExternalLink className="mr-1.5 h-3.5 w-3.5" />
+ )}
+ {t("settingsPage.workspace.enterpriseConsole.open")}
+ </Button>
+ </div>
+ );
+}
diff --git a/src/components/settings/WorkspaceBillingCard.tsx b/src/components/settings/WorkspaceBillingCard.tsx
index c94454b89..e9423d246 100644
--- a/src/components/settings/WorkspaceBillingCard.tsx
+++ b/src/components/settings/WorkspaceBillingCard.tsx
@@ -1,7 +1,9 @@
-import React, { useEffect, useRef, useState } from "react";
+import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { ExternalLink, Loader2, Plus } from "lucide-react";
import { Button } from "../ui/button";
+import EnterpriseConsoleRow from "./EnterpriseConsoleRow";
+import { useBillingRefreshOnReturn } from "../../hooks/useBillingRefreshOnReturn";
import {
Dialog,
DialogContent,
@@ -13,6 +15,7 @@ import {
import { useToast } from "../ui/useToast";
import { WorkspacesService, type SeatPreview } from "../../services/WorkspacesService";
import { useWorkspaceStore } from "../../stores/workspaceStore";
+import { hasActiveWorkspaceSubscription } from "../../lib/workspaceBilling";
import { formatAmount } from "../../utils/formatAmount";
import type { Workspace } from "../../types/electron";
@@ -27,37 +30,17 @@ export default function WorkspaceBillingCard({ workspace, onRefreshEntitlement }
const refresh = useWorkspaceStore((s) => s.refresh);
const [busy, setBusy] = useState<"checkout" | "portal" | "preview" | "seats" | null>(null);
const [seatPreview, setSeatPreview] = useState<SeatPreview | null>(null);
- const focusCleanupRef = useRef<(() => void) | null>(null);
+ const refreshOnReturn = useBillingRefreshOnReturn(() => {
+ void refresh();
+ void onRefreshEntitlement?.();
+ });
const isOwner = workspace.role === "owner";
const hasSubscription = Boolean(workspace.stripe_subscription_id);
- const canAddSeats =
- hasSubscription &&
- ["pro", "business", "enterprise"].includes(workspace.plan) &&
- ["active", "trialing"].includes(workspace.status);
+ const canAddSeats = hasSubscription && hasActiveWorkspaceSubscription(workspace);
const seatsUsed = workspace.seats_used ?? workspace.seats;
const seatsTotal = Math.max(workspace.seats, seatsUsed);
const pct = seatsTotal > 0 ? Math.min(100, (seatsUsed / seatsTotal) * 100) : 0;
- useEffect(() => () => focusCleanupRef.current?.(), []);
-
- function refreshOnReturn() {
- focusCleanupRef.current?.();
- const timers: ReturnType<typeof setTimeout>[] = [];
- const poll = () => {
- void refresh();
- void onRefreshEntitlement?.();
- };
- const onFocus = () => {
- poll();
- for (const delayMs of [4000, 8000, 16000]) timers.push(setTimeout(poll, delayMs));
- };
- window.addEventListener("focus", onFocus, { once: true });
- focusCleanupRef.current = () => {
- window.removeEventListener("focus", onFocus);
- timers.forEach(clearTimeout);
- };
- }
-
async function openBilling(kind: "checkout" | "portal", getUrl: () => Promise<string>) {
setBusy(kind);
try {
@@ -237,6 +220,8 @@ export default function WorkspaceBillingCard({ workspace, onRefreshEntitlement }
</div>
)}
+ <EnterpriseConsoleRow workspace={workspace} />
+
<Dialog open={seatPreview !== null} onOpenChange={(open) => !open && setSeatPreview(null)}>
<DialogContent className="sm:max-w-90">
<DialogHeader>
diff --git a/src/components/settings/WorkspaceSection.tsx b/src/components/settings/WorkspaceSection.tsx
index 6bc72b203..c85ffa16d 100644
--- a/src/components/settings/WorkspaceSection.tsx
+++ b/src/components/settings/WorkspaceSection.tsx
@@ -27,6 +27,7 @@ import { canManageWorkspace } from "../../lib/spacePermissions";
import WorkspaceMembersTab from "./WorkspaceMembersTab";
import WorkspaceTeamsTab from "./WorkspaceTeamsTab";
import WorkspaceDeveloperTab from "./WorkspaceDeveloperTab";
+import EnterpriseConsoleRow from "./EnterpriseConsoleRow";
import type { Workspace } from "../../types/electron";
const SUB_TABS = ["general", "members", "teams", "developer"] as const;
@@ -344,6 +345,8 @@ function GeneralTab({ workspace }: { workspace: Workspace }) {
</SettingsPanelRow>
</SettingsPanel>
+ <EnterpriseConsoleRow workspace={workspace} />
+
{isOwner ? (
<SettingsPanel>
<SettingsPanelRow>
diff --git a/src/hooks/useBillingRefreshOnReturn.ts b/src/hooks/useBillingRefreshOnReturn.ts
new file mode 100644
index 000000000..586cc35a1
--- /dev/null
+++ b/src/hooks/useBillingRefreshOnReturn.ts
@@ -0,0 +1,34 @@
+import { useCallback, useRef } from "react";
+
+const POLL_DELAYS_MS = [4000, 8000, 16000];
+
+let cancelWatch: (() => void) | null = null;
+
+/**
+ * Post-checkout/portal refresh: billing happens in the external browser, so
+ * the next window focus is the earliest signal the user may be done. Refresh
+ * immediately on focus, then re-poll on a short backoff while Stripe's
+ * webhook lands. The watch lives at module scope so it survives the arming
+ * component unmounting while the user is off in Stripe; arming again from
+ * anywhere cancels the previous watch (one pending watch at a time).
+ */
+export function armBillingRefreshOnReturn(refresh: () => void): void {
+ cancelWatch?.();
+ const timers: ReturnType<typeof setTimeout>[] = [];
+ const onFocus = () => {
+ refresh();
+ for (const delayMs of POLL_DELAYS_MS) timers.push(setTimeout(refresh, delayMs));
+ };
+ window.addEventListener("focus", onFocus, { once: true });
+ cancelWatch = () => {
+ window.removeEventListener("focus", onFocus);
+ timers.forEach(clearTimeout);
+ };
+}
+
+/** Component wrapper: the armed watch always calls the latest render's callback. */
+export function useBillingRefreshOnReturn(refresh: () => void): () => void {
+ const refreshRef = useRef(refresh);
+ refreshRef.current = refresh;
+ return useCallback(() => armBillingRefreshOnReturn(() => refreshRef.current()), []);
+}
diff --git a/src/lib/auth.ts b/src/lib/auth.ts
index 1a28760d6..d62fee9ac 100644
--- a/src/lib/auth.ts
+++ b/src/lib/auth.ts
@@ -306,6 +306,36 @@ export async function changePassword(params: {
}
}
+export const ADMIN_URL = import.meta.env.VITE_ADMIN_URL || "https://admin.openwhispr.com";
+
+/**
+ * Open the enterprise admin console signed in: the desktop session lives in
+ * the app (bearer token), not the user's browser, so a single-use short-lived
+ * token carries it across. Verification on the console's /handoff page sets
+ * the cross-subdomain session cookie. If token generation fails for any
+ * reason, fall back to the bare console URL and let the user sign in there.
+ */
+export async function openAdminConsole(): Promise<void> {
+ let url = ADMIN_URL;
+ try {
+ // The generated $fetch types don't discriminate on `throw`, and the
+ // payload arrives bare or under `data` depending on the client version.
+ const result = (await authClient.$fetch("/one-time-token/generate", { throw: true })) as {
+ token?: string;
+ data?: { token?: string } | null;
+ };
+ const token = result.token ?? result.data?.token;
+ if (token) {
+ // The token rides the URL fragment so it never reaches server logs,
+ // proxies, or analytics beacons — the console reads it client-side.
+ url = `${ADMIN_URL}/handoff#token=${encodeURIComponent(token)}`;
+ }
+ } catch {
+ // Fall through to the bare console URL.
+ }
+ openExternalLink(url);
+}
+
// Cache only successful results; errors fail open without being cached. Cleared
// in signOut() so a different account never inherits a stale value.
let credentialAccountCache: boolean | null = null;
diff --git a/src/lib/workspaceBilling.ts b/src/lib/workspaceBilling.ts
new file mode 100644
index 000000000..1b5fab61c
--- /dev/null
+++ b/src/lib/workspaceBilling.ts
@@ -0,0 +1,91 @@
+import type { Workspace } from "../types/electron";
+import { canManageWorkspace } from "./spacePermissions.ts";
+
+const PAID_PLANS = new Set(["pro", "business", "enterprise"]);
+const ENTITLED_STATUSES = new Set(["active", "trialing"]);
+
+type WorkspaceBillingState = Pick<Workspace, "plan" | "status" | "role" | "stripe_subscription_id">;
+
+/** Mirrors the API's `hasActiveWorkspaceSubscription`: a paid plan that is currently entitled. */
+export function hasActiveWorkspaceSubscription(
+ workspace: Pick<WorkspaceBillingState, "plan" | "status">
+): boolean {
+ return PAID_PLANS.has(workspace.plan) && ENTITLED_STATUSES.has(workspace.status);
+}
+
+/**
+ * Mirrors the API's workspace checkout guard: only an owned workspace with no
+ * live Stripe subscription and no active plan can start a self-serve
+ * Enterprise checkout. Client checks are cosmetic — the server enforces (409).
+ */
+export function canSelfServeEnterprise(workspace: WorkspaceBillingState): boolean {
+ return (
+ workspace.role === "owner" &&
+ !workspace.stripe_subscription_id &&
+ !hasActiveWorkspaceSubscription(workspace)
+ );
+}
+
+/** Mirrors the admin console's own gate: entitled Enterprise plan + owner/admin role. */
+export function isEnterpriseConsoleAvailable(
+ workspace: Pick<WorkspaceBillingState, "plan" | "status" | "role">
+): boolean {
+ return (
+ workspace.plan === "enterprise" &&
+ ENTITLED_STATUSES.has(workspace.status) &&
+ canManageWorkspace(workspace.role)
+ );
+}
+
+/**
+ * An owned workspace with a live, entitled Stripe subscription on a lower plan
+ * can upgrade in place (subscription price swap, no new checkout). Manually
+ * provisioned plans have no subscription to update, so they stay sales-led.
+ */
+export function canUpgradeWorkspaceToEnterprise(workspace: WorkspaceBillingState): boolean {
+ return (
+ workspace.role === "owner" &&
+ Boolean(workspace.stripe_subscription_id) &&
+ hasActiveWorkspaceSubscription(workspace) &&
+ workspace.plan !== "enterprise"
+ );
+}
+
+export type EnterpriseTileCta =
+ | { action: "openDialog" }
+ | { action: "createWorkspace" }
+ | { action: "contactSales"; ownerName: string | null };
+
+/**
+ * Which CTA the Enterprise pricing tile leads with: owners of a workspace the
+ * dialog can actually serve (fresh checkout or in-place upgrade) get the
+ * purchase dialog, users with no workspace at all get the create-workspace
+ * on-ramp, and members/admins of someone else's workspace are pointed at the
+ * owner — upgrading in-app would otherwise create a workspace they didn't
+ * want. Owners whose workspaces are all ineligible (e.g. already Enterprise)
+ * get plain contact sales: they are the decision makers, so no ask-owner hint.
+ */
+export function enterpriseTileCta(
+ workspaces: Array<
+ Pick<
+ Workspace,
+ "id" | "role" | "billing_manager" | "plan" | "status" | "stripe_subscription_id"
+ >
+ >,
+ activeWorkspaceId: string | null
+): EnterpriseTileCta {
+ if (
+ workspaces.some(
+ (workspace) => canSelfServeEnterprise(workspace) || canUpgradeWorkspaceToEnterprise(workspace)
+ )
+ ) {
+ return { action: "openDialog" };
+ }
+ if (workspaces.length === 0) return { action: "createWorkspace" };
+ if (workspaces.some((workspace) => workspace.role === "owner")) {
+ return { action: "contactSales", ownerName: null };
+ }
+ const target =
+ workspaces.find((workspace) => workspace.id === activeWorkspaceId) ?? workspaces[0];
+ return { action: "contactSales", ownerName: target.billing_manager ?? null };
+}
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 2789557c7..a3d40b7ab 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -1692,6 +1692,11 @@
"admin": "Workspace-Administrator"
}
}
+ },
+ "enterpriseConsole": {
+ "title": "Enterprise-Konsole",
+ "description": "SSO, Richtlinien und Mitglieder im Web verwalten",
+ "open": "Konsole öffnen"
}
},
"unifiedBilling": {
@@ -1836,7 +1841,9 @@
"SSO & Compliance",
"Dedizierter Support"
],
- "cta": "Vertrieb kontaktieren"
+ "cta": "Vertrieb kontaktieren",
+ "upgradeCta": "Auf Enterprise upgraden",
+ "askOwner": "Bitte {{name}}, euren Workspace zu upgraden."
},
"currentPlan": "Aktueller Tarif",
"coveredByWorkspace": "In Ihrem Workspace-Tarif enthalten",
@@ -2479,6 +2486,34 @@
"endpointUrl": "Endpunkt-URL",
"serverUrl": "Server-URL",
"apiKeyOptional": "API-Schlüssel (optional)"
+ },
+ "enterpriseCheckout": {
+ "title": "Auf Enterprise upgraden",
+ "description": "Workspace, Plätze und Abrechnungszeitraum wählen. Die Zahlung erfolgt im Stripe-Checkout.",
+ "allSubscribed": "Die Workspaces, die dir gehören, sind bereits auf Enterprise oder können hier nicht geändert werden. Für Plan-Änderungen kontaktiere den Vertrieb.",
+ "workspaceLabel": "Workspace",
+ "seatsLabel": "Plätze",
+ "seatsHint_one": "{{count}} Platz derzeit belegt",
+ "seatsHint_other": "{{count}} Plätze derzeit belegt",
+ "intervalLabel": "Abrechnungszeitraum",
+ "interval": {
+ "monthly": "Monatlich",
+ "annual": "Jährlich"
+ },
+ "proratedCharge": "Anteiliger Betrag",
+ "prorationNote": "Die anteilige Differenz wird der nächsten Rechnung hinzugefügt.",
+ "errors": {
+ "previewFailed": "Upgrade-Vorschau konnte nicht geladen werden.",
+ "alreadyEnterprise": "Dieser Workspace ist bereits auf Enterprise.",
+ "subscriptionInactive": "Das Abonnement dieses Workspace ist nicht aktiv. Zahlungsdaten aktualisieren und erneut versuchen.",
+ "priceNotConfigured": "Enterprise-Preise sind derzeit nicht verfügbar. Bitte den Vertrieb kontaktieren."
+ },
+ "priceNote": "Der endgültige Preis wird beim Checkout angezeigt.",
+ "continueCta": "Weiter zum Checkout",
+ "upgradeDescription": "Upgrade von {{workspace}} von {{plan}} auf Enterprise. Plätze und Abrechnungszeitraum bleiben erhalten; die Änderung gilt sofort.",
+ "upgradeCta": "Jetzt upgraden",
+ "upgradedTitle": "Upgrade auf Enterprise abgeschlossen",
+ "upgradedDescription": "{{workspace}} ist jetzt auf Enterprise."
}
},
"models": {
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index de4e5e869..c0eb843dd 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -1692,6 +1692,11 @@
"admin": "Workspace admin"
}
}
+ },
+ "enterpriseConsole": {
+ "title": "Enterprise console",
+ "description": "Manage SSO, policies, and members on the web",
+ "open": "Open console"
}
},
"unifiedBilling": {
@@ -1836,7 +1841,9 @@
"SSO & compliance",
"Dedicated support"
],
- "cta": "Contact Sales"
+ "cta": "Contact Sales",
+ "upgradeCta": "Upgrade to Enterprise",
+ "askOwner": "Ask {{name}} to upgrade your workspace."
},
"currentPlan": "Current plan",
"coveredByWorkspace": "Included with your workspace plan",
@@ -2479,6 +2486,34 @@
"endpointUrl": "Endpoint URL",
"serverUrl": "Server URL",
"apiKeyOptional": "API Key (optional)"
+ },
+ "enterpriseCheckout": {
+ "title": "Upgrade to Enterprise",
+ "description": "Choose a workspace, seats, and billing cycle. Payment is completed in Stripe Checkout.",
+ "allSubscribed": "The workspaces you own are already on Enterprise or can't be changed here. To make plan changes, contact sales.",
+ "workspaceLabel": "Workspace",
+ "seatsLabel": "Seats",
+ "seatsHint_one": "{{count}} seat currently in use",
+ "seatsHint_other": "{{count}} seats currently in use",
+ "intervalLabel": "Billing cycle",
+ "interval": {
+ "monthly": "Monthly",
+ "annual": "Annual"
+ },
+ "proratedCharge": "Prorated charge",
+ "prorationNote": "The prorated difference is added to your next invoice.",
+ "errors": {
+ "previewFailed": "Couldn't load the upgrade preview.",
+ "alreadyEnterprise": "This workspace is already on Enterprise.",
+ "subscriptionInactive": "This workspace's subscription isn't active. Update your billing details and try again.",
+ "priceNotConfigured": "Enterprise pricing isn't available right now. Please contact sales."
+ },
+ "priceNote": "Final pricing is shown at checkout.",
+ "continueCta": "Continue to checkout",
+ "upgradeDescription": "Upgrade {{workspace}} from {{plan}} to Enterprise. Seats and billing cycle carry over; the change takes effect immediately.",
+ "upgradeCta": "Upgrade now",
+ "upgradedTitle": "Upgraded to Enterprise",
+ "upgradedDescription": "{{workspace}} is now on Enterprise."
}
},
"models": {
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 4edd99db8..13f8a9c05 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -1600,7 +1600,9 @@
"SSO y cumplimiento normativo",
"Soporte dedicado"
],
- "cta": "Contactar a ventas"
+ "cta": "Contactar a ventas",
+ "upgradeCta": "Mejorar a Enterprise",
+ "askOwner": "Pide a {{name}} que actualice tu espacio de trabajo."
},
"currentPlan": "Plan actual",
"coveredByWorkspace": "Incluido en tu plan de espacio de trabajo",
@@ -2437,7 +2439,40 @@
"admin": "Administrador del espacio de trabajo"
}
}
+ },
+ "enterpriseConsole": {
+ "title": "Consola Enterprise",
+ "description": "Gestiona SSO, políticas y miembros desde la web",
+ "open": "Abrir consola"
}
+ },
+ "enterpriseCheckout": {
+ "title": "Mejorar a Enterprise",
+ "description": "Elige el espacio de trabajo, los puestos y el ciclo de facturación. El pago se completa en Stripe Checkout.",
+ "allSubscribed": "Los espacios de trabajo de tu propiedad ya están en Enterprise o no se pueden cambiar aquí. Para cambios de plan, contacta con ventas.",
+ "workspaceLabel": "Espacio de trabajo",
+ "seatsLabel": "Puestos",
+ "seatsHint_one": "{{count}} puesto en uso actualmente",
+ "seatsHint_other": "{{count}} puestos en uso actualmente",
+ "intervalLabel": "Ciclo de facturación",
+ "interval": {
+ "monthly": "Mensual",
+ "annual": "Anual"
+ },
+ "proratedCharge": "Cargo prorrateado",
+ "prorationNote": "La diferencia prorrateada se añade a tu próxima factura.",
+ "errors": {
+ "previewFailed": "No se pudo cargar la vista previa de la mejora.",
+ "alreadyEnterprise": "Este espacio de trabajo ya está en Enterprise.",
+ "subscriptionInactive": "La suscripción de este espacio de trabajo no está activa. Actualiza tus datos de facturación e inténtalo de nuevo.",
+ "priceNotConfigured": "Los precios de Enterprise no están disponibles ahora mismo. Contacta con ventas."
+ },
+ "priceNote": "El precio final se muestra al pagar.",
+ "continueCta": "Continuar al pago",
+ "upgradeDescription": "Actualiza {{workspace}} de {{plan}} a Enterprise. Los puestos y el ciclo de facturación se mantienen; el cambio se aplica de inmediato.",
+ "upgradeCta": "Actualizar ahora",
+ "upgradedTitle": "Actualizado a Enterprise",
+ "upgradedDescription": "{{workspace}} ahora está en Enterprise."
}
},
"models": {
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 4c969524c..5c3eb7eab 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -1692,6 +1692,11 @@
"admin": "Administrateur de l'espace"
}
}
+ },
+ "enterpriseConsole": {
+ "title": "Console Enterprise",
+ "description": "Gérez le SSO, les politiques et les membres sur le web",
+ "open": "Ouvrir la console"
}
},
"unifiedBilling": {
@@ -1836,7 +1841,9 @@
"SSO et conformité",
"Support dédié"
],
- "cta": "Contacter les ventes"
+ "cta": "Contacter les ventes",
+ "upgradeCta": "Passer à Enterprise",
+ "askOwner": "Demandez à {{name}} de mettre à niveau votre espace de travail."
},
"currentPlan": "Forfait actuel",
"coveredByWorkspace": "Inclus dans votre plan d'espace de travail",
@@ -2479,6 +2486,34 @@
"endpointUrl": "URL du point d'accès",
"serverUrl": "URL du serveur",
"apiKeyOptional": "Clé API (facultative)"
+ },
+ "enterpriseCheckout": {
+ "title": "Passer à Enterprise",
+ "description": "Choisissez l'espace de travail, les sièges et le cycle de facturation. Le paiement s'effectue dans Stripe Checkout.",
+ "allSubscribed": "Les espaces de travail que vous possédez sont déjà sur Enterprise ou ne peuvent pas être modifiés ici. Pour tout changement de plan, contactez le service commercial.",
+ "workspaceLabel": "Espace de travail",
+ "seatsLabel": "Sièges",
+ "seatsHint_one": "{{count}} siège actuellement utilisé",
+ "seatsHint_other": "{{count}} sièges actuellement utilisés",
+ "intervalLabel": "Cycle de facturation",
+ "interval": {
+ "monthly": "Mensuel",
+ "annual": "Annuel"
+ },
+ "proratedCharge": "Montant au prorata",
+ "prorationNote": "La différence au prorata est ajoutée à votre prochaine facture.",
+ "errors": {
+ "previewFailed": "Impossible de charger l'aperçu de la mise à niveau.",
+ "alreadyEnterprise": "Cet espace de travail est déjà sur Enterprise.",
+ "subscriptionInactive": "L'abonnement de cet espace de travail n'est pas actif. Mettez à jour vos informations de facturation et réessayez.",
+ "priceNotConfigured": "Les tarifs Enterprise ne sont pas disponibles pour le moment. Veuillez contacter le service commercial."
+ },
+ "priceNote": "Le prix final est affiché lors du paiement.",
+ "continueCta": "Continuer vers le paiement",
+ "upgradeDescription": "Passez {{workspace}} de {{plan}} à Enterprise. Les sièges et le cycle de facturation sont conservés ; le changement prend effet immédiatement.",
+ "upgradeCta": "Mettre à niveau",
+ "upgradedTitle": "Mise à niveau effectuée",
+ "upgradedDescription": "{{workspace}} est maintenant sur Enterprise."
}
},
"models": {
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index bb437f7c3..b8c197611 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -1571,7 +1571,9 @@
"SSO e conformità",
"Supporto dedicato"
],
- "cta": "Contatta le vendite"
+ "cta": "Contatta le vendite",
+ "upgradeCta": "Passa a Enterprise",
+ "askOwner": "Chiedi a {{name}} di eseguire l'upgrade del tuo spazio di lavoro."
},
"currentPlan": "Piano attuale",
"coveredByWorkspace": "Incluso nel piano della tua area di lavoro",
@@ -2389,7 +2391,40 @@
"admin": "Amministratore dell'area di lavoro"
}
}
+ },
+ "enterpriseConsole": {
+ "title": "Console Enterprise",
+ "description": "Gestisci SSO, policy e membri dal web",
+ "open": "Apri console"
}
+ },
+ "enterpriseCheckout": {
+ "title": "Passa a Enterprise",
+ "description": "Scegli lo spazio di lavoro, i posti e il ciclo di fatturazione. Il pagamento viene completato in Stripe Checkout.",
+ "allSubscribed": "Gli spazi di lavoro di tua proprietà sono già su Enterprise o non possono essere modificati qui. Per cambiare piano, contatta il team vendite.",
+ "workspaceLabel": "Spazio di lavoro",
+ "seatsLabel": "Posti",
+ "seatsHint_one": "{{count}} posto attualmente in uso",
+ "seatsHint_other": "{{count}} posti attualmente in uso",
+ "intervalLabel": "Ciclo di fatturazione",
+ "interval": {
+ "monthly": "Mensile",
+ "annual": "Annuale"
+ },
+ "proratedCharge": "Addebito proporzionale",
+ "prorationNote": "La differenza proporzionale viene aggiunta alla prossima fattura.",
+ "errors": {
+ "previewFailed": "Impossibile caricare l'anteprima dell'upgrade.",
+ "alreadyEnterprise": "Questo workspace è già su Enterprise.",
+ "subscriptionInactive": "L'abbonamento di questo workspace non è attivo. Aggiorna i dati di fatturazione e riprova.",
+ "priceNotConfigured": "I prezzi Enterprise non sono al momento disponibili. Contatta il team vendite."
+ },
+ "priceNote": "Il prezzo finale viene mostrato al momento del pagamento.",
+ "continueCta": "Continua al pagamento",
+ "upgradeDescription": "Aggiorna {{workspace}} da {{plan}} a Enterprise. Posti e ciclo di fatturazione restano invariati; la modifica ha effetto immediato.",
+ "upgradeCta": "Esegui l'upgrade",
+ "upgradedTitle": "Upgrade completato",
+ "upgradedDescription": "{{workspace}} è ora su Enterprise."
}
},
"models": {
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 4082c27cb..9fd1ea323 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -1552,7 +1552,9 @@
"SSO とコンプライアンス",
"専任サポート"
],
- "cta": "営業に問い合わせる"
+ "cta": "営業に問い合わせる",
+ "upgradeCta": "Enterpriseにアップグレード",
+ "askOwner": "{{name}}さんにワークスペースのアップグレードを依頼してください。"
},
"currentPlan": "現在のプラン",
"coveredByWorkspace": "ワークスペースのプランに含まれています",
@@ -2389,7 +2391,40 @@
"admin": "ワークスペース管理者"
}
}
+ },
+ "enterpriseConsole": {
+ "title": "Enterpriseコンソール",
+ "description": "SSO、ポリシー、メンバーをウェブで管理",
+ "open": "コンソールを開く"
}
+ },
+ "enterpriseCheckout": {
+ "title": "Enterpriseにアップグレード",
+ "description": "ワークスペース、シート数、請求サイクルを選択してください。支払いはStripe Checkoutで完了します。",
+ "allSubscribed": "所有しているワークスペースは既にEnterpriseであるか、ここでは変更できません。プランの変更は営業までお問い合わせください。",
+ "workspaceLabel": "ワークスペース",
+ "seatsLabel": "シート数",
+ "seatsHint_one": "現在{{count}}シート使用中",
+ "seatsHint_other": "現在{{count}}シート使用中",
+ "intervalLabel": "請求サイクル",
+ "interval": {
+ "monthly": "月払い",
+ "annual": "年払い"
+ },
+ "proratedCharge": "日割り料金",
+ "prorationNote": "日割り計算された差額は次回の請求書に追加されます。",
+ "errors": {
+ "previewFailed": "アップグレードのプレビューを読み込めませんでした。",
+ "alreadyEnterprise": "このワークスペースはすでに Enterprise プランです。",
+ "subscriptionInactive": "このワークスペースのサブスクリプションが有効ではありません。請求情報を更新して再度お試しください。",
+ "priceNotConfigured": "Enterprise の料金は現在ご利用いただけません。営業までお問い合わせください。"
+ },
+ "priceNote": "最終的な価格はチェックアウト時に表示されます。",
+ "continueCta": "チェックアウトへ進む",
+ "upgradeDescription": "{{workspace}}を{{plan}}からEnterpriseにアップグレードします。シート数と請求サイクルは引き継がれ、変更は即時に適用されます。",
+ "upgradeCta": "今すぐアップグレード",
+ "upgradedTitle": "Enterpriseにアップグレードしました",
+ "upgradedDescription": "{{workspace}}はEnterpriseになりました。"
}
},
"models": {
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 34919e1bb..85b6de06a 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -1550,7 +1550,9 @@
"SSO e conformidade",
"Suporte dedicado"
],
- "cta": "Falar com Vendas"
+ "cta": "Falar com Vendas",
+ "upgradeCta": "Fazer upgrade para Enterprise",
+ "askOwner": "Peça a {{name}} para fazer o upgrade do seu workspace."
},
"currentPlan": "Plano atual",
"coveredByWorkspace": "Incluído no plano do seu workspace",
@@ -2368,7 +2370,40 @@
"admin": "Administrador do espaço de trabalho"
}
}
+ },
+ "enterpriseConsole": {
+ "title": "Console Enterprise",
+ "description": "Gerencie SSO, políticas e membros pela web",
+ "open": "Abrir console"
}
+ },
+ "enterpriseCheckout": {
+ "title": "Fazer upgrade para Enterprise",
+ "description": "Escolha o workspace, os assentos e o ciclo de cobrança. O pagamento é concluído no Stripe Checkout.",
+ "allSubscribed": "Os workspaces que você possui já estão no Enterprise ou não podem ser alterados aqui. Para mudanças de plano, fale com vendas.",
+ "workspaceLabel": "Workspace",
+ "seatsLabel": "Assentos",
+ "seatsHint_one": "{{count}} assento em uso no momento",
+ "seatsHint_other": "{{count}} assentos em uso no momento",
+ "intervalLabel": "Ciclo de cobrança",
+ "interval": {
+ "monthly": "Mensal",
+ "annual": "Anual"
+ },
+ "proratedCharge": "Cobrança proporcional",
+ "prorationNote": "A diferença proporcional é adicionada à sua próxima fatura.",
+ "errors": {
+ "previewFailed": "Não foi possível carregar a prévia do upgrade.",
+ "alreadyEnterprise": "Este espaço de trabalho já está no Enterprise.",
+ "subscriptionInactive": "A assinatura deste espaço de trabalho não está ativa. Atualize os dados de cobrança e tente novamente.",
+ "priceNotConfigured": "Os preços do Enterprise não estão disponíveis no momento. Fale com a equipe de vendas."
+ },
+ "priceNote": "O preço final é exibido no checkout.",
+ "continueCta": "Continuar para o checkout",
+ "upgradeDescription": "Faça o upgrade de {{workspace}} de {{plan}} para Enterprise. Assentos e ciclo de cobrança são mantidos; a mudança entra em vigor imediatamente.",
+ "upgradeCta": "Fazer upgrade agora",
+ "upgradedTitle": "Upgrade concluído",
+ "upgradedDescription": "{{workspace}} agora está no Enterprise."
}
},
"models": {
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index ee86387cf..05254ea2d 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -1575,7 +1575,9 @@
"SSO и соответствие требованиям",
"Выделенная поддержка"
],
- "cta": "Связаться с отделом продаж"
+ "cta": "Связаться с отделом продаж",
+ "upgradeCta": "Перейти на Enterprise",
+ "askOwner": "Попросите {{name}} обновить план вашего рабочего пространства."
},
"currentPlan": "Текущий тариф",
"coveredByWorkspace": "Включено в тариф вашего рабочего пространства",
@@ -2403,7 +2405,42 @@
"admin": "Администратор рабочего пространства"
}
}
+ },
+ "enterpriseConsole": {
+ "title": "Консоль Enterprise",
+ "description": "Управляйте SSO, политиками и участниками через веб",
+ "open": "Открыть консоль"
}
+ },
+ "enterpriseCheckout": {
+ "title": "Перейти на Enterprise",
+ "description": "Выберите рабочее пространство, количество мест и период оплаты. Оплата выполняется в Stripe Checkout.",
+ "allSubscribed": "Ваши рабочие пространства уже на плане Enterprise или их нельзя изменить здесь. Для изменения плана свяжитесь с отделом продаж.",
+ "workspaceLabel": "Рабочее пространство",
+ "seatsLabel": "Места",
+ "seatsHint_one": "Сейчас используется {{count}} место",
+ "seatsHint_few": "Сейчас используется {{count}} места",
+ "seatsHint_many": "Сейчас используется {{count}} мест",
+ "seatsHint_other": "Сейчас используется {{count}} места",
+ "intervalLabel": "Период оплаты",
+ "interval": {
+ "monthly": "Ежемесячно",
+ "annual": "Ежегодно"
+ },
+ "proratedCharge": "Пропорциональная плата",
+ "prorationNote": "Пропорциональная разница будет добавлена к следующему счету.",
+ "errors": {
+ "previewFailed": "Не удалось загрузить предварительный расчет обновления.",
+ "alreadyEnterprise": "Это рабочее пространство уже на плане Enterprise.",
+ "subscriptionInactive": "Подписка этого рабочего пространства неактивна. Обновите платежные данные и попробуйте снова.",
+ "priceNotConfigured": "Цены Enterprise сейчас недоступны. Свяжитесь с отделом продаж."
+ },
+ "priceNote": "Итоговая цена отображается при оформлении.",
+ "continueCta": "Перейти к оплате",
+ "upgradeDescription": "Обновите {{workspace}} с плана {{plan}} до Enterprise. Количество мест и период оплаты сохраняются; изменение вступает в силу сразу.",
+ "upgradeCta": "Обновить сейчас",
+ "upgradedTitle": "План обновлён до Enterprise",
+ "upgradedDescription": "{{workspace}} теперь на плане Enterprise."
}
},
"models": {
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index 9ae287828..75a4be5d5 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -1571,7 +1571,9 @@
"SSO 与合规",
"专属支持"
],
- "cta": "联系销售"
+ "cta": "联系销售",
+ "upgradeCta": "升级到 Enterprise",
+ "askOwner": "请 {{name}} 升级您的工作区。"
},
"currentPlan": "当前套餐",
"coveredByWorkspace": "已包含在您的工作区套餐中",
@@ -2389,7 +2391,40 @@
"admin": "工作区管理员"
}
}
+ },
+ "enterpriseConsole": {
+ "title": "Enterprise 控制台",
+ "description": "在网页端管理 SSO、策略和成员",
+ "open": "打开控制台"
}
+ },
+ "enterpriseCheckout": {
+ "title": "升级到 Enterprise",
+ "description": "选择工作区、席位数量和计费周期。付款将在 Stripe Checkout 中完成。",
+ "allSubscribed": "您拥有的工作区已在 Enterprise 方案或无法在此更改。如需更改方案,请联系销售。",
+ "workspaceLabel": "工作区",
+ "seatsLabel": "席位",
+ "seatsHint_one": "当前已使用 {{count}} 个席位",
+ "seatsHint_other": "当前已使用 {{count}} 个席位",
+ "intervalLabel": "计费周期",
+ "interval": {
+ "monthly": "按月",
+ "annual": "按年"
+ },
+ "proratedCharge": "按比例费用",
+ "prorationNote": "按比例计算的差额将计入下一张账单。",
+ "errors": {
+ "previewFailed": "无法加载升级预览。",
+ "alreadyEnterprise": "该工作区已在 Enterprise 计划中。",
+ "subscriptionInactive": "该工作区的订阅未激活。请更新账单信息后重试。",
+ "priceNotConfigured": "Enterprise 价格暂不可用。请联系销售。"
+ },
+ "priceNote": "最终价格将在结账时显示。",
+ "continueCta": "继续结账",
+ "upgradeDescription": "将 {{workspace}} 从{{plan}}升级到 Enterprise。席位和计费周期保持不变,更改立即生效。",
+ "upgradeCta": "立即升级",
+ "upgradedTitle": "已升级到 Enterprise",
+ "upgradedDescription": "{{workspace}} 现已升级到 Enterprise。"
}
},
"models": {
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 38953cd11..84ac53b4c 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -1571,7 +1571,9 @@
"SSO 與合規",
"專屬支援"
],
- "cta": "聯繫銷售"
+ "cta": "聯繫銷售",
+ "upgradeCta": "升級至 Enterprise",
+ "askOwner": "請 {{name}} 升級您的工作區。"
},
"currentPlan": "目前方案",
"coveredByWorkspace": "已包含在您的工作區方案中",
@@ -2389,7 +2391,40 @@
"admin": "工作區管理員"
}
}
+ },
+ "enterpriseConsole": {
+ "title": "Enterprise 主控台",
+ "description": "在網頁上管理 SSO、政策與成員",
+ "open": "開啟主控台"
}
+ },
+ "enterpriseCheckout": {
+ "title": "升級至 Enterprise",
+ "description": "選擇工作區、席位數量與計費週期。付款將在 Stripe Checkout 中完成。",
+ "allSubscribed": "您擁有的工作區已是 Enterprise 方案或無法在此變更。如需變更方案,請聯絡銷售團隊。",
+ "workspaceLabel": "工作區",
+ "seatsLabel": "席位",
+ "seatsHint_one": "目前已使用 {{count}} 個席位",
+ "seatsHint_other": "目前已使用 {{count}} 個席位",
+ "intervalLabel": "計費週期",
+ "interval": {
+ "monthly": "按月",
+ "annual": "按年"
+ },
+ "proratedCharge": "按比例費用",
+ "prorationNote": "按比例計算的差額將計入下一張帳單。",
+ "errors": {
+ "previewFailed": "無法載入升級預覽。",
+ "alreadyEnterprise": "該工作區已在 Enterprise 方案中。",
+ "subscriptionInactive": "該工作區的訂閱未啟用。請更新帳單資訊後重試。",
+ "priceNotConfigured": "Enterprise 價格暫不可用。請聯絡銷售。"
+ },
+ "priceNote": "最終價格將在結帳時顯示。",
+ "continueCta": "繼續結帳",
+ "upgradeDescription": "將 {{workspace}} 從{{plan}}升級至 Enterprise。席位與計費週期維持不變,變更立即生效。",
+ "upgradeCta": "立即升級",
+ "upgradedTitle": "已升級至 Enterprise",
+ "upgradedDescription": "{{workspace}} 現已升級至 Enterprise。"
}
},
"models": {
diff --git a/src/services/WorkspacesService.ts b/src/services/WorkspacesService.ts
index b6519ddf1..349222c35 100644
--- a/src/services/WorkspacesService.ts
+++ b/src/services/WorkspacesService.ts
@@ -14,6 +14,18 @@ export interface SeatPreview {
currency: string;
}
+export interface EnterpriseUpgradePreview {
+ // Prorated difference in cents, collected on the next invoice (Stripe
+ // create_prorations), not charged at confirmation time.
+ prorated_amount: number;
+ currency: string;
+ current_price_amount: number | null;
+ new_price_amount: number | null;
+ interval: "monthly" | "annual";
+ quantity: number;
+ next_billing_date: string | null;
+}
+
async function list(): Promise<Workspace[]> {
const res = await cloudGet<DataWrap<Workspace[]>>("/api/workspaces");
return res.data;
@@ -52,11 +64,16 @@ async function removeMember(workspaceId: string, userId: string): Promise<void>
async function billingCheckout(
workspaceId: string,
- interval: "monthly" | "annual" = "monthly"
+ interval: "monthly" | "annual" = "monthly",
+ options?: { tier?: "business" | "enterprise"; additionalSeats?: number }
): Promise<string> {
const res = await cloudPost<DataWrap<{ url: string }>>(
`/api/workspaces/${workspaceId}/billing/checkout`,
- { interval }
+ {
+ interval,
+ ...(options?.tier ? { tier: options.tier } : {}),
+ ...(options?.additionalSeats ? { additional_seats: options.additionalSeats } : {}),
+ }
);
return res.data.url;
}
@@ -78,6 +95,17 @@ async function previewSeats(workspaceId: string, additionalSeats: number): Promi
return res.data;
}
+async function previewEnterpriseUpgrade(workspaceId: string): Promise<EnterpriseUpgradePreview> {
+ const res = await cloudPost<DataWrap<EnterpriseUpgradePreview>>(
+ `/api/workspaces/${workspaceId}/billing/preview-upgrade`
+ );
+ return res.data;
+}
+
+async function upgradeToEnterprise(workspaceId: string): Promise<void> {
+ await cloudPost<DataWrap<{ plan: string }>>(`/api/workspaces/${workspaceId}/billing/upgrade`);
+}
+
async function updateSeats(
workspaceId: string,
quantity: number
@@ -139,5 +167,7 @@ export const WorkspacesService = {
billingCheckout,
billingPortal,
previewSeats,
+ previewEnterpriseUpgrade,
+ upgradeToEnterprise,
updateSeats,
};
diff --git a/test/lib/workspaceBilling.test.js b/test/lib/workspaceBilling.test.js
new file mode 100644
index 000000000..7317e447e
--- /dev/null
+++ b/test/lib/workspaceBilling.test.js
@@ -0,0 +1,132 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const {
+ canSelfServeEnterprise,
+ canUpgradeWorkspaceToEnterprise,
+ enterpriseTileCta,
+ hasActiveWorkspaceSubscription,
+ isEnterpriseConsoleAvailable,
+} = require("../../src/lib/workspaceBilling.ts");
+
+const workspace = (overrides = {}) => ({
+ plan: "free",
+ status: "active",
+ role: "owner",
+ stripe_subscription_id: null,
+ ...overrides,
+});
+
+test("hasActiveWorkspaceSubscription: paid plan and entitled status, nothing else", () => {
+ for (const plan of ["pro", "business", "enterprise"]) {
+ assert.equal(hasActiveWorkspaceSubscription(workspace({ plan, status: "active" })), true);
+ assert.equal(hasActiveWorkspaceSubscription(workspace({ plan, status: "trialing" })), true);
+ assert.equal(hasActiveWorkspaceSubscription(workspace({ plan, status: "past_due" })), false);
+ assert.equal(hasActiveWorkspaceSubscription(workspace({ plan, status: "canceled" })), false);
+ }
+ assert.equal(
+ hasActiveWorkspaceSubscription(workspace({ plan: "free", status: "active" })),
+ false
+ );
+});
+
+test("canSelfServeEnterprise: an owner's free workspace with no Stripe subscription", () => {
+ assert.equal(canSelfServeEnterprise(workspace()), true);
+ assert.equal(canSelfServeEnterprise(workspace({ role: "admin" })), false);
+ assert.equal(canSelfServeEnterprise(workspace({ role: "member" })), false);
+});
+
+test("canSelfServeEnterprise: mirrors the API 409 — any live subscription blocks checkout", () => {
+ // A subscription that is past_due is still live in Stripe.
+ assert.equal(
+ canSelfServeEnterprise(
+ workspace({ plan: "business", status: "past_due", stripe_subscription_id: "sub_1" })
+ ),
+ false
+ );
+ // Manually provisioned plans (no Stripe subscription) must not be clobbered either.
+ assert.equal(canSelfServeEnterprise(workspace({ plan: "enterprise", status: "active" })), false);
+ assert.equal(canSelfServeEnterprise(workspace({ plan: "business", status: "trialing" })), false);
+ // A lapsed manual plan is free to buy again.
+ assert.equal(canSelfServeEnterprise(workspace({ plan: "business", status: "canceled" })), true);
+});
+
+test("isEnterpriseConsoleAvailable: entitled Enterprise plan for owners and admins only", () => {
+ const enterprise = (overrides) => workspace({ plan: "enterprise", ...overrides });
+ assert.equal(isEnterpriseConsoleAvailable(enterprise({ role: "owner" })), true);
+ assert.equal(isEnterpriseConsoleAvailable(enterprise({ role: "admin" })), true);
+ assert.equal(isEnterpriseConsoleAvailable(enterprise({ role: "member" })), false);
+ assert.equal(isEnterpriseConsoleAvailable(enterprise({ status: "trialing" })), true);
+ assert.equal(isEnterpriseConsoleAvailable(enterprise({ status: "past_due" })), false);
+ assert.equal(isEnterpriseConsoleAvailable(enterprise({ status: "canceled" })), false);
+ assert.equal(isEnterpriseConsoleAvailable(workspace({ plan: "business", role: "owner" })), false);
+});
+
+test("canUpgradeWorkspaceToEnterprise: an owner's live lower-plan subscription, nothing else", () => {
+ const business = (overrides) =>
+ workspace({ plan: "business", stripe_subscription_id: "sub_1", ...overrides });
+ assert.equal(canUpgradeWorkspaceToEnterprise(business()), true);
+ assert.equal(canUpgradeWorkspaceToEnterprise(business({ plan: "pro" })), true);
+ assert.equal(canUpgradeWorkspaceToEnterprise(business({ status: "trialing" })), true);
+ assert.equal(canUpgradeWorkspaceToEnterprise(business({ role: "admin" })), false);
+ assert.equal(canUpgradeWorkspaceToEnterprise(business({ role: "member" })), false);
+ assert.equal(canUpgradeWorkspaceToEnterprise(business({ plan: "enterprise" })), false);
+ assert.equal(canUpgradeWorkspaceToEnterprise(business({ status: "past_due" })), false);
+ assert.equal(canUpgradeWorkspaceToEnterprise(business({ status: "canceled" })), false);
+ // Manually provisioned plans have no subscription to update.
+ assert.equal(canUpgradeWorkspaceToEnterprise(business({ stripe_subscription_id: null })), false);
+});
+
+test("enterpriseTileCta: eligible owners get the dialog, first-timers get create, members get the owner", () => {
+ const ws = (id, role, overrides = {}) => ({
+ id,
+ role,
+ billing_manager: null,
+ plan: "free",
+ status: "active",
+ stripe_subscription_id: null,
+ ...overrides,
+ });
+
+ // Owner with a checkout-eligible (unsubscribed) workspace → dialog.
+ assert.deepEqual(enterpriseTileCta([ws("a", "member"), ws("b", "owner")], null), {
+ action: "openDialog",
+ });
+ // Owner with an upgradeable Business subscription → dialog.
+ assert.deepEqual(
+ enterpriseTileCta(
+ [ws("a", "owner", { plan: "business", stripe_subscription_id: "sub_1" })],
+ null
+ ),
+ { action: "openDialog" }
+ );
+ // Owner whose only workspace is already Enterprise → contact sales, and no
+ // ask-owner hint (they are the owner).
+ assert.deepEqual(
+ enterpriseTileCta(
+ [ws("a", "owner", { plan: "enterprise", stripe_subscription_id: "sub_1" })],
+ null
+ ),
+ { action: "contactSales", ownerName: null }
+ );
+ assert.deepEqual(enterpriseTileCta([], null), { action: "createWorkspace" });
+ assert.deepEqual(enterpriseTileCta([ws("a", "admin", { billing_manager: "Alice" })], null), {
+ action: "contactSales",
+ ownerName: "Alice",
+ });
+ // The active workspace's owner wins over the first one.
+ assert.deepEqual(
+ enterpriseTileCta(
+ [
+ ws("a", "member", { billing_manager: "Alice" }),
+ ws("b", "admin", { billing_manager: "Bob" }),
+ ],
+ "b"
+ ),
+ { action: "contactSales", ownerName: "Bob" }
+ );
+ // Unknown active id falls back to the first workspace; a missing name stays null.
+ assert.deepEqual(enterpriseTileCta([ws("a", "member")], "gone"), {
+ action: "contactSales",
+ ownerName: null,
+ });
+});
diff --git a/test/services/workspacesServiceBilling.test.js b/test/services/workspacesServiceBilling.test.js
new file mode 100644
index 000000000..7c6a050ec
--- /dev/null
+++ b/test/services/workspacesServiceBilling.test.js
@@ -0,0 +1,97 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+const CHECKOUT_URL = "https://checkout.stripe.test/session";
+
+// Captures the IPC payload WorkspacesService hands to the main process, so the
+// wire body the API's zod schema receives is pinned here.
+function installCloudCapture(t, responseData = { url: CHECKOUT_URL }) {
+ const requests = [];
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ cloudApiRequest: async (options) => {
+ requests.push(options);
+ return { success: true, data: { data: responseData } };
+ },
+ },
+ },
+ });
+ return requests;
+}
+
+test("billingCheckout without options keeps the pre-enterprise wire body", async (t) => {
+ const requests = installCloudCapture(t);
+ const { WorkspacesService } = require("../../src/services/WorkspacesService.ts");
+
+ const url = await WorkspacesService.billingCheckout("ws-1", "annual");
+
+ assert.equal(url, CHECKOUT_URL);
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0].method, "POST");
+ assert.equal(requests[0].path, "/api/workspaces/ws-1/billing/checkout");
+ assert.deepEqual(requests[0].body, { interval: "annual" });
+});
+
+test("billingCheckout sends the enterprise tier and extra seats in the API's field names", async (t) => {
+ const requests = installCloudCapture(t);
+ const { WorkspacesService } = require("../../src/services/WorkspacesService.ts");
+
+ await WorkspacesService.billingCheckout("ws-1", "monthly", {
+ tier: "enterprise",
+ additionalSeats: 4,
+ });
+
+ assert.deepEqual(requests[0].body, {
+ interval: "monthly",
+ tier: "enterprise",
+ additional_seats: 4,
+ });
+});
+
+test("billingCheckout omits additional_seats when the buyer keeps current occupancy", async (t) => {
+ const requests = installCloudCapture(t);
+ const { WorkspacesService } = require("../../src/services/WorkspacesService.ts");
+
+ await WorkspacesService.billingCheckout("ws-1", "monthly", {
+ tier: "enterprise",
+ additionalSeats: 0,
+ });
+
+ assert.deepEqual(requests[0].body, { interval: "monthly", tier: "enterprise" });
+});
+
+test("previewEnterpriseUpgrade posts no body and returns the preview unchanged", async (t) => {
+ const preview = {
+ prorated_amount: 12300,
+ currency: "usd",
+ current_price_amount: 1500,
+ new_price_amount: 3000,
+ interval: "monthly",
+ quantity: 5,
+ next_billing_date: "2026-09-01T00:00:00.000Z",
+ };
+ const requests = installCloudCapture(t, preview);
+ const { WorkspacesService } = require("../../src/services/WorkspacesService.ts");
+
+ const result = await WorkspacesService.previewEnterpriseUpgrade("ws-1");
+
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0].method, "POST");
+ assert.equal(requests[0].path, "/api/workspaces/ws-1/billing/preview-upgrade");
+ assert.equal(requests[0].body, undefined);
+ assert.deepEqual(result, preview);
+});
+
+test("upgradeToEnterprise posts to the upgrade endpoint with no body", async (t) => {
+ const requests = installCloudCapture(t, { plan: "enterprise" });
+ const { WorkspacesService } = require("../../src/services/WorkspacesService.ts");
+
+ await WorkspacesService.upgradeToEnterprise("ws-1");
+
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0].method, "POST");
+ assert.equal(requests[0].path, "/api/workspaces/ws-1/billing/upgrade");
+ assert.equal(requests[0].body, undefined);
+});