Skip to content

Commit

Permalink
[billing] Implement ReconcileInvoices
Browse files Browse the repository at this point in the history
  • Loading branch information
easyCZ authored and roboquat committed Sep 7, 2022
1 parent b663b56 commit 52279b1
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 12 deletions.
31 changes: 31 additions & 0 deletions components/usage/pkg/apiv1/billing.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,37 @@ func (s *BillingService) UpdateInvoices(ctx context.Context, in *v1.UpdateInvoic
return &v1.UpdateInvoicesResponse{}, nil
}

func (s *BillingService) ReconcileInvoices(ctx context.Context, in *v1.ReconcileInvoicesRequest) (*v1.ReconcileInvoicesResponse, error) {
balances, err := db.ListBalance(ctx, s.conn)
if err != nil {
log.WithError(err).Errorf("Failed to reconcile invoices.")
return nil, status.Errorf(codes.Internal, "Failed to reconcile invoices.")
}

creditSummaryForTeams := map[string]stripe.CreditSummary{}
for _, balance := range balances {
entity, id := balance.AttributionID.Values()

// TODO: Support updating of user attribution IDs
if entity != db.AttributionEntity_Team {
continue
}

creditSummaryForTeams[id] = stripe.CreditSummary{
Credits: int64(math.Ceil(balance.CreditCents.ToCredits())),
ReportID: "no-report",
}
}

err = s.stripeClient.UpdateUsage(ctx, creditSummaryForTeams)
if err != nil {
log.WithError(err).Errorf("Failed to udpate usage in stripe.")
return nil, status.Errorf(codes.Internal, "Failed to update usage in stripe")
}

return &v1.ReconcileInvoicesResponse{}, nil
}

func (s *BillingService) FinalizeInvoice(ctx context.Context, in *v1.FinalizeInvoiceRequest) (*v1.FinalizeInvoiceResponse, error) {
logger := log.WithField("invoice_id", in.GetInvoiceId())

Expand Down
12 changes: 0 additions & 12 deletions components/usage/pkg/stripe/stripe.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,18 +152,6 @@ func (c *Client) updateUsageForCustomer(ctx context.Context, customer *stripe.Cu
return nil, fmt.Errorf("failed to register usage for customer %q on subscription item %s", customer.Name, subscriptionItemId)
}

invoice, err := c.GetUpcomingInvoice(ctx, customer.ID)
if err != nil {
return nil, fmt.Errorf("failed to find upcoming invoice for customer %s: %w", customer.ID, err)
}

_, err = c.UpdateInvoiceMetadata(ctx, invoice.ID, map[string]string{
ReportIDMetadataKey: summary.ReportID,
})
if err != nil {
return nil, fmt.Errorf("failed to udpate invoice %s metadata with report ID: %w", invoice.ID, err)
}

return &UsageRecord{
SubscriptionItemID: subscriptionItemId,
Quantity: summary.Credits,
Expand Down

0 comments on commit 52279b1

Please sign in to comment.