Skip to content

[Usage-based] Untie paid Stripe subscriptions from calendar months #14705

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions components/common-go/db/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"time"

"github.com/relvacode/iso8601"
"google.golang.org/protobuf/types/known/timestamppb"
)

func NewVarCharTime(t time.Time) VarcharTime {
Expand Down Expand Up @@ -129,3 +130,11 @@ const ISO8601Format = "2006-01-02T15:04:05.000Z"
func TimeToISO8601(t time.Time) string {
return t.UTC().Format(ISO8601Format)
}

func VarcharTimeToTimestamppb(t VarcharTime) *timestamppb.Timestamp {
if !t.IsSet() {
return nil
}

return timestamppb.New(t.Time())
}
3 changes: 0 additions & 3 deletions components/server/ee/src/user/stripe-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,15 +154,12 @@ export class StripeService {
taxInformation: customer.tax,
});
}
const startOfNextMonth = new Date(new Date().toISOString().slice(0, 7) + "-01"); // First day of this month (YYYY-MM-01)
startOfNextMonth.setMonth(startOfNextMonth.getMonth() + 1); // Add one month

await reportStripeOutcome("subscriptions_create", () => {
return this.getStripe().subscriptions.create({
customer: customer.id,
items: [{ price: priceId }],
automatic_tax: { enabled: isAutomaticTaxSupported },
billing_cycle_anchor: Math.round(startOfNextMonth.getTime() / 1000),
});
});
}
Expand Down
12 changes: 2 additions & 10 deletions components/usage/pkg/apiv1/usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,20 +191,12 @@ func (s *UsageService) GetCostCenter(ctx context.Context, in *v1.GetCostCenterRe
}

func dbCostCenterToAPI(c db.CostCenter) *v1.CostCenter {
NextBillingTime := timestamppb.New(c.NextBillingTime.Time())
if !c.NextBillingTime.IsSet() {
NextBillingTime = nil
}
BillingCycleStart := timestamppb.New(c.BillingCycleStart.Time())
if !c.BillingCycleStart.IsSet() {
BillingCycleStart = nil
}
return &v1.CostCenter{
AttributionId: string(c.ID),
SpendingLimit: c.SpendingLimit,
BillingStrategy: convertBillingStrategyToAPI(c.BillingStrategy),
NextBillingTime: NextBillingTime,
BillingCycleStart: BillingCycleStart,
NextBillingTime: common_db.VarcharTimeToTimestamppb(c.NextBillingTime),
BillingCycleStart: common_db.VarcharTimeToTimestamppb(c.BillingCycleStart),
}
}

Expand Down
15 changes: 6 additions & 9 deletions components/usage/pkg/db/cost_center.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,8 @@ func (c *CostCenterManager) UpdateCostCenter(ctx context.Context, newCC CostCent
}

