Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. πŸ”₯

fix(billing): scope historical credit/token usage to the team (#3829)

firecrawl-spring[bot]44a6a1665e6e
diff --git a/apps/api/src/services/autumn/__tests__/usage.test.ts b/apps/api/src/services/autumn/__tests__/usage.test.ts
index 1e2188fff..9902f88e8 100644
--- a/apps/api/src/services/autumn/__tests__/usage.test.ts
+++ b/apps/api/src/services/autumn/__tests__/usage.test.ts
@@ -784,28 +784,18 @@ describe("getTeamHistoricalUsage", () => {
);
});
- it("falls back to a customer-level aggregate when the entity is missing", async () => {
- mockAggregate
- .mockRejectedValueOnce(
- Object.assign(new Error("not found"), { statusCode: 404 }),
- )
- .mockResolvedValueOnce({
- list: [
- {
- period: Date.parse("2026-04-02T00:00:00.000Z"),
- values: { CREDITS: 4 },
- },
- ],
- });
+ // The aggregate is scoped strictly to the team's entity. When the entity is
+ // missing the team simply has no usage of its own β€” we return an empty
+ // history rather than falling back to the org-wide total.
+ it("returns an empty history (no org fallback) when the entity is missing", async () => {
+ mockAggregate.mockRejectedValueOnce(
+ Object.assign(new Error("not found"), { statusCode: 404 }),
+ );
- await expect(getTeamHistoricalUsage("team-1")).resolves.toEqual([
- {
- startDate: "2026-04-01T00:00:00.000Z",
- endDate: null,
- creditsUsed: 4,
- },
- ]);
+ await expect(getTeamHistoricalUsage("team-1")).resolves.toEqual([]);
+ // Only the entity-scoped call is made; no customer-level retry.
+ expect(mockAggregate).toHaveBeenCalledTimes(1);
expect(mockAggregate).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
@@ -815,15 +805,13 @@ describe("getTeamHistoricalUsage", () => {
binSize: "day",
}),
);
- expect(mockAggregate).toHaveBeenNthCalledWith(
- 2,
- expect.objectContaining({
- customerId: "org-1",
- range: "90d",
- binSize: "day",
- }),
+ });
+
+ it("rethrows non-404 aggregate errors", async () => {
+ mockAggregate.mockRejectedValueOnce(
+ Object.assign(new Error("boom"), { statusCode: 500 }),
);
- expect(mockAggregate.mock.calls[1][0]).not.toHaveProperty("entityId");
+ await expect(getTeamHistoricalUsage("team-1")).rejects.toThrow("boom");
});
it("uses the next calendar month as endDate when a month has zero usage", async () => {
@@ -970,4 +958,22 @@ describe("getTeamHistoricalUsageByApiKey", () => {
},
]);
});
+
+ it("returns an empty history (no org fallback) when the entity is missing", async () => {
+ mockAggregate.mockRejectedValueOnce(
+ Object.assign(new Error("not found"), { statusCode: 404 }),
+ );
+
+ await expect(getTeamHistoricalUsageByApiKey("team-1")).resolves.toEqual([]);
+
+ expect(mockAggregate).toHaveBeenCalledTimes(1);
+ expect(mockAggregate).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ customerId: "org-1",
+ entityId: "team-1",
+ groupBy: "properties.apiKeyId",
+ }),
+ );
+ });
});
diff --git a/apps/api/src/services/autumn/usage.ts b/apps/api/src/services/autumn/usage.ts
index 681a1b5aa..99ed41349 100644
--- a/apps/api/src/services/autumn/usage.ts
+++ b/apps/api/src/services/autumn/usage.ts
@@ -367,8 +367,11 @@ interface HistoricalPeriodByApiKey {
/**
* Fetches a team's historical credit usage across billing periods from Autumn.
*
- * Uses `events.aggregate` with the last 90 days of daily usage and rolls those
- * daily totals into calendar-month buckets in API code.
+ * Scopes the aggregate to the team's Autumn entity so the response reflects
+ * only that team's usage, not the whole org. Uses `events.aggregate` with the
+ * last 90 days of daily usage and rolls those daily totals into calendar-month
+ * buckets in API code. A team with no entity (never provisioned) has no
+ * team-scoped usage, so we return an empty history rather than the org total.
*/
export async function getTeamHistoricalUsage(
teamId: string,
@@ -381,7 +384,6 @@ export async function getTeamHistoricalUsage(
const orgId = await lookupOrgId(teamId);
- // Try entity-scoped aggregate first, fall back to customer-level
let response: any;
try {
response = await autumnClient.events.aggregate({
@@ -394,13 +396,8 @@ export async function getTeamHistoricalUsage(
} catch (err: any) {
const status = err?.statusCode ?? err?.status ?? err?.response?.status;
if (status !== 404) throw err;
- // Entity not found β€” retry at customer level
- response = await autumnClient.events.aggregate({
- customerId: orgId,
- featureId: CREDITS_FEATURE_ID,
- range: HISTORICAL_RANGE,
- binSize: HISTORICAL_BIN_SIZE,
- });
+ // Entity not found β€” the team has no usage of its own to report.
+ return [];
}
return aggregateHistoricalPeriodsByMonth(response.list ?? []);
@@ -436,13 +433,8 @@ export async function getTeamHistoricalUsageByApiKey(
} catch (err: any) {
const status = err?.statusCode ?? err?.status ?? err?.response?.status;
if (status !== 404) throw err;
- response = await autumnClient.events.aggregate({
- customerId: orgId,
- featureId: CREDITS_FEATURE_ID,
- range: HISTORICAL_RANGE,
- binSize: HISTORICAL_BIN_SIZE,
- groupBy: "properties.apiKeyId",
- });
+ // Entity not found β€” the team has no usage of its own to report.
+ return [];
}
return aggregateHistoricalPeriodsByApiKeyMonth(response.list ?? []);