File size: 1,011 Bytes
097eaf0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { Response } from "express";
import { ErrorResponse, RequestWithAuth } from "./types";
import { getTeamBalance } from "../../services/autumn/usage";

const TOKENS_PER_CREDIT = 15;

interface TokenUsageResponse {
  success: true;
  data: {
    remaining_tokens: number;
    plan_tokens: number;
    billing_period_start: string | null;
    billing_period_end: string | null;
  };
}

export async function tokenUsageController(
  req: RequestWithAuth,
  res: Response<TokenUsageResponse | ErrorResponse>,
): Promise<void> {
  const balance = await getTeamBalance(req.auth.team_id);

  if (!balance) {
    res.status(404).json({
      success: false,
      error: "Could not find token usage information",
    });
    return;
  }

  res.json({
    success: true,
    data: {
      remaining_tokens: balance.remaining * TOKENS_PER_CREDIT,
      plan_tokens: balance.planCredits * TOKENS_PER_CREDIT,
      billing_period_start: balance.periodStart,
      billing_period_end: balance.periodEnd,
    },
  });
}