Mauricio Araujo 2 лет назад
Родитель
Сommit
cc5ea37477

+ 3 - 3
api/server/handlers/billing/ingest.go

@@ -75,7 +75,7 @@ func (c *IngestEventsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
 		}
 	}
 
-	subscriptionID, err := c.Config().BillingManager.LagoClient.GetCustomeActiveSubscription(ctx, proj.ID, proj.EnableSandbox)
+	plan, err := c.Config().BillingManager.LagoClient.GetCustomeActivePlan(ctx, proj.ID, proj.EnableSandbox)
 	if err != nil {
 		err := telemetry.Error(ctx, span, err, "error getting active subscription")
 		c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
@@ -83,10 +83,10 @@ func (c *IngestEventsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
 	}
 
 	telemetry.WithAttributes(span,
-		telemetry.AttributeKV{Key: "subscription_id", Value: subscriptionID},
+		telemetry.AttributeKV{Key: "subscription_id", Value: plan.ID},
 	)
 
-	err = c.Config().BillingManager.LagoClient.IngestEvents(ctx, subscriptionID, ingestEventsRequest.Events, proj.EnableSandbox)
+	err = c.Config().BillingManager.LagoClient.IngestEvents(ctx, plan.ID, ingestEventsRequest.Events, proj.EnableSandbox)
 	if err != nil {
 		err := telemetry.Error(ctx, span, err, "error ingesting events")
 		c.HandleAPIError(w, r, apierrors.NewErrInternal(err))

+ 2 - 9
api/server/handlers/billing/plan.go

@@ -43,7 +43,7 @@ func (c *ListPlansHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 
-	subscriptionID, err := c.Config().BillingManager.LagoClient.GetCustomeActiveSubscription(ctx, proj.ID, proj.EnableSandbox)
+	plan, err := c.Config().BillingManager.LagoClient.GetCustomeActivePlan(ctx, proj.ID, proj.EnableSandbox)
 	if err != nil {
 		err := telemetry.Error(ctx, span, err, "error getting active subscription")
 		c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
@@ -51,16 +51,9 @@ func (c *ListPlansHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
 	}
 
 	telemetry.WithAttributes(span,
-		telemetry.AttributeKV{Key: "subscription_id", Value: subscriptionID},
+		telemetry.AttributeKV{Key: "subscription_id", Value: plan.ID},
 	)
 
-	plan, err := c.Config().BillingManager.LagoClient.ListCustomerPlan(ctx, subscriptionID)
-	if err != nil {
-		err := telemetry.Error(ctx, span, err, "error listing plans")
-		c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
-		return
-	}
-
 	c.WriteResult(w, r, plan)
 }
 

+ 4 - 8
api/types/billing_metronome.go → api/types/billing_usage.go

@@ -151,14 +151,10 @@ type FormattedCost struct {
 }
 
 type Plan struct {
-	ID                  uuid.UUID `json:"id"`
-	PlanID              uuid.UUID `json:"plan_id"`
-	PlanName            string    `json:"plan_name"`
-	PlanDescription     string    `json:"plan_description"`
-	StartingOn          string    `json:"starting_on"`
-	EndingBefore        string    `json:"ending_before"`
-	NetPaymentTermsDays int       `json:"net_payment_terms_days"`
-	TrialInfo           Trial     `json:"trial_info,omitempty"`
+	ID           string `json:"id"`
+	StartingOn   string `json:"starting_on"`
+	EndingBefore string `json:"ending_before"`
+	TrialInfo    Trial  `json:"trial_info,omitempty"`
 }
 
 // Trial contains the information for a trial period

+ 19 - 43
internal/billing/usage.go

@@ -3,8 +3,8 @@ package billing
 import (
 	"context"
 	"fmt"
-	"log"
 	"strconv"
+	"strings"
 	"time"
 
 	"github.com/getlago/lago-go-client"
@@ -55,6 +55,7 @@ func NewLagoClient(lagoApiKey string, porterCloudPlanCode string, porterStandard
 	if lagoClient == nil {
 		return client, fmt.Errorf("failed to create lago client")
 	}
+	// lagoClient.Debug = true
 
 	return LagoClient{
 		client:                   *lagoClient,
@@ -134,74 +135,49 @@ func (m LagoClient) CheckIfCustomerExists(ctx context.Context, projectID uint, e
 	return true, nil
 }
 
-func (m LagoClient) GetCustomeActiveSubscription(ctx context.Context, projectID uint, sandboxEnabled bool) (subscriptionID string, err error) {
+func (m LagoClient) GetCustomeActivePlan(ctx context.Context, projectID uint, sandboxEnabled bool) (plan types.Plan, err error) {
 	ctx, span := telemetry.NewSpan(ctx, "get-active-subscription")
 	defer span.End()
 
 	if projectID == 0 {
-		return subscriptionID, telemetry.Error(ctx, span, err, "project id empty")
+		return plan, telemetry.Error(ctx, span, err, "project id empty")
 	}
 
 	if sandboxEnabled {
-		subscriptionID = m.generateLagoID(SubscriptionIDPrefix, projectID, sandboxEnabled)
-		return subscriptionID, nil
+		subscriptionID := m.generateLagoID(SubscriptionIDPrefix, projectID, sandboxEnabled)
+		return types.Plan{ID: subscriptionID}, nil
 	}
 
 	customerID := m.generateLagoID(CustomerIDPrefix, projectID, sandboxEnabled)
 	subscriptionListInput := lago.SubscriptionListInput{
 		ExternalCustomerID: customerID,
-		Status:             []string{"active"},
 	}
 
 	activeSubscriptions, lagoErr := m.client.Subscription().GetList(ctx, subscriptionListInput)
 	if lagoErr != nil {
-		return subscriptionID, telemetry.Error(ctx, span, fmt.Errorf(lagoErr.ErrorCode), "failed to get active subscription")
+		return plan, telemetry.Error(ctx, span, fmt.Errorf(lagoErr.ErrorCode), "failed to get active subscription")
 	}
 
 	if activeSubscriptions == nil {
-		return subscriptionID, telemetry.Error(ctx, span, err, "no active subscriptions found")
-	}
-
-	if len(activeSubscriptions.Subscriptions) > 0 {
-		subscriptionID = activeSubscriptions.Subscriptions[0].ExternalID
+		return plan, telemetry.Error(ctx, span, err, "no active subscriptions found")
 	}
 
-	return subscriptionID, nil
-}
-
-// ListCustomerPlan will return the current active plan to which the user is subscribed
-func (m LagoClient) ListCustomerPlan(ctx context.Context, subscriptionID string) (plan types.Plan, err error) {
-	ctx, span := telemetry.NewSpan(ctx, "list-customer-plans")
-	defer span.End()
-
-	if subscriptionID == "" {
-		return plan, telemetry.Error(ctx, span, err, "project id empty")
-	}
-
-	subscription, lagoErr := m.client.Subscription().Get(ctx, subscriptionID)
-	if lagoErr != nil {
-		return plan, telemetry.Error(ctx, span, fmt.Errorf(lagoErr.ErrorCode), "failed to get subscription")
-	}
-
-	if subscription == nil {
-		return plan, nil
-	}
-
-	log.Println("subscription", subscription)
-
-	if subscription.StartedAt != nil {
-		plan.StartingOn = subscription.StartedAt.Format(time.RFC3339)
-	}
+	for _, subscription := range activeSubscriptions.Subscriptions {
+		if subscription.Status != lago.SubscriptionStatusActive {
+			continue
+		}
 
-	if subscription.EndingAt != nil {
+		plan.ID = subscription.ExternalID
+		plan.StartingOn = subscription.SubscriptionAt.Format(time.RFC3339)
 		plan.EndingBefore = subscription.EndingAt.Format(time.RFC3339)
-	}
 
-	if subscription.TrialEndedAt != nil {
-		plan.TrialInfo.EndingBefore = subscription.TrialEndedAt.Format(time.RFC3339)
+		if strings.Contains(subscription.ExternalID, TrialIDPrefix) {
+			plan.TrialInfo.EndingBefore = subscription.EndingAt.Format(time.RFC3339)
+		}
+
+		break
 	}
 
-	log.Println("plan", plan)
 	return plan, nil
 }