Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. π₯
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
feat(billing): rewrite historical credit/token usage endpoints to use Autumn API (#3280)
devin-ai-integration[bot]547ac990994d
diff --git a/apps/api/src/__tests__/snips/v1/lib.ts b/apps/api/src/__tests__/snips/v1/lib.tsindex d531348d5..bc68c19d5 100644--- a/apps/api/src/__tests__/snips/v1/lib.ts+++ b/apps/api/src/__tests__/snips/v1/lib.ts@@ -467,6 +467,46 @@ export async function tokenUsage().body.data;}+export async function creditUsageHistorical(identity: Identity): Promise<{+ success: boolean;+ periods: {+ startDate: string | null;+ endDate: string | null;+ creditsUsed: number;+ }[];+}> {+ const req = await request(TEST_API_URL)+ .get("/v1/team/credit-usage/historical")+ .set("Authorization", `Bearer ${identity.apiKey}`)+ .set("Content-Type", "application/json");++ if (req.status !== 200) {+ throw req.body;+ }++ return req.body;+}++export async function tokenUsageHistorical(identity: Identity): Promise<{+ success: boolean;+ periods: {+ startDate: string | null;+ endDate: string | null;+ tokensUsed: number;+ }[];+}> {+ const req = await request(TEST_API_URL)+ .get("/v1/team/token-usage/historical")+ .set("Authorization", `Bearer ${identity.apiKey}`)+ .set("Content-Type", "application/json");++ if (req.status !== 200) {+ throw req.body;+ }++ return req.body;+}+// =========================================// Concurrency API// =========================================diff --git a/apps/api/src/__tests__/snips/v2/billing.test.ts b/apps/api/src/__tests__/snips/v2/billing.test.tsindex 71f8c3b1b..9793a3254 100644--- a/apps/api/src/__tests__/snips/v2/billing.test.ts+++ b/apps/api/src/__tests__/snips/v2/billing.test.ts@@ -3,6 +3,8 @@ import {batchScrape,crawl,creditUsage,+ creditUsageHistorical,+ tokenUsageHistorical,idmux,map,scrape,@@ -569,6 +571,68 @@ describeIf(TEST_PRODUCTION)("Billing tests", () => {600000,);+ it.concurrent(+ "returns historical credit usage",+ async () => {+ const identity = await idmux({+ name: "billing/returns historical credit usage",+ credits: 100,+ });++ const result = await creditUsageHistorical(identity);++ expect(result.success).toBe(true);+ expect(Array.isArray(result.periods)).toBe(true);++ for (const period of result.periods) {+ expect(typeof period.creditsUsed).toBe("number");+ expect(period.creditsUsed).toBeGreaterThanOrEqual(0);+ }++ // Verify periods are sorted by startDate ascending+ for (let i = 1; i < result.periods.length; i++) {+ const prevRaw = result.periods[i - 1].startDate ? Date.parse(result.periods[i - 1].startDate!) : NaN;+ const currRaw = result.periods[i].startDate ? Date.parse(result.periods[i].startDate!) : NaN;+ const prevNaN = Number.isNaN(prevRaw);+ const currNaN = Number.isNaN(currRaw);+ if (!prevNaN && !currNaN) {+ expect(currRaw).toBeGreaterThanOrEqual(prevRaw);+ } else if (!prevNaN && currNaN) {+ // null dates sorted last β valid+ }+ }+ },+ 60000,+ );++ it.concurrent(+ "returns historical token usage",+ async () => {+ const identity = await idmux({+ name: "billing/returns historical token usage",+ credits: 100,+ });++ const result = await tokenUsageHistorical(identity);++ expect(result.success).toBe(true);+ expect(Array.isArray(result.periods)).toBe(true);++ for (const period of result.periods) {+ expect(typeof period.tokensUsed).toBe("number");+ expect(period.tokensUsed).toBeGreaterThanOrEqual(0);+ }++ // Verify periods are sorted by startDate ascending+ for (let i = 1; i < result.periods.length; i++) {+ const prev = new Date(result.periods[i - 1].startDate ?? 0).getTime();+ const curr = new Date(result.periods[i].startDate ?? 0).getTime();+ expect(curr).toBeGreaterThanOrEqual(prev);+ }+ },+ 60000,+ );+it.concurrent("bills custom-cost ZDR scrape correctly",async () => {diff --git a/apps/api/src/__tests__/snips/v2/lib.ts b/apps/api/src/__tests__/snips/v2/lib.tsindex 2f3384f0a..47de0f491 100644--- a/apps/api/src/__tests__/snips/v2/lib.ts+++ b/apps/api/src/__tests__/snips/v2/lib.ts@@ -429,6 +429,46 @@ export async function creditUsage(return req.body.data;}+export async function creditUsageHistorical(identity: Identity): Promise<{+ success: boolean;+ periods: {+ startDate: string | null;+ endDate: string | null;+ creditsUsed: number;+ }[];+}> {+ const req = await request(TEST_API_URL)+ .get("/v2/team/credit-usage/historical")+ .set("Authorization", `Bearer ${identity.apiKey}`)+ .set("Content-Type", "application/json");++ if (req.status !== 200) {+ throw req.body;+ }++ return req.body;+}++export async function tokenUsageHistorical(identity: Identity): Promise<{+ success: boolean;+ periods: {+ startDate: string | null;+ endDate: string | null;+ tokensUsed: number;+ }[];+}> {+ const req = await request(TEST_API_URL)+ .get("/v2/team/token-usage/historical")+ .set("Authorization", `Bearer ${identity.apiKey}`)+ .set("Content-Type", "application/json");++ if (req.status !== 200) {+ throw req.body;+ }++ return req.body;+}+// =========================================// Concurrency API// =========================================diff --git a/apps/api/src/controllers/v1/credit-usage-historical.ts b/apps/api/src/controllers/v1/credit-usage-historical.tsindex 74a3c56de..6fb3571e0 100644--- a/apps/api/src/controllers/v1/credit-usage-historical.ts+++ b/apps/api/src/controllers/v1/credit-usage-historical.ts@@ -1,6 +1,9 @@import { Response } from "express";import { ErrorResponse, RequestWithAuth } from "./types";-import { supabase_rr_service } from "../../services/supabase";+import {+ getTeamHistoricalUsage,+ getTeamHistoricalUsageByApiKey,+} from "../../services/autumn/usage";interface CreditUsageHistoricalResponse {success: true;@@ -18,51 +21,19 @@ export async function creditUsageHistoricalController(): Promise<void> {const byApiKey = req.query.byApiKey === "true";- const { data, error } = await supabase_rr_service.rpc(- "get_historical_credit_usage_by_api_key_1",- {- v_team_id: req.auth.team_id,- v_is_extract: false,- },- { get: true },- );-- if (error || !data) {- throw error ?? new Error("Failed to get historical credit usage");- }-- let periods = data.map(period => ({- startDate: period.start_ts,- endDate: period.end_ts,- apiKey: period.api_key_name,- creditsUsed: period.amount,- }));-- if (!byApiKey) {- periods = periods.reduce((acc, period) => {- let preexisting = acc.find(- p => p.startDate === period.startDate && p.endDate === period.endDate,- );- if (preexisting) {- preexisting.creditsUsed += period.creditsUsed;- } else {- let newPeriod = { ...period };- delete newPeriod.apiKey;- acc.push(newPeriod);- }- return acc;- }, []);- }+ const periods: CreditUsageHistoricalResponse["periods"] = byApiKey+ ? await getTeamHistoricalUsageByApiKey(req.auth.team_id)+ : await getTeamHistoricalUsage(req.auth.team_id);periods.sort((a, b) => {const aTime = a.startDate ? Date.parse(a.startDate) : NaN;const bTime = b.startDate ? Date.parse(b.startDate) : NaN;const aNaN = Number.isNaN(aTime);const bNaN = Number.isNaN(bTime);- if (aNaN && bNaN) return 0; // both invalid/null -> keep relative order- if (aNaN) return 1; // invalid/null goes last- if (bNaN) return -1; // invalid/null goes last- return aTime - bTime; // ascending by valid timestamps+ if (aNaN && bNaN) return 0;+ if (aNaN) return 1;+ if (bNaN) return -1;+ return aTime - bTime;});res.json({diff --git a/apps/api/src/controllers/v1/token-usage-historical.ts b/apps/api/src/controllers/v1/token-usage-historical.tsindex 9095837fd..a75877e55 100644--- a/apps/api/src/controllers/v1/token-usage-historical.ts+++ b/apps/api/src/controllers/v1/token-usage-historical.ts@@ -1,6 +1,11 @@import { Response } from "express";import { ErrorResponse, RequestWithAuth } from "./types";-import { supabase_rr_service } from "../../services/supabase";+import {+ getTeamHistoricalUsage,+ getTeamHistoricalUsageByApiKey,+ toTokenPeriods,+ toTokenPeriodsByApiKey,+} from "../../services/autumn/usage";interface TokenUsageHistoricalResponse {success: true;@@ -18,45 +23,22 @@ export async function tokenUsageHistoricalController(): Promise<void> {const byApiKey = req.query.byApiKey === "true";- const { data, error } = await supabase_rr_service.rpc(- "get_historical_credit_usage_by_api_key_1",- {- v_team_id: req.auth.team_id,- v_is_extract: true,- },- { get: true },- );-- if (error || !data) {- throw error ?? new Error("Failed to get historical token usage");- }-- let periods = data.map(period => ({- startDate: period.start_ts,- endDate: period.end_ts,- apiKey: period.api_key_name,- tokensUsed: period.amount,- }));-- if (!byApiKey) {- periods = periods.reduce((acc, period) => {- let preexisting = acc.find(- p => p.startDate === period.startDate && p.endDate === period.endDate,- );- if (preexisting) {- preexisting.tokensUsed += period.tokensUsed;- } else {- let newPeriod = { ...period };- delete newPeriod.apiKey;- acc.push(newPeriod);- }- return acc;- }, []);- }-- periods.sort(- (a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime(),- );+ const periods: TokenUsageHistoricalResponse["periods"] = byApiKey+ ? toTokenPeriodsByApiKey(+ await getTeamHistoricalUsageByApiKey(req.auth.team_id),+ )+ : toTokenPeriods(await getTeamHistoricalUsage(req.auth.team_id));++ periods.sort((a, b) => {+ const aTime = a.startDate ? Date.parse(a.startDate) : NaN;+ const bTime = b.startDate ? Date.parse(b.startDate) : NaN;+ const aNaN = Number.isNaN(aTime);+ const bNaN = Number.isNaN(bTime);+ if (aNaN && bNaN) return 0;+ if (aNaN) return 1;+ if (bNaN) return -1;+ return aTime - bTime;+ });res.json({success: true,diff --git a/apps/api/src/controllers/v2/credit-usage-historical.ts b/apps/api/src/controllers/v2/credit-usage-historical.tsindex 29b77466f..6fb3571e0 100644--- a/apps/api/src/controllers/v2/credit-usage-historical.ts+++ b/apps/api/src/controllers/v2/credit-usage-historical.ts@@ -1,6 +1,9 @@import { Response } from "express";import { ErrorResponse, RequestWithAuth } from "./types";-import { supabase_rr_service } from "../../services/supabase";+import {+ getTeamHistoricalUsage,+ getTeamHistoricalUsageByApiKey,+} from "../../services/autumn/usage";interface CreditUsageHistoricalResponse {success: true;@@ -18,45 +21,20 @@ export async function creditUsageHistoricalController(): Promise<void> {const byApiKey = req.query.byApiKey === "true";- const { data, error } = await supabase_rr_service.rpc(- "get_historical_credit_usage_by_api_key_1",- {- v_team_id: req.auth.team_id,- v_is_extract: false,- },- { get: true },- );-- if (error || !data) {- throw error ?? new Error("Failed to get historical credit usage");- }-- let periods = data.map(period => ({- startDate: period.start_ts,- endDate: period.end_ts,- apiKey: period.api_key_name,- creditsUsed: period.amount,- }));-- if (!byApiKey) {- periods = periods.reduce((acc, period) => {- let preexisting = acc.find(- p => p.startDate === period.startDate && p.endDate === period.endDate,- );- if (preexisting) {- preexisting.creditsUsed += period.creditsUsed;- } else {- let newPeriod = { ...period };- delete newPeriod.apiKey;- acc.push(newPeriod);- }- return acc;- }, []);- }-- periods.sort(- (a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime(),- );+ const periods: CreditUsageHistoricalResponse["periods"] = byApiKey+ ? await getTeamHistoricalUsageByApiKey(req.auth.team_id)+ : await getTeamHistoricalUsage(req.auth.team_id);++ periods.sort((a, b) => {+ const aTime = a.startDate ? Date.parse(a.startDate) : NaN;+ const bTime = b.startDate ? Date.parse(b.startDate) : NaN;+ const aNaN = Number.isNaN(aTime);+ const bNaN = Number.isNaN(bTime);+ if (aNaN && bNaN) return 0;+ if (aNaN) return 1;+ if (bNaN) return -1;+ return aTime - bTime;+ });res.json({success: true,diff --git a/apps/api/src/controllers/v2/token-usage-historical.ts b/apps/api/src/controllers/v2/token-usage-historical.tsindex 9095837fd..a75877e55 100644--- a/apps/api/src/controllers/v2/token-usage-historical.ts+++ b/apps/api/src/controllers/v2/token-usage-historical.ts@@ -1,6 +1,11 @@import { Response } from "express";import { ErrorResponse, RequestWithAuth } from "./types";-import { supabase_rr_service } from "../../services/supabase";+import {+ getTeamHistoricalUsage,+ getTeamHistoricalUsageByApiKey,+ toTokenPeriods,+ toTokenPeriodsByApiKey,+} from "../../services/autumn/usage";interface TokenUsageHistoricalResponse {success: true;@@ -18,45 +23,22 @@ export async function tokenUsageHistoricalController(): Promise<void> {const byApiKey = req.query.byApiKey === "true";- const { data, error } = await supabase_rr_service.rpc(- "get_historical_credit_usage_by_api_key_1",- {- v_team_id: req.auth.team_id,- v_is_extract: true,- },- { get: true },- );-- if (error || !data) {- throw error ?? new Error("Failed to get historical token usage");- }-- let periods = data.map(period => ({- startDate: period.start_ts,- endDate: period.end_ts,- apiKey: period.api_key_name,- tokensUsed: period.amount,- }));-- if (!byApiKey) {- periods = periods.reduce((acc, period) => {- let preexisting = acc.find(- p => p.startDate === period.startDate && p.endDate === period.endDate,- );- if (preexisting) {- preexisting.tokensUsed += period.tokensUsed;- } else {- let newPeriod = { ...period };- delete newPeriod.apiKey;- acc.push(newPeriod);- }- return acc;- }, []);- }-- periods.sort(- (a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime(),- );+ const periods: TokenUsageHistoricalResponse["periods"] = byApiKey+ ? toTokenPeriodsByApiKey(+ await getTeamHistoricalUsageByApiKey(req.auth.team_id),+ )+ : toTokenPeriods(await getTeamHistoricalUsage(req.auth.team_id));++ periods.sort((a, b) => {+ const aTime = a.startDate ? Date.parse(a.startDate) : NaN;+ const bTime = b.startDate ? Date.parse(b.startDate) : NaN;+ const aNaN = Number.isNaN(aTime);+ const bNaN = Number.isNaN(bTime);+ if (aNaN && bNaN) return 0;+ if (aNaN) return 1;+ if (bNaN) return -1;+ return aTime - bTime;+ });res.json({success: true,diff --git a/apps/api/src/services/autumn/__tests__/usage.test.ts b/apps/api/src/services/autumn/__tests__/usage.test.tsnew file mode 100644index 000000000..f22ec1220--- /dev/null+++ b/apps/api/src/services/autumn/__tests__/usage.test.ts@@ -0,0 +1,272 @@+import { jest } from "@jest/globals";++const mockAggregate = jest.fn<(args: any) => Promise<any>>();++let autumnClientRef: { events: { aggregate: typeof mockAggregate } } | null = {+ events: { aggregate: mockAggregate },+};++let teamLookup = {+ data: { org_id: "org-1" },+ error: null as unknown,+};++let apiKeysData: Array<{ id: number; name: string }> = [];++jest.mock("../client", () => ({+ get autumnClient() {+ return autumnClientRef;+ },+}));++jest.mock("../../supabase", () => ({+ get supabase_rr_service() {+ return {+ from: (table: string) => ({+ select: () => {+ if (table === "teams") {+ return {+ eq: () => ({+ single: () => Promise.resolve(teamLookup),+ }),+ };+ }++ if (table === "api_keys") {+ return {+ in: () => Promise.resolve({ data: apiKeysData, error: null }),+ };+ }++ return {};+ },+ }),+ };+ },+}));++import {+ getTeamHistoricalUsage,+ getTeamHistoricalUsageByApiKey,+} from "../usage";++beforeEach(() => {+ jest.clearAllMocks();+ autumnClientRef = { events: { aggregate: mockAggregate } };+ teamLookup = { data: { org_id: "org-1" }, error: null };+ apiKeysData = [];+});++describe("getTeamHistoricalUsage", () => {+ it("aggregates 90 days of daily usage into calendar-month buckets", async () => {+ mockAggregate.mockResolvedValue({+ list: [+ {+ period: Date.parse("2026-03-30T00:00:00.000Z"),+ values: { CREDITS: 20 },+ },+ {+ period: Date.parse("2026-03-31T00:00:00.000Z"),+ values: { CREDITS: 333 },+ },+ {+ period: Date.parse("2026-04-01T00:00:00.000Z"),+ values: { CREDITS: 1 },+ },+ ],+ });++ await expect(+ getTeamHistoricalUsage("team-1"),+ ).resolves.toEqual([+ {+ startDate: "2026-03-01T00:00:00.000Z",+ endDate: "2026-04-01T00:00:00.000Z",+ creditsUsed: 353,+ },+ {+ startDate: "2026-04-01T00:00:00.000Z",+ endDate: null,+ creditsUsed: 1,+ },+ ]);++ expect(mockAggregate).toHaveBeenCalledWith(+ expect.objectContaining({+ customerId: "org-1",+ entityId: "team-1",+ featureId: "CREDITS",+ range: "90d",+ binSize: "day",+ }),+ );+ });++ 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 },+ },+ ],+ });++ await expect(+ getTeamHistoricalUsage("team-1"),+ ).resolves.toEqual([+ {+ startDate: "2026-04-01T00:00:00.000Z",+ endDate: null,+ creditsUsed: 4,+ },+ ]);++ expect(mockAggregate).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ customerId: "org-1",+ entityId: "team-1",+ range: "90d",+ binSize: "day",+ }),+ );+ expect(mockAggregate).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ customerId: "org-1",+ range: "90d",+ binSize: "day",+ }),+ );+ expect(mockAggregate.mock.calls[1][0]).not.toHaveProperty("entityId");+ });++ it("uses the next calendar month as endDate when a month has zero usage", async () => {+ mockAggregate.mockResolvedValue({+ list: [+ {+ period: Date.parse("2026-01-31T00:00:00.000Z"),+ values: { CREDITS: 12 },+ },+ {+ period: Date.parse("2026-03-01T00:00:00.000Z"),+ values: { CREDITS: 7 },+ },+ ],+ });++ await expect(+ getTeamHistoricalUsage("team-1"),+ ).resolves.toEqual([+ {+ startDate: "2026-01-01T00:00:00.000Z",+ endDate: "2026-02-01T00:00:00.000Z",+ creditsUsed: 12,+ },+ {+ startDate: "2026-03-01T00:00:00.000Z",+ endDate: null,+ creditsUsed: 7,+ },+ ]);+ });+});++describe("getTeamHistoricalUsageByApiKey", () => {+ it("aggregates daily grouped usage into calendar-month buckets", async () => {+ apiKeysData = [+ { id: 101, name: "Default" },+ { id: 202, name: "postman" },+ ];++ mockAggregate.mockResolvedValue({+ list: [+ {+ period: Date.parse("2026-03-30T00:00:00.000Z"),+ grouped_values: { CREDITS: { "101": 10, "202": 3 } },+ },+ {+ period: Date.parse("2026-03-31T00:00:00.000Z"),+ grouped_values: { CREDITS: { "101": 26 } },+ },+ {+ period: Date.parse("2026-04-02T00:00:00.000Z"),+ grouped_values: { CREDITS: { "202": 5 } },+ },+ ],+ });++ await expect(+ getTeamHistoricalUsageByApiKey("team-1"),+ ).resolves.toEqual([+ {+ startDate: "2026-03-01T00:00:00.000Z",+ endDate: "2026-04-01T00:00:00.000Z",+ apiKey: "Default",+ creditsUsed: 36,+ },+ {+ startDate: "2026-03-01T00:00:00.000Z",+ endDate: "2026-04-01T00:00:00.000Z",+ apiKey: "postman",+ creditsUsed: 3,+ },+ {+ startDate: "2026-04-01T00:00:00.000Z",+ endDate: null,+ apiKey: "postman",+ creditsUsed: 5,+ },+ ]);++ expect(mockAggregate).toHaveBeenCalledWith(+ expect.objectContaining({+ customerId: "org-1",+ entityId: "team-1",+ featureId: "CREDITS",+ range: "90d",+ binSize: "day",+ groupBy: "properties.apiKeyId",+ }),+ );+ });++ it("uses the next calendar month as endDate for grouped data when a month has zero usage", async () => {+ apiKeysData = [{ id: 101, name: "Default" }];++ mockAggregate.mockResolvedValue({+ list: [+ {+ period: Date.parse("2026-01-31T00:00:00.000Z"),+ grouped_values: { CREDITS: { "101": 12 } },+ },+ {+ period: Date.parse("2026-03-01T00:00:00.000Z"),+ grouped_values: { CREDITS: { "101": 7 } },+ },+ ],+ });++ await expect(+ getTeamHistoricalUsageByApiKey("team-1"),+ ).resolves.toEqual([+ {+ startDate: "2026-01-01T00:00:00.000Z",+ endDate: "2026-02-01T00:00:00.000Z",+ apiKey: "Default",+ creditsUsed: 12,+ },+ {+ startDate: "2026-03-01T00:00:00.000Z",+ endDate: null,+ apiKey: "Default",+ creditsUsed: 7,+ },+ ]);+ });+});diff --git a/apps/api/src/services/autumn/usage.ts b/apps/api/src/services/autumn/usage.tsindex d4936fa57..defd59e58 100644--- a/apps/api/src/services/autumn/usage.ts+++ b/apps/api/src/services/autumn/usage.ts@@ -3,6 +3,9 @@ import { supabase_rr_service } from "../supabase";import { autumnClient } from "./client";const CREDITS_FEATURE_ID = "CREDITS";+const TOKENS_PER_CREDIT = 15;+const HISTORICAL_RANGE = "90d";+const HISTORICAL_BIN_SIZE = "day";// ---------------------------------------------------------------------------// Types@@ -36,6 +39,142 @@ async function lookupOrgId(teamId: string): Promise<string> {return data.org_id;}+/**+ * Maps numeric API key IDs to their display names from the api_keys table.+ * Returns a map of id β name. Unknown IDs are mapped to their string representation.+ */+async function lookupApiKeyNames(+ apiKeyIds: string[],+): Promise<Record<string, string>> {+ const numericIds = apiKeyIds+ .map(id => Number(id))+ .filter(n => !isNaN(n) && n > 0);++ const nameMap: Record<string, string> = {};++ if (numericIds.length > 0) {+ const { data } = await supabase_rr_service+ .from("api_keys")+ .select("id, name")+ .in("id", numericIds);++ if (data) {+ for (const row of data) {+ nameMap[String(row.id)] = row.name;+ }+ }+ }++ // Fall back to raw ID string for any keys not found+ for (const id of apiKeyIds) {+ if (!nameMap[id]) {+ nameMap[id] = id;+ }+ }++ return nameMap;+}++function toMonthStartIso(period: unknown): string | null {+ if (period == null) return null;++ const date = new Date(period as string | number);+ if (isNaN(date.getTime())) return null;++ return new Date(+ Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1),+ ).toISOString();+}++function nextMonthIso(monthStartIso: string): string {+ const date = new Date(monthStartIso);+ return new Date(+ Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 1),+ ).toISOString();+}++function aggregateHistoricalPeriodsByMonth(list: any[]): HistoricalPeriod[] {+ const monthTotals = new Map<string, number>();++ for (const entry of list) {+ const monthStart = toMonthStartIso(entry.period);+ if (!monthStart) continue;++ monthTotals.set(+ monthStart,+ (monthTotals.get(monthStart) ?? 0) ++ (entry.values?.[CREDITS_FEATURE_ID] ?? 0),+ );+ }++ const monthStarts = [...monthTotals.keys()].sort();++ return monthStarts.map((startDate, i) => ({+ startDate,+ endDate: i < monthStarts.length - 1 ? nextMonthIso(startDate) : null,+ creditsUsed: monthTotals.get(startDate) ?? 0,+ }));+}++function getGroupedCredits(+ entry: any,+): Record<string, number> | undefined {+ return (+ entry.groupedValues?.[CREDITS_FEATURE_ID] ??+ entry.grouped_values?.[CREDITS_FEATURE_ID]+ );+}++async function aggregateHistoricalPeriodsByApiKeyMonth(+ list: any[],+): Promise<HistoricalPeriodByApiKey[]> {+ const monthApiKeyTotals = new Map<string, Map<string, number>>();+ const allApiKeyIds = new Set<string>();++ for (const entry of list) {+ const monthStart = toMonthStartIso(entry.period);+ if (!monthStart) continue;++ const grouped = getGroupedCredits(entry);+ if (!grouped) continue;++ const monthTotals =+ monthApiKeyTotals.get(monthStart) ?? new Map<string, number>();++ for (const [apiKeyId, creditsUsed] of Object.entries(grouped)) {+ allApiKeyIds.add(apiKeyId);+ monthTotals.set(apiKeyId, (monthTotals.get(apiKeyId) ?? 0) + creditsUsed);+ }++ monthApiKeyTotals.set(monthStart, monthTotals);+ }++ const nameMap = await lookupApiKeyNames([...allApiKeyIds]);+ const monthStarts = [...monthApiKeyTotals.keys()].sort();+ const results: HistoricalPeriodByApiKey[] = [];++ for (let i = 0; i < monthStarts.length; i++) {+ const startDate = monthStarts[i];+ const endDate = i < monthStarts.length - 1 ? nextMonthIso(startDate) : null;+ const monthTotals = monthApiKeyTotals.get(startDate);++ if (!monthTotals) continue;++ for (const [apiKeyId, creditsUsed] of [...monthTotals.entries()].sort(+ ([a], [b]) => a.localeCompare(b),+ )) {+ results.push({+ startDate,+ endDate,+ apiKey: nameMap[apiKeyId],+ creditsUsed,+ });+ }+ }++ return results;+}+// ---------------------------------------------------------------------------// Balance (current billing period)// ---------------------------------------------------------------------------@@ -50,7 +189,9 @@ export async function getTeamBalance(teamId: string,): Promise<TeamBalance | null> {if (!autumnClient) {- throw new Error("Autumn client is not configured (AUTUMN_SECRET_KEY missing)");+ throw new Error(+ "Autumn client is not configured (AUTUMN_SECRET_KEY missing)",+ );}const orgId = await lookupOrgId(teamId);@@ -125,3 +266,136 @@ export async function getTeamBalance(: null,};}++// ---------------------------------------------------------------------------+// Historical usage (across billing periods)+// ---------------------------------------------------------------------------++interface HistoricalPeriod {+ startDate: string | null;+ endDate: string | null;+ creditsUsed: number;+}++interface HistoricalPeriodByApiKey {+ startDate: string | null;+ endDate: string | null;+ apiKey: string;+ creditsUsed: number;+}++/**+ * 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.+ */+export async function getTeamHistoricalUsage(+ teamId: string,+): Promise<HistoricalPeriod[]> {+ if (!autumnClient) {+ throw new Error(+ "Autumn client is not configured (AUTUMN_SECRET_KEY missing)",+ );+ }++ const orgId = await lookupOrgId(teamId);++ // Try entity-scoped aggregate first, fall back to customer-level+ let response: any;+ try {+ response = await autumnClient.events.aggregate({+ customerId: orgId,+ entityId: teamId,+ featureId: CREDITS_FEATURE_ID,+ range: HISTORICAL_RANGE,+ binSize: HISTORICAL_BIN_SIZE,+ });+ } 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,+ });+ }++ return aggregateHistoricalPeriodsByMonth(response.list ?? []);+}++/**+ * Fetches a team's historical credit usage grouped by API key from Autumn.+ *+ * Uses the last 90 days of daily usage plus `groupBy: "properties.apiKeyId"`+ * and rolls those daily totals into calendar-month buckets in API code.+ */+export async function getTeamHistoricalUsageByApiKey(+ teamId: string,+): Promise<HistoricalPeriodByApiKey[]> {+ if (!autumnClient) {+ throw new Error(+ "Autumn client is not configured (AUTUMN_SECRET_KEY missing)",+ );+ }++ const orgId = await lookupOrgId(teamId);++ let response: any;+ try {+ response = await autumnClient.events.aggregate({+ customerId: orgId,+ entityId: teamId,+ featureId: CREDITS_FEATURE_ID,+ range: HISTORICAL_RANGE,+ binSize: HISTORICAL_BIN_SIZE,+ groupBy: "properties.apiKeyId",+ });+ } 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",+ });+ }++ return aggregateHistoricalPeriodsByApiKeyMonth(response.list ?? []);+}++/**+ * Converts historical credit periods to token periods.+ * Tokens = credits Γ 15.+ */+export function toTokenPeriods(+ periods: HistoricalPeriod[],+): { startDate: string | null; endDate: string | null; tokensUsed: number }[] {+ return periods.map(p => ({+ startDate: p.startDate,+ endDate: p.endDate,+ tokensUsed: p.creditsUsed * TOKENS_PER_CREDIT,+ }));+}++/**+ * Converts historical credit periods (by API key) to token periods.+ * Tokens = credits Γ 15.+ */+export function toTokenPeriodsByApiKey(periods: HistoricalPeriodByApiKey[]): {+ startDate: string | null;+ endDate: string | null;+ apiKey: string;+ tokensUsed: number;+}[] {+ return periods.map(p => ({+ startDate: p.startDate,+ endDate: p.endDate,+ apiKey: p.apiKey,+ tokensUsed: p.creditsUsed * TOKENS_PER_CREDIT,+ }));+}