Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 152 additions & 0 deletions console-ui/__tests__/billing-enterprise.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";

const enterpriseMock = vi.hoisted(() => ({ response: {} as Record<string, unknown> }));
const aprilFirst = "2026-04-01T00:00:00Z";

vi.mock("@/hooks/useToast", () => ({
useToastStore: () => vi.fn(),
}));

vi.mock("@/hooks/useAuth", () => ({
useAuth: () => ({ email: "[email protected]" }),
}));

vi.mock("@/components/TopBar", () => ({
TopBar: ({ title }: { title?: string }) => <div>{title}</div>,
}));

vi.mock("@/components/UsageChart", () => ({
UsageChart: () => <div data-testid="usage-chart" />,
}));

vi.mock("@/lib/api", async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>;
return {
...actual,
fetchBalance: vi.fn().mockResolvedValue({
balance_micro_usd: 0,
balance_usd: 0,
withdrawable_micro_usd: 0,
withdrawable_usd: 0,
}),
fetchUsage: vi.fn().mockResolvedValue([]),
fetchEnterpriseStatus: vi.fn().mockImplementation(() => Promise.resolve(enterpriseMock.response)),
fetchStripeStatus: vi.fn().mockResolvedValue({ configured: false, has_account: false, status: "" }),
fetchStripeWithdrawals: vi.fn().mockResolvedValue([]),
createStripeCheckout: vi.fn(),
redeemInviteCode: vi.fn(),
};
});

beforeEach(() => {
enterpriseMock.response = {
enabled: true,
credit_remaining_micro_usd: 7_500_000,
account: {
account_id: "acct-ent",
status: "active",
billing_email: "[email protected]",
cadence: "biweekly",
terms_days: 15,
credit_limit_micro_usd: 10_000_000,
accrued_micro_usd: 2_000_000,
reserved_micro_usd: 500_000,
open_invoice_micro_usd: 0,
rounding_carry_micro_usd: 0,
current_period_start: aprilFirst,
next_invoice_at: "2026-04-15T00:00:00Z",
},
recent_invoices: [
{
id: "inv-1",
status: "open",
amount_micro_usd: 3_000_000,
amount_cents: 300,
terms_days: 15,
period_start: "2026-03-15T00:00:00Z",
period_end: aprilFirst,
stripe_hosted_invoice_url: "https://invoice.test/inv-1",
},
],
};
const store = new Map<string, string>();
vi.stubGlobal("localStorage", {
getItem: (k: string) => store.get(k) ?? null,
setItem: (k: string, v: string) => {
store.set(k, v);
},
removeItem: (k: string) => {
store.delete(k);
},
});
});

afterEach(() => {
vi.clearAllMocks();
vi.unstubAllGlobals();
});

describe("Billing Enterprise card", () => {
it("shows cadence, editable terms, remaining credit, and invoice link", async () => {
const BillingContent = (await import("@/app/billing/BillingContent")).default;
render(<BillingContent />);

await waitFor(() => {
expect(screen.getByText("Enterprise Invoicing")).toBeInTheDocument();
});
expect(screen.getByText("Bi-weekly")).toBeInTheDocument();
expect(screen.getByText("Net 15")).toBeInTheDocument();
expect(screen.getByText("$7.50 / $10.00")).toBeInTheDocument();
expect(screen.getByRole("link", { name: /View invoice/i })).toHaveAttribute(
"href",
"https://invoice.test/inv-1",
);
});

it("shows disabled enterprise accounts with invoice history", async () => {
enterpriseMock.response = {
enabled: false,
credit_remaining_micro_usd: 7_000_000,
account: {
account_id: "acct-ent",
status: "disabled",
billing_email: "[email protected]",
stripe_customer_id: "cus_ent",
cadence: "monthly",
terms_days: 30,
credit_limit_micro_usd: 10_000_000,
accrued_micro_usd: 1_000_000,
reserved_micro_usd: 0,
open_invoice_micro_usd: 2_000_000,
rounding_carry_micro_usd: 0,
current_period_start: aprilFirst,
next_invoice_at: "2026-05-01T00:00:00Z",
},
recent_invoices: [
{
id: "inv-disabled",
status: "open",
amount_micro_usd: 2_000_000,
amount_cents: 200,
terms_days: 30,
period_start: "2026-03-01T00:00:00Z",
period_end: aprilFirst,
stripe_hosted_invoice_url: "https://invoice.test/inv-disabled",
},
],
};
const BillingContent = (await import("@/app/billing/BillingContent")).default;
render(<BillingContent />);

await waitFor(() => {
expect(screen.getByText("Enterprise Invoicing")).toBeInTheDocument();
});
expect(screen.getByText("Disabled")).toBeInTheDocument();
expect(screen.getByText("Net 30")).toBeInTheDocument();
expect(screen.getByRole("link", { name: /View invoice/i })).toHaveAttribute(
"href",
"https://invoice.test/inv-disabled",
);
});
});
24 changes: 24 additions & 0 deletions console-ui/src/app/api/payments/enterprise/status/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { NextRequest, NextResponse } from "next/server";