newCC.BillingCycleStart = common_db.NewVarCharTime(now)
// we don't manage stripe billing cycle
newCC.NextBillingTime = common_db.VarcharTime{}
// set an informative nextBillingTime, even though we don't manage Stripe billing cycle
newCC.NextBillingTime = common_db.NewVarCharTime(now.AddDate(0, 1, 0))
}
} else if isTeam {
// Billing strategy is Other, and it remains unchanged
Expand All @@ -214,8 +214,8 @@ func (c *CostCenterManager) UpdateCostCenter(ctx context.Context, newCC CostCent
}

newCC.BillingCycleStart = common_db.NewVarCharTime(now)
// we don't manage stripe billing cycle
newCC.NextBillingTime = common_db.VarcharTime{}
// set an informative nextBillingTime, even though we don't manage Stripe billing cycle
newCC.NextBillingTime = common_db.NewVarCharTime(now.AddDate(0, 1, 0))
}
} else {
return CostCenter{}, status.Errorf(codes.InvalidArgument, "Unknown attribution entity %s", string(attributionID))
Expand Down Expand Up @@ -319,9 +319,6 @@ func (c *CostCenterManager) ResetUsage(ctx context.Context, cc CostCenter) (Cost

now := time.Now().UTC()

// Resetting the usage always resets the billing cycle start time
billingCycleStart := now

// Default to 1 month from now, if there's no nextBillingTime set on the record.
nextBillingTime := now.AddDate(0, 1, 0)
if cc.NextBillingTime.IsSet() {
Expand All @@ -334,12 +331,12 @@ func (c *CostCenterManager) ResetUsage(ctx context.Context, cc CostCenter) (Cost
return CostCenter{}, fmt.Errorf("failed to compute invocie usage record for AttributonID: %s: %w", cc.ID, err)
}

// All fields on the new cost center remain the same, except for CreationTime and NextBillingTime
// All fields on the new cost center remain the same, except for BillingCycleStart, NextBillingTime, and CreationTime
newCostCenter := CostCenter{
ID: cc.ID,
SpendingLimit: spendingLimit,
BillingStrategy: cc.BillingStrategy,
BillingCycleStart: common_db.NewVarCharTime(billingCycleStart),
BillingCycleStart: common_db.NewVarCharTime(now),
NextBillingTime: common_db.NewVarCharTime(nextBillingTime),
CreationTime: common_db.NewVarCharTime(now),
}
Expand Down
2 changes: 1 addition & 1 deletion components/usage/pkg/db/cost_center_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ func TestSaveCostCenterMovedToStripe(t *testing.T) {
teamCC, err = mnr.UpdateCostCenter(context.Background(), teamCC)
require.NoError(t, err)
require.Equal(t, db.CostCenter_Stripe, teamCC.BillingStrategy)
require.Equal(t, common_db.VarcharTime{}, teamCC.NextBillingTime)
require.Equal(t, teamCC.CreationTime.Time().AddDate(0, 1, 0), teamCC.NextBillingTime.Time())
require.Equal(t, int32(400050), teamCC.SpendingLimit)

teamCC.BillingStrategy = db.CostCenter_Other
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 @@ -338,8 +338,6 @@ func (c *Client) CreateSubscription(ctx context.Context, customerID string, pric
return nil, fmt.Errorf("no priceID specified")
}

startOfNextMonth := getStartOfNextMonth(time.Now())

params := &stripe.SubscriptionParams{
Customer: stripe.String(customerID),
Items: []*stripe.SubscriptionItemsParams{
Expand All @@ -350,7 +348,6 @@ func (c *Client) CreateSubscription(ctx context.Context, customerID string, pric
AutomaticTax: &stripe.SubscriptionAutomaticTaxParams{
Enabled: stripe.Bool(isAutomaticTaxSupported),
},
BillingCycleAnchor: stripe.Int64(startOfNextMonth.Unix()),
}

subscription, err := c.sc.Subscriptions.New(params)
Expand All @@ -361,15 +358,6 @@ func (c *Client) CreateSubscription(ctx context.Context, customerID string, pric
return subscription, err
}

func getStartOfNextMonth(t time.Time) time.Time {
currentYear, currentMonth, _ := t.Date()

firstOfMonth := time.Date(currentYear, currentMonth, 1, 0, 0, 0, 0, time.UTC)
startOfNextMonth := firstOfMonth.AddDate(0, 1, 0)

return startOfNextMonth
}

func (c *Client) SetDefaultPaymentForCustomer(ctx context.Context, customerID string, setupIntentId string) (*stripe.Customer, error) {
if customerID == "" {
return nil, fmt.Errorf("no customerID specified")
Expand Down
7 changes: 0 additions & 7 deletions components/usage/pkg/stripe/stripe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ package stripe
import (
"fmt"
"testing"
"time"

"github.com/gitpod-io/gitpod/usage/pkg/db"

Expand Down Expand Up @@ -91,9 +90,3 @@ func TestCustomerQueriesForTeamIds_MultipleQueries(t *testing.T) {
})
}
}

func TestStartOfNextMonth(t *testing.T) {
ts := time.Date(2022, 10, 1, 0, 0, 0, 0, time.UTC)

require.Equal(t, time.Date(2022, 11, 1, 0, 0, 0, 0, time.UTC), getStartOfNextMonth(ts))
}