Skip to content

Commit

Permalink
Working past usage
Browse files Browse the repository at this point in the history
  • Loading branch information
MauAraujo committed May 14, 2024
1 parent ff10a0d commit 0b1fb3d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 17 deletions.
26 changes: 17 additions & 9 deletions dashboard/src/main/home/project-settings/UsagePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 }>
>([]);
Expand All @@ -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);
Expand All @@ -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"),
});
}
Expand All @@ -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)
: "";
Expand All @@ -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")) {
Expand Down
25 changes: 17 additions & 8 deletions internal/billing/usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
)

const (
lagoBaseURL = "https://api.getlago.com"
defaultStarterCreditsCents = 500
defaultRewardAmountCents = 1000
maxReferralRewards = 10
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit 0b1fb3d

Please sign in to comment.