diff --git a/components/usage/pkg/apiv1/billing.go b/components/usage/pkg/apiv1/billing.go index 6fd139de373bf2..5c3adc23b19707 100644 --- a/components/usage/pkg/apiv1/billing.go +++ b/components/usage/pkg/apiv1/billing.go @@ -108,7 +108,8 @@ func (s *BillingService) FinalizeInvoice(ctx context.Context, in *v1.FinalizeInv ID: uuid.New(), AttributionID: attributionID, Description: fmt.Sprintf("Invoice %s finalized in Stripe", invoice.ID), - CreditCents: db.NewCreditCents(float64(creditsOnInvoice)), + // Apply negative value of credits to reduce accrued credit usage + CreditCents: db.NewCreditCents(float64(-creditsOnInvoice)), EffectiveTime: db.NewVarcharTime(finalizedAt), Kind: db.InvoiceUsageKind, Draft: false, diff --git a/components/usage/pkg/stripe/stripe.go b/components/usage/pkg/stripe/stripe.go index 7066267577c7cb..56f9970b3b53c0 100644 --- a/components/usage/pkg/stripe/stripe.go +++ b/components/usage/pkg/stripe/stripe.go @@ -131,6 +131,16 @@ func (c *Client) findCustomers(ctx context.Context, query string) ([]*stripe.Cus } func (c *Client) updateUsageForCustomer(ctx context.Context, customer *stripe.Customer, credits int64) (*UsageRecord, error) { + if credits < 0 { + log.WithField("customer_id", customer.ID). + WithField("customer_name", customer.Name). + WithField("credits", credits). + Infof("Received request to update customer %s usage to negative value, updating to 0 instead.", customer.ID) + + // nullify any existing usage, but do not set it to negative value - negative invoice doesn't make sense... + credits = 0 + } + subscriptions := customer.Subscriptions.Data if len(subscriptions) != 1 { return nil, fmt.Errorf("customer has an unexpected number of subscriptions %v (expected 1, got %d)", subscriptions, len(subscriptions))