const DEFAULT_COORD = process.env.NEXT_PUBLIC_COORDINATOR_URL || "https://api.darkbloom.dev";

export async function GET(req: NextRequest) {
const coordUrl = DEFAULT_COORD;
const apiKey = req.headers.get("x-api-key") || "";

let authHeader = req.headers.get("authorization") || "";
if (!authHeader && apiKey) authHeader = `Bearer ${apiKey}`;
if (!authHeader) {
const privyToken = req.cookies.get("privy-token")?.value;
if (privyToken) authHeader = `Bearer ${privyToken}`;
}

const res = await fetch(`${coordUrl}/v1/billing/enterprise/status`, {
headers: { ...(authHeader ? { Authorization: authHeader } : {}) },
});
if (!res.ok) {
const text = await res.text();
return NextResponse.json({ error: text }, { status: res.status });
}
return NextResponse.json(await res.json().catch(() => ({})));
}
82 changes: 82 additions & 0 deletions console-ui/src/app/billing/BillingContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import {
fetchBalance,
fetchUsage,
fetchEnterpriseStatus,
createStripeCheckout,
redeemInviteCode,
fetchStripeStatus,
Expand All @@ -16,6 +17,7 @@
computeStripeFeeUsd,
type BalanceResponse,
type UsageEntry,
type EnterpriseStatusResponse,
type StripeStatus,
type StripeWithdrawal,
} from "@/lib/api";
Expand Down Expand Up @@ -68,6 +70,7 @@
const { email } = useAuth();
const [balance, setBalance] = useState<BalanceResponse | null>(null);
const [usage, setUsage] = useState<UsageEntry[]>([]);
const [enterprise, setEnterprise] = useState<EnterpriseStatusResponse | null>(null);
const [loading, setLoading] = useState(true);
const [buyOpen, setBuyOpen] = useState(false);
const [buyAmount, setBuyAmount] = useState("10");
Expand Down Expand Up @@ -98,6 +101,7 @@
]);
setBalance(b);
setUsage(u);
fetchEnterpriseStatus().then(setEnterprise).catch(() => setEnterprise({ enabled: false }));
} catch (e) {
addToast(`Failed to load billing data: ${(e as Error).message}`);
}
Expand Down Expand Up @@ -286,6 +290,10 @@
</div>
</div>

{enterprise?.account && (
<EnterpriseBillingCard enterprise={enterprise} />
)}

{/* Invite Code Redemption */}
<div className="rounded-2xl border border-border-dim bg-bg-white p-6 shadow-md">
<div className="flex items-center gap-2 mb-4">
Expand Down Expand Up @@ -515,7 +523,7 @@
transition-all flex items-center justify-center gap-2"
>
{actionLoading && <Loader2 size={14} className="animate-spin" />}
{actionLoading ? "Redirecting..." : "Continue"}

Check warning on line 526 in console-ui/src/app/billing/BillingContent.tsx

View workflow job for this annotation

GitHub Actions / Console UI Lint & Build

Define a constant instead of duplicating this literal 3 times
</button>
<p className="mt-4 text-xs text-text-tertiary text-center">
Powered by Stripe. Secure card payment.
Expand All @@ -541,9 +549,83 @@
);
}

