mirror of
https://github.com/stablyai/orca.git
synced 2026-11-17 03:15:01 +00:00
Merge pull request #738 from nwparker/cloud/strip-admin-ui
feat(cloud): move team, billing and Enterprise admin UI to the web console
This commit is contained in:
@@ -1,10 +1,8 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import { OrcaCloudRequestError } from '../orca-profiles/cloud-auth/profile-cloud-client'
|
||||
import {
|
||||
BillingServiceError,
|
||||
assertStripeHostedUrl,
|
||||
claimTrial,
|
||||
createCheckoutUrl,
|
||||
createPortalUrl,
|
||||
BillingOrgMismatchError,
|
||||
fetchEntitlement,
|
||||
@@ -64,10 +62,13 @@ describe('billing client', () => {
|
||||
describe('EP-9: the token is for the team this device shows', () => {
|
||||
beforeEach(() => resetBillingExplicitOrgForTests())
|
||||
|
||||
it('asks auth for this device\'s team explicitly and accepts a token for it', async () => {
|
||||
it("asks auth for this device's team explicitly and accepts a token for it", async () => {
|
||||
const seen: Seen[] = []
|
||||
const bt = jwt({ sub: 'u1', org: 'org_paid' })
|
||||
const fetchImpl = fakeFetch({ [endpoints.billingTokenEndpoint]: Response.json({ billingToken: bt, expiresAt: 1 }) }, seen)
|
||||
const fetchImpl = fakeFetch(
|
||||
{ [endpoints.billingTokenEndpoint]: Response.json({ billingToken: bt, expiresAt: 1 }) },
|
||||
seen
|
||||
)
|
||||
expect(await mintBillingToken(endpoints, 'a', 'org_paid', fetchImpl)).toBe(bt)
|
||||
expect(seen[0]?.init?.body).toBe(JSON.stringify({ orgId: 'org_paid' }))
|
||||
})
|
||||
@@ -75,15 +76,21 @@ describe('billing client', () => {
|
||||
it('refuses a token auth minted for another team (another device switched the shared active team)', async () => {
|
||||
const fetchImpl: typeof fetch = async () =>
|
||||
Response.json({ billingToken: jwt({ sub: 'u1', org: 'org_eval' }), expiresAt: 1 })
|
||||
await expect(mintBillingToken(endpoints, 'a', 'org_paid', fetchImpl)).rejects.toBeInstanceOf(BillingOrgMismatchError)
|
||||
await expect(mintBillingToken(endpoints, 'a', 'org_paid', fetchImpl)).rejects.toBeInstanceOf(
|
||||
BillingOrgMismatchError
|
||||
)
|
||||
// A personal account never accepts a team token either.
|
||||
await expect(mintBillingToken(endpoints, 'a', null, fetchImpl)).rejects.toBeInstanceOf(BillingOrgMismatchError)
|
||||
await expect(mintBillingToken(endpoints, 'a', null, fetchImpl)).rejects.toBeInstanceOf(
|
||||
BillingOrgMismatchError
|
||||
)
|
||||
})
|
||||
|
||||
it('treats 403 not_a_member as a team-switch error, not a session failure', async () => {
|
||||
const fetchImpl: typeof fetch = async () =>
|
||||
new Response(JSON.stringify({ error: 'not_a_member' }), { status: 403 })
|
||||
await expect(mintBillingToken(endpoints, 'a', 'org_gone', fetchImpl)).rejects.toBeInstanceOf(BillingOrgMismatchError)
|
||||
await expect(mintBillingToken(endpoints, 'a', 'org_gone', fetchImpl)).rejects.toBeInstanceOf(
|
||||
BillingOrgMismatchError
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to the empty body on an older auth (400), still checking the claim', async () => {
|
||||
@@ -114,48 +121,6 @@ describe('billing client', () => {
|
||||
await expect(call).rejects.toBeInstanceOf(OrcaCloudRequestError)
|
||||
})
|
||||
|
||||
it('reports billing refusals as BillingServiceError, never as a session failure', async () => {
|
||||
const call = createCheckoutUrl(
|
||||
endpoints,
|
||||
'bt',
|
||||
{ plan: 'team', interval: 'month', seats: 1 },
|
||||
fakeFetch({
|
||||
'https://billing.example.test/v1/billing/checkout': Response.json(
|
||||
{ error: 'already_subscribed' },
|
||||
{ status: 409 }
|
||||
)
|
||||
})
|
||||
)
|
||||
await expect(call).rejects.toMatchObject({
|
||||
statusCode: 409,
|
||||
errorCode: 'already_subscribed'
|
||||
})
|
||||
await expect(call).rejects.toBeInstanceOf(BillingServiceError)
|
||||
})
|
||||
|
||||
it('sends plan, interval and seats and returns the hosted Checkout URL', async () => {
|
||||
const seen: Seen[] = []
|
||||
const url = await createCheckoutUrl(
|
||||
endpoints,
|
||||
'bt',
|
||||
{ plan: 'team', interval: 'year', seats: 3 },
|
||||
fakeFetch(
|
||||
{
|
||||
'https://billing.example.test/v1/billing/checkout': Response.json({
|
||||
url: 'https://checkout.stripe.com/c/pay/cs_test_1'
|
||||
})
|
||||
},
|
||||
seen
|
||||
)
|
||||
)
|
||||
expect(url).toBe('https://checkout.stripe.com/c/pay/cs_test_1')
|
||||
expect(JSON.parse(String(seen[0]?.init?.body))).toEqual({
|
||||
plan: 'team',
|
||||
interval: 'year',
|
||||
seats: 3
|
||||
})
|
||||
})
|
||||
|
||||
it('only opens Stripe-hosted pages', async () => {
|
||||
expect(assertStripeHostedUrl('https://billing.stripe.com/p/session/x')).toBe(
|
||||
'https://billing.stripe.com/p/session/x'
|
||||
@@ -255,8 +220,13 @@ describe('billing client', () => {
|
||||
expect(unsafe.offers).toBeNull()
|
||||
// A portal cancel's end date (cancel_at) comes through; older services omit it.
|
||||
expect(
|
||||
(await fetchEntitlement(endpoints, 'bt', response({ cancelAtPeriodEnd: true, cancelAt: 1797167516000 })))
|
||||
.cancelAt
|
||||
(
|
||||
await fetchEntitlement(
|
||||
endpoints,
|
||||
'bt',
|
||||
response({ cancelAtPeriodEnd: true, cancelAt: 1797167516000 })
|
||||
)
|
||||
).cancelAt
|
||||
).toBe(1797167516000)
|
||||
expect((await fetchEntitlement(endpoints, 'bt', response({}))).cancelAt).toBeNull()
|
||||
// A plan this desktop doesn't know (a newer service) is still a plan, never "no plan".
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
// then call the billing service with it. Pure (fetch injected) so it is testable without Electron.
|
||||
import { z } from 'zod'
|
||||
import type {
|
||||
OrcaBillingCheckoutArgs,
|
||||
OrcaBillingEntitlement,
|
||||
OrcaBillingOverageArgs,
|
||||
OrcaBillingTeamPlan
|
||||
@@ -183,28 +182,6 @@ export async function fetchEntitlement(
|
||||
)
|
||||
}
|
||||
|
||||
export async function createCheckoutUrl(
|
||||
endpoints: BillingEndpoints,
|
||||
token: string,
|
||||
args: OrcaBillingCheckoutArgs,
|
||||
fetchImpl: typeof fetch = fetch
|
||||
): Promise<string> {
|
||||
const body = await billingRequest(
|
||||
endpoints,
|
||||
token,
|
||||
'POST',
|
||||
'v1/billing/checkout',
|
||||
{
|
||||
plan: args.plan,
|
||||
interval: args.interval,
|
||||
seats: args.seats,
|
||||
...(args.setupSessionId ? { setupSessionId: args.setupSessionId } : {})
|
||||
},
|
||||
fetchImpl
|
||||
)
|
||||
return assertStripeHostedUrl(UrlBody.safeParse(body).data?.url)
|
||||
}
|
||||
|
||||
export async function createPortalUrl(
|
||||
endpoints: BillingEndpoints,
|
||||
token: string,
|
||||
|
||||
@@ -3,10 +3,7 @@ import { describe, expect, it, vi } from 'vitest'
|
||||
vi.mock('electron', () => ({ app: { isPackaged: false } }))
|
||||
|
||||
import { getBillingEndpoints } from './billing-config'
|
||||
import {
|
||||
billingCheckoutArgsFromUnknown,
|
||||
billingOverageArgsFromUnknown
|
||||
} from '../ipc/profiles/orca-profile-billing-handlers'
|
||||
import { billingOverageArgsFromUnknown } from '../ipc/profiles/orca-profile-billing-handlers'
|
||||
|
||||
const authConfig = { apiBaseUrl: 'https://login.onorca.dev' }
|
||||
|
||||
@@ -32,29 +29,6 @@ describe('billing config', () => {
|
||||
})
|
||||
|
||||
describe('billing IPC args', () => {
|
||||
it('accepts a catalog plan id with an interval and 1..500 seats', () => {
|
||||
expect(billingCheckoutArgsFromUnknown({ plan: 'team', interval: 'year', seats: 5 })).toEqual({
|
||||
plan: 'team',
|
||||
interval: 'year',
|
||||
seats: 5
|
||||
})
|
||||
// Billing's catalog names the plans (billing decides what it sells); the shape is checked here.
|
||||
expect(billingCheckoutArgsFromUnknown({ plan: 'pro', interval: 'month', seats: 1 }).plan).toBe(
|
||||
'pro'
|
||||
)
|
||||
for (const bad of [
|
||||
{ plan: 'Pro Plan', interval: 'month', seats: 1 },
|
||||
{ plan: '', interval: 'month', seats: 1 },
|
||||
{ plan: 'team', interval: 'week', seats: 1 },
|
||||
{ plan: 'team', interval: 'month', seats: 0 },
|
||||
{ plan: 'team', interval: 'month', seats: 501 },
|
||||
{ plan: 'team', interval: 'month', seats: 1, extra: true },
|
||||
null
|
||||
]) {
|
||||
expect(() => billingCheckoutArgsFromUnknown(bad)).toThrow('invalid_orca_billing_checkout')
|
||||
}
|
||||
})
|
||||
|
||||
it('accepts overage toggles with an optional whole-cent cap', () => {
|
||||
expect(billingOverageArgsFromUnknown({ enabled: false })).toEqual({ enabled: false })
|
||||
expect(billingOverageArgsFromUnknown({ enabled: true, spendCapCents: 5000 })).toEqual({
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('electron', () => ({ app: { isPackaged: false }, shell: { openExternal: vi.fn() } }))
|
||||
|
||||
import { withSetupSessionFallback } from './billing-setup-session-fallback'
|
||||
import type { OrcaBillingCheckoutArgs, OrcaBillingLinkResult } from '../../shared/orca-billing'
|
||||
|
||||
const ARGS: OrcaBillingCheckoutArgs = {
|
||||
plan: 'team',
|
||||
interval: 'month',
|
||||
seats: 3,
|
||||
setupSessionId: 'cs_x'
|
||||
}
|
||||
|
||||
describe('checkout "Copy link" setup-session fallback', () => {
|
||||
it('retries without the setup session when billing says it is for someone else', async () => {
|
||||
const run = vi.fn(async (args: OrcaBillingCheckoutArgs): Promise<OrcaBillingLinkResult> =>
|
||||
args.setupSessionId
|
||||
? { status: 'failed', error: 'setup_session_mismatch' }
|
||||
: { status: 'ok', url: 'https://checkout.stripe.com/c/pay/cs_live_1' }
|
||||
)
|
||||
await expect(withSetupSessionFallback(ARGS, run)).resolves.toEqual({
|
||||
status: 'ok',
|
||||
url: 'https://checkout.stripe.com/c/pay/cs_live_1'
|
||||
})
|
||||
expect(run).toHaveBeenCalledTimes(2)
|
||||
expect(run.mock.calls[1][0]).not.toHaveProperty('setupSessionId')
|
||||
})
|
||||
|
||||
it('keeps any other refusal as it is', async () => {
|
||||
const run = vi.fn(async (): Promise<OrcaBillingLinkResult> => ({ status: 'forbidden' }))
|
||||
await expect(withSetupSessionFallback(ARGS, run)).resolves.toEqual({ status: 'forbidden' })
|
||||
expect(run).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -6,27 +6,23 @@ import { appendFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { app, shell } from 'electron'
|
||||
import type {
|
||||
OrcaBillingCheckoutArgs,
|
||||
OrcaBillingLinkResult,
|
||||
OrcaBillingOpenResult,
|
||||
OrcaBillingOverageArgs,
|
||||
OrcaBillingOverageResult,
|
||||
OrcaBillingStatusResult,
|
||||
OrcaBillingTeamPlansResult,
|
||||
OrcaBillingTrialClaimResult,
|
||||
OrcaBillingUsageHistoryResult
|
||||
OrcaBillingTrialClaimResult
|
||||
} from '../../shared/orca-billing'
|
||||
import type { OrcaPlanCatalogResult } from '../../shared/orca-billing-plans'
|
||||
import { loadPlanCatalog } from './plan-catalog-client'
|
||||
import { openResultForError } from './billing-open-result'
|
||||
import { withSetupSessionFallback } from './billing-setup-session-fallback'
|
||||
import { getOrcaCloudAuthConfig } from '../orca-profiles/cloud-auth/profile-cloud-auth-config'
|
||||
import { runWithFreshOrcaCloudSession } from '../orca-profiles/cloud-session/profile-cloud-session-refresh'
|
||||
import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store'
|
||||
import {
|
||||
BillingServiceError,
|
||||
claimTrial,
|
||||
createCheckoutUrl,
|
||||
createPortalUrl,
|
||||
fetchEntitlement,
|
||||
fetchTeamPlans,
|
||||
@@ -35,7 +31,6 @@ import {
|
||||
type BillingEndpoints
|
||||
} from './billing-client'
|
||||
import { getBillingEndpoints } from './billing-config'
|
||||
import { fetchUsageHistory } from './billing-usage-client'
|
||||
import { getBillingDevKeyFile, mintDevBillingToken } from './billing-dev-token'
|
||||
import { cleanCloudServiceUrl } from '../../shared/cloud-service-url'
|
||||
import { listOrcaProfileOrgMembers } from '../orca-profiles/cloud-org/profile-cloud-org-members-service'
|
||||
@@ -117,7 +112,11 @@ function prepare(userDataPath: string): Ready {
|
||||
// The team this device shows, from the same profile whose session this is (a local
|
||||
// profile switch mid-call must not pair one profile's session with another's team);
|
||||
// never auth's shared "active team" (EP-9).
|
||||
await mintBillingToken(endpoints, session.accessToken, active.profile.cloud?.activeOrgId ?? null),
|
||||
await mintBillingToken(
|
||||
endpoints,
|
||||
session.accessToken,
|
||||
active.profile.cloud?.activeOrgId ?? null
|
||||
),
|
||||
endpoints
|
||||
)
|
||||
)
|
||||
@@ -187,25 +186,6 @@ export async function getOrcaBillingStatus(userDataPath: string): Promise<OrcaBi
|
||||
}
|
||||
}
|
||||
|
||||
/** The last 30 days of sandbox hours, with days starting at the viewer's local midnight. */
|
||||
export async function getOrcaBillingUsageHistory(
|
||||
userDataPath: string,
|
||||
utcOffsetMinutes: number
|
||||
): Promise<OrcaBillingUsageHistoryResult> {
|
||||
const ready = prepare(userDataPath)
|
||||
if (!ready.ok) {
|
||||
return { status: ready.status }
|
||||
}
|
||||
try {
|
||||
const history = await ready.run((token, endpoints) =>
|
||||
fetchUsageHistory(endpoints, token, utcOffsetMinutes)
|
||||
)
|
||||
return history === 'signed-out' ? { status: 'signed-out' } : { status: 'ok', history }
|
||||
} catch (error) {
|
||||
return { status: 'failed', error: message(error) }
|
||||
}
|
||||
}
|
||||
|
||||
/** Plan state for other teams the signed-in user is on (cloud start B2); never switches teams. */
|
||||
export async function getOrcaBillingTeamPlans(
|
||||
userDataPath: string,
|
||||
@@ -268,17 +248,6 @@ async function openHosted(
|
||||
}
|
||||
}
|
||||
|
||||
export function openOrcaBillingCheckout(
|
||||
userDataPath: string,
|
||||
args: OrcaBillingCheckoutArgs
|
||||
): Promise<OrcaBillingOpenResult> {
|
||||
return withSetupSessionFallback(args, (checkoutArgs) =>
|
||||
openHosted(userDataPath, (token, endpoints) =>
|
||||
createCheckoutUrl(endpoints, token, checkoutArgs)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
export function openOrcaBillingPortal(userDataPath: string): Promise<OrcaBillingOpenResult> {
|
||||
return openHosted(userDataPath, (token, endpoints) => createPortalUrl(endpoints, token))
|
||||
}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import type { OrcaBillingCheckoutArgs } from '../../shared/orca-billing'
|
||||
|
||||
/** A setup session for another team or user (or an expired one) must not block buying. */
|
||||
export async function withSetupSessionFallback<T extends { status: string; error?: string }>(
|
||||
args: OrcaBillingCheckoutArgs,
|
||||
run: (args: OrcaBillingCheckoutArgs) => Promise<T>
|
||||
): Promise<T> {
|
||||
const result = await run(args)
|
||||
if (
|
||||
args.setupSessionId &&
|
||||
result.status === 'failed' &&
|
||||
/setup_session_mismatch/.test(result.error ?? '')
|
||||
) {
|
||||
const { setupSessionId: _dropped, ...plain } = args
|
||||
return run(plain)
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { fetchUsageHistory } from './billing-usage-client'
|
||||
|
||||
const endpoints = {
|
||||
billingApiUrl: 'https://billing.example.test',
|
||||
billingTokenEndpoint: 'https://login.example.test/v1/desktop/auth/billing-token'
|
||||
}
|
||||
|
||||
type Seen = { url: string; init: RequestInit | undefined }
|
||||
|
||||
function fakeFetch(responses: Record<string, Response>, seen: Seen[] = []): typeof fetch {
|
||||
return async (input, init) => {
|
||||
const url = String(input)
|
||||
seen.push({ url, init })
|
||||
const response = responses[url]
|
||||
if (!response) {
|
||||
throw new Error(`unexpected ${url}`)
|
||||
}
|
||||
return response
|
||||
}
|
||||
}
|
||||
|
||||
describe('fetchUsageHistory', () => {
|
||||
const url = 'https://billing.example.test/v1/billing/usage?utcOffset=-480'
|
||||
const body = {
|
||||
days: [{ start: 1, seconds: 3600 }],
|
||||
totalSeconds: 3600,
|
||||
yourSeconds: 1800,
|
||||
members: { top: [{ userId: 'u1', seconds: 3600 }], otherCount: 0, otherSeconds: 0 },
|
||||
sandboxes: { top: [{ sandboxId: 'sbx_1', seconds: 3600 }], otherCount: 0, otherSeconds: 0 }
|
||||
}
|
||||
|
||||
it('sends the local offset and maps both breakdowns to one row shape', async () => {
|
||||
const seen: Seen[] = []
|
||||
const history = await fetchUsageHistory(
|
||||
endpoints,
|
||||
'bt',
|
||||
-480,
|
||||
fakeFetch({ [url]: Response.json(body) }, seen)
|
||||
)
|
||||
expect(seen[0]!.init?.method).toBe('GET')
|
||||
expect(history.members).toEqual({
|
||||
top: [{ id: 'u1', seconds: 3600 }],
|
||||
otherCount: 0,
|
||||
otherSeconds: 0
|
||||
})
|
||||
expect(history.sandboxes?.top).toEqual([{ id: 'sbx_1', seconds: 3600 }])
|
||||
})
|
||||
|
||||
it('accepts a member’s view and rejects malformed rows', async () => {
|
||||
const member = await fetchUsageHistory(
|
||||
endpoints,
|
||||
'bt',
|
||||
-480,
|
||||
fakeFetch({ [url]: Response.json({ ...body, members: null, sandboxes: null }) })
|
||||
)
|
||||
expect(member.members).toBeNull()
|
||||
await expect(
|
||||
fetchUsageHistory(
|
||||
endpoints,
|
||||
'bt',
|
||||
-480,
|
||||
fakeFetch({
|
||||
[url]: Response.json({
|
||||
...body,
|
||||
members: { top: [{ userId: '<script>', seconds: 1 }], otherCount: 0, otherSeconds: 0 }
|
||||
})
|
||||
})
|
||||
)
|
||||
).rejects.toThrow('invalid_billing_response')
|
||||
})
|
||||
})
|
||||
@@ -1,67 +0,0 @@
|
||||
// GET /v1/billing/usage behind Plan & billing's "Last 30 days". Pure (fetch injected).
|
||||
import { z } from 'zod'
|
||||
import type { OrcaBillingUsageHistory } from '../../shared/orca-billing'
|
||||
import { billingRequest, type BillingEndpoints } from './billing-client'
|
||||
|
||||
const UsageId = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(128)
|
||||
.regex(/^[A-Za-z0-9_.:-]+$/)
|
||||
const UsageSeconds = z.number().finite().nonnegative()
|
||||
const usageTop = <K extends 'userId' | 'sandboxId'>(key: K) =>
|
||||
z
|
||||
.object({
|
||||
top: z.array(z.record(z.string(), z.unknown())).max(20),
|
||||
otherCount: z.number().int().nonnegative(),
|
||||
otherSeconds: UsageSeconds
|
||||
})
|
||||
.transform((value, ctx) => {
|
||||
const top = value.top.map((row) => ({
|
||||
id: UsageId.safeParse(row[key]),
|
||||
seconds: UsageSeconds.safeParse(row.seconds)
|
||||
}))
|
||||
if (top.some((row) => !row.id.success || !row.seconds.success)) {
|
||||
ctx.addIssue({ code: 'custom', message: 'invalid_usage_row' })
|
||||
return z.NEVER
|
||||
}
|
||||
return {
|
||||
top: top.map((row) => ({
|
||||
id: row.id.data!,
|
||||
seconds: row.seconds.data!
|
||||
})),
|
||||
otherCount: value.otherCount,
|
||||
otherSeconds: value.otherSeconds
|
||||
}
|
||||
})
|
||||
.nullable()
|
||||
const UsageHistoryBody = z.object({
|
||||
days: z.array(z.object({ start: z.number().int(), seconds: UsageSeconds })).max(31),
|
||||
totalSeconds: UsageSeconds,
|
||||
yourSeconds: UsageSeconds,
|
||||
members: usageTop('userId'),
|
||||
sandboxes: usageTop('sandboxId')
|
||||
})
|
||||
|
||||
/** GET /v1/billing/usage: 30 days of sandbox hours, days starting at the local midnight. */
|
||||
export async function fetchUsageHistory(
|
||||
endpoints: BillingEndpoints,
|
||||
token: string,
|
||||
utcOffsetMinutes: number,
|
||||
fetchImpl: typeof fetch = fetch
|
||||
): Promise<OrcaBillingUsageHistory> {
|
||||
const body = UsageHistoryBody.safeParse(
|
||||
await billingRequest(
|
||||
endpoints,
|
||||
token,
|
||||
'GET',
|
||||
`v1/billing/usage?utcOffset=${Math.round(utcOffsetMinutes)}`,
|
||||
undefined,
|
||||
fetchImpl
|
||||
)
|
||||
)
|
||||
if (!body.success) {
|
||||
throw new Error('invalid_billing_response')
|
||||
}
|
||||
return body.data
|
||||
}
|
||||
@@ -147,43 +147,9 @@ describe('teammate names', () => {
|
||||
expect(keys.map((key) => key.createdByName)).toEqual(['Ada Lovelace', null, undefined])
|
||||
})
|
||||
|
||||
it('reads the team audit log: filters go in the query, unknown kinds and categories still parse', async () => {
|
||||
const event = {
|
||||
id: 'aud_1',
|
||||
at: 5,
|
||||
category: 'something_new',
|
||||
action: 'secret.updated',
|
||||
actor: { kind: 'robot', userId: 'u_ada', name: 'Ada Lovelace', via: 'carrier_pigeon' },
|
||||
target: { type: 'secret', id: 'STRIPE_KEY', label: 'STRIPE_KEY' },
|
||||
detail: { scope: 'org' }
|
||||
}
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
respond(200, {
|
||||
events: [event],
|
||||
nextCursor: '5.aud_1',
|
||||
actors: [event.actor],
|
||||
categories: ['secrets']
|
||||
})
|
||||
)
|
||||
const page = await client(fetchImpl).listAuditLog({
|
||||
category: 'secrets',
|
||||
actor: 'u_ada',
|
||||
limit: 50
|
||||
})
|
||||
expect(String(fetchImpl.mock.calls[0]?.[0])).toBe(
|
||||
'https://cp.example.dev/v1/audit-log?category=secrets&actor=u_ada&limit=50'
|
||||
)
|
||||
expect(page.nextCursor).toBe('5.aud_1')
|
||||
expect(page.events[0]).toMatchObject({
|
||||
category: 'other',
|
||||
actor: { kind: 'person', name: 'Ada Lovelace', via: null },
|
||||
target: { label: 'STRIPE_KEY' }
|
||||
})
|
||||
})
|
||||
|
||||
it('tells a plan without the audit log apart from a missing role and an older control plane', async () => {
|
||||
it('tells a plan without the feature apart from a missing role and an older control plane', async () => {
|
||||
const answer = (status: number, body: unknown) =>
|
||||
codeOf(client(vi.fn<typeof fetch>(async () => respond(status, body))).listAuditLog())
|
||||
codeOf(client(vi.fn<typeof fetch>(async () => respond(status, body))).listGrants())
|
||||
expect(await answer(403, { error: 'entitlement_denied', reason: 'audit_log' })).toBe(
|
||||
'plan-required'
|
||||
)
|
||||
@@ -200,35 +166,10 @@ describe('teammate names', () => {
|
||||
vi.fn<typeof fetch>(async () =>
|
||||
respond(403, { error: 'entitlement_denied', reason: 'audit_log' })
|
||||
)
|
||||
).listAuditLog()
|
||||
).listGrants()
|
||||
)
|
||||
expect(refused.detail).toBe('audit_log')
|
||||
})
|
||||
|
||||
it('exports the audit log as CSV text and says when the export was cut short', async () => {
|
||||
const csv = 'time,category,action\r\n2026-11-12T00:00:00.000Z,secrets,secret.updated\r\n'
|
||||
const fetchImpl = vi.fn<typeof fetch>(
|
||||
async () =>
|
||||
new Response(csv, {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'text/csv', 'x-orca-audit-truncated': 'true' }
|
||||
})
|
||||
)
|
||||
const exported = await client(fetchImpl).exportAuditLogCsv({ category: 'secrets' })
|
||||
expect(String(fetchImpl.mock.calls[0]?.[0])).toBe(
|
||||
'https://cp.example.dev/v1/audit-log?category=secrets&format=csv'
|
||||
)
|
||||
expect(exported).toEqual({ csv, truncated: true })
|
||||
expect(
|
||||
await codeOf(
|
||||
client(
|
||||
vi.fn<typeof fetch>(async () =>
|
||||
respond(403, { error: 'entitlement_denied', reason: 'audit_log' })
|
||||
)
|
||||
).exportAuditLogCsv()
|
||||
)
|
||||
).toBe('plan-required')
|
||||
})
|
||||
})
|
||||
|
||||
describe('response hardening', () => {
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
CloudApiApprovalSchema,
|
||||
CloudAuditLogPageSchema,
|
||||
CloudApiCreatedKeySchema,
|
||||
CloudApiGrantListSchema,
|
||||
CloudApiInstallationListSchema,
|
||||
@@ -20,8 +19,6 @@ import {
|
||||
RoutineUpdatedSchema,
|
||||
RoutineWebhookSchema,
|
||||
type CloudApiErrorCode,
|
||||
type CloudAuditLogExport,
|
||||
type CloudAuditLogQuery,
|
||||
type CreateCloudApiApprovalInput,
|
||||
type CreateCloudApiKeyInput,
|
||||
type RoutineInput,
|
||||
@@ -32,7 +29,6 @@ import {
|
||||
const REQUEST_TIMEOUT_MS = 20_000
|
||||
const MAX_DETAIL_CHARS = 200
|
||||
// 5000 events is about 1.5 MB; anything far past that is not the export this client asked for.
|
||||
const MAX_EXPORT_CHARS = 16 * 1024 * 1024
|
||||
|
||||
export class CloudApiError extends Error {
|
||||
constructor(
|
||||
@@ -212,24 +208,6 @@ export function createCloudApiClient(deps: CloudApiClientDeps) {
|
||||
getSettings: () => request('GET', 'v1/settings', CloudApiSettingsSchema),
|
||||
putSettings: (settings: { vmCliEnabled: boolean }) =>
|
||||
request('PUT', 'v1/settings', CloudApiSettingsSchema, { body: settings }),
|
||||
listAuditLog: (query: CloudAuditLogQuery = {}) =>
|
||||
request('GET', 'v1/audit-log', CloudAuditLogPageSchema, {
|
||||
query,
|
||||
notFoundMeansUnavailable: true
|
||||
}),
|
||||
exportAuditLogCsv: async (
|
||||
query: Pick<CloudAuditLogQuery, 'category' | 'actor'> = {}
|
||||
): Promise<CloudAuditLogExport> => {
|
||||
const response = await send('GET', 'v1/audit-log', {
|
||||
query: { ...query, format: 'csv' },
|
||||
notFoundMeansUnavailable: true
|
||||
})
|
||||
const csv = await response.text().catch(() => null)
|
||||
if (csv === null || csv.length > MAX_EXPORT_CHARS) {
|
||||
throw new CloudApiError('invalid-response')
|
||||
}
|
||||
return { csv, truncated: response.headers.get('x-orca-audit-truncated') === 'true' }
|
||||
},
|
||||
listProjects: () => request('GET', 'v1/projects', CloudApiProjectListSchema),
|
||||
listInstallations: () =>
|
||||
request('GET', 'v1/github/installations', CloudApiInstallationListSchema, {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { ipcMain } from 'electron'
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
CloudAuditLogQuerySchema,
|
||||
CreateCloudApiApprovalInputSchema,
|
||||
CreateCloudApiKeyInputSchema,
|
||||
RoutineInputSchema,
|
||||
@@ -17,7 +16,6 @@ import {
|
||||
} from './cloud-api-service'
|
||||
|
||||
const Id = z.string().min(1).max(128)
|
||||
const AuditExportQuery = CloudAuditLogQuerySchema.pick({ category: true, actor: true })
|
||||
const SettingsInput = z.object({ vmCliEnabled: z.boolean() }).strict()
|
||||
|
||||
type Handler = (...args: unknown[]) => Promise<CloudApiResult<unknown>>
|
||||
@@ -55,12 +53,6 @@ const HANDLERS: Record<string, Handler> = {
|
||||
'cloudApi:revokeGrant': call([Id], (c, id) => c.revokeGrant(id)),
|
||||
'cloudApi:getSettings': call([], (c) => c.getSettings()),
|
||||
'cloudApi:putSettings': call([SettingsInput], (c, input) => c.putSettings(input)),
|
||||
'cloudApi:listAuditLog': call([CloudAuditLogQuerySchema.optional()], (c, q) =>
|
||||
c.listAuditLog(q ?? {})
|
||||
),
|
||||
'cloudApi:exportAuditLogCsv': call([AuditExportQuery.optional()], (c, q) =>
|
||||
c.exportAuditLogCsv(q ?? {})
|
||||
),
|
||||
'cloudApi:listProjects': call([], (c) => c.listProjects()),
|
||||
'cloudApi:listInstallations': call([], (c) => c.listInstallations()),
|
||||
'cloudApi:listRoutines': call([], (c) => c.listRoutines()),
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
// "Manage in browser": opens a web console page for the active profile's account.
|
||||
import { ipcMain } from 'electron'
|
||||
import {
|
||||
isOrcaCloudConsoleSection,
|
||||
type OrcaCloudConsoleOpenResult
|
||||
} from '../../../shared/orca-cloud-console'
|
||||
import { openOrcaCloudConsole } from '../../orca-profiles/cloud-console/cloud-console-link'
|
||||
import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths'
|
||||
|
||||
export function registerOrcaCloudConsoleHandlers(): void {
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:openCloudConsole',
|
||||
async (_event, rawArgs: unknown): Promise<OrcaCloudConsoleOpenResult> => {
|
||||
const section =
|
||||
typeof rawArgs === 'object' && rawArgs !== null && 'section' in rawArgs
|
||||
? rawArgs.section
|
||||
: undefined
|
||||
if (!isOrcaCloudConsoleSection(section)) {
|
||||
return { status: 'failed', error: 'invalid_orca_cloud_console_section' }
|
||||
}
|
||||
return openOrcaCloudConsole(getProfileUserDataPath(), section)
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -1,28 +1,20 @@
|
||||
import { ipcMain } from 'electron'
|
||||
import { z } from 'zod'
|
||||
import type {
|
||||
OrcaBillingCheckoutArgs,
|
||||
OrcaBillingOpenResult,
|
||||
OrcaBillingOverageArgs,
|
||||
OrcaBillingOverageResult,
|
||||
OrcaBillingStatusResult,
|
||||
OrcaBillingTeamPlansResult,
|
||||
OrcaBillingTrialClaimResult,
|
||||
OrcaBillingUsageHistoryResult
|
||||
OrcaBillingTrialClaimResult
|
||||
} from '../../../shared/orca-billing'
|
||||
import type { OrcaPlanCatalogResult } from '../../../shared/orca-billing-plans'
|
||||
import {
|
||||
ORCA_BILLING_INTERVALS,
|
||||
ORCA_BILLING_MAX_SEATS,
|
||||
ORCA_BILLING_TEAM_PLANS_MAX_ORGS
|
||||
} from '../../../shared/orca-billing'
|
||||
import { ORCA_BILLING_TEAM_PLANS_MAX_ORGS } from '../../../shared/orca-billing'
|
||||
import {
|
||||
claimOrcaBillingTrial,
|
||||
getOrcaBillingStatus,
|
||||
getOrcaBillingTeamPlans,
|
||||
getOrcaBillingUsageHistory,
|
||||
getOrcaPlanCatalog,
|
||||
openOrcaBillingCheckout,
|
||||
openOrcaBillingPortal,
|
||||
setOrcaBillingOverage
|
||||
} from '../../billing/billing-service'
|
||||
@@ -45,16 +37,6 @@ import {
|
||||
startCloudSetup
|
||||
} from '../../billing/cloud-setup-service'
|
||||
|
||||
const CheckoutArgs = z
|
||||
.object({
|
||||
// A plan id from billing's catalog (GET /v1/plans); billing decides what it sells.
|
||||
plan: z.string().regex(/^[a-z][a-z0-9_]{0,39}$/),
|
||||
interval: z.enum(ORCA_BILLING_INTERVALS),
|
||||
seats: z.number().int().min(1).max(ORCA_BILLING_MAX_SEATS),
|
||||
setupSessionId: z.string().regex(CLOUD_SETUP_SESSION_ID).optional()
|
||||
})
|
||||
.strict()
|
||||
|
||||
// Cents; the billing service enforces the plan's maximum.
|
||||
const OverageArgs = z
|
||||
.object({
|
||||
@@ -63,21 +45,6 @@ const OverageArgs = z
|
||||
})
|
||||
.strict()
|
||||
|
||||
// Minutes east of UTC (the renderer's -getTimezoneOffset()), so chart days are local days.
|
||||
const UsageHistoryArgs = z
|
||||
.object({ utcOffsetMinutes: z.number().int().min(-840).max(840) })
|
||||
.strict()
|
||||
|
||||
export function billingUsageHistoryArgsFromUnknown(args: unknown): {
|
||||
utcOffsetMinutes: number
|
||||
} {
|
||||
const parsed = UsageHistoryArgs.safeParse(args)
|
||||
if (!parsed.success) {
|
||||
throw new Error('invalid_orca_billing_usage_history')
|
||||
}
|
||||
return parsed.data
|
||||
}
|
||||
|
||||
const TeamPlansArgs = z
|
||||
.object({
|
||||
orgIds: z
|
||||
@@ -121,14 +88,6 @@ export function cloudSetupStartArgsFromUnknown(args: unknown): CloudSetupStartAr
|
||||
return parsed.data
|
||||
}
|
||||
|
||||
export function billingCheckoutArgsFromUnknown(args: unknown): OrcaBillingCheckoutArgs {
|
||||
const parsed = CheckoutArgs.safeParse(args)
|
||||
if (!parsed.success) {
|
||||
throw new Error('invalid_orca_billing_checkout')
|
||||
}
|
||||
return parsed.data
|
||||
}
|
||||
|
||||
export function billingOverageArgsFromUnknown(args: unknown): OrcaBillingOverageArgs {
|
||||
const parsed = OverageArgs.safeParse(args)
|
||||
if (!parsed.success) {
|
||||
@@ -163,24 +122,11 @@ export function registerOrcaProfileBillingHandlers(store: Store): void {
|
||||
ipcMain.handle('orcaProfiles:billingPlans', async (): Promise<OrcaPlanCatalogResult> =>
|
||||
getOrcaPlanCatalog(getProfileUserDataPath())
|
||||
)
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:billingOpenCheckout',
|
||||
async (_event, rawArgs: unknown): Promise<OrcaBillingOpenResult> =>
|
||||
openOrcaBillingCheckout(getProfileUserDataPath(), billingCheckoutArgsFromUnknown(rawArgs))
|
||||
)
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:billingSetOverage',
|
||||
async (_event, rawArgs: unknown): Promise<OrcaBillingOverageResult> =>
|
||||
setOrcaBillingOverage(getProfileUserDataPath(), billingOverageArgsFromUnknown(rawArgs))
|
||||
)
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:billingUsageHistory',
|
||||
async (_event, rawArgs: unknown): Promise<OrcaBillingUsageHistoryResult> =>
|
||||
getOrcaBillingUsageHistory(
|
||||
getProfileUserDataPath(),
|
||||
billingUsageHistoryArgsFromUnknown(rawArgs).utcOffsetMinutes
|
||||
)
|
||||
)
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:billingTeamPlans',
|
||||
async (_event, rawArgs: unknown): Promise<OrcaBillingTeamPlansResult> =>
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
// IPC for Settings › Enterprise (single sign-on and directory sync) on the active profile's team.
|
||||
import { ipcMain } from 'electron'
|
||||
import {
|
||||
ORCA_ORG_SSO_DOMAIN_MAX_LENGTH,
|
||||
type OrcaProfileOrgEnterpriseResult,
|
||||
type OrcaProfileOrgSsoDomainResult,
|
||||
type OrcaProfileOrgSsoSetupLinkResult
|
||||
} from '../../../shared/orca-org-enterprise'
|
||||
import {
|
||||
changeOrcaProfileOrgSsoDomain,
|
||||
createOrcaProfileOrgSsoSetupLink,
|
||||
getOrcaProfileOrgEnterprise
|
||||
} from '../../orca-profiles/cloud-org/profile-cloud-org-enterprise-service'
|
||||
import type { OrgSsoDomainAction } from '../../orca-profiles/cloud-org/profile-cloud-org-enterprise-client'
|
||||
import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths'
|
||||
|
||||
function orgIdFromUnknown(args: unknown): { orgId: string; record: Record<string, unknown> } {
|
||||
if (!args || typeof args !== 'object') {
|
||||
throw new Error('invalid_orca_profile_org_selection')
|
||||
}
|
||||
const record = args as Record<string, unknown>
|
||||
const orgId = typeof record.orgId === 'string' ? record.orgId.trim() : ''
|
||||
if (!orgId) {
|
||||
throw new Error('invalid_orca_profile_org_selection')
|
||||
}
|
||||
return { orgId, record }
|
||||
}
|
||||
|
||||
function domainFromUnknown(value: unknown): string {
|
||||
const domain = typeof value === 'string' ? value.trim() : ''
|
||||
if (!domain || domain.length > ORCA_ORG_SSO_DOMAIN_MAX_LENGTH) {
|
||||
throw new Error('invalid_orca_org_sso_domain')
|
||||
}
|
||||
return domain
|
||||
}
|
||||
|
||||
export function registerOrcaProfileOrgEnterpriseHandlers(): void {
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:orgEnterprise',
|
||||
async (_event, rawArgs: unknown): Promise<OrcaProfileOrgEnterpriseResult> =>
|
||||
getOrcaProfileOrgEnterprise(getProfileUserDataPath(), orgIdFromUnknown(rawArgs).orgId)
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:orgSsoSetupLink',
|
||||
async (_event, rawArgs: unknown): Promise<OrcaProfileOrgSsoSetupLinkResult> =>
|
||||
createOrcaProfileOrgSsoSetupLink(getProfileUserDataPath(), orgIdFromUnknown(rawArgs).orgId)
|
||||
)
|
||||
|
||||
const domainHandler =
|
||||
(action: OrgSsoDomainAction) =>
|
||||
async (_event: unknown, rawArgs: unknown): Promise<OrcaProfileOrgSsoDomainResult> => {
|
||||
const { orgId, record } = orgIdFromUnknown(rawArgs)
|
||||
return changeOrcaProfileOrgSsoDomain(getProfileUserDataPath(), {
|
||||
orgId,
|
||||
domain: domainFromUnknown(record.domain),
|
||||
action
|
||||
})
|
||||
}
|
||||
ipcMain.handle('orcaProfiles:orgSsoDomainAdd', domainHandler('add'))
|
||||
ipcMain.handle('orcaProfiles:orgSsoDomainVerify', domainHandler('verify'))
|
||||
ipcMain.handle('orcaProfiles:orgSsoDomainRemove', domainHandler('remove'))
|
||||
}
|
||||
@@ -1,168 +1,30 @@
|
||||
import { isValidOrgName, ORCA_ORG_NAME_MAX_LENGTH } from '../../../shared/orca-org-management'
|
||||
import type { OrcaProfileOrgCreateResult } from '../../../shared/orca-org-management'
|
||||
// Read-only team IPC the desktop still needs: the roster (names, presence, owners), the person's
|
||||
// own two-factor state, and the team's MFA policy as it applies to them. Managing the team, its
|
||||
// members and its policies happens in the web console (see orca-cloud-console-handlers.ts).
|
||||
import { ipcMain } from 'electron'
|
||||
import { registerOrcaProfileOrgEnterpriseHandlers } from './orca-profile-org-enterprise-handlers'
|
||||
import type {
|
||||
OrcaOrgRole,
|
||||
OrcaProfileOrgInviteRevokeArgs,
|
||||
OrcaProfileOrgMemberChangeRoleArgs,
|
||||
OrcaProfileOrgMemberInviteArgs,
|
||||
OrcaProfileOrgMemberMutationResult,
|
||||
OrcaProfileOrgMemberRemoveArgs,
|
||||
OrcaProfileOrgMembersListArgs,
|
||||
OrcaProfileOrgMembersListResult
|
||||
} from '../../../shared/orca-profiles'
|
||||
import type { OrcaAccountMfaResult } from '../../../shared/orca-account-mfa'
|
||||
import { getOrcaProfileAccountMfa } from '../../orca-profiles/cloud-mfa/profile-cloud-mfa-service'
|
||||
import {
|
||||
ORCA_TEAM_MFA_GRACE_CHOICES,
|
||||
type OrcaTeamMfaGrace,
|
||||
type OrcaTeamMfaPendingResult,
|
||||
type OrcaTeamMfaPolicyResult,
|
||||
type OrcaTeamMfaPolicySetResult,
|
||||
type OrcaTeamMfaRemindResult
|
||||
} from '../../../shared/orca-team-mfa-policy'
|
||||
import {
|
||||
getOrcaTeamMfaPolicy,
|
||||
listOrcaTeamMfaPending,
|
||||
remindOrcaTeamMfa,
|
||||
setOrcaTeamMfaPolicy
|
||||
} from '../../orca-profiles/cloud-mfa/profile-cloud-team-mfa-service'
|
||||
import type { OrcaTeamMfaPolicyResult } from '../../../shared/orca-team-mfa-policy'
|
||||
import { getOrcaTeamMfaPolicy } from '../../orca-profiles/cloud-mfa/profile-cloud-team-mfa-service'
|
||||
import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths'
|
||||
import {
|
||||
changeOrcaProfileOrgMemberRole,
|
||||
createOrcaProfileOrg,
|
||||
inviteOrcaProfileOrgMember,
|
||||
leaveOrcaProfileOrg,
|
||||
resendOrcaProfileOrgInvite,
|
||||
listOrcaProfileOrgMembers,
|
||||
removeOrcaProfileOrgMember,
|
||||
revokeOrcaProfileOrgInvite
|
||||
} from '../../orca-profiles/cloud-org/profile-cloud-org-members-service'
|
||||
import {
|
||||
checkOrcaProfileOrgDelete,
|
||||
deleteOrcaProfileOrg
|
||||
} from '../../orca-profiles/cloud-org/profile-cloud-org-delete-service'
|
||||
import {
|
||||
ORCA_ORG_DELETE_CONFIRM_MAX_LENGTH,
|
||||
type OrcaProfileOrgDeleteCheckResult,
|
||||
type OrcaProfileOrgDeleteResult
|
||||
} from '../../../shared/orca-org-delete'
|
||||
import { listOrcaProfileOrgMembers } from '../../orca-profiles/cloud-org/profile-cloud-org-members-service'
|
||||
import { registerOrcaCloudConsoleHandlers } from './orca-cloud-console-handlers'
|
||||
|
||||
function orgMembersScopedArgs(args: unknown): { orgId: string; record: Record<string, unknown> } {
|
||||
if (!args || typeof args !== 'object') {
|
||||
throw new Error('invalid_orca_profile_org_selection')
|
||||
}
|
||||
const record = args as Record<string, unknown>
|
||||
function orgIdFromUnknown(args: unknown): string {
|
||||
const record = args && typeof args === 'object' ? (args as Record<string, unknown>) : {}
|
||||
const orgId = typeof record.orgId === 'string' ? record.orgId.trim() : ''
|
||||
if (!orgId) {
|
||||
throw new Error('invalid_orca_profile_org_selection')
|
||||
}
|
||||
return { orgId, record }
|
||||
}
|
||||
|
||||
function orgRoleFromUnknown(value: unknown): OrcaOrgRole {
|
||||
if (value === 'owner' || value === 'admin' || value === 'member') {
|
||||
return value
|
||||
}
|
||||
throw new Error('invalid_orca_org_role')
|
||||
}
|
||||
|
||||
function orgEmailFromUnknown(value: unknown): string {
|
||||
const email = typeof value === 'string' ? value.trim() : ''
|
||||
if (!email) {
|
||||
throw new Error('invalid_orca_org_member_email')
|
||||
}
|
||||
return email
|
||||
}
|
||||
|
||||
function orgUserIdFromUnknown(value: unknown): string {
|
||||
const userId = typeof value === 'string' ? value.trim() : ''
|
||||
if (!userId) {
|
||||
throw new Error('invalid_orca_org_member_user')
|
||||
}
|
||||
return userId
|
||||
}
|
||||
|
||||
function orgMemberInviteArgsFromUnknown(args: unknown): OrcaProfileOrgMemberInviteArgs {
|
||||
const { orgId, record } = orgMembersScopedArgs(args)
|
||||
return { orgId, email: orgEmailFromUnknown(record.email), role: orgRoleFromUnknown(record.role) }
|
||||
}
|
||||
|
||||
function orgInviteRevokeArgsFromUnknown(args: unknown): OrcaProfileOrgInviteRevokeArgs {
|
||||
const { orgId, record } = orgMembersScopedArgs(args)
|
||||
return { orgId, email: orgEmailFromUnknown(record.email) }
|
||||
}
|
||||
|
||||
function orgMemberChangeRoleArgsFromUnknown(args: unknown): OrcaProfileOrgMemberChangeRoleArgs {
|
||||
const { orgId, record } = orgMembersScopedArgs(args)
|
||||
return {
|
||||
orgId,
|
||||
userId: orgUserIdFromUnknown(record.userId),
|
||||
role: orgRoleFromUnknown(record.role)
|
||||
}
|
||||
}
|
||||
|
||||
function orgMemberRemoveArgsFromUnknown(args: unknown): OrcaProfileOrgMemberRemoveArgs {
|
||||
const { orgId, record } = orgMembersScopedArgs(args)
|
||||
return { orgId, userId: orgUserIdFromUnknown(record.userId) }
|
||||
}
|
||||
|
||||
function orgCreateNameFromUnknown(args: unknown): string {
|
||||
const record = args && typeof args === 'object' ? (args as Record<string, unknown>) : {}
|
||||
const name = typeof record.name === 'string' ? record.name.trim() : ''
|
||||
if (!name || name.length > ORCA_ORG_NAME_MAX_LENGTH || !isValidOrgName(name)) {
|
||||
throw new Error('invalid_orca_org_name')
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
/** The name exactly as typed (auth compares it case-sensitively), so it is never trimmed here. */
|
||||
function orgDeleteConfirmNameFromUnknown(value: unknown): string {
|
||||
if (typeof value !== 'string' || !value || value.length > ORCA_ORG_DELETE_CONFIRM_MAX_LENGTH) {
|
||||
throw new Error('invalid_orca_org_delete_confirm_name')
|
||||
}
|
||||
return value
|
||||
return orgId
|
||||
}
|
||||
|
||||
export function registerOrcaProfileOrgMemberHandlers(): void {
|
||||
// Settings › Enterprise (single sign-on, directory sync) for the same team.
|
||||
registerOrcaProfileOrgEnterpriseHandlers()
|
||||
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:orgDeleteCheck',
|
||||
async (_event, rawArgs: unknown): Promise<OrcaProfileOrgDeleteCheckResult> =>
|
||||
checkOrcaProfileOrgDelete(getProfileUserDataPath(), orgMembersScopedArgs(rawArgs).orgId)
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:orgDelete',
|
||||
async (_event, rawArgs: unknown): Promise<OrcaProfileOrgDeleteResult> => {
|
||||
const { orgId, record } = orgMembersScopedArgs(rawArgs)
|
||||
return deleteOrcaProfileOrg(getProfileUserDataPath(), {
|
||||
orgId,
|
||||
confirmName: orgDeleteConfirmNameFromUnknown(record.confirmName)
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:orgInviteResend',
|
||||
async (_event, rawArgs: unknown): Promise<OrcaProfileOrgMemberMutationResult> =>
|
||||
resendOrcaProfileOrgInvite(getProfileUserDataPath(), orgMemberInviteArgsFromUnknown(rawArgs))
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:orgLeave',
|
||||
async (_event, rawArgs: unknown): Promise<OrcaProfileOrgMemberMutationResult> =>
|
||||
leaveOrcaProfileOrg(getProfileUserDataPath(), { orgId: orgMembersScopedArgs(rawArgs).orgId })
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:orgCreate',
|
||||
async (_event, rawArgs: unknown): Promise<OrcaProfileOrgCreateResult> =>
|
||||
createOrcaProfileOrg(getProfileUserDataPath(), { name: orgCreateNameFromUnknown(rawArgs) })
|
||||
)
|
||||
registerOrcaCloudConsoleHandlers()
|
||||
|
||||
ipcMain.handle('orcaProfiles:accountMfa', async (): Promise<OrcaAccountMfaResult> =>
|
||||
getOrcaProfileAccountMfa(getProfileUserDataPath())
|
||||
@@ -171,39 +33,7 @@ export function registerOrcaProfileOrgMemberHandlers(): void {
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:teamMfaPolicy',
|
||||
async (_event, rawArgs: unknown): Promise<OrcaTeamMfaPolicyResult> =>
|
||||
getOrcaTeamMfaPolicy(getProfileUserDataPath(), orgMembersScopedArgs(rawArgs).orgId)
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:teamMfaPolicySet',
|
||||
async (_event, rawArgs: unknown): Promise<OrcaTeamMfaPolicySetResult> => {
|
||||
const { orgId, record } = orgMembersScopedArgs(rawArgs)
|
||||
// Only the fixed choices cross to the server; anything else is refused here.
|
||||
const enforce: OrcaTeamMfaGrace | 'off' | undefined =
|
||||
record.enforce === 'off'
|
||||
? 'off'
|
||||
: ORCA_TEAM_MFA_GRACE_CHOICES.find((choice) => choice === record.enforce)
|
||||
if (enforce === undefined) {
|
||||
return { status: 'failed', error: 'invalid_enforce' }
|
||||
}
|
||||
return setOrcaTeamMfaPolicy(getProfileUserDataPath(), { orgId, enforce })
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:teamMfaPending',
|
||||
async (_event, rawArgs: unknown): Promise<OrcaTeamMfaPendingResult> =>
|
||||
listOrcaTeamMfaPending(getProfileUserDataPath(), orgMembersScopedArgs(rawArgs).orgId)
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:teamMfaRemind',
|
||||
async (_event, rawArgs: unknown): Promise<OrcaTeamMfaRemindResult> => {
|
||||
const { orgId, record } = orgMembersScopedArgs(rawArgs)
|
||||
const userId =
|
||||
typeof record.userId === 'string' && record.userId.length <= 128 ? record.userId : undefined
|
||||
return remindOrcaTeamMfa(getProfileUserDataPath(), { orgId, ...(userId ? { userId } : {}) })
|
||||
}
|
||||
getOrcaTeamMfaPolicy(getProfileUserDataPath(), orgIdFromUnknown(rawArgs))
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
@@ -212,45 +42,6 @@ export function registerOrcaProfileOrgMemberHandlers(): void {
|
||||
_event,
|
||||
rawArgs: OrcaProfileOrgMembersListArgs
|
||||
): Promise<OrcaProfileOrgMembersListResult> =>
|
||||
listOrcaProfileOrgMembers(getProfileUserDataPath(), orgMembersScopedArgs(rawArgs).orgId)
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:orgMemberInvite',
|
||||
async (
|
||||
_event,
|
||||
rawArgs: OrcaProfileOrgMemberInviteArgs
|
||||
): Promise<OrcaProfileOrgMemberMutationResult> =>
|
||||
inviteOrcaProfileOrgMember(getProfileUserDataPath(), orgMemberInviteArgsFromUnknown(rawArgs))
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:orgInviteRevoke',
|
||||
async (
|
||||
_event,
|
||||
rawArgs: OrcaProfileOrgInviteRevokeArgs
|
||||
): Promise<OrcaProfileOrgMemberMutationResult> =>
|
||||
revokeOrcaProfileOrgInvite(getProfileUserDataPath(), orgInviteRevokeArgsFromUnknown(rawArgs))
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:orgMemberChangeRole',
|
||||
async (
|
||||
_event,
|
||||
rawArgs: OrcaProfileOrgMemberChangeRoleArgs
|
||||
): Promise<OrcaProfileOrgMemberMutationResult> =>
|
||||
changeOrcaProfileOrgMemberRole(
|
||||
getProfileUserDataPath(),
|
||||
orgMemberChangeRoleArgsFromUnknown(rawArgs)
|
||||
)
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'orcaProfiles:orgMemberRemove',
|
||||
async (
|
||||
_event,
|
||||
rawArgs: OrcaProfileOrgMemberRemoveArgs
|
||||
): Promise<OrcaProfileOrgMemberMutationResult> =>
|
||||
removeOrcaProfileOrgMember(getProfileUserDataPath(), orgMemberRemoveArgsFromUnknown(rawArgs))
|
||||
listOrcaProfileOrgMembers(getProfileUserDataPath(), orgIdFromUnknown(rawArgs))
|
||||
)
|
||||
}
|
||||
|
||||
@@ -9,24 +9,11 @@ function cleanEnvString(value: string | undefined, fallback: string): string {
|
||||
return trimmed || fallback
|
||||
}
|
||||
|
||||
// Dev-only org list: the seeded orgs plus any created (and minus any left) this run.
|
||||
const createdDevOrganizations: OrcaCloudOrgSummary[] = []
|
||||
const leftDevOrganizationIds = new Set<string>()
|
||||
|
||||
export function addDevOrganization(org: OrcaCloudOrgSummary): void {
|
||||
createdDevOrganizations.push(org)
|
||||
}
|
||||
|
||||
export function removeDevOrganization(orgId: string): void {
|
||||
leftDevOrganizationIds.add(orgId)
|
||||
}
|
||||
|
||||
function defaultDevOrganizations(): OrcaCloudOrgSummary[] {
|
||||
return [
|
||||
{ orgId: 'dev-personal', name: 'Personal', role: 'Owner' },
|
||||
{ orgId: 'dev-acme', name: 'Acme Dev', role: 'Admin' },
|
||||
...createdDevOrganizations
|
||||
].filter((org) => !leftDevOrganizationIds.has(org.orgId))
|
||||
{ orgId: 'dev-acme', name: 'Acme Dev', role: 'Admin' }
|
||||
]
|
||||
}
|
||||
|
||||
function devCapabilities(): OrcaCloudCapabilities {
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
ORCA_CLOUD_CALLBACK_RESPONSE_HEADERS,
|
||||
ORCA_CLOUD_CALLBACK_SUCCESS_PAGE
|
||||
} from './profile-cloud-callback-page'
|
||||
import { ORCA_CLOUD_AUTH_SSO_REQUIRED_ERROR } from '../../../shared/orca-org-enterprise'
|
||||
import { ORCA_CLOUD_AUTH_SSO_REQUIRED_ERROR } from '../../../shared/orca-profile-reconnect-reason'
|
||||
|
||||
export type OrcaCloudAuthorizationCode = {
|
||||
code: string
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// Where the web console lives and how the desktop asks auth for a console ticket. One module so
|
||||
// the contract is easy to adjust (orca-cloud apps/auth/src/http/console-ticket-route.ts).
|
||||
import { cleanCloudServiceOrigin } from '../../../shared/cloud-service-url'
|
||||
import type { OrcaCloudAuthConfig } from '../cloud-auth/profile-cloud-auth-config'
|
||||
|
||||
/**
|
||||
* Mints a single-use console ticket for the signed-in desktop session (Bearer access token).
|
||||
* Body (strict, at most 256 bytes): `{ page?, orgId? }`. Answer: `{ url, expiresAt }`; the desktop
|
||||
* opens `url` as-is.
|
||||
*/
|
||||
export const CLOUD_CONSOLE_TICKET_PATH = '/v1/desktop/console/ticket'
|
||||
/** A click should open the browser promptly; past this the console opens without a ticket. */
|
||||
export const CLOUD_CONSOLE_TICKET_TIMEOUT_MS = 8_000
|
||||
|
||||
/**
|
||||
* The console's origin: ORCA_CLOUD_CONSOLE_URL when set (staging, local dev), else the auth
|
||||
* service's own origin, which serves the console pages.
|
||||
*/
|
||||
export function cloudConsoleOrigin(
|
||||
config: Pick<OrcaCloudAuthConfig, 'apiBaseUrl'>,
|
||||
env: NodeJS.ProcessEnv,
|
||||
allowLoopbackHttp: boolean
|
||||
): string {
|
||||
return (
|
||||
cleanCloudServiceOrigin(env.ORCA_CLOUD_CONSOLE_URL, allowLoopbackHttp) ??
|
||||
new URL(config.apiBaseUrl).origin
|
||||
)
|
||||
}
|
||||
|
||||
export function cloudConsoleTicketUrl(config: Pick<OrcaCloudAuthConfig, 'apiBaseUrl'>): string {
|
||||
return new URL(CLOUD_CONSOLE_TICKET_PATH, `${config.apiBaseUrl}/`).toString()
|
||||
}
|
||||
|
||||
/** Without a ticket: the console's front door, where the browser asks the person to sign in. */
|
||||
export function cloudConsoleFallbackUrl(origin: string): string {
|
||||
return new URL('/console', origin).toString()
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('electron', () => ({ app: { isPackaged: false }, shell: { openExternal: vi.fn() } }))
|
||||
|
||||
import { CLOUD_CONSOLE_TICKET_PATH, cloudConsoleOrigin } from './cloud-console-config'
|
||||
import { acceptedTicketUrl, requestCloudConsoleTicket } from './cloud-console-link'
|
||||
|
||||
const config = { apiBaseUrl: 'https://login.onorca.dev' }
|
||||
|
||||
function fakeFetch(response: Response, seen: { url: string; init?: RequestInit }[] = []) {
|
||||
return vi.fn<typeof fetch>(async (url, init) => {
|
||||
seen.push({ url: String(url), init })
|
||||
return response
|
||||
})
|
||||
}
|
||||
|
||||
describe('console origin', () => {
|
||||
it('is the auth origin unless ORCA_CLOUD_CONSOLE_URL names another', () => {
|
||||
expect(cloudConsoleOrigin(config, {}, false)).toBe('https://login.onorca.dev')
|
||||
expect(
|
||||
cloudConsoleOrigin(config, { ORCA_CLOUD_CONSOLE_URL: 'https://console.staging.dev' }, false)
|
||||
).toBe('https://console.staging.dev')
|
||||
// Plain http only in development builds.
|
||||
expect(
|
||||
cloudConsoleOrigin(config, { ORCA_CLOUD_CONSOLE_URL: 'http://127.0.0.1:8787' }, false)
|
||||
).toBe('https://login.onorca.dev')
|
||||
expect(
|
||||
cloudConsoleOrigin(config, { ORCA_CLOUD_CONSOLE_URL: 'http://127.0.0.1:8787' }, true)
|
||||
).toBe('http://127.0.0.1:8787')
|
||||
})
|
||||
})
|
||||
|
||||
describe('console ticket', () => {
|
||||
it('posts the page and team with the access token, and never follows redirects', async () => {
|
||||
const seen: { url: string; init?: RequestInit }[] = []
|
||||
const ticket = 'https://login.onorca.dev/console/redeem?t=abc'
|
||||
const url = await requestCloudConsoleTicket(
|
||||
config,
|
||||
{ accessToken: 'at' },
|
||||
{ section: 'enterprise', orgId: 'org_1' },
|
||||
fakeFetch(Response.json({ url: ticket, expiresAt: 1 }), seen)
|
||||
)
|
||||
expect(url).toBe(ticket)
|
||||
expect(seen[0]?.url).toBe(`https://login.onorca.dev${CLOUD_CONSOLE_TICKET_PATH}`)
|
||||
expect(seen[0]?.init?.method).toBe('POST')
|
||||
expect(seen[0]?.init?.redirect).toBe('error')
|
||||
expect(new Headers(seen[0]?.init?.headers).get('authorization')).toBe('Bearer at')
|
||||
expect(JSON.parse(String(seen[0]?.init?.body))).toEqual({ page: 'enterprise', orgId: 'org_1' })
|
||||
})
|
||||
|
||||
it('leaves out the team for a personal account', async () => {
|
||||
const seen: { url: string; init?: RequestInit }[] = []
|
||||
await requestCloudConsoleTicket(
|
||||
config,
|
||||
{ accessToken: 'at' },
|
||||
{ section: 'billing', orgId: null },
|
||||
fakeFetch(Response.json({ url: 'x' }), seen)
|
||||
)
|
||||
expect(JSON.parse(String(seen[0]?.init?.body))).toEqual({ page: 'billing' })
|
||||
})
|
||||
|
||||
it('throws on a refusal so the console opens without a ticket', async () => {
|
||||
await expect(
|
||||
requestCloudConsoleTicket(
|
||||
config,
|
||||
{ accessToken: 'at' },
|
||||
{ section: 'team', orgId: null },
|
||||
fakeFetch(Response.json({ error: 'recent_sign_in_required' }, { status: 403 }))
|
||||
)
|
||||
).rejects.toMatchObject({ statusCode: 403, errorCode: 'recent_sign_in_required' })
|
||||
})
|
||||
|
||||
it('opens only a ticket URL on the console or auth origin', () => {
|
||||
const allowed = ['https://console.onorca.dev', 'https://login.onorca.dev']
|
||||
const ticket = 'https://login.onorca.dev/console/redeem?t=abc'
|
||||
expect(acceptedTicketUrl(ticket, allowed)).toBe(ticket)
|
||||
for (const bad of [
|
||||
'https://evil.example/console/redeem?t=abc',
|
||||
'javascript:alert(1)',
|
||||
'https://user:pw@login.onorca.dev/console',
|
||||
'',
|
||||
7,
|
||||
null
|
||||
]) {
|
||||
expect(acceptedTicketUrl(bad, allowed)).toBeNull()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,113 @@
|
||||
// Opens a web console page in the system browser (never an in-app view) through a single-use ticket
|
||||
// URL from auth, so the browser lands signed in; when that fails for any reason the console opens
|
||||
// without one and the browser asks the person to sign in. The ticket is never logged or kept.
|
||||
import { app, shell } from 'electron'
|
||||
import type {
|
||||
OrcaCloudConsoleOpenResult,
|
||||
OrcaCloudConsoleSection
|
||||
} from '../../../shared/orca-cloud-console'
|
||||
import {
|
||||
getOrcaCloudAuthConfig,
|
||||
isOrcaCloudDevAuthEnabled,
|
||||
type OrcaCloudAuthConfig
|
||||
} from '../cloud-auth/profile-cloud-auth-config'
|
||||
import { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client'
|
||||
import type { OrcaCloudSession } from '../cloud-session/profile-cloud-session-store'
|
||||
import { extractErrorCode } from '../cloud-org/profile-cloud-org-members-client'
|
||||
import { runOrgMemberCall } from '../cloud-org/profile-cloud-org-members-service'
|
||||
import { ensureActiveOrcaProfile } from '../profile-index-store'
|
||||
import {
|
||||
CLOUD_CONSOLE_TICKET_TIMEOUT_MS,
|
||||
cloudConsoleFallbackUrl,
|
||||
cloudConsoleOrigin,
|
||||
cloudConsoleTicketUrl
|
||||
} from './cloud-console-config'
|
||||
|
||||
/**
|
||||
* The ticket URL from auth, opened as-is; null for anything that isn't an http(s) URL on the
|
||||
* console's or auth's own origin, so a bad answer can never send the browser elsewhere.
|
||||
*/
|
||||
export function acceptedTicketUrl(
|
||||
value: unknown,
|
||||
allowedOrigins: readonly string[]
|
||||
): string | null {
|
||||
if (typeof value !== 'string') {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
const url = new URL(value)
|
||||
const web = url.protocol === 'https:' || url.protocol === 'http:'
|
||||
return web && !url.username && !url.password && allowedOrigins.includes(url.origin)
|
||||
? value
|
||||
: null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** Asks auth for a single-use console ticket; answers its `url` unchecked (see acceptedTicketUrl). */
|
||||
export async function requestCloudConsoleTicket(
|
||||
config: Pick<OrcaCloudAuthConfig, 'apiBaseUrl'>,
|
||||
session: Pick<OrcaCloudSession, 'accessToken'>,
|
||||
args: { section: OrcaCloudConsoleSection; orgId: string | null },
|
||||
fetchImpl: typeof fetch = fetch
|
||||
): Promise<unknown> {
|
||||
const response = await fetchImpl(cloudConsoleTicketUrl(config), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
authorization: `Bearer ${session.accessToken}`
|
||||
},
|
||||
body: JSON.stringify({ page: args.section, ...(args.orgId ? { orgId: args.orgId } : {}) }),
|
||||
// Never follow a redirect with the access token attached.
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(CLOUD_CONSOLE_TICKET_TIMEOUT_MS)
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new OrcaCloudRequestError(response.status, await extractErrorCode(response))
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null)
|
||||
return typeof body === 'object' && body !== null && 'url' in body ? body.url : null
|
||||
}
|
||||
|
||||
async function mintTicketUrl(
|
||||
config: OrcaCloudAuthConfig,
|
||||
userDataPath: string,
|
||||
section: OrcaCloudConsoleSection
|
||||
): Promise<unknown> {
|
||||
if (isOrcaCloudDevAuthEnabled()) {
|
||||
return null
|
||||
}
|
||||
const active = ensureActiveOrcaProfile(userDataPath)
|
||||
if (!active.profile.cloud) {
|
||||
return null
|
||||
}
|
||||
const orgId = active.profile.cloud.activeOrgId ?? null
|
||||
const result = await runOrgMemberCall(config, active, userDataPath, (session) =>
|
||||
requestCloudConsoleTicket(config, session, { section, orgId })
|
||||
)
|
||||
return result.status === 'ok' ? result.value : null
|
||||
}
|
||||
|
||||
export async function openOrcaCloudConsole(
|
||||
userDataPath: string,
|
||||
section: OrcaCloudConsoleSection,
|
||||
openExternal: (url: string) => Promise<void> = (url) => shell.openExternal(url)
|
||||
): Promise<OrcaCloudConsoleOpenResult> {
|
||||
const configState = getOrcaCloudAuthConfig()
|
||||
if (!configState.configured) {
|
||||
return { status: 'unconfigured' }
|
||||
}
|
||||
const { config } = configState
|
||||
const origin = cloudConsoleOrigin(config, process.env, !app.isPackaged)
|
||||
const ticketUrl = acceptedTicketUrl(
|
||||
await mintTicketUrl(config, userDataPath, section).catch(() => null),
|
||||
[origin, new URL(config.apiBaseUrl).origin]
|
||||
)
|
||||
try {
|
||||
await openExternal(ticketUrl ?? cloudConsoleFallbackUrl(origin))
|
||||
return { status: 'opened', signedIn: ticketUrl !== null }
|
||||
} catch (error) {
|
||||
return { status: 'failed', error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
normalizePendingMembers,
|
||||
normalizeTeamMfaPolicy,
|
||||
sameOriginUrl
|
||||
} from './profile-cloud-team-mfa-service'
|
||||
import { normalizeTeamMfaPolicy, sameOriginUrl } from './profile-cloud-team-mfa-service'
|
||||
|
||||
const API = 'https://cloud.orca.dev'
|
||||
const setupUrl = `${API}/v1/account/security`
|
||||
@@ -18,25 +14,13 @@ describe('normalizeTeamMfaPolicy', () => {
|
||||
).toEqual({ policy: { enforceAt: 200, setAt: 100 }, self: 'pending', setupUrl })
|
||||
})
|
||||
|
||||
it('reads a manager answer, including a policy the plan no longer covers', () => {
|
||||
it('ignores the manager fields (the policy is managed in the web console)', () => {
|
||||
expect(
|
||||
normalizeTeamMfaPolicy(
|
||||
{
|
||||
policy: null,
|
||||
self: { mfa: 'on' },
|
||||
setupUrl,
|
||||
available: false,
|
||||
pendingMembers: 3,
|
||||
inactivePolicy: { enforceAt: 500 }
|
||||
},
|
||||
{ policy: null, self: { mfa: 'on' }, setupUrl, available: false, pendingMembers: 3 },
|
||||
API
|
||||
)
|
||||
).toEqual({
|
||||
policy: null,
|
||||
self: 'on',
|
||||
setupUrl,
|
||||
manage: { available: false, pendingMembers: 3, inactiveEnforceAt: 500, ssoHandled: false }
|
||||
})
|
||||
).toEqual({ policy: null, self: 'on', setupUrl })
|
||||
})
|
||||
|
||||
it('never turns a malformed state into blocked', () => {
|
||||
@@ -64,50 +48,11 @@ describe('normalizeTeamMfaPolicy', () => {
|
||||
})
|
||||
|
||||
describe('single sign-on', () => {
|
||||
it('reads the delegated state and the team-level flag', () => {
|
||||
it('reads the delegated state', () => {
|
||||
const read = normalizeTeamMfaPolicy(
|
||||
{
|
||||
policy: { enforceAt: 200, setAt: 100 },
|
||||
self: { mfa: 'delegated' },
|
||||
setupUrl,
|
||||
available: true,
|
||||
pendingMembers: 0,
|
||||
ssoHandled: true
|
||||
},
|
||||
{ policy: { enforceAt: 200, setAt: 100 }, self: { mfa: 'delegated' }, setupUrl },
|
||||
API
|
||||
)
|
||||
expect(read.self).toBe('delegated')
|
||||
expect(read.manage?.ssoHandled).toBe(true)
|
||||
})
|
||||
|
||||
it('treats anything but true as not handled', () => {
|
||||
for (const ssoHandled of [undefined, 'true', 1, null]) {
|
||||
const read = normalizeTeamMfaPolicy(
|
||||
{ policy: null, self: { mfa: 'on' }, setupUrl, available: true, ssoHandled },
|
||||
API
|
||||
)
|
||||
expect(read.manage?.ssoHandled).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('normalizePendingMembers', () => {
|
||||
it('keeps members with an email and maps unknown states to off', () => {
|
||||
expect(
|
||||
normalizePendingMembers({
|
||||
members: [
|
||||
{ userId: 'u1', email: 'a@x.dev', displayName: 'Ada', mfa: 'pending' },
|
||||
{ userId: null, email: 'b@x.dev', mfa: 'blocked' },
|
||||
{ userId: 'u3', email: 'c@x.dev', mfa: 'whatever' },
|
||||
{ userId: 'u4' },
|
||||
'nope'
|
||||
]
|
||||
})
|
||||
).toEqual([
|
||||
{ userId: 'u1', email: 'a@x.dev', displayName: 'Ada', mfa: 'pending' },
|
||||
{ userId: null, email: 'b@x.dev', mfa: 'blocked' },
|
||||
{ userId: 'u3', email: 'c@x.dev', mfa: 'off' }
|
||||
])
|
||||
expect(normalizePendingMembers(null)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
import {
|
||||
ORCA_TEAM_MFA_GRACE_CHOICES,
|
||||
type OrcaTeamMfaGrace,
|
||||
type OrcaTeamMfaPendingMember,
|
||||
type OrcaTeamMfaPendingResult,
|
||||
type OrcaTeamMfaPolicy,
|
||||
type OrcaTeamMfaPolicyResult,
|
||||
type OrcaTeamMfaPolicySetResult,
|
||||
type OrcaTeamMfaRemindResult,
|
||||
type OrcaTeamMfaSelfState
|
||||
import type {
|
||||
OrcaTeamMfaPolicy,
|
||||
OrcaTeamMfaPolicyResult,
|
||||
OrcaTeamMfaSelfState
|
||||
} from '../../../shared/orca-team-mfa-policy'
|
||||
import {
|
||||
getOrcaCloudAuthConfig,
|
||||
@@ -73,49 +67,13 @@ export function normalizeTeamMfaPolicy(value: unknown, apiBaseUrl: string): Orca
|
||||
const selfRecord = isRecord(record.self) ? record.self : {}
|
||||
// An unrecognized state is "unknown", never "blocked": only the server's word blocks anyone.
|
||||
const self = SELF_STATES.find((state) => state === selfRecord.mfa) ?? 'unknown'
|
||||
const pendingMembers = finiteNumber(record.pendingMembers)
|
||||
const inactive = isRecord(record.inactivePolicy)
|
||||
? finiteNumber(record.inactivePolicy.enforceAt)
|
||||
: null
|
||||
return {
|
||||
policy: normalizeDeadline(record.policy),
|
||||
self,
|
||||
setupUrl,
|
||||
// Present only when the server sent the manager fields; a member's answer has none.
|
||||
...(typeof record.available === 'boolean'
|
||||
? {
|
||||
manage: {
|
||||
available: record.available,
|
||||
pendingMembers: pendingMembers ?? 0,
|
||||
...(inactive !== null ? { inactiveEnforceAt: inactive } : {}),
|
||||
ssoHandled: record.ssoHandled === true
|
||||
}
|
||||
}
|
||||
: {})
|
||||
setupUrl
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizePendingMembers(value: unknown): OrcaTeamMfaPendingMember[] {
|
||||
const record = isRecord(value) ? value : null
|
||||
const members = Array.isArray(record?.members) ? record.members : []
|
||||
return members.flatMap((entry): OrcaTeamMfaPendingMember[] => {
|
||||
const member = isRecord(entry) ? entry : null
|
||||
const email = typeof member?.email === 'string' ? member.email.trim() : ''
|
||||
if (!member || !email) {
|
||||
return []
|
||||
}
|
||||
const displayName = typeof member.displayName === 'string' ? member.displayName.trim() : ''
|
||||
return [
|
||||
{
|
||||
userId: typeof member.userId === 'string' && member.userId ? member.userId : null,
|
||||
email,
|
||||
...(displayName ? { displayName } : {}),
|
||||
mfa: member.mfa === 'blocked' ? 'blocked' : member.mfa === 'pending' ? 'pending' : 'off'
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
async function request(url: string, init: RequestInit): Promise<unknown> {
|
||||
const response = await fetch(url, init)
|
||||
if (!response.ok) {
|
||||
@@ -199,100 +157,3 @@ export async function getOrcaTeamMfaPolicy(
|
||||
? result
|
||||
: unavailable(result)
|
||||
}
|
||||
|
||||
export async function setOrcaTeamMfaPolicy(
|
||||
userDataPath: string,
|
||||
args: { orgId: string; enforce: OrcaTeamMfaGrace | 'off' }
|
||||
): Promise<OrcaTeamMfaPolicySetResult> {
|
||||
if (args.enforce !== 'off' && !ORCA_TEAM_MFA_GRACE_CHOICES.includes(args.enforce)) {
|
||||
return { status: 'failed', error: 'invalid_enforce' }
|
||||
}
|
||||
const result = await call(
|
||||
userDataPath,
|
||||
async (_apiBaseUrl, token, url) => {
|
||||
const init =
|
||||
args.enforce === 'off'
|
||||
? { ...requestInit('GET', token), method: 'DELETE' }
|
||||
: { ...requestInit('POST', token, { enforce: args.enforce }), method: 'PUT' }
|
||||
const answer = await request(url('/mfa-policy'), init)
|
||||
const body = isRecord(answer) ? answer : null
|
||||
return {
|
||||
policy: normalizeDeadline(body?.policy),
|
||||
pendingMembers: finiteNumber(body?.pendingMembers) ?? 0
|
||||
}
|
||||
},
|
||||
args.orgId
|
||||
)
|
||||
if (result.status === 'ok') {
|
||||
return { status: 'ok', ...result.value }
|
||||
}
|
||||
if (result.status === 'unconfigured' || result.status === 'unsupported') {
|
||||
return result
|
||||
}
|
||||
if (result.status === 'request-error') {
|
||||
const { errorCode } = result.error
|
||||
if (errorCode === 'actor_needs_mfa') {
|
||||
return { status: 'actor-needs-mfa' }
|
||||
}
|
||||
if (errorCode === 'mfa_enforcement_not_entitled') {
|
||||
return { status: 'not-entitled' }
|
||||
}
|
||||
if (errorCode === 'sso_team_needs_notice') {
|
||||
return { status: 'sso-needs-notice' }
|
||||
}
|
||||
}
|
||||
return unavailable(result)
|
||||
}
|
||||
|
||||
export async function listOrcaTeamMfaPending(
|
||||
userDataPath: string,
|
||||
orgId: string
|
||||
): Promise<OrcaTeamMfaPendingResult> {
|
||||
const result = await call(
|
||||
userDataPath,
|
||||
async (_apiBaseUrl, token, url) =>
|
||||
normalizePendingMembers(await request(url('/mfa-policy/pending'), requestInit('GET', token))),
|
||||
orgId
|
||||
)
|
||||
if (result.status === 'ok') {
|
||||
return { status: 'ok', members: result.value }
|
||||
}
|
||||
return result.status === 'unconfigured' || result.status === 'unsupported'
|
||||
? result
|
||||
: unavailable(result)
|
||||
}
|
||||
|
||||
export async function remindOrcaTeamMfa(
|
||||
userDataPath: string,
|
||||
args: { orgId: string; userId?: string }
|
||||
): Promise<OrcaTeamMfaRemindResult> {
|
||||
const result = await call(
|
||||
userDataPath,
|
||||
async (_apiBaseUrl, token, url) => {
|
||||
const answer = await request(
|
||||
url('/mfa-policy/remind'),
|
||||
requestInit('POST', token, args.userId ? { userId: args.userId } : {})
|
||||
)
|
||||
const body = isRecord(answer) ? answer : null
|
||||
const delivery: 'log' | 'test-inbox' | 'unknown' =
|
||||
body?.delivery === 'log' || body?.delivery === 'test-inbox' ? body.delivery : 'unknown'
|
||||
return { recipients: finiteNumber(body?.recipients) ?? 0, delivery }
|
||||
},
|
||||
args.orgId
|
||||
)
|
||||
if (result.status === 'ok') {
|
||||
return { status: 'ok', ...result.value }
|
||||
}
|
||||
if (result.status === 'unconfigured' || result.status === 'unsupported') {
|
||||
return result
|
||||
}
|
||||
if (result.status === 'request-error') {
|
||||
if (result.error.errorCode === 'no_policy') {
|
||||
return { status: 'no-policy' }
|
||||
}
|
||||
if (result.error.errorCode === 'member_not_found') {
|
||||
return { status: 'not-found' }
|
||||
}
|
||||
}
|
||||
return unavailable(result)
|
||||
}
|
||||
|
||||
@@ -1,19 +1,11 @@
|
||||
import { isValidOrgName } from '../../../shared/orca-org-management'
|
||||
import type { OrcaProfileOrgCreateResult } from '../../../shared/orca-org-management'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { addDevOrganization, removeDevOrganization } from '../cloud-auth/profile-cloud-dev-auth'
|
||||
import type {
|
||||
OrcaOrgMember,
|
||||
OrcaOrgMembersRoster,
|
||||
OrcaOrgPendingInvite,
|
||||
OrcaProfileOrgMemberChangeRoleArgs,
|
||||
OrcaProfileOrgMemberInviteArgs,
|
||||
OrcaProfileOrgMemberMutationResult,
|
||||
OrcaProfileOrgMemberRemoveArgs,
|
||||
OrcaProfileOrgInviteRevokeArgs
|
||||
OrcaOrgPendingInvite
|
||||
} from '../../../shared/orca-profiles'
|
||||
|
||||
// With no dev-auth server, this roster mirrors real membership states and mutation results.
|
||||
// With no dev-auth server, this roster mirrors real membership states (read-only: the team is
|
||||
// managed in the web console).
|
||||
type DevOrgRoster = {
|
||||
members: OrcaOrgMember[]
|
||||
pendingInvites: OrcaOrgPendingInvite[]
|
||||
@@ -78,29 +70,8 @@ function getDevRoster(orgId: string): DevOrgRoster {
|
||||
return seeded
|
||||
}
|
||||
|
||||
/** ORCA_CLOUD_DEV_INVITE_ACCEPT_MS: invites older than this are accepted (dev demos of seats). */
|
||||
function acceptAgedDevInvites(roster: DevOrgRoster): void {
|
||||
const acceptAfterMs = Number(process.env.ORCA_CLOUD_DEV_INVITE_ACCEPT_MS)
|
||||
if (!Number.isFinite(acceptAfterMs) || acceptAfterMs <= 0) {
|
||||
return
|
||||
}
|
||||
const now = Date.now()
|
||||
const accepted = roster.pendingInvites.filter((invite) => now - invite.createdAt >= acceptAfterMs)
|
||||
roster.pendingInvites = roster.pendingInvites.filter((invite) => !accepted.includes(invite))
|
||||
for (const invite of accepted) {
|
||||
const local = invite.email.split('@')[0] ?? invite.email
|
||||
roster.members.push({
|
||||
userId: `dev-${local}`,
|
||||
email: invite.email,
|
||||
displayName: local.charAt(0).toUpperCase() + local.slice(1),
|
||||
role: invite.role
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function listDevOrcaCloudOrgMembers(orgId: string): OrcaOrgMembersRoster {
|
||||
const roster = getDevRoster(orgId)
|
||||
acceptAgedDevInvites(roster)
|
||||
return {
|
||||
members: roster.members.map((member) => ({ ...member })),
|
||||
pendingInvites: roster.pendingInvites.map((invite) => ({ ...invite })),
|
||||
@@ -108,86 +79,3 @@ export function listDevOrcaCloudOrgMembers(orgId: string): OrcaOrgMembersRoster
|
||||
canManageMembers: true
|
||||
}
|
||||
}
|
||||
|
||||
export function inviteDevOrcaCloudOrgMember(
|
||||
args: OrcaProfileOrgMemberInviteArgs
|
||||
): OrcaProfileOrgMemberMutationResult {
|
||||
const roster = getDevRoster(args.orgId)
|
||||
const email = args.email.toLowerCase()
|
||||
if (roster.members.some((member) => member.email.toLowerCase() === email)) {
|
||||
return { status: 'conflict', reason: 'already_member' }
|
||||
}
|
||||
if (roster.pendingInvites.some((invite) => invite.email.toLowerCase() === email)) {
|
||||
return { status: 'conflict', reason: 'already_invited' }
|
||||
}
|
||||
roster.pendingInvites.push({ email: args.email, role: args.role, createdAt: Date.now() })
|
||||
return { status: 'ok' }
|
||||
}
|
||||
|
||||
export function revokeDevOrcaCloudOrgInvite(
|
||||
args: OrcaProfileOrgInviteRevokeArgs
|
||||
): OrcaProfileOrgMemberMutationResult {
|
||||
const roster = getDevRoster(args.orgId)
|
||||
const email = args.email.toLowerCase()
|
||||
const index = roster.pendingInvites.findIndex((invite) => invite.email.toLowerCase() === email)
|
||||
if (index === -1) {
|
||||
return { status: 'not-found' }
|
||||
}
|
||||
roster.pendingInvites.splice(index, 1)
|
||||
return { status: 'ok' }
|
||||
}
|
||||
|
||||
export function changeDevOrcaCloudOrgMemberRole(
|
||||
args: OrcaProfileOrgMemberChangeRoleArgs
|
||||
): OrcaProfileOrgMemberMutationResult {
|
||||
const roster = getDevRoster(args.orgId)
|
||||
if (args.userId === devSelf().userId) {
|
||||
return { status: 'invalid', reason: 'cannot_change_own_role' }
|
||||
}
|
||||
const member = roster.members.find((candidate) => candidate.userId === args.userId)
|
||||
if (!member) {
|
||||
return { status: 'not-found' }
|
||||
}
|
||||
member.role = args.role
|
||||
return { status: 'ok' }
|
||||
}
|
||||
|
||||
export function removeDevOrcaCloudOrgMember(
|
||||
args: OrcaProfileOrgMemberRemoveArgs
|
||||
): OrcaProfileOrgMemberMutationResult {
|
||||
const roster = getDevRoster(args.orgId)
|
||||
if (args.userId === devSelf().userId) {
|
||||
return { status: 'invalid', reason: 'cannot_remove_self' }
|
||||
}
|
||||
const index = roster.members.findIndex((candidate) => candidate.userId === args.userId)
|
||||
if (index === -1) {
|
||||
return { status: 'not-found' }
|
||||
}
|
||||
roster.members.splice(index, 1)
|
||||
return { status: 'ok' }
|
||||
}
|
||||
|
||||
export function createDevOrcaCloudOrg(name: string): OrcaProfileOrgCreateResult {
|
||||
const trimmed = name.trim()
|
||||
if (!isValidOrgName(trimmed)) {
|
||||
return { status: 'invalid' }
|
||||
}
|
||||
const orgId = `dev-team-${randomUUID().slice(0, 8)}`
|
||||
addDevOrganization({ orgId, name: trimmed, role: 'Owner' })
|
||||
// A new team starts with just its creator.
|
||||
devRostersByOrg.set(orgId, { members: [devSelf()], pendingInvites: [] })
|
||||
return { status: 'created', orgId, name: trimmed }
|
||||
}
|
||||
|
||||
export function leaveDevOrcaCloudOrg(orgId: string): OrcaProfileOrgMemberMutationResult {
|
||||
const roster = getDevRoster(orgId)
|
||||
const self = devSelf()
|
||||
const owners = roster.members.filter((member) => member.role === 'owner')
|
||||
const selfMember = roster.members.find((member) => member.userId === self.userId)
|
||||
if (selfMember?.role === 'owner' && owners.length <= 1) {
|
||||
return { status: 'invalid', reason: 'last_owner' }
|
||||
}
|
||||
roster.members = roster.members.filter((member) => member.userId !== self.userId)
|
||||
removeDevOrganization(orgId)
|
||||
return { status: 'ok' }
|
||||
}
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { OrcaCloudAuthConfig } from '../cloud-auth/profile-cloud-auth-config'
|
||||
import type { OrcaCloudSession } from '../cloud-session/profile-cloud-session-store'
|
||||
import { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client'
|
||||
import {
|
||||
checkOrcaCloudOrgDelete,
|
||||
deleteOrcaCloudOrg,
|
||||
parseOrgDeleteCheck
|
||||
} from './profile-cloud-org-delete-client'
|
||||
import { mapOrgDeleteRequestError } from './profile-cloud-org-delete-service'
|
||||
|
||||
const base = 'https://auth.test'
|
||||
const config: OrcaCloudAuthConfig = {
|
||||
apiBaseUrl: base,
|
||||
authorizeEndpoint: `${base}/a`,
|
||||
sessionEndpoint: `${base}/s`,
|
||||
refreshEndpoint: `${base}/r`,
|
||||
capabilitiesEndpoint: `${base}/c`,
|
||||
profileEndpoint: `${base}/p`,
|
||||
orgEndpoint: `${base}/o`,
|
||||
logoutEndpoint: `${base}/l`,
|
||||
relayTokenEndpoint: `${base}/rt`,
|
||||
connectorTokenEndpoint: `${base}/ct`,
|
||||
relayDirectorUrl: base,
|
||||
clientId: 'orca-desktop',
|
||||
scope: 'openid'
|
||||
}
|
||||
const session: OrcaCloudSession = {
|
||||
accessToken: 'token',
|
||||
refreshToken: 'refresh',
|
||||
expiresAt: 4_102_444_800_000,
|
||||
capabilities: { flags: {}, refreshedAt: 0 }
|
||||
}
|
||||
|
||||
function respond(status: number, body: unknown): void {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => new Response(JSON.stringify(body), { status }))
|
||||
)
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('team delete client (TEAM-DELETE)', () => {
|
||||
it('reads the pre-check, keeping known blockers only', async () => {
|
||||
respond(200, {
|
||||
deletable: false,
|
||||
blockers: [
|
||||
{ code: 'subscription_active', status: 'trialing' },
|
||||
{ code: 'workspaces_exist', count: 3 },
|
||||
{ code: 'something_new' }
|
||||
]
|
||||
})
|
||||
await expect(checkOrcaCloudOrgDelete(config, session, 'org_1')).resolves.toEqual({
|
||||
deletable: false,
|
||||
blockers: [
|
||||
{ code: 'subscription_active', status: 'trialing' },
|
||||
{ code: 'workspaces_exist', count: 3 }
|
||||
]
|
||||
})
|
||||
expect(vi.mocked(fetch).mock.calls[0]?.[0]).toBe(
|
||||
`${base}/v1/desktop/orgs/org_1/delete-check?supports=cancel_on_delete`
|
||||
)
|
||||
})
|
||||
|
||||
it('never calls a team deletable while a known blocker is listed', () => {
|
||||
expect(
|
||||
parseOrgDeleteCheck({ deletable: true, blockers: [{ code: 'workspaces_exist', count: 1 }] })
|
||||
.deletable
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('sends the typed name as is and reads 409 not_deletable as blocked', async () => {
|
||||
respond(409, { error: 'not_deletable', blockers: [{ code: 'workspaces_exist', count: 1 }] })
|
||||
await expect(
|
||||
deleteOrcaCloudOrg(config, session, { orgId: 'org_1', confirmName: ' Acme ' })
|
||||
).resolves.toEqual({ kind: 'blocked', blockers: [{ code: 'workspaces_exist', count: 1 }] })
|
||||
const init = vi.mocked(fetch).mock.calls[0]?.[1]
|
||||
expect(init?.body).toBe(JSON.stringify({ confirmName: ' Acme ' }))
|
||||
expect(init?.redirect).toBe('error')
|
||||
})
|
||||
|
||||
it('throws other failures with their code, and maps them', async () => {
|
||||
respond(400, { error: 'confirm_mismatch' })
|
||||
const error = await deleteOrcaCloudOrg(config, session, {
|
||||
orgId: 'org_1',
|
||||
confirmName: 'x'
|
||||
}).catch((reason: unknown) => reason)
|
||||
expect(error).toBeInstanceOf(OrcaCloudRequestError)
|
||||
expect(mapOrgDeleteRequestError(new OrcaCloudRequestError(503, 'billing_unavailable'))).toEqual(
|
||||
{ status: 'unavailable' }
|
||||
)
|
||||
expect(mapOrgDeleteRequestError(new OrcaCloudRequestError(429, 'rate_limited'))).toEqual({
|
||||
status: 'rate-limited'
|
||||
})
|
||||
expect(mapOrgDeleteRequestError(new OrcaCloudRequestError(403, 'not_owner'))).toEqual({
|
||||
status: 'forbidden'
|
||||
})
|
||||
// No JSON code on a 404: this auth predates team delete.
|
||||
expect(mapOrgDeleteRequestError(new OrcaCloudRequestError(404))).toEqual({
|
||||
status: 'unsupported'
|
||||
})
|
||||
})
|
||||
|
||||
it('EP-10: reads a cancelling plan the delete ends now, and ignores a malformed one', async () => {
|
||||
respond(200, {
|
||||
deletable: true,
|
||||
blockers: [],
|
||||
cancelsSubscription: { periodEnd: '2026-12-01T00:00:00.000Z' }
|
||||
})
|
||||
await expect(checkOrcaCloudOrgDelete(config, session, 'org_1')).resolves.toEqual({
|
||||
deletable: true,
|
||||
blockers: [],
|
||||
cancelsSubscription: { periodEnd: '2026-12-01T00:00:00.000Z' }
|
||||
})
|
||||
expect(
|
||||
parseOrgDeleteCheck({
|
||||
deletable: true,
|
||||
blockers: [],
|
||||
cancelsSubscription: { periodEnd: 'soon' }
|
||||
})
|
||||
).toEqual({ deletable: true, blockers: [] })
|
||||
})
|
||||
|
||||
it('EP-10: a delete that failed after the plan ended says so, whatever its status', async () => {
|
||||
respond(503, { error: 'delete_failed_after_cancel', cause: 'sandbox_control_unavailable' })
|
||||
await expect(
|
||||
deleteOrcaCloudOrg(config, session, { orgId: 'org_1', confirmName: 'Acme' })
|
||||
).resolves.toEqual({ kind: 'failed-after-cancel', cause: 'sandbox_control_unavailable' })
|
||||
expect(vi.mocked(fetch).mock.calls[0]?.[0]).toBe(
|
||||
`${base}/v1/desktop/orgs/org_1/delete?supports=cancel_on_delete`
|
||||
)
|
||||
respond(409, {
|
||||
error: 'delete_failed_after_cancel',
|
||||
cause: 'not_deletable',
|
||||
blockers: [{ code: 'workspaces_exist', count: 1 }]
|
||||
})
|
||||
await expect(
|
||||
deleteOrcaCloudOrg(config, session, { orgId: 'org_1', confirmName: 'Acme' })
|
||||
).resolves.toEqual({ kind: 'failed-after-cancel', cause: 'not_deletable' })
|
||||
})
|
||||
|
||||
it('EP-10: billing could not end the plan: blocked, team and plan untouched', async () => {
|
||||
respond(409, {
|
||||
error: 'not_deletable',
|
||||
blockers: [{ code: 'subscription_active', status: 'cancelling' }]
|
||||
})
|
||||
await expect(
|
||||
deleteOrcaCloudOrg(config, session, { orgId: 'org_1', confirmName: 'Acme' })
|
||||
).resolves.toEqual({
|
||||
kind: 'blocked',
|
||||
blockers: [{ code: 'subscription_active', status: 'cancelling' }]
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,90 +0,0 @@
|
||||
// Auth's team-delete routes (TEAM-DELETE). Same Bearer token, timeout and no-redirect rule as the
|
||||
// other /v1/desktop/orgs routes.
|
||||
import {
|
||||
isPlainRecord,
|
||||
normalizeOrgDeleteBlockers,
|
||||
normalizeOrgDeleteCancelsSubscription,
|
||||
ORCA_ORG_DELETE_SUPPORTS,
|
||||
type OrcaOrgDeleteBlocker,
|
||||
type OrcaOrgDeleteCancelsSubscription
|
||||
} from '../../../shared/orca-org-delete'
|
||||
import type { OrcaCloudAuthConfig } from '../cloud-auth/profile-cloud-auth-config'
|
||||
import type { OrcaCloudSession } from '../cloud-session/profile-cloud-session-store'
|
||||
import { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client'
|
||||
import { extractErrorCode, orgMembersUrl, requestInit } from './profile-cloud-org-members-client'
|
||||
|
||||
export type OrgDeleteCheck = {
|
||||
deletable: boolean
|
||||
blockers: OrcaOrgDeleteBlocker[]
|
||||
cancelsSubscription?: OrcaOrgDeleteCancelsSubscription
|
||||
}
|
||||
export type OrgDeleteOutcome =
|
||||
| { kind: 'deleted' }
|
||||
| { kind: 'blocked'; blockers: OrcaOrgDeleteBlocker[] }
|
||||
| { kind: 'failed-after-cancel'; cause: string }
|
||||
|
||||
/** EP-10: both routes, so auth may offer (and report) ending a cancelling plan on delete. */
|
||||
const SUPPORTS_QUERY = `?supports=${ORCA_ORG_DELETE_SUPPORTS}`
|
||||
|
||||
async function readJson(response: Response): Promise<Record<string, unknown>> {
|
||||
try {
|
||||
const body: unknown = await response.json()
|
||||
return isPlainRecord(body) ? body : {}
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
export function parseOrgDeleteCheck(body: Record<string, unknown>): OrgDeleteCheck {
|
||||
const blockers = normalizeOrgDeleteBlockers(body.blockers)
|
||||
const cancelsSubscription = normalizeOrgDeleteCancelsSubscription(body.cancelsSubscription)
|
||||
// Never call a team deletable while auth lists a blocker this desktop understands.
|
||||
return {
|
||||
deletable: body.deletable === true && blockers.length === 0,
|
||||
blockers,
|
||||
...(cancelsSubscription ? { cancelsSubscription } : {})
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkOrcaCloudOrgDelete(
|
||||
config: OrcaCloudAuthConfig,
|
||||
session: OrcaCloudSession,
|
||||
orgId: string
|
||||
): Promise<OrgDeleteCheck> {
|
||||
const response = await fetch(
|
||||
orgMembersUrl(config, orgId, `/delete-check${SUPPORTS_QUERY}`),
|
||||
requestInit('GET', session.accessToken)
|
||||
)
|
||||
if (!response.ok) {
|
||||
throw new OrcaCloudRequestError(response.status, await extractErrorCode(response))
|
||||
}
|
||||
return parseOrgDeleteCheck(await readJson(response))
|
||||
}
|
||||
|
||||
/** 409 not_deletable comes back as `blocked` with auth's blockers; other failures throw. */
|
||||
export async function deleteOrcaCloudOrg(
|
||||
config: OrcaCloudAuthConfig,
|
||||
session: OrcaCloudSession,
|
||||
args: { orgId: string; confirmName: string }
|
||||
): Promise<OrgDeleteOutcome> {
|
||||
const response = await fetch(
|
||||
orgMembersUrl(config, args.orgId, `/delete${SUPPORTS_QUERY}`),
|
||||
requestInit('POST', session.accessToken, { confirmName: args.confirmName })
|
||||
)
|
||||
if (response.ok) {
|
||||
return { kind: 'deleted' }
|
||||
}
|
||||
const body = await readJson(response)
|
||||
const error = typeof body.error === 'string' ? body.error : undefined
|
||||
// EP-10: the plan already ended (whatever status the rest failed with): say so, never "nothing happened".
|
||||
if (error === 'delete_failed_after_cancel') {
|
||||
return {
|
||||
kind: 'failed-after-cancel',
|
||||
cause: typeof body.cause === 'string' ? body.cause : 'unknown'
|
||||
}
|
||||
}
|
||||
if (response.status === 409 && error === 'not_deletable') {
|
||||
return { kind: 'blocked', blockers: normalizeOrgDeleteBlockers(body.blockers) }
|
||||
}
|
||||
throw new OrcaCloudRequestError(response.status, error)
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
// Team delete for the active profile (TEAM-DELETE): the pre-check and the delete itself. Business
|
||||
// refusals come back as values; only a 401 refreshes the session.
|
||||
import type {
|
||||
OrcaProfileOrgDeleteArgs,
|
||||
OrcaProfileOrgDeleteCheckResult,
|
||||
OrcaProfileOrgDeleteResult
|
||||
} from '../../../shared/orca-org-delete'
|
||||
import { ensureActiveOrcaProfile } from '../profile-index-store'
|
||||
import {
|
||||
getOrcaCloudAuthConfig,
|
||||
isOrcaCloudDevAuthEnabled
|
||||
} from '../cloud-auth/profile-cloud-auth-config'
|
||||
import type { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client'
|
||||
import { removeDevOrganization } from '../cloud-auth/profile-cloud-dev-auth'
|
||||
import { runOrgMemberCall } from './profile-cloud-org-members-service'
|
||||
import { checkOrcaCloudOrgDelete, deleteOrcaCloudOrg } from './profile-cloud-org-delete-client'
|
||||
|
||||
type CommonFailure = Exclude<
|
||||
OrcaProfileOrgDeleteCheckResult,
|
||||
{ status: 'ok' } | { status: 'unconfigured' } | { status: 'reconnect-required' }
|
||||
>
|
||||
|
||||
export function mapOrgDeleteRequestError(error: OrcaCloudRequestError): CommonFailure {
|
||||
switch (error.statusCode) {
|
||||
case 403:
|
||||
return { status: 'forbidden' }
|
||||
case 404:
|
||||
case 405:
|
||||
// An unknown route (no JSON error code) means this auth deployment predates team delete.
|
||||
return error.errorCode
|
||||
? { status: 'failed', error: error.message }
|
||||
: { status: 'unsupported' }
|
||||
case 429:
|
||||
return { status: 'rate-limited' }
|
||||
case 503:
|
||||
return { status: 'unavailable' }
|
||||
default:
|
||||
return { status: 'failed', error: error.message }
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkOrcaProfileOrgDelete(
|
||||
userDataPath: string,
|
||||
orgId: string
|
||||
): Promise<OrcaProfileOrgDeleteCheckResult> {
|
||||
const active = ensureActiveOrcaProfile(userDataPath)
|
||||
if (isOrcaCloudDevAuthEnabled()) {
|
||||
return { status: 'ok', deletable: true, blockers: [] }
|
||||
}
|
||||
const configState = getOrcaCloudAuthConfig()
|
||||
if (!configState.configured) {
|
||||
return { status: 'unconfigured' }
|
||||
}
|
||||
const result = await runOrgMemberCall(configState.config, active, userDataPath, (session) =>
|
||||
checkOrcaCloudOrgDelete(configState.config, session, orgId)
|
||||
)
|
||||
switch (result.status) {
|
||||
case 'ok':
|
||||
return { status: 'ok', ...result.value }
|
||||
case 'reconnect-required':
|
||||
return { status: 'reconnect-required' }
|
||||
case 'request-error':
|
||||
return mapOrgDeleteRequestError(result.error)
|
||||
case 'failed':
|
||||
return { status: 'failed', error: result.error }
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteOrcaProfileOrg(
|
||||
userDataPath: string,
|
||||
args: OrcaProfileOrgDeleteArgs
|
||||
): Promise<OrcaProfileOrgDeleteResult> {
|
||||
const active = ensureActiveOrcaProfile(userDataPath)
|
||||
if (isOrcaCloudDevAuthEnabled()) {
|
||||
removeDevOrganization(args.orgId)
|
||||
return { status: 'deleted' }
|
||||
}
|
||||
const configState = getOrcaCloudAuthConfig()
|
||||
if (!configState.configured) {
|
||||
return { status: 'unconfigured' }
|
||||
}
|
||||
const result = await runOrgMemberCall(configState.config, active, userDataPath, (session) =>
|
||||
deleteOrcaCloudOrg(configState.config, session, args)
|
||||
)
|
||||
switch (result.status) {
|
||||
case 'ok':
|
||||
return result.value.kind === 'deleted'
|
||||
? { status: 'deleted' }
|
||||
: result.value.kind === 'failed-after-cancel'
|
||||
? { status: 'failed-after-cancel', cause: result.value.cause }
|
||||
: { status: 'blocked', blockers: result.value.blockers }
|
||||
case 'reconnect-required':
|
||||
return { status: 'reconnect-required' }
|
||||
case 'request-error':
|
||||
return result.error.statusCode === 400 && result.error.errorCode === 'confirm_mismatch'
|
||||
? { status: 'confirm-mismatch' }
|
||||
: mapOrgDeleteRequestError(result.error)
|
||||
case 'failed':
|
||||
return { status: 'failed', error: result.error }
|
||||
}
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { OrcaCloudAuthConfig } from '../cloud-auth/profile-cloud-auth-config'
|
||||
import { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client'
|
||||
import type { OrcaCloudSession } from '../cloud-session/profile-cloud-session-store'
|
||||
import {
|
||||
changeOrcaCloudOrgSsoDomain,
|
||||
createOrcaCloudOrgSsoSetupLink,
|
||||
getOrcaCloudOrgEnterprise
|
||||
} from './profile-cloud-org-enterprise-client'
|
||||
import { mapOrgEnterpriseRequestError } from './profile-cloud-org-enterprise-service'
|
||||
|
||||
const base = 'https://auth.test'
|
||||
const config: OrcaCloudAuthConfig = {
|
||||
apiBaseUrl: base,
|
||||
authorizeEndpoint: `${base}/a`,
|
||||
sessionEndpoint: `${base}/s`,
|
||||
refreshEndpoint: `${base}/r`,
|
||||
capabilitiesEndpoint: `${base}/c`,
|
||||
profileEndpoint: `${base}/p`,
|
||||
orgEndpoint: `${base}/o`,
|
||||
logoutEndpoint: `${base}/l`,
|
||||
relayTokenEndpoint: `${base}/rt`,
|
||||
connectorTokenEndpoint: `${base}/ct`,
|
||||
relayDirectorUrl: base,
|
||||
clientId: 'orca-desktop',
|
||||
scope: 'openid'
|
||||
}
|
||||
const session: OrcaCloudSession = {
|
||||
accessToken: 'token',
|
||||
refreshToken: 'refresh',
|
||||
expiresAt: 4_102_444_800_000,
|
||||
capabilities: { flags: {}, refreshedAt: 0 }
|
||||
}
|
||||
|
||||
function respond(status: number, body: unknown): void {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => new Response(JSON.stringify(body), { status }))
|
||||
)
|
||||
}
|
||||
|
||||
function call(): { url: unknown; init: RequestInit } {
|
||||
const [url, init] = vi.mocked(fetch).mock.calls[0] ?? []
|
||||
return { url, init: init ?? {} }
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
const RECORD = { type: 'TXT', name: '_orca-verify.acme.com', value: 'orca-verify=abc' }
|
||||
|
||||
describe('Settings › Enterprise client (single sign-on and directory sync)', () => {
|
||||
it('reads the pane state from auth; directory sync is available only when auth says so', async () => {
|
||||
respond(200, {
|
||||
canManage: true,
|
||||
sso: { entitled: true, status: 'live', idp: 'Okta', required: true, domains: [] },
|
||||
scim: { available: true, status: 'waiting', setupUrl: 'https://idp.test/org/settings/1' }
|
||||
})
|
||||
const enterprise = await getOrcaCloudOrgEnterprise(config, session, 'org_1')
|
||||
expect(call().url).toBe(`${base}/v1/desktop/orgs/org_1/enterprise`)
|
||||
expect(enterprise.sso).toMatchObject({ status: 'live', idp: 'Okta', required: true })
|
||||
expect(enterprise.scim).toMatchObject({
|
||||
available: true,
|
||||
status: 'waiting',
|
||||
setupUrl: 'https://idp.test/org/settings/1'
|
||||
})
|
||||
|
||||
respond(200, { canManage: true, sso: { entitled: true, status: 'live' } })
|
||||
expect((await getOrcaCloudOrgEnterprise(config, session, 'org_1')).scim.available).toBe(false)
|
||||
})
|
||||
|
||||
it('mints a setup link, and refuses one that is not https', async () => {
|
||||
respond(200, { url: 'https://idp.test/setup/abc', expiresAt: 123 })
|
||||
await expect(createOrcaCloudOrgSsoSetupLink(config, session, 'org_1')).resolves.toEqual({
|
||||
url: 'https://idp.test/setup/abc',
|
||||
expiresAt: 123
|
||||
})
|
||||
expect(call().url).toBe(`${base}/v1/desktop/orgs/org_1/enterprise/sso/setup-link`)
|
||||
expect(call().init.method).toBe('POST')
|
||||
for (const url of ['http://idp.test/setup', 'javascript:alert(1)', '', undefined]) {
|
||||
respond(200, { url, expiresAt: 123 })
|
||||
await expect(createOrcaCloudOrgSsoSetupLink(config, session, 'org_1')).rejects.toThrow(
|
||||
'invalid_orca_cloud_sso_setup_link'
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it('carries auth’s refusal code for the service to explain', async () => {
|
||||
respond(403, { error: 'recent_sign_in_required' })
|
||||
await expect(createOrcaCloudOrgSsoSetupLink(config, session, 'org_1')).rejects.toMatchObject({
|
||||
statusCode: 403,
|
||||
errorCode: 'recent_sign_in_required'
|
||||
})
|
||||
})
|
||||
|
||||
it('adds, checks and removes a domain on their own routes', async () => {
|
||||
const domain = { domain: 'acme.com', status: 'pending', record: RECORD }
|
||||
respond(200, { domain })
|
||||
await expect(
|
||||
changeOrcaCloudOrgSsoDomain(config, session, {
|
||||
orgId: 'org_1',
|
||||
domain: 'acme.com',
|
||||
action: 'add'
|
||||
})
|
||||
).resolves.toEqual(domain)
|
||||
expect(call().url).toBe(`${base}/v1/desktop/orgs/org_1/enterprise/sso/domains`)
|
||||
expect(call().init.body).toBe(JSON.stringify({ domain: 'acme.com' }))
|
||||
|
||||
respond(200, { domain: { ...domain, status: 'verified' } })
|
||||
await changeOrcaCloudOrgSsoDomain(config, session, {
|
||||
orgId: 'org_1',
|
||||
domain: 'acme.com',
|
||||
action: 'verify'
|
||||
})
|
||||
expect(call().url).toBe(`${base}/v1/desktop/orgs/org_1/enterprise/sso/domains/verify`)
|
||||
|
||||
respond(200, { ok: true })
|
||||
await expect(
|
||||
changeOrcaCloudOrgSsoDomain(config, session, {
|
||||
orgId: 'org_1',
|
||||
domain: 'acme.com',
|
||||
action: 'remove'
|
||||
})
|
||||
).resolves.toBeNull()
|
||||
expect(call().url).toBe(`${base}/v1/desktop/orgs/org_1/enterprise/sso/domains/remove`)
|
||||
})
|
||||
|
||||
it('an auth deployment without the routes reads as unsupported, not as an error', () => {
|
||||
expect(mapOrgEnterpriseRequestError(new OrcaCloudRequestError(404))).toEqual({
|
||||
status: 'unsupported'
|
||||
})
|
||||
expect(
|
||||
mapOrgEnterpriseRequestError(new OrcaCloudRequestError(403, 'insufficient_role'))
|
||||
).toEqual({ status: 'forbidden' })
|
||||
expect(mapOrgEnterpriseRequestError(new OrcaCloudRequestError(429, 'rate_limited'))).toEqual({
|
||||
status: 'rate-limited'
|
||||
})
|
||||
expect(
|
||||
mapOrgEnterpriseRequestError(new OrcaCloudRequestError(502, 'directory_unavailable'))
|
||||
).toEqual({ status: 'unavailable' })
|
||||
})
|
||||
})
|
||||
@@ -1,86 +0,0 @@
|
||||
// Auth's Settings › Enterprise routes for a team (single sign-on and directory sync). Same Bearer
|
||||
// token, timeout and no-redirect rule as the other /v1/desktop/orgs routes.
|
||||
import { isPlainRecord } from '../../../shared/orca-org-delete'
|
||||
import {
|
||||
normalizeOrgEnterprise,
|
||||
normalizeOrgSsoDomain,
|
||||
type OrcaOrgEnterprise,
|
||||
type OrcaOrgSsoDomain
|
||||
} from '../../../shared/orca-org-enterprise'
|
||||
import type { OrcaCloudAuthConfig } from '../cloud-auth/profile-cloud-auth-config'
|
||||
import { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client'
|
||||
import type { OrcaCloudSession } from '../cloud-session/profile-cloud-session-store'
|
||||
import { extractErrorCode, orgMembersUrl, requestInit } from './profile-cloud-org-members-client'
|
||||
|
||||
async function send(url: string, init: RequestInit): Promise<Record<string, unknown>> {
|
||||
const response = await fetch(url, init)
|
||||
if (!response.ok) {
|
||||
throw new OrcaCloudRequestError(response.status, await extractErrorCode(response))
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null)
|
||||
return isPlainRecord(body) ? body : {}
|
||||
}
|
||||
|
||||
export async function getOrcaCloudOrgEnterprise(
|
||||
config: OrcaCloudAuthConfig,
|
||||
session: OrcaCloudSession,
|
||||
orgId: string
|
||||
): Promise<OrcaOrgEnterprise> {
|
||||
return normalizeOrgEnterprise(
|
||||
await send(orgMembersUrl(config, orgId, '/enterprise'), requestInit('GET', session.accessToken))
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The identity provider's self-serve setup page for the team's connection. The link needs no
|
||||
* sign-in there, so it is only ever handed to the owner who asked: never logged, never stored.
|
||||
*/
|
||||
export async function createOrcaCloudOrgSsoSetupLink(
|
||||
config: OrcaCloudAuthConfig,
|
||||
session: OrcaCloudSession,
|
||||
orgId: string
|
||||
): Promise<{ url: string; expiresAt: number }> {
|
||||
const body = await send(
|
||||
orgMembersUrl(config, orgId, '/enterprise/sso/setup-link'),
|
||||
requestInit('POST', session.accessToken, {})
|
||||
)
|
||||
const url = typeof body.url === 'string' ? body.url : ''
|
||||
let https = false
|
||||
try {
|
||||
https = new URL(url).protocol === 'https:'
|
||||
} catch {
|
||||
https = false
|
||||
}
|
||||
if (!https || typeof body.expiresAt !== 'number') {
|
||||
throw new Error('invalid_orca_cloud_sso_setup_link')
|
||||
}
|
||||
return { url, expiresAt: body.expiresAt }
|
||||
}
|
||||
|
||||
export type OrgSsoDomainAction = 'add' | 'verify' | 'remove'
|
||||
|
||||
const DOMAIN_PATHS: Record<OrgSsoDomainAction, string> = {
|
||||
add: '/enterprise/sso/domains',
|
||||
verify: '/enterprise/sso/domains/verify',
|
||||
remove: '/enterprise/sso/domains/remove'
|
||||
}
|
||||
|
||||
/** Adds, checks or removes one of the team's email domains. A removal answers null. */
|
||||
export async function changeOrcaCloudOrgSsoDomain(
|
||||
config: OrcaCloudAuthConfig,
|
||||
session: OrcaCloudSession,
|
||||
args: { orgId: string; domain: string; action: OrgSsoDomainAction }
|
||||
): Promise<OrcaOrgSsoDomain | null> {
|
||||
const body = await send(
|
||||
orgMembersUrl(config, args.orgId, DOMAIN_PATHS[args.action]),
|
||||
requestInit('POST', session.accessToken, { domain: args.domain })
|
||||
)
|
||||
if (args.action === 'remove') {
|
||||
return null
|
||||
}
|
||||
const domain = normalizeOrgSsoDomain(body.domain)
|
||||
if (!domain) {
|
||||
throw new Error('invalid_orca_cloud_sso_domain')
|
||||
}
|
||||
return domain
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
// Settings › Enterprise for the active profile's team: the pane's state, the single sign-on setup
|
||||
// link, and the team's verified email domains. Business refusals come back as values; only a 401
|
||||
// refreshes the session.
|
||||
import type {
|
||||
OrcaOrgSsoDomainRefusal,
|
||||
OrcaProfileOrgEnterpriseResult,
|
||||
OrcaProfileOrgSsoDomainResult,
|
||||
OrcaProfileOrgSsoSetupLinkResult
|
||||
} from '../../../shared/orca-org-enterprise'
|
||||
import {
|
||||
getOrcaCloudAuthConfig,
|
||||
isOrcaCloudDevAuthEnabled
|
||||
} from '../cloud-auth/profile-cloud-auth-config'
|
||||
import type { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client'
|
||||
import { ensureActiveOrcaProfile } from '../profile-index-store'
|
||||
import {
|
||||
changeOrcaCloudOrgSsoDomain,
|
||||
createOrcaCloudOrgSsoSetupLink,
|
||||
getOrcaCloudOrgEnterprise,
|
||||
type OrgSsoDomainAction
|
||||
} from './profile-cloud-org-enterprise-client'
|
||||
import { runOrgMemberCall } from './profile-cloud-org-members-service'
|
||||
|
||||
type CommonFailure = Exclude<
|
||||
OrcaProfileOrgEnterpriseResult,
|
||||
{ status: 'ok' } | { status: 'unconfigured' } | { status: 'reconnect-required' }
|
||||
>
|
||||
|
||||
export function mapOrgEnterpriseRequestError(error: OrcaCloudRequestError): CommonFailure {
|
||||
switch (error.statusCode) {
|
||||
case 403:
|
||||
return { status: 'forbidden' }
|
||||
case 404:
|
||||
case 405:
|
||||
// An unknown route (no JSON error code) means this auth deployment predates Enterprise.
|
||||
return error.errorCode
|
||||
? { status: 'failed', error: error.message }
|
||||
: { status: 'unsupported' }
|
||||
case 429:
|
||||
return { status: 'rate-limited' }
|
||||
case 502:
|
||||
case 503:
|
||||
return { status: 'unavailable' }
|
||||
default:
|
||||
return { status: 'failed', error: error.message }
|
||||
}
|
||||
}
|
||||
|
||||
const DOMAIN_REFUSALS: Record<string, OrcaOrgSsoDomainRefusal> = {
|
||||
invalid_domain: 'invalid-domain',
|
||||
invalid_request: 'invalid-domain',
|
||||
public_domain: 'public-domain',
|
||||
too_many_domains: 'too-many-domains',
|
||||
domain_not_found: 'domain-not-found',
|
||||
domain_taken: 'domain-taken',
|
||||
record_not_found: 'record-not-found',
|
||||
dns_unavailable: 'dns-unavailable'
|
||||
}
|
||||
|
||||
export async function getOrcaProfileOrgEnterprise(
|
||||
userDataPath: string,
|
||||
orgId: string
|
||||
): Promise<OrcaProfileOrgEnterpriseResult> {
|
||||
const active = ensureActiveOrcaProfile(userDataPath)
|
||||
// The in-app fake account has no auth service behind it: nothing to show.
|
||||
if (isOrcaCloudDevAuthEnabled()) {
|
||||
return { status: 'unsupported' }
|
||||
}
|
||||
const configState = getOrcaCloudAuthConfig()
|
||||
if (!configState.configured) {
|
||||
return { status: 'unconfigured' }
|
||||
}
|
||||
const result = await runOrgMemberCall(configState.config, active, userDataPath, (session) =>
|
||||
getOrcaCloudOrgEnterprise(configState.config, session, orgId)
|
||||
)
|
||||
switch (result.status) {
|
||||
case 'ok':
|
||||
return { status: 'ok', enterprise: result.value }
|
||||
case 'reconnect-required':
|
||||
return { status: 'reconnect-required' }
|
||||
case 'request-error':
|
||||
return mapOrgEnterpriseRequestError(result.error)
|
||||
case 'failed':
|
||||
return { status: 'failed', error: result.error }
|
||||
}
|
||||
}
|
||||
|
||||
export async function createOrcaProfileOrgSsoSetupLink(
|
||||
userDataPath: string,
|
||||
orgId: string
|
||||
): Promise<OrcaProfileOrgSsoSetupLinkResult> {
|
||||
const active = ensureActiveOrcaProfile(userDataPath)
|
||||
if (isOrcaCloudDevAuthEnabled()) {
|
||||
return { status: 'unsupported' }
|
||||
}
|
||||
const configState = getOrcaCloudAuthConfig()
|
||||
if (!configState.configured) {
|
||||
return { status: 'unconfigured' }
|
||||
}
|
||||
const result = await runOrgMemberCall(configState.config, active, userDataPath, (session) =>
|
||||
createOrcaCloudOrgSsoSetupLink(configState.config, session, orgId)
|
||||
)
|
||||
switch (result.status) {
|
||||
case 'ok':
|
||||
return { status: 'ok', ...result.value }
|
||||
case 'reconnect-required':
|
||||
return { status: 'reconnect-required' }
|
||||
case 'request-error':
|
||||
if (result.error.statusCode === 403 && result.error.errorCode === 'recent_sign_in_required') {
|
||||
return { status: 'recent-sign-in-required' }
|
||||
}
|
||||
if (result.error.statusCode === 403 && result.error.errorCode === 'not_entitled') {
|
||||
return { status: 'not-entitled' }
|
||||
}
|
||||
return mapOrgEnterpriseRequestError(result.error)
|
||||
case 'failed':
|
||||
return { status: 'failed', error: result.error }
|
||||
}
|
||||
}
|
||||
|
||||
export async function changeOrcaProfileOrgSsoDomain(
|
||||
userDataPath: string,
|
||||
args: { orgId: string; domain: string; action: OrgSsoDomainAction }
|
||||
): Promise<OrcaProfileOrgSsoDomainResult> {
|
||||
const active = ensureActiveOrcaProfile(userDataPath)
|
||||
if (isOrcaCloudDevAuthEnabled()) {
|
||||
return { status: 'unsupported' }
|
||||
}
|
||||
const configState = getOrcaCloudAuthConfig()
|
||||
if (!configState.configured) {
|
||||
return { status: 'unconfigured' }
|
||||
}
|
||||
const result = await runOrgMemberCall(configState.config, active, userDataPath, (session) =>
|
||||
changeOrcaCloudOrgSsoDomain(configState.config, session, args)
|
||||
)
|
||||
switch (result.status) {
|
||||
case 'ok':
|
||||
return { status: 'ok', domain: result.value }
|
||||
case 'reconnect-required':
|
||||
return { status: 'reconnect-required' }
|
||||
case 'request-error': {
|
||||
const refusal = result.error.errorCode ? DOMAIN_REFUSALS[result.error.errorCode] : undefined
|
||||
if (refusal) {
|
||||
return { status: 'refused', reason: refusal }
|
||||
}
|
||||
if (result.error.statusCode === 403 && result.error.errorCode === 'not_entitled') {
|
||||
return { status: 'not-entitled' }
|
||||
}
|
||||
return mapOrgEnterpriseRequestError(result.error)
|
||||
}
|
||||
case 'failed':
|
||||
return { status: 'failed', error: result.error }
|
||||
}
|
||||
}
|
||||
@@ -194,84 +194,3 @@ export async function listOrcaCloudOrgMembers(
|
||||
normalizeRoster
|
||||
)
|
||||
}
|
||||
|
||||
export async function inviteOrcaCloudOrgMember(
|
||||
config: OrcaCloudAuthConfig,
|
||||
session: OrcaCloudSession,
|
||||
args: { orgId: string; email: string; role: OrcaOrgRole }
|
||||
): Promise<void> {
|
||||
await requestOrgMembers(
|
||||
orgMembersUrl(config, args.orgId, '/invites'),
|
||||
requestInit('POST', session.accessToken, { email: args.email, role: args.role }),
|
||||
() => undefined
|
||||
)
|
||||
}
|
||||
|
||||
export async function revokeOrcaCloudOrgInvite(
|
||||
config: OrcaCloudAuthConfig,
|
||||
session: OrcaCloudSession,
|
||||
args: { orgId: string; email: string }
|
||||
): Promise<void> {
|
||||
await requestOrgMembers(
|
||||
orgMembersUrl(config, args.orgId, '/invites/revoke'),
|
||||
requestInit('POST', session.accessToken, { email: args.email }),
|
||||
() => undefined
|
||||
)
|
||||
}
|
||||
|
||||
export async function changeOrcaCloudOrgMemberRole(
|
||||
config: OrcaCloudAuthConfig,
|
||||
session: OrcaCloudSession,
|
||||
args: { orgId: string; userId: string; role: OrcaOrgRole }
|
||||
): Promise<void> {
|
||||
await requestOrgMembers(
|
||||
orgMembersUrl(config, args.orgId, '/members/role'),
|
||||
requestInit('POST', session.accessToken, { userId: args.userId, role: args.role }),
|
||||
() => undefined
|
||||
)
|
||||
}
|
||||
|
||||
export async function removeOrcaCloudOrgMember(
|
||||
config: OrcaCloudAuthConfig,
|
||||
session: OrcaCloudSession,
|
||||
args: { orgId: string; userId: string }
|
||||
): Promise<void> {
|
||||
await requestOrgMembers(
|
||||
orgMembersUrl(config, args.orgId, '/members/remove'),
|
||||
requestInit('POST', session.accessToken, { userId: args.userId }),
|
||||
() => undefined
|
||||
)
|
||||
}
|
||||
|
||||
/** Leaves the org as the signed-in user. Auth refuses the last owner (`last_owner`). */
|
||||
export async function leaveOrcaCloudOrg(
|
||||
config: OrcaCloudAuthConfig,
|
||||
session: OrcaCloudSession,
|
||||
orgId: string
|
||||
): Promise<void> {
|
||||
await requestOrgMembers(
|
||||
orgMembersUrl(config, orgId, '/members/leave'),
|
||||
requestInit('POST', session.accessToken, {}),
|
||||
() => undefined
|
||||
)
|
||||
}
|
||||
|
||||
/** Creates an org owned by the signed-in user. */
|
||||
export async function createOrcaCloudOrg(
|
||||
config: OrcaCloudAuthConfig,
|
||||
session: OrcaCloudSession,
|
||||
name: string
|
||||
): Promise<{ orgId: string; name: string }> {
|
||||
return requestOrgMembers(
|
||||
`${config.apiBaseUrl}/v1/desktop/orgs`,
|
||||
requestInit('POST', session.accessToken, { name }),
|
||||
(value) => {
|
||||
const record = value && typeof value === 'object' ? (value as Record<string, unknown>) : {}
|
||||
const orgId = typeof record.orgId === 'string' ? record.orgId.trim() : ''
|
||||
if (!orgId) {
|
||||
throw new Error('invalid_org_create_response')
|
||||
}
|
||||
return { orgId, name: typeof record.name === 'string' ? record.name : name }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,16 +1,4 @@
|
||||
import type {
|
||||
OrcaProfileOrgCreateArgs,
|
||||
OrcaProfileOrgCreateResult,
|
||||
OrcaProfileOrgLeaveArgs
|
||||
} from '../../../shared/orca-org-management'
|
||||
import type {
|
||||
OrcaProfileOrgInviteRevokeArgs,
|
||||
OrcaProfileOrgMemberChangeRoleArgs,
|
||||
OrcaProfileOrgMemberInviteArgs,
|
||||
OrcaProfileOrgMemberMutationResult,
|
||||
OrcaProfileOrgMemberRemoveArgs,
|
||||
OrcaProfileOrgMembersListResult
|
||||
} from '../../../shared/orca-profiles'
|
||||
import type { OrcaProfileOrgMembersListResult } from '../../../shared/orca-profiles'
|
||||
import type { ActiveOrcaProfileState } from '../profile-index-store'
|
||||
import { ensureActiveOrcaProfile } from '../profile-index-store'
|
||||
import type { OrcaCloudAuthConfig } from '../cloud-auth/profile-cloud-auth-config'
|
||||
@@ -21,25 +9,8 @@ import {
|
||||
import type { OrcaCloudSession } from '../cloud-session/profile-cloud-session-store'
|
||||
import { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client'
|
||||
import { runWithFreshOrcaCloudSession } from '../cloud-session/profile-cloud-session-refresh'
|
||||
import { bumpOrcaCloudTokenEpoch } from '../cloud-token-epoch'
|
||||
import {
|
||||
changeOrcaCloudOrgMemberRole,
|
||||
createOrcaCloudOrg,
|
||||
inviteOrcaCloudOrgMember,
|
||||
leaveOrcaCloudOrg,
|
||||
listOrcaCloudOrgMembers,
|
||||
removeOrcaCloudOrgMember,
|
||||
revokeOrcaCloudOrgInvite
|
||||
} from './profile-cloud-org-members-client'
|
||||
import {
|
||||
changeDevOrcaCloudOrgMemberRole,
|
||||
createDevOrcaCloudOrg,
|
||||
inviteDevOrcaCloudOrgMember,
|
||||
leaveDevOrcaCloudOrg,
|
||||
listDevOrcaCloudOrgMembers,
|
||||
removeDevOrcaCloudOrgMember,
|
||||
revokeDevOrcaCloudOrgInvite
|
||||
} from './profile-cloud-dev-org-members'
|
||||
import { listOrcaCloudOrgMembers } from './profile-cloud-org-members-client'
|
||||
import { listDevOrcaCloudOrgMembers } from './profile-cloud-dev-org-members'
|
||||
|
||||
export type OrgCallResult<T> =
|
||||
| { status: 'ok'; value: T }
|
||||
@@ -82,48 +53,6 @@ export async function runOrgMemberCall<T>(
|
||||
}
|
||||
}
|
||||
|
||||
function mapMutationRequestError(error: OrcaCloudRequestError): OrcaProfileOrgMemberMutationResult {
|
||||
switch (error.statusCode) {
|
||||
case 403:
|
||||
return { status: 'forbidden' }
|
||||
case 404:
|
||||
// An unknown route (no JSON error code) means this auth deployment predates the action.
|
||||
return error.errorCode ? { status: 'not-found' } : { status: 'unsupported' }
|
||||
case 429:
|
||||
return { status: 'rate-limited' }
|
||||
case 409:
|
||||
return {
|
||||
status: 'conflict',
|
||||
reason: error.errorCode === 'already_member' ? 'already_member' : 'already_invited'
|
||||
}
|
||||
case 400:
|
||||
return {
|
||||
status: 'invalid',
|
||||
reason:
|
||||
error.errorCode === 'cannot_remove_self'
|
||||
? 'cannot_remove_self'
|
||||
: error.errorCode === 'last_owner'
|
||||
? 'last_owner'
|
||||
: 'cannot_change_own_role'
|
||||
}
|
||||
default:
|
||||
return { status: 'failed', error: error.message }
|
||||
}
|
||||
}
|
||||
|
||||
function mapMutationResult(result: OrgCallResult<void>): OrcaProfileOrgMemberMutationResult {
|
||||
switch (result.status) {
|
||||
case 'ok':
|
||||
return { status: 'ok' }
|
||||
case 'reconnect-required':
|
||||
return { status: 'reconnect-required' }
|
||||
case 'request-error':
|
||||
return mapMutationRequestError(result.error)
|
||||
case 'failed':
|
||||
return { status: 'failed', error: result.error }
|
||||
}
|
||||
}
|
||||
|
||||
export async function listOrcaProfileOrgMembers(
|
||||
userDataPath: string,
|
||||
orgId: string
|
||||
@@ -150,158 +79,3 @@ export async function listOrcaProfileOrgMembers(
|
||||
return { status: 'failed', error: result.error }
|
||||
}
|
||||
}
|
||||
|
||||
export async function inviteOrcaProfileOrgMember(
|
||||
userDataPath: string,
|
||||
args: OrcaProfileOrgMemberInviteArgs
|
||||
): Promise<OrcaProfileOrgMemberMutationResult> {
|
||||
const active = ensureActiveOrcaProfile(userDataPath)
|
||||
if (isOrcaCloudDevAuthEnabled()) {
|
||||
return inviteDevOrcaCloudOrgMember(args)
|
||||
}
|
||||
const configState = getOrcaCloudAuthConfig()
|
||||
if (!configState.configured) {
|
||||
return { status: 'unconfigured' }
|
||||
}
|
||||
return mapMutationResult(
|
||||
await runOrgMemberCall(configState.config, active, userDataPath, (session) =>
|
||||
inviteOrcaCloudOrgMember(configState.config, session, args)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
export async function revokeOrcaProfileOrgInvite(
|
||||
userDataPath: string,
|
||||
args: OrcaProfileOrgInviteRevokeArgs
|
||||
): Promise<OrcaProfileOrgMemberMutationResult> {
|
||||
const active = ensureActiveOrcaProfile(userDataPath)
|
||||
if (isOrcaCloudDevAuthEnabled()) {
|
||||
return revokeDevOrcaCloudOrgInvite(args)
|
||||
}
|
||||
const configState = getOrcaCloudAuthConfig()
|
||||
if (!configState.configured) {
|
||||
return { status: 'unconfigured' }
|
||||
}
|
||||
return mapMutationResult(
|
||||
await runOrgMemberCall(configState.config, active, userDataPath, (session) =>
|
||||
revokeOrcaCloudOrgInvite(configState.config, session, args)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
export async function changeOrcaProfileOrgMemberRole(
|
||||
userDataPath: string,
|
||||
args: OrcaProfileOrgMemberChangeRoleArgs
|
||||
): Promise<OrcaProfileOrgMemberMutationResult> {
|
||||
const active = ensureActiveOrcaProfile(userDataPath)
|
||||
if (isOrcaCloudDevAuthEnabled()) {
|
||||
return changeDevOrcaCloudOrgMemberRole(args)
|
||||
}
|
||||
const configState = getOrcaCloudAuthConfig()
|
||||
if (!configState.configured) {
|
||||
return { status: 'unconfigured' }
|
||||
}
|
||||
const result = mapMutationResult(
|
||||
await runOrgMemberCall(configState.config, active, userDataPath, (session) =>
|
||||
changeOrcaCloudOrgMemberRole(configState.config, session, args)
|
||||
)
|
||||
)
|
||||
// Why: the member may be this user; a cached sandbox token would keep the old role.
|
||||
bumpOrcaCloudTokenEpoch()
|
||||
return result
|
||||
}
|
||||
|
||||
export async function removeOrcaProfileOrgMember(
|
||||
userDataPath: string,
|
||||
args: OrcaProfileOrgMemberRemoveArgs
|
||||
): Promise<OrcaProfileOrgMemberMutationResult> {
|
||||
const active = ensureActiveOrcaProfile(userDataPath)
|
||||
if (isOrcaCloudDevAuthEnabled()) {
|
||||
return removeDevOrcaCloudOrgMember(args)
|
||||
}
|
||||
const configState = getOrcaCloudAuthConfig()
|
||||
if (!configState.configured) {
|
||||
return { status: 'unconfigured' }
|
||||
}
|
||||
const result = mapMutationResult(
|
||||
await runOrgMemberCall(configState.config, active, userDataPath, (session) =>
|
||||
removeOrcaCloudOrgMember(configState.config, session, args)
|
||||
)
|
||||
)
|
||||
// Why: the member may be this user; a cached sandbox token would keep the old role.
|
||||
bumpOrcaCloudTokenEpoch()
|
||||
return result
|
||||
}
|
||||
|
||||
/** Revoke then re-send so the provider emails a fresh link; the role is kept. */
|
||||
export async function resendOrcaProfileOrgInvite(
|
||||
userDataPath: string,
|
||||
args: OrcaProfileOrgMemberInviteArgs
|
||||
): Promise<OrcaProfileOrgMemberMutationResult> {
|
||||
const revoked = await revokeOrcaProfileOrgInvite(userDataPath, {
|
||||
orgId: args.orgId,
|
||||
email: args.email
|
||||
})
|
||||
// A missing invite (accepted or revoked elsewhere) still gets a fresh one.
|
||||
if (revoked.status !== 'ok' && revoked.status !== 'not-found') {
|
||||
return revoked
|
||||
}
|
||||
return inviteOrcaProfileOrgMember(userDataPath, args)
|
||||
}
|
||||
|
||||
export async function leaveOrcaProfileOrg(
|
||||
userDataPath: string,
|
||||
args: OrcaProfileOrgLeaveArgs
|
||||
): Promise<OrcaProfileOrgMemberMutationResult> {
|
||||
const active = ensureActiveOrcaProfile(userDataPath)
|
||||
if (isOrcaCloudDevAuthEnabled()) {
|
||||
return leaveDevOrcaCloudOrg(args.orgId)
|
||||
}
|
||||
const configState = getOrcaCloudAuthConfig()
|
||||
if (!configState.configured) {
|
||||
return { status: 'unconfigured' }
|
||||
}
|
||||
return mapMutationResult(
|
||||
await runOrgMemberCall(configState.config, active, userDataPath, (session) =>
|
||||
leaveOrcaCloudOrg(configState.config, session, args.orgId)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
export async function createOrcaProfileOrg(
|
||||
userDataPath: string,
|
||||
args: OrcaProfileOrgCreateArgs
|
||||
): Promise<OrcaProfileOrgCreateResult> {
|
||||
const active = ensureActiveOrcaProfile(userDataPath)
|
||||
if (isOrcaCloudDevAuthEnabled()) {
|
||||
return createDevOrcaCloudOrg(args.name)
|
||||
}
|
||||
const configState = getOrcaCloudAuthConfig()
|
||||
if (!configState.configured) {
|
||||
return { status: 'unconfigured' }
|
||||
}
|
||||
const result = await runOrgMemberCall(configState.config, active, userDataPath, (session) =>
|
||||
createOrcaCloudOrg(configState.config, session, args.name)
|
||||
)
|
||||
switch (result.status) {
|
||||
case 'ok':
|
||||
return { status: 'created', orgId: result.value.orgId, name: result.value.name }
|
||||
case 'reconnect-required':
|
||||
return { status: 'reconnect-required' }
|
||||
case 'request-error':
|
||||
if (result.error.statusCode === 404 || result.error.statusCode === 405) {
|
||||
return { status: 'unsupported' }
|
||||
}
|
||||
if (result.error.statusCode === 429) {
|
||||
return { status: 'rate-limited' }
|
||||
}
|
||||
if (result.error.statusCode === 409) {
|
||||
return { status: 'name-taken' }
|
||||
}
|
||||
return result.error.statusCode === 400
|
||||
? { status: 'invalid' }
|
||||
: { status: 'failed', error: result.error.message }
|
||||
case 'failed':
|
||||
return { status: 'failed', error: result.error }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,9 +10,6 @@ import type {
|
||||
CloudApiProject,
|
||||
CloudApiResult,
|
||||
CloudApiSettings,
|
||||
CloudAuditLogExport,
|
||||
CloudAuditLogPage,
|
||||
CloudAuditLogQuery,
|
||||
CreateCloudApiApprovalInput,
|
||||
CreateCloudApiKeyInput,
|
||||
Routine,
|
||||
@@ -25,7 +22,7 @@ import type {
|
||||
RoutineUpdated
|
||||
} from '../../shared/cloud-api/cloud-api-types'
|
||||
|
||||
/** Desktop only: Orca Cloud API keys, org settings, the team audit log and routines. The session token stays in main. */
|
||||
/** Desktop only: Orca Cloud API keys, org settings and routines. The session token stays in main. */
|
||||
export type CloudApiBridge = {
|
||||
availability: () => Promise<CloudApiAvailability>
|
||||
/** The desktop workspace running on this Orca Cloud sandbox, if this computer has it. */
|
||||
@@ -39,11 +36,6 @@ export type CloudApiBridge = {
|
||||
revokeGrant: (id: string) => Promise<CloudApiResult<unknown>>
|
||||
getSettings: () => Promise<CloudApiResult<CloudApiSettings>>
|
||||
putSettings: (input: { vmCliEnabled: boolean }) => Promise<CloudApiResult<CloudApiSettings>>
|
||||
/** The team audit log: owners and admins of a team whose plan includes it (else `plan-required`). */
|
||||
listAuditLog: (query?: CloudAuditLogQuery) => Promise<CloudApiResult<CloudAuditLogPage>>
|
||||
exportAuditLogCsv: (
|
||||
query?: Pick<CloudAuditLogQuery, 'category' | 'actor'>
|
||||
) => Promise<CloudApiResult<CloudAuditLogExport>>
|
||||
listProjects: () => Promise<CloudApiResult<{ projects: CloudApiProject[] }>>
|
||||
listInstallations: () => Promise<CloudApiResult<{ installations: CloudApiInstallation[] }>>
|
||||
listRoutines: () => Promise<CloudApiResult<{ routines: Routine[] }>>
|
||||
@@ -72,8 +64,6 @@ export const cloudApiBridge: CloudApiBridge = {
|
||||
revokeGrant: invoke('cloudApi:revokeGrant'),
|
||||
getSettings: invoke('cloudApi:getSettings'),
|
||||
putSettings: invoke('cloudApi:putSettings'),
|
||||
listAuditLog: invoke('cloudApi:listAuditLog'),
|
||||
exportAuditLogCsv: invoke('cloudApi:exportAuditLogCsv'),
|
||||
listProjects: invoke('cloudApi:listProjects'),
|
||||
listInstallations: invoke('cloudApi:listInstallations'),
|
||||
listRoutines: invoke('cloudApi:listRoutines'),
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import type {
|
||||
OrcaTeamMfaPendingResult,
|
||||
OrcaTeamMfaPolicyArgs,
|
||||
OrcaTeamMfaPolicyResult,
|
||||
OrcaTeamMfaPolicySetArgs,
|
||||
OrcaTeamMfaPolicySetResult,
|
||||
OrcaTeamMfaRemindArgs,
|
||||
OrcaTeamMfaRemindResult
|
||||
OrcaTeamMfaPolicyResult
|
||||
} from '../../shared/orca-team-mfa-policy'
|
||||
import type {
|
||||
OrcaCloudConsoleOpenArgs,
|
||||
OrcaCloudConsoleOpenResult
|
||||
} from '../../shared/orca-cloud-console'
|
||||
import type { OrcaAccountMfaResult } from '../../shared/orca-account-mfa'
|
||||
import type {
|
||||
CloudSetupGetResult,
|
||||
@@ -14,24 +13,6 @@ import type {
|
||||
CloudSetupStartArgs,
|
||||
CloudSetupStartResult
|
||||
} from '../../shared/orca-cloud-setup'
|
||||
import type {
|
||||
OrcaProfileOrgDeleteArgs,
|
||||
OrcaProfileOrgDeleteCheckArgs,
|
||||
OrcaProfileOrgDeleteCheckResult,
|
||||
OrcaProfileOrgDeleteResult
|
||||
} from '../../shared/orca-org-delete'
|
||||
import type {
|
||||
OrcaProfileOrgEnterpriseArgs,
|
||||
OrcaProfileOrgEnterpriseDomainArgs,
|
||||
OrcaProfileOrgEnterpriseResult,
|
||||
OrcaProfileOrgSsoDomainResult,
|
||||
OrcaProfileOrgSsoSetupLinkResult
|
||||
} from '../../shared/orca-org-enterprise'
|
||||
import type {
|
||||
OrcaProfileOrgCreateArgs,
|
||||
OrcaProfileOrgCreateResult,
|
||||
OrcaProfileOrgLeaveArgs
|
||||
} from '../../shared/orca-org-management'
|
||||
import type {
|
||||
OrcaCloudSignInEnd,
|
||||
OrcaCloudSignInProgress,
|
||||
@@ -44,11 +25,6 @@ import type {
|
||||
FindOrcaProfileProjectsByPathResult,
|
||||
OrcaProfileAuthStatus,
|
||||
OrcaProfileListResult,
|
||||
OrcaProfileOrgInviteRevokeArgs,
|
||||
OrcaProfileOrgMemberChangeRoleArgs,
|
||||
OrcaProfileOrgMemberInviteArgs,
|
||||
OrcaProfileOrgMemberMutationResult,
|
||||
OrcaProfileOrgMemberRemoveArgs,
|
||||
OrcaProfileOrgMembersListArgs,
|
||||
OrcaProfileOrgMembersListResult,
|
||||
RefreshCurrentOrcaProfileAuthResult,
|
||||
@@ -61,15 +37,13 @@ import type {
|
||||
TransferOrcaProfileProjectResult
|
||||
} from '../../shared/orca-profiles'
|
||||
import type {
|
||||
OrcaBillingCheckoutArgs,
|
||||
OrcaBillingOpenResult,
|
||||
OrcaBillingOverageArgs,
|
||||
OrcaBillingOverageResult,
|
||||
OrcaBillingTrialClaimResult,
|
||||
OrcaBillingReturn,
|
||||
OrcaBillingStatusResult,
|
||||
OrcaBillingTeamPlansResult,
|
||||
OrcaBillingUsageHistoryResult
|
||||
OrcaBillingTeamPlansResult
|
||||
} from '../../shared/orca-billing'
|
||||
import type { OrcaCloudSetupReturn } from '../../shared/orca-cloud-setup-link'
|
||||
import type { OrcaPlanCatalogResult } from '../../shared/orca-billing-plans'
|
||||
@@ -105,49 +79,12 @@ export type OrcaProfileApi = {
|
||||
accountMfa: () => Promise<OrcaAccountMfaResult>
|
||||
/** The team's "require MFA" policy and the person's own state in it. */
|
||||
teamMfaPolicy: (args: OrcaTeamMfaPolicyArgs) => Promise<OrcaTeamMfaPolicyResult>
|
||||
teamMfaPolicySet: (args: OrcaTeamMfaPolicySetArgs) => Promise<OrcaTeamMfaPolicySetResult>
|
||||
teamMfaPending: (args: OrcaTeamMfaPolicyArgs) => Promise<OrcaTeamMfaPendingResult>
|
||||
teamMfaRemind: (args: OrcaTeamMfaRemindArgs) => Promise<OrcaTeamMfaRemindResult>
|
||||
orgMembersList: (args: OrcaProfileOrgMembersListArgs) => Promise<OrcaProfileOrgMembersListResult>
|
||||
orgMemberInvite: (
|
||||
args: OrcaProfileOrgMemberInviteArgs
|
||||
) => Promise<OrcaProfileOrgMemberMutationResult>
|
||||
orgInviteRevoke: (
|
||||
args: OrcaProfileOrgInviteRevokeArgs
|
||||
) => Promise<OrcaProfileOrgMemberMutationResult>
|
||||
orgMemberChangeRole: (
|
||||
args: OrcaProfileOrgMemberChangeRoleArgs
|
||||
) => Promise<OrcaProfileOrgMemberMutationResult>
|
||||
orgMemberRemove: (
|
||||
args: OrcaProfileOrgMemberRemoveArgs
|
||||
) => Promise<OrcaProfileOrgMemberMutationResult>
|
||||
/** Revokes and re-sends a pending invite with the same role. */
|
||||
orgInviteResend: (
|
||||
args: OrcaProfileOrgMemberInviteArgs
|
||||
) => Promise<OrcaProfileOrgMemberMutationResult>
|
||||
/** Leaves the org as the signed-in user; the last owner is refused. */
|
||||
orgLeave: (args: OrcaProfileOrgLeaveArgs) => Promise<OrcaProfileOrgMemberMutationResult>
|
||||
/** Creates a team owned by the signed-in user. */
|
||||
orgCreate: (args: OrcaProfileOrgCreateArgs) => Promise<OrcaProfileOrgCreateResult>
|
||||
/** Whether an owner can delete the team now, and what blocks it (TEAM-DELETE). */
|
||||
orgDeleteCheck: (args: OrcaProfileOrgDeleteCheckArgs) => Promise<OrcaProfileOrgDeleteCheckResult>
|
||||
/** Deletes the team for everyone; `confirmName` is the name exactly as typed. */
|
||||
orgDelete: (args: OrcaProfileOrgDeleteArgs) => Promise<OrcaProfileOrgDeleteResult>
|
||||
/** Settings › Enterprise for the team: single sign-on and directory sync, as auth reports them. */
|
||||
orgEnterprise: (args: OrcaProfileOrgEnterpriseArgs) => Promise<OrcaProfileOrgEnterpriseResult>
|
||||
/** A fresh single sign-on setup link (owners, just after signing in). Never stored. */
|
||||
orgSsoSetupLink: (args: OrcaProfileOrgEnterpriseArgs) => Promise<OrcaProfileOrgSsoSetupLinkResult>
|
||||
/** Starts verifying an email domain: answers the DNS record to publish. */
|
||||
orgSsoDomainAdd: (
|
||||
args: OrcaProfileOrgEnterpriseDomainArgs
|
||||
) => Promise<OrcaProfileOrgSsoDomainResult>
|
||||
/** Checks the domain's DNS record. */
|
||||
orgSsoDomainVerify: (
|
||||
args: OrcaProfileOrgEnterpriseDomainArgs
|
||||
) => Promise<OrcaProfileOrgSsoDomainResult>
|
||||
orgSsoDomainRemove: (
|
||||
args: OrcaProfileOrgEnterpriseDomainArgs
|
||||
) => Promise<OrcaProfileOrgSsoDomainResult>
|
||||
/**
|
||||
* Opens a web console page (team, billing, Enterprise) in the system browser, signed in with a
|
||||
* single-use code when auth gives one.
|
||||
*/
|
||||
openCloudConsole: (args: OrcaCloudConsoleOpenArgs) => Promise<OrcaCloudConsoleOpenResult>
|
||||
/** Fires when the browser comes back from Stripe Checkout or the Portal (orca:// link). */
|
||||
onBillingReturn: (callback: (event: OrcaBillingReturn) => void) => () => void
|
||||
/** Main asks for a billing re-read (cloud workspace created/woken, or the usage poll). */
|
||||
@@ -158,8 +95,6 @@ export type OrcaProfileApi = {
|
||||
billingStatus: () => Promise<OrcaBillingStatusResult>
|
||||
/** Billing's public plan catalog: prices (Stripe's), features, seat bounds. */
|
||||
billingPlans: () => Promise<OrcaPlanCatalogResult>
|
||||
/** Opens hosted Stripe Checkout in the browser. */
|
||||
billingOpenCheckout: (args: OrcaBillingCheckoutArgs) => Promise<OrcaBillingOpenResult>
|
||||
/** Starts Orca Cloud setup: one browser tab for sign-in, team, plan and GitHub. */
|
||||
cloudSetupStart: (args: CloudSetupStartArgs) => Promise<CloudSetupStartResult>
|
||||
/** The setup session's steps, for the composer's setup panel. */
|
||||
@@ -168,10 +103,6 @@ export type OrcaProfileApi = {
|
||||
cloudSetupLink: (args: { sessionId: string }) => Promise<CloudSetupLinkResult>
|
||||
/** Opens the Stripe Customer Portal in the browser. */
|
||||
billingOpenPortal: () => Promise<OrcaBillingOpenResult>
|
||||
/** The last 30 days of sandbox hours (breakdowns for owners and admins only). */
|
||||
billingUsageHistory: (args: {
|
||||
utcOffsetMinutes: number
|
||||
}) => Promise<OrcaBillingUsageHistoryResult>
|
||||
/** Plan state for other teams the user is on ("Switch to <team>"); never switches teams. */
|
||||
billingTeamPlans: (args: { orgIds: string[] }) => Promise<OrcaBillingTeamPlansResult>
|
||||
/** Opt in/out of sandbox overage and set the monthly spend cap (org admins). */
|
||||
|
||||
@@ -75,24 +75,8 @@ export const orcaProfilesApi = {
|
||||
selectOrg: (args) => ipcRenderer.invoke('orcaProfiles:selectOrg', args),
|
||||
accountMfa: () => ipcRenderer.invoke('orcaProfiles:accountMfa'),
|
||||
teamMfaPolicy: (args) => ipcRenderer.invoke('orcaProfiles:teamMfaPolicy', args),
|
||||
teamMfaPolicySet: (args) => ipcRenderer.invoke('orcaProfiles:teamMfaPolicySet', args),
|
||||
teamMfaPending: (args) => ipcRenderer.invoke('orcaProfiles:teamMfaPending', args),
|
||||
teamMfaRemind: (args) => ipcRenderer.invoke('orcaProfiles:teamMfaRemind', args),
|
||||
orgMembersList: (args) => ipcRenderer.invoke('orcaProfiles:orgMembersList', args),
|
||||
orgMemberInvite: (args) => ipcRenderer.invoke('orcaProfiles:orgMemberInvite', args),
|
||||
orgInviteRevoke: (args) => ipcRenderer.invoke('orcaProfiles:orgInviteRevoke', args),
|
||||
orgMemberChangeRole: (args) => ipcRenderer.invoke('orcaProfiles:orgMemberChangeRole', args),
|
||||
orgMemberRemove: (args) => ipcRenderer.invoke('orcaProfiles:orgMemberRemove', args),
|
||||
orgInviteResend: (args) => ipcRenderer.invoke('orcaProfiles:orgInviteResend', args),
|
||||
orgLeave: (args) => ipcRenderer.invoke('orcaProfiles:orgLeave', args),
|
||||
orgCreate: (args) => ipcRenderer.invoke('orcaProfiles:orgCreate', args),
|
||||
orgDeleteCheck: (args) => ipcRenderer.invoke('orcaProfiles:orgDeleteCheck', args),
|
||||
orgDelete: (args) => ipcRenderer.invoke('orcaProfiles:orgDelete', args),
|
||||
orgEnterprise: (args) => ipcRenderer.invoke('orcaProfiles:orgEnterprise', args),
|
||||
orgSsoSetupLink: (args) => ipcRenderer.invoke('orcaProfiles:orgSsoSetupLink', args),
|
||||
orgSsoDomainAdd: (args) => ipcRenderer.invoke('orcaProfiles:orgSsoDomainAdd', args),
|
||||
orgSsoDomainVerify: (args) => ipcRenderer.invoke('orcaProfiles:orgSsoDomainVerify', args),
|
||||
orgSsoDomainRemove: (args) => ipcRenderer.invoke('orcaProfiles:orgSsoDomainRemove', args),
|
||||
openCloudConsole: (args) => ipcRenderer.invoke('orcaProfiles:openCloudConsole', args),
|
||||
onBillingReturn: (callback: (event: OrcaBillingReturn) => void): (() => void) => {
|
||||
const listener = (_event: unknown, payload: OrcaBillingReturn): void => callback(payload)
|
||||
ipcRenderer.on(ORCA_BILLING_RETURN_CHANNEL, listener)
|
||||
@@ -110,10 +94,8 @@ export const orcaProfilesApi = {
|
||||
},
|
||||
billingStatus: () => ipcRenderer.invoke('orcaProfiles:billingStatus'),
|
||||
billingPlans: () => ipcRenderer.invoke('orcaProfiles:billingPlans'),
|
||||
billingOpenCheckout: (args) => ipcRenderer.invoke('orcaProfiles:billingOpenCheckout', args),
|
||||
billingOpenPortal: () => ipcRenderer.invoke('orcaProfiles:billingOpenPortal'),
|
||||
billingTeamPlans: (args) => ipcRenderer.invoke('orcaProfiles:billingTeamPlans', args),
|
||||
billingUsageHistory: (args) => ipcRenderer.invoke('orcaProfiles:billingUsageHistory', args),
|
||||
cloudSetupStart: (args) => ipcRenderer.invoke('orcaProfiles:cloudSetupStart', args),
|
||||
cloudSetupGet: (args) => ipcRenderer.invoke('orcaProfiles:cloudSetupGet', args),
|
||||
cloudSetupLink: (args) => ipcRenderer.invoke('orcaProfiles:cloudSetupLink', args),
|
||||
|
||||
@@ -5,7 +5,6 @@ import { TooltipProvider } from '@/components/ui/tooltip'
|
||||
import { ConfirmationDialogProvider } from './components/confirmation-dialog'
|
||||
import { BrowserWebAuthnAccountDialog } from './components/browser-webauthn-account-dialog'
|
||||
import { BrowserExtensionInstallDialog } from './components/browser-extension-install-dialog'
|
||||
import { PlansDialogHost } from './components/billing/plans/PlansDialogHost'
|
||||
import { CloudMoveToComputerDialogMount } from './components/orca-cloud/CloudMoveToComputerDialogMount'
|
||||
import { CloudPrimaryDeleteDialogMount } from './components/orca-cloud/CloudPrimaryDeleteDialog'
|
||||
import { CloudSecretsAskDialogHost } from './components/cloud-secrets-ask/CloudSecretsMissingNotice'
|
||||
@@ -13,7 +12,6 @@ import { OrcaCloudSignInSheet } from './components/settings/agent-accounts/sign-
|
||||
import { AgentHostPanel } from './components/agent-host-panel/AgentHostPanel'
|
||||
import { SecretRequestUnseenNotifier } from './components/agent-pane/SecretRequestUnseenNotifier'
|
||||
import { LocalCommandApprovalDialogHost } from './components/local-commands/LocalCommandApprovalDialog'
|
||||
import { TeamDialogHost } from './components/billing/team/TeamDialogHost'
|
||||
import { TeammateProfileDialog } from './components/teammates/TeammateProfileDialog'
|
||||
import { CloudWorkspacePickerDialog } from './components/cloud-workspaces/CloudWorkspacePicker'
|
||||
import { PokesNotifier } from './components/teammates/PokesNotifier'
|
||||
@@ -129,7 +127,6 @@ function App(): React.JSX.Element {
|
||||
/>
|
||||
<BrowserWebAuthnAccountDialog />
|
||||
<BrowserExtensionInstallDialog />
|
||||
<PlansDialogHost />
|
||||
<CloudMoveToComputerDialogMount />
|
||||
<CloudPrimaryDeleteDialogMount />
|
||||
<CloudSecretsAskDialogHost />
|
||||
@@ -137,7 +134,6 @@ function App(): React.JSX.Element {
|
||||
<OrcaCloudSignInSheet />
|
||||
<SecretRequestUnseenNotifier />
|
||||
<LocalCommandApprovalDialogHost />
|
||||
<TeamDialogHost />
|
||||
<TeammateProfileDialog />
|
||||
<CloudWorkspacePickerDialog />
|
||||
<PokesNotifier />
|
||||
|
||||
@@ -11,7 +11,7 @@ import { useTranslate } from '@/i18n/use-translate'
|
||||
import { cn } from '@/lib/class-names'
|
||||
import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing'
|
||||
import { accountMenuTrialRow } from './plan-billing-usage-copy'
|
||||
import { openPlansPage } from './plans/plans-page-store'
|
||||
import { openCloudConsole } from '@/lib/orca-cloud/open-cloud-console'
|
||||
|
||||
export function AccountMenuTrialRow({
|
||||
result
|
||||
@@ -35,7 +35,7 @@ export function AccountMenuTrialRow({
|
||||
{row.canChoosePlan ? (
|
||||
<DropdownMenuItem
|
||||
data-account-menu-trial=""
|
||||
onSelect={() => openPlansPage('account-menu')}
|
||||
onSelect={() => void openCloudConsole('billing')}
|
||||
aria-label={t('auto.components.billing.trialRowChoosePlan', '{{trial}}. Choose plan', {
|
||||
trial: row.label
|
||||
})}
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
// OVERAGE-REENABLE: the overage card through on → off → on, and each save state it can show.
|
||||
import { useState } from 'react'
|
||||
import { defineFixture } from '../../component-fixtures/component-fixture'
|
||||
import type {
|
||||
OrcaBillingEntitlement,
|
||||
OrcaBillingOverageArgs
|
||||
} from '../../../../shared/orca-billing'
|
||||
import { PlanBillingView, type PlanBillingNotice } from './PlanBillingSection'
|
||||
import { sampleTeam } from './plan-billing-fixtures'
|
||||
|
||||
type Outcome = 'ok' | 'failed' | 'pending'
|
||||
|
||||
const overageOn: OrcaBillingEntitlement = {
|
||||
...sampleTeam,
|
||||
overage: { ...sampleTeam.overage, optedIn: true, active: true, spendCapCents: 4000 }
|
||||
}
|
||||
|
||||
/** Plays PlanBillingSection with a fake billing: busy while out, then a re-read or a failure. */
|
||||
function OverageCard({
|
||||
initial,
|
||||
outcome
|
||||
}: {
|
||||
initial: OrcaBillingEntitlement
|
||||
outcome: Outcome
|
||||
}): React.JSX.Element {
|
||||
const [entitlement, setEntitlement] = useState(initial)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [failures, setFailures] = useState(0)
|
||||
const [notice, setNotice] = useState<PlanBillingNotice | null>(null)
|
||||
const setOverage = (args: OrcaBillingOverageArgs): void => {
|
||||
setBusy(true)
|
||||
setNotice(null)
|
||||
if (outcome === 'pending') {
|
||||
return
|
||||
}
|
||||
setTimeout(() => {
|
||||
setBusy(false)
|
||||
if (outcome === 'failed') {
|
||||
setNotice({ kind: 'error', text: 'Couldn’t reach billing. Try again.' })
|
||||
setFailures((count) => count + 1)
|
||||
return
|
||||
}
|
||||
setEntitlement((current) => ({
|
||||
...current,
|
||||
overage: {
|
||||
...current.overage,
|
||||
optedIn: args.enabled,
|
||||
active: args.enabled,
|
||||
spendCapCents: args.spendCapCents ?? current.overage.spendCapCents
|
||||
}
|
||||
}))
|
||||
}, 20)
|
||||
}
|
||||
return (
|
||||
<PlanBillingView
|
||||
loading={false}
|
||||
busy={busy}
|
||||
notice={notice}
|
||||
teamName="Orca Staging Eval Team"
|
||||
result={{ status: 'ok', entitlement }}
|
||||
overageFailures={failures}
|
||||
onRefresh={() => {}}
|
||||
onPortal={() => {}}
|
||||
onSetOverage={setOverage}
|
||||
onSeePlans={() => {}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function clickButton(frame: HTMLElement, label: RegExp): void {
|
||||
const button = [...frame.querySelectorAll<HTMLButtonElement>('button')].find((candidate) =>
|
||||
label.test(candidate.textContent ?? '')
|
||||
)
|
||||
button?.click()
|
||||
}
|
||||
|
||||
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 150))
|
||||
|
||||
/** Turned on, then off: the off line, a working "Turn on with a $25 cap" and "Saved". */
|
||||
export const overageOffAfterOn = defineFixture({
|
||||
width: 680,
|
||||
render: () => <OverageCard initial={overageOn} outcome="ok" />,
|
||||
interact: async (frame) => {
|
||||
clickButton(frame, /^Turn off overage$/)
|
||||
await settle()
|
||||
}
|
||||
})
|
||||
|
||||
/** In flight: a spinner with "Saving…" (no check), Turn on still there but inert. */
|
||||
export const overageSaving = defineFixture({
|
||||
width: 680,
|
||||
render: () => <OverageCard initial={sampleTeam} outcome="pending" />,
|
||||
interact: async (frame) => {
|
||||
clickButton(frame, /^Turn on with a/)
|
||||
await settle()
|
||||
}
|
||||
})
|
||||
|
||||
/** Turned on again from off: the $25 cap field, focused, with "✓ Saved". */
|
||||
export const overageSavedOnAgain = defineFixture({
|
||||
width: 680,
|
||||
render: () => <OverageCard initial={sampleTeam} outcome="ok" />,
|
||||
interact: async (frame) => {
|
||||
clickButton(frame, /^Turn on with a/)
|
||||
await settle()
|
||||
}
|
||||
})
|
||||
|
||||
/** Turn off failed: overage stays on at its cap, "Couldn’t save", and billing's reason below. */
|
||||
export const overageSaveError = defineFixture({
|
||||
width: 680,
|
||||
render: () => <OverageCard initial={overageOn} outcome="failed" />,
|
||||
interact: async (frame) => {
|
||||
clickButton(frame, /^Turn off overage$/)
|
||||
await settle()
|
||||
}
|
||||
})
|
||||
@@ -1,197 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
// OVERAGE-REENABLE: after Turn off the card showed "✓ Saving…" forever and no way to turn on again.
|
||||
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { useState } from 'react'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import type {
|
||||
OrcaBillingEntitlement,
|
||||
OrcaBillingOverageArgs
|
||||
} from '../../../../shared/orca-billing'
|
||||
import { OverageControls } from './PlanBillingUsage'
|
||||
import { sampleTeam } from './plan-billing-fixtures'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
type Pending = { args: OrcaBillingOverageArgs; settle: (ok: boolean) => void }
|
||||
|
||||
/** Plays PlanBillingSection: busy while the request is out, then a re-read or a failure bump. */
|
||||
function renderCard(initial: OrcaBillingEntitlement = sampleTeam): { pending: Pending[] } {
|
||||
const pending: Pending[] = []
|
||||
function Card(): React.JSX.Element {
|
||||
const [entitlement, setEntitlement] = useState(initial)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [failures, setFailures] = useState(0)
|
||||
return (
|
||||
<OverageControls
|
||||
entitlement={entitlement}
|
||||
busy={busy}
|
||||
failures={failures}
|
||||
onSetOverage={(args) => {
|
||||
setBusy(true)
|
||||
pending.push({
|
||||
args,
|
||||
settle: (ok) => {
|
||||
setBusy(false)
|
||||
if (!ok) {
|
||||
setFailures((count) => count + 1)
|
||||
return
|
||||
}
|
||||
// Billing keeps the cap through an opt-out; an omitted cap keeps the current one.
|
||||
setEntitlement((current) => ({
|
||||
...current,
|
||||
overage: {
|
||||
...current.overage,
|
||||
optedIn: args.enabled,
|
||||
active: args.enabled,
|
||||
spendCapCents: args.spendCapCents ?? current.overage.spendCapCents
|
||||
}
|
||||
}))
|
||||
}
|
||||
})
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
render(<Card />)
|
||||
return { pending }
|
||||
}
|
||||
|
||||
const settleLast = (pending: Pending[], ok: boolean): void => {
|
||||
act(() => pending.at(-1)!.settle(ok))
|
||||
}
|
||||
const turnOnButton = (): HTMLElement =>
|
||||
screen.getByRole('button', { name: 'Turn on with a $25 cap' })
|
||||
const statusText = (): string | null => screen.queryByRole('status')?.textContent ?? null
|
||||
|
||||
describe('overage on, off and on again', () => {
|
||||
it('turns on, off and on again with the same control, ending each change in Saved', () => {
|
||||
const { pending } = renderCard()
|
||||
fireEvent.click(turnOnButton())
|
||||
expect(pending.at(-1)!.args).toEqual({ enabled: true, spendCapCents: 2500 })
|
||||
expect(statusText()).toBe('Saving…')
|
||||
settleLast(pending, true)
|
||||
expect(screen.getByLabelText<HTMLInputElement>('Monthly spend cap').value).toBe('25')
|
||||
expect(statusText()).toBe('Saved')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Turn off overage' }))
|
||||
expect(pending.at(-1)!.args).toEqual({ enabled: false })
|
||||
expect(statusText()).toBe('Saving…')
|
||||
settleLast(pending, true)
|
||||
expect(screen.getByText(/^Overage is off\./)).toBeTruthy()
|
||||
// The bug: the off view kept a stale flag and showed "✓ Saving…" in place of Turn on.
|
||||
expect(statusText()).toBe('Saved')
|
||||
expect(turnOnButton().getAttribute('aria-disabled')).toBeNull()
|
||||
expect(document.activeElement).toBe(turnOnButton())
|
||||
|
||||
fireEvent.click(turnOnButton())
|
||||
expect(pending).toHaveLength(3)
|
||||
expect(pending.at(-1)!.args).toEqual({ enabled: true, spendCapCents: 2500 })
|
||||
settleLast(pending, true)
|
||||
expect(screen.getByLabelText('Monthly spend cap')).toBeTruthy()
|
||||
expect(document.activeElement).toBe(screen.getByLabelText('Monthly spend cap'))
|
||||
expect(statusText()).toBe('Saved')
|
||||
})
|
||||
|
||||
it('keeps Turn on visible but inert while saving, so one click sends one change', () => {
|
||||
const { pending } = renderCard()
|
||||
fireEvent.click(turnOnButton())
|
||||
expect(turnOnButton().getAttribute('aria-disabled')).toBe('true')
|
||||
fireEvent.click(turnOnButton())
|
||||
expect(pending).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('a cap change goes Saving… then Saved, and editing again clears it', () => {
|
||||
const { pending } = renderCard({
|
||||
...sampleTeam,
|
||||
overage: { ...sampleTeam.overage, optedIn: true, active: true, spendCapCents: 4000 }
|
||||
})
|
||||
const field = screen.getByLabelText<HTMLInputElement>('Monthly spend cap')
|
||||
fireEvent.change(field, { target: { value: '60' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
|
||||
expect(statusText()).toBe('Saving…')
|
||||
expect(screen.queryByRole('button', { name: 'Save' })).toBeNull()
|
||||
settleLast(pending, true)
|
||||
expect(statusText()).toBe('Saved')
|
||||
expect(field.value).toBe('60')
|
||||
fireEvent.change(field, { target: { value: '70' } })
|
||||
expect(statusText()).toBeNull()
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('overage save state', () => {
|
||||
// design-squad: the failure sits by the control that failed, not by the cap field.
|
||||
it('a failed Turn off says so by its link and leaves overage on and changeable', () => {
|
||||
const { pending } = renderCard({
|
||||
...sampleTeam,
|
||||
overage: { ...sampleTeam.overage, optedIn: true, active: true, spendCapCents: 4000 }
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Turn off overage' }))
|
||||
settleLast(pending, false)
|
||||
expect(statusText()).toBe('Couldn’t turn off overage.')
|
||||
const off = screen.getByRole('button', { name: 'Turn off overage' })
|
||||
expect(off.closest('div')?.contains(screen.getByRole('status'))).toBe(true)
|
||||
const field = screen.getByLabelText<HTMLInputElement>('Monthly spend cap')
|
||||
expect(field.value).toBe('40')
|
||||
expect(field.closest('form')?.contains(screen.getByRole('status'))).toBe(false)
|
||||
expect(off.getAttribute('aria-disabled')).toBeNull()
|
||||
fireEvent.click(off)
|
||||
expect(pending).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('a failed Turn on says so next to a working Turn on', () => {
|
||||
const { pending } = renderCard()
|
||||
fireEvent.click(turnOnButton())
|
||||
settleLast(pending, false)
|
||||
expect(statusText()).toBe('Couldn’t turn on overage.')
|
||||
expect(screen.queryByLabelText('Monthly spend cap')).toBeNull()
|
||||
fireEvent.click(turnOnButton())
|
||||
expect(pending).toHaveLength(2)
|
||||
settleLast(pending, true)
|
||||
expect(statusText()).toBe('Saved')
|
||||
})
|
||||
|
||||
it('a failed cap change says Couldn’t save by the field and rolls the value back', () => {
|
||||
const { pending } = renderCard({
|
||||
...sampleTeam,
|
||||
overage: { ...sampleTeam.overage, optedIn: true, active: true, spendCapCents: 4000 }
|
||||
})
|
||||
const field = screen.getByLabelText<HTMLInputElement>('Monthly spend cap')
|
||||
fireEvent.change(field, { target: { value: '60' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
|
||||
settleLast(pending, false)
|
||||
expect(statusText()).toBe('Couldn’t save')
|
||||
expect(field.closest('form')?.contains(screen.getByRole('status'))).toBe(true)
|
||||
expect(field.value).toBe('40')
|
||||
})
|
||||
|
||||
it('never shows the check with Saving…', () => {
|
||||
const { pending } = renderCard()
|
||||
fireEvent.click(turnOnButton())
|
||||
const saving = screen.getByRole('status')
|
||||
expect(saving.textContent).toBe('Saving…')
|
||||
expect(saving.querySelector('.lucide-check')).toBeNull()
|
||||
settleLast(pending, true)
|
||||
expect(screen.getByRole('status').querySelector('.lucide-check')).toBeTruthy()
|
||||
})
|
||||
|
||||
// A host that never reports busy still resolves once the card reads the new state.
|
||||
it('resolves Saving… from the re-read when busy never changes', () => {
|
||||
const view = render(
|
||||
<OverageControls entitlement={sampleTeam} busy={false} onSetOverage={() => {}} />
|
||||
)
|
||||
fireEvent.click(turnOnButton())
|
||||
expect(statusText()).toBe('Saving…')
|
||||
view.rerender(
|
||||
<OverageControls
|
||||
entitlement={{
|
||||
...sampleTeam,
|
||||
overage: { ...sampleTeam.overage, optedIn: true, active: true, spendCapCents: 2500 }
|
||||
}}
|
||||
busy={false}
|
||||
onSetOverage={() => {}}
|
||||
/>
|
||||
)
|
||||
expect(statusText()).toBe('Saved')
|
||||
})
|
||||
})
|
||||
@@ -1,426 +0,0 @@
|
||||
import { defineFixture } from '../../component-fixtures/component-fixture'
|
||||
import { PlanBillingView } from './PlanBillingSection'
|
||||
import {
|
||||
sampleTeam,
|
||||
sampleTrial,
|
||||
sampleTrialUsedUp,
|
||||
sampleUsageHistory,
|
||||
sampleUsageNames
|
||||
} from './plan-billing-fixtures'
|
||||
|
||||
const HOUR = 3600
|
||||
|
||||
const handlers = {
|
||||
loading: false,
|
||||
busy: false,
|
||||
notice: null,
|
||||
onRefresh: () => {},
|
||||
onPortal: () => {},
|
||||
onSetOverage: () => {},
|
||||
onSeePlans: () => {}
|
||||
}
|
||||
|
||||
const usage = { status: 'ok', history: sampleUsageHistory, names: sampleUsageNames } as const
|
||||
|
||||
// JA-18: "<Team> · Team plan", the last 30 days with top workspaces and members, one cap field.
|
||||
export const activeTeam = defineFixture({
|
||||
width: 680,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
teamName="Orca Staging Eval Team"
|
||||
usage={usage}
|
||||
result={{ status: 'ok', entitlement: sampleTeam }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
// Billing sent no catalog (an older service or a failed read): "Turn on overage" with no amount,
|
||||
// alert copy without levels. Billing applies its own default cap.
|
||||
export const overageOffNoOffers = defineFixture({
|
||||
width: 680,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
teamName="Orca Staging Eval Team"
|
||||
usage={usage}
|
||||
result={{ status: 'ok', entitlement: { ...sampleTeam, offers: null } }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
// Today's dev billing (before #507): offers carry every number but no alert levels.
|
||||
export const olderServiceNoAlertLevels = defineFixture({
|
||||
width: 680,
|
||||
render: () => {
|
||||
const { warnAtPercent: _levels, ...team } = sampleTeam.offers!.team
|
||||
return (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
teamName="Orca Staging Eval Team"
|
||||
usage={usage}
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
overage: { ...sampleTeam.overage, optedIn: true, active: true, spendCapCents: 4000 },
|
||||
offers: { ...sampleTeam.offers!, team }
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
export const noPlan = defineFixture({
|
||||
width: 680,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
plan: null,
|
||||
planLabel: null,
|
||||
status: 'none',
|
||||
interval: null,
|
||||
seats: 0,
|
||||
period: null,
|
||||
usageWindow: null,
|
||||
includedSeconds: 0,
|
||||
usedSeconds: 0,
|
||||
remainingIncludedSeconds: 0,
|
||||
canStartSandbox: false,
|
||||
reason: 'no_subscription'
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const overageCapReached = defineFixture({
|
||||
width: 600,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
interval: 'year',
|
||||
seats: 5,
|
||||
includedSeconds: 300 * HOUR,
|
||||
usedSeconds: 333 * HOUR,
|
||||
remainingIncludedSeconds: 0,
|
||||
usageWarningPercent: 100,
|
||||
overageSeconds: 33 * HOUR,
|
||||
overage: {
|
||||
optedIn: true,
|
||||
active: true,
|
||||
spendCapCents: 2500,
|
||||
spentCents: 2500,
|
||||
centsPerHour: 100
|
||||
},
|
||||
canStartSandbox: false,
|
||||
reason: 'overage_cap_reached'
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
// Overage is off by default: out of included hours, running sandboxes go to sleep.
|
||||
export const hoursUsedOverageOff = defineFixture({
|
||||
width: 600,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
usedSeconds: sampleTeam.includedSeconds,
|
||||
remainingIncludedSeconds: 0,
|
||||
usageWarningPercent: 100,
|
||||
canStartSandbox: false,
|
||||
reason: 'included_hours_exhausted'
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const pastDueMember = defineFixture({
|
||||
width: 600,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
status: 'past_due',
|
||||
usedSeconds: 100 * HOUR,
|
||||
remainingIncludedSeconds: 20 * HOUR,
|
||||
usageWarningPercent: 80,
|
||||
payment: {
|
||||
pastDueSince: Date.UTC(2026, 10, 8, 9),
|
||||
graceEndsAt: Date.UTC(2026, 10, 12, 9),
|
||||
suspendRunning: false
|
||||
},
|
||||
canStartSandbox: false,
|
||||
reason: 'payment_past_due',
|
||||
canManageBilling: false
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const suspendedAdmin = defineFixture({
|
||||
width: 600,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
status: 'past_due',
|
||||
payment: {
|
||||
pastDueSince: Date.UTC(2026, 10, 3, 9),
|
||||
graceEndsAt: Date.UTC(2026, 10, 7, 9),
|
||||
suspendRunning: true
|
||||
},
|
||||
canStartSandbox: false,
|
||||
reason: 'payment_grace_expired'
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
/** First open of Settings › Orca Cloud › Plan & billing: the section holds its shape while billing answers. */
|
||||
export const loading = defineFixture({
|
||||
width: 600,
|
||||
render: () => <PlanBillingView {...handlers} loading result={null} />
|
||||
})
|
||||
|
||||
/** Billing's 75% level: the early warning under the bar (still the neutral tone below 90%). */
|
||||
export const usageWarning75 = defineFixture({
|
||||
width: 600,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
usedSeconds: 92 * HOUR,
|
||||
remainingIncludedSeconds: 28 * HOUR,
|
||||
usageWarningPercent: 75
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
/** Billing's 90% level: the bar turns to the warning tone; one hour left reads singular. */
|
||||
export const usageWarning90 = defineFixture({
|
||||
width: 600,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
usedSeconds: 119 * HOUR,
|
||||
remainingIncludedSeconds: 1 * HOUR,
|
||||
usageWarningPercent: 90,
|
||||
overage: { ...sampleTeam.overage, optedIn: true, active: false }
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
/** 100% with overage off: the alert says sandboxes sleep and points at overage (no repeat below). */
|
||||
export const usageAlert100OverageOff = defineFixture({
|
||||
width: 600,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
usedSeconds: 120 * HOUR,
|
||||
remainingIncludedSeconds: 0,
|
||||
usageWarningPercent: 100,
|
||||
canStartSandbox: false,
|
||||
reason: 'included_hours_exhausted'
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
/** 100% with overage on: the alert names the spend cap the team keeps going up to. */
|
||||
export const usageAlert100OverageOn = defineFixture({
|
||||
width: 600,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
usedSeconds: 123 * HOUR,
|
||||
remainingIncludedSeconds: 0,
|
||||
overageSeconds: 3 * HOUR,
|
||||
usageWarningPercent: 100,
|
||||
overage: { ...sampleTeam.overage, optedIn: true, active: true, spentCents: 300 }
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
/** A member at billing's 90% level: no admin usage notice (members aren't alerted). */
|
||||
export const usageWarningMember = defineFixture({
|
||||
width: 600,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
usedSeconds: 109 * HOUR,
|
||||
remainingIncludedSeconds: 11 * HOUR,
|
||||
usageWarningPercent: 90,
|
||||
canManageBilling: false
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
/** A member while overage is on: one line saying the cap, and what's been used. */
|
||||
export const overageOnMember = defineFixture({
|
||||
width: 600,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
canManageBilling: false,
|
||||
overage: { ...sampleTeam.overage, optedIn: true, active: true, spentCents: 300 }
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
/** Keyboard: "Turn off overage" reads as a link at rest and shows its focus ring. */
|
||||
export const overageTurnOffFocused = defineFixture({
|
||||
...usageAlert100OverageOn,
|
||||
interact: async (frame) => {
|
||||
const turnOff = [...frame.querySelectorAll<HTMLButtonElement>('button')].find(
|
||||
(button) => button.textContent === 'Turn off overage'
|
||||
)
|
||||
turnOff?.focus()
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
}
|
||||
})
|
||||
|
||||
/** An admin types a cap above billing's maximum: the field says what the maximum is. */
|
||||
export const capTooHigh = defineFixture({
|
||||
width: 600,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
overage: { ...sampleTeam.overage, optedIn: true, active: true, spentCents: 400 }
|
||||
}
|
||||
}}
|
||||
/>
|
||||
),
|
||||
interact: async (frame) => {
|
||||
const input = frame.querySelector<HTMLInputElement>('input[inputmode="numeric"]')
|
||||
if (!input) {
|
||||
return
|
||||
}
|
||||
input.focus()
|
||||
// React listens for native input events.
|
||||
const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set
|
||||
setValue?.call(input, '6000')
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
}
|
||||
})
|
||||
|
||||
/** Spec T1: the team's one-time trial, owner view (Choose plan). */
|
||||
export const trial = defineFixture({
|
||||
width: 600,
|
||||
render: () => (
|
||||
<PlanBillingView {...handlers} result={{ status: 'ok', entitlement: sampleTrial }} />
|
||||
)
|
||||
})
|
||||
|
||||
export const trialMember = defineFixture({
|
||||
width: 600,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
result={{ status: 'ok', entitlement: { ...sampleTrial, canManageBilling: false } }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const trialUsedUp = defineFixture({
|
||||
width: 600,
|
||||
render: () => (
|
||||
<PlanBillingView {...handlers} result={{ status: 'ok', entitlement: sampleTrialUsedUp }} />
|
||||
)
|
||||
})
|
||||
|
||||
export const trialUsedUpMember = defineFixture({
|
||||
width: 600,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
result={{ status: 'ok', entitlement: { ...sampleTrialUsedUp, canManageBilling: false } }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
/** No plan and no trial on offer (this account or team already used one). */
|
||||
export const trialUnavailable = defineFixture({
|
||||
width: 600,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTrial,
|
||||
status: 'none',
|
||||
trial: null,
|
||||
includedSeconds: 0,
|
||||
usedSeconds: 0,
|
||||
remainingIncludedSeconds: 0,
|
||||
canStartSandbox: false,
|
||||
reason: 'trial_unavailable'
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
@@ -1,365 +0,0 @@
|
||||
import { useState } from 'react'
|
||||
import { ExternalLink } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { InlineError } from '@/components/ui/inline-error'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
|
||||
import { formatCents } from './plans/plans-pricing'
|
||||
import {
|
||||
isOrcaCloudTrial,
|
||||
type OrcaBillingOpenResult,
|
||||
type OrcaBillingOverageArgs,
|
||||
type OrcaBillingOverageResult,
|
||||
type OrcaBillingStatusResult
|
||||
} from '../../../../shared/orca-billing'
|
||||
import { openPlansPage } from './plans/plans-page-store'
|
||||
import { PaymentIssueNotice } from './PaymentIssueNotice'
|
||||
import { OverageControls, UsageSummary } from './PlanBillingUsage'
|
||||
import { denyReasonCopy, openFailureCopy, overageFailureCopy } from './plan-billing-copy'
|
||||
import { PlanStatusBadge } from './PlanStatusBadge'
|
||||
import { TrialPlanSummary } from './TrialPlanSummary'
|
||||
import { useOrcaBillingStatus } from './use-orca-billing-status'
|
||||
import { useAppStore } from '@/store/index'
|
||||
import { usageAlertLevel } from '../../../../shared/orca-billing-usage-alerts'
|
||||
import { BILLING_CAPABILITY } from './register-plan-billing-menu-item'
|
||||
import { SettingsGroupHeader } from '@/components/settings/section-layout/SettingsGroup'
|
||||
import { PlanBillingUsageHistory } from './PlanBillingUsageHistory'
|
||||
import {
|
||||
usePlanBillingUsageHistory,
|
||||
type PlanBillingUsageState
|
||||
} from './use-plan-billing-usage-history'
|
||||
|
||||
export function PlanBillingSection(): React.JSX.Element | null {
|
||||
const t = useTranslate()
|
||||
const locale = useIntlLocale()
|
||||
const { loading, result, refresh } = useOrcaBillingStatus(true)
|
||||
// Only billing-flagged accounts get a skeleton; others hear "unconfigured" and show nothing.
|
||||
const billingFlagged = useAppStore(
|
||||
(state) => state.orcaProfileAuthStatus?.capabilities?.flags[BILLING_CAPABILITY] === true
|
||||
)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [notice, setNotice] = useState<PlanBillingNotice | null>(null)
|
||||
const [overageFailures, setOverageFailures] = useState(0)
|
||||
const cloud = useAppStore((state) => state.orcaProfileAuthStatus?.cloud)
|
||||
const entitlement = result?.status === 'ok' ? result.entitlement : null
|
||||
const hasPlan =
|
||||
entitlement !== null && entitlement.plan !== null && entitlement.status !== 'canceled'
|
||||
// Re-read the history with every billing read (it re-reads on window focus). The first read
|
||||
// starts with the page, not after the plan read answers, so the chart isn't a second behind it.
|
||||
// Main reads for the active profile; without the account summary yet, key it as that profile so
|
||||
// the chart still loads instead of waiting on a key that never comes.
|
||||
const accountKey = cloud ? `${cloud.userId}:${cloud.activeOrgId ?? ''}` : 'active-profile'
|
||||
const usage = usePlanBillingUsageHistory(
|
||||
hasPlan || result === null ? `${accountKey}|${entitlement?.usedSeconds ?? ''}` : null,
|
||||
cloud?.activeOrgId ?? null,
|
||||
cloud?.userId ?? null,
|
||||
entitlement?.canManageBilling === true
|
||||
)
|
||||
|
||||
const run = async (open: () => Promise<OrcaBillingOpenResult>): Promise<void> => {
|
||||
setBusy(true)
|
||||
setNotice(null)
|
||||
const outcome = await open().catch((error: unknown): OrcaBillingOpenResult => ({
|
||||
status: 'failed',
|
||||
error: String(error)
|
||||
}))
|
||||
setBusy(false)
|
||||
const failure = openFailureCopy(outcome, t)
|
||||
setNotice(
|
||||
failure
|
||||
? { kind: 'error', text: failure }
|
||||
: {
|
||||
kind: 'info',
|
||||
text: t(
|
||||
'auto.components.billing.continueInBrowser',
|
||||
'Continue in your browser. This updates when you come back.'
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
const setOverage = async (args: OrcaBillingOverageArgs): Promise<void> => {
|
||||
setBusy(true)
|
||||
setNotice(null)
|
||||
const outcome = await window.api.orcaProfiles
|
||||
.billingSetOverage(args)
|
||||
.catch((error: unknown): OrcaBillingOverageResult => ({
|
||||
status: 'failed',
|
||||
error: String(error)
|
||||
}))
|
||||
setBusy(false)
|
||||
if (outcome.status === 'ok') {
|
||||
// One shared store: this re-read also updates the Run-on picker's Orca Cloud row.
|
||||
refresh()
|
||||
} else {
|
||||
const maxCap =
|
||||
result?.status === 'ok' ? (result.entitlement.offers?.team.maxSpendCapCents ?? null) : null
|
||||
const failure = overageFailureCopy(outcome, t, maxCap, locale)
|
||||
setNotice(failure ? { kind: 'error', text: failure } : null)
|
||||
setOverageFailures((count) => count + 1)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<PlanBillingView
|
||||
result={result}
|
||||
loading={loading && (result !== null || billingFlagged)}
|
||||
busy={busy}
|
||||
notice={notice}
|
||||
teamName={cloud?.activeOrgName ?? null}
|
||||
usage={usage.state}
|
||||
onRetryUsage={usage.retry}
|
||||
onRefresh={refresh}
|
||||
onPortal={() => void run(() => window.api.orcaProfiles.billingOpenPortal())}
|
||||
overageFailures={overageFailures}
|
||||
onSetOverage={(args) => void setOverage(args)}
|
||||
onSeePlans={() => openPlansPage('settings')}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const noop = (): void => {}
|
||||
|
||||
export type PlanBillingNotice = { kind: 'error' | 'info'; text: string }
|
||||
|
||||
export type PlanBillingViewProps = {
|
||||
result: OrcaBillingStatusResult | null
|
||||
loading: boolean
|
||||
busy: boolean
|
||||
notice: PlanBillingNotice | null
|
||||
/** The active team's name, for the "<Team> · Team plan" title. */
|
||||
teamName?: string | null
|
||||
/** The last 30 days; absent (fixtures without history) renders nothing. */
|
||||
usage?: PlanBillingUsageState
|
||||
onRetryUsage?: () => void
|
||||
/** Re-reads the plan after a failed load (the page otherwise re-reads on window focus). */
|
||||
onRefresh: () => void
|
||||
onPortal: () => void
|
||||
onSetOverage: (args: OrcaBillingOverageArgs) => void
|
||||
overageFailures?: number
|
||||
/** Opens the plans page (pricing, Checkout, Enterprise contact). */
|
||||
onSeePlans: () => void
|
||||
}
|
||||
|
||||
export function PlanBillingView({
|
||||
result,
|
||||
loading,
|
||||
busy,
|
||||
notice,
|
||||
teamName = null,
|
||||
usage,
|
||||
onRetryUsage = noop,
|
||||
onRefresh,
|
||||
onPortal,
|
||||
onSetOverage,
|
||||
overageFailures = 0,
|
||||
onSeePlans
|
||||
}: PlanBillingViewProps): React.JSX.Element | null {
|
||||
const t = useTranslate()
|
||||
const locale = useIntlLocale()
|
||||
if (!result) {
|
||||
return loading ? <PlanBillingSkeleton /> : null
|
||||
}
|
||||
if (result.status === 'unconfigured') {
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t(
|
||||
'auto.components.billing.unconfigured',
|
||||
'Billing isn’t available in this build of Orca.'
|
||||
)}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
if (result.status === 'signed-out') {
|
||||
// The Orca Cloud panes show the sign-in prompt before this renders.
|
||||
return null
|
||||
}
|
||||
|
||||
if (result.status === 'failed') {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<InlineError
|
||||
title={t('auto.components.billing.loadFailedTitle', 'Couldn’t load your plan')}
|
||||
detail={
|
||||
result.error === 'billing_org_mismatch'
|
||||
? t(
|
||||
// EP-9: auth answered for a different team than this device shows; refused.
|
||||
'auto.components.billing.loadFailedOtherTeam',
|
||||
'Orca couldn’t confirm this team’s billing. Try again, or sign out and back in.'
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
retryLabel={t('auto.components.billing.plans.retry', 'Try again')}
|
||||
onRetry={onRefresh}
|
||||
retrying={loading}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const entitlement = result.entitlement
|
||||
const hasPlan = entitlement.plan !== null && entitlement.status !== 'canceled'
|
||||
// The one-time trial stands in for a plan until one starts (spec T1).
|
||||
const onTrial = !hasPlan && isOrcaCloudTrial(entitlement)
|
||||
const trialUsedUp = onTrial && entitlement.trial?.exhausted === true
|
||||
const monthlyCents = entitlement.offers?.team.monthlyPriceCentsPerSeat ?? null
|
||||
const teamPrice = monthlyCents === null ? null : formatCents(monthlyCents, locale)
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<PaymentIssueNotice entitlement={entitlement} busy={busy} onUpdatePayment={onPortal} />
|
||||
{hasPlan ? (
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-4">
|
||||
<SettingsGroupHeader
|
||||
className="px-0"
|
||||
title={
|
||||
teamName
|
||||
? t('auto.components.billing.teamPlanTitle', '{{team}} · {{plan}} plan', {
|
||||
team: teamName,
|
||||
plan: entitlement.planLabel
|
||||
})
|
||||
: t('auto.components.billing.planTitle', '{{plan}} plan', {
|
||||
plan: entitlement.planLabel
|
||||
})
|
||||
}
|
||||
description={
|
||||
entitlement.interval === 'year'
|
||||
? t('auto.components.billing.seatsAnnual', '{{count}} seats · Annual', {
|
||||
count: entitlement.seats,
|
||||
defaultValue_one: '{{count}} seat · Annual'
|
||||
})
|
||||
: t('auto.components.billing.seatsMonthly', '{{count}} seats · Monthly', {
|
||||
count: entitlement.seats,
|
||||
defaultValue_one: '{{count}} seat · Monthly'
|
||||
})
|
||||
}
|
||||
action={<PlanStatusBadge entitlement={entitlement} />}
|
||||
/>
|
||||
<UsageSummary entitlement={entitlement} />
|
||||
</div>
|
||||
{usage ? <PlanBillingUsageHistory state={usage} onRetry={onRetryUsage} /> : null}
|
||||
{/* Overage is moot while sandboxes are suspended for a failed payment. */}
|
||||
{entitlement.payment.suspendRunning ? null : (
|
||||
<OverageControls
|
||||
entitlement={entitlement}
|
||||
busy={busy}
|
||||
failures={overageFailures}
|
||||
onSetOverage={onSetOverage}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{onTrial ? <TrialPlanSummary entitlement={entitlement} onChoosePlan={onSeePlans} /> : null}
|
||||
|
||||
{/* Admins already read these above: the overage card's cap-reached hint, and the usage
|
||||
alert's out-of-hours sentence. */}
|
||||
{(hasPlan || entitlement.reason === 'trial_unavailable') &&
|
||||
entitlement.reason &&
|
||||
entitlement.payment.pastDueSince === null &&
|
||||
!(
|
||||
entitlement.canManageBilling &&
|
||||
(entitlement.reason === 'overage_cap_reached' ||
|
||||
(entitlement.reason === 'included_hours_exhausted' &&
|
||||
usageAlertLevel(entitlement) === 100))
|
||||
) ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{denyReasonCopy(entitlement.reason, t, entitlement.canManageBilling)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{!hasPlan && !onTrial ? (
|
||||
<p className="text-sm text-muted-foreground text-pretty">
|
||||
{teamPrice
|
||||
? t(
|
||||
'auto.components.billing.upsellLine2',
|
||||
'Orca Cloud runs agents in sandboxes. Team is {{value0}} per seat per month.',
|
||||
{ value0: teamPrice }
|
||||
)
|
||||
: t(
|
||||
'auto.components.billing.upsellLineNoPrice',
|
||||
'Orca Cloud runs agents in hosted sandboxes for your whole team.'
|
||||
)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{hasPlan || onTrial ? null : (
|
||||
<Button type="button" size="sm" onClick={onSeePlans}>
|
||||
{t('auto.components.billing.comparePlans', 'Compare plans')}
|
||||
</Button>
|
||||
)}
|
||||
{hasPlan && entitlement.canManageBilling && entitlement.payment.pastDueSince === null ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-disabled={busy || undefined}
|
||||
onClick={busy ? undefined : onPortal}
|
||||
>
|
||||
{t('auto.components.billing.manageBilling', 'Manage billing')}
|
||||
<ExternalLink />
|
||||
</Button>
|
||||
) : null}
|
||||
{hasPlan ? (
|
||||
// Members have no other action here, so it gets the button's chrome (and its alignment).
|
||||
<Button
|
||||
type="button"
|
||||
variant={entitlement.canManageBilling ? 'ghost' : 'outline'}
|
||||
size="sm"
|
||||
onClick={onSeePlans}
|
||||
>
|
||||
{t('auto.components.billing.comparePlans', 'Compare plans')}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* The payment alert already says who to ask; don't ask twice. */}
|
||||
{!entitlement.canManageBilling &&
|
||||
entitlement.payment.pastDueSince === null &&
|
||||
!trialUsedUp ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('auto.components.billing.askAdmin2', 'Ask an owner or admin to change the plan.')}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{notice?.kind === 'error' ? (
|
||||
<InlineError tone="error" title={notice.text} />
|
||||
) : notice ? (
|
||||
<p role="status" className="text-xs text-muted-foreground">
|
||||
{notice.text}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Same rows as a loaded plan (header, plan line, usage, overage card) so nothing jumps in. */
|
||||
function PlanBillingSkeleton(): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
return (
|
||||
<div
|
||||
className="space-y-4"
|
||||
role="status"
|
||||
aria-busy
|
||||
aria-label={t('auto.components.billing.loadingPlan', 'Loading your plan…')}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton shape="circle" className="size-4" />
|
||||
<Skeleton shape="small" className="h-4 w-16" />
|
||||
<Skeleton shape="small" className="h-3 w-28" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between gap-3">
|
||||
<Skeleton shape="small" className="h-3 w-56" />
|
||||
<Skeleton shape="small" className="h-3 w-28" />
|
||||
</div>
|
||||
<Skeleton shape="circle" className="h-2 w-full" />
|
||||
<Skeleton shape="small" className="h-3 w-40" />
|
||||
</div>
|
||||
<Skeleton shape="card" className="h-20 w-full" />
|
||||
<Skeleton className="h-8 w-32" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { OrcaBillingEntitlement } from '../../../../shared/orca-billing'
|
||||
import { OverageControls } from './PlanBillingUsage'
|
||||
import { PlanBillingUsageHistory } from './PlanBillingUsageHistory'
|
||||
import { PlanBillingView } from './PlanBillingSection'
|
||||
import { sampleTeam, sampleUsageHistory, sampleUsageNames } from './plan-billing-fixtures'
|
||||
import { UsageHistoryChart } from './UsageHistoryChart'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const overageOn: OrcaBillingEntitlement = {
|
||||
...sampleTeam,
|
||||
overage: { ...sampleTeam.overage, optedIn: true, active: true, spendCapCents: 4000 }
|
||||
}
|
||||
|
||||
function capField(): HTMLInputElement {
|
||||
const field = screen.getByLabelText('Monthly spend cap')
|
||||
if (!(field instanceof HTMLInputElement)) {
|
||||
throw new Error('the spend cap is not an input')
|
||||
}
|
||||
return field
|
||||
}
|
||||
|
||||
describe('spend cap field', () => {
|
||||
// N-09: off is one status line and one action; no "$ 0" field (it read as "on, capped at nothing").
|
||||
it('shows off as a status line and one Turn on button, with no cap field', () => {
|
||||
const onSetOverage = vi.fn()
|
||||
render(<OverageControls entitlement={sampleTeam} busy={false} onSetOverage={onSetOverage} />)
|
||||
expect(
|
||||
screen.getByText(
|
||||
'Overage is off. Running sandboxes go to sleep and new ones can’t start when your team runs out of sandbox hours.'
|
||||
)
|
||||
).toBeTruthy()
|
||||
expect(screen.queryByLabelText('Monthly spend cap')).toBeNull()
|
||||
expect(screen.queryByText('$')).toBeNull()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Turn on with a $25 cap' }))
|
||||
expect(onSetOverage).toHaveBeenCalledWith({ enabled: true, spendCapCents: 2500 })
|
||||
})
|
||||
|
||||
it('on: saves a new cap, refuses $0, and turns off with its own button', () => {
|
||||
const onSetOverage = vi.fn()
|
||||
render(<OverageControls entitlement={overageOn} busy={false} onSetOverage={onSetOverage} />)
|
||||
expect(capField().value).toBe('40')
|
||||
fireEvent.change(capField(), { target: { value: '60' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
|
||||
expect(onSetOverage).toHaveBeenLastCalledWith({ enabled: true, spendCapCents: 6000 })
|
||||
cleanup()
|
||||
onSetOverage.mockClear()
|
||||
render(<OverageControls entitlement={overageOn} busy={false} onSetOverage={onSetOverage} />)
|
||||
fireEvent.change(capField(), { target: { value: '0' } })
|
||||
expect(screen.getByText('Set a spend cap above $0, or turn overage off.')).toBeTruthy()
|
||||
expect(screen.queryByRole('button', { name: 'Save' })).toBeNull()
|
||||
expect(onSetOverage).not.toHaveBeenCalled()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Turn off overage' }))
|
||||
expect(onSetOverage).toHaveBeenLastCalledWith({ enabled: false })
|
||||
})
|
||||
|
||||
it('puts the rate in one hint, shows spend as "of … used" and keeps the alert sentence', () => {
|
||||
render(<OverageControls entitlement={overageOn} busy={false} onSetOverage={() => {}} />)
|
||||
expect(capField().getAttribute('aria-describedby')).toBeTruthy()
|
||||
expect(
|
||||
screen.getByText('$1.00 per sandbox hour after your included hours, billed by the minute.')
|
||||
).toBeTruthy()
|
||||
expect(screen.getByText(/of \$40 used/)).toBeTruthy()
|
||||
expect(screen.getByText(/alerted in Orca at 75%, 90% and 100%/)).toBeTruthy()
|
||||
})
|
||||
|
||||
// Without billing's catalog (an older service, or a failed read) nothing is guessed.
|
||||
it('sends no cap and states no numbers when billing sent no offers', () => {
|
||||
const onSetOverage = vi.fn()
|
||||
render(
|
||||
<OverageControls
|
||||
entitlement={{ ...sampleTeam, offers: null }}
|
||||
busy={false}
|
||||
onSetOverage={onSetOverage}
|
||||
/>
|
||||
)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Turn on overage' }))
|
||||
expect(onSetOverage).toHaveBeenCalledWith({ enabled: true })
|
||||
expect(screen.queryByText(/\d+%/)).toBeNull()
|
||||
})
|
||||
|
||||
// Today's dev billing (before #507): offers with every number but no warnAtPercent.
|
||||
it('keeps the cap and rate but states no alert levels when billing sends none', () => {
|
||||
const { warnAtPercent: _levels, ...olderTeam } = sampleTeam.offers!.team
|
||||
const onSetOverage = vi.fn()
|
||||
render(
|
||||
<OverageControls
|
||||
entitlement={{ ...overageOn, offers: { ...sampleTeam.offers!, team: olderTeam } }}
|
||||
busy={false}
|
||||
onSetOverage={onSetOverage}
|
||||
/>
|
||||
)
|
||||
expect(
|
||||
screen.getByText(
|
||||
'Owners and admins are alerted in Orca as your team’s sandbox hours run low.'
|
||||
)
|
||||
).toBeTruthy()
|
||||
expect(screen.queryByText(/\d+%/)).toBeNull()
|
||||
expect(capField().value).toBe('40')
|
||||
expect(
|
||||
screen.getByText('$1.00 per sandbox hour after your included hours, billed by the minute.')
|
||||
).toBeTruthy()
|
||||
})
|
||||
|
||||
it('shows members the setting as text', () => {
|
||||
render(
|
||||
<OverageControls
|
||||
entitlement={{ ...overageOn, canManageBilling: false }}
|
||||
busy={false}
|
||||
onSetOverage={() => {}}
|
||||
/>
|
||||
)
|
||||
expect(screen.queryByLabelText('Monthly spend cap')).toBeNull()
|
||||
expect(screen.getByText('Overage is on, up to your $40 spend cap.')).toBeTruthy()
|
||||
expect(screen.queryByText(/alerted in Orca/)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('last 30 days', () => {
|
||||
it('reads each day with the arrow keys and lists every day in a table', () => {
|
||||
render(<UsageHistoryChart days={sampleUsageHistory.days} />)
|
||||
const chart = screen.getByRole('group')
|
||||
fireEvent.focus(chart)
|
||||
expect(screen.getByRole('status').textContent).toMatch(/· 0\.6 sandbox hours$/)
|
||||
fireEvent.keyDown(chart, { key: 'ArrowLeft' })
|
||||
expect(screen.getByRole('status').textContent).toMatch(/· 1\.5 sandbox hours$/)
|
||||
fireEvent.keyDown(chart, { key: 'Home' })
|
||||
expect(screen.getByRole('status').textContent).toMatch(/· 0\.5 sandbox hours$/)
|
||||
expect(screen.getAllByRole('row')).toHaveLength(30)
|
||||
})
|
||||
|
||||
it('shows owners the top workspaces and members, and members only their share', () => {
|
||||
render(
|
||||
<PlanBillingUsageHistory
|
||||
state={{ status: 'ok', history: sampleUsageHistory, names: sampleUsageNames }}
|
||||
onRetry={() => {}}
|
||||
/>
|
||||
)
|
||||
expect(screen.getByText('Top workspaces')).toBeTruthy()
|
||||
expect(screen.getByText('Checkout retries')).toBeTruthy()
|
||||
expect(screen.getByText('48 sandbox hours in 30 days')).toBeTruthy()
|
||||
cleanup()
|
||||
render(
|
||||
<PlanBillingUsageHistory
|
||||
state={{
|
||||
status: 'ok',
|
||||
history: { ...sampleUsageHistory, members: null, sandboxes: null },
|
||||
names: sampleUsageNames
|
||||
}}
|
||||
onRetry={() => {}}
|
||||
/>
|
||||
)
|
||||
expect(screen.queryByText('Top workspaces')).toBeNull()
|
||||
expect(screen.getByText('You used 18.4 of your team’s 48 sandbox hours.')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('has empty, loading and error states', () => {
|
||||
const onRetry = vi.fn()
|
||||
render(<PlanBillingUsageHistory state={{ status: 'failed' }} onRetry={onRetry} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Try again' }))
|
||||
expect(onRetry).toHaveBeenCalled()
|
||||
cleanup()
|
||||
render(<PlanBillingUsageHistory state={{ status: 'loading' }} onRetry={onRetry} />)
|
||||
expect(screen.getByRole('status', { name: 'Loading your usage history…' })).toBeTruthy()
|
||||
cleanup()
|
||||
const empty = {
|
||||
...sampleUsageHistory,
|
||||
days: sampleUsageHistory.days.map((day) => ({ ...day, seconds: 0 })),
|
||||
totalSeconds: 0
|
||||
}
|
||||
render(
|
||||
<PlanBillingUsageHistory
|
||||
state={{ status: 'ok', history: empty, names: sampleUsageNames }}
|
||||
onRetry={onRetry}
|
||||
/>
|
||||
)
|
||||
expect(screen.getByText(/No sandbox hours yet/)).toBeTruthy()
|
||||
expect(screen.queryByRole('group')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('plan header', () => {
|
||||
it('titles the page "<Team> · Team plan" with no refresh button', () => {
|
||||
render(
|
||||
<PlanBillingView
|
||||
result={{ status: 'ok', entitlement: sampleTeam }}
|
||||
loading={false}
|
||||
busy={false}
|
||||
notice={null}
|
||||
teamName="Orca Staging Eval Team"
|
||||
onRefresh={() => {}}
|
||||
onPortal={() => {}}
|
||||
onSetOverage={() => {}}
|
||||
onSeePlans={() => {}}
|
||||
/>
|
||||
)
|
||||
expect(screen.getByRole('heading', { name: 'Orca Staging Eval Team · Team plan' })).toBeTruthy()
|
||||
expect(screen.queryByRole('button', { name: 'Refresh plan' })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
it('gives members an outlined Compare plans and the off line', () => {
|
||||
render(
|
||||
<PlanBillingView
|
||||
result={{ status: 'ok', entitlement: { ...sampleTeam, canManageBilling: false } }}
|
||||
loading={false}
|
||||
busy={false}
|
||||
notice={null}
|
||||
onRefresh={() => {}}
|
||||
onPortal={() => {}}
|
||||
onSetOverage={() => {}}
|
||||
onSeePlans={() => {}}
|
||||
/>
|
||||
)
|
||||
expect(screen.getByText('Off until an owner or admin turns it on.')).toBeTruthy()
|
||||
expect(screen.getByRole('button', { name: 'Compare plans' }).className).toMatch(/border/)
|
||||
})
|
||||
@@ -1,416 +0,0 @@
|
||||
import { useEffect, useId, useRef, useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { SettingsDisabledControlTooltip } from '@/components/settings/form-controls/SettingsDisabledControlTooltip'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
|
||||
import type {
|
||||
OrcaBillingEntitlement,
|
||||
OrcaBillingOverageArgs
|
||||
} from '../../../../shared/orca-billing'
|
||||
import { formatHours, formatHoursUsed, includedUsagePercent } from './plan-billing-format'
|
||||
import {
|
||||
includedUsageTone,
|
||||
sandboxHoursLeftLine,
|
||||
sandboxHoursOverLine,
|
||||
usageWarningLine
|
||||
} from './plan-billing-usage-copy'
|
||||
import { formatCents, formatRateCents } from './plans/plans-pricing'
|
||||
import { capTooHighCopy } from './plan-billing-copy'
|
||||
import { OverageSaveStatus, useOverageSaveState, type OverageAction } from './overage-save-state'
|
||||
import { ORCA_BILLING_OVERAGE_SECTION_ID } from '../new-workspace/orca-cloud-run-target-access'
|
||||
|
||||
/** "Resets and renews Dec 2" when both land the same day (monthly); separate parts otherwise. */
|
||||
function resetLine(
|
||||
entitlement: OrcaBillingEntitlement,
|
||||
date: (ms: number) => string,
|
||||
t: ReturnType<typeof useTranslate>
|
||||
): string | null {
|
||||
const resets = entitlement.usageWindow ? date(entitlement.usageWindow.end) : null
|
||||
const ends = entitlement.period ? date(entitlement.period.end) : null
|
||||
if (entitlement.cancelAtPeriodEnd && (entitlement.cancelAt ?? ends)) {
|
||||
// A portal cancel names its own end date (cancel_at); otherwise the plan ends with the period.
|
||||
const endsOn = entitlement.cancelAt ? date(entitlement.cancelAt) : ends!
|
||||
return resets
|
||||
? t('auto.components.billing.resetsEnds', 'Hours reset {{value0}} · Plan ends {{value1}}', {
|
||||
value0: resets,
|
||||
value1: endsOn
|
||||
})
|
||||
: t('auto.components.billing.endsOn', 'Plan ends {{value0}}', {
|
||||
value0: endsOn
|
||||
})
|
||||
}
|
||||
if (resets && ends) {
|
||||
return resets === ends
|
||||
? t('auto.components.billing.resetsAndRenews', 'Resets and renews {{value0}}', {
|
||||
value0: ends
|
||||
})
|
||||
: t('auto.components.billing.resetsRenews', 'Hours reset {{value0}} · Renews {{value1}}', {
|
||||
value0: resets,
|
||||
value1: ends
|
||||
})
|
||||
}
|
||||
if (resets) {
|
||||
return t('auto.components.billing.resets', 'Hours reset {{value0}}', {
|
||||
value0: resets
|
||||
})
|
||||
}
|
||||
return ends
|
||||
? t('auto.components.billing.renewsOn', 'Renews {{value0}}', {
|
||||
value0: ends
|
||||
})
|
||||
: null
|
||||
}
|
||||
|
||||
export function UsageSummary({
|
||||
entitlement
|
||||
}: {
|
||||
entitlement: OrcaBillingEntitlement
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const locale = useIntlLocale()
|
||||
const date = (ms: number): string =>
|
||||
new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(ms)
|
||||
const overLine = sandboxHoursOverLine(entitlement, t)
|
||||
const warning = usageWarningLine(entitlement, t, locale)
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-baseline justify-between gap-3 text-xs">
|
||||
<span className="font-medium">
|
||||
{t(
|
||||
'auto.components.billing.sandboxHoursUsedMonth',
|
||||
'{{value0}} of {{value1}} sandbox hours used this month',
|
||||
{
|
||||
value0: formatHoursUsed(
|
||||
Math.min(entitlement.usedSeconds, entitlement.includedSeconds)
|
||||
),
|
||||
value1: formatHours(entitlement.includedSeconds)
|
||||
}
|
||||
)}
|
||||
</span>
|
||||
<span className="text-muted-foreground">{sandboxHoursLeftLine(entitlement, t)}</span>
|
||||
</div>
|
||||
<Progress
|
||||
value={includedUsagePercent(entitlement)}
|
||||
tone={includedUsageTone(entitlement)}
|
||||
aria-label={t('auto.components.billing.sandboxHoursUsedLabel', 'Sandbox hours used')}
|
||||
/>
|
||||
{overLine ? <p className="text-xs text-muted-foreground tabular-nums">{overLine}</p> : null}
|
||||
{warning ? <p className="text-xs font-medium">{warning}</p> : null}
|
||||
<p className="text-xs text-muted-foreground">{resetLine(entitlement, date, t)}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function OverageControls({
|
||||
entitlement,
|
||||
busy,
|
||||
failures = 0,
|
||||
onSetOverage
|
||||
}: {
|
||||
entitlement: OrcaBillingEntitlement
|
||||
busy: boolean
|
||||
/** Bumped by the parent each time a change fails, to roll back the optimistic state. */
|
||||
failures?: number
|
||||
onSetOverage: (args: OrcaBillingOverageArgs) => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const locale = useIntlLocale()
|
||||
const capId = useId()
|
||||
const hintId = useId()
|
||||
const capErrorId = useId()
|
||||
const capInputRef = useRef<HTMLInputElement>(null)
|
||||
const turnOnRef = useRef<HTMLButtonElement>(null)
|
||||
// Set by Turn on / Turn off: once the card switches, focus lands on the new view's control (N-09).
|
||||
const focusOnSwitch = useRef(false)
|
||||
const { overage } = entitlement
|
||||
useEffect(() => {
|
||||
if (focusOnSwitch.current) {
|
||||
focusOnSwitch.current = false
|
||||
if (overage.optedIn) {
|
||||
capInputRef.current?.focus()
|
||||
} else {
|
||||
turnOnRef.current?.focus()
|
||||
}
|
||||
}
|
||||
}, [overage.optedIn])
|
||||
// One field: the cap while overage is on, $0 while it's off.
|
||||
const savedDollars = overage.optedIn ? String(Math.round(overage.spendCapCents / 100)) : '0'
|
||||
// Billing's default cap; unknown (no catalog) sends none and billing applies its own.
|
||||
const defaultCapCents = entitlement.offers?.team.defaultSpendCapCents ?? null
|
||||
const [capDollars, setCapDollars] = useState(savedDollars)
|
||||
// Re-seed from the server whenever the saved values change (render-time adjustment, no effect).
|
||||
const [seededFrom, setSeededFrom] = useState(savedDollars)
|
||||
if (seededFrom !== savedDollars) {
|
||||
setSeededFrom(savedDollars)
|
||||
setCapDollars(savedDollars)
|
||||
}
|
||||
const { status, action, begin, clear } = useOverageSaveState({
|
||||
overage,
|
||||
busy,
|
||||
failures,
|
||||
// Roll back to what billing has.
|
||||
onFailure: () => setCapDollars(savedDollars)
|
||||
})
|
||||
const saving = status === 'saving'
|
||||
const parsedCap = Number(capDollars)
|
||||
const maxCapCents = entitlement.offers?.team.maxSpendCapCents ?? null
|
||||
const capWhole = capDollars.trim() !== '' && Number.isInteger(parsedCap) && parsedCap >= 0
|
||||
// N-09: "off" has one representation (the Turn on button); a saved $0 cap would read as "on".
|
||||
const capZero = capWhole && parsedCap === 0
|
||||
const capTooHigh = capWhole && maxCapCents !== null && parsedCap * 100 > maxCapCents
|
||||
const capValid = capWhole && !capTooHigh && !capZero
|
||||
const changed = capValid && capDollars.trim() !== savedDollars
|
||||
const paymentFailed = entitlement.payment.pastDueSince !== null
|
||||
const rate = formatRateCents(overage.centsPerHour, locale)
|
||||
const hint = t(
|
||||
'components.billing.overage.capHint2',
|
||||
'{{rate}} per sandbox hour after your included hours, billed by the minute.',
|
||||
{ rate }
|
||||
)
|
||||
const capPercent =
|
||||
overage.spendCapCents > 0
|
||||
? Math.min(100, Math.round((overage.spentCents / overage.spendCapCents) * 100))
|
||||
: 0
|
||||
const spent = (
|
||||
<div className="space-y-1.5">
|
||||
<Progress
|
||||
value={capPercent}
|
||||
tone={capPercent >= 100 ? 'warning' : 'default'}
|
||||
aria-label={t('auto.components.billing.capUsedLabel', 'Overage spend cap used')}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground tabular-nums">
|
||||
{t('components.billing.overageUsed', '{{value0}} of {{value1}} used', {
|
||||
value0: formatCents(overage.spentCents, locale),
|
||||
value1: formatCents(overage.spendCapCents, locale)
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
const title = (
|
||||
<p className="text-sm font-medium">{t('auto.components.billing.overageTitle', 'Overage')}</p>
|
||||
)
|
||||
|
||||
// Members see the setting as plain text: a field they can't use only invites clicks.
|
||||
if (!entitlement.canManageBilling) {
|
||||
return (
|
||||
<div className="space-y-2 rounded-md border border-border/60 p-3">
|
||||
{title}
|
||||
<p className="text-xs text-muted-foreground tabular-nums">
|
||||
{overage.optedIn
|
||||
? t(
|
||||
'components.billing.overage.memberOn5',
|
||||
'Overage is on, up to your {{cap}} spend cap.',
|
||||
{ cap: formatCents(overage.spendCapCents, locale) }
|
||||
)
|
||||
: t(
|
||||
'components.billing.overage.memberOff5',
|
||||
'Off until an owner or admin turns it on.'
|
||||
)}
|
||||
</p>
|
||||
{overage.optedIn ? spent : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const save = (action: OverageAction, cents: number | null): void => {
|
||||
const enabled = action !== 'off'
|
||||
begin({ action, optedIn: enabled, capCents: enabled ? cents : null })
|
||||
onSetOverage(
|
||||
!enabled
|
||||
? { enabled: false }
|
||||
: cents === null
|
||||
? { enabled: true }
|
||||
: { enabled: true, spendCapCents: cents }
|
||||
)
|
||||
}
|
||||
const blocked = busy || saving || paymentFailed
|
||||
const statusLine = <OverageSaveStatus status={status} action={action} />
|
||||
// Turn off's status sits by its link, so it doesn't read as the cap failing (design-squad).
|
||||
const offStatus = action === 'off'
|
||||
const blockedReason = paymentFailed
|
||||
? t(
|
||||
'auto.components.billing.overagePaymentFailed',
|
||||
'Update the payment method before changing overage.'
|
||||
)
|
||||
: undefined
|
||||
const alertLevels = entitlement.offers?.team.warnAtPercent ?? null
|
||||
const alertsNote = (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{alertLevels && alertLevels.length > 0
|
||||
? t(
|
||||
'auto.components.billing.usageAlertsNoteLevels',
|
||||
'Owners and admins are alerted in Orca at {{levels}} of your team’s sandbox hours.',
|
||||
{ levels: formatPercentList(alertLevels, locale) }
|
||||
)
|
||||
: t(
|
||||
'auto.components.billing.usageAlertsNoteGeneric',
|
||||
'Owners and admins are alerted in Orca as your team’s sandbox hours run low.'
|
||||
)}
|
||||
</p>
|
||||
)
|
||||
const turnOn = (): void => {
|
||||
if (blocked) {
|
||||
return
|
||||
}
|
||||
if (defaultCapCents !== null) {
|
||||
setCapDollars(String(Math.round(defaultCapCents / 100)))
|
||||
}
|
||||
focusOnSwitch.current = true
|
||||
save('on', defaultCapCents)
|
||||
}
|
||||
|
||||
// N-09: off is one status line and one action. No cap field and no "$ 0" (which reads as "on").
|
||||
if (!overage.optedIn) {
|
||||
return (
|
||||
<div
|
||||
id={ORCA_BILLING_OVERAGE_SECTION_ID}
|
||||
className="space-y-3 rounded-md border border-border/60 p-3"
|
||||
>
|
||||
{title}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
'components.billing.overage.offStatus2',
|
||||
'Overage is off. Running sandboxes go to sleep and new ones can’t start when your team runs out of sandbox hours.'
|
||||
)}
|
||||
</p>
|
||||
{/* Turn on is always here, whatever the last change did (OVERAGE-REENABLE). */}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<SettingsDisabledControlTooltip reason={blockedReason}>
|
||||
<Button
|
||||
ref={turnOnRef}
|
||||
type="button"
|
||||
variant="outline"
|
||||
aria-disabled={blocked || undefined}
|
||||
onClick={paymentFailed ? undefined : turnOn}
|
||||
>
|
||||
{defaultCapCents === null
|
||||
? t('auto.components.billing.overage.turnOnNoCap', 'Turn on overage')
|
||||
: t('auto.components.billing.overage.turnOn', 'Turn on with a {{cap}} cap', {
|
||||
cap: formatCents(defaultCapCents, locale)
|
||||
})}
|
||||
</Button>
|
||||
</SettingsDisabledControlTooltip>
|
||||
{statusLine}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{hint}</p>
|
||||
{alertsNote}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
// Deep-link target: the Run-on picker's "Turn on overage" / "Raise cap" lands here.
|
||||
<div
|
||||
id={ORCA_BILLING_OVERAGE_SECTION_ID}
|
||||
className="space-y-3 rounded-md border border-border/60 p-3"
|
||||
>
|
||||
{title}
|
||||
<form
|
||||
className="flex flex-wrap items-start gap-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
if (changed && !blocked) {
|
||||
save('cap', parsedCap * 100)
|
||||
// Save turns into the status in place; keep focus in the card on the field.
|
||||
capInputRef.current?.focus()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<label htmlFor={capId} className="flex h-9 items-center text-xs font-medium">
|
||||
{t('auto.components.billing.capLabel2', 'Monthly spend cap')}
|
||||
</label>
|
||||
<div className="space-y-1">
|
||||
<SettingsDisabledControlTooltip reason={blockedReason}>
|
||||
<div className="relative w-32">
|
||||
<span
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-sm text-muted-foreground"
|
||||
>
|
||||
$
|
||||
</span>
|
||||
<Input
|
||||
ref={capInputRef}
|
||||
id={capId}
|
||||
inputMode="numeric"
|
||||
adornment="leading"
|
||||
value={capDollars}
|
||||
readOnly={paymentFailed}
|
||||
aria-disabled={paymentFailed || undefined}
|
||||
aria-invalid={!capValid || undefined}
|
||||
aria-describedby={capValid ? hintId : `${capErrorId} ${hintId}`}
|
||||
onChange={(event) => {
|
||||
setCapDollars(event.target.value)
|
||||
clear()
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</SettingsDisabledControlTooltip>
|
||||
{capValid ? null : (
|
||||
<p id={capErrorId} className="text-xs text-destructive">
|
||||
{capZero
|
||||
? t('components.billing.capZero2', 'Set a spend cap above $0, or turn overage off.')
|
||||
: capTooHigh && maxCapCents !== null
|
||||
? capTooHighCopy(maxCapCents, locale, t)
|
||||
: t('auto.components.billing.capInvalid', 'Enter a whole dollar amount.')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{saving || !changed ? (
|
||||
offStatus ? null : (
|
||||
statusLine
|
||||
)
|
||||
) : (
|
||||
<Button type="submit" variant="outline" aria-disabled={blocked || undefined}>
|
||||
{t('auto.components.billing.saveCap', 'Save')}
|
||||
</Button>
|
||||
)}
|
||||
<p id={hintId} className="basis-full text-xs text-muted-foreground">
|
||||
{hint}
|
||||
</p>
|
||||
{capValid && entitlement.reason === 'overage_cap_reached' ? (
|
||||
<p className="basis-full text-xs text-muted-foreground">
|
||||
{t(
|
||||
'auto.components.billing.capReachedHint2',
|
||||
'Raise the cap to start sandboxes again. Your sandboxes are asleep, and your files are safe.'
|
||||
)}
|
||||
</p>
|
||||
) : null}
|
||||
</form>
|
||||
{spent}
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<SettingsDisabledControlTooltip reason={blockedReason}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="link-muted"
|
||||
size="inline"
|
||||
aria-disabled={blocked || undefined}
|
||||
onClick={() => {
|
||||
if (!blocked) {
|
||||
focusOnSwitch.current = true
|
||||
save('off', null)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/* Reads as a link at rest, not only on hover (design-squad, as RR-c1). */}
|
||||
<span className="underline underline-offset-4">
|
||||
{t('components.billing.overage.turnOff', 'Turn off overage')}
|
||||
</span>
|
||||
</Button>
|
||||
</SettingsDisabledControlTooltip>
|
||||
{offStatus ? statusLine : null}
|
||||
</div>
|
||||
{alertsNote}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** "75%, 90% and 100%" in the UI locale (billing's alert levels). */
|
||||
function formatPercentList(levels: readonly number[], locale: string): string {
|
||||
const percent = new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 0 })
|
||||
// House style has no serial comma in English (en-US's ListFormat adds one).
|
||||
const listLocale = locale.toLowerCase().startsWith('en') ? 'en-GB' : locale
|
||||
return new Intl.ListFormat(listLocale, { type: 'conjunction' }).format(
|
||||
levels.map((level) => percent.format(level / 100))
|
||||
)
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
import { defineFixture } from '../../component-fixtures/component-fixture'
|
||||
import { PlanBillingView } from './PlanBillingSection'
|
||||
import { sampleTeam, sampleUsageHistory, sampleUsageNames } from './plan-billing-fixtures'
|
||||
|
||||
// JA-18 states of Plan & billing's "Last 30 days" and spend cap (activeTeam lives with the page).
|
||||
const HOUR = 3600
|
||||
|
||||
const handlers = {
|
||||
loading: false,
|
||||
busy: false,
|
||||
notice: null,
|
||||
onRefresh: () => {},
|
||||
onPortal: () => {},
|
||||
onSetOverage: () => {},
|
||||
onSeePlans: () => {}
|
||||
}
|
||||
|
||||
const usage = { status: 'ok', history: sampleUsageHistory, names: sampleUsageNames } as const
|
||||
|
||||
export const activeTeamOverageOn = defineFixture({
|
||||
width: 680,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
teamName="Orca Staging Eval Team"
|
||||
usage={usage}
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
overage: { ...sampleTeam.overage, optedIn: true, active: true, spentCents: 320 }
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
// Members see the team's chart and their own hours, not who used what.
|
||||
export const activeTeamMember = defineFixture({
|
||||
width: 680,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
teamName="Orca Staging Eval Team"
|
||||
usage={{
|
||||
...usage,
|
||||
history: { ...sampleUsageHistory, members: null, sandboxes: null }
|
||||
}}
|
||||
result={{ status: 'ok', entitlement: { ...sampleTeam, canManageBilling: false } }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const usageLoading = defineFixture({
|
||||
width: 680,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
teamName="Orca Staging Eval Team"
|
||||
usage={{ status: 'loading' }}
|
||||
result={{ status: 'ok', entitlement: sampleTeam }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const usageEmpty = defineFixture({
|
||||
width: 680,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
teamName="Orca Staging Eval Team"
|
||||
usage={{
|
||||
...usage,
|
||||
history: {
|
||||
...sampleUsageHistory,
|
||||
days: sampleUsageHistory.days.map((day) => ({ ...day, seconds: 0 })),
|
||||
totalSeconds: 0,
|
||||
yourSeconds: 0,
|
||||
members: { top: [], otherCount: 0, otherSeconds: 0 },
|
||||
sandboxes: { top: [], otherCount: 0, otherSeconds: 0 }
|
||||
}
|
||||
}}
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: { ...sampleTeam, usedSeconds: 0, remainingIncludedSeconds: 120 * HOUR }
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const usageFailed = defineFixture({
|
||||
width: 680,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
teamName="Orca Staging Eval Team"
|
||||
usage={{ status: 'failed' }}
|
||||
result={{ status: 'ok', entitlement: sampleTeam }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
// V3-06: a staging-like team: a few live workspaces among hundreds of short-lived, deleted ones.
|
||||
// Up to 5 live ones by name, then one deleted line, then the other live ones.
|
||||
const stagingLike = {
|
||||
...sampleUsageHistory,
|
||||
totalSeconds: 34.6 * HOUR,
|
||||
sandboxes: {
|
||||
top: [
|
||||
{ id: 'sbx_gone_1', seconds: 1.2 * HOUR },
|
||||
{ id: 'sbx_orca', seconds: 0.9 * HOUR },
|
||||
{ id: 'sbx_gone_2', seconds: 0.8 * HOUR },
|
||||
{ id: 'sbx_hello', seconds: 0.6 * HOUR },
|
||||
{ id: 'sbx_push', seconds: 0.5 * HOUR },
|
||||
{ id: 'sbx_ja3', seconds: 0.4 * HOUR },
|
||||
{ id: 'sbx_ikzw', seconds: 0.35 * HOUR },
|
||||
{ id: 'sbx_gone_3', seconds: 0.3 * HOUR },
|
||||
{ id: 'sbx_w312', seconds: 0.3 * HOUR }
|
||||
],
|
||||
otherCount: 578,
|
||||
otherSeconds: 29.75 * HOUR
|
||||
}
|
||||
}
|
||||
const stagingNames = {
|
||||
...sampleUsageNames,
|
||||
workspaces: new Map([
|
||||
['sbx_orca', 'orca'],
|
||||
['sbx_hello', 'Hello-World · ik-sheet'],
|
||||
['sbx_push', 'orca-sandbox-push-test'],
|
||||
['sbx_ja3', 'ja3-claude'],
|
||||
['sbx_ikzw', 'ik-zw'],
|
||||
['sbx_w312', 'W-312']
|
||||
])
|
||||
}
|
||||
export const usageStagingLike = defineFixture({
|
||||
width: 680,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
teamName="Orca Staging Eval Team"
|
||||
usage={{ status: 'ok', history: stagingLike, names: stagingNames }}
|
||||
result={{ status: 'ok', entitlement: sampleTeam }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
// V3-06: a small team: every live workspace by name, nothing summed.
|
||||
export const usageSmallTeam = defineFixture({
|
||||
width: 680,
|
||||
render: () => (
|
||||
<PlanBillingView
|
||||
{...handlers}
|
||||
teamName="Acme"
|
||||
usage={{
|
||||
status: 'ok',
|
||||
history: {
|
||||
...sampleUsageHistory,
|
||||
totalSeconds: 26 * HOUR,
|
||||
sandboxes: {
|
||||
top: [
|
||||
{ id: 'sbx_checkout', seconds: 11 * HOUR },
|
||||
{ id: 'sbx_ledger', seconds: 8 * HOUR },
|
||||
{ id: 'sbx_docs', seconds: 5 * HOUR },
|
||||
{ id: 'sbx_flaky', seconds: 2 * HOUR }
|
||||
],
|
||||
otherCount: 0,
|
||||
otherSeconds: 0
|
||||
}
|
||||
},
|
||||
names: sampleUsageNames
|
||||
}}
|
||||
result={{ status: 'ok', entitlement: sampleTeam }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
@@ -1,155 +0,0 @@
|
||||
import { InlineError } from '@/components/ui/inline-error'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { formatHoursUsed } from './plan-billing-format'
|
||||
import {
|
||||
topMemberRows,
|
||||
topWorkspaceRows,
|
||||
usageWindowTotalLine,
|
||||
yourUsageLine,
|
||||
type UsageBreakdownRow
|
||||
} from './plan-billing-usage-history'
|
||||
import { UsageHistoryChart } from './UsageHistoryChart'
|
||||
import type { PlanBillingUsageState } from './use-plan-billing-usage-history'
|
||||
|
||||
// Thirty placeholder bars with a gentle rise and fall (static, so reduced motion is unaffected).
|
||||
const LOADING_BAR_HEIGHTS = Array.from({ length: 30 }, (_, index) =>
|
||||
Math.round(30 + 25 * Math.sin(index / 3) + 20 * Math.cos(index / 5) + 25)
|
||||
)
|
||||
|
||||
/** A part of Plan & billing, so a step below its section header (the size of "Overage"). */
|
||||
function UsageHistoryHeading({
|
||||
title,
|
||||
total = null
|
||||
}: {
|
||||
title: string
|
||||
total?: string | null
|
||||
}): React.JSX.Element {
|
||||
return (
|
||||
<div className="flex items-baseline justify-between gap-3">
|
||||
<h4 className="text-sm font-medium">{title}</h4>
|
||||
{total ? <span className="text-xs text-muted-foreground tabular-nums">{total}</span> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** "Last 30 days": the team's daily hours; owners and admins also see the top workspaces and members. */
|
||||
export function PlanBillingUsageHistory({
|
||||
state,
|
||||
onRetry
|
||||
}: {
|
||||
state: PlanBillingUsageState
|
||||
onRetry: () => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const title = t('auto.components.billing.usage.title', 'Last 30 days')
|
||||
if (state.status === 'failed') {
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
<UsageHistoryHeading title={title} />
|
||||
<InlineError
|
||||
title={t('auto.components.billing.usage.loadFailed', 'Couldn’t load your usage history')}
|
||||
retryLabel={t('auto.components.billing.plans.retry', 'Try again')}
|
||||
onRetry={onRetry}
|
||||
/>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
if (state.status === 'loading') {
|
||||
return (
|
||||
<section
|
||||
className="space-y-3"
|
||||
role="status"
|
||||
aria-busy
|
||||
aria-label={t('auto.components.billing.usage.loading', 'Loading your usage history…')}
|
||||
>
|
||||
<UsageHistoryHeading title={title} />
|
||||
{/* Shaped like the chart it stands in for, so it reads as "loading", not an empty panel. */}
|
||||
<div className="flex h-[136px] w-full items-end gap-1" aria-hidden>
|
||||
{LOADING_BAR_HEIGHTS.map((height, index) => (
|
||||
<Skeleton key={index} className="flex-1" style={{ height: `${height}%` }} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
const { history, names } = state
|
||||
const workspaces = topWorkspaceRows(history, names, t)
|
||||
const members = topMemberRows(history, names, t)
|
||||
const empty = history.totalSeconds <= 0
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
<UsageHistoryHeading
|
||||
title={title}
|
||||
total={empty ? null : usageWindowTotalLine(history.totalSeconds, t)}
|
||||
/>
|
||||
{empty ? (
|
||||
<p className="rounded-md border border-dashed border-border px-3 py-6 text-center text-xs text-muted-foreground">
|
||||
{t(
|
||||
'auto.components.billing.usage.empty',
|
||||
'No sandbox hours yet. Usage shows here once your team runs cloud workspaces.'
|
||||
)}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<UsageHistoryChart days={history.days} />
|
||||
{workspaces && members ? (
|
||||
<div className="grid gap-x-6 gap-y-4 pt-1 sm:grid-cols-2">
|
||||
<BreakdownList
|
||||
title={t('auto.components.billing.usage.topWorkspaces', 'Top workspaces')}
|
||||
rows={workspaces}
|
||||
/>
|
||||
<BreakdownList
|
||||
title={t('auto.components.billing.usage.topMembers', 'Top members')}
|
||||
rows={members}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground tabular-nums">
|
||||
{yourUsageLine(history, t)}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function BreakdownList({
|
||||
title,
|
||||
rows
|
||||
}: {
|
||||
title: string
|
||||
rows: UsageBreakdownRow[]
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
return (
|
||||
<div className="min-w-0 space-y-2">
|
||||
<div className="flex items-baseline justify-between gap-3 text-xs">
|
||||
<h4 className="font-medium">{title}</h4>
|
||||
<span className="text-muted-foreground">
|
||||
{t('auto.components.billing.usage.hoursColumn', 'Sandbox hours')}
|
||||
</span>
|
||||
</div>
|
||||
<ul className="space-y-2">
|
||||
{rows.map((row) => (
|
||||
<li key={row.key} className="space-y-1">
|
||||
<div className="flex items-baseline justify-between gap-3 text-xs">
|
||||
<span className={row.other ? 'truncate text-muted-foreground' : 'truncate'}>
|
||||
{row.label}
|
||||
</span>
|
||||
<span className="shrink-0 tabular-nums">{formatHoursUsed(row.seconds)}</span>
|
||||
</div>
|
||||
{/* Share of the team's hours: decoration; the number beside it carries the value. */}
|
||||
<div aria-hidden className="h-1 w-full rounded-full bg-muted">
|
||||
<div
|
||||
className="h-full rounded-full bg-chart-3 dark:bg-chart-2"
|
||||
style={{ width: `${Math.max(1, row.share)}%` }}
|
||||
/>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
// The team's one-time trial (spec T1) in Plan & billing and on the plans page: a "Trial" badge,
|
||||
// the hours bar, and the one-time-allowance line. Never "Hours reset every month" here.
|
||||
import { Cloud } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import type { OrcaBillingEntitlement } from '../../../../shared/orca-billing'
|
||||
import { includedUsagePercent } from './plan-billing-format'
|
||||
import { denyReasonCopy } from './plan-billing-copy'
|
||||
import {
|
||||
includedUsageTone,
|
||||
sandboxHoursLeftLine,
|
||||
trialHoursUsedLine
|
||||
} from './plan-billing-usage-copy'
|
||||
import { PlanStatusBadge } from './PlanStatusBadge'
|
||||
|
||||
export function TrialPlanSummary({
|
||||
entitlement,
|
||||
onChoosePlan
|
||||
}: {
|
||||
entitlement: OrcaBillingEntitlement
|
||||
/** Shown to owners and admins; omitted where the plan cards are already on screen. */
|
||||
onChoosePlan?: () => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const usedUp = entitlement.trial?.exhausted === true
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Cloud className="size-4 text-muted-foreground" />
|
||||
<p className="text-sm font-medium">
|
||||
{t('auto.components.billing.trialProduct', 'Orca Cloud')}
|
||||
</p>
|
||||
<PlanStatusBadge entitlement={entitlement} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Progress
|
||||
value={includedUsagePercent(entitlement)}
|
||||
tone={usedUp ? 'warning' : includedUsageTone(entitlement)}
|
||||
aria-label={t('auto.components.billing.trialHoursUsedLabel', 'Trial sandbox hours used')}
|
||||
/>
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-2 text-xs tabular-nums">
|
||||
<span className="font-medium">{trialHoursUsedLine(entitlement, t)}</span>
|
||||
<span className="text-muted-foreground">{sandboxHoursLeftLine(entitlement, t)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground text-pretty">
|
||||
{usedUp
|
||||
? denyReasonCopy('trial_used_up', t, entitlement.canManageBilling)
|
||||
: t(
|
||||
'auto.components.billing.trialOneTime',
|
||||
'Trial hours are a one-time allowance and don’t reset. When they’re used up, choose a plan to keep going. No card needed until then.'
|
||||
)}
|
||||
</p>
|
||||
{onChoosePlan && entitlement.canManageBilling ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant={usedUp ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={onChoosePlan}
|
||||
>
|
||||
{t('auto.components.billing.choosePlan', 'Choose plan')}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
import { useState } from 'react'
|
||||
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
|
||||
import { cn } from '@/lib/class-names'
|
||||
import type { OrcaBillingUsageHistory } from '../../../../shared/orca-billing'
|
||||
import {
|
||||
usageBarPercent,
|
||||
usageChartMaxHours,
|
||||
usageDayLabel,
|
||||
usageDayLine
|
||||
} from './plan-billing-usage-history'
|
||||
|
||||
const HEIGHT_PX = 112
|
||||
|
||||
/**
|
||||
* Sandbox hours per day for the last 30 days: one series, so no legend (the heading names it).
|
||||
* Hover or arrow keys show a day's hours; a visually hidden table carries every value.
|
||||
*/
|
||||
export function UsageHistoryChart({
|
||||
days
|
||||
}: {
|
||||
days: OrcaBillingUsageHistory['days']
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const locale = useIntlLocale()
|
||||
const [active, setActive] = useState<number | null>(null)
|
||||
const maxHours = usageChartMaxHours(days)
|
||||
const ticks = [maxHours, maxHours / 2, 0]
|
||||
const activeDay = active === null ? null : days[active]
|
||||
const last = days.length - 1
|
||||
|
||||
const move = (event: React.KeyboardEvent<HTMLDivElement>): void => {
|
||||
const from = active ?? last
|
||||
const to =
|
||||
event.key === 'ArrowLeft'
|
||||
? Math.max(0, from - 1)
|
||||
: event.key === 'ArrowRight'
|
||||
? Math.min(last, from + 1)
|
||||
: event.key === 'Home'
|
||||
? 0
|
||||
: event.key === 'End'
|
||||
? last
|
||||
: null
|
||||
if (to !== null) {
|
||||
event.preventDefault()
|
||||
setActive(to)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex gap-2">
|
||||
{/* Y axis: hours, top / middle / zero. */}
|
||||
<div
|
||||
aria-hidden
|
||||
className="relative w-6 shrink-0 text-right text-[10px] leading-none tabular-nums text-muted-foreground"
|
||||
style={{ height: HEIGHT_PX }}
|
||||
>
|
||||
{ticks.map((tick) => (
|
||||
<span
|
||||
key={tick}
|
||||
className="absolute right-0 -translate-y-1/2"
|
||||
style={{ top: `${100 - (tick / maxHours) * 100}%` }}
|
||||
>
|
||||
{tick}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div
|
||||
role="group"
|
||||
tabIndex={0}
|
||||
aria-label={t(
|
||||
'auto.components.billing.usage.chartLabel',
|
||||
'Sandbox hours per day, last 30 days. Use the arrow keys to read each day.'
|
||||
)}
|
||||
onKeyDown={move}
|
||||
onFocus={() => setActive((current) => current ?? last)}
|
||||
onBlur={() => setActive(null)}
|
||||
onPointerLeave={() => setActive(null)}
|
||||
className="relative min-w-0 flex-1 rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
|
||||
style={{ height: HEIGHT_PX }}
|
||||
>
|
||||
{/* Hairline grid: top and middle; the baseline is drawn solid below. */}
|
||||
{ticks.slice(0, 2).map((tick) => (
|
||||
<div
|
||||
key={tick}
|
||||
aria-hidden
|
||||
className="absolute inset-x-0 border-t border-border/60"
|
||||
style={{ top: `${100 - (tick / maxHours) * 100}%` }}
|
||||
/>
|
||||
))}
|
||||
<div aria-hidden className="absolute inset-x-0 bottom-0 border-t border-border" />
|
||||
<div aria-hidden className="absolute inset-0 flex items-end gap-[2px]">
|
||||
{days.map((day, index) => (
|
||||
// The whole column is the hit target, not just the (often tiny) bar.
|
||||
<div
|
||||
key={day.start}
|
||||
className="flex h-full min-w-0 flex-1 items-end justify-center"
|
||||
onPointerEnter={() => setActive(index)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'w-full max-w-6 rounded-t-[4px]',
|
||||
index === active ? 'bg-chart-4 dark:bg-chart-1' : 'bg-chart-3 dark:bg-chart-2'
|
||||
)}
|
||||
style={{
|
||||
height: `${usageBarPercent(day.seconds, maxHours)}%`
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{activeDay && active !== null ? (
|
||||
<div
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute -top-1 z-10 -translate-y-full rounded-md border border-border bg-popover px-2 py-1 text-xs whitespace-nowrap text-popover-foreground shadow-sm"
|
||||
style={
|
||||
active > days.length / 2
|
||||
? { right: `${((last - active) / days.length) * 100}%` }
|
||||
: { left: `${(active / days.length) * 100}%` }
|
||||
}
|
||||
>
|
||||
{usageDayLine(activeDay, locale, t)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
aria-hidden
|
||||
className="flex justify-between pl-8 text-[10px] leading-none text-muted-foreground"
|
||||
>
|
||||
<span>{usageDayLabel(days[0]?.start ?? 0, locale)}</span>
|
||||
<span>{t('auto.components.billing.usage.today', 'Today')}</span>
|
||||
</div>
|
||||
{/* Screen readers: the active day as it changes, and every day in a table. */}
|
||||
<p role="status" className="sr-only">
|
||||
{activeDay ? usageDayLine(activeDay, locale, t) : ''}
|
||||
</p>
|
||||
<table className="sr-only">
|
||||
<caption>
|
||||
{t('auto.components.billing.usage.tableCaption', 'Sandbox hours per day')}
|
||||
</caption>
|
||||
<tbody>
|
||||
{days.map((day) => (
|
||||
<tr key={day.start}>
|
||||
<td>{usageDayLine(day, locale, t)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { useSyncExternalStore } from 'react'
|
||||
import { useAppStore } from '@/store'
|
||||
import { getOrcaAccountKey } from '@/hooks/use-orca-account-key'
|
||||
import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing'
|
||||
import { isActivePlan } from './team/team-seat-math'
|
||||
import { isActivePlan } from './plan-billing-format'
|
||||
|
||||
export type BillingSummary = {
|
||||
/** null until the first read answers (or when billing is off for this build/account). */
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
import { defineFixture } from '../../../component-fixtures/component-fixture'
|
||||
import { Dialog } from '@/components/ui/dialog'
|
||||
import { sampleOffers, sampleTeam } from '../plan-billing-fixtures'
|
||||
import { PlansDialogContent } from '../plans/PlansDialogContent'
|
||||
import { CheckoutPanel, type CheckoutPanelProps } from './CheckoutPanel'
|
||||
import { sampleCatalogResult } from '../plans/plan-catalog-fixtures'
|
||||
|
||||
const NOW = Date.UTC(2026, 10, 18, 15)
|
||||
const order = { planId: 'team', interval: 'month' as const, seats: 3 }
|
||||
const width = 1280
|
||||
|
||||
function Page({ phase }: { phase: CheckoutPanelProps['phase'] }): React.JSX.Element {
|
||||
return (
|
||||
<Dialog open modal={false}>
|
||||
<PlansDialogContent
|
||||
result={{ status: 'ok', entitlement: sampleTeam }}
|
||||
catalog={sampleCatalogResult}
|
||||
busy={false}
|
||||
notice={null}
|
||||
seats={3}
|
||||
onCheckout={() => {}}
|
||||
onManage={() => {}}
|
||||
onContactSales={() => {}}
|
||||
onRetry={() => {}}
|
||||
checkout={
|
||||
<CheckoutPanel
|
||||
phase={phase}
|
||||
team={sampleOffers.team}
|
||||
now={NOW}
|
||||
onReopen={() => {}}
|
||||
onKeepWaiting={() => {}}
|
||||
onBack={() => {}}
|
||||
contactUrl="https://orca.dev/enterprise"
|
||||
onContact={() => {}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export const opening = defineFixture({
|
||||
width,
|
||||
render: () => <Page phase={{ kind: 'opening', order }} />
|
||||
})
|
||||
export const awaitingPayment = defineFixture({
|
||||
width,
|
||||
render: () => <Page phase={{ kind: 'awaiting-payment', order, since: NOW }} />
|
||||
})
|
||||
export const paid = defineFixture({
|
||||
width,
|
||||
render: () => <Page phase={{ kind: 'paid', order, seats: 3 }} />
|
||||
})
|
||||
export const canceled = defineFixture({
|
||||
width,
|
||||
render: () => <Page phase={{ kind: 'canceled', order }} />
|
||||
})
|
||||
export const needsAttention = defineFixture({
|
||||
width,
|
||||
render: () => <Page phase={{ kind: 'needs-attention', order }} />
|
||||
})
|
||||
export const timedOut = defineFixture({
|
||||
width,
|
||||
render: () => <Page phase={{ kind: 'timed-out', order }} />
|
||||
})
|
||||
export const openFailed = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page phase={{ kind: 'open-failed', order, result: { status: 'failed', error: 'timeout' } }} />
|
||||
)
|
||||
})
|
||||
export const annual = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page
|
||||
phase={{
|
||||
kind: 'awaiting-payment',
|
||||
order: { planId: 'team', interval: 'year', seats: 5 },
|
||||
since: NOW
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
/** Billing's 409 plan_unavailable: Stripe has no price on sale. Try again, or contact us. */
|
||||
export const planUnavailable = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page phase={{ kind: 'open-failed', order, result: { status: 'plan-unavailable' } }} />
|
||||
)
|
||||
})
|
||||
@@ -1,52 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { sampleOffers } from '../plan-billing-fixtures'
|
||||
import { CheckoutPanel } from './CheckoutPanel'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const order = { planId: 'team', interval: 'month' as const, seats: 3 }
|
||||
|
||||
describe('checkout when billing cannot sell the plan (409 plan_unavailable)', () => {
|
||||
it('says so, retries, and offers a way to contact us', () => {
|
||||
const onReopen = vi.fn()
|
||||
const onContact = vi.fn()
|
||||
render(
|
||||
<CheckoutPanel
|
||||
phase={{ kind: 'open-failed', order, result: { status: 'plan-unavailable' } }}
|
||||
team={sampleOffers.team}
|
||||
now={Date.UTC(2026, 10, 12)}
|
||||
onReopen={onReopen}
|
||||
onKeepWaiting={() => {}}
|
||||
onBack={() => {}}
|
||||
contactUrl="https://orca.dev/enterprise"
|
||||
onContact={onContact}
|
||||
/>
|
||||
)
|
||||
expect(
|
||||
screen.getByRole('heading', { name: 'This plan isn’t available right now' })
|
||||
).toBeTruthy()
|
||||
fireEvent.click(screen.getByRole('button', { name: /Try again/ }))
|
||||
expect(onReopen).toHaveBeenCalled()
|
||||
fireEvent.click(screen.getByRole('button', { name: /Contact us/ }))
|
||||
expect(onContact).toHaveBeenCalledWith('https://orca.dev/enterprise')
|
||||
})
|
||||
|
||||
it('a generic failure keeps its own title and no contact action', () => {
|
||||
render(
|
||||
<CheckoutPanel
|
||||
phase={{ kind: 'open-failed', order, result: { status: 'failed', error: 'timeout' } }}
|
||||
team={sampleOffers.team}
|
||||
now={0}
|
||||
onReopen={() => {}}
|
||||
onKeepWaiting={() => {}}
|
||||
onBack={() => {}}
|
||||
contactUrl="https://orca.dev/enterprise"
|
||||
onContact={() => {}}
|
||||
/>
|
||||
)
|
||||
expect(screen.getByRole('heading', { name: 'Checkout didn’t open' })).toBeTruthy()
|
||||
expect(screen.queryByRole('button', { name: /Contact us/ })).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,305 +0,0 @@
|
||||
import { useEffect, useId, useRef } from 'react'
|
||||
import { AlertCircle, Check, ExternalLink, Lock, RotateCcw, XCircle } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
|
||||
import { cn } from '@/lib/class-names'
|
||||
import { openFailureCopy } from '../plan-billing-copy'
|
||||
import { formatCents, periodTotalCents } from '../plans/plans-pricing'
|
||||
import type { CheckoutPhase } from './checkout-flow'
|
||||
|
||||
export type CheckoutPanelProps = {
|
||||
phase: Exclude<CheckoutPhase, { kind: 'idle' }>
|
||||
/** The plan's name and per-seat prices (billing's catalog, or an older service's offers). */
|
||||
team: {
|
||||
label: string
|
||||
monthlyPriceCentsPerSeat: number | null
|
||||
annualPriceCentsPerSeat: number | null
|
||||
currency?: string
|
||||
}
|
||||
/** When the order was placed; the renewal date counts from it. */
|
||||
now: number
|
||||
onReopen: () => void
|
||||
onKeepWaiting: () => void
|
||||
onBack: () => void
|
||||
/** Where "Contact us" goes when billing can't sell the plan (the plan's supportUrl, else Enterprise's contact). */
|
||||
contactUrl?: string | null
|
||||
onContact?: (url: string) => void
|
||||
}
|
||||
|
||||
function OrderSummary({
|
||||
phase,
|
||||
team,
|
||||
now
|
||||
}: Pick<CheckoutPanelProps, 'phase' | 'team'> & { now: number }): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const locale = useIntlLocale()
|
||||
const { interval, seats } = phase.order
|
||||
const perSeat = interval === 'year' ? team.annualPriceCentsPerSeat : team.monthlyPriceCentsPerSeat
|
||||
const total = periodTotalCents(team, interval, seats)
|
||||
const renews = new Date(now)
|
||||
if (interval === 'year') {
|
||||
renews.setFullYear(renews.getFullYear() + 1)
|
||||
} else {
|
||||
renews.setMonth(renews.getMonth() + 1)
|
||||
}
|
||||
const renewsLabel = new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(renews)
|
||||
const seatCount = new Intl.NumberFormat(locale).format(seats)
|
||||
return (
|
||||
<div className="space-y-2 rounded-lg border border-border bg-muted/40 p-4 text-sm">
|
||||
<dl className="space-y-2">
|
||||
<div className="flex items-baseline justify-between gap-3">
|
||||
<dt className="font-medium">
|
||||
{interval === 'year'
|
||||
? t('auto.components.billing.checkout.planAnnual', '{{value0}} · Annual', {
|
||||
value0: team.label
|
||||
})
|
||||
: t('auto.components.billing.checkout.planMonthly', '{{value0}} · Monthly', {
|
||||
value0: team.label
|
||||
})}
|
||||
</dt>
|
||||
<dd className="text-muted-foreground tabular-nums">
|
||||
{perSeat === null
|
||||
? null
|
||||
: interval === 'year'
|
||||
? t(
|
||||
'auto.components.billing.checkout.lineItemYearly',
|
||||
'{{seats}} × {{price}} per seat, billed yearly',
|
||||
{
|
||||
count: seats,
|
||||
seats: seatCount,
|
||||
price: formatCents(perSeat, locale, team.currency),
|
||||
defaultValue_one: '{{seats}} × {{price}} per seat, billed yearly'
|
||||
}
|
||||
)
|
||||
: t(
|
||||
'auto.components.billing.checkout.lineItemMonthly',
|
||||
'{{seats}} × {{price}} per seat per month',
|
||||
{
|
||||
count: seats,
|
||||
seats: seatCount,
|
||||
price: formatCents(perSeat, locale, team.currency),
|
||||
defaultValue_one: '{{seats}} × {{price}} per seat per month'
|
||||
}
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
<div className="flex items-baseline justify-between gap-3 border-t border-border/60 pt-2">
|
||||
<dt className="font-medium">
|
||||
{phase.kind === 'paid'
|
||||
? t('auto.components.billing.checkout.paidRow', 'Paid')
|
||||
: t('auto.components.billing.checkout.dueToday', 'Due today')}
|
||||
</dt>
|
||||
<dd className="text-base font-semibold tabular-nums">
|
||||
{total === null ? '—' : formatCents(total, locale, team.currency)}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
'auto.components.billing.checkout.renewsNote',
|
||||
'Renews {{value0}}. Before tax. Seats follow your team.',
|
||||
{ value0: renewsLabel }
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function StatusIcon({ phase }: { phase: CheckoutPanelProps['phase'] }): React.JSX.Element {
|
||||
if (phase.kind === 'paid') {
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
className="flex size-11 items-center justify-center rounded-full border border-border bg-muted text-foreground animate-in zoom-in-50 fade-in-0 duration-300 motion-reduce:animate-none"
|
||||
>
|
||||
<Check className="size-6" strokeWidth={2.5} />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
if (phase.kind === 'canceled' || phase.kind === 'open-failed') {
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
className="flex size-11 items-center justify-center rounded-full bg-muted text-muted-foreground"
|
||||
>
|
||||
<XCircle className="size-5" />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
if (phase.kind === 'needs-attention' || phase.kind === 'timed-out') {
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
className="flex size-11 items-center justify-center rounded-full border border-status-warning-border bg-status-warning-background text-status-warning-text"
|
||||
>
|
||||
<AlertCircle className="size-5" />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<span aria-hidden className="relative flex size-11 items-center justify-center">
|
||||
<span className="absolute inset-0 rounded-full bg-foreground/5 motion-safe:animate-pulse" />
|
||||
<LoadingSpinner />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* What the plans dialog shows while Checkout runs in the browser: the order, what is happening,
|
||||
* and the next step. Announced politely so screen readers hear each change.
|
||||
*/
|
||||
export function CheckoutPanel(props: CheckoutPanelProps): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const { phase } = props
|
||||
const now = props.now
|
||||
const headingRef = useRef<HTMLHeadingElement>(null)
|
||||
const bodyId = useId()
|
||||
|
||||
// Move focus with the state so keyboard users land on the new message and its actions.
|
||||
useEffect(() => {
|
||||
headingRef.current?.focus()
|
||||
}, [phase.kind])
|
||||
|
||||
let title: string
|
||||
let body: string
|
||||
switch (phase.kind) {
|
||||
case 'opening':
|
||||
title = t('auto.components.billing.checkout.opening', 'Opening secure checkout…')
|
||||
body = t(
|
||||
'auto.components.billing.checkout.openingBody',
|
||||
'Stripe’s checkout opens in your browser.'
|
||||
)
|
||||
break
|
||||
case 'awaiting-payment':
|
||||
title = t('auto.components.billing.checkout.finish', 'Finish payment in your browser')
|
||||
body = t(
|
||||
'auto.components.billing.checkout.finishBody',
|
||||
'This updates the moment Stripe confirms. Your card details go to Stripe, never to Orca.'
|
||||
)
|
||||
break
|
||||
case 'paid':
|
||||
title = t('auto.components.billing.checkout.paid', 'Payment confirmed')
|
||||
body = t(
|
||||
'auto.components.billing.checkout.paidBody2',
|
||||
'{{value0}} plan is active. Opening your team…',
|
||||
{ value0: props.team.label }
|
||||
)
|
||||
break
|
||||
case 'canceled':
|
||||
title = t('auto.components.billing.checkout.canceled', 'Checkout canceled')
|
||||
body = t(
|
||||
'auto.components.billing.checkout.canceledBody2',
|
||||
'Nothing was charged. You can choose a plan again any time.'
|
||||
)
|
||||
break
|
||||
case 'needs-attention':
|
||||
title = t('auto.components.billing.checkout.attention2', 'Stripe needs one more step')
|
||||
body = t(
|
||||
'auto.components.billing.checkout.attentionBody',
|
||||
'Your bank asked for verification or declined the card. Reopen checkout to finish, or use another card.'
|
||||
)
|
||||
break
|
||||
case 'timed-out':
|
||||
title = t('auto.components.billing.checkout.timedOut', 'Still waiting for Stripe')
|
||||
body = t(
|
||||
'auto.components.billing.checkout.timedOutBody',
|
||||
'If you already paid, confirmation can take a minute. Otherwise reopen checkout.'
|
||||
)
|
||||
break
|
||||
case 'open-failed':
|
||||
title =
|
||||
phase.result.status === 'plan-unavailable'
|
||||
? t(
|
||||
'auto.components.billing.checkout.planUnavailableTitle',
|
||||
'This plan isn’t available right now'
|
||||
)
|
||||
: t('auto.components.billing.checkout.openFailed', 'Checkout didn’t open')
|
||||
body =
|
||||
openFailureCopy(phase.result, t) ??
|
||||
t('auto.components.billing.openFailed', 'Couldn’t reach billing. Try again.')
|
||||
break
|
||||
}
|
||||
|
||||
const reopen = (
|
||||
<Button type="button" onClick={props.onReopen}>
|
||||
{phase.kind === 'canceled' || phase.kind === 'open-failed' ? <RotateCcw /> : null}
|
||||
{phase.kind === 'canceled' || phase.kind === 'open-failed'
|
||||
? t('auto.components.billing.checkout.tryAgain', 'Try again')
|
||||
: t('auto.components.billing.checkout.reopen', 'Reopen checkout')}
|
||||
{phase.kind === 'canceled' || phase.kind === 'open-failed' ? null : <ExternalLink />}
|
||||
</Button>
|
||||
)
|
||||
const back = (
|
||||
<Button type="button" variant="ghost" onClick={props.onBack}>
|
||||
{phase.kind === 'awaiting-payment' || phase.kind === 'opening'
|
||||
? t('auto.components.billing.checkout.cancel', 'Cancel')
|
||||
: t('auto.components.billing.checkout.back', 'Back to plans')}
|
||||
</Button>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-md flex-col gap-5 py-2">
|
||||
{/* Focus moves to the heading on each change (described by the body), which screen
|
||||
readers announce once; no separate live region, so nothing is read twice. */}
|
||||
<div className="flex flex-col items-center gap-3 text-center">
|
||||
<StatusIcon phase={phase} />
|
||||
<h3
|
||||
ref={headingRef}
|
||||
tabIndex={-1}
|
||||
aria-describedby={bodyId}
|
||||
className="text-lg font-semibold tracking-tight outline-none"
|
||||
>
|
||||
{title}
|
||||
</h3>
|
||||
<p
|
||||
id={bodyId}
|
||||
className={cn(
|
||||
'max-w-sm text-sm text-pretty',
|
||||
// Unavailable is not the buyer's error: the title and icon carry it, the body stays muted.
|
||||
phase.kind === 'open-failed' && phase.result.status !== 'plan-unavailable'
|
||||
? 'text-destructive'
|
||||
: 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{body}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<OrderSummary phase={phase} team={props.team} now={now} />
|
||||
|
||||
{phase.kind === 'paid' ? null : (
|
||||
<div className="flex flex-wrap items-center justify-center gap-2">
|
||||
{phase.kind === 'opening' ? null : reopen}
|
||||
{phase.kind === 'open-failed' &&
|
||||
phase.result.status === 'plan-unavailable' &&
|
||||
props.contactUrl &&
|
||||
props.onContact ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => props.contactUrl && props.onContact?.(props.contactUrl)}
|
||||
>
|
||||
{t('auto.components.billing.checkout.contactUs', 'Contact us')}
|
||||
<ExternalLink />
|
||||
</Button>
|
||||
) : null}
|
||||
{phase.kind === 'timed-out' ? (
|
||||
<Button type="button" variant="outline" onClick={props.onKeepWaiting}>
|
||||
{t('auto.components.billing.checkout.keepWaiting', 'Keep waiting')}
|
||||
</Button>
|
||||
) : null}
|
||||
{back}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="flex items-center justify-center gap-1.5 text-xs text-muted-foreground">
|
||||
<Lock className="size-3" />
|
||||
{t(
|
||||
'auto.components.billing.checkout.secured2',
|
||||
'Payments by Stripe · Cards, Apple Pay and Link · Bank verification'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { sampleTeam } from '../plan-billing-fixtures'
|
||||
import { checkoutPollVerdict, nextPhaseAfterOpen } from './checkout-flow'
|
||||
|
||||
const order = { planId: 'team', interval: 'month' as const, seats: 2 }
|
||||
|
||||
describe('checkoutPollVerdict', () => {
|
||||
it('waits until a subscription exists', () => {
|
||||
expect(checkoutPollVerdict({ ...sampleTeam, plan: null, status: 'none' })).toBe('waiting')
|
||||
})
|
||||
it('is paid once the subscription is active or trialing', () => {
|
||||
expect(checkoutPollVerdict(sampleTeam)).toBe('paid')
|
||||
expect(checkoutPollVerdict({ ...sampleTeam, status: 'trialing' })).toBe('paid')
|
||||
})
|
||||
it('flags a first invoice that needs action (3-D Secure, decline)', () => {
|
||||
expect(checkoutPollVerdict({ ...sampleTeam, status: 'incomplete' })).toBe('needs-attention')
|
||||
expect(checkoutPollVerdict({ ...sampleTeam, status: 'past_due' })).toBe('needs-attention')
|
||||
})
|
||||
})
|
||||
|
||||
describe('nextPhaseAfterOpen', () => {
|
||||
it('awaits payment when the browser opened', () => {
|
||||
expect(nextPhaseAfterOpen(order, { status: 'opened' }, 5)).toEqual({
|
||||
kind: 'awaiting-payment',
|
||||
order,
|
||||
since: 5
|
||||
})
|
||||
})
|
||||
it('reports why Checkout could not open', () => {
|
||||
expect(nextPhaseAfterOpen(order, { status: 'forbidden' }, 5)).toEqual({
|
||||
kind: 'open-failed',
|
||||
order,
|
||||
result: { status: 'forbidden' }
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,68 +0,0 @@
|
||||
// The in-app half of Checkout. Payment itself happens on Stripe's hosted page in the system
|
||||
// browser (Apple Pay, Link, password-manager autofill, 3-D Secure and a URL bar the user can
|
||||
// verify; card data never enters Orca). This tracks the order, waits for the subscription to
|
||||
// appear, and decides what the plans dialog shows meanwhile.
|
||||
import type {
|
||||
OrcaBillingEntitlement,
|
||||
OrcaBillingInterval,
|
||||
OrcaBillingOpenResult
|
||||
} from '../../../../../shared/orca-billing'
|
||||
|
||||
/** `planId`: billing's catalog plan; billing resolves the Stripe price for it. */
|
||||
export type CheckoutOrder = { planId: string; interval: OrcaBillingInterval; seats: number }
|
||||
|
||||
export type CheckoutPhase =
|
||||
| { kind: 'idle' }
|
||||
/** Asking billing for a Checkout session; the browser is about to open. */
|
||||
| { kind: 'opening'; order: CheckoutOrder }
|
||||
/** Stripe's page is open in the browser; polling for the subscription. */
|
||||
| { kind: 'awaiting-payment'; order: CheckoutOrder; since: number }
|
||||
/** Paid: a short confirmation before landing on the Team page. */
|
||||
| { kind: 'paid'; order: CheckoutOrder; seats: number }
|
||||
/** The browser came back from Stripe's cancel link. Nothing was charged. */
|
||||
| { kind: 'canceled'; order: CheckoutOrder }
|
||||
/** Stripe took the card but the first invoice needs action (3-D Secure, decline). */
|
||||
| { kind: 'needs-attention'; order: CheckoutOrder }
|
||||
/** No payment arrived within the watch window; the user can keep waiting or reopen. */
|
||||
| { kind: 'timed-out'; order: CheckoutOrder }
|
||||
/** Billing refused to open Checkout; `copy` explains why. */
|
||||
| { kind: 'open-failed'; order: CheckoutOrder; result: OrcaBillingOpenResult }
|
||||
|
||||
/** Poll cadence and window while Stripe's page is open (design review M3). */
|
||||
export const CHECKOUT_POLL_MS = 2_000
|
||||
export const CHECKOUT_WATCH_MS = 3 * 60_000
|
||||
/** After the window, or while the bank wants a step: keep listening, gently. */
|
||||
export const CHECKOUT_SLOW_POLL_MS = 10_000
|
||||
export const CHECKOUT_SLOW_WATCH_MS = 15 * 60_000
|
||||
|
||||
export type CheckoutPollVerdict = 'paid' | 'needs-attention' | 'waiting'
|
||||
|
||||
/** Reads one entitlement poll while awaiting payment. */
|
||||
export function checkoutPollVerdict(entitlement: OrcaBillingEntitlement): CheckoutPollVerdict {
|
||||
if (entitlement.plan === null) {
|
||||
return 'waiting'
|
||||
}
|
||||
if (entitlement.status === 'active' || entitlement.status === 'trialing') {
|
||||
return 'paid'
|
||||
}
|
||||
// A subscription exists but its first invoice is unpaid (3-D Secure abandoned, card declined).
|
||||
if (entitlement.status === 'incomplete' || entitlement.status === 'past_due') {
|
||||
return 'needs-attention'
|
||||
}
|
||||
return 'waiting'
|
||||
}
|
||||
|
||||
export function nextPhaseAfterOpen(
|
||||
order: CheckoutOrder,
|
||||
result: OrcaBillingOpenResult,
|
||||
now: number
|
||||
): CheckoutPhase {
|
||||
if (result.status === 'opened') {
|
||||
return { kind: 'awaiting-payment', order, since: now }
|
||||
}
|
||||
return { kind: 'open-failed', order, result }
|
||||
}
|
||||
|
||||
export function isCheckoutActive(phase: CheckoutPhase): boolean {
|
||||
return phase.kind !== 'idle' && phase.kind !== 'open-failed'
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import { useAppStore } from '@/store/index'
|
||||
import {
|
||||
takeOrcaCloudCheckoutReturn,
|
||||
emitOrcaCloudCheckoutReturn
|
||||
} from '@/lib/orca-cloud-after-checkout'
|
||||
import { requestOrcaCloudSelectionAfterSignIn } from '@/lib/orca-cloud-select-after-sign-in'
|
||||
import { invalidateOrcaCloudBilling } from '@/components/new-workspace/orca-cloud-billing-cache'
|
||||
import { ORCA_CLOUD_RECIPE_ID } from '../../../../../shared/hosted-sandbox/orca-cloud-recipe-id'
|
||||
import { closePlansPage } from '../plans/plans-page-store'
|
||||
import { closeTeamPage, openTeamPage } from '../team/team-page-store'
|
||||
|
||||
/**
|
||||
* A paid Checkout closes the plans page and goes back to the work that hit the wall: the open
|
||||
* composer with Orca Cloud picked, or the refused create, retried. Without an intent it lands on
|
||||
* the Team page's "You're on Team" confirmation.
|
||||
*/
|
||||
export function returnAfterPaidCheckout(paidSeats: number): void {
|
||||
closePlansPage()
|
||||
const store = useAppStore.getState()
|
||||
const target = takeOrcaCloudCheckoutReturn({
|
||||
composerOpen: store.activeModal === 'new-workspace-composer',
|
||||
hasCreation: (creationId) => Boolean(store.pendingWorktreeCreations[creationId])
|
||||
})
|
||||
if (target.kind === 'team-page') {
|
||||
openTeamPage({ kind: 'checkout-success', seats: paidSeats })
|
||||
return
|
||||
}
|
||||
closeTeamPage()
|
||||
// The Run-on row cached "no plan"; read the new entitlement now so it shows hours, not Upgrade.
|
||||
invalidateOrcaCloudBilling()
|
||||
switch (target.kind) {
|
||||
case 'retry':
|
||||
// Lazy: the creation flow's import graph is heavy and billing never needs it otherwise.
|
||||
void import('@/lib/workspace/creation/worktree-creation-flow').then(
|
||||
({ retryBackgroundWorktreeCreation }) => retryBackgroundWorktreeCreation(target.creationId)
|
||||
)
|
||||
return
|
||||
case 'select-in-composer':
|
||||
// The composer's recipe list reloads and consumes this, as it does after signing in.
|
||||
requestOrcaCloudSelectionAfterSignIn()
|
||||
emitOrcaCloudCheckoutReturn()
|
||||
return
|
||||
case 'open-composer':
|
||||
store.openModal('new-workspace-composer', {
|
||||
initialEphemeralVmRecipeId: ORCA_CLOUD_RECIPE_ID,
|
||||
telemetrySource: 'unknown'
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { OrcaBillingOpenResult } from '../../../../../shared/orca-billing'
|
||||
import { getBillingGeneration, recordBillingStatusIfCurrent } from '../billing-summary-store'
|
||||
import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval'
|
||||
import {
|
||||
activeCloudSetupSessionId,
|
||||
startCloudSetupSession
|
||||
} from '@/lib/orca-cloud/cloud-setup-session'
|
||||
import {
|
||||
CHECKOUT_POLL_MS,
|
||||
CHECKOUT_SLOW_POLL_MS,
|
||||
CHECKOUT_SLOW_WATCH_MS,
|
||||
CHECKOUT_WATCH_MS,
|
||||
checkoutPollVerdict,
|
||||
nextPhaseAfterOpen,
|
||||
type CheckoutOrder,
|
||||
type CheckoutPhase
|
||||
} from './checkout-flow'
|
||||
|
||||
/** How long the "paid" check shows before the Team page takes over. */
|
||||
export const PAID_HANDOFF_MS = 2_200
|
||||
|
||||
export type CheckoutFlow = {
|
||||
phase: CheckoutPhase
|
||||
start: (order: CheckoutOrder) => void
|
||||
/** Opens a fresh Checkout session for the same order. */
|
||||
reopen: () => void
|
||||
/** Restarts the watch window after a timeout. */
|
||||
keepWaiting: () => void
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Drives Checkout from the plans dialog. Polls the entitlement every 2 s for up to 3 min while
|
||||
* Stripe's page is open, and also reacts at once to the orca://billing/return link.
|
||||
*/
|
||||
export function useCheckoutFlow({ onPaid }: { onPaid: (seats: number) => void }): CheckoutFlow {
|
||||
const [phase, setPhase] = useState<CheckoutPhase>({ kind: 'idle' })
|
||||
const [watchKey, setWatchKey] = useState(0)
|
||||
const onPaidRef = useRef(onPaid)
|
||||
useEffect(() => {
|
||||
onPaidRef.current = onPaid
|
||||
}, [onPaid])
|
||||
const runId = useRef(0)
|
||||
|
||||
const start = useCallback((order: CheckoutOrder) => {
|
||||
const id = ++runId.current
|
||||
setPhase({ kind: 'opening', order })
|
||||
// Joins an open setup session, so Checkout returns to its next step (T2 Compare plans).
|
||||
const setupSessionId = activeCloudSetupSessionId()
|
||||
void window.api.orcaProfiles
|
||||
.billingOpenCheckout({
|
||||
plan: order.planId,
|
||||
interval: order.interval,
|
||||
seats: order.seats,
|
||||
...(setupSessionId ? { setupSessionId } : {})
|
||||
})
|
||||
.catch((error: unknown): OrcaBillingOpenResult => ({
|
||||
status: 'failed',
|
||||
error: String(error)
|
||||
}))
|
||||
.then(async (result): Promise<OrcaBillingOpenResult> => {
|
||||
if (result.status !== 'team-required') {
|
||||
return result
|
||||
}
|
||||
// O1: a plan always lands on a team. The browser makes or picks the team, then Checkout;
|
||||
// the setup session switches this profile to that team when it's there.
|
||||
const started = await startCloudSetupSession({ needs: ['team', 'plan'], chooseTeam: true })
|
||||
return started && 'sessionId' in started ? { status: 'opened' } : result
|
||||
})
|
||||
.then((result) => {
|
||||
if (id === runId.current) {
|
||||
setPhase(nextPhaseAfterOpen(order, result, Date.now()))
|
||||
}
|
||||
})
|
||||
}, [])
|
||||
|
||||
const reset = useCallback(() => {
|
||||
runId.current++
|
||||
setPhase({ kind: 'idle' })
|
||||
}, [])
|
||||
|
||||
// Watch while a payment can still land: fast while Stripe's page is open, slower after the
|
||||
// window ends or when the bank asked for a step (3-D Secure can finish minutes later).
|
||||
const watching =
|
||||
phase.kind === 'awaiting-payment' ||
|
||||
phase.kind === 'timed-out' ||
|
||||
phase.kind === 'needs-attention'
|
||||
? phase
|
||||
: null
|
||||
|
||||
useEffect(() => {
|
||||
if (!watching) {
|
||||
return
|
||||
}
|
||||
const order = watching.order
|
||||
let disposed = false
|
||||
let inFlight = false
|
||||
// A cancel link that lands mid-poll waits for that poll's answer instead of being dropped.
|
||||
let pendingUnpaid: (() => void) | undefined
|
||||
const check = (onUnpaid?: () => void): void => {
|
||||
if (onUnpaid) {
|
||||
pendingUnpaid = onUnpaid
|
||||
}
|
||||
if (inFlight) {
|
||||
return
|
||||
}
|
||||
inFlight = true
|
||||
const startedGeneration = getBillingGeneration()
|
||||
void window.api.orcaProfiles
|
||||
.billingStatus()
|
||||
.catch(() => null)
|
||||
.then((result) => {
|
||||
inFlight = false
|
||||
if (disposed || result?.status !== 'ok') {
|
||||
return
|
||||
}
|
||||
recordBillingStatusIfCurrent(startedGeneration, result)
|
||||
const unpaid = pendingUnpaid
|
||||
pendingUnpaid = undefined
|
||||
const verdict = checkoutPollVerdict(result.entitlement)
|
||||
if (verdict === 'paid') {
|
||||
setPhase({ kind: 'paid', order, seats: result.entitlement.seats })
|
||||
} else if (verdict === 'needs-attention' && watching.kind !== 'needs-attention') {
|
||||
setPhase({ kind: 'needs-attention', order })
|
||||
} else {
|
||||
unpaid?.()
|
||||
}
|
||||
})
|
||||
}
|
||||
const poll = (): void => check()
|
||||
// Paused while the window is hidden; becoming visible checks at once.
|
||||
const stopPolling = installWindowVisibilityInterval({
|
||||
run: poll,
|
||||
intervalMs: watching.kind === 'awaiting-payment' ? CHECKOUT_POLL_MS : CHECKOUT_SLOW_POLL_MS
|
||||
})
|
||||
const deadline =
|
||||
watching.kind === 'awaiting-payment'
|
||||
? window.setTimeout(
|
||||
() => setPhase({ kind: 'timed-out', order }),
|
||||
Math.max(0, watching.since + CHECKOUT_WATCH_MS - Date.now())
|
||||
)
|
||||
: // Slow watch ends after a while; window focus and the return link still check.
|
||||
window.setTimeout(stopPolling, CHECKOUT_SLOW_WATCH_MS)
|
||||
window.addEventListener('focus', poll)
|
||||
const disposeReturn = window.api.orcaProfiles.onBillingReturn?.((event) => {
|
||||
// Any local app can open an orca:// link, so "canceled" is shown only after billing
|
||||
// confirms there is still no paid plan.
|
||||
check(
|
||||
event.kind === 'checkout-cancel' ? () => setPhase({ kind: 'canceled', order }) : undefined
|
||||
)
|
||||
})
|
||||
return () => {
|
||||
disposed = true
|
||||
stopPolling()
|
||||
window.clearTimeout(deadline)
|
||||
window.removeEventListener('focus', poll)
|
||||
disposeReturn?.()
|
||||
}
|
||||
// watchKey restarts the window after "Keep waiting".
|
||||
}, [watching, watchKey])
|
||||
|
||||
// Hand off to the Team page after the check has had a moment.
|
||||
const paidSeats = phase.kind === 'paid' ? phase.seats : null
|
||||
useEffect(() => {
|
||||
if (paidSeats === null) {
|
||||
return
|
||||
}
|
||||
const timer = window.setTimeout(() => onPaidRef.current(paidSeats), PAID_HANDOFF_MS)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [paidSeats])
|
||||
|
||||
const order = phase.kind === 'idle' ? null : phase.order
|
||||
const reopen = useCallback(() => {
|
||||
if (order) {
|
||||
start(order)
|
||||
}
|
||||
}, [order, start])
|
||||
const keepWaiting = useCallback(() => {
|
||||
if (order) {
|
||||
setPhase({ kind: 'awaiting-payment', order, since: Date.now() })
|
||||
setWatchKey((key) => key + 1)
|
||||
}
|
||||
}, [order])
|
||||
|
||||
return { phase, start, reopen, keepWaiting, reset }
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
import { useState } from 'react'
|
||||
import { Check, LoaderCircle } from 'lucide-react'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import type { OrcaBillingEntitlement } from '../../../../shared/orca-billing'
|
||||
|
||||
/**
|
||||
* Where an overage change stands. `saving` lasts while the request is in flight and always ends:
|
||||
* in `saved` once billing accepts it (or the card already reads the new state), or in `error`.
|
||||
* It never outlives the request: a flag that stayed set after Turn off hid the Turn on button
|
||||
* behind a stuck "✓ Saving…" (OVERAGE-REENABLE).
|
||||
*/
|
||||
export type OverageSaveState = 'idle' | 'saving' | 'saved' | 'error'
|
||||
|
||||
/** Which control made the change: its status shows next to that control (design-squad). */
|
||||
export type OverageAction = 'on' | 'off' | 'cap'
|
||||
|
||||
/** What a pending change asks for; a null cap means billing's default (or, when off, none). */
|
||||
export type OverageTarget = { action: OverageAction; optedIn: boolean; capCents: number | null }
|
||||
|
||||
export function overageMatches(
|
||||
overage: OrcaBillingEntitlement['overage'],
|
||||
target: OverageTarget
|
||||
): boolean {
|
||||
if (overage.optedIn !== target.optedIn) {
|
||||
return false
|
||||
}
|
||||
return !target.optedIn || target.capCents === null || overage.spendCapCents === target.capCents
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks one change from Save / Turn on / Turn off to its end. `busy` is the parent's request
|
||||
* flag and `failures` its failure count; `onFailure` runs (during render) when a change fails.
|
||||
*/
|
||||
export function useOverageSaveState({
|
||||
overage,
|
||||
busy,
|
||||
failures,
|
||||
onFailure
|
||||
}: {
|
||||
overage: OrcaBillingEntitlement['overage']
|
||||
busy: boolean
|
||||
failures: number
|
||||
onFailure: () => void
|
||||
}): {
|
||||
status: OverageSaveState
|
||||
/** The control behind the last change; null before the first one. */
|
||||
action: OverageAction | null
|
||||
begin: (target: OverageTarget) => void
|
||||
/** Back to no status, e.g. once the field is edited again (review M13). */
|
||||
clear: () => void
|
||||
} {
|
||||
const [saveState, setSaveState] = useState<OverageSaveState>('idle')
|
||||
const [target, setTarget] = useState<OverageTarget | null>(null)
|
||||
const [action, setAction] = useState<OverageAction | null>(null)
|
||||
// Whether the parent has reported the request in flight since this change began.
|
||||
const [sawBusy, setSawBusy] = useState(false)
|
||||
const [seenFailures, setSeenFailures] = useState(failures)
|
||||
// Render-time adjustment (no effect), so no frame shows a finished change as "Saving…".
|
||||
let status = saveState
|
||||
if (seenFailures !== failures) {
|
||||
setSeenFailures(failures)
|
||||
onFailure()
|
||||
if (status === 'saving') {
|
||||
status = 'error'
|
||||
setSaveState('error')
|
||||
setTarget(null)
|
||||
}
|
||||
} else if (status === 'saving') {
|
||||
if (busy) {
|
||||
if (!sawBusy) {
|
||||
setSawBusy(true)
|
||||
}
|
||||
} else if (sawBusy || (target !== null && overageMatches(overage, target))) {
|
||||
// The request finished without a failure, or the card already reads the new state.
|
||||
status = 'saved'
|
||||
setSaveState('saved')
|
||||
setTarget(null)
|
||||
}
|
||||
}
|
||||
return {
|
||||
status,
|
||||
action,
|
||||
begin: (next) => {
|
||||
setSaveState('saving')
|
||||
setAction(next.action)
|
||||
setSawBusy(false)
|
||||
setTarget(next)
|
||||
},
|
||||
clear: () => {
|
||||
if (status !== 'saving') {
|
||||
setSaveState('idle')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One status for both views: a spinner while saving; the check only ever goes with "Saved". */
|
||||
export function OverageSaveStatus({
|
||||
status,
|
||||
action
|
||||
}: {
|
||||
status: OverageSaveState
|
||||
action: OverageAction | null
|
||||
}): React.JSX.Element | null {
|
||||
const t = useTranslate()
|
||||
if (status === 'idle') {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<span
|
||||
role="status"
|
||||
className={
|
||||
status === 'error'
|
||||
? 'flex h-9 items-center gap-1 text-xs text-destructive'
|
||||
: 'flex h-9 items-center gap-1 text-xs text-muted-foreground'
|
||||
}
|
||||
>
|
||||
{status === 'saving' ? (
|
||||
<>
|
||||
<LoaderCircle className="size-3.5 animate-spin" aria-hidden />
|
||||
{t('auto.components.billing.capSaving', 'Saving…')}
|
||||
</>
|
||||
) : status === 'saved' ? (
|
||||
<>
|
||||
<Check className="size-3.5" aria-hidden />
|
||||
{t('auto.components.billing.capSaved', 'Saved')}
|
||||
</>
|
||||
) : action === 'off' ? (
|
||||
t('components.billing.overage.turnOffFailed', 'Couldn’t turn off overage.')
|
||||
) : action === 'on' ? (
|
||||
t('components.billing.overage.turnOnFailed', 'Couldn’t turn on overage.')
|
||||
) : (
|
||||
t('auto.components.billing.capNotSaved', 'Couldn’t save')
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -2,10 +2,9 @@
|
||||
import type { Translate } from '@/i18n/use-translate'
|
||||
import type {
|
||||
OrcaBillingDenyReason,
|
||||
OrcaBillingOpenResult,
|
||||
OrcaBillingOverageResult
|
||||
} from '../../../../shared/orca-billing'
|
||||
import { formatCents } from './plans/plans-pricing'
|
||||
import { formatCents } from '../../../../shared/orca-billing-usage-alerts'
|
||||
|
||||
export function denyReasonCopy(
|
||||
reason: OrcaBillingDenyReason,
|
||||
@@ -104,49 +103,7 @@ export function statusLabel(status: string, t: Translate): string {
|
||||
}
|
||||
}
|
||||
|
||||
export function openFailureCopy(result: OrcaBillingOpenResult, t: Translate): string | null {
|
||||
switch (result.status) {
|
||||
case 'opened':
|
||||
return null
|
||||
case 'forbidden':
|
||||
return t(
|
||||
'auto.components.billing.openForbidden2',
|
||||
'Only an owner or admin can manage billing.'
|
||||
)
|
||||
case 'already-subscribed':
|
||||
return t(
|
||||
'auto.components.billing.openAlreadySubscribed',
|
||||
'This account already has a plan. Use Manage billing to change it.'
|
||||
)
|
||||
case 'team-required':
|
||||
return t(
|
||||
'auto.components.billing.openTeamRequired',
|
||||
'Plans belong to a team. Create a team, then choose a plan.'
|
||||
)
|
||||
case 'no-billing-account':
|
||||
return t(
|
||||
'auto.components.billing.openNoAccount',
|
||||
'There is no billing account yet. Choose a plan first.'
|
||||
)
|
||||
case 'signed-out':
|
||||
return t(
|
||||
'auto.components.billing.openSignedOut2',
|
||||
'Sign in to Orca again to manage your team.'
|
||||
)
|
||||
case 'plan-unavailable':
|
||||
return t(
|
||||
'auto.components.billing.openPlanUnavailable',
|
||||
'Checkout for this plan isn’t working right now. Try again in a few minutes, or contact us and we’ll set you up.'
|
||||
)
|
||||
case 'unconfigured':
|
||||
return t('auto.components.billing.openUnconfigured', 'Billing is unavailable in this build.')
|
||||
case 'failed':
|
||||
return t('auto.components.billing.openFailed', 'Couldn’t reach billing. Try again.')
|
||||
}
|
||||
}
|
||||
|
||||
/** "The spend cap can be at most $5,000." */
|
||||
export function capTooHighCopy(maxCents: number, locale: string, t: Translate): string {
|
||||
function capTooHighCopy(maxCents: number, locale: string, t: Translate): string {
|
||||
return t('auto.components.billing.capAtMost', 'The spend cap can be at most {{max}}.', {
|
||||
max: formatCents(maxCents, locale)
|
||||
})
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
// Shared sample entitlements for billing tests and component fixtures.
|
||||
import type {
|
||||
OrcaBillingEntitlement,
|
||||
OrcaBillingOffers,
|
||||
OrcaBillingUsageHistory
|
||||
} from '../../../../shared/orca-billing'
|
||||
import type { UsageNames } from './plan-billing-usage-history'
|
||||
import type { OrcaBillingEntitlement, OrcaBillingOffers } from '../../../../shared/orca-billing'
|
||||
import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../shared/hosted-sandbox/hosted-sandbox-wire'
|
||||
|
||||
const HOUR = 3600
|
||||
@@ -94,56 +89,3 @@ export const sampleTrialUsedUp: OrcaBillingEntitlement = {
|
||||
canStartSandbox: false,
|
||||
reason: 'trial_used_up'
|
||||
}
|
||||
|
||||
const DAY_MS = 24 * 3600 * 1000
|
||||
// Hours per day, oldest first: quiet weekends, a busy release week and today in progress.
|
||||
const DAILY_HOURS = [
|
||||
0.5, 1.2, 0, 0, 2.4, 3.1, 1.8, 2.2, 0.9, 0, 0, 1.4, 2.8, 4.6, 5.2, 3.9, 0.3, 0, 1.1, 2, 1.7, 2.6,
|
||||
0.8, 0, 0, 1.9, 3.4, 2.1, 1.5, 0.6
|
||||
]
|
||||
const HISTORY_START = Date.UTC(2026, 9, 12, 7)
|
||||
|
||||
export const sampleUsageHistory: OrcaBillingUsageHistory = {
|
||||
days: DAILY_HOURS.map((hours, index) => ({
|
||||
start: HISTORY_START + index * DAY_MS,
|
||||
seconds: Math.round(hours * HOUR)
|
||||
})),
|
||||
totalSeconds: Math.round(DAILY_HOURS.reduce((sum, hours) => sum + hours, 0) * HOUR),
|
||||
yourSeconds: 18.4 * HOUR,
|
||||
members: {
|
||||
top: [
|
||||
{ id: 'u-neil', seconds: 18.4 * HOUR },
|
||||
{ id: 'u-grace', seconds: 15.1 * HOUR },
|
||||
{ id: 'u-linus', seconds: 8.6 * HOUR },
|
||||
{ id: 'u-gone', seconds: 4.2 * HOUR }
|
||||
],
|
||||
otherCount: 0,
|
||||
otherSeconds: 1.7 * HOUR
|
||||
},
|
||||
sandboxes: {
|
||||
top: [
|
||||
{ id: 'sbx_checkout', seconds: 14.2 * HOUR },
|
||||
{ id: 'sbx_ledger', seconds: 11 * HOUR },
|
||||
{ id: 'sbx_docs', seconds: 7.3 * HOUR },
|
||||
{ id: 'sbx_gone', seconds: 5.9 * HOUR },
|
||||
{ id: 'sbx_deleted', seconds: 3.1 * HOUR }
|
||||
],
|
||||
otherCount: 4,
|
||||
otherSeconds: 6.5 * HOUR
|
||||
}
|
||||
}
|
||||
|
||||
export const sampleUsageNames: UsageNames = {
|
||||
selfId: 'u-neil',
|
||||
members: new Map([
|
||||
['u-neil', 'Neil Parker'],
|
||||
['u-grace', 'Grace Hopper'],
|
||||
['u-linus', 'Linus Torvalds']
|
||||
]),
|
||||
workspaces: new Map([
|
||||
['sbx_checkout', 'Checkout retries'],
|
||||
['sbx_ledger', 'Ledger migration'],
|
||||
['sbx_docs', 'Docs search'],
|
||||
['sbx_flaky', 'Flaky e2e repro']
|
||||
])
|
||||
}
|
||||
|
||||
@@ -66,3 +66,14 @@ export function formatDollars(cents: number): string {
|
||||
const dollars = Math.max(0, cents) / 100
|
||||
return Number.isInteger(dollars) ? `$${dollars}` : `$${dollars.toFixed(2)}`
|
||||
}
|
||||
|
||||
/** A plan that is in force now (not canceled, never started, or lapsed before it began). */
|
||||
export function isActivePlan(entitlement: OrcaBillingEntitlement | null): boolean {
|
||||
return Boolean(
|
||||
entitlement &&
|
||||
entitlement.plan !== null &&
|
||||
entitlement.status !== 'canceled' &&
|
||||
entitlement.status !== 'none' &&
|
||||
entitlement.status !== 'incomplete_expired'
|
||||
)
|
||||
}
|
||||
|
||||
@@ -11,9 +11,9 @@ import {
|
||||
includedUsagePercent,
|
||||
sandboxHoursAmount,
|
||||
sandboxHoursLeft,
|
||||
sandboxHoursUsed
|
||||
sandboxHoursUsed,
|
||||
isActivePlan
|
||||
} from './plan-billing-format'
|
||||
import { isActivePlan } from './team/team-seat-math'
|
||||
|
||||
/** The bar's warning tone without billing's alert levels (an older service). */
|
||||
const DEFAULT_WARNING_TONE_PERCENT = 90
|
||||
|
||||
@@ -1,163 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import {
|
||||
USAGE_NAMED_ROWS,
|
||||
usageWorkspaceNames,
|
||||
topMemberRows,
|
||||
topWorkspaceRows,
|
||||
usageBarPercent,
|
||||
usageChartMaxHours,
|
||||
usageTotalLine,
|
||||
usageWindowTotalLine,
|
||||
yourUsageLine
|
||||
} from './plan-billing-usage-history'
|
||||
import { sampleUsageHistory, sampleUsageNames } from './plan-billing-fixtures'
|
||||
|
||||
const HOUR = 3600
|
||||
const day = (hours: number) => ({ start: 0, seconds: hours * HOUR })
|
||||
|
||||
describe('usage chart scale', () => {
|
||||
it('tops the axis at the nearest clean value just above the busiest day', () => {
|
||||
expect(usageChartMaxHours([day(0)])).toBe(1)
|
||||
expect(usageChartMaxHours([day(0.4)])).toBe(1)
|
||||
expect(usageChartMaxHours([day(1.5), day(0.2)])).toBe(2)
|
||||
expect(usageChartMaxHours([day(5.2)])).toBe(6)
|
||||
expect(usageChartMaxHours([day(3)])).toBe(3)
|
||||
expect(usageChartMaxHours([day(7)])).toBe(8)
|
||||
expect(usageChartMaxHours([day(48)])).toBe(50)
|
||||
expect(usageChartMaxHours([day(120)])).toBe(200)
|
||||
})
|
||||
|
||||
it('keeps any used day visible and an idle day empty', () => {
|
||||
expect(usageBarPercent(0, 10)).toBe(0)
|
||||
expect(usageBarPercent(36, 10)).toBe(2)
|
||||
expect(usageBarPercent(5 * HOUR, 10)).toBe(50)
|
||||
expect(usageBarPercent(20 * HOUR, 10)).toBe(100)
|
||||
})
|
||||
})
|
||||
|
||||
describe('top workspaces and members', () => {
|
||||
it('names members, calls the viewer "You", and keeps unknown ids readable', () => {
|
||||
const rows = topMemberRows(sampleUsageHistory, sampleUsageNames, translate)!
|
||||
expect(rows.map((row) => row.label)).toEqual([
|
||||
'You',
|
||||
'Grace Hopper',
|
||||
'Linus Torvalds',
|
||||
'Former member',
|
||||
'Not attributed to a member'
|
||||
])
|
||||
expect(rows[0]!.share).toBeCloseTo((18.4 / 48) * 100)
|
||||
expect(rows.at(-1)!.other).toBe(true)
|
||||
})
|
||||
|
||||
it('merges unknown ids into one row after the named ones, and folds 0-hour rows into the others line', () => {
|
||||
const history = {
|
||||
...sampleUsageHistory,
|
||||
sandboxes: {
|
||||
top: [
|
||||
{ id: 'sbx_gone1', seconds: 0.6 * HOUR },
|
||||
{ id: 'sbx_docs', seconds: 0.5 * HOUR },
|
||||
{ id: 'sbx_gone2', seconds: 0.5 * HOUR },
|
||||
{ id: 'sbx_tiny', seconds: 20 }
|
||||
],
|
||||
otherCount: 2,
|
||||
otherSeconds: 0.4 * HOUR
|
||||
}
|
||||
}
|
||||
const rows = topWorkspaceRows(history, sampleUsageNames, translate)!
|
||||
expect(rows.map((row) => [row.label, row.seconds])).toEqual([
|
||||
['Docs search', 0.5 * HOUR],
|
||||
['2 deleted workspaces', 3960],
|
||||
['3 other workspaces', 0.4 * HOUR + 20]
|
||||
])
|
||||
})
|
||||
|
||||
it('drops an others line that rounds to 0 hours', () => {
|
||||
const history = {
|
||||
...sampleUsageHistory,
|
||||
members: { top: [{ id: 'u-grace', seconds: 2 * HOUR }], otherCount: 1, otherSeconds: 30 }
|
||||
}
|
||||
const rows = topMemberRows(history, sampleUsageNames, translate)!
|
||||
expect(rows.map((row) => row.label)).toEqual(['Grace Hopper'])
|
||||
})
|
||||
|
||||
it('titles workspaces and folds the rest into one line', () => {
|
||||
const rows = topWorkspaceRows(sampleUsageHistory, sampleUsageNames, translate)!
|
||||
expect(rows.map((row) => row.label)).toEqual([
|
||||
'Checkout retries',
|
||||
'Ledger migration',
|
||||
'Docs search',
|
||||
'2 deleted workspaces',
|
||||
'4 other workspaces'
|
||||
])
|
||||
})
|
||||
|
||||
it('has no breakdown for members', () => {
|
||||
const memberView = { ...sampleUsageHistory, members: null, sandboxes: null }
|
||||
expect(topMemberRows(memberView, sampleUsageNames, translate)).toBeNull()
|
||||
expect(topWorkspaceRows(memberView, sampleUsageNames, translate)).toBeNull()
|
||||
expect(yourUsageLine(memberView, translate)).toBe(
|
||||
'You used 18.4 of your team’s 48 sandbox hours.'
|
||||
)
|
||||
})
|
||||
|
||||
it('formats totals with the meter’s hours (one decimal, whole numbers bare)', () => {
|
||||
expect(usageTotalLine(48 * HOUR, translate)).toBe('48 sandbox hours')
|
||||
expect(usageTotalLine(HOUR, translate)).toBe('1 sandbox hour')
|
||||
expect(usageTotalLine(0.26 * HOUR, translate)).toBe('0.3 sandbox hours')
|
||||
expect(usageWindowTotalLine(48 * HOUR, translate)).toBe('48 sandbox hours in 30 days')
|
||||
})
|
||||
})
|
||||
|
||||
describe('V3-06: at most five named workspaces, then the buckets', () => {
|
||||
it('names the 5 busiest live ones, then deleted, then the other live ones folded in', () => {
|
||||
const ids = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
|
||||
const history = {
|
||||
...sampleUsageHistory,
|
||||
totalSeconds: 40 * HOUR,
|
||||
sandboxes: {
|
||||
top: [
|
||||
{ id: 'gone', seconds: 9 * HOUR },
|
||||
...ids.map((id, index) => ({ id, seconds: (7 - index) * HOUR }))
|
||||
],
|
||||
otherCount: 10,
|
||||
otherSeconds: 3 * HOUR
|
||||
}
|
||||
}
|
||||
const names = {
|
||||
...sampleUsageNames,
|
||||
workspaces: new Map(ids.map((id) => [id, id.toUpperCase()]))
|
||||
}
|
||||
const rows = topWorkspaceRows(history, names, translate)!
|
||||
expect(rows.map((row) => row.label)).toEqual([
|
||||
'A',
|
||||
'B',
|
||||
'C',
|
||||
'D',
|
||||
'E',
|
||||
'1 deleted workspace',
|
||||
'12 other workspaces'
|
||||
])
|
||||
// The deleted bucket is the biggest but still sits after the names.
|
||||
expect(rows[5]!.seconds).toBe(9 * HOUR)
|
||||
// F (2 h) and G (1 h) joined the 3 h of others.
|
||||
expect(rows[6]!.seconds).toBe(6 * HOUR)
|
||||
expect(USAGE_NAMED_ROWS).toBe(5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('V3-06b: workspaces with the same title', () => {
|
||||
it('adds the workspace number only to titles that repeat', () => {
|
||||
const names = usageWorkspaceNames([
|
||||
{ id: 's1', title: 'orca', number: 512 },
|
||||
{ id: 's2', title: 'orca', number: 498 },
|
||||
{ id: 's3', title: 'Hello-World', number: 7 },
|
||||
{ id: 's4', title: 'orca', number: null }
|
||||
])
|
||||
expect(names.get('s1')).toBe('orca · W-512')
|
||||
expect(names.get('s2')).toBe('orca · W-498')
|
||||
expect(names.get('s3')).toBe('Hello-World')
|
||||
// No number from an older control plane: the title stays as is.
|
||||
expect(names.get('s4')).toBe('orca')
|
||||
})
|
||||
})
|
||||
@@ -1,239 +0,0 @@
|
||||
// Pure helpers for Plan & billing's "Last 30 days": the chart's scale and labels, and the top
|
||||
// workspaces and members with their names resolved. Hours use formatHours, like the meter above.
|
||||
import type { Translate } from '@/i18n/use-translate'
|
||||
import type { OrcaBillingUsageHistory, OrcaBillingUsageTop } from '../../../../shared/orca-billing'
|
||||
import { formatHours, formatHoursUsed } from './plan-billing-format'
|
||||
import { formatWorkspaceNumber } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
|
||||
|
||||
const HOUR = 3600
|
||||
|
||||
// Axis tops whose half is also a clean tick (0 / mid / max), × a power of ten.
|
||||
const NICE_TOPS = [1, 2, 3, 4, 5, 6, 8, 10]
|
||||
|
||||
/** The y-axis top in hours: the nearest clean value at or above the busiest day (min 1). */
|
||||
export function usageChartMaxHours(days: OrcaBillingUsageHistory['days']): number {
|
||||
const busiest = Math.max(0, ...days.map((day) => day.seconds)) / HOUR
|
||||
if (busiest <= 1) {
|
||||
return 1
|
||||
}
|
||||
const power = 10 ** Math.floor(Math.log10(busiest))
|
||||
const top = NICE_TOPS.find((step) => busiest <= step * power) ?? 10
|
||||
return top * power
|
||||
}
|
||||
|
||||
/** A bar's height as a share of the axis (0..100); a day with any usage stays visible (2%). */
|
||||
export function usageBarPercent(seconds: number, maxHours: number): number {
|
||||
if (seconds <= 0) {
|
||||
return 0
|
||||
}
|
||||
return Math.min(100, Math.max(2, (seconds / HOUR / maxHours) * 100))
|
||||
}
|
||||
|
||||
export type UsageBreakdownRow = {
|
||||
key: string
|
||||
label: string
|
||||
seconds: number
|
||||
/** Share of the team's 30-day hours, 0..100, for the row's thin bar. */
|
||||
share: number
|
||||
/** True for the "N others" line. */
|
||||
other?: boolean
|
||||
}
|
||||
|
||||
export type UsageNames = {
|
||||
/** Display names by member id (the team roster). */
|
||||
members: ReadonlyMap<string, string>
|
||||
/** Workspace titles by sandbox id (the team's cloud workspace list). */
|
||||
workspaces: ReadonlyMap<string, string>
|
||||
/** The viewer's member id: their row reads "You". */
|
||||
selfId: string | null
|
||||
}
|
||||
|
||||
/** V3-06: at most this many named rows; billing sends more so deleted ones don't crowd out live ones. */
|
||||
export const USAGE_NAMED_ROWS = 5
|
||||
|
||||
/**
|
||||
* V3-06b: workspace names for Top workspaces by sandbox id. Two workspaces with the same title would
|
||||
* read alike, so duplicates get their number ("orca · W-512"); unique titles stay as they are.
|
||||
*/
|
||||
export function usageWorkspaceNames(
|
||||
workspaces: readonly { id: string; title: string; number?: number | null }[]
|
||||
): Map<string, string> {
|
||||
const counts = new Map<string, number>()
|
||||
for (const workspace of workspaces) {
|
||||
counts.set(workspace.title, (counts.get(workspace.title) ?? 0) + 1)
|
||||
}
|
||||
return new Map(
|
||||
workspaces.map((workspace) => [
|
||||
workspace.id,
|
||||
(counts.get(workspace.title) ?? 0) > 1 && workspace.number
|
||||
? `${workspace.title} · ${formatWorkspaceNumber(workspace.number)}`
|
||||
: workspace.title
|
||||
])
|
||||
)
|
||||
}
|
||||
|
||||
function share(seconds: number, total: number): number {
|
||||
return total > 0 ? Math.min(100, (seconds / total) * 100) : 0
|
||||
}
|
||||
|
||||
function rows(
|
||||
top: OrcaBillingUsageTop,
|
||||
total: number,
|
||||
/** The row's name, or null for an id that's no longer known (one merged row for all of them). */
|
||||
label: (id: string) => string | null,
|
||||
unknownLabel: (count: number) => string,
|
||||
othersLabel: (count: number) => string
|
||||
): UsageBreakdownRow[] {
|
||||
const list: UsageBreakdownRow[] = []
|
||||
let unknown = { count: 0, seconds: 0 }
|
||||
let others = { count: top.otherCount, seconds: top.otherSeconds }
|
||||
for (const row of top.top) {
|
||||
// A row that shows as 0 hours says nothing on its own: it joins the others line.
|
||||
if (formatHours(row.seconds) === '0') {
|
||||
others = { count: others.count + 1, seconds: others.seconds + row.seconds }
|
||||
continue
|
||||
}
|
||||
const name = label(row.id)
|
||||
if (name === null) {
|
||||
unknown = { count: unknown.count + 1, seconds: unknown.seconds + row.seconds }
|
||||
} else {
|
||||
list.push({
|
||||
key: row.id,
|
||||
label: name,
|
||||
seconds: row.seconds,
|
||||
share: share(row.seconds, total)
|
||||
})
|
||||
}
|
||||
}
|
||||
// Named rows lead (they're what someone acts on), the busiest few by name; the rest join the
|
||||
// others line. The merged unknowns and the others line are buckets: always after the names.
|
||||
list.sort((a, b) => b.seconds - a.seconds)
|
||||
for (const extra of list.splice(USAGE_NAMED_ROWS)) {
|
||||
others = { count: others.count + 1, seconds: others.seconds + extra.seconds }
|
||||
}
|
||||
if (unknown.count > 0) {
|
||||
list.push({
|
||||
key: 'unknown',
|
||||
label: unknownLabel(unknown.count),
|
||||
seconds: unknown.seconds,
|
||||
share: share(unknown.seconds, total)
|
||||
})
|
||||
}
|
||||
// An others line that shows as 0 hours is noise: leave it out.
|
||||
if (formatHours(others.seconds) !== '0') {
|
||||
list.push({
|
||||
key: 'other',
|
||||
label: othersLabel(others.count),
|
||||
seconds: others.seconds,
|
||||
share: share(others.seconds, total),
|
||||
other: true
|
||||
})
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
export function topMemberRows(
|
||||
history: OrcaBillingUsageHistory,
|
||||
names: UsageNames,
|
||||
t: Translate
|
||||
): UsageBreakdownRow[] | null {
|
||||
if (!history.members) {
|
||||
return null
|
||||
}
|
||||
return rows(
|
||||
history.members,
|
||||
history.totalSeconds,
|
||||
(id) =>
|
||||
id === names.selfId
|
||||
? t('auto.components.billing.usage.you', 'You')
|
||||
: (names.members.get(id) ?? null),
|
||||
(count) =>
|
||||
t('auto.components.billing.usage.formerMembers', '{{count}} former members', {
|
||||
count,
|
||||
defaultValue_one: 'Former member'
|
||||
}),
|
||||
(count) =>
|
||||
count > 0
|
||||
? t('auto.components.billing.usage.otherMembers', '{{count}} others', {
|
||||
count,
|
||||
defaultValue_one: '{{count}} other'
|
||||
})
|
||||
: t('auto.components.billing.usage.unattributed', 'Not attributed to a member')
|
||||
)
|
||||
}
|
||||
|
||||
export function topWorkspaceRows(
|
||||
history: OrcaBillingUsageHistory,
|
||||
names: UsageNames,
|
||||
t: Translate
|
||||
): UsageBreakdownRow[] | null {
|
||||
if (!history.sandboxes) {
|
||||
return null
|
||||
}
|
||||
return rows(
|
||||
history.sandboxes,
|
||||
history.totalSeconds,
|
||||
(id) => names.workspaces.get(id) ?? null,
|
||||
(count) =>
|
||||
t('auto.components.billing.usage.deletedWorkspaces2', '{{count}} deleted workspaces', {
|
||||
count,
|
||||
defaultValue_one: '{{count}} deleted workspace'
|
||||
}),
|
||||
(count) =>
|
||||
t('auto.components.billing.usage.otherWorkspaces', '{{count}} other workspaces', {
|
||||
count,
|
||||
defaultValue_one: '{{count}} other workspace'
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
/** "48 sandbox hours in 30 days": the chart's total, distinct from the month's meter above. */
|
||||
export function usageWindowTotalLine(seconds: number, t: Translate): string {
|
||||
return t('auto.components.billing.usage.windowTotal', '{{value}} sandbox hours in 30 days', {
|
||||
value: formatHoursUsed(seconds),
|
||||
count: Number(formatHoursUsed(seconds)),
|
||||
defaultValue_one: '{{value}} sandbox hour in 30 days'
|
||||
})
|
||||
}
|
||||
|
||||
/** "41.5 sandbox hours" (a day's readout). */
|
||||
export function usageTotalLine(seconds: number, t: Translate): string {
|
||||
return t('auto.components.billing.usage.total', '{{value}} sandbox hours', {
|
||||
value: formatHoursUsed(seconds),
|
||||
count: Number(formatHoursUsed(seconds)),
|
||||
defaultValue_one: '{{value}} sandbox hour'
|
||||
})
|
||||
}
|
||||
|
||||
/** A member's line: "You used 5 of your team's 41.5 sandbox hours." */
|
||||
export function yourUsageLine(history: OrcaBillingUsageHistory, t: Translate): string {
|
||||
return t(
|
||||
'auto.components.billing.usage.yours',
|
||||
'You used {{yours}} of your team’s {{total}} sandbox hours.',
|
||||
{
|
||||
yours: formatHoursUsed(history.yourSeconds),
|
||||
total: formatHoursUsed(history.totalSeconds)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/** The bar's readout (tooltip, live region and table): "Nov 3 · 2.5 sandbox hours". */
|
||||
export function usageDayLine(
|
||||
day: OrcaBillingUsageHistory['days'][number],
|
||||
locale: string,
|
||||
t: Translate
|
||||
): string {
|
||||
return t('auto.components.billing.usage.dayLine', '{{date}} · {{hours}}', {
|
||||
date: usageDayLabel(day.start, locale),
|
||||
hours: usageTotalLine(day.seconds, t)
|
||||
})
|
||||
}
|
||||
|
||||
const DAY_FORMAT: Intl.DateTimeFormatOptions = {
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
}
|
||||
|
||||
export function usageDayLabel(start: number, locale: string): string {
|
||||
return new Intl.DateTimeFormat(locale, DAY_FORMAT).format(start)
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
import { Building2, ExternalLink } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
|
||||
import { PlanCardShell } from './PlanCardShell'
|
||||
import { planFeatureLines } from './plan-feature-copy'
|
||||
import type { EnterprisePlanModel } from './plans-model'
|
||||
|
||||
export function EnterprisePlanCard({
|
||||
enterprise,
|
||||
onContactSales
|
||||
}: {
|
||||
enterprise: EnterprisePlanModel
|
||||
onContactSales: (url: string) => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const locale = useIntlLocale()
|
||||
// Billing's catalog lists what Enterprise adds; an older service lists nothing.
|
||||
const features = planFeatureLines(
|
||||
enterprise.features,
|
||||
{ overage: null, currency: 'usd' },
|
||||
t,
|
||||
locale
|
||||
)
|
||||
const contactUrl = enterprise.contactUrl
|
||||
return (
|
||||
<PlanCardShell
|
||||
id="plans-enterprise-title"
|
||||
title={
|
||||
<>
|
||||
<Building2 className="size-4 text-muted-foreground" />
|
||||
{enterprise.label}
|
||||
</>
|
||||
}
|
||||
price={
|
||||
enterprise.priceLabel ? (
|
||||
<p className="text-xl font-semibold tracking-tight">{enterprise.priceLabel}</p>
|
||||
) : null
|
||||
}
|
||||
priceNote={t('auto.components.billing.plans.entPriced2', 'Priced for your team')}
|
||||
featuresLead={
|
||||
features.length > 0
|
||||
? t('auto.components.billing.plans.entLead', 'Everything in Team, plus:')
|
||||
: undefined
|
||||
}
|
||||
features={features}
|
||||
footer={
|
||||
contactUrl ? (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
onClick={() => onContactSales(contactUrl)}
|
||||
>
|
||||
{t('auto.components.billing.plans.contactSales', 'Contact sales')}
|
||||
<ExternalLink />
|
||||
</Button>
|
||||
<p className="text-center text-xs text-muted-foreground">
|
||||
{t(
|
||||
'auto.components.billing.plans.entHint',
|
||||
'Tell us about your team and where you run.'
|
||||
)}
|
||||
</p>
|
||||
</>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import { Check } from 'lucide-react'
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
/**
|
||||
* Shared plan card layout. Both cards use the same rows (title, price, details, features,
|
||||
* footer) and stretch to the same height, so their dividers and buttons line up.
|
||||
*/
|
||||
export function PlanCardShell({
|
||||
id,
|
||||
title,
|
||||
badge,
|
||||
price,
|
||||
priceNote,
|
||||
details,
|
||||
featuresLead,
|
||||
features,
|
||||
footer
|
||||
}: {
|
||||
id: string
|
||||
title: ReactNode
|
||||
badge?: ReactNode
|
||||
price: ReactNode
|
||||
priceNote: ReactNode
|
||||
details?: ReactNode
|
||||
featuresLead?: string
|
||||
features: string[]
|
||||
footer: ReactNode
|
||||
}): React.JSX.Element {
|
||||
return (
|
||||
<section
|
||||
aria-labelledby={id}
|
||||
className="flex h-full flex-col gap-5 rounded-xl border border-border bg-card p-5 shadow-xs"
|
||||
>
|
||||
<div className="flex min-h-6 items-center justify-between gap-3">
|
||||
<h3 id={id} className="flex items-center gap-2 text-base font-semibold">
|
||||
{title}
|
||||
</h3>
|
||||
{badge}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{price}
|
||||
<p className="text-xs text-muted-foreground">{priceNote}</p>
|
||||
</div>
|
||||
{details}
|
||||
<div className="flex-1 space-y-2.5">
|
||||
{featuresLead ? (
|
||||
<p className="text-xs font-medium text-muted-foreground">{featuresLead}</p>
|
||||
) : null}
|
||||
<ul className="space-y-2.5">
|
||||
{features.map((feature) => (
|
||||
<li key={feature} className="flex items-start gap-2 text-sm text-pretty">
|
||||
<Check className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
|
||||
<span>{feature}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
{/* Fixed footer height (button + up to two lines) keeps both cards' dividers level. */}
|
||||
<div className="flex min-h-[6rem] flex-col justify-start gap-2 border-t border-border/60 pt-4">
|
||||
{footer}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { PlansView, isSubscribed, type PlansViewProps } from './PlansView'
|
||||
|
||||
/**
|
||||
* The plans page surface: heading plus plans, or the checkout panel while Checkout runs.
|
||||
* Top-anchored so loading, plans and checkout never make the dialog jump (review M4).
|
||||
*/
|
||||
export function PlansDialogContent(
|
||||
props: PlansViewProps & {
|
||||
checkout?: ReactNode
|
||||
/** Checkout state, so the dialog title says what happened (paid, canceled). */
|
||||
checkoutState?: 'paid' | 'canceled' | 'other'
|
||||
/** Payment landed: the Team page takes over, so this dialog leaves without its zoom-out. */
|
||||
handingOff?: boolean
|
||||
}
|
||||
): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const subscribed = isSubscribed(props.result)
|
||||
const { checkout, checkoutState, handingOff, ...viewProps } = props
|
||||
return (
|
||||
<DialogContent
|
||||
scrollable
|
||||
exitMotion={handingOff ? 'none' : 'default'}
|
||||
className={
|
||||
checkout
|
||||
? // Checkout is one column; a narrower dialog keeps it from floating in empty space.
|
||||
'top-[6vh] max-h-[88vh] translate-y-0 sm:max-w-lg [@media(max-height:800px)]:top-4 [@media(max-height:800px)]:max-h-[calc(100vh-2rem)]'
|
||||
: 'top-[6vh] max-h-[88vh] translate-y-0 sm:max-w-4xl [@media(max-height:800px)]:top-4 [@media(max-height:800px)]:max-h-[calc(100vh-2rem)]'
|
||||
}
|
||||
onOpenAutoFocus={(event) => {
|
||||
// The heading, not the first button: Enter on "Continue" would start a monthly Checkout,
|
||||
// and Tab from here reaches the interval toggle before the plan cards.
|
||||
event.preventDefault()
|
||||
if (event.currentTarget instanceof HTMLElement) {
|
||||
const heading = event.currentTarget.querySelector<HTMLElement>('[data-plans-heading]')
|
||||
;(heading ?? event.currentTarget).focus()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogHeader className="items-center text-center">
|
||||
<p className="text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground">
|
||||
{t('auto.components.billing.plans.eyebrow', 'Orca Cloud')}
|
||||
</p>
|
||||
<DialogTitle size="display" tabIndex={-1} data-plans-heading="">
|
||||
{checkout
|
||||
? checkoutState === 'paid'
|
||||
? t('auto.components.billing.checkout.titlePaid', 'Welcome to Orca Cloud')
|
||||
: checkoutState === 'canceled'
|
||||
? t('auto.components.billing.checkout.titleCanceled', 'Checkout canceled')
|
||||
: t('auto.components.billing.checkout.title', 'Checkout')
|
||||
: subscribed
|
||||
? t('auto.components.billing.plans.titleSubscribed', 'Your Orca Cloud plan')
|
||||
: t('auto.components.billing.plans.title', 'Cloud sandboxes for your whole team')}
|
||||
</DialogTitle>
|
||||
<DialogDescription
|
||||
className={subscribed || checkout ? 'sr-only' : 'mx-auto max-w-xl text-center'}
|
||||
>
|
||||
{checkout
|
||||
? t(
|
||||
'auto.components.billing.checkout.subtitle',
|
||||
'Pay on Stripe’s secure page in your browser. Orca picks it up the moment it goes through.'
|
||||
)
|
||||
: subscribed
|
||||
? t(
|
||||
'auto.components.billing.plans.subtitleSubscribed',
|
||||
'Usage this month, your plan, and what Enterprise adds.'
|
||||
)
|
||||
: t(
|
||||
'auto.components.billing.plans.subtitle2',
|
||||
'Run Orca agents in hosted sandboxes that keep going when you step away.'
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{checkout ?? <PlansView {...viewProps} />}
|
||||
</DialogContent>
|
||||
)
|
||||
}
|
||||
@@ -1,136 +0,0 @@
|
||||
import { useState } from 'react'
|
||||
import { Dialog } from '@/components/ui/dialog'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { useAppStore } from '@/store/index'
|
||||
import type { OrcaBillingOpenResult } from '../../../../../shared/orca-billing'
|
||||
import { CheckoutPanel } from '../checkout/CheckoutPanel'
|
||||
import { useCheckoutFlow } from '../checkout/use-checkout-flow'
|
||||
import { openFailureCopy } from '../plan-billing-copy'
|
||||
import type { PlanBillingNotice } from '../PlanBillingSection'
|
||||
import { returnAfterPaidCheckout } from '../checkout/checkout-return'
|
||||
import { cancelOrcaCloudAfterCheckout } from '@/lib/orca-cloud-after-checkout'
|
||||
import { useOrcaBillingStatus } from '../use-orca-billing-status'
|
||||
import { PlansDialogContent } from './PlansDialogContent'
|
||||
import { closePlansPage, usePlansPageState } from './plans-page-store'
|
||||
import { useOrgSeatCount } from './use-org-seat-count'
|
||||
import { usePlanCatalog } from './use-plan-catalog'
|
||||
import { planContactUrl, resolvePlansModel } from './plans-model'
|
||||
|
||||
/**
|
||||
* The plans page. A dialog because choosing a plan is a decision step in front of Checkout;
|
||||
* it reads billing's plan catalog (GET /v1/plans: Stripe's prices, the catalog's features), so
|
||||
* prices and features are never hardcoded here.
|
||||
* Checkout itself runs on Stripe's hosted page in the browser; this dialog follows it and,
|
||||
* once paid, returns to the Orca Cloud wall that opened it, or hands over to the Team page.
|
||||
*/
|
||||
export function PlansDialogHost(): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const { open } = usePlansPageState()
|
||||
const billing = useOrcaBillingStatus(open)
|
||||
const orgId = useAppStore((state) => state.orcaProfileAuthStatus?.cloud?.activeOrgId ?? null)
|
||||
const seats = useOrgSeatCount(open ? orgId : null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [notice, setNotice] = useState<PlanBillingNotice | null>(null)
|
||||
const [orderedAt, setOrderedAt] = useState(0)
|
||||
|
||||
const checkout = useCheckoutFlow({ onPaid: returnAfterPaidCheckout })
|
||||
|
||||
const openPortal = async (): Promise<void> => {
|
||||
setBusy(true)
|
||||
setNotice(null)
|
||||
const outcome = await window.api.orcaProfiles
|
||||
.billingOpenPortal()
|
||||
.catch((error: unknown): OrcaBillingOpenResult => ({
|
||||
status: 'failed',
|
||||
error: String(error)
|
||||
}))
|
||||
setBusy(false)
|
||||
const failure = openFailureCopy(outcome, t)
|
||||
setNotice(
|
||||
failure
|
||||
? { kind: 'error', text: failure }
|
||||
: {
|
||||
kind: 'info',
|
||||
text: t(
|
||||
'auto.components.billing.continueInBrowser',
|
||||
'Continue in your browser. This updates when you come back.'
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
const catalog = usePlanCatalog(open)
|
||||
const plans = resolvePlansModel(catalog.result, billing.result)
|
||||
const team = plans.state === 'ready' ? plans.model.team : null
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) {
|
||||
// Closing ends the watch: polling stops and the next open starts from the plans.
|
||||
checkout.reset()
|
||||
closePlansPage()
|
||||
// Leaving without paying: nothing to return to Orca Cloud for.
|
||||
cancelOrcaCloudAfterCheckout()
|
||||
setNotice(null)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{open ? (
|
||||
<PlansDialogContent
|
||||
result={billing.result}
|
||||
catalog={catalog.result}
|
||||
busy={busy}
|
||||
notice={notice}
|
||||
seats={seats}
|
||||
onCheckout={({ planId, interval, seats: count }) => {
|
||||
setOrderedAt(Date.now())
|
||||
checkout.start({ planId, interval, seats: count })
|
||||
}}
|
||||
onManage={() => void openPortal()}
|
||||
onContactSales={(url) => void window.api.shell.openUrl(url)}
|
||||
onRetry={() => {
|
||||
billing.refresh()
|
||||
catalog.refresh()
|
||||
}}
|
||||
checkoutState={
|
||||
checkout.phase.kind === 'paid'
|
||||
? 'paid'
|
||||
: checkout.phase.kind === 'canceled'
|
||||
? 'canceled'
|
||||
: 'other'
|
||||
}
|
||||
handingOff={checkout.phase.kind === 'paid'}
|
||||
checkout={
|
||||
checkout.phase.kind !== 'idle' && team ? (
|
||||
<CheckoutPanel
|
||||
phase={checkout.phase}
|
||||
team={team}
|
||||
now={orderedAt}
|
||||
onReopen={() => {
|
||||
// Billing couldn't sell the plan: re-read the catalog (and plan state) first.
|
||||
if (
|
||||
checkout.phase.kind === 'open-failed' &&
|
||||
checkout.phase.result.status === 'plan-unavailable'
|
||||
) {
|
||||
catalog.refresh()
|
||||
billing.refresh()
|
||||
}
|
||||
checkout.reopen()
|
||||
}}
|
||||
contactUrl={plans.state === 'ready' ? planContactUrl(plans.model) : null}
|
||||
onContact={(url) => void window.api.shell.openUrl(url)}
|
||||
onKeepWaiting={checkout.keepWaiting}
|
||||
onBack={() => {
|
||||
checkout.reset()
|
||||
billing.refresh()
|
||||
}}
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import { SettingsSegmentedControl } from '@/components/settings/form-controls/SettingsSegmentedControl'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import type { OrcaBillingInterval } from '../../../../../shared/orca-billing'
|
||||
|
||||
/** Monthly / Annual on the shared segmented control (keyboard, contrast, reduced motion). */
|
||||
export function PlansIntervalToggle({
|
||||
value,
|
||||
savingsPercent,
|
||||
disabled,
|
||||
onChange
|
||||
}: {
|
||||
value: OrcaBillingInterval
|
||||
savingsPercent: number | null
|
||||
disabled: boolean
|
||||
onChange: (interval: OrcaBillingInterval) => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const save =
|
||||
savingsPercent === null
|
||||
? null
|
||||
: t('auto.components.billing.plans.savePercent', 'Save {{value0}}%', {
|
||||
value0: String(savingsPercent)
|
||||
})
|
||||
return (
|
||||
<div className="mx-auto flex w-72 justify-center">
|
||||
<SettingsSegmentedControl<OrcaBillingInterval>
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
size="sm"
|
||||
equalWidth
|
||||
ariaLabel={t('auto.components.billing.plans.billingPeriod', 'Billing period')}
|
||||
options={[
|
||||
{
|
||||
value: 'month',
|
||||
label: t('auto.components.billing.plans.monthly', 'Monthly'),
|
||||
disabled
|
||||
},
|
||||
{
|
||||
value: 'year',
|
||||
label: save ? (
|
||||
<span className="flex items-center gap-1.5">
|
||||
{t('auto.components.billing.plans.annual', 'Annual')}
|
||||
<span className="rounded-full bg-foreground/10 px-1.5 text-[10px] font-semibold tabular-nums">
|
||||
{save}
|
||||
</span>
|
||||
</span>
|
||||
) : (
|
||||
t('auto.components.billing.plans.annual', 'Annual')
|
||||
),
|
||||
ariaLabel: save
|
||||
? `${t('auto.components.billing.plans.annual', 'Annual')}, ${save}`
|
||||
: undefined,
|
||||
disabled
|
||||
}
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
import { defineFixture } from '../../../component-fixtures/component-fixture'
|
||||
import type { OrcaBillingEntitlement } from '../../../../../shared/orca-billing'
|
||||
import { sampleTeam, sampleTrial, sampleTrialUsedUp } from '../plan-billing-fixtures'
|
||||
import { Dialog } from '@/components/ui/dialog'
|
||||
import { PlansDialogContent } from './PlansDialogContent'
|
||||
import type { PlansViewProps } from './PlansView'
|
||||
import { monthlyOnlyCatalogResult, sampleCatalogResult } from './plan-catalog-fixtures'
|
||||
|
||||
const HOUR = 3600
|
||||
|
||||
const handlers = {
|
||||
catalog: sampleCatalogResult,
|
||||
busy: false,
|
||||
notice: null,
|
||||
seats: 4,
|
||||
onCheckout: () => {},
|
||||
onManage: () => {},
|
||||
onContactSales: () => {},
|
||||
onRetry: () => {}
|
||||
}
|
||||
|
||||
const noPlan: OrcaBillingEntitlement = {
|
||||
...sampleTeam,
|
||||
plan: null,
|
||||
planLabel: null,
|
||||
status: 'none',
|
||||
interval: null,
|
||||
seats: 0,
|
||||
period: null,
|
||||
usageWindow: null,
|
||||
includedSeconds: 0,
|
||||
usedSeconds: 0,
|
||||
remainingIncludedSeconds: 0,
|
||||
canStartSandbox: false,
|
||||
reason: 'no_subscription'
|
||||
}
|
||||
|
||||
const width = 1280
|
||||
|
||||
function Page(props: Pick<PlansViewProps, 'result'> & Partial<PlansViewProps>): React.JSX.Element {
|
||||
return (
|
||||
<Dialog open modal={false}>
|
||||
<PlansDialogContent {...handlers} {...props} />
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export const choosePlan = defineFixture({
|
||||
width,
|
||||
render: () => <Page result={{ status: 'ok', entitlement: noPlan }} />
|
||||
})
|
||||
|
||||
export const memberCannotBuy = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page result={{ status: 'ok', entitlement: { ...noPlan, canManageBilling: false } }} />
|
||||
)
|
||||
})
|
||||
|
||||
export const currentPlan = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
interval: 'year',
|
||||
seats: 4,
|
||||
includedSeconds: 240 * HOUR,
|
||||
usedSeconds: 96 * HOUR,
|
||||
remainingIncludedSeconds: 144 * HOUR
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const paymentFailed = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
status: 'past_due',
|
||||
payment: {
|
||||
pastDueSince: Date.UTC(2026, 10, 8, 9),
|
||||
graceEndsAt: Date.UTC(2026, 10, 12, 9),
|
||||
suspendRunning: false
|
||||
},
|
||||
canStartSandbox: false,
|
||||
reason: 'payment_past_due'
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const loading = defineFixture({
|
||||
width,
|
||||
render: () => <Page result={null} />
|
||||
})
|
||||
|
||||
export const loadFailed = defineFixture({
|
||||
width,
|
||||
render: () => <Page result={{ status: 'failed', error: 'timeout' }} />
|
||||
})
|
||||
|
||||
/** Billing's 90% level on the plans page: the strip warns under the bar. */
|
||||
export const currentPlanUsageWarning = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page
|
||||
result={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...sampleTeam,
|
||||
seats: 4,
|
||||
includedSeconds: 240 * HOUR,
|
||||
usedSeconds: 220 * HOUR,
|
||||
remainingIncludedSeconds: 20 * HOUR,
|
||||
usageWarningPercent: 90
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
/** Spec T1: the plans page during the trial; the strip replaces the value props. */
|
||||
export const trialStrip = defineFixture({
|
||||
width,
|
||||
render: () => <Page result={{ status: 'ok', entitlement: sampleTrial }} />
|
||||
})
|
||||
|
||||
export const trialUsedUpStrip = defineFixture({
|
||||
width,
|
||||
render: () => <Page result={{ status: 'ok', entitlement: sampleTrialUsedUp }} />
|
||||
})
|
||||
|
||||
/** Billing's catalog is still on its way (the entitlement already came back). */
|
||||
export const catalogLoading = defineFixture({
|
||||
width,
|
||||
render: () => <Page result={{ status: 'ok', entitlement: noPlan }} catalog={null} />
|
||||
})
|
||||
|
||||
/** No catalog and no offers to fall back on: an error with Retry, never a guessed price. */
|
||||
export const catalogFailed = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page
|
||||
result={{ status: 'ok', entitlement: { ...noPlan, offers: null } }}
|
||||
catalog={{ status: 'failed', error: 'plan_catalog_503' }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
/** Stripe has only a monthly price on sale: no interval toggle, monthly only. */
|
||||
export const onlyMonthlyPrice = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page result={{ status: 'ok', entitlement: noPlan }} catalog={monthlyOnlyCatalogResult} />
|
||||
)
|
||||
})
|
||||
|
||||
/** A billing service from before GET /v1/plans (404): its entitlement offers stand in. */
|
||||
export const olderServiceOffers = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page result={{ status: 'ok', entitlement: noPlan }} catalog={{ status: 'unsupported' }} />
|
||||
)
|
||||
})
|
||||
@@ -1,88 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { OrcaBillingEntitlement } from '../../../../../shared/orca-billing'
|
||||
import { sampleTeam } from '../plan-billing-fixtures'
|
||||
import { monthlyOnlyCatalogResult, sampleCatalogResult } from './plan-catalog-fixtures'
|
||||
import { PlansView, shownInterval, type PlansViewProps } from './PlansView'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const noPlan: OrcaBillingEntitlement = {
|
||||
...sampleTeam,
|
||||
plan: null,
|
||||
planLabel: null,
|
||||
status: 'none',
|
||||
interval: null,
|
||||
seats: 0,
|
||||
canStartSandbox: false,
|
||||
reason: 'no_subscription'
|
||||
}
|
||||
|
||||
function view(props: Partial<PlansViewProps>): PlansViewProps {
|
||||
return {
|
||||
result: { status: 'ok', entitlement: noPlan },
|
||||
catalog: sampleCatalogResult,
|
||||
busy: false,
|
||||
notice: null,
|
||||
seats: 4,
|
||||
onCheckout: vi.fn(),
|
||||
onManage: vi.fn(),
|
||||
onContactSales: vi.fn(),
|
||||
onRetry: vi.fn(),
|
||||
...props
|
||||
}
|
||||
}
|
||||
|
||||
describe("plans dialog from billing's catalog", () => {
|
||||
it("shows Stripe's prices and the catalog's features, and checks out the catalog plan", () => {
|
||||
const props = view({})
|
||||
render(<PlansView {...props} />)
|
||||
expect(screen.getByText('$50')).toBeTruthy()
|
||||
expect(
|
||||
screen.getByText('60 sandbox hours per seat each month, pooled across your team')
|
||||
).toBeTruthy()
|
||||
expect(screen.getByText('Run sandboxes in your own cloud account')).toBeTruthy()
|
||||
// The catalog lists egress_controls on Enterprise, but no team can set an egress policy yet.
|
||||
expect(screen.queryByText(/egress/i)).toBeNull()
|
||||
// The audit log is its own catalog line; the SSO line doesn't repeat it.
|
||||
expect(screen.getByText('SSO and SCIM provisioning')).toBeTruthy()
|
||||
expect(screen.getAllByText(/audit log/i).map((node) => node.textContent)).toEqual([
|
||||
'Team audit log'
|
||||
])
|
||||
fireEvent.click(screen.getByRole('button', { name: /Continue to checkout/ }))
|
||||
expect(props.onCheckout).toHaveBeenCalledWith({ planId: 'team', interval: 'month', seats: 4 })
|
||||
fireEvent.click(screen.getByRole('button', { name: /Contact sales/ }))
|
||||
expect(props.onContactSales).toHaveBeenCalledWith('https://orca.dev/enterprise')
|
||||
})
|
||||
|
||||
it('offers only the intervals Stripe prices: no toggle with one', () => {
|
||||
render(<PlansView {...view({ catalog: monthlyOnlyCatalogResult })} />)
|
||||
expect(screen.queryByRole('radiogroup')).toBeNull()
|
||||
expect(screen.queryByText('Annual')).toBeNull()
|
||||
expect(shownInterval('year', ['month'])).toBe('month')
|
||||
})
|
||||
|
||||
it('shows the skeleton while the catalog loads', () => {
|
||||
render(<PlansView {...view({ catalog: null })} />)
|
||||
expect(screen.getByRole('status', { name: 'Loading plans…' })).toBeTruthy()
|
||||
})
|
||||
|
||||
it('without a catalog or offers: an error and Retry, never a price', () => {
|
||||
const props = view({
|
||||
result: { status: 'ok', entitlement: { ...noPlan, offers: null } },
|
||||
catalog: { status: 'failed', error: 'plan_catalog_503' }
|
||||
})
|
||||
render(<PlansView {...props} />)
|
||||
expect(screen.getByText('Plans didn’t load')).toBeTruthy()
|
||||
expect(screen.queryByText(/\$\d/)).toBeNull()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Try again' }))
|
||||
expect(props.onRetry).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reads an older service (404) through its offers', () => {
|
||||
render(<PlansView {...view({ catalog: { status: 'unsupported' } })} />)
|
||||
expect(screen.getByText('$50')).toBeTruthy()
|
||||
expect(screen.queryByText('Everything in Team, plus:')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,229 +0,0 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
|
||||
import {
|
||||
isOrcaCloudTrial,
|
||||
type OrcaBillingEntitlement,
|
||||
type OrcaBillingInterval,
|
||||
type OrcaBillingStatusResult
|
||||
} from '../../../../../shared/orca-billing'
|
||||
import { PaymentIssueNotice } from '../PaymentIssueNotice'
|
||||
import { PlanStatusBadge } from '../PlanStatusBadge'
|
||||
import type { PlanBillingNotice } from '../PlanBillingSection'
|
||||
import { PlanSeatFacts } from '../team/TeamPlanSummary'
|
||||
import { formatHours, formatHoursUsed, includedUsagePercent } from '../plan-billing-format'
|
||||
import {
|
||||
includedUsageTone,
|
||||
sandboxHoursCount,
|
||||
sandboxHoursLeftLine,
|
||||
usageWarningLine
|
||||
} from '../plan-billing-usage-copy'
|
||||
import { TrialPlanSummary } from '../TrialPlanSummary'
|
||||
import { EnterprisePlanCard } from './EnterprisePlanCard'
|
||||
import { PlansLoadError, PlansSkeleton, ValueProps } from './PlansViewParts'
|
||||
import { PlansIntervalToggle } from './PlansIntervalToggle'
|
||||
import { TeamPlanCard, type TeamPlanCardMode } from './TeamPlanCard'
|
||||
import { annualSavingsPercent, clampSeats } from './plans-pricing'
|
||||
import { resolvePlansModel } from './plans-model'
|
||||
import type { OrcaPlanCatalogResult } from '../../../../../shared/orca-billing-plans'
|
||||
|
||||
export type PlansViewProps = {
|
||||
result: OrcaBillingStatusResult | null
|
||||
/** Billing's plan catalog (GET /v1/plans); null while it loads. */
|
||||
catalog: OrcaPlanCatalogResult | null
|
||||
busy: boolean
|
||||
notice: PlanBillingNotice | null
|
||||
/** Seats Checkout will bill: org members, or 1 for a personal account. */
|
||||
seats: number
|
||||
onCheckout: (args: { planId: string; interval: OrcaBillingInterval; seats: number }) => void
|
||||
onManage: () => void
|
||||
onContactSales: (url: string) => void
|
||||
onRetry: () => void
|
||||
}
|
||||
|
||||
export function isSubscribed(result: OrcaBillingStatusResult | null): boolean {
|
||||
return (
|
||||
result?.status === 'ok' &&
|
||||
result.entitlement.plan !== null &&
|
||||
result.entitlement.status !== 'canceled'
|
||||
)
|
||||
}
|
||||
|
||||
function CurrentPlanStrip({
|
||||
entitlement,
|
||||
members
|
||||
}: {
|
||||
entitlement: OrcaBillingEntitlement
|
||||
members: number
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const locale = useIntlLocale()
|
||||
const resets = entitlement.usageWindow
|
||||
? new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(entitlement.usageWindow.end)
|
||||
: null
|
||||
const warning = usageWarningLine(entitlement, t, locale)
|
||||
return (
|
||||
<div className="space-y-2 rounded-xl border border-border bg-card p-4 shadow-xs">
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="font-medium">{entitlement.planLabel}</span>
|
||||
<PlanStatusBadge entitlement={entitlement} />
|
||||
</div>
|
||||
<Progress
|
||||
value={includedUsagePercent(entitlement)}
|
||||
tone={includedUsageTone(entitlement)}
|
||||
aria-label={t('auto.components.billing.sandboxHoursUsedLabel', 'Sandbox hours used')}
|
||||
/>
|
||||
<div className="flex flex-wrap justify-between gap-2 text-xs text-muted-foreground tabular-nums">
|
||||
<span>
|
||||
{t(
|
||||
'auto.components.billing.sandboxHoursUsedMonth',
|
||||
'{{value0}} of {{value1}} sandbox hours used this month',
|
||||
{
|
||||
value0: formatHoursUsed(
|
||||
Math.min(entitlement.usedSeconds, entitlement.includedSeconds)
|
||||
),
|
||||
value1: formatHours(entitlement.includedSeconds)
|
||||
}
|
||||
)}
|
||||
</span>
|
||||
<span>
|
||||
{resets
|
||||
? t(
|
||||
'auto.components.billing.plans.sandboxHoursLeftResets',
|
||||
'{{count}} sandbox hours left · resets {{date}}',
|
||||
{
|
||||
count: sandboxHoursCount(entitlement.remainingIncludedSeconds),
|
||||
date: resets,
|
||||
defaultValue_one: '{{count}} sandbox hour left · resets {{date}}'
|
||||
}
|
||||
)
|
||||
: sandboxHoursLeftLine(entitlement, t)}
|
||||
</span>
|
||||
</div>
|
||||
{warning ? <p className="text-xs font-medium">{warning}</p> : null}
|
||||
{/* Seat facts moved here from the Team dialog, which now only links to Plan & billing. */}
|
||||
<PlanSeatFacts entitlement={entitlement} members={members} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The interval to show: the one picked when it is on sale, else the first one that is. */
|
||||
export function shownInterval(
|
||||
picked: OrcaBillingInterval,
|
||||
intervals: readonly OrcaBillingInterval[]
|
||||
): OrcaBillingInterval {
|
||||
return intervals.includes(picked) ? picked : (intervals[0] ?? picked)
|
||||
}
|
||||
|
||||
export function PlansView(props: PlansViewProps): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const [picked, setInterval] = useState<OrcaBillingInterval>('month')
|
||||
const result = props.result
|
||||
const plans = resolvePlansModel(props.catalog, result)
|
||||
const ready = result?.status === 'ok' && plans.state === 'ready'
|
||||
// Once plans load (or after "Back to plans"), land on the dialog heading, never on a buy button
|
||||
// (Enter would start Checkout): Tab then reaches the interval toggle before the cards. Only when
|
||||
// focus is on the dialog or nowhere; never steal it from something the user picked.
|
||||
useEffect(() => {
|
||||
const active = document.activeElement
|
||||
if (
|
||||
ready &&
|
||||
(!active || active === document.body || active.getAttribute('role') === 'dialog')
|
||||
) {
|
||||
document.querySelector<HTMLElement>('[role="dialog"] [data-plans-heading]')?.focus()
|
||||
}
|
||||
}, [ready])
|
||||
|
||||
if (result?.status === 'signed-out' || result?.status === 'unconfigured') {
|
||||
return (
|
||||
<p className="py-12 text-center text-sm text-muted-foreground">
|
||||
{result.status === 'signed-out'
|
||||
? t(
|
||||
'auto.components.billing.openSignedOut2',
|
||||
'Sign in to Orca again to manage your team.'
|
||||
)
|
||||
: t('auto.components.billing.openUnconfigured', 'Billing is unavailable in this build.')}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
if (result === null || (result.status === 'ok' && plans.state === 'loading')) {
|
||||
return <PlansSkeleton />
|
||||
}
|
||||
if (result.status !== 'ok' || plans.state !== 'ready') {
|
||||
// Never a guessed price: without billing's catalog (or offers) there is nothing to show.
|
||||
return <PlansLoadError onRetry={props.onRetry} />
|
||||
}
|
||||
|
||||
const entitlement = result.entitlement
|
||||
const { team, enterprise } = plans.model
|
||||
const subscribed = isSubscribed(result)
|
||||
const mode: TeamPlanCardMode = subscribed
|
||||
? 'current'
|
||||
: entitlement.canManageBilling
|
||||
? 'choose'
|
||||
: 'locked'
|
||||
const paymentIssue = entitlement.payment.pastDueSince !== null
|
||||
const interval = shownInterval(picked, team.intervals)
|
||||
const seats = Math.max(team.seats.min, clampSeats(props.seats, team.seats.max))
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{subscribed ? (
|
||||
<>
|
||||
<PaymentIssueNotice
|
||||
entitlement={entitlement}
|
||||
busy={props.busy}
|
||||
onUpdatePayment={props.onManage}
|
||||
/>
|
||||
<CurrentPlanStrip entitlement={entitlement} members={props.seats} />
|
||||
</>
|
||||
) : isOrcaCloudTrial(entitlement) ? (
|
||||
// The trial's strip: the plan cards right below are the way out of it (spec T1).
|
||||
<div className="rounded-xl border border-border bg-card p-4 shadow-xs">
|
||||
<TrialPlanSummary entitlement={entitlement} />
|
||||
</div>
|
||||
) : (
|
||||
<ValueProps />
|
||||
)}
|
||||
{mode === 'choose' && team.intervals.length > 1 ? (
|
||||
<PlansIntervalToggle
|
||||
value={interval}
|
||||
savingsPercent={annualSavingsPercent(team)}
|
||||
disabled={props.busy}
|
||||
onChange={setInterval}
|
||||
/>
|
||||
) : null}
|
||||
<div className={enterprise ? 'grid items-stretch gap-4 md:grid-cols-2' : 'mx-auto max-w-md'}>
|
||||
<TeamPlanCard
|
||||
team={team}
|
||||
interval={subscribed && entitlement.interval ? entitlement.interval : interval}
|
||||
seats={seats}
|
||||
mode={mode}
|
||||
busy={props.busy}
|
||||
notice={props.notice}
|
||||
hideManage={paymentIssue}
|
||||
onCheckout={() => props.onCheckout({ planId: team.planId, interval, seats })}
|
||||
onManage={props.onManage}
|
||||
/>
|
||||
{enterprise ? (
|
||||
<EnterprisePlanCard enterprise={enterprise} onContactSales={props.onContactSales} />
|
||||
) : null}
|
||||
</div>
|
||||
<div className="space-y-1 text-center text-xs text-muted-foreground text-pretty">
|
||||
<p>
|
||||
{t(
|
||||
'auto.components.billing.plans.footHours3',
|
||||
'Hours reset every month, including on annual plans.'
|
||||
)}
|
||||
</p>
|
||||
<p>
|
||||
{t(
|
||||
'auto.components.billing.plans.footTerms5',
|
||||
'Prices in {{currency}}, before tax. Overage is off until an owner or admin turns it on. Cancel anytime; your plan runs to the end of the billing period.',
|
||||
{ currency: team.currency.toUpperCase() }
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
// The plans page's surrounding states: the value props, the loading skeleton and the load error.
|
||||
import { Cloud, KeyRound, Zap } from 'lucide-react'
|
||||
import { InlineError } from '@/components/ui/inline-error'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
|
||||
export function ValueProps(): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
// Same promises as the marketing site's /cloud page.
|
||||
const items = [
|
||||
{
|
||||
icon: Cloud,
|
||||
title: t('auto.components.billing.plans.vpRunningTitle', 'Agents keep running'),
|
||||
body: t(
|
||||
'auto.components.billing.plans.vpRunningBody2',
|
||||
'Sandboxes keep working while you are away and report back when they finish.'
|
||||
)
|
||||
},
|
||||
{
|
||||
icon: Zap,
|
||||
title: t('auto.components.billing.plans.vpWakeTitle', 'Wake in seconds'),
|
||||
body: t(
|
||||
'auto.components.billing.plans.vpWakeBody3',
|
||||
'Idle sandboxes sleep to save sandbox hours and wake with your files as you left them.'
|
||||
)
|
||||
},
|
||||
{
|
||||
icon: KeyRound,
|
||||
title: t('auto.components.billing.plans.vpSecretsTitleEdge', 'Agent keys stay out of the sandbox'),
|
||||
body: t(
|
||||
'auto.components.billing.plans.vpSecretsBodyEdge',
|
||||
'Model API keys and agent sign-ins are swapped in at the network edge. Other secrets are environment variables.'
|
||||
)
|
||||
}
|
||||
]
|
||||
return (
|
||||
<ul className="grid gap-4 sm:grid-cols-3 [@media(max-height:900px)]:hidden">
|
||||
{items.map((item) => (
|
||||
<li key={item.title} className="flex items-start gap-3">
|
||||
<span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
|
||||
<item.icon className="size-4" />
|
||||
</span>
|
||||
<div className="space-y-0.5">
|
||||
<p className="text-sm font-medium">{item.title}</p>
|
||||
<p className="text-xs leading-5 text-muted-foreground text-pretty">{item.body}</p>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
function SkeletonLine({ className }: { className: string }): React.JSX.Element {
|
||||
return <Skeleton className={className} />
|
||||
}
|
||||
|
||||
function SkeletonCard({
|
||||
lines,
|
||||
seatRow = false
|
||||
}: {
|
||||
lines: number
|
||||
seatRow?: boolean
|
||||
}): React.JSX.Element {
|
||||
return (
|
||||
<div className="flex h-full flex-col gap-5 rounded-xl border border-border bg-card p-5 shadow-xs">
|
||||
<SkeletonLine className="h-4 w-24" />
|
||||
<div className="space-y-2">
|
||||
<SkeletonLine className="h-8 w-32" />
|
||||
<SkeletonLine className="h-3 w-28" />
|
||||
</div>
|
||||
{seatRow ? <SkeletonLine className="h-9 w-full" /> : null}
|
||||
<div className="flex-1 space-y-3">
|
||||
{Array.from({ length: lines }, (_, index) => (
|
||||
<SkeletonLine key={index} className={index % 2 ? 'h-3 w-4/5' : 'h-3 w-11/12'} />
|
||||
))}
|
||||
</div>
|
||||
<div className="min-h-[6rem] space-y-2 border-t border-border/60 pt-4">
|
||||
<SkeletonLine className="h-9 w-full" />
|
||||
<SkeletonLine className="mx-auto h-3 w-3/5" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Same geometry as the loaded page (value props, toggle, two cards) so nothing jumps (review M4). */
|
||||
export function PlansSkeleton(): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
return (
|
||||
<div
|
||||
className="space-y-6"
|
||||
role="status"
|
||||
aria-label={t('auto.components.billing.plans.loading', 'Loading plans…')}
|
||||
>
|
||||
<ValueProps />
|
||||
<div className="flex justify-center">
|
||||
<Skeleton shape="circle" className="h-8 w-72" />
|
||||
</div>
|
||||
<div className="grid items-stretch gap-4 md:grid-cols-2">
|
||||
<SkeletonCard lines={5} seatRow />
|
||||
<SkeletonCard lines={4} />
|
||||
</div>
|
||||
<div className="mx-auto max-w-xl space-y-1.5">
|
||||
<Skeleton className="mx-auto h-3 w-2/3" />
|
||||
<Skeleton className="mx-auto h-3 w-5/6" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function PlansLoadError({ onRetry }: { onRetry: () => void }): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<ValueProps />
|
||||
<InlineError
|
||||
className="mx-auto my-16 max-w-md"
|
||||
title={t('auto.components.billing.plans.loadFailedTitle', 'Plans didn’t load')}
|
||||
detail={t(
|
||||
'auto.components.billing.plans.loadFailed2',
|
||||
'Couldn’t load plans. Try again in a moment.'
|
||||
)}
|
||||
retryLabel={t('auto.components.billing.plans.retry', 'Try again')}
|
||||
onRetry={onRetry}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,226 +0,0 @@
|
||||
import { ExternalLink, Lock, Users } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { InlineError } from '@/components/ui/inline-error'
|
||||
import type { PlanBillingNotice } from '../PlanBillingSection'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
|
||||
import type { OrcaBillingInterval } from '../../../../../shared/orca-billing'
|
||||
import type { TeamPlanModel } from './plans-model'
|
||||
import { planFeatureLines } from './plan-feature-copy'
|
||||
import { PlanCardShell } from './PlanCardShell'
|
||||
import { formatCents, perSeatMonthlyCents, periodTotalCents } from './plans-pricing'
|
||||
|
||||
export type TeamPlanCardMode = 'choose' | 'current' | 'locked'
|
||||
|
||||
export function TeamPlanCard({
|
||||
team,
|
||||
interval,
|
||||
seats,
|
||||
mode,
|
||||
busy,
|
||||
notice,
|
||||
hideManage,
|
||||
onCheckout,
|
||||
onManage
|
||||
}: {
|
||||
team: TeamPlanModel
|
||||
interval: OrcaBillingInterval
|
||||
seats: number
|
||||
/** choose: can buy; current: already on Team; locked: only owners/admins can buy. */
|
||||
mode: TeamPlanCardMode
|
||||
busy: boolean
|
||||
notice: PlanBillingNotice | null
|
||||
/** A payment banner already offers the same Portal action. */
|
||||
hideManage: boolean
|
||||
onCheckout: () => void
|
||||
onManage: () => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const locale = useIntlLocale()
|
||||
const monthly = perSeatMonthlyCents(team, interval)
|
||||
const fullMonthly = team.monthlyPriceCentsPerSeat
|
||||
const total = periodTotalCents(team, interval, seats)
|
||||
const discounted =
|
||||
interval === 'year' && monthly !== null && fullMonthly !== null && monthly < fullMonthly
|
||||
|
||||
// Which bullets, and their numbers, are billing's catalog; known ones are localized.
|
||||
const features = planFeatureLines(team.features, team, t, locale)
|
||||
const fmt = (cents: number): string => formatCents(cents, locale, team.currency)
|
||||
const legacyLabel = team.legacyPriceLabels?.[interval] || null
|
||||
|
||||
const price = (
|
||||
// Keyed so the figure fades in again when the period changes.
|
||||
<p
|
||||
key={interval}
|
||||
className="flex items-baseline gap-1.5 animate-in fade-in-0 slide-in-from-bottom-1 duration-200 motion-reduce:animate-none"
|
||||
>
|
||||
{discounted && fullMonthly !== null ? (
|
||||
<del className="text-lg text-muted-foreground tabular-nums">
|
||||
<span className="sr-only">{t('auto.components.billing.plans.was', 'Was')} </span>
|
||||
{fmt(fullMonthly)}
|
||||
</del>
|
||||
) : null}
|
||||
<span className="text-3xl font-semibold tracking-tight tabular-nums">
|
||||
{monthly === null
|
||||
? (legacyLabel ??
|
||||
t('auto.components.billing.plans.priceUnavailable', 'Price unavailable'))
|
||||
: fmt(monthly)}
|
||||
</span>
|
||||
{monthly === null ? null : (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t('auto.components.billing.plans.perSeatPerMonth', 'per seat per month')}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
)
|
||||
|
||||
const priceNote =
|
||||
interval === 'year'
|
||||
? team.annualPriceCentsPerSeat === null
|
||||
? t('auto.components.billing.plans.billedYearly', 'Billed yearly')
|
||||
: t(
|
||||
'auto.components.billing.plans.billedYearlyAmount2',
|
||||
'{{value0}} per seat, billed yearly',
|
||||
{
|
||||
value0: fmt(team.annualPriceCentsPerSeat)
|
||||
}
|
||||
)
|
||||
: t('auto.components.billing.plans.billedMonthly', 'Billed monthly')
|
||||
|
||||
const details =
|
||||
mode === 'choose' ? (
|
||||
<div className="flex items-baseline justify-between gap-3 rounded-md bg-muted/60 px-3 py-2">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
'auto.components.billing.plans.seatsPerMember',
|
||||
'{{count}} seats, one per team member',
|
||||
{
|
||||
count: seats,
|
||||
defaultValue_one: '{{count}} seat, one per team member'
|
||||
}
|
||||
)}
|
||||
</p>
|
||||
{total === null ? null : (
|
||||
<p className="text-sm font-medium tabular-nums" aria-live="polite">
|
||||
{interval === 'year'
|
||||
? t('auto.components.billing.plans.totalPerYear', '{{total}} per year', {
|
||||
total: fmt(total)
|
||||
})
|
||||
: t('auto.components.billing.plans.totalPerMonth', '{{total}} per month', {
|
||||
total: fmt(total)
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : null
|
||||
|
||||
let footer: React.ReactNode
|
||||
if (mode === 'choose' && !team.checkoutAvailable) {
|
||||
footer = (
|
||||
<p role="status" className="text-center text-xs text-muted-foreground text-pretty">
|
||||
{t(
|
||||
'auto.components.billing.plans.checkoutUnavailable',
|
||||
'This plan isn’t available right now. Try again later.'
|
||||
)}
|
||||
</p>
|
||||
)
|
||||
} else if (mode === 'choose') {
|
||||
footer = (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
className="w-full"
|
||||
aria-disabled={busy || undefined}
|
||||
onClick={busy ? undefined : onCheckout}
|
||||
>
|
||||
{busy ? <LoadingSpinner /> : null}
|
||||
{busy
|
||||
? t('auto.components.billing.plans.waiting', 'Waiting for checkout…')
|
||||
: t('auto.components.billing.plans.checkout', 'Continue to checkout')}
|
||||
{busy ? null : <ExternalLink />}
|
||||
</Button>
|
||||
{notice?.kind === 'error' ? (
|
||||
<InlineError title={notice.text} />
|
||||
) : (
|
||||
<p role="status" className="text-center text-xs text-muted-foreground text-pretty">
|
||||
{notice?.text ??
|
||||
t(
|
||||
'auto.components.billing.plans.seatsFollow2',
|
||||
'Seats follow your team: new members add a seat now; removed seats drop off at renewal.'
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
} else if (mode === 'current') {
|
||||
footer = hideManage ? (
|
||||
<p className="text-center text-xs text-muted-foreground">
|
||||
{t(
|
||||
'auto.components.billing.plans.fixPaymentAbove',
|
||||
'Update your payment method above to keep your plan active.'
|
||||
)}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
aria-disabled={busy || undefined}
|
||||
onClick={busy ? undefined : onManage}
|
||||
>
|
||||
{t('auto.components.billing.manageBilling', 'Manage billing')}
|
||||
<ExternalLink />
|
||||
</Button>
|
||||
{notice?.kind === 'error' ? (
|
||||
<InlineError title={notice.text} />
|
||||
) : (
|
||||
<p role="status" className="text-center text-xs text-muted-foreground">
|
||||
{notice?.text ??
|
||||
t(
|
||||
'auto.components.billing.plans.manageHint',
|
||||
'Switch monthly or annual, update payment, or cancel.'
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
} else {
|
||||
footer = (
|
||||
<div className="flex items-start gap-2 text-sm">
|
||||
<Lock className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
|
||||
<p className="text-pretty">
|
||||
{t(
|
||||
'auto.components.billing.plans.lockedBody2',
|
||||
'Only an owner or admin of your team can choose a plan. Ask one of them to open Plan & billing in Orca.'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<PlanCardShell
|
||||
id="plans-team-title"
|
||||
title={
|
||||
<>
|
||||
<Users className="size-4 text-muted-foreground" />
|
||||
{team.label}
|
||||
</>
|
||||
}
|
||||
badge={
|
||||
mode === 'current' ? (
|
||||
<Badge variant="secondary">
|
||||
{t('auto.components.billing.plans.currentPlan', 'Current plan')}
|
||||
</Badge>
|
||||
) : null
|
||||
}
|
||||
price={price}
|
||||
priceNote={priceNote}
|
||||
details={details}
|
||||
features={features}
|
||||
footer={footer}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
// A sample of billing's GET /v1/plans (as the main process parses it) for tests and fixtures:
|
||||
// the launch catalog (cloud/apps/billing/catalog/catalog.json) with Stripe TEST prices.
|
||||
import type {
|
||||
OrcaPlanCatalog,
|
||||
OrcaPlanCatalogResult
|
||||
} from '../../../../../shared/orca-billing-plans'
|
||||
|
||||
export const sampleCatalog: OrcaPlanCatalog = {
|
||||
catalogVersion: 'c_sample',
|
||||
plans: [
|
||||
{
|
||||
kind: 'trial',
|
||||
id: 'trial',
|
||||
name: 'Trial',
|
||||
version: 1,
|
||||
supportUrl: null,
|
||||
features: [
|
||||
{ id: 'trial_hours', params: { hours: 2 }, text: '2 sandbox hours to try Orca Cloud' }
|
||||
]
|
||||
},
|
||||
{
|
||||
kind: 'self_serve',
|
||||
id: 'team',
|
||||
name: 'Team',
|
||||
version: 2,
|
||||
supportUrl: 'https://orca.dev/enterprise',
|
||||
features: [
|
||||
{
|
||||
id: 'included_hours_per_seat',
|
||||
params: { hours: 60 },
|
||||
text: '60 sandbox hours per seat each month, pooled across your team'
|
||||
},
|
||||
{ id: 'sandbox_spec', params: {}, text: 'Every sandbox gets 8 vCPU and 16 GB' },
|
||||
{ id: 'ready_in_seconds', params: {}, text: 'Ready in seconds, nothing to set up or host' },
|
||||
{
|
||||
id: 'agents_keep_running',
|
||||
params: {},
|
||||
text: 'Agents keep running when you close your laptop'
|
||||
},
|
||||
{
|
||||
id: 'idle_sleep',
|
||||
params: {},
|
||||
text: 'Sandboxes sleep when idle, so you only use hours while they work'
|
||||
},
|
||||
{
|
||||
id: 'overage_optional',
|
||||
params: {},
|
||||
text: 'Optional overage up to a monthly spend cap you set'
|
||||
}
|
||||
],
|
||||
prices: [
|
||||
{ interval: 'month', unitAmountCents: 5000, currency: 'usd' },
|
||||
{ interval: 'year', unitAmountCents: 48000, currency: 'usd' }
|
||||
],
|
||||
overage: { centsPerHour: 100, defaultSpendCapCents: 2500, maxSpendCapCents: 500_000 },
|
||||
seats: { min: 1, max: 500 },
|
||||
includedHoursPerSeat: 60,
|
||||
checkoutAvailable: true
|
||||
},
|
||||
{
|
||||
kind: 'contact_sales',
|
||||
id: 'enterprise',
|
||||
name: 'Enterprise',
|
||||
version: 2,
|
||||
supportUrl: null,
|
||||
// Billing's current Enterprise version (catalog.json v2).
|
||||
features: [
|
||||
{ id: 'byoc', params: {}, text: 'Run sandboxes in your own cloud' },
|
||||
{ id: 'sso_scim', params: {}, text: 'SSO and SCIM' },
|
||||
{ id: 'mfa_enforcement', params: {}, text: 'Require multi-factor authentication' },
|
||||
{ id: 'audit_log', params: {}, text: 'Team audit log' },
|
||||
{ id: 'egress_controls', params: {}, text: 'Network egress controls' },
|
||||
{ id: 'custom_limits', params: {}, text: 'Custom limits and pricing' }
|
||||
],
|
||||
contactUrl: 'https://orca.dev/enterprise',
|
||||
priceLabel: 'Custom'
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
export const sampleCatalogResult: OrcaPlanCatalogResult = {
|
||||
status: 'ok',
|
||||
catalog: sampleCatalog,
|
||||
source: 'live',
|
||||
fetchedAt: Date.UTC(2026, 10, 12)
|
||||
}
|
||||
|
||||
/** The same catalog with only a monthly price on sale (Stripe has no annual price). */
|
||||
export const monthlyOnlyCatalogResult: OrcaPlanCatalogResult = {
|
||||
...sampleCatalogResult,
|
||||
catalog: {
|
||||
...sampleCatalog,
|
||||
plans: sampleCatalog.plans.map((plan) =>
|
||||
plan.kind === 'self_serve' && 'prices' in plan
|
||||
? { ...plan, prices: plan.prices.filter((price) => price.interval === 'month') }
|
||||
: plan
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { translate as t } from '@/i18n/i18n'
|
||||
import { planFeatureLine, planFeatureLines } from './plan-feature-copy'
|
||||
|
||||
const context = { overage: { centsPerHour: 100, defaultSpendCapCents: 2500 }, currency: 'usd' }
|
||||
|
||||
describe('plan feature copy', () => {
|
||||
it('localizes known ids with the catalog numbers', () => {
|
||||
expect(
|
||||
planFeatureLine(
|
||||
{ id: 'included_hours_per_seat', params: { hours: 60 }, text: 'x' },
|
||||
context,
|
||||
t,
|
||||
'en-US'
|
||||
)
|
||||
).toBe('60 sandbox hours per seat each month, pooled across your team')
|
||||
expect(
|
||||
planFeatureLine({ id: 'overage_optional', params: {}, text: 'x' }, context, t, 'en-US')
|
||||
).toBe(
|
||||
'Optional overage at $1.00 per sandbox hour, billed by the minute, up to a monthly spend cap you set ($25 by default)'
|
||||
)
|
||||
expect(
|
||||
planFeatureLine(
|
||||
{ id: 'overage_optional', params: {}, text: 'x' },
|
||||
{ overage: null, currency: 'usd' },
|
||||
t,
|
||||
'en-US'
|
||||
)
|
||||
).toBe('Optional overage up to a monthly spend cap you set')
|
||||
expect(
|
||||
planFeatureLine({ id: 'sandbox_spec', params: {}, text: 'x' }, context, t, 'en-US')
|
||||
).toMatch(/^Every sandbox gets \d+ vCPU · \d+ GB$/)
|
||||
expect(
|
||||
planFeatureLine({ id: 'idle_sleep', params: { minutes: 15 }, text: 'x' }, context, t, 'en-US')
|
||||
).toBe('Sleeps after 15 minutes idle, so quiet time is free')
|
||||
})
|
||||
|
||||
it('never advertises egress controls, which no team can configure yet', () => {
|
||||
const egress = { id: 'egress_controls', params: {}, text: 'Network egress controls' }
|
||||
expect(planFeatureLine(egress, context, t, 'en-US')).toBeNull()
|
||||
expect(
|
||||
planFeatureLines(
|
||||
[
|
||||
{ id: 'byoc', params: {}, text: 'x' },
|
||||
egress,
|
||||
{ id: 'custom_limits', params: {}, text: 'x' }
|
||||
],
|
||||
context,
|
||||
t,
|
||||
'en-US'
|
||||
)
|
||||
).toEqual(['Run sandboxes in your own cloud account', 'Custom limits, invoicing and terms'])
|
||||
})
|
||||
|
||||
it("shows billing's text for ids it does not know, or a known id missing its numbers", () => {
|
||||
expect(
|
||||
planFeatureLine(
|
||||
{ id: 'gpu_sandboxes', params: {}, text: 'GPU sandboxes' },
|
||||
context,
|
||||
t,
|
||||
'en-US'
|
||||
)
|
||||
).toBe('GPU sandboxes')
|
||||
expect(
|
||||
planFeatureLine(
|
||||
{ id: 'included_hours_per_seat', params: {}, text: 'Lots of hours' },
|
||||
context,
|
||||
t,
|
||||
'en-US'
|
||||
)
|
||||
).toBe('Lots of hours')
|
||||
expect(
|
||||
planFeatureLines([{ id: 'unknown', params: {}, text: ' ' }], context, t, 'en-US')
|
||||
).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -1,110 +0,0 @@
|
||||
// A plan feature from billing's catalog as one line of copy. Feature ids the desktop knows are
|
||||
// localized here, filled with the catalog's numbers; an id it doesn't know (a newer catalog) shows
|
||||
// billing's English text. Which features a plan lists, and their numbers, are billing's.
|
||||
import type { Translate } from '@/i18n/use-translate'
|
||||
import type { OrcaPlanFeature } from '../../../../../shared/orca-billing-plans'
|
||||
import { formatCents, formatRateCents } from './plans-pricing'
|
||||
import { ORCA_CLOUD_SANDBOX_SPEC } from '../../../../../shared/hosted-sandbox/hosted-sandbox-wire'
|
||||
|
||||
/** Plan-level numbers some feature lines quote (the overage rate and default cap). */
|
||||
export type PlanFeatureContext = {
|
||||
overage: { centsPerHour: number; defaultSpendCapCents: number } | null
|
||||
currency: string
|
||||
}
|
||||
|
||||
function numberParam(feature: OrcaPlanFeature, key: string): number | null {
|
||||
const value = feature.params[key]
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : null
|
||||
}
|
||||
|
||||
export function planFeatureLine(
|
||||
feature: OrcaPlanFeature,
|
||||
context: PlanFeatureContext,
|
||||
t: Translate,
|
||||
locale: string
|
||||
): string | null {
|
||||
const fallback = feature.text.trim() || null
|
||||
switch (feature.id) {
|
||||
case 'included_hours_per_seat': {
|
||||
const hours = numberParam(feature, 'hours')
|
||||
return hours === null
|
||||
? fallback
|
||||
: t(
|
||||
'auto.components.billing.plans.featureHours4',
|
||||
'{{value0}} sandbox hours per seat each month, pooled across your team',
|
||||
{ value0: String(hours) }
|
||||
)
|
||||
}
|
||||
case 'agents_keep_running':
|
||||
return t(
|
||||
'auto.components.billing.plans.featureKeepRunning',
|
||||
'Agents keep running when you close your laptop'
|
||||
)
|
||||
case 'idle_sleep': {
|
||||
const minutes = numberParam(feature, 'minutes')
|
||||
return minutes === null
|
||||
? t(
|
||||
'auto.components.billing.plans.featureIdleSleep',
|
||||
'Sandboxes sleep when idle, so you only use hours while they work'
|
||||
)
|
||||
: t(
|
||||
'auto.components.billing.plans.featureSleep3',
|
||||
'Sleeps after {{value0}} minutes idle, so quiet time is free',
|
||||
{ value0: String(minutes) }
|
||||
)
|
||||
}
|
||||
case 'overage_optional':
|
||||
return context.overage
|
||||
? t(
|
||||
'auto.components.billing.plans.featureOverage7',
|
||||
'Optional overage at {{rate}} per sandbox hour, billed by the minute, up to a monthly spend cap you set ({{cap}} by default)',
|
||||
{
|
||||
rate: formatRateCents(context.overage.centsPerHour, locale, context.currency),
|
||||
cap: formatCents(context.overage.defaultSpendCapCents, locale, context.currency)
|
||||
}
|
||||
)
|
||||
: t(
|
||||
'auto.components.billing.plans.featureOverageNoRate',
|
||||
'Optional overage up to a monthly spend cap you set'
|
||||
)
|
||||
case 'sandbox_spec':
|
||||
// The product's one sandbox size (glossary): the catalog only says to list it.
|
||||
return t(
|
||||
'auto.components.billing.plans.featureSpec',
|
||||
'Every sandbox gets {{value0}} vCPU · {{value1}} GB',
|
||||
{
|
||||
value0: String(ORCA_CLOUD_SANDBOX_SPEC.vcpus),
|
||||
value1: String(ORCA_CLOUD_SANDBOX_SPEC.memoryGb)
|
||||
}
|
||||
)
|
||||
case 'ready_in_seconds':
|
||||
return t(
|
||||
'auto.components.billing.plans.featureReady',
|
||||
'Ready in seconds, nothing to set up or host'
|
||||
)
|
||||
case 'byoc':
|
||||
return t('auto.components.billing.plans.entByoc', 'Run sandboxes in your own cloud account')
|
||||
case 'sso_scim':
|
||||
return t('auto.components.billing.plans.entSso', 'SSO and SCIM provisioning')
|
||||
case 'egress_controls':
|
||||
// Not offered yet: the sandbox egress policy is one operator-wide setting, open by default, and
|
||||
// no team can choose its own. The catalog keeps the feature; the desktop doesn't advertise it.
|
||||
return null
|
||||
case 'custom_limits':
|
||||
return t('auto.components.billing.plans.entTerms', 'Custom limits, invoicing and terms')
|
||||
default:
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
export function planFeatureLines(
|
||||
features: readonly OrcaPlanFeature[],
|
||||
context: PlanFeatureContext,
|
||||
t: Translate,
|
||||
locale: string
|
||||
): string[] {
|
||||
return features.flatMap((feature) => {
|
||||
const line = planFeatureLine(feature, context, t, locale)
|
||||
return line ? [line] : []
|
||||
})
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { sampleOffers, sampleTeam } from '../plan-billing-fixtures'
|
||||
import {
|
||||
monthlyOnlyCatalogResult,
|
||||
sampleCatalog,
|
||||
sampleCatalogResult
|
||||
} from './plan-catalog-fixtures'
|
||||
import {
|
||||
planContactUrl,
|
||||
plansModelFromCatalog,
|
||||
plansModelFromOffers,
|
||||
resolvePlansModel
|
||||
} from './plans-model'
|
||||
|
||||
const billing = { status: 'ok' as const, entitlement: sampleTeam }
|
||||
|
||||
describe('plans model', () => {
|
||||
it('takes prices, features, seats and Enterprise from the catalog', () => {
|
||||
const model = plansModelFromCatalog(sampleCatalog)
|
||||
expect(model?.source).toBe('catalog')
|
||||
expect(model?.team).toMatchObject({
|
||||
planId: 'team',
|
||||
label: 'Team',
|
||||
currency: 'usd',
|
||||
monthlyPriceCentsPerSeat: 5000,
|
||||
annualPriceCentsPerSeat: 48000,
|
||||
intervals: ['month', 'year'],
|
||||
seats: { min: 1, max: 500 },
|
||||
checkoutAvailable: true
|
||||
})
|
||||
expect(model?.team.features.map((feature) => feature.id)).toEqual([
|
||||
'included_hours_per_seat',
|
||||
'sandbox_spec',
|
||||
'ready_in_seconds',
|
||||
'agents_keep_running',
|
||||
'idle_sleep',
|
||||
'overage_optional'
|
||||
])
|
||||
expect(model?.enterprise?.features.map((feature) => feature.id)).toEqual([
|
||||
'byoc',
|
||||
'sso_scim',
|
||||
'mfa_enforcement',
|
||||
'audit_log',
|
||||
'egress_controls',
|
||||
'custom_limits'
|
||||
])
|
||||
})
|
||||
|
||||
it('sells only the intervals Stripe has a price for', () => {
|
||||
const model =
|
||||
monthlyOnlyCatalogResult.status === 'ok'
|
||||
? plansModelFromCatalog(monthlyOnlyCatalogResult.catalog)
|
||||
: null
|
||||
expect(model?.team).toMatchObject({ intervals: ['month'], annualPriceCentsPerSeat: null })
|
||||
})
|
||||
|
||||
it('reads an older service through its offers (billing numbers, no Enterprise bullets)', () => {
|
||||
const model = plansModelFromOffers(sampleOffers)
|
||||
expect(model.source).toBe('offers')
|
||||
expect(model.team).toMatchObject({
|
||||
planId: 'team',
|
||||
monthlyPriceCentsPerSeat: 5000,
|
||||
intervals: ['month', 'year']
|
||||
})
|
||||
expect(model.team.features[0]).toEqual({
|
||||
id: 'included_hours_per_seat',
|
||||
params: { hours: 60 },
|
||||
text: ''
|
||||
})
|
||||
expect(model.enterprise?.features).toEqual([])
|
||||
})
|
||||
|
||||
it('resolves loading, catalog, the 404 fallback and failure', () => {
|
||||
expect(resolvePlansModel(null, billing)).toEqual({ state: 'loading' })
|
||||
expect(resolvePlansModel(sampleCatalogResult, null)).toMatchObject({
|
||||
state: 'ready',
|
||||
model: { source: 'catalog' }
|
||||
})
|
||||
expect(resolvePlansModel({ status: 'unsupported' }, billing)).toMatchObject({
|
||||
state: 'ready',
|
||||
model: { source: 'offers' }
|
||||
})
|
||||
expect(resolvePlansModel({ status: 'failed', error: 'x' }, billing)).toMatchObject({
|
||||
state: 'ready',
|
||||
model: { source: 'offers' }
|
||||
})
|
||||
expect(
|
||||
resolvePlansModel(
|
||||
{ status: 'failed', error: 'x' },
|
||||
{ status: 'ok', entitlement: { ...sampleTeam, offers: null } }
|
||||
)
|
||||
).toEqual({ state: 'failed' })
|
||||
expect(resolvePlansModel({ status: 'unsupported' }, { status: 'failed', error: 'x' })).toEqual({
|
||||
state: 'failed'
|
||||
})
|
||||
})
|
||||
|
||||
it("sends Contact us to the plan's supportUrl, else Enterprise's contact", () => {
|
||||
const model = plansModelFromCatalog(sampleCatalog)!
|
||||
expect(planContactUrl(model)).toBe('https://orca.dev/enterprise')
|
||||
expect(planContactUrl({ ...model, team: { ...model.team, supportUrl: null } })).toBe(
|
||||
model.enterprise!.contactUrl
|
||||
)
|
||||
expect(
|
||||
planContactUrl({ ...model, team: { ...model.team, supportUrl: null }, enterprise: null })
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,175 +0,0 @@
|
||||
// What the plans dialog renders, from billing's plan catalog (GET /v1/plans). Every price, feature
|
||||
// and bound here is billing's: prices are Stripe's, features and seat bounds the billing catalog's.
|
||||
// A billing service from before the catalog (404) is read through its entitlement `offers`, which
|
||||
// are billing's numbers too; the desktop never supplies a price or a feature of its own.
|
||||
import type {
|
||||
OrcaBillingInterval,
|
||||
OrcaBillingOffers,
|
||||
OrcaBillingStatusResult
|
||||
} from '../../../../../shared/orca-billing'
|
||||
import {
|
||||
isContactSalesPlan,
|
||||
isSelfServePlan,
|
||||
type OrcaPlanCatalog,
|
||||
type OrcaPlanCatalogResult,
|
||||
type OrcaPlanFeature
|
||||
} from '../../../../../shared/orca-billing-plans'
|
||||
import { ORCA_BILLING_MAX_SEATS } from '../../../../../shared/orca-billing'
|
||||
|
||||
export type TeamPlanModel = {
|
||||
/** Sent to Checkout; billing resolves the Stripe price for it. */
|
||||
planId: string
|
||||
label: string
|
||||
currency: string
|
||||
monthlyPriceCentsPerSeat: number | null
|
||||
annualPriceCentsPerSeat: number | null
|
||||
/** Intervals on sale (priced), in display order. */
|
||||
intervals: OrcaBillingInterval[]
|
||||
seats: { min: number; max: number }
|
||||
features: OrcaPlanFeature[]
|
||||
includedHoursPerSeat: number | null
|
||||
overage: { centsPerHour: number; defaultSpendCapCents: number } | null
|
||||
idleSleepMinutes: number | null
|
||||
checkoutAvailable: boolean
|
||||
/** An older service's display labels, for a price it sends no cents for. */
|
||||
legacyPriceLabels: { month: string; year: string } | null
|
||||
/** The plan's own "Contact us" (https), when the catalog names one. */
|
||||
supportUrl: string | null
|
||||
}
|
||||
|
||||
export type EnterprisePlanModel = {
|
||||
label: string
|
||||
priceLabel: string | null
|
||||
contactUrl: string | null
|
||||
features: OrcaPlanFeature[]
|
||||
}
|
||||
|
||||
export type PlansModel = {
|
||||
team: TeamPlanModel
|
||||
enterprise: EnterprisePlanModel | null
|
||||
source: 'catalog' | 'offers'
|
||||
}
|
||||
|
||||
export function plansModelFromCatalog(catalog: OrcaPlanCatalog): PlansModel | null {
|
||||
const team = catalog.plans.find(isSelfServePlan)
|
||||
if (!team) {
|
||||
return null
|
||||
}
|
||||
const price = (interval: OrcaBillingInterval) =>
|
||||
team.prices.find((entry) => entry.interval === interval) ?? null
|
||||
const monthly = price('month')
|
||||
const annual = price('year')
|
||||
const enterprise = catalog.plans.find(isContactSalesPlan)
|
||||
return {
|
||||
source: 'catalog',
|
||||
team: {
|
||||
planId: team.id,
|
||||
label: team.name,
|
||||
currency: (monthly ?? annual)?.currency ?? 'usd',
|
||||
monthlyPriceCentsPerSeat: monthly?.unitAmountCents ?? null,
|
||||
annualPriceCentsPerSeat: annual?.unitAmountCents ?? null,
|
||||
intervals: [monthly, annual].flatMap((entry) => (entry ? [entry.interval] : [])),
|
||||
seats: team.seats,
|
||||
features: team.features,
|
||||
includedHoursPerSeat: team.includedHoursPerSeat,
|
||||
overage: team.overage,
|
||||
idleSleepMinutes: null,
|
||||
checkoutAvailable: team.checkoutAvailable,
|
||||
legacyPriceLabels: null,
|
||||
supportUrl: team.supportUrl
|
||||
},
|
||||
enterprise: enterprise
|
||||
? {
|
||||
label: enterprise.name,
|
||||
priceLabel: enterprise.priceLabel,
|
||||
contactUrl: enterprise.contactUrl,
|
||||
features: enterprise.features
|
||||
}
|
||||
: null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An older billing service (no GET /v1/plans): its entitlement offers, as the same model. The
|
||||
* feature ids below are the catalog's own; their numbers are the offers' (billing's).
|
||||
*/
|
||||
export function plansModelFromOffers(offers: OrcaBillingOffers): PlansModel {
|
||||
const team = offers.team
|
||||
const intervals: OrcaBillingInterval[] = []
|
||||
if (team.monthlyPriceCentsPerSeat !== null) {
|
||||
intervals.push('month')
|
||||
}
|
||||
if (team.annualPriceCentsPerSeat !== null) {
|
||||
intervals.push('year')
|
||||
}
|
||||
const feature = (id: string, params: Record<string, number> = {}): OrcaPlanFeature => ({
|
||||
id,
|
||||
params,
|
||||
text: ''
|
||||
})
|
||||
return {
|
||||
source: 'offers',
|
||||
team: {
|
||||
planId: 'team',
|
||||
label: team.label,
|
||||
currency: 'usd',
|
||||
monthlyPriceCentsPerSeat: team.monthlyPriceCentsPerSeat,
|
||||
annualPriceCentsPerSeat: team.annualPriceCentsPerSeat,
|
||||
// Services without per-seat cents still sell both intervals by their price labels.
|
||||
intervals: intervals.length > 0 ? intervals : ['month', 'year'],
|
||||
seats: { min: 1, max: ORCA_BILLING_MAX_SEATS },
|
||||
features: [
|
||||
feature('included_hours_per_seat', { hours: team.includedHoursPerSeat }),
|
||||
feature('idle_sleep', { minutes: team.idleSleepMinutes }),
|
||||
feature('overage_optional')
|
||||
],
|
||||
includedHoursPerSeat: team.includedHoursPerSeat,
|
||||
overage: {
|
||||
centsPerHour: team.overageCentsPerHour,
|
||||
defaultSpendCapCents: team.defaultSpendCapCents
|
||||
},
|
||||
idleSleepMinutes: team.idleSleepMinutes,
|
||||
checkoutAvailable: true,
|
||||
legacyPriceLabels: { month: team.monthlyPriceLabel, year: team.annualPriceLabel },
|
||||
supportUrl: null
|
||||
},
|
||||
enterprise: {
|
||||
label: offers.enterprise.label,
|
||||
priceLabel: offers.enterprise.priceLabel,
|
||||
contactUrl: offers.enterprise.contactUrl,
|
||||
// Older services name no Enterprise features; the card leads with "Contact sales".
|
||||
features: []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type PlansModelState =
|
||||
| { state: 'loading' }
|
||||
| { state: 'ready'; model: PlansModel }
|
||||
| { state: 'failed' }
|
||||
|
||||
/**
|
||||
* Catalog first. The entitlement's offers stand in only when the service predates the catalog,
|
||||
* or the catalog couldn't be read (they are billing's numbers as well). Nothing usable: failed.
|
||||
*/
|
||||
export function resolvePlansModel(
|
||||
catalog: OrcaPlanCatalogResult | null,
|
||||
billing: OrcaBillingStatusResult | null
|
||||
): PlansModelState {
|
||||
if (catalog?.status === 'ok') {
|
||||
const model = plansModelFromCatalog(catalog.catalog)
|
||||
if (model) {
|
||||
return { state: 'ready', model }
|
||||
}
|
||||
}
|
||||
const offers = billing?.status === 'ok' ? billing.entitlement.offers : null
|
||||
if (catalog === null || billing === null) {
|
||||
return { state: 'loading' }
|
||||
}
|
||||
return offers ? { state: 'ready', model: plansModelFromOffers(offers) } : { state: 'failed' }
|
||||
}
|
||||
|
||||
/** Where "Contact us" goes when billing can't sell the plan: its support URL, else Enterprise's contact. */
|
||||
export function planContactUrl(model: PlansModel): string | null {
|
||||
return model.team.supportUrl ?? model.enterprise?.contactUrl ?? null
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
// Open state for the plans page. Any entry point (account menu, Settings, a "start a cloud
|
||||
// sandbox" upsell) calls openPlansPage(); PlansDialogHost renders it.
|
||||
import { useSyncExternalStore } from 'react'
|
||||
|
||||
export type PlansPageSource = 'account-menu' | 'settings' | 'sandbox' | 'team' | 'run-on' | 'other'
|
||||
|
||||
type PlansPageState = { open: boolean; source: PlansPageSource | null }
|
||||
|
||||
let state: PlansPageState = { open: false, source: null }
|
||||
const listeners = new Set<() => void>()
|
||||
|
||||
function set(next: PlansPageState): void {
|
||||
state = next
|
||||
for (const listener of listeners) {
|
||||
listener()
|
||||
}
|
||||
}
|
||||
|
||||
export function openPlansPage(source: PlansPageSource = 'other'): void {
|
||||
set({ open: true, source })
|
||||
}
|
||||
|
||||
export function closePlansPage(): void {
|
||||
set({ open: false, source: state.source })
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener)
|
||||
return () => listeners.delete(listener)
|
||||
}
|
||||
|
||||
export function getPlansPageState(): PlansPageState {
|
||||
return state
|
||||
}
|
||||
|
||||
export function usePlansPageState(): PlansPageState {
|
||||
return useSyncExternalStore(subscribe, getPlansPageState)
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { sampleOffers } from '../plan-billing-fixtures'
|
||||
import {
|
||||
annualSavingsPercent,
|
||||
clampSeats,
|
||||
formatCents,
|
||||
formatRateCents,
|
||||
perSeatMonthlyCents,
|
||||
periodTotalCents
|
||||
} from './plans-pricing'
|
||||
import { closePlansPage, getPlansPageState, openPlansPage } from './plans-page-store'
|
||||
|
||||
const team = sampleOffers.team
|
||||
|
||||
describe('plans pricing', () => {
|
||||
it('shows annual as its monthly equivalent and totals per period', () => {
|
||||
expect(perSeatMonthlyCents(team, 'month')).toBe(5000)
|
||||
expect(perSeatMonthlyCents(team, 'year')).toBe(4000)
|
||||
expect(periodTotalCents(team, 'month', 3)).toBe(15000)
|
||||
expect(periodTotalCents(team, 'year', 3)).toBe(144000)
|
||||
expect(periodTotalCents(team, 'year', 0)).toBe(48000)
|
||||
})
|
||||
|
||||
it('computes the annual saving and hides it when annual is not cheaper', () => {
|
||||
expect(annualSavingsPercent(team)).toBe(20)
|
||||
expect(annualSavingsPercent({ ...team, annualPriceCentsPerSeat: 60000 })).toBeNull()
|
||||
expect(annualSavingsPercent({ ...team, monthlyPriceCentsPerSeat: null })).toBeNull()
|
||||
})
|
||||
|
||||
it('falls back to labels when an older service sends no cents', () => {
|
||||
const legacy = { ...team, monthlyPriceCentsPerSeat: null, annualPriceCentsPerSeat: null }
|
||||
expect(perSeatMonthlyCents(legacy, 'month')).toBeNull()
|
||||
expect(periodTotalCents(legacy, 'year', 2)).toBeNull()
|
||||
})
|
||||
|
||||
it('formats whole and fractional dollars', () => {
|
||||
expect(formatCents(5000, 'en-US')).toBe('$50')
|
||||
expect(formatCents(75, 'en-US')).toBe('$0.75')
|
||||
expect(formatCents(144000, 'en-US')).toBe('$1,440')
|
||||
})
|
||||
|
||||
it('always shows cents on a per-hour rate', () => {
|
||||
expect(formatRateCents(100, 'en-US')).toBe('$1.00')
|
||||
expect(formatRateCents(75, 'en-US')).toBe('$0.75')
|
||||
})
|
||||
|
||||
it('clamps seats to 1..max', () => {
|
||||
expect(clampSeats(0, 500)).toBe(1)
|
||||
expect(clampSeats(Number.NaN, 500)).toBe(1)
|
||||
expect(clampSeats(900, 500)).toBe(500)
|
||||
expect(clampSeats(3.6, 500)).toBe(4)
|
||||
})
|
||||
})
|
||||
|
||||
describe('plans page store', () => {
|
||||
it('opens from any entry point and closes', () => {
|
||||
openPlansPage('sandbox')
|
||||
expect(getPlansPageState()).toEqual({ open: true, source: 'sandbox' })
|
||||
closePlansPage()
|
||||
expect(getPlansPageState().open).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,59 +0,0 @@
|
||||
// Price math for the plans page. Every number comes from the billing service: its plan catalog
|
||||
// (Stripe's prices), or an older service's offers.
|
||||
import type { OrcaBillingInterval } from '../../../../../shared/orca-billing'
|
||||
|
||||
/** Per-seat prices in cents; null where billing has no price for that interval. */
|
||||
type TeamOffer = { monthlyPriceCentsPerSeat: number | null; annualPriceCentsPerSeat: number | null }
|
||||
|
||||
/** What one seat costs per month on this interval (annual shown as its monthly equivalent). */
|
||||
export function perSeatMonthlyCents(team: TeamOffer, interval: OrcaBillingInterval): number | null {
|
||||
if (interval === 'month') {
|
||||
return team.monthlyPriceCentsPerSeat
|
||||
}
|
||||
return team.annualPriceCentsPerSeat === null
|
||||
? null
|
||||
: Math.round(team.annualPriceCentsPerSeat / 12)
|
||||
}
|
||||
|
||||
/** The amount billed each period for `seats` seats. */
|
||||
export function periodTotalCents(
|
||||
team: TeamOffer,
|
||||
interval: OrcaBillingInterval,
|
||||
seats: number
|
||||
): number | null {
|
||||
const perSeat =
|
||||
interval === 'month' ? team.monthlyPriceCentsPerSeat : team.annualPriceCentsPerSeat
|
||||
return perSeat === null ? null : perSeat * Math.max(1, seats)
|
||||
}
|
||||
|
||||
/** Whole-percent saving of annual over twelve monthly payments, or null when not cheaper. */
|
||||
export function annualSavingsPercent(team: TeamOffer): number | null {
|
||||
const monthly = team.monthlyPriceCentsPerSeat
|
||||
const annual = team.annualPriceCentsPerSeat
|
||||
if (monthly === null || annual === null || monthly <= 0) {
|
||||
return null
|
||||
}
|
||||
const percent = Math.round((1 - annual / (monthly * 12)) * 100)
|
||||
return percent > 0 ? percent : null
|
||||
}
|
||||
|
||||
export { formatCents } from '../../../../../shared/orca-billing-usage-alerts'
|
||||
|
||||
/** A per-hour rate always shows cents ("$1.00", "$0.75"), unlike whole-dollar prices. */
|
||||
export function formatRateCents(cents: number, locale: string, currency = 'usd'): string {
|
||||
return new Intl.NumberFormat(locale, {
|
||||
style: 'currency',
|
||||
currency: currency.toUpperCase(),
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2
|
||||
}).format(cents / 100)
|
||||
}
|
||||
|
||||
export const MIN_SEATS = 1
|
||||
|
||||
export function clampSeats(value: number, max: number): number {
|
||||
if (!Number.isFinite(value)) {
|
||||
return MIN_SEATS
|
||||
}
|
||||
return Math.min(max, Math.max(MIN_SEATS, Math.round(value)))
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import { useOrgRoster } from '../team/use-org-roster'
|
||||
|
||||
/**
|
||||
* Seats Team bills at Checkout: the active org's members (pending invites excluded), or 1 for a
|
||||
* personal account. Billing re-reads the count from auth; this is only for showing the total.
|
||||
*/
|
||||
export function useOrgSeatCount(orgId: string | null): number {
|
||||
const roster = useOrgRoster(orgId)
|
||||
if (!orgId || roster.result?.status !== 'ok') {
|
||||
return 1
|
||||
}
|
||||
return Math.max(1, roster.result.roster.members.length)
|
||||
}
|
||||
@@ -4,6 +4,8 @@ const auth = vi.hoisted(() => {
|
||||
const state: { status: unknown } = { status: null }
|
||||
return state
|
||||
})
|
||||
const openCloudConsole = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/lib/orca-cloud/open-cloud-console', () => ({ openCloudConsole }))
|
||||
vi.mock('@/store/index', () => ({
|
||||
useAppStore: {
|
||||
getState: () => ({ orcaProfileAuthStatus: auth.status }),
|
||||
@@ -18,8 +20,6 @@ import {
|
||||
import { getBillingReadInFlight, recordBillingStatus } from './billing-summary-store'
|
||||
import { sampleTeam } from './plan-billing-fixtures'
|
||||
import { BILLING_CAPABILITY, registerPlanBillingMenuItem } from './register-plan-billing-menu-item'
|
||||
import { getPlansPageState } from './plans/plans-page-store'
|
||||
import { closeTeamPage, getTeamPageState } from './team/team-page-store'
|
||||
|
||||
const visible = (): string[] =>
|
||||
selectVisibleAccountMenuItems(getRegisteredAccountMenuItems(), {
|
||||
@@ -34,7 +34,7 @@ afterEach(() => {
|
||||
auth.status = null
|
||||
vi.unstubAllGlobals()
|
||||
recordBillingStatus({ status: 'signed-out' })
|
||||
closeTeamPage()
|
||||
openCloudConsole.mockReset()
|
||||
})
|
||||
|
||||
describe('account menu billing items', () => {
|
||||
@@ -52,7 +52,7 @@ describe('account menu billing items', () => {
|
||||
expect(visible()).toEqual(['orca.team', 'orca.plan-billing'])
|
||||
const plans = getRegisteredAccountMenuItems().find((item) => item.id === 'orca.plan-billing')
|
||||
plans?.onSelect()
|
||||
expect(getPlansPageState()).toEqual({ open: true, source: 'account-menu' })
|
||||
expect(openCloudConsole).toHaveBeenCalledWith('billing')
|
||||
dispose()
|
||||
expect(getRegisteredAccountMenuItems()).toHaveLength(0)
|
||||
})
|
||||
@@ -73,12 +73,12 @@ describe('account menu billing items', () => {
|
||||
dispose()
|
||||
})
|
||||
|
||||
it('opens the Team page from the Team item', () => {
|
||||
it('opens the team console page from the Team item', () => {
|
||||
const dispose = registerPlanBillingMenuItem()
|
||||
getRegisteredAccountMenuItems()
|
||||
.find((item) => item.id === 'orca.team')
|
||||
?.onSelect()
|
||||
expect(getTeamPageState()).toEqual({ open: true, arrival: null })
|
||||
expect(openCloudConsole).toHaveBeenCalledWith('team')
|
||||
dispose()
|
||||
})
|
||||
|
||||
|
||||
@@ -8,8 +8,7 @@ import {
|
||||
resetBillingSummary,
|
||||
subscribeBillingSummary
|
||||
} from './billing-summary-store'
|
||||
import { openPlansPage } from './plans/plans-page-store'
|
||||
import { openTeamPage } from './team/team-page-store'
|
||||
import { openCloudConsole } from '@/lib/orca-cloud/open-cloud-console'
|
||||
|
||||
/** Cloud capability flag that turns billing on per account (server-controlled rollout). */
|
||||
export const BILLING_CAPABILITY = 'billing'
|
||||
@@ -17,8 +16,8 @@ export const BILLING_CAPABILITY = 'billing'
|
||||
const UPGRADE_ITEM_ID = 'orca.upgrade'
|
||||
|
||||
/**
|
||||
* Account menu: "Team" opens the Team page; "Plan & billing" opens the plans page. Accounts
|
||||
* without a plan also get "Upgrade to Orca Cloud" at the top of the group.
|
||||
* Account menu: "Team" and "Plan & billing" open the web console in the browser. Accounts without
|
||||
* a plan get "Upgrade to Orca Cloud" (also the console's billing page) in place of Plan & billing.
|
||||
*/
|
||||
export function registerPlanBillingMenuItem(): () => void {
|
||||
const registerBilling = (): (() => void) =>
|
||||
@@ -28,7 +27,7 @@ export function registerPlanBillingMenuItem(): () => void {
|
||||
icon: CreditCard,
|
||||
order: 11,
|
||||
requiredCapability: BILLING_CAPABILITY,
|
||||
onSelect: () => openPlansPage('account-menu')
|
||||
onSelect: () => void openCloudConsole('billing')
|
||||
})
|
||||
let disposeBilling: (() => void) | null = registerBilling()
|
||||
const disposeTeam = registerAccountMenuItem({
|
||||
@@ -38,7 +37,7 @@ export function registerPlanBillingMenuItem(): () => void {
|
||||
order: 10,
|
||||
// Team management doesn't depend on billing or a flag: any signed-in account can open it.
|
||||
requiresSignIn: true,
|
||||
onSelect: () => openTeamPage()
|
||||
onSelect: () => void openCloudConsole('team')
|
||||
})
|
||||
|
||||
let disposeUpgrade: (() => void) | null = null
|
||||
@@ -60,7 +59,7 @@ export function registerPlanBillingMenuItem(): () => void {
|
||||
order: 9,
|
||||
tone: 'accent',
|
||||
requiredCapability: BILLING_CAPABILITY,
|
||||
onSelect: () => openPlansPage('account-menu')
|
||||
onSelect: () => void openCloudConsole('billing')
|
||||
})
|
||||
} else if (!show && disposeUpgrade) {
|
||||
disposeUpgrade()
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
// JA-07: home, Plan & billing, the composer and the account menu once showed four numbers for the
|
||||
// same hours. Every surface now goes through one rounding rule; these pin it.
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { Translate } from '@/i18n/use-translate'
|
||||
import type { OrcaBillingUsageHistory } from '../../../../shared/orca-billing'
|
||||
import { getOrcaCloudHoursLeft } from '../new-workspace/orca-cloud-run-target-access'
|
||||
import { formatHoursUsed, sandboxHoursLeft, sandboxHoursUsed } from './plan-billing-format'
|
||||
import { sandboxHoursCount } from './plan-billing-usage-copy'
|
||||
@@ -41,23 +39,4 @@ describe('sandbox hours: one rule on every surface', () => {
|
||||
expect(Math.round(total * 10) / 10).toBe(180)
|
||||
}
|
||||
})
|
||||
|
||||
// JA-07 re-run: member page showed "18 used" beside "17.9 in 30 days" for the same usage.
|
||||
it('usage amounts on Plan & billing round like "used"', async () => {
|
||||
const { usageWindowTotalLine, yourUsageLine } = await import('./plan-billing-usage-history')
|
||||
const t: Translate = (_key, fallback, values) =>
|
||||
fallback.replace(/\{\{(\w+)\}\}/g, (_m, name: string) => String(values?.[name] ?? ''))
|
||||
const seconds = 17.94 * HOUR
|
||||
const history: OrcaBillingUsageHistory = {
|
||||
days: [],
|
||||
totalSeconds: seconds,
|
||||
yourSeconds: seconds,
|
||||
members: null,
|
||||
sandboxes: null
|
||||
}
|
||||
expect(formatHoursUsed(seconds)).toBe('18')
|
||||
expect(usageWindowTotalLine(seconds, t)).toContain('18 sandbox hours in 30 days')
|
||||
expect(yourUsageLine(history, t)).toContain('You used 18 of')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
import { isValidOrgName, ORCA_ORG_NAME_MAX_LENGTH } from '../../../../../shared/orca-org-management'
|
||||
import { useId, useState } from 'react'
|
||||
import { ArrowRight, Users } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import type { OrcaCloudOrgSummary } from '../../../../../shared/orca-profiles'
|
||||
import { TeamMark } from './TeamAvatar'
|
||||
import { normalizeOrgRole, roleLabel } from './team-roles'
|
||||
|
||||
export type TeamCreateViewProps = {
|
||||
/** Teams the user already belongs to (switch instead of creating). */
|
||||
organizations: OrcaCloudOrgSummary[]
|
||||
creating: boolean
|
||||
error: string | null
|
||||
/** This account service can't create teams yet: show a notice, not a field error. */
|
||||
unavailable: boolean
|
||||
switchingOrgId: string | null
|
||||
onCreate: (name: string) => void
|
||||
onSwitch: (orgId: string) => void
|
||||
}
|
||||
|
||||
/** Personal account: create a team (you become its owner) or switch to one you're in. */
|
||||
export function TeamCreateView(props: TeamCreateViewProps): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const id = useId()
|
||||
const [name, setName] = useState('')
|
||||
const trimmed = name.trim()
|
||||
const nameValid = isValidOrgName(trimmed)
|
||||
const showRule = trimmed.length > 0 && !nameValid
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<section
|
||||
aria-labelledby={`${id}-title`}
|
||||
className="rounded-xl border border-border bg-card p-5 shadow-xs"
|
||||
>
|
||||
<div className="flex items-start gap-4">
|
||||
<span className="flex size-10 shrink-0 items-center justify-center rounded-lg border border-dashed border-border text-muted-foreground">
|
||||
<Users className="size-5" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<h3 id={`${id}-title`} className="text-base font-semibold">
|
||||
{t('auto.components.billing.team.createTitle', 'Create a team')}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground text-pretty">
|
||||
{t(
|
||||
'auto.components.billing.team.createBody',
|
||||
'You’re on a personal account. A team shares one Orca Cloud plan: invite people, manage seats and billing in one place. You’ll be its owner.'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<form
|
||||
className="mt-4 space-y-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
if (nameValid && !props.creating && !props.unavailable) {
|
||||
props.onCreate(trimmed)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<label htmlFor={`${id}-name`} className="text-sm font-medium">
|
||||
{t('auto.components.billing.team.teamName', 'Team name')}
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id={`${id}-name`}
|
||||
value={name}
|
||||
maxLength={ORCA_ORG_NAME_MAX_LENGTH}
|
||||
placeholder={t(
|
||||
'auto.components.billing.team.teamNamePlaceholder',
|
||||
'Acme Engineering'
|
||||
)}
|
||||
aria-invalid={props.error || showRule ? true : undefined}
|
||||
aria-describedby={props.error ? `${id}-error` : showRule ? `${id}-rule` : undefined}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
readOnly={props.creating}
|
||||
aria-disabled={props.creating || undefined}
|
||||
disabled={props.unavailable}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!props.creating && (!nameValid || props.unavailable)}
|
||||
aria-disabled={props.creating || undefined}
|
||||
>
|
||||
{props.creating ? <LoadingSpinner className="size-3.5" /> : null}
|
||||
{t('auto.components.billing.team.createCta', 'Create team')}
|
||||
</Button>
|
||||
</div>
|
||||
{props.unavailable ? (
|
||||
<p
|
||||
role="status"
|
||||
className="rounded-md bg-muted px-3 py-2 text-xs text-muted-foreground"
|
||||
>
|
||||
{t(
|
||||
'auto.components.billing.team.createUnavailable',
|
||||
'Team creation isn’t available yet. Ask a teammate to invite you.'
|
||||
)}
|
||||
</p>
|
||||
) : null}
|
||||
{showRule && !props.error ? (
|
||||
<p id={`${id}-rule`} className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
'auto.components.billing.team.createInvalid2',
|
||||
'Use letters, numbers, spaces or underscores (up to 64).'
|
||||
)}
|
||||
</p>
|
||||
) : null}
|
||||
{props.error ? (
|
||||
<p id={`${id}-error`} role="alert" className="text-xs text-destructive">
|
||||
{props.error}
|
||||
</p>
|
||||
) : null}
|
||||
</form>
|
||||
</section>
|
||||
|
||||
{props.organizations.length > 0 ? (
|
||||
<section aria-labelledby={`${id}-switch`} className="space-y-2">
|
||||
<h3 id={`${id}-switch`} className="text-sm font-medium">
|
||||
{t('auto.components.billing.team.yourTeams', 'Or open a team you’re in')}
|
||||
</h3>
|
||||
<ul className="divide-y divide-border/60 overflow-hidden rounded-lg border border-border">
|
||||
{props.organizations.map((org) => (
|
||||
<li key={org.orgId} className="flex items-center gap-3 bg-card px-3 py-2.5">
|
||||
<TeamMark name={org.name} className="size-8 text-xs" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium">{org.name}</p>
|
||||
{org.role ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{roleLabel(normalizeOrgRole(org.role), t)}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-disabled={props.switchingOrgId !== null || undefined}
|
||||
onClick={() => {
|
||||
if (props.switchingOrgId === null) {
|
||||
props.onSwitch(org.orgId)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{props.switchingOrgId === org.orgId ? (
|
||||
<LoadingSpinner className="size-3.5" />
|
||||
) : null}
|
||||
{t('auto.components.billing.team.switch', 'Switch')}
|
||||
<ArrowRight />
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
import { Dialog } from '@/components/ui/dialog'
|
||||
import { defineFixture } from '../../../component-fixtures/component-fixture'
|
||||
import { TeamDeleteDialogView, type TeamDeleteDialogViewProps } from './TeamDeleteDialog'
|
||||
|
||||
const noop = (): void => {}
|
||||
const base: TeamDeleteDialogViewProps = {
|
||||
teamName: 'Acme Engineering',
|
||||
typed: '',
|
||||
submitting: false,
|
||||
error: null,
|
||||
waiting: false,
|
||||
onTypedChange: noop,
|
||||
onCancel: noop,
|
||||
onSubmit: noop,
|
||||
onBlockerAction: noop
|
||||
}
|
||||
|
||||
function View(props: Partial<TeamDeleteDialogViewProps>): React.JSX.Element {
|
||||
return (
|
||||
<Dialog open>
|
||||
<TeamDeleteDialogView {...base} {...props} />
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export const empty = defineFixture({ width: 720, render: () => <View /> })
|
||||
|
||||
export const typed = defineFixture({ width: 720, render: () => <View typed="Acme Engineering" /> })
|
||||
|
||||
export const mismatch = defineFixture({
|
||||
width: 720,
|
||||
render: () => (
|
||||
<View
|
||||
typed="acme engineering"
|
||||
error={{ kind: 'mismatch', text: 'The team name doesn’t match.' }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const unavailable = defineFixture({
|
||||
width: 720,
|
||||
render: () => (
|
||||
<View
|
||||
typed="Acme Engineering"
|
||||
error={{
|
||||
kind: 'message',
|
||||
text: 'Couldn’t check the team right now, so nothing was deleted. Try again.'
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const rateLimited = defineFixture({
|
||||
width: 720,
|
||||
render: () => (
|
||||
<View
|
||||
typed="Acme Engineering"
|
||||
waiting
|
||||
error={{ kind: 'message', text: 'Too many attempts. Wait a minute, then try again.' }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const blockedAtSubmit = defineFixture({
|
||||
width: 720,
|
||||
render: () => (
|
||||
<View
|
||||
typed="Acme Engineering"
|
||||
error={{
|
||||
kind: 'blocked',
|
||||
blockers: [
|
||||
{ code: 'subscription_active', status: 'active' },
|
||||
{ code: 'workspaces_exist', count: 2 }
|
||||
]
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
/** EP-10: the plan is set to end; the dialog says deleting ends it now, with no refund. */
|
||||
export const cancelsPlan = defineFixture({
|
||||
width: 720,
|
||||
render: () => (
|
||||
<View
|
||||
typed="Acme Engineering"
|
||||
cancelsSubscription={{ periodEnd: '2026-12-01T12:00:00.000Z' }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
/** EP-10: the plan already ended, but the team wasn't deleted: say so, offer to try again. */
|
||||
export const planEndedRetry = defineFixture({
|
||||
width: 720,
|
||||
render: () => (
|
||||
<View
|
||||
typed="Acme Engineering"
|
||||
cancelsSubscription={{ periodEnd: '2026-12-01T12:00:00.000Z' }}
|
||||
error={{
|
||||
kind: 'planEnded',
|
||||
text: 'Your team wasn’t deleted, but its plan has already ended, with no refund for the rest of the period.'
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
@@ -1,137 +0,0 @@
|
||||
import { useId } from 'react'
|
||||
import { LoaderCircle } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
|
||||
import type {
|
||||
OrcaOrgDeleteBlocker,
|
||||
OrcaOrgDeleteCancelsSubscription
|
||||
} from '../../../../../shared/orca-org-delete'
|
||||
import { TeamDeleteBlockers } from './TeamDeleteSection'
|
||||
import { teamDeleteCancelsPlanText, type TeamDeleteDialogError } from './team-delete-copy'
|
||||
|
||||
export type TeamDeleteDialogViewProps = {
|
||||
teamName: string
|
||||
typed: string
|
||||
submitting: boolean
|
||||
error: TeamDeleteDialogError | null
|
||||
/** 429: [Delete team] stays disabled until the wait is over. */
|
||||
waiting: boolean
|
||||
/** EP-10: the plan is set to end; this delete ends it now, with no refund for the rest. */
|
||||
cancelsSubscription?: OrcaOrgDeleteCancelsSubscription
|
||||
onTypedChange: (value: string) => void
|
||||
onCancel: () => void
|
||||
onSubmit: () => void
|
||||
onBlockerAction: (code: OrcaOrgDeleteBlocker['code']) => void
|
||||
}
|
||||
|
||||
/** "Delete <team>?": type the exact name (case-sensitive, paste allowed) to enable the delete. */
|
||||
export function TeamDeleteDialogView(props: TeamDeleteDialogViewProps): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const locale = useIntlLocale()
|
||||
const fieldId = useId()
|
||||
const planEnded = props.error?.kind === 'planEnded'
|
||||
const mismatchId = useId()
|
||||
const matches = props.typed === props.teamName
|
||||
const canSubmit = matches && !props.submitting && !props.waiting
|
||||
const mismatch = props.error?.kind === 'mismatch' ? props.error.text : null
|
||||
return (
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
className="sm:max-w-md"
|
||||
onInteractOutside={(event) => {
|
||||
if (props.submitting) {
|
||||
event.preventDefault()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{t('auto.components.billing.team.delete.confirmTitle', 'Delete {{value0}}?', {
|
||||
value0: props.teamName
|
||||
})}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t(
|
||||
'auto.components.billing.team.delete.confirmBody',
|
||||
'Everyone loses access to the team. Pending invites are cancelled. Its settings and team cloud secrets are deleted. Billing history is kept. This can’t be undone.'
|
||||
)}
|
||||
</DialogDescription>
|
||||
{props.cancelsSubscription && !planEnded ? (
|
||||
<p data-team-delete-cancels-plan="" className="text-sm font-medium text-pretty">
|
||||
{teamDeleteCancelsPlanText(props.cancelsSubscription.periodEnd, t, locale)}
|
||||
</p>
|
||||
) : null}
|
||||
</DialogHeader>
|
||||
<form
|
||||
className="space-y-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
if (canSubmit) {
|
||||
props.onSubmit()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Label htmlFor={fieldId}>
|
||||
{t('auto.components.billing.team.delete.typeToConfirm', 'Type {{value0}} to confirm', {
|
||||
value0: props.teamName
|
||||
})}
|
||||
</Label>
|
||||
<Input
|
||||
id={fieldId}
|
||||
value={props.typed}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
autoFocus
|
||||
aria-invalid={mismatch ? true : undefined}
|
||||
aria-describedby={mismatch ? mismatchId : undefined}
|
||||
onChange={(event) => props.onTypedChange(event.target.value)}
|
||||
/>
|
||||
{mismatch ? (
|
||||
<p id={mismatchId} className="text-xs text-destructive-text">
|
||||
{mismatch}
|
||||
</p>
|
||||
) : null}
|
||||
</form>
|
||||
{props.error?.kind === 'blocked' ? (
|
||||
<div role="alert">
|
||||
<TeamDeleteBlockers blockers={props.error.blockers} onAction={props.onBlockerAction} />
|
||||
</div>
|
||||
) : props.error?.kind === 'message' || props.error?.kind === 'planEnded' ? (
|
||||
<p role="alert" className="text-xs text-destructive-text text-pretty">
|
||||
{props.error.text}
|
||||
</p>
|
||||
) : null}
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={props.submitting}
|
||||
onClick={props.onCancel}
|
||||
>
|
||||
{t('auto.components.confirmation.dialog.56f5c60e0c', 'Cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
disabled={!canSubmit}
|
||||
aria-busy={props.submitting || undefined}
|
||||
onClick={props.onSubmit}
|
||||
>
|
||||
{props.submitting ? <LoaderCircle className="motion-safe:animate-spin" /> : null}
|
||||
{planEnded
|
||||
? t('auto.components.billing.team.delete.retry', 'Try deleting again')
|
||||
: t('auto.components.billing.team.delete.cta', 'Delete team')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
)
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
import { useId } from 'react'
|
||||
import { Trash2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import type {
|
||||
OrcaOrgDeleteBlocker,
|
||||
OrcaOrgDeleteCancelsSubscription
|
||||
} from '../../../../../shared/orca-org-delete'
|
||||
import { teamDeleteBlockerLines } from './team-delete-copy'
|
||||
|
||||
/** The pre-check: `checking` until auth answers; a failed check shows no blockers (auth re-checks). */
|
||||
export type TeamDeleteCheck =
|
||||
| { state: 'checking' }
|
||||
| {
|
||||
state: 'ready'
|
||||
blockers: OrcaOrgDeleteBlocker[]
|
||||
/** EP-10: the plan is set to end; deleting ends it now (no refund for the rest). */
|
||||
cancelsSubscription?: OrcaOrgDeleteCancelsSubscription
|
||||
}
|
||||
|
||||
/** Each blocker's way out, shown as a link after its line. */
|
||||
export function TeamDeleteBlockers({
|
||||
blockers,
|
||||
onAction
|
||||
}: {
|
||||
blockers: readonly OrcaOrgDeleteBlocker[]
|
||||
onAction: (code: OrcaOrgDeleteBlocker['code']) => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
return (
|
||||
<ul className="space-y-1">
|
||||
{teamDeleteBlockerLines(blockers, t).map((line) => (
|
||||
<li key={line.code} className="text-xs text-muted-foreground text-pretty">
|
||||
{line.text}{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-sm whitespace-nowrap text-foreground underline underline-offset-2 hover:text-foreground/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => onAction(line.code)}
|
||||
>
|
||||
{line.actionLabel}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
/** Settings › Team danger zone (owners only): "Delete <team>", styled like "Leave <team>". */
|
||||
export function TeamDeleteSection({
|
||||
teamName,
|
||||
check,
|
||||
onDelete,
|
||||
onBlockerAction
|
||||
}: {
|
||||
teamName: string
|
||||
check: TeamDeleteCheck
|
||||
onDelete: () => void
|
||||
onBlockerAction: (code: OrcaOrgDeleteBlocker['code']) => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const titleId = useId()
|
||||
const blockers = check.state === 'ready' ? check.blockers : []
|
||||
const blocked = blockers.length > 0
|
||||
return (
|
||||
<section aria-labelledby={titleId} className="flex flex-wrap items-center gap-3 p-4">
|
||||
<div className="min-w-[14rem] flex-1 space-y-1">
|
||||
<h3 id={titleId} className="text-sm font-medium">
|
||||
{t('auto.components.billing.team.delete.title', 'Delete {{value0}}', {
|
||||
value0: teamName
|
||||
})}
|
||||
</h3>
|
||||
<p className="text-xs text-muted-foreground text-pretty">
|
||||
{t(
|
||||
'auto.components.billing.team.delete.cardBody',
|
||||
'Removes the team for everyone. This can’t be undone.'
|
||||
)}
|
||||
</p>
|
||||
{blocked ? <TeamDeleteBlockers blockers={blockers} onAction={onBlockerAction} /> : null}
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive-chip"
|
||||
size="sm"
|
||||
disabled={blocked}
|
||||
aria-busy={check.state === 'checking' || undefined}
|
||||
onClick={check.state === 'checking' ? undefined : onDelete}
|
||||
>
|
||||
<Trash2 />
|
||||
{t('auto.components.billing.team.delete.cta', 'Delete team')}
|
||||
</Button>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, render } from '@testing-library/react'
|
||||
import { afterEach, expect, it } from 'vitest'
|
||||
import { Dialog } from '@/components/ui/dialog'
|
||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||
import { TeamDialogContent } from './TeamDialogHost'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
// TEAM-MODAL-CENTER: the Team dialog (opened from the account menu, Create a team, or after
|
||||
// Checkout; all go through this one surface) is centred in the window like every other dialog.
|
||||
it('centres the Team dialog in the window instead of pinning it near the top', () => {
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<Dialog open>
|
||||
<TeamDialogContent>
|
||||
<p>Team</p>
|
||||
</TeamDialogContent>
|
||||
</Dialog>
|
||||
</TooltipProvider>
|
||||
)
|
||||
const dialog = document.querySelector<HTMLElement>('[data-team-dialog]')!
|
||||
// Portaled to the document, not into the menu that opened it.
|
||||
expect(dialog.closest('[data-slot="dropdown-menu-content"]')).toBeNull()
|
||||
const classes = dialog.className.split(/\s+/)
|
||||
expect(classes).toContain('fixed')
|
||||
expect(classes).toContain('top-[50%]')
|
||||
expect(classes).toContain('left-[50%]')
|
||||
expect(classes).toContain('translate-y-[-50%]')
|
||||
expect(classes).toContain('translate-x-[-50%]')
|
||||
expect(classes).not.toContain('top-[6vh]')
|
||||
expect(classes).not.toContain('translate-y-0')
|
||||
})
|
||||
@@ -1,327 +0,0 @@
|
||||
import { useTeamMfaGate } from '@/components/team-mfa/TeamMfaGate'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog'
|
||||
import { useConfirmationDialog } from '@/components/confirmation-dialog-context'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { useAppStore } from '@/store/index'
|
||||
import type { OrcaBillingOpenResult } from '../../../../../shared/orca-billing'
|
||||
import type { OrcaProfileOrgCreateResult } from '../../../../../shared/orca-org-management'
|
||||
import { openFailureCopy } from '../plan-billing-copy'
|
||||
import { openPlansPage } from '../plans/plans-page-store'
|
||||
import { useOrcaBillingStatus } from '../use-orca-billing-status'
|
||||
import { TeamPageView } from './TeamPageView'
|
||||
import { createTeamFailureCopy, mutationFailureCopy } from './team-copy'
|
||||
import { clearTeamPageArrival, closeTeamPage, useTeamPageState } from './team-page-store'
|
||||
import { useOrgRoster } from './use-org-roster'
|
||||
import { leaveTeamConfirmation } from './team-leave'
|
||||
import { useTeamActions } from './use-team-actions'
|
||||
import { useTeamDelete } from './use-team-delete'
|
||||
import { TeamDeleteSection } from './TeamDeleteSection'
|
||||
import { openTeammateProfile } from '../../teammates/teammate-profile-store'
|
||||
import { ORCA_CLOUD_RECIPE_ID } from '../../../../../shared/hosted-sandbox/orca-cloud-recipe-id'
|
||||
|
||||
export function TeamPageBody({
|
||||
arrival,
|
||||
inline
|
||||
}: {
|
||||
arrival: ReturnType<typeof useTeamPageState>['arrival']
|
||||
/** Settings → Team: rendered on the page instead of in the dialog (JA-17). */
|
||||
inline?: { onOpenPlanBilling: () => void }
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const confirm = useConfirmationDialog()
|
||||
const authStatus = useAppStore((state) => state.orcaProfileAuthStatus)
|
||||
const selectOrg = useAppStore((state) => state.selectOrcaProfileOrg)
|
||||
const refreshAuth = useAppStore((state) => state.refreshCurrentOrcaProfileAuth)
|
||||
const openModal = useAppStore((state) => state.openModal)
|
||||
const cloud = authStatus?.cloud
|
||||
const orgId = cloud?.activeOrgId ?? null
|
||||
const roster = useOrgRoster(orgId)
|
||||
const mfa = useTeamMfaGate()
|
||||
const billing = useOrcaBillingStatus(true)
|
||||
const [userRefreshing, setUserRefreshing] = useState(false)
|
||||
const [billingBusy, setBillingBusy] = useState(false)
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [createError, setCreateError] = useState<string | null>(null)
|
||||
const [createUnavailable, setCreateUnavailable] = useState(false)
|
||||
const [switchingOrgId, setSwitchingOrgId] = useState<string | null>(null)
|
||||
const [now] = useState(() => Date.now())
|
||||
|
||||
const refreshRoster = roster.refresh
|
||||
const refreshBilling = billing.refresh
|
||||
// Both refreshes are stable callbacks; depending on the hook results would rebuild this each render.
|
||||
const quietRefresh = useCallback(() => {
|
||||
refreshRoster()
|
||||
refreshBilling()
|
||||
}, [refreshRoster, refreshBilling])
|
||||
const actions = useTeamActions({ orgId: orgId ?? '', onChanged: quietRefresh })
|
||||
|
||||
const rosterResult =
|
||||
roster.result?.status === 'ok'
|
||||
? { ...roster.result, roster: actions.applyOverlays(roster.result.roster, roster.resultSeq) }
|
||||
: roster.result
|
||||
|
||||
const openPortal = (): void => {
|
||||
setBillingBusy(true)
|
||||
void window.api.orcaProfiles
|
||||
.billingOpenPortal()
|
||||
.catch((error: unknown): OrcaBillingOpenResult => ({
|
||||
status: 'failed',
|
||||
error: String(error)
|
||||
}))
|
||||
.then((outcome) => {
|
||||
setBillingBusy(false)
|
||||
const failure = openFailureCopy(outcome, t)
|
||||
if (failure) {
|
||||
toast.error(failure)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const createTeam = (name: string): void => {
|
||||
setCreating(true)
|
||||
setCreateError(null)
|
||||
void window.api.orcaProfiles
|
||||
.orgCreate({ name })
|
||||
.catch((error: unknown): OrcaProfileOrgCreateResult => ({
|
||||
status: 'failed',
|
||||
error: String(error)
|
||||
}))
|
||||
.then(async (outcome) => {
|
||||
if (outcome.status === 'created') {
|
||||
// Clear "create" first so the remount for the new team lands on its page, not a blank form.
|
||||
clearTeamPageArrival()
|
||||
const selected = await selectOrg(outcome.orgId)
|
||||
if (selected?.status === 'selected') {
|
||||
toast.success(
|
||||
t('auto.components.billing.team.createdToast', '{{value0}} created', {
|
||||
value0: outcome.name
|
||||
})
|
||||
)
|
||||
} else {
|
||||
toast.error(
|
||||
t(
|
||||
'auto.components.billing.team.createdNotSwitched',
|
||||
'{{value0}} was created, but Orca couldn’t switch to it.',
|
||||
{ value0: outcome.name }
|
||||
),
|
||||
{
|
||||
action: {
|
||||
label: t('auto.components.billing.team.switch', 'Switch'),
|
||||
onClick: () => void selectOrg(outcome.orgId)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
} else if (outcome.status === 'unsupported') {
|
||||
setCreateUnavailable(true)
|
||||
} else {
|
||||
setCreateError(createTeamFailureCopy(outcome, t))
|
||||
}
|
||||
setCreating(false)
|
||||
})
|
||||
}
|
||||
|
||||
const switchOrg = (target: string): void => {
|
||||
clearTeamPageArrival()
|
||||
setSwitchingOrgId(target)
|
||||
void selectOrg(target).finally(() => setSwitchingOrgId(null))
|
||||
}
|
||||
|
||||
const leave = (): void => {
|
||||
if (!orgId) {
|
||||
return
|
||||
}
|
||||
const name = cloud?.activeOrgName ?? t('auto.components.billing.team.thisTeam', 'this team')
|
||||
void confirm(leaveTeamConfirmation(name, t)).then((accepted) => {
|
||||
if (!accepted) {
|
||||
return
|
||||
}
|
||||
void window.api.orcaProfiles
|
||||
.orgLeave({ orgId })
|
||||
.catch((error: unknown) => ({ status: 'failed' as const, error: String(error) }))
|
||||
.then(async (outcome) => {
|
||||
if (outcome.status === 'ok') {
|
||||
await refreshAuth()
|
||||
closeTeamPage()
|
||||
toast.success(
|
||||
t('auto.components.billing.team.leftToast', 'You left {{value0}}', { value0: name })
|
||||
)
|
||||
} else {
|
||||
toast.error(mutationFailureCopy(outcome, t) ?? '')
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const org =
|
||||
orgId && arrival?.kind !== 'create' ? { orgId, name: cloud?.activeOrgName ?? orgId } : null
|
||||
// Settings › Team only, owners only (TEAM-DELETE).
|
||||
const teamDelete = useTeamDelete({
|
||||
orgId: org?.orgId ?? null,
|
||||
teamName: org?.name ?? '',
|
||||
enabled:
|
||||
Boolean(inline) &&
|
||||
org !== null &&
|
||||
rosterResult?.status === 'ok' &&
|
||||
rosterResult.roster.viewerRole === 'owner',
|
||||
onManageBilling: openPortal,
|
||||
onDeleted: async () => {
|
||||
await refreshAuth()
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<>
|
||||
<TeamPageView
|
||||
org={org}
|
||||
mfaNotice={mfa.blocked ?? mfa.banner}
|
||||
viewerUserId={cloud?.userId ?? null}
|
||||
roster={rosterResult}
|
||||
billing={billing.result}
|
||||
arrival={arrival}
|
||||
rowStates={actions.rowStates}
|
||||
refreshing={userRefreshing && (roster.loading || billing.loading)}
|
||||
billingBusy={billingBusy}
|
||||
now={now}
|
||||
create={{
|
||||
organizations: (authStatus?.organizations ?? []).filter(
|
||||
(candidate) => candidate.orgId !== orgId
|
||||
),
|
||||
creating,
|
||||
error: createError,
|
||||
unavailable: createUnavailable,
|
||||
switchingOrgId
|
||||
}}
|
||||
onCreateTeam={createTeam}
|
||||
onSwitchOrg={switchOrg}
|
||||
onRefresh={() => {
|
||||
setUserRefreshing(true)
|
||||
quietRefresh()
|
||||
window.setTimeout(() => setUserRefreshing(false), 600)
|
||||
}}
|
||||
onInvite={actions.invite}
|
||||
onChangeRole={(member, role) => actions.changeRole(member, role)}
|
||||
onMakeOwner={actions.makeOwner}
|
||||
onRemove={actions.remove}
|
||||
onResend={actions.resend}
|
||||
onRevoke={(email) => {
|
||||
const role =
|
||||
rosterResult?.status === 'ok'
|
||||
? (rosterResult.roster.pendingInvites.find((invite) => invite.email === email)
|
||||
?.role ?? 'member')
|
||||
: 'member'
|
||||
actions.revoke(email, role)
|
||||
}}
|
||||
onLeave={leave}
|
||||
onSeePlans={() => {
|
||||
closeTeamPage()
|
||||
openPlansPage('team')
|
||||
}}
|
||||
onManageBilling={openPortal}
|
||||
onCreateWorkspace={() => {
|
||||
closeTeamPage()
|
||||
// The plan is for Orca Cloud, so the composer opens on it rather than this computer.
|
||||
openModal('new-workspace-composer', {
|
||||
initialEphemeralVmRecipeId: ORCA_CLOUD_RECIPE_ID,
|
||||
telemetrySource: 'unknown'
|
||||
})
|
||||
}}
|
||||
onOpenProfile={(userId) => {
|
||||
// One dialog at a time: the profile replaces the Team page (as in Conductor 0.91).
|
||||
closeTeamPage()
|
||||
openTeammateProfile(userId)
|
||||
}}
|
||||
onDismissArrival={clearTeamPageArrival}
|
||||
onOpenEnterprise={() => {
|
||||
// SSO, SCIM and the audit log live in Settings › Enterprise (#614); the dialog points there.
|
||||
closeTeamPage()
|
||||
const store = useAppStore.getState()
|
||||
store.openSettingsTarget({ pane: 'cloud-enterprise', repoId: null })
|
||||
store.openSettingsPage()
|
||||
}}
|
||||
inline={inline}
|
||||
dangerZone={
|
||||
org && teamDelete.check ? (
|
||||
<TeamDeleteSection
|
||||
teamName={org.name}
|
||||
check={teamDelete.check}
|
||||
onDelete={teamDelete.open}
|
||||
onBlockerAction={teamDelete.onBlockerAction}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
{teamDelete.dialog}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The Team page's dialog surface, centred in the window like every other dialog, whichever entry
|
||||
* point opened it (account menu, Create a team, the post-checkout hand-off). It used to be pinned
|
||||
* 6vh from the top (`top-[6vh] translate-y-0`), so it sat high on screen (TEAM-MODAL-CENTER).
|
||||
*/
|
||||
export function TeamDialogContent({ children }: { children: React.ReactNode }): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
return (
|
||||
<DialogContent
|
||||
scrollable
|
||||
data-team-dialog=""
|
||||
className="max-h-[88vh] sm:max-w-2xl"
|
||||
onOpenAutoFocus={(event) => {
|
||||
event.preventDefault()
|
||||
if (event.currentTarget instanceof HTMLElement) {
|
||||
event.currentTarget.focus()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogTitle className="sr-only">
|
||||
{t('auto.components.billing.team.title', 'Team')}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="sr-only">
|
||||
{t(
|
||||
'auto.components.billing.team.description',
|
||||
'Members, invites, roles, seats and your Orca Cloud plan.'
|
||||
)}
|
||||
</DialogDescription>
|
||||
{children}
|
||||
</DialogContent>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The Team page: members, invites, roles, seats and the plan, in one place. A dialog like the
|
||||
* plans page so it opens over whatever the user was doing; Checkout lands here when it succeeds.
|
||||
*/
|
||||
export function TeamDialogHost(): React.JSX.Element {
|
||||
const { open, arrival } = useTeamPageState()
|
||||
// Remount per team so optimistic rows and row errors never carry over to another org.
|
||||
const orgKey = useAppStore((state) => state.orcaProfileAuthStatus?.cloud?.activeOrgId ?? 'none')
|
||||
// An arrival (create mode, or the post-checkout welcome) belongs to the team it was opened for;
|
||||
// switching teams drops it so it never shows on another team.
|
||||
const arrivalOrg = useRef(orgKey)
|
||||
useEffect(() => {
|
||||
if (arrivalOrg.current !== orgKey) {
|
||||
arrivalOrg.current = orgKey
|
||||
clearTeamPageArrival()
|
||||
}
|
||||
}, [orgKey])
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) {
|
||||
closeTeamPage()
|
||||
}
|
||||
}}
|
||||
>
|
||||
{open ? (
|
||||
<TeamDialogContent>
|
||||
<TeamPageBody key={orgKey} arrival={arrival} />
|
||||
</TeamDialogContent>
|
||||
) : null}
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { afterEach, expect, it } from 'vitest'
|
||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||
import { TeamInviteComposer } from './TeamInviteComposer'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const RULE = 'Each invite uses a seat once accepted.'
|
||||
|
||||
it('says only the seat rule, with no seat counts or prices, however many are entered', () => {
|
||||
render(<TeamInviteComposer viewerRole="owner" onInvite={async () => ({ failed: [] })} />, {
|
||||
wrapper: TooltipProvider
|
||||
})
|
||||
const input = screen.getByRole('textbox')
|
||||
const hint = document.getElementById(input.getAttribute('aria-describedby')!)!
|
||||
expect(hint.textContent).toBe(RULE)
|
||||
|
||||
fireEvent.change(input, { target: { value: 'jordan@acme.dev, kim@acme.dev ' } })
|
||||
expect(hint.textContent).toBe(RULE)
|
||||
expect(hint.textContent).not.toMatch(/open seat|\$|prorated/)
|
||||
})
|
||||
|
||||
it('still flags invalid entries after the rule', () => {
|
||||
render(<TeamInviteComposer viewerRole="owner" onInvite={async () => ({ failed: [] })} />, {
|
||||
wrapper: TooltipProvider
|
||||
})
|
||||
const input = screen.getByRole('textbox')
|
||||
fireEvent.change(input, { target: { value: 'jordan@acme.dev, not-an-email ' } })
|
||||
const hint = document.getElementById(input.getAttribute('aria-describedby')!)!
|
||||
expect(hint.textContent).toBe(`${RULE} Skipping 1 invalid entry.`)
|
||||
})
|
||||
@@ -1,281 +0,0 @@
|
||||
import { useId, useRef, useState } from 'react'
|
||||
import { CircleAlert, Send, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { SettingsDisabledControlTooltip } from '@/components/settings/form-controls/SettingsDisabledControlTooltip'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { cn } from '@/lib/class-names'
|
||||
import type { OrcaOrgRole } from '../../../../../shared/orca-profiles'
|
||||
import {
|
||||
MAX_INVITES_PER_BATCH,
|
||||
mergeInviteCandidates,
|
||||
splitInviteText,
|
||||
type InviteCandidate
|
||||
} from './parse-invite-emails'
|
||||
import { roleDescription } from './team-copy'
|
||||
import { assignableRoles, roleLabel } from './team-roles'
|
||||
|
||||
export type InviteBatchOutcome = { failed: { email: string; message: string }[] }
|
||||
|
||||
export type TeamInviteComposerProps = {
|
||||
viewerRole: OrcaOrgRole
|
||||
/** Sends every invite; resolves with the ones that failed so they stay in the field. */
|
||||
onInvite: (emails: string[], role: OrcaOrgRole) => Promise<InviteBatchOutcome>
|
||||
inputRef?: React.Ref<HTMLInputElement>
|
||||
}
|
||||
|
||||
/** Multi-email invite field: paste a list, review the chips, pick a role, send. */
|
||||
export function TeamInviteComposer(props: TeamInviteComposerProps): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const id = useId()
|
||||
const [draft, setDraft] = useState('')
|
||||
const [candidates, setCandidates] = useState<InviteCandidate[]>([])
|
||||
const [errors, setErrors] = useState<Record<string, string>>({})
|
||||
const [role, setRole] = useState<OrcaOrgRole>('member')
|
||||
const [sending, setSending] = useState(false)
|
||||
const localInput = useRef<HTMLInputElement | null>(null)
|
||||
const roles = assignableRoles(props.viewerRole)
|
||||
|
||||
const commit = (text: string): InviteCandidate[] => {
|
||||
const next = mergeInviteCandidates(candidates, splitInviteText(text))
|
||||
setCandidates(next)
|
||||
setDraft('')
|
||||
return next
|
||||
}
|
||||
const remove = (email: string): void => {
|
||||
setCandidates((list) => list.filter((candidate) => candidate.email !== email))
|
||||
setErrors(({ [email]: _removed, ...rest }) => rest)
|
||||
}
|
||||
|
||||
const pendingDraft = draft.trim()
|
||||
? mergeInviteCandidates(candidates, splitInviteText(draft))
|
||||
: candidates
|
||||
// The button counts what Send would send, including a typed, unseparated address.
|
||||
const valid = pendingDraft.filter((candidate) => candidate.valid)
|
||||
const committedValid = candidates.filter((candidate) => candidate.valid)
|
||||
const invalidCount = candidates.length - committedValid.length
|
||||
|
||||
const send = async (): Promise<void> => {
|
||||
const all = commit(draft)
|
||||
const emails = all.filter((candidate) => candidate.valid).map((candidate) => candidate.email)
|
||||
if (emails.length === 0 || sending) {
|
||||
return
|
||||
}
|
||||
setSending(true)
|
||||
const outcome = await props.onInvite(emails, role)
|
||||
setSending(false)
|
||||
const failed = new Map(outcome.failed.map((entry) => [entry.email, entry.message]))
|
||||
// Sent ones leave; failures and invalid entries stay so nothing typed is lost (review M12).
|
||||
setCandidates((list) =>
|
||||
list.filter((candidate) => !candidate.valid || failed.has(candidate.email))
|
||||
)
|
||||
setErrors(Object.fromEntries(failed))
|
||||
}
|
||||
|
||||
const hintId = `${id}-hint`
|
||||
const describedErrors = Object.entries(errors)
|
||||
|
||||
return (
|
||||
<form
|
||||
className="space-y-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
void send()
|
||||
}}
|
||||
>
|
||||
<label htmlFor={`${id}-input`} className="text-sm font-medium">
|
||||
{t('auto.components.billing.team.inviteLabel', 'Invite teammates')}
|
||||
</label>
|
||||
<div className="flex flex-wrap items-start gap-2">
|
||||
<div
|
||||
className={cn(
|
||||
'flex min-h-8 min-w-[16rem] flex-1 cursor-text flex-wrap items-center gap-1 rounded-md border border-input bg-transparent px-2 py-0.5 shadow-xs transition-[color,box-shadow] dark:bg-input/30',
|
||||
'focus-within:border-ring focus-within:ring-2 focus-within:ring-focus-ring'
|
||||
)}
|
||||
onClick={() => localInput.current?.focus()}
|
||||
>
|
||||
{candidates.map((candidate) => {
|
||||
const error = errors[candidate.email]
|
||||
const bad = !candidate.valid || Boolean(error)
|
||||
return (
|
||||
<span
|
||||
key={candidate.email}
|
||||
className={cn(
|
||||
'inline-flex max-w-full items-center gap-1 rounded-full border py-0.5 pr-0.5 pl-2 text-xs animate-in fade-in-0 zoom-in-95 duration-150 motion-reduce:animate-none',
|
||||
bad
|
||||
? 'border-destructive bg-destructive/10 text-foreground'
|
||||
: 'border-border bg-secondary text-secondary-foreground'
|
||||
)}
|
||||
title={
|
||||
error ??
|
||||
(candidate.valid
|
||||
? undefined
|
||||
: t('auto.components.billing.team.notAnEmail', 'Not an email address'))
|
||||
}
|
||||
>
|
||||
{bad ? (
|
||||
<CircleAlert aria-hidden className="size-3 shrink-0 text-destructive" />
|
||||
) : null}
|
||||
<span className="truncate">{candidate.email}</span>
|
||||
{bad ? (
|
||||
<span className="sr-only">
|
||||
{error ?? t('auto.components.billing.team.notAnEmail', 'Not an email address')}
|
||||
</span>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className="-my-1 -mr-1 flex size-6 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-foreground/10 hover:text-foreground focus-visible:ring-2 focus-visible:ring-focus-ring focus-visible:outline-none"
|
||||
aria-label={t('auto.components.billing.team.removeChip', 'Remove {{value0}}', {
|
||||
value0: candidate.email
|
||||
})}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
remove(candidate.email)
|
||||
}}
|
||||
>
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
<input
|
||||
id={`${id}-input`}
|
||||
ref={(node) => {
|
||||
localInput.current = node
|
||||
if (typeof props.inputRef === 'function') {
|
||||
props.inputRef(node)
|
||||
} else if (props.inputRef) {
|
||||
props.inputRef.current = node
|
||||
}
|
||||
}}
|
||||
type="text"
|
||||
inputMode="email"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
aria-describedby={hintId}
|
||||
aria-invalid={invalidCount > 0 || undefined}
|
||||
readOnly={sending || candidates.length >= MAX_INVITES_PER_BATCH}
|
||||
aria-disabled={sending || undefined}
|
||||
placeholder={
|
||||
candidates.length === 0
|
||||
? t(
|
||||
'auto.components.billing.team.invitePlaceholder2',
|
||||
'alex@company.com, sam@company.com'
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
className="h-6 min-w-[10rem] flex-1 bg-transparent px-1 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed"
|
||||
value={draft}
|
||||
onChange={(event) => {
|
||||
const value = event.target.value
|
||||
// A separator ends the current address.
|
||||
if (/[\s,;]$/.test(value)) {
|
||||
commit(value)
|
||||
} else {
|
||||
setDraft(value)
|
||||
}
|
||||
}}
|
||||
onPaste={(event) => {
|
||||
const text = event.clipboardData.getData('text')
|
||||
if (/[\s,;<]/.test(text)) {
|
||||
event.preventDefault()
|
||||
commit(`${draft}${text}`)
|
||||
}
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Backspace' && draft === '' && candidates.length > 0 && !sending) {
|
||||
remove(candidates.at(-1)!.email)
|
||||
}
|
||||
}}
|
||||
onBlur={() => {
|
||||
if (draft.trim()) {
|
||||
commit(draft)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex shrink-0 gap-2">
|
||||
<Select
|
||||
value={role}
|
||||
disabled={sending}
|
||||
onValueChange={(next) => {
|
||||
const picked = roles.find((candidate) => candidate === next)
|
||||
if (picked) {
|
||||
setRole(picked)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger
|
||||
size="sm"
|
||||
className="w-28"
|
||||
aria-label={t('auto.components.billing.team.inviteRole', 'Role for the invite')}
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent align="end">
|
||||
{roles.map((option) => (
|
||||
<SelectItem key={option} value={option} title={roleDescription(option, t)}>
|
||||
{roleLabel(option, t)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<SettingsDisabledControlTooltip
|
||||
reason={
|
||||
!sending && valid.length === 0
|
||||
? t('auto.components.billing.team.enterEmail', 'Enter a teammate’s email')
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
// aria-disabled keeps focus here while sending; submit ignores it meanwhile.
|
||||
disabled={!sending && valid.length === 0}
|
||||
aria-disabled={sending || undefined}
|
||||
>
|
||||
{sending ? <LoadingSpinner className="size-3.5" /> : <Send />}
|
||||
{valid.length === 0
|
||||
? // Nothing to count yet: a plain verb, not "Send 1 invite".
|
||||
t('auto.components.billing.team.send', 'Send invite')
|
||||
: t('auto.components.billing.team.sendInvites', 'Send {{count}} invites', {
|
||||
count: valid.length,
|
||||
defaultValue_one: 'Send {{count}} invite'
|
||||
})}
|
||||
</Button>
|
||||
</SettingsDisabledControlTooltip>
|
||||
</div>
|
||||
</div>
|
||||
<p id={hintId} className="text-xs text-muted-foreground text-pretty">
|
||||
{/* Only the rule: seat counts and prices live in Plan & billing (Neil, TEAM-DIALOG-2). */}
|
||||
{t('auto.components.billing.team.inviteSeatRule', 'Each invite uses a seat once accepted.')}
|
||||
{invalidCount > 0
|
||||
? ` ${t(
|
||||
'auto.components.billing.team.skipInvalid',
|
||||
'Skipping {{count}} invalid entries.',
|
||||
{
|
||||
count: invalidCount,
|
||||
defaultValue_one: 'Skipping {{count}} invalid entry.'
|
||||
}
|
||||
)}`
|
||||
: null}
|
||||
</p>
|
||||
{describedErrors.length > 0 ? (
|
||||
<ul role="alert" className="space-y-0.5 text-xs text-destructive">
|
||||
{describedErrors.map(([email, message]) => (
|
||||
<li key={email}>
|
||||
{email}: {message}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -1,204 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, render } from '@testing-library/react'
|
||||
import { afterEach, expect, it } from 'vitest'
|
||||
import type { OrcaOrgMembersRoster } from '../../../../../shared/orca-profiles'
|
||||
import { TeamMemberList } from './TeamMemberList'
|
||||
import { teamRows } from './team-roster-rows'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const roster: OrcaOrgMembersRoster = {
|
||||
viewerRole: 'owner',
|
||||
canManageMembers: true,
|
||||
members: [
|
||||
{ userId: 'u-neil', email: 'neil@acme.dev', displayName: 'Neil Parker', role: 'owner' },
|
||||
{ userId: 'u-grace', email: 'grace@acme.dev', displayName: 'Grace Hopper', role: 'member' }
|
||||
],
|
||||
pendingInvites: []
|
||||
}
|
||||
|
||||
const noop = (): void => {}
|
||||
|
||||
it('marks a busy row with aria-busy and a spinner, without dimming it', () => {
|
||||
const { container } = render(
|
||||
<TeamMemberList
|
||||
rows={teamRows(roster, 'u-neil')}
|
||||
viewerRole="owner"
|
||||
rowStates={{ 'member:u-grace': { busy: true } }}
|
||||
canLeave
|
||||
now={Date.UTC(2026, 10, 18)}
|
||||
onChangeRole={noop}
|
||||
onMakeOwner={noop}
|
||||
onRemove={noop}
|
||||
onResend={noop}
|
||||
onRevoke={noop}
|
||||
onLeave={noop}
|
||||
/>
|
||||
)
|
||||
const busy = container.querySelector('[data-team-row="member:u-grace"]')!
|
||||
const idle = container.querySelector('[data-team-row="member:u-neil"]')!
|
||||
expect(busy.getAttribute('aria-busy')).toBe('true')
|
||||
expect(idle.hasAttribute('aria-busy')).toBe(false)
|
||||
// Dimming dropped the email under AA; the row keeps full opacity.
|
||||
expect(busy.className).not.toMatch(/opacity-/)
|
||||
expect(busy.querySelector('.animate-spin')).not.toBeNull()
|
||||
expect(idle.querySelector('.animate-spin')).toBeNull()
|
||||
})
|
||||
|
||||
it('offers Leave from the ⋯ on your own row only', () => {
|
||||
const { container } = render(
|
||||
<TeamMemberList
|
||||
rows={teamRows({ ...roster, viewerRole: 'member', canManageMembers: false }, 'u-grace')}
|
||||
viewerRole="member"
|
||||
rowStates={{}}
|
||||
canLeave
|
||||
now={Date.UTC(2026, 10, 18)}
|
||||
onChangeRole={noop}
|
||||
onMakeOwner={noop}
|
||||
onRemove={noop}
|
||||
onResend={noop}
|
||||
onRevoke={noop}
|
||||
onLeave={noop}
|
||||
/>
|
||||
)
|
||||
const self = container.querySelector('[data-team-row="member:u-grace"]')!
|
||||
const other = container.querySelector('[data-team-row="member:u-neil"]')!
|
||||
expect(self.querySelector('button[aria-label^="Actions for"]')).not.toBeNull()
|
||||
// A plain member has nothing to do on someone else's row.
|
||||
expect(other.querySelector('button[aria-label^="Actions for"]')).toBeNull()
|
||||
})
|
||||
|
||||
function renderList(
|
||||
listRoster: OrcaOrgMembersRoster,
|
||||
viewerUserId: string
|
||||
): ReturnType<typeof render> {
|
||||
return render(
|
||||
<TeamMemberList
|
||||
rows={teamRows(listRoster, viewerUserId)}
|
||||
viewerRole={listRoster.viewerRole}
|
||||
rowStates={{}}
|
||||
canLeave
|
||||
now={Date.UTC(2026, 10, 18)}
|
||||
onChangeRole={noop}
|
||||
onMakeOwner={noop}
|
||||
onRemove={noop}
|
||||
onResend={noop}
|
||||
onRevoke={noop}
|
||||
onLeave={noop}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const rosterWithMfa: OrcaOrgMembersRoster = {
|
||||
...roster,
|
||||
members: [
|
||||
{ ...roster.members[0]!, mfa: 'on' },
|
||||
{ ...roster.members[1]!, mfa: 'pending', mfaDeadline: Date.UTC(2026, 10, 24, 12) }
|
||||
],
|
||||
pendingInvites: [{ email: 'alex@acme.dev', role: 'member', createdAt: Date.UTC(2026, 10, 17) }]
|
||||
}
|
||||
|
||||
it.each(['owner', 'admin'] as const)('shows the MFA column to an %s', (viewerRole) => {
|
||||
const { container } = renderList({ ...rosterWithMfa, viewerRole }, 'u-neil')
|
||||
const cell = (key: string): Element =>
|
||||
container.querySelector(`[data-team-row="${key}"] [data-team-mfa]`)!
|
||||
expect(cell('member:u-neil').textContent).toBe('2FA on')
|
||||
expect(cell('member:u-grace').textContent).toBe('2FA due Nov 24')
|
||||
// A small muted badge, not bare text.
|
||||
expect(cell('member:u-neil').querySelector('[data-slot="badge"]')).not.toBeNull()
|
||||
// Invites keep an empty cell so the role column stays aligned.
|
||||
expect(cell('invite:alex@acme.dev').textContent).toBe('')
|
||||
})
|
||||
|
||||
it('hides the MFA column from a plain member, even if a roster carried the status', () => {
|
||||
const { container } = renderList(
|
||||
{ ...rosterWithMfa, viewerRole: 'member', canManageMembers: false },
|
||||
'u-grace'
|
||||
)
|
||||
expect(container.querySelector('[data-team-mfa]')).toBeNull()
|
||||
expect(container.textContent).not.toContain('MFA')
|
||||
})
|
||||
|
||||
it('shows no MFA column when the server sent no status', () => {
|
||||
const { container } = renderList(roster, 'u-neil')
|
||||
expect(container.querySelector('[data-team-mfa]')).toBeNull()
|
||||
})
|
||||
|
||||
it('leaves the cell blank, not "off", for a member with no status', () => {
|
||||
const { container } = renderList(
|
||||
{
|
||||
...roster,
|
||||
members: [{ ...roster.members[0]!, mfa: 'off' }, roster.members[1]!]
|
||||
},
|
||||
'u-neil'
|
||||
)
|
||||
const cell = (key: string): Element =>
|
||||
container.querySelector(`[data-team-row="${key}"] [data-team-mfa]`)!
|
||||
expect(cell('member:u-neil').textContent).toBe('2FA off')
|
||||
expect(cell('member:u-grace').textContent).toBe('')
|
||||
})
|
||||
|
||||
it('shows no MFA badge for a member who has not signed in yet', () => {
|
||||
const { container } = renderList(
|
||||
{
|
||||
...roster,
|
||||
members: [
|
||||
{ ...roster.members[0]!, mfa: 'on' },
|
||||
{ userId: null, email: 'linus@acme.dev', role: 'member', mfa: 'off' }
|
||||
]
|
||||
},
|
||||
'u-neil'
|
||||
)
|
||||
const pending = container.querySelector(
|
||||
'[data-team-row="member:linus@acme.dev"] [data-team-mfa]'
|
||||
)!
|
||||
expect(pending.textContent).toBe('')
|
||||
})
|
||||
|
||||
it('a team its identity provider manages: no role or remove controls, and the row says why', () => {
|
||||
const managed = teamRows({ ...roster, directoryManaged: true }, 'u-neil')
|
||||
expect(managed.map((row) => [row.key, row.manageable])).toEqual([
|
||||
['member:u-neil', false],
|
||||
['member:u-grace', false]
|
||||
])
|
||||
const { container } = render(
|
||||
<TeamMemberList
|
||||
rows={managed}
|
||||
viewerRole="owner"
|
||||
rowStates={{}}
|
||||
canLeave
|
||||
now={Date.UTC(2026, 10, 18)}
|
||||
onChangeRole={noop}
|
||||
onMakeOwner={noop}
|
||||
onRemove={noop}
|
||||
onResend={noop}
|
||||
onRevoke={noop}
|
||||
onLeave={noop}
|
||||
/>
|
||||
)
|
||||
const grace = container.querySelector('[data-team-row="member:u-grace"]')!
|
||||
// The role is text, not a select, and names the identity provider as its owner.
|
||||
expect(grace.querySelector('[role="combobox"]')).toBeNull()
|
||||
expect(grace.querySelector('[title="Managed by your identity provider"]')?.textContent).toBe(
|
||||
'Member'
|
||||
)
|
||||
// Without the flag the owner can still manage the same member.
|
||||
expect(teamRows(roster, 'u-neil').find((row) => row.key === 'member:u-grace')?.manageable).toBe(
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
it('shows a member whose two-factor is their identity provider’s as via SSO', () => {
|
||||
const { container } = renderList(
|
||||
{
|
||||
...roster,
|
||||
members: [
|
||||
{ ...roster.members[0]!, mfa: 'on' },
|
||||
{ ...roster.members[1]!, mfa: 'sso' }
|
||||
]
|
||||
},
|
||||
'u-neil'
|
||||
)
|
||||
const cell = container.querySelector('[data-team-row="member:u-grace"] [data-team-mfa]')!
|
||||
expect(cell.textContent).toBe('2FA via SSO')
|
||||
})
|
||||
@@ -1,361 +0,0 @@
|
||||
import {
|
||||
Crown,
|
||||
LogOut,
|
||||
MailPlus,
|
||||
MoreHorizontal,
|
||||
UserMinus,
|
||||
UserRound,
|
||||
XCircle
|
||||
} from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { InlineError } from '@/components/ui/inline-error'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
|
||||
import type { OrcaOrgMember, OrcaOrgRole } from '../../../../../shared/orca-profiles'
|
||||
import { PersonAvatar } from './TeamAvatar'
|
||||
import { invitedAsCopy, memberStatusLabel, roleDescription } from './team-copy'
|
||||
import { memberMfaLabel, showMfaColumn } from './team-member-mfa'
|
||||
import { assignableRoles, roleLabel } from './team-roles'
|
||||
import type { TeamRow } from './team-roster-rows'
|
||||
|
||||
export type TeamRowState = { busy?: boolean; error?: string }
|
||||
|
||||
export type TeamMemberListProps = {
|
||||
rows: TeamRow[]
|
||||
viewerRole: OrcaOrgRole
|
||||
rowStates: Readonly<Record<string, TeamRowState>>
|
||||
/** The viewer may leave (another owner exists, or they are not an owner). */
|
||||
canLeave: boolean
|
||||
/** Shown under the disabled "Leave team…" item when `canLeave` is false: what to do instead. */
|
||||
leaveBlockedReason?: string | null
|
||||
now: number
|
||||
onChangeRole: (member: OrcaOrgMember, role: OrcaOrgRole) => void
|
||||
onMakeOwner: (member: OrcaOrgMember) => void
|
||||
onRemove: (member: OrcaOrgMember) => void
|
||||
onResend: (email: string, role: OrcaOrgRole) => void
|
||||
onRevoke: (email: string) => void
|
||||
onLeave: () => void
|
||||
/** Opens a signed-in member's profile (usage heatmap, recent workspaces, Pokes). */
|
||||
onOpenProfile?: (userId: string) => void
|
||||
}
|
||||
|
||||
function relativeSince(then: number, now: number, locale: string): string {
|
||||
const format = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' })
|
||||
const minutes = Math.round((then - now) / 60_000)
|
||||
if (Math.abs(minutes) < 60) {
|
||||
return format.format(Math.min(0, minutes), 'minute')
|
||||
}
|
||||
const hours = Math.round(minutes / 60)
|
||||
if (Math.abs(hours) < 24) {
|
||||
return format.format(hours, 'hour')
|
||||
}
|
||||
return format.format(Math.round(hours / 24), 'day')
|
||||
}
|
||||
|
||||
function RoleControl({
|
||||
row,
|
||||
viewerRole,
|
||||
busy,
|
||||
onChange
|
||||
}: {
|
||||
row: Extract<TeamRow, { kind: 'member' }>
|
||||
viewerRole: OrcaOrgRole
|
||||
busy: boolean
|
||||
onChange: (role: OrcaOrgRole) => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const member = row.member
|
||||
if (!row.manageable) {
|
||||
return (
|
||||
<span
|
||||
className="w-28 shrink-0 pl-3 text-left text-sm text-muted-foreground"
|
||||
title={
|
||||
row.managedByDirectory
|
||||
? t('auto.components.billing.team.managedByIdp', 'Managed by your identity provider')
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{roleLabel(member.role, t)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
const roles = assignableRoles(viewerRole)
|
||||
return (
|
||||
<Select
|
||||
value={member.role}
|
||||
// Not disabled while saving: disabling would drop keyboard focus. Changes wait instead.
|
||||
onValueChange={(next) => {
|
||||
const role = roles.find((candidate) => candidate === next)
|
||||
if (role && role !== member.role && !busy) {
|
||||
onChange(role)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger
|
||||
size="sm"
|
||||
className="w-28 shrink-0"
|
||||
aria-disabled={busy || undefined}
|
||||
aria-label={t('auto.components.billing.team.roleFor', 'Role for {{value0}}', {
|
||||
value0: member.displayName ?? member.email
|
||||
})}
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent align="end">
|
||||
{roles.map((role) => (
|
||||
<SelectItem key={role} value={role} title={roleDescription(role, t)}>
|
||||
{roleLabel(role, t)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)
|
||||
}
|
||||
|
||||
function RowMenu({
|
||||
row,
|
||||
props
|
||||
}: {
|
||||
row: TeamRow
|
||||
props: TeamMemberListProps
|
||||
}): React.JSX.Element | null {
|
||||
const t = useTranslate()
|
||||
const name =
|
||||
row.kind === 'member' ? (row.member.displayName ?? row.member.email) : row.invite.email
|
||||
const items: React.ReactNode[] = []
|
||||
const profileUserId = row.kind === 'member' && row.status === 'active' ? row.member.userId : null
|
||||
if (profileUserId && props.onOpenProfile) {
|
||||
items.push(
|
||||
<DropdownMenuItem key="profile" onSelect={() => props.onOpenProfile?.(profileUserId)}>
|
||||
<UserRound />
|
||||
{t('auto.components.billing.team.viewProfile', 'View profile')}
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
}
|
||||
// Profile sits apart from the role and membership actions below it.
|
||||
const separateFromProfile = (): void => {
|
||||
if (items.length === 1 && profileUserId && props.onOpenProfile) {
|
||||
items.push(<DropdownMenuSeparator key="profile-sep" />)
|
||||
}
|
||||
}
|
||||
if (row.kind === 'invite' && row.manageable) {
|
||||
separateFromProfile()
|
||||
items.push(
|
||||
<DropdownMenuItem
|
||||
key="resend"
|
||||
onSelect={() => props.onResend(row.invite.email, row.invite.role)}
|
||||
>
|
||||
<MailPlus />
|
||||
{t('auto.components.billing.team.resend', 'Resend invite')}
|
||||
</DropdownMenuItem>,
|
||||
<DropdownMenuSeparator key="sep" />,
|
||||
<DropdownMenuItem
|
||||
key="revoke"
|
||||
variant="destructive"
|
||||
onSelect={() => props.onRevoke(row.invite.email)}
|
||||
>
|
||||
<XCircle />
|
||||
{t('auto.components.billing.team.revokeInvite', 'Revoke invite')}
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
}
|
||||
if (row.kind === 'member' && row.manageable) {
|
||||
separateFromProfile()
|
||||
if (props.viewerRole === 'owner' && row.member.role !== 'owner') {
|
||||
items.push(
|
||||
<DropdownMenuItem key="owner" onSelect={() => props.onMakeOwner(row.member)}>
|
||||
<Crown />
|
||||
{t('auto.components.billing.team.makeOwner', 'Make owner…')}
|
||||
</DropdownMenuItem>,
|
||||
<DropdownMenuSeparator key="sep" />
|
||||
)
|
||||
}
|
||||
items.push(
|
||||
<DropdownMenuItem
|
||||
key="remove"
|
||||
variant="destructive"
|
||||
onSelect={() => props.onRemove(row.member)}
|
||||
>
|
||||
<UserMinus />
|
||||
{t('auto.components.billing.team.removeMember', 'Remove from team…')}
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
}
|
||||
if (row.self) {
|
||||
separateFromProfile()
|
||||
items.push(
|
||||
<DropdownMenuItem
|
||||
key="leave"
|
||||
variant="destructive"
|
||||
disabled={!props.canLeave}
|
||||
onSelect={props.onLeave}
|
||||
>
|
||||
<LogOut />
|
||||
{t('auto.components.billing.team.leave', 'Leave team…')}
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
if (!props.canLeave && props.leaveBlockedReason) {
|
||||
// A disabled item alone doesn't say why; the last owner needs the way out spelled out.
|
||||
items.push(
|
||||
<p
|
||||
key="leave-why"
|
||||
data-team-leave-blocked=""
|
||||
className="px-2 pb-1.5 text-xs text-muted-foreground text-pretty"
|
||||
>
|
||||
{props.leaveBlockedReason}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
}
|
||||
if (items.length === 0) {
|
||||
// Keeps the role column aligned with rows that have a menu.
|
||||
return <span aria-hidden className="size-7 shrink-0" />
|
||||
}
|
||||
return (
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="size-7 shrink-0"
|
||||
aria-label={t('auto.components.billing.team.actionsFor', 'Actions for {{value0}}', {
|
||||
value0: name
|
||||
})}
|
||||
>
|
||||
<MoreHorizontal />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className={row.self && !props.canLeave ? 'w-64' : 'w-48'}>
|
||||
{items}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
|
||||
export function TeamMemberList(props: TeamMemberListProps): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const locale = useIntlLocale()
|
||||
const mfaColumn = showMfaColumn(props.rows, props.viewerRole)
|
||||
return (
|
||||
<ul
|
||||
className="divide-y divide-border/60 overflow-hidden rounded-lg border border-border"
|
||||
aria-label={t('auto.components.billing.team.membersList', 'Team members and invites')}
|
||||
>
|
||||
{props.rows.map((row) => {
|
||||
const state = props.rowStates[row.key] ?? {}
|
||||
const name =
|
||||
row.kind === 'member' ? (row.member.displayName ?? row.member.email) : row.invite.email
|
||||
const profileUserId =
|
||||
row.kind === 'member' && row.status === 'active' ? row.member.userId : null
|
||||
const secondary =
|
||||
row.kind === 'member'
|
||||
? row.member.displayName
|
||||
? row.member.email
|
||||
: null
|
||||
: invitedAsCopy(
|
||||
row.invite.role,
|
||||
relativeSince(row.invite.createdAt, props.now, locale),
|
||||
t
|
||||
)
|
||||
return (
|
||||
<li
|
||||
key={row.key}
|
||||
data-team-row={row.key}
|
||||
aria-busy={state.busy || undefined}
|
||||
// Busy rows keep full contrast; the spinner and aria-busy say a change is pending.
|
||||
className="group/row flex min-h-12 flex-col justify-center bg-card px-3 py-2 transition-colors animate-in fade-in-0 duration-200 motion-reduce:animate-none"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<PersonAvatar
|
||||
name={name}
|
||||
pending={row.status !== 'active'}
|
||||
pictureUrl={row.kind === 'member' ? row.member.pictureUrl : undefined}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="flex min-w-0 items-center gap-2 text-sm font-medium">
|
||||
{profileUserId && props.onOpenProfile ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => props.onOpenProfile?.(profileUserId)}
|
||||
aria-label={t(
|
||||
'auto.components.billing.team.openProfile',
|
||||
'Open {{value0}}’s profile',
|
||||
{ value0: name }
|
||||
)}
|
||||
className="min-w-0 cursor-default truncate rounded-sm text-left outline-none hover:underline focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-focus-ring"
|
||||
>
|
||||
{name}
|
||||
</button>
|
||||
) : (
|
||||
<span className="truncate">{name}</span>
|
||||
)}
|
||||
{row.self ? (
|
||||
<span className="shrink-0 text-xs font-normal text-muted-foreground">
|
||||
{t('auto.components.billing.team.you', '(you)')}
|
||||
</span>
|
||||
) : null}
|
||||
{row.status === 'active' ? null : (
|
||||
<Badge variant="outline" className="shrink-0">
|
||||
<span className="text-muted-foreground">
|
||||
{memberStatusLabel(row.status, t)}
|
||||
</span>
|
||||
</Badge>
|
||||
)}
|
||||
</p>
|
||||
{secondary ? (
|
||||
<p className="truncate text-xs text-muted-foreground">{secondary}</p>
|
||||
) : null}
|
||||
</div>
|
||||
{state.busy ? <LoadingSpinner className="size-3.5 shrink-0" /> : null}
|
||||
{mfaColumn ? (
|
||||
// Rendered for every row, invites included, so the role column stays aligned.
|
||||
<span
|
||||
data-team-mfa={row.kind === 'member' ? (row.member.mfa ?? '') : ''}
|
||||
className="flex w-28 shrink-0"
|
||||
>
|
||||
{/* Only for members who have signed in: someone still pending has no account
|
||||
state yet, so "off" would mislead. */}
|
||||
{row.kind === 'member' &&
|
||||
row.status === 'active' &&
|
||||
memberMfaLabel(row.member, locale, t) ? (
|
||||
<Badge variant="tag">{memberMfaLabel(row.member, locale, t)}</Badge>
|
||||
) : null}
|
||||
</span>
|
||||
) : null}
|
||||
{row.kind === 'member' ? (
|
||||
<RoleControl
|
||||
row={row}
|
||||
viewerRole={props.viewerRole}
|
||||
busy={Boolean(state.busy)}
|
||||
onChange={(role) => props.onChangeRole(row.member, role)}
|
||||
/>
|
||||
) : (
|
||||
<span className="w-28 shrink-0 pl-3 text-left text-sm text-muted-foreground">
|
||||
{roleLabel(row.invite.role, t)}
|
||||
</span>
|
||||
)}
|
||||
<RowMenu row={row} props={props} />
|
||||
</div>
|
||||
{state.error ? <InlineError className="mt-2 ml-9" title={state.error} /> : null}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
@@ -1,407 +0,0 @@
|
||||
import { useEffect } from 'react'
|
||||
import { defineFixture } from '../../../component-fixtures/component-fixture'
|
||||
import { ConfirmationDialogProvider } from '@/components/confirmation-dialog'
|
||||
import { useConfirmationDialog } from '@/components/confirmation-dialog-context'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { Dialog } from '@/components/ui/dialog'
|
||||
import type { OrcaBillingEntitlement } from '../../../../../shared/orca-billing'
|
||||
import type { OrcaOrgMembersRoster } from '../../../../../shared/orca-profiles'
|
||||
import { sampleTeam } from '../plan-billing-fixtures'
|
||||
import { TeamDialogContent } from './TeamDialogHost'
|
||||
import { TeamPageView, type TeamPageViewProps } from './TeamPageView'
|
||||
import { TeamDeleteSection, type TeamDeleteCheck } from './TeamDeleteSection'
|
||||
import { leaveTeamConfirmation } from './team-leave'
|
||||
|
||||
// Fixtures render offline: a self-contained stand-in for a provider profile picture.
|
||||
const ADA_PICTURE =
|
||||
"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'><defs><linearGradient id='g' x1='0' y1='0' x2='1' y2='1'><stop offset='0' stop-color='%23f6c38f'/><stop offset='1' stop-color='%23c0713d'/></linearGradient></defs><rect width='64' height='64' fill='url(%23g)'/><circle cx='32' cy='26' r='12' fill='%23fff3e6'/><rect x='14' y='42' width='36' height='22' rx='11' fill='%23fff3e6'/></svg>"
|
||||
|
||||
const NOW = Date.UTC(2026, 10, 18, 15)
|
||||
const DAY = 86_400_000
|
||||
const width = 1100
|
||||
|
||||
const roster: OrcaOrgMembersRoster = {
|
||||
viewerRole: 'owner',
|
||||
canManageMembers: true,
|
||||
members: [
|
||||
{ userId: 'u-neil', email: 'neil@acme.dev', displayName: 'Neil Parker', role: 'owner' },
|
||||
{
|
||||
userId: 'u-ada',
|
||||
email: 'ada@acme.dev',
|
||||
displayName: 'Ada Lovelace',
|
||||
role: 'admin',
|
||||
pictureUrl: ADA_PICTURE
|
||||
},
|
||||
{ userId: 'u-grace', email: 'grace@acme.dev', displayName: 'Grace Hopper', role: 'member' },
|
||||
{ userId: null, email: 'linus@acme.dev', role: 'member' }
|
||||
],
|
||||
pendingInvites: [
|
||||
{ email: 'alex@acme.dev', role: 'member', createdAt: NOW - 2 * DAY },
|
||||
{ email: 'sam@acme.dev', role: 'admin', createdAt: NOW - 3 * 3600_000 }
|
||||
]
|
||||
}
|
||||
|
||||
const team: OrcaBillingEntitlement = {
|
||||
...sampleTeam,
|
||||
seats: 4,
|
||||
period: { start: Date.UTC(2026, 10, 3), end: Date.UTC(2026, 11, 3) }
|
||||
}
|
||||
const noPlan: OrcaBillingEntitlement = {
|
||||
...sampleTeam,
|
||||
plan: null,
|
||||
planLabel: null,
|
||||
status: 'none',
|
||||
interval: null,
|
||||
seats: 0,
|
||||
period: null,
|
||||
canStartSandbox: false,
|
||||
reason: 'no_subscription'
|
||||
}
|
||||
|
||||
const noop = (): void => {}
|
||||
const base: TeamPageViewProps = {
|
||||
org: { orgId: 'org-acme', name: 'Acme Engineering' },
|
||||
viewerUserId: 'u-neil',
|
||||
roster: { status: 'ok', roster },
|
||||
billing: { status: 'ok', entitlement: team },
|
||||
arrival: null,
|
||||
rowStates: {},
|
||||
refreshing: false,
|
||||
billingBusy: false,
|
||||
now: NOW,
|
||||
create: {
|
||||
organizations: [],
|
||||
creating: false,
|
||||
error: null,
|
||||
unavailable: false,
|
||||
switchingOrgId: null
|
||||
},
|
||||
onCreateTeam: noop,
|
||||
onSwitchOrg: noop,
|
||||
onRefresh: noop,
|
||||
onInvite: async () => ({ failed: [] }),
|
||||
onChangeRole: noop,
|
||||
onMakeOwner: noop,
|
||||
onRemove: noop,
|
||||
onResend: noop,
|
||||
onRevoke: noop,
|
||||
onLeave: noop,
|
||||
onSeePlans: noop,
|
||||
onManageBilling: noop,
|
||||
onCreateWorkspace: noop,
|
||||
onDismissArrival: noop,
|
||||
onOpenEnterprise: noop
|
||||
}
|
||||
|
||||
function Page(props: Partial<TeamPageViewProps>): React.JSX.Element {
|
||||
return (
|
||||
<Dialog open modal={false}>
|
||||
<TeamDialogContent>
|
||||
<TeamPageView {...base} {...props} />
|
||||
</TeamDialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export const ownerOnTeam = defineFixture({ width, render: () => <Page /> })
|
||||
|
||||
/** TEAM-MODAL-CENTER: in a tall window the dialog sits in the middle, not pinned near the top. */
|
||||
export const centeredInWindow = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<div className="h-[1000px]">
|
||||
<Page
|
||||
roster={{
|
||||
status: 'ok',
|
||||
roster: { ...roster, members: roster.members.slice(0, 2), pendingInvites: [] }
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export const justUpgraded = defineFixture({
|
||||
width,
|
||||
render: () => <Page arrival={{ kind: 'checkout-success', seats: 4 }} />
|
||||
})
|
||||
|
||||
export const noPlanUpgrade = defineFixture({
|
||||
width,
|
||||
render: () => <Page billing={{ status: 'ok', entitlement: noPlan }} />
|
||||
})
|
||||
|
||||
export const memberReadOnly = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page
|
||||
viewerUserId="u-grace"
|
||||
roster={{
|
||||
status: 'ok',
|
||||
roster: { ...roster, viewerRole: 'member', canManageMembers: false, pendingInvites: [] }
|
||||
}}
|
||||
billing={{ status: 'ok', entitlement: { ...noPlan, canManageBilling: false } }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
// What the server sends an owner or admin: every member carries an MFA status.
|
||||
const rosterWithMfa: OrcaOrgMembersRoster = {
|
||||
...roster,
|
||||
members: [
|
||||
{ ...roster.members[0]!, mfa: 'on' },
|
||||
{ ...roster.members[1]!, mfa: 'off' },
|
||||
{ ...roster.members[2]!, mfa: 'pending', mfaDeadline: NOW + 6 * DAY },
|
||||
{ ...roster.members[3]!, mfa: 'off' }
|
||||
]
|
||||
}
|
||||
|
||||
export const ownerSeesMfaColumn = defineFixture({
|
||||
width,
|
||||
render: () => <Page roster={{ status: 'ok', roster: rosterWithMfa }} />
|
||||
})
|
||||
|
||||
export const adminSeesMfaColumn = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page
|
||||
viewerUserId="u-ada"
|
||||
roster={{ status: 'ok', roster: { ...rosterWithMfa, viewerRole: 'admin' } }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const mfaColumnNarrow = defineFixture({
|
||||
width: 640,
|
||||
render: () => <Page roster={{ status: 'ok', roster: rosterWithMfa }} />
|
||||
})
|
||||
|
||||
export const rowBusyAndError = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page
|
||||
rowStates={{
|
||||
'member:u-grace': { busy: true },
|
||||
'invite:alex@acme.dev': {
|
||||
error: 'Too many team changes at once. Wait a minute and try again.'
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const seatsDropAtRenewal = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page
|
||||
billing={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...team,
|
||||
seats: 5,
|
||||
seatChange: { seatsAtRenewal: 4, effectiveAt: Date.UTC(2026, 11, 3) }
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
// Billing sent no catalog (an older service or a failed read): no price is shown, never "$0".
|
||||
export const noPriceKnown = defineFixture({
|
||||
width,
|
||||
render: () => <Page billing={{ status: 'ok', entitlement: { ...team, offers: null } }} />
|
||||
})
|
||||
|
||||
export const paymentFailed = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page
|
||||
billing={{
|
||||
status: 'ok',
|
||||
entitlement: {
|
||||
...team,
|
||||
status: 'past_due',
|
||||
payment: { pastDueSince: NOW - DAY, graceEndsAt: NOW + 3 * DAY, suspendRunning: false },
|
||||
canStartSandbox: false,
|
||||
reason: 'payment_past_due'
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const loading = defineFixture({ width, render: () => <Page roster={null} billing={null} /> })
|
||||
|
||||
export const loadFailed = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page
|
||||
roster={{ status: 'failed', error: 'timeout' }}
|
||||
billing={{ status: 'failed', error: 'x' }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const personalCreateTeam = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page
|
||||
org={null}
|
||||
create={{
|
||||
organizations: [
|
||||
{ orgId: 'org-acme', name: 'Acme Engineering', role: 'Admin' },
|
||||
{ orgId: 'org-oss', name: 'Open Source Club', role: 'Member' }
|
||||
],
|
||||
creating: false,
|
||||
error: null,
|
||||
unavailable: false,
|
||||
switchingOrgId: null
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const createTeamUnsupported = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page
|
||||
org={null}
|
||||
create={{
|
||||
organizations: [],
|
||||
creating: false,
|
||||
error: null,
|
||||
unavailable: true,
|
||||
switchingOrgId: null
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
/** Types into the invite field; the trailing separator commits the chips. */
|
||||
async function typeInvites(text: string): Promise<void> {
|
||||
// The dialog portals to <body>, outside the fixture frame.
|
||||
const input = document.querySelector<HTMLInputElement>('input[inputmode="email"]')
|
||||
if (!input) {
|
||||
return
|
||||
}
|
||||
input.focus()
|
||||
// React listens for native input events.
|
||||
const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set
|
||||
setValue?.call(input, text)
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
}
|
||||
|
||||
/** Pasted list: the chips, one invalid entry, and the seat rule (no counts or prices). */
|
||||
export const invitePasted = defineFixture({
|
||||
width,
|
||||
render: () => <Page billing={{ status: 'ok', entitlement: { ...team, seats: 4 } }} />,
|
||||
interact: () => typeInvites('jordan@acme.dev, kim@acme.dev, not-an-email ')
|
||||
})
|
||||
|
||||
/** Short roster so the Enterprise row sits inside the frame. */
|
||||
export const ssoRow = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<Page
|
||||
roster={{
|
||||
status: 'ok',
|
||||
roster: {
|
||||
...roster,
|
||||
members: [roster.members[0]!, { ...roster.members[1]!, role: 'owner' }],
|
||||
pendingInvites: []
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
/** The only owner opens the ⋯ on their own row: Leave is off and says what to do instead. */
|
||||
export const lastOwnerLeaveBlocked = defineFixture({
|
||||
width,
|
||||
render: () => <Page />,
|
||||
interact: async () => {
|
||||
const trigger = document.querySelector<HTMLElement>(
|
||||
'[data-team-row="member:u-neil"] button[aria-haspopup="menu"]'
|
||||
)
|
||||
trigger?.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }))
|
||||
await new Promise((resolve) => setTimeout(resolve, 150))
|
||||
}
|
||||
})
|
||||
|
||||
/** Choosing "Leave team…" from the ⋯ menu on your own row. */
|
||||
function OpenLeaveConfirm(): null {
|
||||
const t = useTranslate()
|
||||
const confirm = useConfirmationDialog()
|
||||
useEffect(() => {
|
||||
void confirm(leaveTeamConfirmation('Orca Staging Eval Team', t))
|
||||
}, [confirm, t])
|
||||
return null
|
||||
}
|
||||
|
||||
export const leaveConfirm = defineFixture({
|
||||
width: 560,
|
||||
render: () => (
|
||||
<div className="h-[300px]">
|
||||
<ConfirmationDialogProvider>
|
||||
<OpenLeaveConfirm />
|
||||
</ConfirmationDialogProvider>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
// TEAM-DELETE: Settings › Team (inline), owner. The danger zone sits in the bottom card.
|
||||
function DeletePage({ check }: { check: TeamDeleteCheck }): React.JSX.Element {
|
||||
// Settings › Team renders the page inline, not in the dialog, so the whole page shows.
|
||||
return (
|
||||
<div className="max-w-2xl p-6">
|
||||
<TeamPageView
|
||||
{...base}
|
||||
inline={{ onOpenPlanBilling: noop }}
|
||||
dangerZone={
|
||||
<TeamDeleteSection
|
||||
teamName="Acme Engineering"
|
||||
check={check}
|
||||
onDelete={noop}
|
||||
onBlockerAction={noop}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const deleteTeamAllowed = defineFixture({
|
||||
width,
|
||||
render: () => <DeletePage check={{ state: 'ready', blockers: [] }} />
|
||||
})
|
||||
|
||||
export const deleteTeamBlockedPlan = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<DeletePage
|
||||
check={{ state: 'ready', blockers: [{ code: 'subscription_active', status: 'active' }] }}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const deleteTeamBlockedOneWorkspace = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<DeletePage check={{ state: 'ready', blockers: [{ code: 'workspaces_exist', count: 1 }] }} />
|
||||
)
|
||||
})
|
||||
|
||||
export const deleteTeamBlockedBoth = defineFixture({
|
||||
width,
|
||||
render: () => (
|
||||
<DeletePage
|
||||
check={{
|
||||
state: 'ready',
|
||||
blockers: [
|
||||
{ code: 'subscription_active', status: 'trialing' },
|
||||
{ code: 'workspaces_exist', count: 3 }
|
||||
]
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
@@ -1,100 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||
import type { OrcaOrgMembersRoster } from '../../../../../shared/orca-profiles'
|
||||
import { sampleTeam } from '../plan-billing-fixtures'
|
||||
import { TeamPageView, type TeamPageViewProps } from './TeamPageView'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const roster: OrcaOrgMembersRoster = {
|
||||
viewerRole: 'owner',
|
||||
canManageMembers: true,
|
||||
members: [
|
||||
{ userId: 'u-neil', email: 'neil@acme.dev', displayName: 'Neil Parker', role: 'owner' },
|
||||
{ userId: 'u-ada', email: 'ada@acme.dev', displayName: 'Ada Lovelace', role: 'admin' }
|
||||
],
|
||||
pendingInvites: [{ email: 'sam@acme.dev', role: 'member', createdAt: 0 }]
|
||||
}
|
||||
|
||||
const noop = (): void => {}
|
||||
const props: TeamPageViewProps = {
|
||||
org: { orgId: 'org-acme', name: 'Acme Engineering' },
|
||||
viewerUserId: 'u-neil',
|
||||
roster: { status: 'ok', roster },
|
||||
billing: { status: 'ok', entitlement: { ...sampleTeam, canManageBilling: true } },
|
||||
arrival: null,
|
||||
rowStates: {},
|
||||
refreshing: false,
|
||||
billingBusy: false,
|
||||
now: 0,
|
||||
create: {
|
||||
organizations: [],
|
||||
creating: false,
|
||||
error: null,
|
||||
unavailable: false,
|
||||
switchingOrgId: null
|
||||
},
|
||||
onCreateTeam: noop,
|
||||
onSwitchOrg: noop,
|
||||
onRefresh: noop,
|
||||
onInvite: async () => ({ failed: [] }),
|
||||
onChangeRole: noop,
|
||||
onMakeOwner: noop,
|
||||
onRemove: noop,
|
||||
onResend: noop,
|
||||
onRevoke: noop,
|
||||
onLeave: noop,
|
||||
onSeePlans: noop,
|
||||
onManageBilling: noop,
|
||||
onCreateWorkspace: noop,
|
||||
onDismissArrival: noop
|
||||
}
|
||||
|
||||
it('keeps the header to the name and counts: no role sentence, no Plan & billing button', () => {
|
||||
render(<TeamPageView {...props} />, { wrapper: TooltipProvider })
|
||||
const header = document.querySelector('header')!
|
||||
expect(header.textContent).toContain('2 members · 1 invited')
|
||||
expect(header.textContent).not.toMatch(/You’re an|Plan & billing/)
|
||||
expect(header.querySelector('button')).toBeNull()
|
||||
// Seat counts and prices live only in Plan & billing.
|
||||
expect(screen.queryByText(/open seat/)).toBeNull()
|
||||
})
|
||||
|
||||
it('points owners and admins to Settings › Enterprise with one plain button', () => {
|
||||
const onOpenEnterprise = vi.fn()
|
||||
for (const viewerRole of ['owner', 'admin'] as const) {
|
||||
render(
|
||||
<TeamPageView
|
||||
{...props}
|
||||
roster={{ status: 'ok', roster: { ...roster, viewerRole } }}
|
||||
onOpenEnterprise={onOpenEnterprise}
|
||||
/>,
|
||||
{ wrapper: TooltipProvider }
|
||||
)
|
||||
const row = screen.getByRole('region', {
|
||||
name: 'Single sign-on, directory sync and the audit log'
|
||||
})
|
||||
// No Copy link split: the row has exactly one control.
|
||||
expect(row.querySelectorAll('button')).toHaveLength(1)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Open Enterprise settings' }))
|
||||
cleanup()
|
||||
}
|
||||
expect(onOpenEnterprise).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('hides the Enterprise row from plain members', () => {
|
||||
render(
|
||||
<TeamPageView
|
||||
{...props}
|
||||
roster={{
|
||||
status: 'ok',
|
||||
roster: { ...roster, viewerRole: 'member', canManageMembers: false }
|
||||
}}
|
||||
onOpenEnterprise={() => {}}
|
||||
/>,
|
||||
{ wrapper: TooltipProvider }
|
||||
)
|
||||
expect(screen.queryByText('Single sign-on, directory sync and the audit log')).toBeNull()
|
||||
})
|
||||
@@ -1,327 +0,0 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { KeyRound, RefreshCw } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { InlineError } from '@/components/ui/inline-error'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { cn } from '@/lib/class-names'
|
||||
import type { OrcaBillingStatusResult } from '../../../../../shared/orca-billing'
|
||||
import type {
|
||||
OrcaOrgMember,
|
||||
OrcaOrgRole,
|
||||
OrcaProfileOrgMembersListResult
|
||||
} from '../../../../../shared/orca-profiles'
|
||||
import { TeamMark } from './TeamAvatar'
|
||||
import { TeamCreateView, type TeamCreateViewProps } from './TeamCreateView'
|
||||
import { TeamInviteComposer, type InviteBatchOutcome } from './TeamInviteComposer'
|
||||
import { TeamMemberList, type TeamRowState } from './TeamMemberList'
|
||||
import { PaymentIssueNotice } from '../PaymentIssueNotice'
|
||||
import { TeamCheckoutCelebration, TeamUpgradeCard } from './TeamPlanSummary'
|
||||
import { memberCountLabel } from './team-copy'
|
||||
import { leaveBlockedReason } from './team-leave'
|
||||
import { otherOwnerCount, teamRows } from './team-roster-rows'
|
||||
import { isActivePlan } from './team-seat-math'
|
||||
import type { TeamPageArrival } from './team-page-store'
|
||||
|
||||
export type TeamPageViewProps = {
|
||||
/** The active team, or null on a personal account. */
|
||||
org: { orgId: string; name: string } | null
|
||||
/** The team's MFA requirement for this person: the countdown banner or the setup screen. */
|
||||
mfaNotice?: React.ReactNode
|
||||
viewerUserId: string | null
|
||||
roster: OrcaProfileOrgMembersListResult | null
|
||||
billing: OrcaBillingStatusResult | null
|
||||
arrival: TeamPageArrival
|
||||
rowStates: Readonly<Record<string, TeamRowState>>
|
||||
/** True only while a user-requested refresh runs (review M16: no spin on background reads). */
|
||||
refreshing: boolean
|
||||
billingBusy: boolean
|
||||
now: number
|
||||
create: Omit<TeamCreateViewProps, 'onCreate' | 'onSwitch'>
|
||||
onCreateTeam: (name: string) => void
|
||||
onSwitchOrg: (orgId: string) => void
|
||||
onRefresh: () => void
|
||||
onInvite: (emails: string[], role: OrcaOrgRole) => Promise<InviteBatchOutcome>
|
||||
onChangeRole: (member: OrcaOrgMember, role: OrcaOrgRole) => void
|
||||
onMakeOwner: (member: OrcaOrgMember) => void
|
||||
onRemove: (member: OrcaOrgMember) => void
|
||||
onResend: (email: string, role: OrcaOrgRole) => void
|
||||
onRevoke: (email: string) => void
|
||||
onLeave: () => void
|
||||
onOpenProfile?: (userId: string) => void
|
||||
onSeePlans: () => void
|
||||
onManageBilling: () => void
|
||||
onCreateWorkspace: () => void
|
||||
onDismissArrival: () => void
|
||||
/** Settings → Team renders the page inline: seats and invoices stay on Plan & billing (linked). */
|
||||
inline?: { onOpenPlanBilling: () => void }
|
||||
/** Owners in Settings › Team: "Delete <team>", after "Leave <team>" (TEAM-DELETE). */
|
||||
dangerZone?: React.ReactNode
|
||||
/** Opens Settings › Enterprise (SSO, SCIM, audit log). Shown to owners and admins only. */
|
||||
onOpenEnterprise?: () => void
|
||||
}
|
||||
|
||||
function SkeletonRows(): React.JSX.Element {
|
||||
return (
|
||||
<div
|
||||
aria-hidden
|
||||
className="divide-y divide-border/60 overflow-hidden rounded-lg border border-border"
|
||||
>
|
||||
{[0, 1, 2].map((index) => (
|
||||
<div key={index} className="flex min-h-12 items-center gap-3 bg-card px-3 py-2">
|
||||
<Skeleton shape="circle" className="size-6" />
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Skeleton className="h-3 w-32" />
|
||||
<Skeleton className="h-2.5 w-44" />
|
||||
</div>
|
||||
<Skeleton className="h-8 w-28" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function TeamPageView(props: TeamPageViewProps): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const inviteInput = useRef<HTMLInputElement>(null)
|
||||
const hasRoster = props.roster !== null
|
||||
const inline = props.inline ?? null
|
||||
useEffect(() => {
|
||||
const active = document.activeElement
|
||||
if (
|
||||
!inline &&
|
||||
hasRoster &&
|
||||
(!active || active === document.body || active.getAttribute('role') === 'dialog')
|
||||
) {
|
||||
document.querySelector<HTMLElement>('[data-team-page-heading]')?.focus()
|
||||
}
|
||||
}, [hasRoster, inline])
|
||||
|
||||
if (!props.org) {
|
||||
return (
|
||||
<TeamCreateView
|
||||
{...props.create}
|
||||
onCreate={props.onCreateTeam}
|
||||
onSwitch={props.onSwitchOrg}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const roster = props.roster?.status === 'ok' ? props.roster.roster : null
|
||||
const entitlement = props.billing?.status === 'ok' ? props.billing.entitlement : null
|
||||
const rows = roster ? teamRows(roster, props.viewerUserId) : []
|
||||
const selfRow = rows.find((row) => row.self)
|
||||
const viewerRole = roster?.viewerRole ?? 'member'
|
||||
// Matches who sees Settings › Enterprise: team owners and admins (Enterprise or not).
|
||||
const showEnterprise =
|
||||
Boolean(props.onOpenEnterprise) &&
|
||||
(roster?.viewerRole === 'owner' || roster?.viewerRole === 'admin')
|
||||
const canLeave =
|
||||
Boolean(selfRow) &&
|
||||
(viewerRole !== 'owner' || (roster ? otherOwnerCount(roster, props.viewerUserId) > 0 : false))
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{props.mfaNotice ?? null}
|
||||
<header className="flex items-center gap-3">
|
||||
<TeamMark name={props.org.name} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<h2
|
||||
data-team-page-heading=""
|
||||
tabIndex={-1}
|
||||
className="truncate text-lg font-semibold tracking-tight outline-none"
|
||||
>
|
||||
{props.org.name}
|
||||
</h2>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{roster
|
||||
? [
|
||||
memberCountLabel(roster.members.length, t),
|
||||
roster.pendingInvites.length > 0
|
||||
? t('auto.components.billing.team.invitedCount', '{{count}} invited', {
|
||||
count: roster.pendingInvites.length
|
||||
})
|
||||
: null
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ')
|
||||
: props.roster === null
|
||||
? t('auto.components.billing.team.loading', 'Loading your team…')
|
||||
: t('auto.components.billing.team.loadFailedTitle', 'Couldn’t load team')}
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{props.arrival?.kind === 'checkout-success' && entitlement ? (
|
||||
<TeamCheckoutCelebration
|
||||
seats={entitlement.seats || props.arrival.seats}
|
||||
planLabel={entitlement.planLabel ?? 'Team'}
|
||||
onCreateWorkspace={props.onCreateWorkspace}
|
||||
onInvite={() => {
|
||||
props.onDismissArrival()
|
||||
inviteInput.current?.focus()
|
||||
}}
|
||||
onDismiss={() => {
|
||||
props.onDismissArrival()
|
||||
// The focused dismiss button unmounts; keep focus on something real.
|
||||
;(inviteInput.current ?? document.getElementById('team-members-title'))?.focus()
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{inline ? (
|
||||
<p className="flex flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
|
||||
{t('auto.components.billing.team.seatsOnPlanBilling', 'Seats and invoices are in')}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-sm text-foreground underline underline-offset-2 hover:text-foreground/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={inline.onOpenPlanBilling}
|
||||
>
|
||||
{t('settings.accountBilling.title2', 'Account & billing')}
|
||||
</button>
|
||||
</p>
|
||||
) : entitlement ? (
|
||||
<>
|
||||
<PaymentIssueNotice
|
||||
entitlement={entitlement}
|
||||
busy={props.billingBusy}
|
||||
onUpdatePayment={props.onManageBilling}
|
||||
/>
|
||||
{isActivePlan(entitlement) ? null : (
|
||||
<TeamUpgradeCard entitlement={entitlement} onSeePlans={props.onSeePlans} />
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{props.roster === null ? (
|
||||
<div aria-hidden className="space-y-2">
|
||||
<Skeleton className="h-4 w-28" />
|
||||
<div className="flex gap-2">
|
||||
<Skeleton className="h-8 flex-1" />
|
||||
<Skeleton className="h-8 w-28" />
|
||||
<Skeleton className="h-8 w-28" />
|
||||
</div>
|
||||
<Skeleton className="h-3 w-3/4" />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{roster?.canManageMembers ? (
|
||||
<TeamInviteComposer
|
||||
viewerRole={viewerRole}
|
||||
onInvite={props.onInvite}
|
||||
inputRef={inviteInput}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<section aria-labelledby="team-members-title" className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h3 id="team-members-title" tabIndex={-1} className="text-sm font-medium outline-none">
|
||||
{t('auto.components.billing.team.members', 'Members')}
|
||||
</h3>
|
||||
{roster ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={props.refreshing ? undefined : props.onRefresh}
|
||||
aria-disabled={props.refreshing || undefined}
|
||||
aria-label={t('auto.components.billing.team.refresh', 'Refresh team')}
|
||||
>
|
||||
<RefreshCw className={cn(props.refreshing && 'motion-safe:animate-spin')} />
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
{roster?.directoryManaged ? (
|
||||
<p role="note" className="text-xs text-muted-foreground text-pretty">
|
||||
{t(
|
||||
'auto.components.billing.team.managedByIdpNote',
|
||||
'Managed by your identity provider. Add or remove people and change roles there.'
|
||||
)}
|
||||
</p>
|
||||
) : null}
|
||||
{roster ? (
|
||||
<TeamMemberList
|
||||
rows={rows}
|
||||
viewerRole={viewerRole}
|
||||
rowStates={props.rowStates}
|
||||
canLeave={canLeave}
|
||||
leaveBlockedReason={leaveBlockedReason(
|
||||
{ canLeave, canDeleteTeam: Boolean(props.dangerZone) },
|
||||
t
|
||||
)}
|
||||
now={props.now}
|
||||
// Promoting to owner hands over billing control, so it always confirms first.
|
||||
onChangeRole={(member, role) =>
|
||||
role === 'owner' ? props.onMakeOwner(member) : props.onChangeRole(member, role)
|
||||
}
|
||||
onMakeOwner={props.onMakeOwner}
|
||||
onRemove={props.onRemove}
|
||||
onResend={props.onResend}
|
||||
onRevoke={props.onRevoke}
|
||||
onLeave={props.onLeave}
|
||||
onOpenProfile={props.onOpenProfile}
|
||||
/>
|
||||
) : props.roster === null ? (
|
||||
<SkeletonRows />
|
||||
) : (
|
||||
<InlineError
|
||||
title={t('auto.components.billing.team.loadFailedTitle', 'Couldn’t load team')}
|
||||
detail={
|
||||
props.roster.status === 'reconnect-required'
|
||||
? t(
|
||||
'auto.components.billing.openSignedOut2',
|
||||
'Sign in to Orca again to manage your team.'
|
||||
)
|
||||
: t(
|
||||
'auto.components.billing.team.loadFailed2',
|
||||
'Couldn’t load your team. Check your connection.'
|
||||
)
|
||||
}
|
||||
retryLabel={t('auto.components.billing.plans.retry', 'Try again')}
|
||||
onRetry={props.onRefresh}
|
||||
retrying={props.refreshing}
|
||||
/>
|
||||
)}
|
||||
{roster && !roster.canManageMembers ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
'auto.components.billing.team.readOnly',
|
||||
'Only owners and admins can invite people or change roles.'
|
||||
)}
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
{showEnterprise || props.dangerZone ? (
|
||||
<div className="divide-y divide-border/60 rounded-xl border border-border">
|
||||
{showEnterprise ? (
|
||||
// One quiet pointer to Settings › Enterprise, which owns SSO, SCIM and the audit log
|
||||
// (and shows the upsell to teams without Enterprise). Same audience as that section.
|
||||
<section
|
||||
aria-labelledby="team-enterprise-title"
|
||||
className="flex flex-wrap items-center gap-3 p-4"
|
||||
>
|
||||
<h3
|
||||
id="team-enterprise-title"
|
||||
className="flex min-w-[14rem] flex-1 items-center gap-2 text-sm font-medium"
|
||||
>
|
||||
<KeyRound aria-hidden className="size-4 shrink-0 text-muted-foreground" />
|
||||
{t(
|
||||
'auto.components.billing.team.enterpriseRowTitle',
|
||||
'Single sign-on, directory sync and the audit log'
|
||||
)}
|
||||
</h3>
|
||||
<Button type="button" variant="outline" size="sm" onClick={props.onOpenEnterprise}>
|
||||
{t(
|
||||
'auto.components.billing.team.openEnterpriseSettings',
|
||||
'Open Enterprise settings'
|
||||
)}
|
||||
</Button>
|
||||
</section>
|
||||
) : null}
|
||||
{props.dangerZone}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { ArrowRight, Check, Cloud, UserPlus, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
|
||||
import type { OrcaBillingEntitlement } from '../../../../../shared/orca-billing'
|
||||
import { formatCents, perSeatMonthlyCents } from '../plans/plans-pricing'
|
||||
import { seatCountLabel } from './team-copy'
|
||||
import { nextInvoiceEstimate } from './team-seat-math'
|
||||
|
||||
/** One-time confirmation after Checkout: tasteful, dismissible, with the obvious next steps. */
|
||||
export function TeamCheckoutCelebration({
|
||||
seats,
|
||||
planLabel,
|
||||
onCreateWorkspace,
|
||||
onInvite,
|
||||
onDismiss
|
||||
}: {
|
||||
seats: number
|
||||
planLabel: string
|
||||
onCreateWorkspace: () => void
|
||||
onInvite: () => void
|
||||
onDismiss: () => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const headingRef = useRef<HTMLHeadingElement>(null)
|
||||
useEffect(() => {
|
||||
// Billing can answer seconds after the page opens; only take focus if the user hasn't
|
||||
// moved it into the page yet (it's still on the dialog itself or nowhere).
|
||||
const active = document.activeElement
|
||||
if (!active || active === document.body || active.getAttribute('role') === 'dialog') {
|
||||
headingRef.current?.focus()
|
||||
}
|
||||
}, [])
|
||||
return (
|
||||
<section
|
||||
aria-labelledby="team-celebration-title"
|
||||
className="relative overflow-hidden rounded-xl border border-border bg-muted/40 p-4 animate-in fade-in-0 slide-in-from-top-2 duration-300 motion-reduce:animate-none"
|
||||
>
|
||||
<div className="relative flex items-start gap-3">
|
||||
<span
|
||||
aria-hidden
|
||||
className="flex size-9 shrink-0 items-center justify-center rounded-full bg-status-success text-background shadow-sm animate-in zoom-in-50 duration-300 motion-reduce:animate-none"
|
||||
>
|
||||
<Check className="size-5" strokeWidth={2.5} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<h3
|
||||
id="team-celebration-title"
|
||||
ref={headingRef}
|
||||
tabIndex={-1}
|
||||
className="text-base font-semibold tracking-tight outline-none"
|
||||
>
|
||||
{t('auto.components.billing.team.celebrateTitle2', 'Welcome to Orca Cloud')}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground text-pretty">
|
||||
{t(
|
||||
'auto.components.billing.team.celebrateBody2',
|
||||
'{{value0}} plan · {{value1}} active. Agents keep running in the cloud when you step away.',
|
||||
{ value0: planLabel, value1: seatCountLabel(seats, t) }
|
||||
)}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2 pt-2">
|
||||
<Button type="button" size="sm" onClick={onCreateWorkspace}>
|
||||
<Cloud />
|
||||
{t('auto.components.billing.team.createWorkspace', 'Create a cloud workspace')}
|
||||
</Button>
|
||||
<Button type="button" size="sm" variant="outline" onClick={onInvite}>
|
||||
<UserPlus />
|
||||
{t('auto.components.billing.team.inviteTeammates', 'Invite teammates')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
onClick={onDismiss}
|
||||
aria-label={t('auto.components.billing.team.dismiss', 'Dismiss')}
|
||||
>
|
||||
<X />
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function Stat({
|
||||
label,
|
||||
value,
|
||||
detail
|
||||
}: {
|
||||
label: string
|
||||
value: string
|
||||
detail?: string | null
|
||||
}): React.JSX.Element {
|
||||
return (
|
||||
<div className="min-w-0 space-y-0.5">
|
||||
<dt className="text-xs text-muted-foreground">{label}</dt>
|
||||
<dd className="truncate text-sm font-medium tabular-nums">{value}</dd>
|
||||
{detail ? <dd className="truncate text-xs text-muted-foreground">{detail}</dd> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The seat facts in Plan & billing: seats paid and in use, the per-seat price, the next invoice (an
|
||||
* estimate before tax and overage) and the seat rule. Billing's numbers only; no price is shown
|
||||
* when billing didn't send one.
|
||||
*/
|
||||
export function PlanSeatFacts({
|
||||
entitlement,
|
||||
members
|
||||
}: {
|
||||
entitlement: OrcaBillingEntitlement
|
||||
members: number
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const locale = useIntlLocale()
|
||||
const date = (ms: number): string =>
|
||||
new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }).format(ms)
|
||||
const invoice = nextInvoiceEstimate(entitlement)
|
||||
// Only a price billing actually sent; never "$0 per seat".
|
||||
const seatMonthlyCents = entitlement.offers
|
||||
? perSeatMonthlyCents(entitlement.offers.team, entitlement.interval ?? 'month')
|
||||
: null
|
||||
const seatsDetail = entitlement.seatChange
|
||||
? t('auto.components.billing.team.seatsDropOn', 'Drops to {{value0}} on {{value1}}', {
|
||||
value0: String(entitlement.seatChange.seatsAtRenewal),
|
||||
value1: date(entitlement.seatChange.effectiveAt)
|
||||
})
|
||||
: members > entitlement.seats
|
||||
? // Billing re-reads membership on its next sync and charges the new seats then.
|
||||
t('auto.components.billing.team.seatsSyncing', '{{value0}} members · updating', {
|
||||
value0: String(members)
|
||||
})
|
||||
: t('auto.components.billing.team.seatsInUse', '{{value0}} in use', {
|
||||
value0: String(members)
|
||||
})
|
||||
const billedLabel =
|
||||
entitlement.interval === 'year'
|
||||
? t('auto.components.billing.annual', 'Annual')
|
||||
: t('auto.components.billing.monthly', 'Monthly')
|
||||
return (
|
||||
<div className="space-y-2 border-t border-border/60 pt-3">
|
||||
<dl className="grid grid-cols-3 gap-4">
|
||||
<Stat
|
||||
label={t('auto.components.billing.team.seatsPaid', 'Seats paid')}
|
||||
value={String(entitlement.seats)}
|
||||
detail={seatsDetail}
|
||||
/>
|
||||
<Stat
|
||||
label={t('auto.components.billing.team.perSeat', 'Per seat')}
|
||||
value={
|
||||
seatMonthlyCents === null
|
||||
? billedLabel
|
||||
: t('auto.components.billing.team.perSeatMonthValue', '{{value0}}/mo', {
|
||||
value0: formatCents(seatMonthlyCents, locale)
|
||||
})
|
||||
}
|
||||
detail={seatMonthlyCents === null ? null : billedLabel}
|
||||
/>
|
||||
{invoice ? (
|
||||
<Stat
|
||||
label={t('auto.components.billing.team.nextInvoice', 'Next invoice (est.)')}
|
||||
value={formatCents(invoice.amountCents, locale)}
|
||||
detail={t('auto.components.billing.team.nextInvoiceOn', '{{value0}} · {{value1}}', {
|
||||
value0: date(invoice.at),
|
||||
value1: seatCountLabel(invoice.seats, t)
|
||||
})}
|
||||
/>
|
||||
) : (
|
||||
<Stat
|
||||
label={t('auto.components.billing.team.planEnds', 'Plan ends')}
|
||||
value={entitlement.period ? date(entitlement.period.end) : '—'}
|
||||
/>
|
||||
)}
|
||||
</dl>
|
||||
<p className="text-xs text-muted-foreground text-pretty">
|
||||
{t(
|
||||
'auto.components.billing.team.seatRulesShort',
|
||||
'New members above your paid seats are charged now, prorated. Removed seats stay paid until renewal.'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** "Upgrade to use Orca Cloud" for teams without a plan. Members see who can upgrade. */
|
||||
export function TeamUpgradeCard({
|
||||
entitlement,
|
||||
onSeePlans
|
||||
}: {
|
||||
entitlement: OrcaBillingEntitlement
|
||||
onSeePlans: () => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const locale = useIntlLocale()
|
||||
const monthly = entitlement.offers?.team.monthlyPriceCentsPerSeat ?? null
|
||||
return (
|
||||
<section
|
||||
aria-labelledby="team-upgrade-title"
|
||||
className="relative overflow-hidden rounded-xl border border-border bg-card p-4 shadow-xs"
|
||||
>
|
||||
<div
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute inset-0 bg-[radial-gradient(120%_80%_at_100%_0%,color-mix(in_oklab,var(--foreground)_7%,transparent),transparent_60%)]"
|
||||
/>
|
||||
<div className="relative flex flex-wrap items-center gap-4">
|
||||
<span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground">
|
||||
<Cloud className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-[14rem] flex-1 space-y-0.5">
|
||||
<h3 id="team-upgrade-title" className="text-sm font-semibold">
|
||||
{t('auto.components.billing.upgrade.title', 'Upgrade to use Orca Cloud')}
|
||||
</h3>
|
||||
<p className="text-xs text-muted-foreground text-pretty">
|
||||
{monthly === null
|
||||
? t(
|
||||
'auto.components.billing.upgrade.bodyNoPrice',
|
||||
'Hosted sandboxes for the whole team. Agents keep running when you close your laptop.'
|
||||
)
|
||||
: t(
|
||||
'auto.components.billing.upgrade.body3',
|
||||
'Hosted sandboxes for the whole team. Agents keep running when you close your laptop. {{price}} per seat per month.',
|
||||
{ price: formatCents(monthly, locale) }
|
||||
)}
|
||||
</p>
|
||||
{entitlement.canManageBilling ? null : (
|
||||
<p className="pt-1 text-xs font-medium text-muted-foreground">
|
||||
{t('auto.components.billing.upgrade.askOwner', 'Ask an owner or admin to upgrade.')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{entitlement.canManageBilling ? (
|
||||
<Button type="button" onClick={onSeePlans}>
|
||||
{t('auto.components.billing.comparePlans', 'Compare plans')}
|
||||
<ArrowRight />
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
MAX_INVITES_PER_BATCH,
|
||||
mergeInviteCandidates,
|
||||
splitInviteText
|
||||
} from './parse-invite-emails'
|
||||
|
||||
describe('splitInviteText', () => {
|
||||
it('splits commas, semicolons, newlines and spaces', () => {
|
||||
expect(splitInviteText('a@x.io, b@x.io;c@x.io\nd@x.io e@x.io')).toEqual([
|
||||
'a@x.io',
|
||||
'b@x.io',
|
||||
'c@x.io',
|
||||
'd@x.io',
|
||||
'e@x.io'
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps only the address from mail-client lines', () => {
|
||||
expect(splitInviteText('Ada Lovelace <ada@x.io>, "Grace H" <grace@x.io>')).toEqual([
|
||||
'ada@x.io',
|
||||
'grace@x.io'
|
||||
])
|
||||
})
|
||||
|
||||
it('strips mailto and wrapping punctuation', () => {
|
||||
expect(splitInviteText('mailto:a@x.io (b@x.io).')).toEqual(['a@x.io', 'b@x.io'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('mergeInviteCandidates', () => {
|
||||
it('dedupes case-insensitively and flags invalid entries', () => {
|
||||
const merged = mergeInviteCandidates([{ email: 'a@x.io', valid: true }], ['A@X.io', 'nope'])
|
||||
expect(merged).toEqual([
|
||||
{ email: 'a@x.io', valid: true },
|
||||
{ email: 'nope', valid: false }
|
||||
])
|
||||
})
|
||||
|
||||
it('caps a batch', () => {
|
||||
const tokens = Array.from({ length: MAX_INVITES_PER_BATCH + 5 }, (_, i) => `u${i}@x.io`)
|
||||
expect(mergeInviteCandidates([], tokens)).toHaveLength(MAX_INVITES_PER_BATCH)
|
||||
})
|
||||
})
|
||||
@@ -1,47 +0,0 @@
|
||||
// Turns pasted text (a list from a spreadsheet, "Name <a@b.co>" lines from a mail client, comma or
|
||||
// newline separated) into invite candidates. Validation is advisory; auth re-validates every email.
|
||||
|
||||
export const MAX_INVITES_PER_BATCH = 50
|
||||
|
||||
const EMAIL = /^[^\s@<>,;]+@[^\s@<>,;]+\.[^\s@<>,;]{2,}$/
|
||||
|
||||
export type InviteCandidate = { email: string; valid: boolean }
|
||||
|
||||
export function isInviteEmail(value: string): boolean {
|
||||
return EMAIL.test(value)
|
||||
}
|
||||
|
||||
/** Splits on commas, semicolons and whitespace; keeps the address inside angle brackets. */
|
||||
export function splitInviteText(text: string): string[] {
|
||||
const out: string[] = []
|
||||
// "Ada Lovelace <ada@x.io>" → keep just the bracketed address so the name doesn't split into junk.
|
||||
const withoutNames = text.replace(/[^,;\n<>]*<([^<>]+)>/g, ' $1 ')
|
||||
for (const raw of withoutNames.split(/[\s,;]+/)) {
|
||||
const token = raw
|
||||
.trim()
|
||||
.replace(/^mailto:/i, '')
|
||||
.replace(/^["'(]+|["').]+$/g, '')
|
||||
if (token) {
|
||||
out.push(token)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Adds tokens to an existing list, dropping case-insensitive duplicates and anything past the cap. */
|
||||
export function mergeInviteCandidates(
|
||||
existing: readonly InviteCandidate[],
|
||||
tokens: readonly string[]
|
||||
): InviteCandidate[] {
|
||||
const seen = new Set(existing.map((candidate) => candidate.email.toLowerCase()))
|
||||
const next = [...existing]
|
||||
for (const token of tokens) {
|
||||
const key = token.toLowerCase()
|
||||
if (seen.has(key) || next.length >= MAX_INVITES_PER_BATCH) {
|
||||
continue
|
||||
}
|
||||
seen.add(key)
|
||||
next.push({ email: token, valid: isInviteEmail(token) })
|
||||
}
|
||||
return next
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
// Team page copy that more than one component needs.
|
||||
import type { OrcaProfileOrgCreateResult } from '../../../../../shared/orca-org-management'
|
||||
import type { Translate } from '@/i18n/use-translate'
|
||||
import type {
|
||||
OrcaOrgRole,
|
||||
OrcaProfileOrgMemberMutationResult
|
||||
} from '../../../../../shared/orca-profiles'
|
||||
|
||||
// i18next plurals (`_one` / `_other` in the catalogs), never ternaries.
|
||||
export function seatCountLabel(count: number, t: Translate): string {
|
||||
return t('auto.components.billing.team.seatCount', '{{count}} seats', {
|
||||
count,
|
||||
defaultValue_one: '{{count}} seat'
|
||||
})
|
||||
}
|
||||
|
||||
export function memberCountLabel(count: number, t: Translate): string {
|
||||
return t('auto.components.billing.team.memberCount', '{{count}} members', {
|
||||
count,
|
||||
defaultValue_one: '{{count}} member'
|
||||
})
|
||||
}
|
||||
|
||||
/** "Invited 2 days ago as an admin": one key per role, so no lowercased labels in sentences. */
|
||||
export function invitedAsCopy(role: OrcaOrgRole, when: string, t: Translate): string {
|
||||
switch (role) {
|
||||
case 'owner':
|
||||
return t('auto.components.billing.team.invitedAsOwner', 'Invited {{value0}} as an owner', {
|
||||
value0: when
|
||||
})
|
||||
case 'admin':
|
||||
return t('auto.components.billing.team.invitedAsAdmin', 'Invited {{value0}} as an admin', {
|
||||
value0: when
|
||||
})
|
||||
case 'member':
|
||||
return t('auto.components.billing.team.invitedAsMember', 'Invited {{value0}} as a member', {
|
||||
value0: when
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function roleChangedCopy(name: string, role: OrcaOrgRole, t: Translate): string {
|
||||
switch (role) {
|
||||
case 'owner':
|
||||
return t('auto.components.billing.team.nowOwner', '{{value0}} is now an owner', {
|
||||
value0: name
|
||||
})
|
||||
case 'admin':
|
||||
return t('auto.components.billing.team.nowAdmin', '{{value0}} is now an admin', {
|
||||
value0: name
|
||||
})
|
||||
case 'member':
|
||||
return t('auto.components.billing.team.nowMember', '{{value0}} is now a member', {
|
||||
value0: name
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function roleDescription(role: OrcaOrgRole, t: Translate): string {
|
||||
switch (role) {
|
||||
case 'owner':
|
||||
return t(
|
||||
'auto.components.billing.team.roleOwnerHint',
|
||||
'Everything, including billing and other owners'
|
||||
)
|
||||
case 'admin':
|
||||
return t('auto.components.billing.team.roleAdminHint', 'Manages members and billing')
|
||||
case 'member':
|
||||
return t('auto.components.billing.team.roleMemberHint', 'Uses Orca Cloud with the team')
|
||||
}
|
||||
}
|
||||
|
||||
/** Status of a roster entry: signed in, invited (email sent), or added but never signed in. */
|
||||
export type TeamMemberStatus = 'active' | 'invited' | 'pending'
|
||||
|
||||
export function memberStatusLabel(status: TeamMemberStatus, t: Translate): string {
|
||||
switch (status) {
|
||||
case 'active':
|
||||
return t('auto.components.billing.team.statusActive', 'Active')
|
||||
case 'invited':
|
||||
return t('auto.components.billing.team.statusInvited', 'Invited')
|
||||
case 'pending':
|
||||
return t('auto.components.billing.team.statusPending', 'Pending sign-in')
|
||||
}
|
||||
}
|
||||
|
||||
export function mutationFailureCopy(
|
||||
result: OrcaProfileOrgMemberMutationResult,
|
||||
t: Translate
|
||||
): string | null {
|
||||
switch (result.status) {
|
||||
case 'ok':
|
||||
return null
|
||||
case 'conflict':
|
||||
return result.reason === 'already_member'
|
||||
? t('auto.components.billing.team.alreadyMember', 'That person is already a member.')
|
||||
: t('auto.components.billing.team.alreadyInvited', 'That person already has an invite.')
|
||||
case 'invalid':
|
||||
switch (result.reason) {
|
||||
case 'cannot_remove_self':
|
||||
return t(
|
||||
'auto.components.billing.team.cannotRemoveSelf',
|
||||
'Use Leave team to remove yourself.'
|
||||
)
|
||||
case 'last_owner':
|
||||
return t(
|
||||
'auto.components.billing.team.lastOwner',
|
||||
'Make someone else an owner before you leave.'
|
||||
)
|
||||
case 'cannot_change_own_role':
|
||||
return t(
|
||||
'auto.components.billing.team.cannotChangeOwnRole',
|
||||
'Another owner has to change your role.'
|
||||
)
|
||||
}
|
||||
return null
|
||||
case 'forbidden':
|
||||
return t(
|
||||
'auto.components.billing.team.forbidden',
|
||||
'Only owners and admins can manage members, and only owners can manage owners.'
|
||||
)
|
||||
case 'not-found':
|
||||
return t('auto.components.billing.team.notFound', 'That member or invite no longer exists.')
|
||||
case 'unsupported':
|
||||
return t(
|
||||
'auto.components.billing.team.unsupported2',
|
||||
'This isn’t available yet. Ask an owner or admin to do it for you.'
|
||||
)
|
||||
case 'rate-limited':
|
||||
return t(
|
||||
'auto.components.billing.team.rateLimited',
|
||||
'Too many team changes at once. Wait a minute and try again.'
|
||||
)
|
||||
case 'reconnect-required':
|
||||
return t(
|
||||
'auto.components.billing.openSignedOut2',
|
||||
'Sign in to Orca again to manage your team.'
|
||||
)
|
||||
case 'unconfigured':
|
||||
return t('auto.components.billing.openUnconfigured', 'Billing is unavailable in this build.')
|
||||
case 'failed':
|
||||
return t('auto.components.billing.team.failed', 'Could not update the team. Try again.')
|
||||
}
|
||||
}
|
||||
|
||||
export function createTeamFailureCopy(
|
||||
result: OrcaProfileOrgCreateResult,
|
||||
t: Translate
|
||||
): string | null {
|
||||
switch (result.status) {
|
||||
case 'created':
|
||||
return null
|
||||
case 'invalid':
|
||||
return t(
|
||||
'auto.components.billing.team.createInvalid2',
|
||||
'Use letters, numbers, spaces or underscores (up to 64).'
|
||||
)
|
||||
case 'name-taken':
|
||||
return t('auto.components.billing.team.nameTaken', 'That team name is taken. Try another.')
|
||||
case 'unsupported':
|
||||
return t(
|
||||
'auto.components.billing.team.createUnavailable',
|
||||
'Team creation isn’t available yet. Ask a teammate to invite you.'
|
||||
)
|
||||
case 'rate-limited':
|
||||
return t(
|
||||
'auto.components.billing.team.rateLimited',
|
||||
'Too many team changes at once. Wait a minute and try again.'
|
||||
)
|
||||
case 'reconnect-required':
|
||||
return t(
|
||||
'auto.components.billing.openSignedOut2',
|
||||
'Sign in to Orca again to manage your team.'
|
||||
)
|
||||
case 'unconfigured':
|
||||
return t('auto.components.billing.openUnconfigured', 'Billing is unavailable in this build.')
|
||||
case 'failed':
|
||||
return t('auto.components.billing.team.createFailed', 'Could not create the team. Try again.')
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user