Selaa lähdekoodia

Working past usage

Mauricio Araujo 2 vuotta sitten
vanhempi
sitoutus
0b1fb3d0a8
2 muutettua tiedostoa jossa 34 lisäystä ja 17 poistoa
  1. 17 9
      dashboard/src/main/home/project-settings/UsagePage.tsx
  2. 17 8
      internal/billing/usage.go

+ 17 - 9
dashboard/src/main/home/project-settings/UsagePage.tsx

@@ -13,9 +13,11 @@ dayjs.extend(utc);
 
 function UsagePage(): JSX.Element {
   const { plan } = useCustomerPlan();
-  const planStartDate = dayjs.utc(plan?.starting_on);
+  const planStartDate = dayjs.utc(plan?.starting_on).startOf("month");
 
-  const [currentPeriod, setCurrentPeriod] = useState(planStartDate);
+  const [currentPeriod, setCurrentPeriod] = useState(
+    dayjs().utc().startOf("month")
+  );
   const [options, setOptions] = useState<
     Array<{ value: string; label: string }>
   >([]);
@@ -37,11 +39,11 @@ function UsagePage(): JSX.Element {
     const monthsElapsed = dayjs
       .utc()
       .startOf("month")
-      .diff(planStartDate.utc().startOf("month"), "month");
+      .diff(planStartDate, "month");
 
     if (monthsElapsed <= 0) {
       options.push({
-        value: currentPeriod.toISOString(),
+        value: currentPeriod.month().toString(),
         label: dayjs().utc().format("MMMM YYYY"),
       });
       setShowCurrentPeriod(true);
@@ -52,7 +54,7 @@ function UsagePage(): JSX.Element {
     for (let i = 0; i <= monthsElapsed; i++) {
       const optionDate = planStartDate.add(i, "month");
       options.push({
-        value: optionDate.toISOString(),
+        value: optionDate.month().toString(),
         label: optionDate.format("MMMM YYYY"),
       });
     }
@@ -61,13 +63,19 @@ function UsagePage(): JSX.Element {
   };
 
   const processedUsage = useMemo(() => {
-    if (!usageList || !usageList.length) {
+    if (!usageList?.length) {
       return null;
     }
 
-    const periodUsage = usageList.find((usage) =>
-      dayjs(usage.from_datetime).isSame(currentPeriod.month(), "month")
+    const periodUsage = usageList.find(
+      (usage) =>
+        dayjs(usage.from_datetime).utc().month() === currentPeriod.month()
     );
+
+    if (!periodUsage) {
+      return null;
+    }
+
     const totalCost = periodUsage?.total_amount_cents
       ? (periodUsage.total_amount_cents / 100).toFixed(4)
       : "";
@@ -92,7 +100,7 @@ function UsagePage(): JSX.Element {
     <>
       <Select
         options={options}
-        value={currentPeriod.toISOString()}
+        value={currentPeriod.month().toString()}
         setValue={(value) => {
           setCurrentPeriod(dayjs.utc(value));
           if (dayjs(value).isSame(dayjs(), "month")) {

+ 17 - 8
internal/billing/usage.go

@@ -15,6 +15,7 @@ import (
 )
 
 const (
+	lagoBaseURL                = "https://api.getlago.com"
 	defaultStarterCreditsCents = 500
 	defaultRewardAmountCents   = 1000
 	maxReferralRewards         = 10
@@ -58,7 +59,6 @@ func NewLagoClient(lagoApiKey string, porterCloudPlanCode string, porterStandard
 	if lagoClient == nil {
 		return client, fmt.Errorf("failed to create lago client")
 	}
-	lagoClient.Debug = true
 
 	return LagoClient{
 		lagoApiKey:               lagoApiKey,
@@ -222,7 +222,6 @@ func (m LagoClient) ListCustomerCredits(ctx context.Context, projectID uint, san
 
 	// We manually do the request in this function because the Lago client has an issue
 	// with types for this specific request
-	lagoBaseURL := "https://api.getlago.com"
 	url := fmt.Sprintf("%s/api/v1/wallets?external_customer_id=%s", lagoBaseURL, customerID)
 	req, err := http.NewRequest("GET", url, nil)
 	if err != nil {
@@ -319,14 +318,24 @@ func (m LagoClient) ListCustomerUsage(ctx context.Context, customerID string, su
 		usage := createUsageFromLagoUsage(*currentUsage)
 		usageList = append(usageList, usage)
 	} else {
-		customerPastUsageInput := &lago.CustomerPastUsageInput{
-			PeriodsCount:           previousPeriods,
-			ExternalSubscriptionID: subscriptionID,
+		url := fmt.Sprintf("%s/api/v1/customers/%s/past_usage?external_subscription_id=%s&periods_count=%d", lagoBaseURL, customerID, subscriptionID, previousPeriods)
+		req, err := http.NewRequest("GET", url, nil)
+		if err != nil {
+			return usageList, telemetry.Error(ctx, span, err, "failed to create wallets request")
 		}
 
-		previousUsage, lagoErr := m.client.Customer().PastUsage(ctx, customerID, customerPastUsageInput)
-		if lagoErr != nil {
-			return usageList, telemetry.Error(ctx, span, fmt.Errorf(lagoErr.ErrorCode), "failed to get customer usage")
+		req.Header.Set("Authorization", "Bearer "+m.lagoApiKey)
+
+		client := &http.Client{}
+		resp, err := client.Do(req)
+		if err != nil {
+			return usageList, telemetry.Error(ctx, span, err, "failed to get customer credits")
+		}
+
+		var previousUsage lago.CustomerPastUsageResult
+		err = json.NewDecoder(resp.Body).Decode(&previousUsage)
+		if err != nil {
+			return usageList, telemetry.Error(ctx, span, err, "failed to decode usage list response")
 		}
 
 		for _, pastUsage := range previousUsage.UsagePeriods {