Separate billing buckets (#57)

* refactor: move DataForSEO response cache from KV to R2 (#46)

* refactor: move lighthouse audits to dataforseo (#43)

* refactor: move lighthouse audits to dataforseo

* chore: remove obsolete audit settings modal

* refactor: rename psi flows to lighthouse

* save

* refactor: simplify audit lighthouse storage flow

* fix: separate lighthouse metrics from actionable audits

* refactor: remove redundant audit project inputs

* feat: redesign lighthouse issues screen with score gauges and table layout

Replace flat score cards with circular SVG gauges, condense metrics into
a compact grid, and switch issue list from cards to an expandable table
with fixed column widths.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test: harden lighthouse regression coverage

* fix: restore project-scoped audit inputs

* refactor: simplify lighthouse payload handling

* refactor: inline lighthouse server handlers

* refactor: share audit workflow types

* refactor: simplify lighthouse payload flows

* save

* refactor: drop project pagespeed api key

* fix: restore lighthouse issues loading with resilient project context

* fix: restore audit issues back navigation

* refactor: simplify project context and lighthouse error handling

* fix: tolerate DataForSEO lighthouse payload drift

* refactor: route audit lighthouse through dataforseo client

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: move DataForSEO response cache from KV to R2

KV TTL-based expiry is imprecise for cache freshness. Switch to R2 with
soft TTL via custom metadata (expiresAt) and a 7-day lifecycle rule for
cleanup. Cache objects live under the `dataforseo-cache/` prefix,
separate from durable audit payloads in `site-audit/`.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: use Workers crypto for R2 cache keys

Keep the cache helper aligned with the Cloudflare runtime and avoid pulling Worker bindings into Vitest. Also clarify that R2 lifecycle cleanup is optional but recommended to control storage growth.

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: move hosted billing to Autumn hooks (#48)

* refactor: move lighthouse audits to dataforseo (#43)

* refactor: move lighthouse audits to dataforseo

* chore: remove obsolete audit settings modal

* refactor: rename psi flows to lighthouse

* save

* refactor: simplify audit lighthouse storage flow

* fix: separate lighthouse metrics from actionable audits

* refactor: remove redundant audit project inputs

* feat: redesign lighthouse issues screen with score gauges and table layout

Replace flat score cards with circular SVG gauges, condense metrics into
a compact grid, and switch issue list from cards to an expandable table
with fixed column widths.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test: harden lighthouse regression coverage

* fix: restore project-scoped audit inputs

* refactor: simplify lighthouse payload handling

* refactor: inline lighthouse server handlers

* refactor: share audit workflow types

* refactor: simplify lighthouse payload flows

* save

* refactor: drop project pagespeed api key

* fix: restore lighthouse issues loading with resilient project context

* fix: restore audit issues back navigation

* refactor: simplify project context and lighthouse error handling

* fix: tolerate DataForSEO lighthouse payload drift

* refactor: route audit lighthouse through dataforseo client

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: move hosted billing to Autumn hooks

* fix: satisfy ci checks for hosted billing

* refactor: simplify hosted Autumn billing integration

Limit Autumn wiring to the billing route and remove billing-specific indirection so the hosted billing flow is easier to reason about. Stop sending organization IDs as fake customer names to keep customer identity data honest.

* fix: satisfy ci line-limit check for hosted billing

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: split SEO credits into monthly included and top-up pools

Replaces the single usage_credits balance with two separate pools:
- usage_credits: monthly grant from base-plan, resets each cycle
- topup_credits: one-off purchases from credit-top-up, never expire

Usage now deducts from monthly credits first, then falls back to
top-ups. The billing UI shows both balances separately with a reset
date on the monthly card. Requires Autumn dashboard changes to create
the topup_credits credit system and update the credit-top-up plan.

* formt

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ben Senescu 2026-04-02 00:24:37 -04:00 committed by Ben Senescu
parent add176c3cc
commit d4aacb13be
7 changed files with 438 additions and 54 deletions

View File

@ -17,8 +17,8 @@ export function BillingHeader(args: {
</h1> </h1>
<p className="max-w-2xl text-base-content/70"> <p className="max-w-2xl text-base-content/70">
{args.hasManagedServiceAccess {args.hasManagedServiceAccess
? `OpenSEO hosted usage is metered against your shared backlinks balance. ${args.basePlanName} includes ${args.includedCreditsLabel} of usage credits each cycle, and extra top-ups carry forward.` ? `${args.basePlanName} includes ${args.includedCreditsLabel} of usage credits each month. Monthly credits are used first; purchased top-ups never expire.`
: `You need an active ${args.basePlanName} subscription to use OpenSEO's managed service. It includes ${args.includedCreditsLabel} of usage credits each cycle, and you can buy more at any time.`} : `You need an active ${args.basePlanName} subscription to use OpenSEO's managed service. It includes ${args.includedCreditsLabel} of usage credits each month, and you can buy more at any time.`}
</p> </p>
</div> </div>
); );
@ -38,7 +38,7 @@ export function SubscriptionIntro(args: {
<p className="text-sm text-base-content/65"> <p className="text-sm text-base-content/65">
{args.hasManagedServiceAccess {args.hasManagedServiceAccess
? "Hosted workspaces need an active paid plan before project pages and DataForSEO-backed features are available." ? "Hosted workspaces need an active paid plan before project pages and DataForSEO-backed features are available."
: `Start ${args.basePlanName} to unlock OpenSEO's managed service and your included monthly usage credits.`} : `Start ${args.basePlanName} to unlock OpenSEO's managed service and your included monthly credits.`}
</p> </p>
</div> </div>
); );

View File

@ -14,10 +14,12 @@ import {
AUTUMN_SEO_DATA_BALANCE_FEATURE_ID, AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
AUTUMN_SEO_DATA_CREDITS_PER_USD, AUTUMN_SEO_DATA_CREDITS_PER_USD,
AUTUMN_SEO_DATA_TOP_UP_PLAN_ID, AUTUMN_SEO_DATA_TOP_UP_PLAN_ID,
AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
} from "@/shared/billing"; } from "@/shared/billing";
import { import {
formatCreditAmount, formatCreditAmount,
formatPlanPrice, formatPlanPrice,
formatResetDate,
getIncludedFeatureQuantity, getIncludedFeatureQuantity,
parseTopUpAmount, parseTopUpAmount,
} from "@/client/features/billing/HostedBillingContentUtils"; } from "@/client/features/billing/HostedBillingContentUtils";
@ -55,8 +57,10 @@ export function HostedBillingContent({
const customer = customerQuery.data; const customer = customerQuery.data;
const basePlan = const basePlan =
plans.find((plan) => plan.id === AUTUMN_PAID_PLAN_ID) ?? null; plans.find((plan) => plan.id === AUTUMN_PAID_PLAN_ID) ?? null;
const balance = const monthlyBalance =
customer?.balances?.[AUTUMN_SEO_DATA_BALANCE_FEATURE_ID] ?? null; customer?.balances?.[AUTUMN_SEO_DATA_BALANCE_FEATURE_ID] ?? null;
const topupBalance =
customer?.balances?.[AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID] ?? null;
const hasManagedServiceAccess = Boolean( const hasManagedServiceAccess = Boolean(
customer?.flags?.[AUTUMN_MANAGED_SERVICE_ACCESS_FEATURE_ID], customer?.flags?.[AUTUMN_MANAGED_SERVICE_ACCESS_FEATURE_ID],
); );
@ -136,7 +140,8 @@ export function HostedBillingContent({
/> />
<SeoDataCreditsSection <SeoDataCreditsSection
balance={balance} monthlyBalance={monthlyBalance}
topupBalance={topupBalance}
basePlanName={basePlanName} basePlanName={basePlanName}
hasManagedServiceAccess={hasManagedServiceAccess} hasManagedServiceAccess={hasManagedServiceAccess}
isTopUpPending={pendingAction === "top-up"} isTopUpPending={pendingAction === "top-up"}
@ -153,7 +158,7 @@ export function HostedBillingContent({
successUrl: window.location.href, successUrl: window.location.href,
featureQuantities: [ featureQuantities: [
{ {
featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID, featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
quantity: Math.round( quantity: Math.round(
parsedTopUpAmount * AUTUMN_SEO_DATA_CREDITS_PER_USD, parsedTopUpAmount * AUTUMN_SEO_DATA_CREDITS_PER_USD,
), ),
@ -236,12 +241,16 @@ function SubscriptionSection(args: {
); );
} }
function SeoDataCreditsSection(args: { type CreditBalance = {
balance: {
granted: number; granted: number;
remaining: number; remaining: number;
usage: number; usage: number;
nextResetAt?: number | null;
} | null; } | null;
function SeoDataCreditsSection(args: {
monthlyBalance: CreditBalance;
topupBalance: CreditBalance;
basePlanName: string; basePlanName: string;
hasManagedServiceAccess: boolean; hasManagedServiceAccess: boolean;
isTopUpPending: boolean; isTopUpPending: boolean;
@ -250,6 +259,9 @@ function SeoDataCreditsSection(args: {
onTopUp: () => void; onTopUp: () => void;
onTopUpAmountChange: (value: string) => void; onTopUpAmountChange: (value: string) => void;
}) { }) {
const totalRemaining =
(args.monthlyBalance?.remaining ?? 0) + (args.topupBalance?.remaining ?? 0);
return ( return (
<section className="card border border-base-300 bg-base-100 shadow-sm"> <section className="card border border-base-300 bg-base-100 shadow-sm">
<div className="card-body gap-4"> <div className="card-body gap-4">
@ -258,22 +270,36 @@ function SeoDataCreditsSection(args: {
SEO data credits SEO data credits
</h2> </h2>
<p className="mt-1 text-sm text-base-content/70"> <p className="mt-1 text-sm text-base-content/70">
Buy extra usage credits for DataForSEO-powered features like Monthly credits are used first. Purchased top-ups never expire.
backlinks.
</p> </p>
</div> </div>
<div className="rounded-box border border-base-300 bg-base-200/60 p-4"> <div className="rounded-box border border-base-300 bg-base-200/60 p-4">
<div className="flex items-baseline justify-between gap-3"> <div className="flex items-baseline justify-between gap-3">
<span className="text-sm text-base-content/70">Remaining</span> <span className="text-sm text-base-content/70">
Total remaining
</span>
<span className="text-2xl font-semibold text-base-content"> <span className="text-2xl font-semibold text-base-content">
{formatCreditAmount(args.balance?.remaining ?? 0)} {formatCreditAmount(totalRemaining)}
</span> </span>
</div> </div>
<div className="mt-3 grid gap-2 text-sm text-base-content/70 sm:grid-cols-2">
<CreditStat label="Granted" value={args.balance?.granted ?? 0} />
<CreditStat label="Used" value={args.balance?.usage ?? 0} />
</div> </div>
<div className="grid gap-3 sm:grid-cols-2">
<CreditPoolCard
title="Monthly included"
badge={formatResetDate(args.monthlyBalance?.nextResetAt ?? null)}
remaining={args.monthlyBalance?.remaining ?? 0}
granted={args.monthlyBalance?.granted ?? 0}
usage={args.monthlyBalance?.usage ?? 0}
/>
<CreditPoolCard
title="Purchased top-ups"
badge="Never expires"
remaining={args.topupBalance?.remaining ?? 0}
granted={args.topupBalance?.granted ?? 0}
usage={args.topupBalance?.usage ?? 0}
/>
</div> </div>
<label className="form-control gap-2"> <label className="form-control gap-2">
@ -314,22 +340,49 @@ function SeoDataCreditsSection(args: {
<p className="text-xs leading-relaxed text-base-content/60"> <p className="text-xs leading-relaxed text-base-content/60">
Credit purchases use our hosted checkout flow and apply to your Credit purchases use our hosted checkout flow and apply to your
organization balance. organization's top-up balance.
</p> </p>
</div> </div>
</section> </section>
); );
} }
function CreditStat({ label, value }: { label: string; value: number }) { function CreditPoolCard(args: {
title: string;
badge: string | null;
remaining: number;
granted: number;
usage: number;
}) {
return ( return (
<div className="rounded-md bg-base-100 px-3 py-2"> <div className="rounded-box border border-base-300 bg-base-200/40 p-3">
<span className="block text-xs uppercase tracking-wide text-base-content/50"> <div className="flex items-center justify-between gap-2">
{label} <span className="text-sm font-medium text-base-content">
{args.title}
</span> </span>
<span className="font-medium text-base-content"> {args.badge ? (
{formatCreditAmount(value)} <span className="badge badge-sm badge-ghost text-base-content/60">
{args.badge}
</span> </span>
) : null}
</div>
<div className="mt-2 text-xl font-semibold text-base-content">
{formatCreditAmount(args.remaining)}
</div>
<div className="mt-2 grid grid-cols-2 gap-2 text-xs text-base-content/60">
<div>
<span className="block uppercase tracking-wide">Granted</span>
<span className="font-medium text-base-content/80">
{formatCreditAmount(args.granted)}
</span>
</div>
<div>
<span className="block uppercase tracking-wide">Used</span>
<span className="font-medium text-base-content/80">
{formatCreditAmount(args.usage)}
</span>
</div>
</div>
</div> </div>
); );
} }

View File

@ -0,0 +1,46 @@
import { describe, expect, it } from "vitest";
import {
formatCreditAmount,
formatResetDate,
parseTopUpAmount,
} from "./HostedBillingContentUtils";
describe("formatResetDate", () => {
it("formats a valid Unix timestamp in ms", () => {
const date = new Date(2026, 3, 15); // April 15, local time
const result = formatResetDate(date.getTime());
expect(result).toBe("Resets Apr 15");
});
it("returns null for null input", () => {
expect(formatResetDate(null)).toBeNull();
});
});
describe("parseTopUpAmount", () => {
it("accepts valid whole-dollar amounts", () => {
expect(parseTopUpAmount("20")).toEqual({ isValid: true, parsed: 20 });
expect(parseTopUpAmount("10")).toEqual({ isValid: true, parsed: 10 });
expect(parseTopUpAmount("99")).toEqual({ isValid: true, parsed: 99 });
});
it("rejects amounts below minimum", () => {
expect(parseTopUpAmount("9")).toEqual({ isValid: false, parsed: 20 });
});
it("rejects amounts above maximum", () => {
expect(parseTopUpAmount("100")).toEqual({ isValid: false, parsed: 20 });
});
it("rejects non-numeric input", () => {
expect(parseTopUpAmount("abc")).toEqual({ isValid: false, parsed: 20 });
});
});
describe("formatCreditAmount", () => {
it("converts credits to formatted USD", () => {
expect(formatCreditAmount(5000)).toBe("$5.00");
expect(formatCreditAmount(1000)).toBe("$1.00");
expect(formatCreditAmount(0)).toBe("$0.00");
});
});

View File

@ -43,6 +43,15 @@ export function formatPlanPrice(
return `${formatUsd(amount, amount % 1 === 0 ? 0 : 2)}/${intervalToLabel(interval)}`; return `${formatUsd(amount, amount % 1 === 0 ? 0 : 2)}/${intervalToLabel(interval)}`;
} }
export function formatResetDate(timestampMs: number | null): string | null {
if (timestampMs == null) return null;
const date = new Date(timestampMs);
if (Number.isNaN(date.getTime())) return null;
return `Resets ${date.toLocaleDateString("en-US", { month: "short", day: "numeric" })}`;
}
function formatUsd(value: number, minimumFractionDigits = 2) { function formatUsd(value: number, minimumFractionDigits = 2) {
return new Intl.NumberFormat("en-US", { return new Intl.NumberFormat("en-US", {
style: "currency", style: "currency",

View File

@ -0,0 +1,240 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
} from "@/shared/billing";
const { checkMock, trackMock, getOrCreateMock, isHostedServerAuthModeMock } =
vi.hoisted(() => ({
checkMock: vi.fn(),
trackMock: vi.fn(),
getOrCreateMock: vi.fn(),
isHostedServerAuthModeMock: vi.fn(),
}));
vi.mock("@/server/billing/autumn", () => ({
autumn: {
check: checkMock,
track: trackMock,
},
}));
vi.mock("@/server/billing/subscription", () => ({
getOrCreateOrganizationCustomer: getOrCreateMock,
}));
vi.mock("@/server/lib/runtime-env", () => ({
isHostedServerAuthMode: isHostedServerAuthModeMock,
}));
vi.mock("@/server/lib/dataforseo", () => ({
fetchKeywordIdeasRaw: vi.fn(),
fetchKeywordSuggestionsRaw: vi.fn(),
fetchRelatedKeywordsRaw: vi.fn(),
fetchDomainRankOverviewRaw: vi.fn(),
fetchRankedKeywordsRaw: vi.fn(),
fetchLiveSerpItemsRaw: vi.fn(),
}));
vi.mock("@/server/lib/dataforseoLighthouse", () => ({
fetchDataforseoLighthouseResultRaw: vi.fn(),
}));
vi.mock("@/server/lib/dataforseoBacklinks", () => ({
fetchBacklinksRowsRaw: vi.fn(),
fetchBacklinksSummaryRaw: vi.fn(),
fetchDomainPagesSummaryRaw: vi.fn(),
fetchNewLostTimeseriesRaw: vi.fn(),
fetchReferringDomainsRaw: vi.fn(),
fetchTimeseriesSummaryRaw: vi.fn(),
}));
import { createDataforseoClient } from "./dataforseoClient";
import { fetchBacklinksSummaryRaw } from "./dataforseoBacklinks";
const billingCustomer = {
organizationId: "org_123",
userEmail: "alice@example.com",
};
const backlinksInput = {
target: "example.com",
includeSubdomains: true,
includeIndirectLinks: true,
excludeInternalBacklinks: true,
status: "live" as const,
};
function setupHostedMode() {
isHostedServerAuthModeMock.mockResolvedValue(true);
getOrCreateMock.mockResolvedValue({ id: "org_123" });
}
function mockBalances(monthly: number, topup: number) {
checkMock.mockImplementation(async (args: { featureId: string }) => {
if (args.featureId === AUTUMN_SEO_DATA_BALANCE_FEATURE_ID) {
return { allowed: true, balance: { remaining: monthly } };
}
if (args.featureId === AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID) {
return { allowed: true, balance: { remaining: topup } };
}
return { allowed: false, balance: null };
});
}
function mockDataforseoResult(costUsd: number) {
vi.mocked(fetchBacklinksSummaryRaw).mockResolvedValue({
data: { rank: 42 },
billing: { costUsd, path: ["backlinks", "summary"], resultCount: 1 },
});
}
describe("meterDataforseoCall with split balances", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("skips billing in non-hosted mode", async () => {
isHostedServerAuthModeMock.mockResolvedValue(false);
mockDataforseoResult(0.05);
const client = createDataforseoClient(billingCustomer);
const result = await client.backlinks.summary(backlinksInput);
expect(result).toEqual({ rank: 42 });
expect(checkMock).not.toHaveBeenCalled();
expect(trackMock).not.toHaveBeenCalled();
});
it("checks both monthly and topup balances in parallel", async () => {
setupHostedMode();
mockBalances(5000, 3000);
mockDataforseoResult(0.05);
const client = createDataforseoClient(billingCustomer);
await client.backlinks.summary(backlinksInput);
expect(checkMock).toHaveBeenCalledTimes(2);
expect(checkMock).toHaveBeenCalledWith({
customerId: "org_123",
featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
});
expect(checkMock).toHaveBeenCalledWith({
customerId: "org_123",
featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
});
});
it("deducts entirely from monthly when monthly has enough", async () => {
setupHostedMode();
mockBalances(5000, 3000);
mockDataforseoResult(0.05);
const client = createDataforseoClient(billingCustomer);
await client.backlinks.summary(backlinksInput);
expect(trackMock).toHaveBeenCalledTimes(1);
expect(trackMock).toHaveBeenCalledWith(
expect.objectContaining({
customerId: "org_123",
featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
value: 50,
}),
);
});
it("deducts entirely from topup when monthly is empty", async () => {
setupHostedMode();
mockBalances(0, 5000);
mockDataforseoResult(0.05);
const client = createDataforseoClient(billingCustomer);
await client.backlinks.summary(backlinksInput);
expect(trackMock).toHaveBeenCalledTimes(1);
expect(trackMock).toHaveBeenCalledWith(
expect.objectContaining({
customerId: "org_123",
featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
value: 50,
}),
);
});
it("splits deduction across monthly and topup when monthly is partially sufficient", async () => {
setupHostedMode();
mockBalances(30, 5000);
mockDataforseoResult(0.05);
const client = createDataforseoClient(billingCustomer);
await client.backlinks.summary(backlinksInput);
expect(trackMock).toHaveBeenCalledTimes(2);
expect(trackMock).toHaveBeenCalledWith(
expect.objectContaining({
customerId: "org_123",
featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
value: 30,
}),
);
expect(trackMock).toHaveBeenCalledWith(
expect.objectContaining({
customerId: "org_123",
featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
value: 20,
}),
);
});
it("throws PAYMENT_REQUIRED when combined balance is below minimum", async () => {
setupHostedMode();
// minimum is 150 credits (0.15 USD * 1000); 50 + 50 = 100 < 150
mockBalances(50, 50);
const client = createDataforseoClient(billingCustomer);
await expect(
client.backlinks.summary(backlinksInput),
).rejects.toMatchObject({ code: "PAYMENT_REQUIRED" });
expect(trackMock).not.toHaveBeenCalled();
});
it("throws PAYMENT_REQUIRED when both balances are zero", async () => {
setupHostedMode();
mockBalances(0, 0);
const client = createDataforseoClient(billingCustomer);
await expect(
client.backlinks.summary(backlinksInput),
).rejects.toMatchObject({ code: "PAYMENT_REQUIRED" });
});
it("includes balanceFeatureId in track properties", async () => {
setupHostedMode();
mockBalances(30, 5000);
mockDataforseoResult(0.05);
const client = createDataforseoClient(billingCustomer);
await client.backlinks.summary(backlinksInput);
const monthlyCall = trackMock.mock.calls.find(
(call: unknown[]) =>
(call[0] as { featureId: string }).featureId ===
AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
);
const topupCall = trackMock.mock.calls.find(
(call: unknown[]) =>
(call[0] as { featureId: string }).featureId ===
AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
);
expect(
(monthlyCall?.[0] as { properties: { balanceFeatureId: string } })
.properties.balanceFeatureId,
).toBe(AUTUMN_SEO_DATA_BALANCE_FEATURE_ID);
expect(
(topupCall?.[0] as { properties: { balanceFeatureId: string } })
.properties.balanceFeatureId,
).toBe(AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID);
});
});

View File

@ -1,8 +1,8 @@
import { MINIMUM_SEO_DATA_BALANCE_USD } from "@/shared/billing";
import { import {
AUTUMN_SEO_DATA_BALANCE_FEATURE_ID, AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
AUTUMN_SEO_DATA_CREDITS_PER_USD, AUTUMN_SEO_DATA_CREDITS_PER_USD,
AUTUMN_SEO_DATA_USAGE_FEATURE_ID, AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
MINIMUM_SEO_DATA_BALANCE_USD,
roundUsdForBilling, roundUsdForBilling,
} from "@/shared/billing"; } from "@/shared/billing";
import { autumn } from "@/server/billing/autumn"; import { autumn } from "@/server/billing/autumn";
@ -192,7 +192,7 @@ async function meterDataforseoCall<T>(
const billingCustomer = await getOrCreateOrganizationCustomer(customer); const billingCustomer = await getOrCreateOrganizationCustomer(customer);
await assertSeoDataBalanceAvailable({ const { monthlyRemaining } = await assertSeoDataBalanceAvailable({
customerId: billingCustomer.id, customerId: billingCustomer.id,
minimumBalanceUsd: MINIMUM_SEO_DATA_BALANCE_USD, minimumBalanceUsd: MINIMUM_SEO_DATA_BALANCE_USD,
}); });
@ -202,6 +202,7 @@ async function meterDataforseoCall<T>(
await trackDataforseoCost({ await trackDataforseoCost({
customerId: billingCustomer.id, customerId: billingCustomer.id,
billing: result.billing, billing: result.billing,
monthlyRemaining,
}); });
return result.data; return result.data;
@ -211,43 +212,77 @@ async function assertSeoDataBalanceAvailable(args: {
customerId: string; customerId: string;
minimumBalanceUsd: number; minimumBalanceUsd: number;
}) { }) {
const result = await autumn.check({ const minimumCredits = Math.ceil(
customerId: args.customerId,
featureId: AUTUMN_SEO_DATA_USAGE_FEATURE_ID,
requiredBalance: Math.ceil(
roundUsdForBilling(args.minimumBalanceUsd) * roundUsdForBilling(args.minimumBalanceUsd) *
AUTUMN_SEO_DATA_CREDITS_PER_USD, AUTUMN_SEO_DATA_CREDITS_PER_USD,
), );
});
if (!result.allowed) { const [monthlyCheck, topupCheck] = await Promise.all([
autumn.check({
customerId: args.customerId,
featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
}),
autumn.check({
customerId: args.customerId,
featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
}),
]);
const monthlyRemaining = monthlyCheck.balance?.remaining ?? 0;
const topupRemaining = topupCheck.balance?.remaining ?? 0;
if (monthlyRemaining + topupRemaining < minimumCredits) {
throw new AppError("PAYMENT_REQUIRED"); throw new AppError("PAYMENT_REQUIRED");
} }
return { monthlyRemaining };
} }
async function trackDataforseoCost(args: { async function trackDataforseoCost(args: {
customerId: string; customerId: string;
billing: DataforseoApiCallCost; billing: DataforseoApiCallCost;
monthlyRemaining: number;
}) { }) {
const totalCostUsd = roundUsdForBilling(args.billing.costUsd); const totalCostUsd = roundUsdForBilling(args.billing.costUsd);
const totalCostCredits = Math.ceil( const totalCostCredits = Math.ceil(
totalCostUsd * AUTUMN_SEO_DATA_CREDITS_PER_USD, totalCostUsd * AUTUMN_SEO_DATA_CREDITS_PER_USD,
); );
await autumn.track({ const monthlyDeduct = Math.min(args.monthlyRemaining, totalCostCredits);
customerId: args.customerId, const topupDeduct = totalCostCredits - monthlyDeduct;
featureId: AUTUMN_SEO_DATA_USAGE_FEATURE_ID,
value: totalCostCredits, const properties = {
properties: {
provider: "dataforseo", provider: "dataforseo",
currency: "USD", currency: "USD",
balanceFeatureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
paths: [args.billing.path.join("/")], paths: [args.billing.path.join("/")],
totalCostUsd, totalCostUsd,
totalCostCredits, totalCostCredits,
fromCache: false, fromCache: false,
};
if (monthlyDeduct > 0) {
await autumn.track({
customerId: args.customerId,
featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
value: monthlyDeduct,
properties: {
...properties,
balanceFeatureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
}, },
}); });
} }
if (topupDeduct > 0) {
await autumn.track({
customerId: args.customerId,
featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
value: topupDeduct,
properties: {
...properties,
balanceFeatureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
},
});
}
}
export type { LabsKeywordDataItem, SerpLiveItem }; export type { LabsKeywordDataItem, SerpLiveItem };

View File

@ -5,6 +5,7 @@ export const AUTUMN_SEO_DATA_TOP_UP_PLAN_ID = "credit-top-up";
export const AUTUMN_MANAGED_SERVICE_ACCESS_FEATURE_ID = export const AUTUMN_MANAGED_SERVICE_ACCESS_FEATURE_ID =
"managed_service_access"; "managed_service_access";
export const AUTUMN_SEO_DATA_BALANCE_FEATURE_ID = "usage_credits"; export const AUTUMN_SEO_DATA_BALANCE_FEATURE_ID = "usage_credits";
export const AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID = "topup_credits";
export const AUTUMN_SEO_DATA_USAGE_FEATURE_ID = "seo_data_usage"; export const AUTUMN_SEO_DATA_USAGE_FEATURE_ID = "seo_data_usage";
export const AUTUMN_SEO_DATA_CREDITS_PER_USD = 1000; export const AUTUMN_SEO_DATA_CREDITS_PER_USD = 1000;
export const MINIMUM_SEO_DATA_BALANCE_USD = 0.15; export const MINIMUM_SEO_DATA_BALANCE_USD = 0.15;