Răsfoiți Sursa

Add frontend calls to usage endpoint

Mauricio Araujo 2 ani în urmă
părinte
comite
a47e256017

+ 6 - 0
api/server/handlers/billing/plan.go

@@ -198,6 +198,12 @@ func (c *ListCustomerUsageHandler) ServeHTTP(w http.ResponseWriter, r *http.Requ
 
 	req := &types.ListCustomerUsageRequest{}
 
+	if ok := c.DecodeAndValidate(w, r, req); !ok {
+		err := telemetry.Error(ctx, span, nil, "error decoding list customer usage request")
+		c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
+		return
+	}
+
 	credits, err := c.Config().BillingManager.MetronomeClient.ListCustomerUsage(ctx, proj.UsageID, req.StartingOn, req.EndingBefore, req.WindowSize, req.CurrentPeriod)
 	if err != nil {
 		err := telemetry.Error(ctx, span, err, "error listing customer usage")

+ 8 - 0
dashboard/src/lib/billing/types.tsx

@@ -27,6 +27,14 @@ export const Plan = z.object({
   trial_info: Trial,
 });
 
+export type UsageList = Usage[];
+export type Usage = z.infer<typeof Usage>;
+export const Usage = z.object({
+  starting_on: z.string(),
+  ending_on: z.string(),
+  value: z.number(),
+});
+
 export type CreditGrants = z.infer<typeof CreditGrantsValidator>;
 export const CreditGrantsValidator = z.object({
   granted_credits: z.number(),

+ 37 - 0
dashboard/src/lib/hooks/useStripe.tsx

@@ -7,6 +7,8 @@ import {
   CreditGrantsValidator,
   PaymentMethodValidator,
   Plan,
+  Usage,
+  UsageList,
   type CreditGrants,
   type PaymentMethod,
   type PaymentMethodList,
@@ -57,6 +59,11 @@ type TGetPlan = {
   plan: Plan | undefined;
 };
 
+type TGetUsage = {
+  usage: UsageList | undefined;
+};
+
+
 const embeddableDashboardColors = {
   grayDark: "Gray_dark",
   grayMedium: "Gray_medium",
@@ -307,6 +314,36 @@ export const useCustomerPlan = (): TGetPlan => {
   };
 };
 
+export const useCustomerUsage = (): TGetUsage => {
+  const { currentProject } = useContext(Context);
+
+  // Fetch current plan
+  const usageReq = useQuery(
+    ["listCustomerUsage", currentProject?.id],
+    async () => {
+      if (!currentProject?.id || currentProject.id === -1) {
+        return;
+      }
+      const res = await api.getCustomerUsage(
+        "<token>",
+        {
+          window_size: "none",
+          current_period: true,
+        },
+        {
+          project_id: currentProject?.id,
+        }
+      );
+      const usage = Usage.array().parse(res.data);
+      return usage;
+    }
+  );
+
+  return {
+    usage: usageReq.data,
+  };
+};
+
 export const useSetDefaultPaymentMethod = (): TSetDefaultPaymentMethod => {
   const { currentProject } = useContext(Context);
 

+ 8 - 4
dashboard/src/main/home/project-settings/BillingPage.tsx

@@ -13,6 +13,7 @@ import Text from "components/porter/Text";
 import {
   checkIfProjectHasPayment,
   useCustomerPlan,
+  useCustomerUsage,
   useCustomeUsageDashboard,
   usePaymentMethods,
   usePorterCredits,
@@ -46,6 +47,9 @@ function BillingPage(): JSX.Element {
 
   const { url: usageDashboard } = useCustomeUsageDashboard("usage");
 
+  const { usage } = useCustomerUsage();
+  console.log(usage)
+
   const formatCredits = (credits: number): string => {
     return (credits / 100).toFixed(2);
   };
@@ -195,10 +199,10 @@ function BillingPage(): JSX.Element {
               <Spacer inline x={1} />
               <Text size={20}>
                 {creditGrants !== undefined &&
-                creditGrants.remaining_credits > 0
+                  creditGrants.remaining_credits > 0
                   ? `$${formatCredits(
-                      creditGrants.remaining_credits
-                    )}/$${formatCredits(creditGrants.granted_credits)}`
+                    creditGrants.remaining_credits
+                  )}/$${formatCredits(creditGrants.granted_credits)}`
                   : "$ 0.00"}
               </Text>
             </Container>
@@ -224,7 +228,7 @@ function BillingPage(): JSX.Element {
                     </Container>
                     <Container row>
                       {plan.trial_info !== undefined &&
-                      plan.trial_info.ending_before !== "" ? (
+                        plan.trial_info.ending_before !== "" ? (
                         <Text>
                           Free trial ends{" "}
                           {relativeTime(plan.trial_info.ending_before)}

+ 13 - 0
dashboard/src/shared/api.tsx

@@ -3464,6 +3464,18 @@ const getPublishableKey = baseApi<
   ({ project_id }) => `/api/projects/${project_id}/billing/publishable_key`
 );
 
+const getCustomerUsage = baseApi<
+  {
+    window_size: string;
+    starting_on?: string;
+    ending_before?: string;
+    current_period?: boolean;
+  },
+  {
+    project_id?: number;
+  }
+>("POST", ({ project_id }) => `/api/projects/${project_id}/billing/usage`);
+
 const getUsageDashboard = baseApi<
   {
     dashboard: string;
@@ -3909,6 +3921,7 @@ export default {
   getPublishableKey,
   getPorterCredits,
   getCustomerPlan,
+  getCustomerUsage,
   getUsageDashboard,
   listPaymentMethod,
   addPaymentMethod,