function EnterpriseBillingCard({ enterprise }: { enterprise: EnterpriseStatusResponse }) {
const account = enterprise.account;
if (!account) return null;
const active = enterprise.enabled;
const committed =
account.open_invoice_micro_usd + account.accrued_micro_usd + account.reserved_micro_usd + (account.rounding_carry_micro_usd ?? 0);
const remaining = enterprise.credit_remaining_micro_usd ?? Math.max(account.credit_limit_micro_usd - committed, 0);
const limitUsd = account.credit_limit_micro_usd / 1_000_000;
const remainingUsd = remaining / 1_000_000;
const periodUsageUsd = (account.accrued_micro_usd + account.reserved_micro_usd + (account.rounding_carry_micro_usd ?? 0)) / 1_000_000;
const cadence = account.cadence === "biweekly" ? "Bi-weekly" : account.cadence[0].toUpperCase() + account.cadence.slice(1);

return (
<div className="rounded-2xl border border-border-dim bg-bg-white p-6 shadow-md">
<div className="flex flex-wrap items-center gap-2 mb-4">
<Building2 size={16} className="text-teal" />
<h3 className="text-sm font-semibold text-text-primary">Enterprise Invoicing</h3>
<span className={`ml-auto text-[10px] font-mono uppercase tracking-widest rounded px-2 py-0.5 ${
active
? "text-teal bg-teal/10 border border-teal/30"
: "text-text-tertiary bg-bg-primary border border-border-dim"
}`}>
{active ? "Active" : "Disabled"}
</span>
</div>
<div className="grid grid-cols-1 sm:grid-cols-4 gap-3 mb-4">
<div className="rounded-lg bg-bg-primary border border-border-dim p-3">
<p className="text-[10px] font-mono uppercase tracking-wider text-text-tertiary mb-1">Cadence</p>
<p className="text-sm font-semibold text-text-primary">{cadence}</p>
</div>
<div className="rounded-lg bg-bg-primary border border-border-dim p-3">
<p className="text-[10px] font-mono uppercase tracking-wider text-text-tertiary mb-1">Terms</p>
<p className="text-sm font-semibold text-text-primary">Net {account.terms_days}</p>
</div>
<div className="rounded-lg bg-bg-primary border border-border-dim p-3">
<p className="text-[10px] font-mono uppercase tracking-wider text-text-tertiary mb-1">Period Usage</p>
<p className="text-sm font-mono font-semibold text-text-primary">${periodUsageUsd.toFixed(2)}</p>
</div>
<div className="rounded-lg bg-bg-primary border border-border-dim p-3">
<p className="text-[10px] font-mono uppercase tracking-wider text-text-tertiary mb-1">Remaining</p>
<p className="text-sm font-mono font-semibold text-text-primary">
${remainingUsd.toFixed(2)} / ${limitUsd.toFixed(2)}
</p>
</div>
</div>
<div className="flex flex-wrap items-center gap-3 text-xs text-text-tertiary font-mono">
<span>Next invoice {new Date(account.next_invoice_at).toLocaleDateString()}</span>
<span>{account.billing_email}</span>
</div>
{(enterprise.recent_invoices?.length ?? 0) > 0 && (
<div className="mt-4 border-t border-border-subtle pt-4 space-y-2">
{enterprise.recent_invoices!.slice(0, 3).map((invoice) => (
<div key={invoice.id} className="flex items-center justify-between gap-3 text-xs">
<span className="font-mono text-text-secondary">
${(invoice.amount_micro_usd / 1_000_000).toFixed(2)} · {invoice.status}
</span>
{invoice.stripe_hosted_invoice_url && (
<a
href={invoice.stripe_hosted_invoice_url}
target="_blank"
rel="noreferrer"
className="font-semibold text-coral hover:underline"
>
View invoice
</a>
)}
</div>
))}
</div>
)}
</div>
);
}

// --- Stripe Payouts components ---

function StripePayoutsCard({

Check warning on line 628 in console-ui/src/app/billing/BillingContent.tsx

View workflow job for this annotation

GitHub Actions / Console UI Lint & Build

Refactor this function to reduce its Cognitive Complexity from 34 to the 15 allowed
status,
withdrawals,
balanceMicroUsd,
Expand Down Expand Up @@ -606,7 +688,7 @@
{onboardLoading ? "Redirecting..." : "Link bank via Stripe"}
</button>
</>
) : ready ? (

Check warning on line 691 in console-ui/src/app/billing/BillingContent.tsx

View workflow job for this annotation

GitHub Actions / Console UI Lint & Build

Extract this nested ternary operation into an independent statement
<>
<div className="rounded-lg bg-bg-primary border border-border-dim p-3 mb-4 flex items-center justify-between">
<div className="flex items-center gap-2 text-sm text-text-secondary">
Expand Down Expand Up @@ -645,7 +727,7 @@
<AlertCircle size={14} className="text-coral mt-0.5 flex-shrink-0" />
{restricted
? "Stripe needs more information to enable payouts on your account."
: rejected

Check warning on line 730 in console-ui/src/app/billing/BillingContent.tsx

View workflow job for this annotation

GitHub Actions / Console UI Lint & Build

Extract this nested ternary operation into an independent statement
? "Stripe has disabled payouts on this account. Contact support."
: "Finish linking your account on Stripe to enable withdrawals."}
</p>
Expand All @@ -656,7 +738,7 @@
className="flex items-center gap-2 px-5 py-2.5 rounded-lg bg-teal border-2 border-ink text-white text-sm font-bold hover:opacity-90 disabled:opacity-50 transition-all"
>
{onboardLoading ? <Loader2 size={14} className="animate-spin" /> : <Building2 size={14} />}
{onboardLoading ? "Redirecting..." : restricted ? "Provide more info" : "Continue setup"}

Check warning on line 741 in console-ui/src/app/billing/BillingContent.tsx

View workflow job for this annotation

GitHub Actions / Console UI Lint & Build

Extract this nested ternary operation into an independent statement
</button>
)}
</>
Expand All @@ -673,7 +755,7 @@
<div className="flex items-center gap-2">
{w.status === "paid" ? (
<Check size={12} className="text-teal" />
) : w.status === "failed" ? (

Check warning on line 758 in console-ui/src/app/billing/BillingContent.tsx

View workflow job for this annotation

GitHub Actions / Console UI Lint & Build

Extract this nested ternary operation into an independent statement
<X size={12} className="text-coral" />
) : (
<Clock size={12} className="text-gold" />
Expand All @@ -687,7 +769,7 @@
</div>
<span className={`text-xs font-mono ${
w.status === "paid" ? "text-teal" :
w.status === "failed" ? "text-coral" :

Check warning on line 772 in console-ui/src/app/billing/BillingContent.tsx

View workflow job for this annotation

GitHub Actions / Console UI Lint & Build

Extract this nested ternary operation into an independent statement
"text-text-tertiary"
}`}>
{w.status}
Expand Down Expand Up @@ -856,7 +938,7 @@
className={`flex items-center justify-between gap-3 px-3 py-3 rounded-lg border-2 transition-all text-left ${
selected
? "bg-teal/10 border-teal text-teal"
: disabled

Check warning on line 941 in console-ui/src/app/billing/BillingContent.tsx

View workflow job for this annotation

GitHub Actions / Console UI Lint & Build

Extract this nested ternary operation into an independent statement
? "bg-bg-primary border-border-dim text-text-tertiary cursor-not-allowed opacity-60"
: "bg-bg-primary border-border-dim text-text-secondary hover:border-teal/30 hover:text-teal"
}`}
Expand Down
43 changes: 43 additions & 0 deletions console-ui/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,49 @@ export async function fetchUsage(): Promise<UsageEntry[]> {
return data.usage || data;
}

export interface EnterpriseAccount {
account_id: string;
status: "active" | "disabled";
billing_email: string;
stripe_customer_id?: string;
cadence: "weekly" | "biweekly" | "monthly";
terms_days: number;
credit_limit_micro_usd: number;
accrued_micro_usd: number;
reserved_micro_usd: number;
open_invoice_micro_usd: number;
rounding_carry_micro_usd?: number;
current_period_start: string;
next_invoice_at: string;
}

export interface EnterpriseInvoice {
id: string;
status: string;
amount_micro_usd: number;
amount_cents: number;
terms_days: number;
period_start: string;
period_end: string;
due_at?: string;
paid_at?: string;
stripe_hosted_invoice_url?: string;
stripe_invoice_pdf?: string;
}

export interface EnterpriseStatusResponse {
enabled: boolean;
account?: EnterpriseAccount;
recent_invoices?: EnterpriseInvoice[];
credit_remaining_micro_usd?: number;
}

export async function fetchEnterpriseStatus(): Promise<EnterpriseStatusResponse> {
const res = await fetch("/api/payments/enterprise/status", { headers: proxyHeaders() });
if (!res.ok) throw new Error(`Failed to fetch enterprise status: ${res.status}`);
return res.json();
}

export interface StripeCheckoutResponse {
url: string;
session_id: string;
Expand Down
6 changes: 6 additions & 0 deletions coordinator/cmd/coordinator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,12 @@ func main() {
// Start background eviction of stale providers.
reg.StartEvictionLoop(ctx, 90*time.Second)

// Generate due Enterprise invoices in the background when Stripe is
// configured. Manual admin runs use the same code path.
saferun.Go(logger, "enterprise_invoice_runner", func() {
srv.StartEnterpriseInvoiceLoop(ctx, time.Hour)
})

// Push gauge values to DogStatsD periodically.
go srv.StartDDGaugeLoop(ctx)

Expand Down
Loading
Loading