Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

feature: add plans (#714)

Guilherme Oenning405c23c6b566
diff --git a/app/cmd/routes.go b/app/cmd/routes.go
index 4a8c3f9ce..5819a6fb3 100644
--- a/app/cmd/routes.go
+++ b/app/cmd/routes.go
@@ -147,10 +147,8 @@ func routes(r *web.Engine) *web.Engine {
//From this step, only Administrators are allowed
ui.Use(middlewares.IsAuthorized(models.RoleAdministrator))
- ui.Get("/admin/billing", handlers.BillingPage())
ui.Get("/admin/export", handlers.Page("Export · Site Settings", "", "Export.page"))
ui.Get("/admin/export/posts.csv", handlers.ExportPostsToCSV())
- ui.Post("/_api/admin/billing/paymentinfo", handlers.UpdatePaymentInfo())
ui.Post("/_api/admin/settings/general", handlers.UpdateSettings())
ui.Post("/_api/admin/settings/advanced", handlers.UpdateAdvancedSettings())
ui.Post("/_api/admin/settings/privacy", handlers.UpdatePrivacy())
@@ -158,6 +156,13 @@ func routes(r *web.Engine) *web.Engine {
ui.Post("/_api/admin/roles/:role/users", handlers.ChangeUserRole())
ui.Put("/_api/admin/users/:userID/block", handlers.BlockUser())
ui.Delete("/_api/admin/users/:userID/block", handlers.UnblockUser())
+
+ ui.Use(middlewares.RequireBillingEnabled())
+
+ ui.Get("/admin/billing", handlers.BillingPage())
+ ui.Post("/_api/admin/billing/paymentinfo", handlers.UpdatePaymentInfo())
+ ui.Post("/_api/admin/billing/subscription/:planID", handlers.BillingSubscribe())
+ ui.Delete("/_api/admin/billing/subscription/:planID", handlers.CancelBillingSubscription())
}
api := r.Group()
diff --git a/app/handlers/billing.go b/app/handlers/billing.go
index 5b170b2c1..12eb81151 100644
--- a/app/handlers/billing.go
+++ b/app/handlers/billing.go
@@ -3,20 +3,20 @@ package handlers
import (
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
- "github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/web"
)
// BillingPage is the billing settings page
func BillingPage() web.HandlerFunc {
return func(c web.Context) error {
- if !env.IsBillingEnabled() || c.Tenant().Billing == nil {
- return c.Redirect(c.BaseURL())
+ _, err := c.Services().Billing.CreateCustomer("")
+ if err != nil {
+ return err
}
- err := ensureStripeCustomerID(c)
+ err = c.Services().Tenants.UpdateBillingSettings(c.Tenant().Billing)
if err != nil {
- return c.Failure(err)
+ return err
}
paymentInfo, err := c.Services().Billing.GetPaymentInfo()
@@ -24,12 +24,24 @@ func BillingPage() web.HandlerFunc {
return c.Failure(err)
}
+ plans, err := c.Services().Billing.ListPlans()
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ tenantUserCount, err := c.Services().Users.Count()
+ if err != nil {
+ return c.Failure(err)
+ }
+
return c.Page(web.Props{
Title: "Billing · Site Settings",
ChunkName: "Billing.page",
Data: web.Map{
- "paymentInfo": paymentInfo,
- "countries": models.GetAllCountries(),
+ "tenantUserCount": tenantUserCount,
+ "plans": plans,
+ "paymentInfo": paymentInfo,
+ "countries": models.GetAllCountries(),
},
})
}
@@ -38,10 +50,6 @@ func BillingPage() web.HandlerFunc {
// UpdatePaymentInfo on stripe based on given input
func UpdatePaymentInfo() web.HandlerFunc {
return func(c web.Context) error {
- if c.Tenant().Billing == nil {
- return c.Unauthorized()
- }
-
input := new(actions.CreateEditBillingPaymentInfo)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
@@ -56,20 +64,57 @@ func UpdatePaymentInfo() web.HandlerFunc {
}
}
-func ensureStripeCustomerID(c web.Context) error {
- billing := c.Tenant().Billing
- if billing.StripeCustomerID == "" {
- customerID, err := c.Services().Billing.CreateCustomer("")
+// BillingSubscribe subscribes current tenant to given plan on stripe
+func BillingSubscribe() web.HandlerFunc {
+ return func(c web.Context) error {
+ var plan *models.BillingPlan
+ planID := c.Param("planID")
+
+ plan, err := c.Services().Billing.GetPlanByID(planID)
if err != nil {
- return err
+ return c.Failure(err)
}
- billing.StripeCustomerID = customerID
- err = c.Services().Tenants.UpdateBillingSettings(billing)
+ userCount, err := c.Services().Users.Count()
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ if plan.MaxUsers > 0 && userCount > plan.MaxUsers {
+ return c.Unauthorized()
+ }
+
+ err = c.Services().Billing.Subscribe(plan.ID)
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ err = c.Services().Tenants.UpdateBillingSettings(c.Tenant().Billing)
if err != nil {
return err
}
+ err = c.Services().Tenants.Activate(c.Tenant().ID)
+ if err != nil {
+ return err
+ }
+
+ return c.Ok(web.Map{})
}
+}
- return nil
+// CancelBillingSubscription cancels current subscription from current tenant
+func CancelBillingSubscription() web.HandlerFunc {
+ return func(c web.Context) error {
+ err := c.Services().Billing.CancelSubscription()
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ err = c.Services().Tenants.UpdateBillingSettings(c.Tenant().Billing)
+ if err != nil {
+ return err
+ }
+
+ return c.Ok(web.Map{})
+ }
}
diff --git a/app/middlewares/common.go b/app/middlewares/common.go
new file mode 100644
index 000000000..b3c9d8296
--- /dev/null
+++ b/app/middlewares/common.go
@@ -0,0 +1,18 @@
+package middlewares
+
+import (
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/web"
+)
+
+// RequireBillingEnabled returns 404 if billing is not enabled, otherwise it continues the chain
+func RequireBillingEnabled() web.MiddlewareFunc {
+ return func(next web.HandlerFunc) web.HandlerFunc {
+ return func(c web.Context) error {
+ if !env.IsBillingEnabled() || c.Tenant().Billing == nil {
+ return c.NotFound()
+ }
+ return next(c)
+ }
+ }
+}
diff --git a/app/models/billing.go b/app/models/billing.go
index 670f2ac62..349a5d0a0 100644
--- a/app/models/billing.go
+++ b/app/models/billing.go
@@ -37,3 +37,13 @@ type PaymentInfo struct {
AddressState string `json:"addressState"`
AddressPostalCode string `json:"addressPostalCode"`
}
+
+// BillingPlan is the model for billing plan from Stripe
+type BillingPlan struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ MaxUsers int `json:"maxUsers"`
+ Price int64 `json:"price"`
+ Interval string `json:"interval"`
+}
diff --git a/app/models/identity.go b/app/models/identity.go
index 512323d11..0d19595e3 100644
--- a/app/models/identity.go
+++ b/app/models/identity.go
@@ -33,8 +33,11 @@ var (
//TenantBilling has all the billing information of given tenant
type TenantBilling struct {
- StripeCustomerID string
- TrialEndsAt time.Time `json:"trialEndsAt"`
+ StripeCustomerID string
+ StripeSubscriptionID string
+ StripePlanID string `json:"stripePlanID"`
+ TrialEndsAt time.Time `json:"trialEndsAt"`
+ SubscriptionEndsAt *time.Time `json:"subscriptionEndsAt,omitempty"`
}
//Upload represents a file that has been uploaded to Fider
diff --git a/app/pkg/billing/stripe.go b/app/pkg/billing/stripe.go
index 8df83c6a7..921b1c72d 100644
--- a/app/pkg/billing/stripe.go
+++ b/app/pkg/billing/stripe.go
@@ -2,7 +2,10 @@ package billing
import (
"fmt"
+ "sort"
"strconv"
+ "sync"
+ "time"
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/env"
@@ -11,17 +14,19 @@ import (
"github.com/stripe/stripe-go/client"
)
-var sc *client.API
+var stripeClient *client.API
+var mu sync.RWMutex
+var plans []*models.BillingPlan
func init() {
stripe.LogLevel = 0
- sc = &client.API{}
- sc.Init(env.Config.Stripe.SecretKey, nil)
+ stripeClient = &client.API{}
+ stripeClient.Init(env.Config.Stripe.SecretKey, nil)
}
// Client is a billing client wrapper for Stripe
type Client struct {
- sc *client.API
+ stripe *client.API
tenant *models.Tenant
user *models.User
}
@@ -29,7 +34,7 @@ type Client struct {
// NewClient creates a new billing client
func NewClient() *Client {
return &Client{
- sc: sc,
+ stripe: stripeClient,
}
}
@@ -43,7 +48,7 @@ func (c *Client) SetCurrentUser(user *models.User) {
c.user = user
}
-// CreateCustomer on stripe
+// CreateCustomer on Stripe
func (c *Client) CreateCustomer(email string) (string, error) {
if c.tenant.Billing == nil {
return "", errors.New("Tenant doesn't have a billing record")
@@ -55,16 +60,30 @@ func (c *Client) CreateCustomer(email string) (string, error) {
Description: stripe.String(customerDesc(c.tenant)),
}
params.AddMetadata("tenant_id", strconv.Itoa(c.tenant.ID))
- customer, err := c.sc.Customers.New(params)
+ customer, err := c.stripe.Customers.New(params)
if err != nil {
return "", errors.Wrap(err, "failed to create Stripe customer")
}
+ c.tenant.Billing.StripeCustomerID = customer.ID
return customer.ID, nil
}
return c.tenant.Billing.StripeCustomerID, nil
}
+// DeleteCustomer on Stripe
+func (c *Client) DeleteCustomer() error {
+ if !env.IsTest() {
+ return errors.New("Stripe customer can only be deleted on test mode")
+ }
+
+ _, err := c.stripe.Customers.Del(c.tenant.Billing.StripeCustomerID, &stripe.CustomerParams{})
+ if err != nil {
+ return errors.Wrap(err, "failed to delete Stripe customer")
+ }
+ return nil
+}
+
// GetPaymentInfo from a stripe card
func (c *Client) GetPaymentInfo() (*models.PaymentInfo, error) {
if c.tenant.Billing == nil || c.tenant.Billing.StripeCustomerID == "" {
@@ -73,7 +92,7 @@ func (c *Client) GetPaymentInfo() (*models.PaymentInfo, error) {
customerID := c.tenant.Billing.StripeCustomerID
- customer, err := c.sc.Customers.Get(customerID, &stripe.CustomerParams{})
+ customer, err := c.stripe.Customers.Get(customerID, &stripe.CustomerParams{})
if err != nil {
return nil, errors.Wrap(err, "failed to get customer")
}
@@ -86,7 +105,7 @@ func (c *Client) GetPaymentInfo() (*models.PaymentInfo, error) {
return nil, nil
}
- card, err := c.sc.Cards.Get(customer.DefaultSource.ID, &stripe.CardParams{
+ card, err := c.stripe.Cards.Get(customer.DefaultSource.ID, &stripe.CardParams{
Customer: stripe.String(customerID),
})
if err != nil {
@@ -113,7 +132,35 @@ func (c *Client) GetPaymentInfo() (*models.PaymentInfo, error) {
return info, nil
}
-// UpdatePaymentInfo creates or updates customer payment info on stripe
+// ClearPaymentInfo removes all payment information from stripe
+func (c *Client) ClearPaymentInfo() error {
+ current, err := c.GetPaymentInfo()
+ if err != nil {
+ return err
+ }
+
+ if current != nil {
+ customerID := c.tenant.Billing.StripeCustomerID
+ _, err = c.stripe.Customers.Update(customerID, &stripe.CustomerParams{
+ Email: stripe.String(""),
+ })
+ if err != nil {
+ return errors.Wrap(err, "failed to delete customer billing email")
+ }
+ if current.StripeCardID != "" {
+ _, err = c.stripe.Cards.Del(current.StripeCardID, &stripe.CardParams{
+ Customer: stripe.String(customerID),
+ })
+ if err != nil {
+ return errors.Wrap(err, "failed to delete customer card")
+ }
+ }
+ }
+
+ return nil
+}
+
+// UpdatePaymentInfo creates or updates customer payment info on Stripe
func (c *Client) UpdatePaymentInfo(input *models.CreateEditBillingPaymentInfo) error {
customerID := c.tenant.Billing.StripeCustomerID
current, err := c.GetPaymentInfo()
@@ -123,7 +170,7 @@ func (c *Client) UpdatePaymentInfo(input *models.CreateEditBillingPaymentInfo) e
// email is different, update it
if current == nil || current.Email != input.Email {
- _, err = c.sc.Customers.Update(customerID, &stripe.CustomerParams{
+ _, err = c.stripe.Customers.Update(customerID, &stripe.CustomerParams{
Email: stripe.String(input.Email),
Description: stripe.String(customerDesc(c.tenant)),
})
@@ -134,7 +181,7 @@ func (c *Client) UpdatePaymentInfo(input *models.CreateEditBillingPaymentInfo) e
// new card, just create it
if current == nil || current.StripeCardID == "" {
- _, err = c.sc.Cards.New(&stripe.CardParams{
+ _, err = c.stripe.Cards.New(&stripe.CardParams{
Customer: stripe.String(customerID),
Token: stripe.String(input.Card.Token),
})
@@ -146,7 +193,7 @@ func (c *Client) UpdatePaymentInfo(input *models.CreateEditBillingPaymentInfo) e
// replacing card, create new and delete old
if input.Card != nil && input.Card.Token != "" {
- _, err = c.sc.Cards.New(&stripe.CardParams{
+ _, err = c.stripe.Cards.New(&stripe.CardParams{
Customer: stripe.String(customerID),
Token: stripe.String(input.Card.Token),
})
@@ -154,7 +201,7 @@ func (c *Client) UpdatePaymentInfo(input *models.CreateEditBillingPaymentInfo) e
return errors.Wrap(err, "failed to create new stripe card")
}
- _, err = c.sc.Cards.Del(current.StripeCardID, &stripe.CardParams{
+ _, err = c.stripe.Cards.Del(current.StripeCardID, &stripe.CardParams{
Customer: stripe.String(customerID),
Token: stripe.String(input.Card.Token),
})
@@ -165,7 +212,7 @@ func (c *Client) UpdatePaymentInfo(input *models.CreateEditBillingPaymentInfo) e
}
// updating card, just update current card
- _, err = c.sc.Cards.Update(current.StripeCardID, &stripe.CardParams{
+ _, err = c.stripe.Cards.Update(current.StripeCardID, &stripe.CardParams{
Customer: stripe.String(customerID),
Name: stripe.String(input.Name),
AddressCity: stripe.String(input.AddressCity),
@@ -184,3 +231,108 @@ func (c *Client) UpdatePaymentInfo(input *models.CreateEditBillingPaymentInfo) e
func customerDesc(tenant *models.Tenant) string {
return fmt.Sprintf("%s [%s]", tenant.Name, tenant.Subdomain)
}
+
+// GetPlanByID return a plan by its ID
+func (c *Client) GetPlanByID(planID string) (*models.BillingPlan, error) {
+ plans, err := c.ListPlans()
+ if err != nil {
+ return nil, err
+ }
+
+ for _, plan := range plans {
+ if plan.ID == planID {
+ return plan, nil
+ }
+ }
+ return nil, errors.New("failed to get plan by id: " + planID)
+}
+
+// ListPlans on Stripe
+func (c *Client) ListPlans() ([]*models.BillingPlan, error) {
+ if plans != nil {
+ return plans, nil
+ }
+
+ mu.Lock()
+ defer mu.Unlock()
+
+ if plans == nil {
+ plans = make([]*models.BillingPlan, 0)
+ it := c.stripe.Plans.List(&stripe.PlanListParams{
+ Active: stripe.Bool(true),
+ })
+ for it.Next() {
+ plan := it.Plan()
+ maxUsers, _ := strconv.Atoi(plan.Metadata["max_users"])
+ plans = append(plans, &models.BillingPlan{
+ ID: plan.ID,
+ Name: plan.Nickname,
+ Description: plan.Metadata["description"],
+ MaxUsers: maxUsers,
+ Price: plan.Amount,
+ Interval: string(plan.Interval),
+ })
+ }
+ if err := it.Err(); err != nil {
+ return nil, err
+ }
+ sort.Slice(plans, func(i, j int) bool {
+ return plans[i].Price < plans[j].Price
+ })
+ }
+
+ return plans, nil
+}
+
+// Subscribe current tenant to given plan on Stripe
+func (c *Client) Subscribe(planID string) error {
+ customerID := c.tenant.Billing.StripeCustomerID
+ if c.tenant.Billing.StripeSubscriptionID != "" {
+ sub, err := c.stripe.Subscriptions.Get(c.tenant.Billing.StripeSubscriptionID, nil)
+ if err != nil {
+ return errors.Wrap(err, "failed to get stripe subscription")
+ }
+ sub, err = c.stripe.Subscriptions.Update(c.tenant.Billing.StripeSubscriptionID, &stripe.SubscriptionParams{
+ CancelAtPeriodEnd: stripe.Bool(false),
+ Items: []*stripe.SubscriptionItemsParams{
+ {
+ ID: stripe.String(sub.Items.Data[0].ID),
+ Plan: stripe.String(planID),
+ },
+ },
+ })
+ if err != nil {
+ return errors.Wrap(err, "failed to update stripe subscription")
+ }
+ c.tenant.Billing.SubscriptionEndsAt = nil
+ } else {
+ sub, err := c.stripe.Subscriptions.New(&stripe.SubscriptionParams{
+ Customer: stripe.String(customerID),
+ Items: []*stripe.SubscriptionItemsParams{
+ {
+ Plan: stripe.String(planID),
+ },
+ },
+ })
+ if err != nil {
+ return errors.Wrap(err, "failed to create stripe subscription")
+ }
+ c.tenant.Billing.StripeSubscriptionID = sub.ID
+ }
+
+ c.tenant.Billing.StripePlanID = planID
+ return nil
+}
+
+// CancelSubscription from current tenant on Stripe
+func (c *Client) CancelSubscription() error {
+ sub, err := c.stripe.Subscriptions.Update(c.tenant.Billing.StripeSubscriptionID, &stripe.SubscriptionParams{
+ CancelAtPeriodEnd: stripe.Bool(true),
+ })
+ if err != nil {
+ return errors.Wrap(err, "failed to cancel stripe subscription")
+ }
+ endDate := time.Unix(sub.CurrentPeriodEnd, 0)
+ c.tenant.Billing.SubscriptionEndsAt = &endDate
+ return nil
+}
diff --git a/app/pkg/billing/stripe_test.go b/app/pkg/billing/stripe_test.go
new file mode 100644
index 000000000..99f5f4a63
--- /dev/null
+++ b/app/pkg/billing/stripe_test.go
@@ -0,0 +1,156 @@
+package billing_test
+
+import (
+ "testing"
+
+ "github.com/getfider/fider/app/pkg/env"
+
+ "github.com/getfider/fider/app/pkg/billing"
+
+ "github.com/getfider/fider/app/models"
+ . "github.com/getfider/fider/app/pkg/assert"
+)
+
+func TestCreateCustomer(t *testing.T) {
+ RegisterT(t)
+ if !env.IsBillingEnabled() {
+ return
+ }
+
+ tenant := &models.Tenant{
+ ID: 2,
+ Name: "Game Inc.",
+ Subdomain: "gameinc",
+ Billing: &models.TenantBilling{},
+ }
+ client := billing.NewClient()
+ client.SetCurrentTenant(tenant)
+ customerID, err := client.CreateCustomer("")
+ Expect(err).IsNil()
+ Expect(customerID).IsNotEmpty()
+ Expect(customerID).Equals(tenant.Billing.StripeCustomerID)
+
+ err = client.DeleteCustomer()
+ Expect(err).IsNil()
+}
+
+var forUnitTestingTenant = &models.Tenant{
+ ID: 5,
+ Name: "For Unit Testing (DO NOT DELETE)",
+ Subdomain: "unittesting",
+ Billing: &models.TenantBilling{
+ StripeCustomerID: "cus_EICBuXBIkhI2EV",
+ },
+}
+
+func TestUpdatePaymentInfo(t *testing.T) {
+ RegisterT(t)
+ if !env.IsBillingEnabled() {
+ return
+ }
+
+ var firstCardID string
+
+ client := billing.NewClient()
+ client.SetCurrentTenant(forUnitTestingTenant)
+
+ err := client.ClearPaymentInfo()
+ Expect(err).IsNil()
+
+ //Creating a new card
+ err = client.UpdatePaymentInfo(&models.CreateEditBillingPaymentInfo{
+ Email: "[email protected]",
+ Card: &models.CreateEditBillingPaymentInfoCard{
+ Token: "tok_visa",
+ },
+ })
+ Expect(err).IsNil()
+
+ info, err := client.GetPaymentInfo()
+ Expect(err).IsNil()
+ firstCardID = info.StripeCardID
+
+ Expect(info.StripeCardID).IsNotEmpty()
+ Expect(info.Email).Equals("[email protected]")
+ Expect(info.CardBrand).Equals("Visa")
+ Expect(info.CardCountry).Equals("US")
+ Expect(info.CardLast4).Equals("4242")
+ Expect(int(info.CardExpMonth)).Equals(1)
+ Expect(int(info.CardExpYear)).Equals(2020)
+ Expect(info.Name).Equals("")
+ Expect(info.AddressLine1).Equals("")
+ Expect(info.AddressLine2).Equals("")
+ Expect(info.AddressCity).Equals("")
+ Expect(info.AddressState).Equals("")
+ Expect(info.AddressPostalCode).Equals("")
+ Expect(info.AddressCountry).Equals("")
+
+ //Update existing card
+ err = client.UpdatePaymentInfo(&models.CreateEditBillingPaymentInfo{
+ Email: "[email protected]",
+ Name: "Jon Snow",
+ AddressLine1: "Street 1",
+ AddressLine2: "Av. ABC",
+ AddressCity: "New York",
+ AddressState: "NYC",
+ AddressPostalCode: "12098",
+ AddressCountry: "US",
+ })
+ Expect(err).IsNil()
+
+ info, err = client.GetPaymentInfo()
+ Expect(err).IsNil()
+ Expect(info.Name).Equals("Jon Snow")
+ Expect(info.CardLast4).Equals("4242")
+ Expect(info.AddressLine1).Equals("Street 1")
+ Expect(info.AddressLine2).Equals("Av. ABC")
+ Expect(info.AddressCity).Equals("New York")
+ Expect(info.AddressState).Equals("NYC")
+ Expect(info.AddressPostalCode).Equals("12098")
+ Expect(info.AddressCountry).Equals("US")
+
+ //Replace card
+ err = client.UpdatePaymentInfo(&models.CreateEditBillingPaymentInfo{
+ Email: "[email protected]",
+ Card: &models.CreateEditBillingPaymentInfoCard{
+ Token: "tok_br",
+ },
+ })
+ Expect(err).IsNil()
+
+ info, err = client.GetPaymentInfo()
+ Expect(err).IsNil()
+ Expect(info.StripeCardID).IsNotEmpty()
+ Expect(info.StripeCardID).NotEquals(firstCardID)
+ Expect(info.Email).Equals("[email protected]")
+ Expect(info.CardBrand).Equals("Visa")
+ Expect(info.CardCountry).Equals("BR")
+ Expect(info.CardLast4).Equals("0002")
+ Expect(int(info.CardExpMonth)).Equals(1)
+ Expect(int(info.CardExpYear)).Equals(2020)
+ Expect(info.Name).Equals("")
+ Expect(info.AddressLine1).Equals("")
+ Expect(info.AddressLine2).Equals("")
+ Expect(info.AddressCity).Equals("")
+ Expect(info.AddressState).Equals("")
+ Expect(info.AddressPostalCode).Equals("")
+ Expect(info.AddressCountry).Equals("")
+}
+
+func TestListPlans(t *testing.T) {
+ RegisterT(t)
+ if !env.IsBillingEnabled() {
+ return
+ }
+
+ client := billing.NewClient()
+ plans, err := client.ListPlans()
+ Expect(err).IsNil()
+ Expect(plans).HasLen(3)
+ Expect(plans[0].ID).Equals("plan_EIE1LpQIzPXxOn")
+ Expect(plans[0].Name).Equals("Fider Starter (monthly)")
+ Expect(plans[1].ID).Equals("plan_DoK187GZcnFpKY")
+ Expect(plans[1].Name).Equals("Fider Business (monthly)")
+ Expect(plans[2].ID).Equals("plan_DpN9SkJMjNTvLd")
+ Expect(plans[2].Name).Equals("Fider Business (yearly)")
+}
diff --git a/app/storage/inmemory/user.go b/app/storage/inmemory/user.go
index ed2715277..506420b7b 100644
--- a/app/storage/inmemory/user.go
+++ b/app/storage/inmemory/user.go
@@ -202,3 +202,8 @@ func (s *UserStorage) Unblock(userID int) error {
}
return nil
}
+
+// Count returns the total number of registered users
+func (s *UserStorage) Count() (int, error) {
+ return len(s.users), nil
+}
diff --git a/app/storage/postgres/tenant.go b/app/storage/postgres/tenant.go
index 7c22cfba7..e567cc0d2 100644
--- a/app/storage/postgres/tenant.go
+++ b/app/storage/postgres/tenant.go
@@ -44,8 +44,13 @@ func (t *dbTenant) toModel() *models.Tenant {
if t.Billing != nil && t.Billing.TrialEndsAt.Valid {
tenant.Billing = &models.TenantBilling{
- TrialEndsAt: t.Billing.TrialEndsAt.Time,
- StripeCustomerID: t.Billing.StripeCustomerID.String,
+ TrialEndsAt: t.Billing.TrialEndsAt.Time,
+ StripeCustomerID: t.Billing.StripeCustomerID.String,
+ StripeSubscriptionID: t.Billing.StripeSubscriptionID.String,
+ StripePlanID: t.Billing.StripePlanID.String,
+ }
+ if t.Billing.SubscriptionEndsAt.Valid {
+ tenant.Billing.SubscriptionEndsAt = &t.Billing.SubscriptionEndsAt.Time
}
}
@@ -53,8 +58,11 @@ func (t *dbTenant) toModel() *models.Tenant {
}
type dbTenantBilling struct {
- StripeCustomerID dbx.NullString `db:"stripe_customer_id"`
- TrialEndsAt dbx.NullTime `db:"trial_ends_at"`
+ StripeCustomerID dbx.NullString `db:"stripe_customer_id"`
+ StripeSubscriptionID dbx.NullString `db:"stripe_subscription_id"`
+ StripePlanID dbx.NullString `db:"stripe_plan_id"`
+ TrialEndsAt dbx.NullTime `db:"trial_ends_at"`
+ SubscriptionEndsAt dbx.NullTime `db:"subscription_ends_at"`
}
type dbEmailVerification struct {
@@ -187,7 +195,10 @@ func (s *TenantStorage) First() (*models.Tenant, error) {
err := s.trx.Get(&tenant, `
SELECT t.id, t.name, t.subdomain, t.cname, t.invitation, t.welcome_message, t.status, t.is_private, t.logo_bkey, t.custom_css,
tb.trial_ends_at AS billing_trial_ends_at,
- tb.stripe_customer_id AS billing_stripe_customer_id
+ tb.subscription_ends_at AS billing_subscription_ends_at,
+ tb.stripe_customer_id AS billing_stripe_customer_id,
+ tb.stripe_plan_id AS billing_stripe_plan_id,
+ tb.stripe_subscription_id AS billing_stripe_subscription_id
FROM tenants t
LEFT JOIN tenants_billing tb
ON tb.tenant_id = t.id
@@ -207,7 +218,10 @@ func (s *TenantStorage) GetByDomain(domain string) (*models.Tenant, error) {
err := s.trx.Get(&tenant, `
SELECT t.id, t.name, t.subdomain, t.cname, t.invitation, t.welcome_message, t.status, t.is_private, t.logo_bkey, t.custom_css,
tb.trial_ends_at AS billing_trial_ends_at,
- tb.stripe_customer_id AS billing_stripe_customer_id
+ tb.subscription_ends_at AS billing_subscription_ends_at,
+ tb.stripe_customer_id AS billing_stripe_customer_id,
+ tb.stripe_plan_id AS billing_stripe_plan_id,
+ tb.stripe_subscription_id AS billing_stripe_subscription_id
FROM tenants t
LEFT JOIN tenants_billing tb
ON tb.tenant_id = t.id
@@ -243,8 +257,8 @@ func (s *TenantStorage) UpdateSettings(settings *models.UpdateTenantSettings) er
// UpdateBillingSettings of current tenant
func (s *TenantStorage) UpdateBillingSettings(billing *models.TenantBilling) error {
- query := "UPDATE tenants_billing SET stripe_customer_id = $1 WHERE tenant_id = $2"
- _, err := s.trx.Execute(query, billing.StripeCustomerID, s.current.ID)
+ query := "UPDATE tenants_billing SET stripe_customer_id = $1, stripe_plan_id = $2, stripe_subscription_id = $3, subscription_ends_at = $4 WHERE tenant_id = $5"
+ _, err := s.trx.Execute(query, billing.StripeCustomerID, billing.StripePlanID, billing.StripeSubscriptionID, billing.SubscriptionEndsAt, s.current.ID)
if err != nil {
return errors.Wrap(err, "failed update tenant billing settings")
}
diff --git a/app/storage/postgres/user.go b/app/storage/postgres/user.go
index 08eacf95b..2ccc13eda 100644
--- a/app/storage/postgres/user.go
+++ b/app/storage/postgres/user.go
@@ -379,3 +379,13 @@ func (s *UserStorage) Unblock(userID int) error {
}
return nil
}
+
+// Count returns the total number of registered users
+func (s *UserStorage) Count() (int, error) {
+ var count int
+ err := s.trx.Scalar(&count, "SELECT COUNT(*) FROM users WHERE tenant_id = $1", s.tenant.ID)
+ if err != nil {
+ return 0, errors.Wrap(err, "failed to count users")
+ }
+ return count, nil
+}
diff --git a/app/storage/storage.go b/app/storage/storage.go
index dc57fb5da..f0547b9d6 100644
--- a/app/storage/storage.go
+++ b/app/storage/storage.go
@@ -65,6 +65,7 @@ type User interface {
RegenerateAPIKey() (string, error)
Block(userID int) error
Unblock(userID int) error
+ Count() (int, error)
}
// Tenant contains read and write operations for tenants
diff --git a/public/components/common/Modal.scss b/public/components/common/Modal.scss
index 12ec29fc3..8439f7da4 100644
--- a/public/components/common/Modal.scss
+++ b/public/components/common/Modal.scss
@@ -77,10 +77,6 @@
.c-modal-content {
padding: 15px 20px;
- img {
- max-width: 90vw;
- max-height: 80vh;
- }
}
.c-modal-footer {
diff --git a/public/components/common/Moment.tsx b/public/components/common/Moment.tsx
index 20aaaf3c1..9baf36083 100644
--- a/public/components/common/Moment.tsx
+++ b/public/components/common/Moment.tsx
@@ -3,6 +3,7 @@ import { formatDate, timeSince } from "@fider/services";
interface MomentText {
date: Date | string;
+ format?: "full" | "timeSince";
}
export const Moment = (props: MomentText) => {
@@ -10,11 +11,13 @@ export const Moment = (props: MomentText) => {
return <span />;
}
+ const format = props.format || "timeSince";
+
const now = new Date();
const date = props.date instanceof Date ? props.date : new Date(props.date);
const diff = (now.getTime() - date.getTime()) / (60 * 60 * 24 * 1000);
- const display = diff >= 365 ? formatDate(props.date) : timeSince(now, date);
+ const display = format === "full" || diff >= 365 ? formatDate(props.date) : timeSince(now, date);
return (
<span className="date" title={formatDate(props.date)}>
diff --git a/public/components/common/form/ImageViewer.scss b/public/components/common/form/ImageViewer.scss
index db5bbeac8..5910ea605 100644
--- a/public/components/common/form/ImageViewer.scss
+++ b/public/components/common/form/ImageViewer.scss
@@ -10,4 +10,10 @@
+ .c-image-viewer {
margin-left: 10px;
}
+}
+.c-image-viewer-modal {
+ img {
+ max-width: 90vw;
+ max-height: 80vh;
+ }
}
\ No newline at end of file
diff --git a/public/components/common/form/ImageViewer.tsx b/public/components/common/form/ImageViewer.tsx
index 045886758..f2ce16eff 100644
--- a/public/components/common/form/ImageViewer.tsx
+++ b/public/components/common/form/ImageViewer.tsx
@@ -45,7 +45,7 @@ export class ImageViewer extends React.Component<ImageViewerProps, ImageViewerSt
private modal() {
return (
- <Modal.Window isOpen={this.state.showModal} center={false} size="fluid">
+ <Modal.Window className="c-image-viewer-modal" isOpen={this.state.showModal} center={false} size="fluid">
<Modal.Content>
{!this.state.loadedPreview && <Loader />}
<img onLoad={this.onPreviewLoad} src={uploadedImageURL(this.props.bkey, 1500)} />
diff --git a/public/models/billing.ts b/public/models/billing.ts
index 255938857..b624b3106 100644
--- a/public/models/billing.ts
+++ b/public/models/billing.ts
@@ -12,3 +12,12 @@ export interface PaymentInfo {
addressState: string;
addressPostalCode: string;
}
+
+export interface BillingPlan {
+ id: string;
+ name: string;
+ description: string;
+ maxUsers: number;
+ price: number;
+ interval: "month" | "year";
+}
diff --git a/public/models/identity.ts b/public/models/identity.ts
index 6dca2df9d..a621043b1 100644
--- a/public/models/identity.ts
+++ b/public/models/identity.ts
@@ -9,6 +9,8 @@ export interface Tenant {
isPrivate: boolean;
logoBlobKey: string;
billing?: {
+ stripePlanID: string;
+ subscriptionEndsAt: string;
trialEndsAt: string;
};
}
diff --git a/public/pages/Administration/components/BillingPlanPanel.scss b/public/pages/Administration/components/BillingPlanPanel.scss
new file mode 100644
index 000000000..e69de29bb
diff --git a/public/pages/Administration/components/BillingPlanPanel.tsx b/public/pages/Administration/components/BillingPlanPanel.tsx
new file mode 100644
index 000000000..afbdaf08c
--- /dev/null
+++ b/public/pages/Administration/components/BillingPlanPanel.tsx
@@ -0,0 +1,215 @@
+import "./BillingPlanPanel.scss";
+
+import React from "react";
+import { Segment, Button, Moment, Modal, ButtonClickEvent } from "@fider/components";
+import { BillingPlan } from "@fider/models";
+import { Fider, actions } from "@fider/services";
+
+interface BillingPlanOptionProps {
+ tenantUserCount: number;
+ disabled: boolean;
+ plan: BillingPlan;
+ currentPlan?: BillingPlan;
+ onSubscribe: (plan: BillingPlan) => Promise<void>;
+ onCancel: (plan: BillingPlan) => Promise<void>;
+}
+
+const BillingPlanOption = (props: BillingPlanOptionProps) => {
+ const billing = Fider.session.tenant.billing!;
+ return (
+ <div className="col-md-4">
+ <Segment className="l-plan">
+ <p className="l-title">{props.plan.name}</p>
+ <p className="l-description">{props.plan.description}</p>
+ <p>
+ <span className="l-dollar">$</span>
+ <span className="l-price">{props.plan.price / 100}</span>
+ <span className="l-interval">/{props.plan.interval}</span>
+ </p>
+ {billing.stripePlanID === props.plan.id && !billing.subscriptionEndsAt && (
+ <>
+ <p>
+ <Button disabled={props.disabled} color="danger" onClick={props.onCancel.bind(undefined, props.plan)}>
+ Cancel
+ </Button>
+ </p>
+ <p className="info">You are subscribed to this plan.</p>
+ </>
+ )}
+ {(billing.stripePlanID !== props.plan.id || !!billing.subscriptionEndsAt) && (
+ <>
+ <p>
+ <Button
+ disabled={props.disabled || (props.plan.maxUsers > 0 && props.tenantUserCount > props.plan.maxUsers)}
+ onClick={props.onSubscribe.bind(undefined, props.plan)}
+ >
+ Subscribe
+ </Button>
+ </p>
+ </>
+ )}
+ {props.plan.maxUsers > 0 && (
+ <p className="info">
+ You have <strong>{props.tenantUserCount}</strong> tracked users.
+ </p>
+ )}
+ </Segment>
+ </div>
+ );
+};
+
+interface BillingPlanPanelProps {
+ tenantUserCount: number;
+ disabled: boolean;
+ plans: BillingPlan[];
+}
+
+interface BillingPlanPanelState {
+ confirmPlan?: BillingPlan;
+ action?: "" | "subscribe" | "cancel";
+}
+
+export class BillingPlanPanel extends React.Component<BillingPlanPanelProps, BillingPlanPanelState> {
+ constructor(props: BillingPlanPanelProps) {
+ super(props);
+ this.state = {};
+ }
+
+ private onSubscribe = async (plan: BillingPlan) => {
+ this.setState({
+ confirmPlan: plan,
+ action: "subscribe"
+ });
+ };
+
+ private onCancel = async (plan: BillingPlan) => {
+ this.setState({
+ confirmPlan: plan,
+ action: "cancel"
+ });
+ };
+
+ private confirm = async (e: ButtonClickEvent) => {
+ e.preventEnable();
+
+ if (this.state.action && this.state.confirmPlan) {
+ const action = this.state.action === "subscribe" ? actions.billingSubscribe : actions.cancelBillingSubscription;
+ const result = await action(this.state.confirmPlan.id);
+ if (result.ok) {
+ location.reload();
+ }
+ }
+ };
+
+ private closeModal = async () => {
+ this.setState({
+ action: "",
+ confirmPlan: undefined
+ });
+ };
+
+ private getCurrentPlan(): BillingPlan | undefined {
+ const filtered = this.props.plans.filter(x => x.id === Fider.session.tenant.billing!.stripePlanID);
+ if (filtered.length > 0) {
+ return filtered[0];
+ }
+ }
+
+ public render() {
+ const billing = Fider.session.tenant.billing!;
+ const currentPlan = this.getCurrentPlan();
+ const trialExpired = new Date(billing.trialEndsAt) <= new Date();
+
+ return (
+ <>
+ <Modal.Window canClose={true} isOpen={!!this.state.action} center={false} onClose={this.closeModal}>
+ {this.state.action === "subscribe" && <Modal.Header>Subscribe</Modal.Header>}
+ {this.state.action === "cancel" && <Modal.Header>Cancel Subscription</Modal.Header>}
+ <Modal.Content>
+ {this.state.action === "subscribe" && (
+ <>
+ <p>
+ You'll be billed a total of{" "}
+ <strong>
+ ${this.state.confirmPlan!.price / 100} per {this.state.confirmPlan!.interval}
+ </strong>{" "}
+ on your card.
+ </p>
+ <ul>
+ <li>You can cancel it at any time.</li>
+ <li>You can upgrade/downgrade it at any time.</li>
+ </ul>
+ </>
+ )}
+ {this.state.action === "cancel" && (
+ <>
+ <p>You're about to cancel your subscription. Please review the following before continuing.</p>
+ <ul>
+ <li>Canceling the subscription will pause any further billing on your card.</li>
+ <li>You'll be able to use the service until the end of current period.</li>
+ <li>You can re-subscribe at any time.</li>
+ <li>No refunds will be given.</li>
+ </ul>
+ <strong>Are you sure?</strong>
+ </>
+ )}
+ </Modal.Content>
+ <Modal.Footer>
+ <Button
+ color={this.state.action === "subscribe" ? "positive" : "danger"}
+ size="tiny"
+ onClick={this.confirm}
+ >
+ {this.state.action === "subscribe" && "Confirm"}
+ {this.state.action === "cancel" && "Yes"}
+ </Button>
+ <Button color="cancel" size="tiny" onClick={this.closeModal}>
+ {this.state.action === "subscribe" && "Cancel"}
+ {this.state.action === "cancel" && "No"}
+ </Button>
+ </Modal.Footer>
+ </Modal.Window>
+
+ <Segment className="l-billing-plans">
+ <h4>Plans</h4>
+ {!billing.stripePlanID && (
+ <p className="info">
+ You don't have any active subscription.
+ {!trialExpired && (
+ <>
+ Your trial period ends at{" "}
+ <strong>
+ <Moment date={billing.trialEndsAt} format="full" />
+ </strong>
+ . Subscribe to a plan and avoid a service interruption.
+ </>
+ )}
+ </p>
+ )}
+ {currentPlan && !!billing.subscriptionEndsAt && (
+ <p className="info">
+ Your <strong>{currentPlan.name}</strong> ends at{" "}
+ <strong>
+ <Moment date={billing.subscriptionEndsAt} format="full" />
+ </strong>
+ . Subscribe to a new plan and avoid a service interruption.
+ </p>
+ )}
+ <div className="row">
+ {this.props.plans.map(x => (
+ <BillingPlanOption
+ key={x.id}
+ plan={x}
+ tenantUserCount={this.props.tenantUserCount}
+ currentPlan={currentPlan}
+ disabled={this.props.disabled}
+ onSubscribe={this.onSubscribe}
+ onCancel={this.onCancel}
+ />
+ ))}
+ </div>
+ </Segment>
+ </>
+ );
+ }
+}
diff --git a/public/pages/Administration/pages/Billing.page.scss b/public/pages/Administration/pages/Billing.page.scss
index d76cfd728..d61cf8214 100644
--- a/public/pages/Administration/pages/Billing.page.scss
+++ b/public/pages/Administration/pages/Billing.page.scss
@@ -1,4 +1,27 @@
@import '~@fider/assets/styles/variables.scss';
#p-admin-billing {
+ .l-plan {
+ padding: 10px;
+ .l-title {
+ color: $main-color;
+ font-size: $font-size-large;
+ font-weight: 600;
+ }
+ }
+ .l-description {
+ min-height: 40px;
+ }
+ span.l-dollar {
+ color: $gray-darker;
+ font-size: $font-size-small;
+ vertical-align: top;
+ }
+ span.l-price {
+ font-size: $font-size-big;
+ }
+ span.l-interval {
+ color: $gray-darker;
+ font-size: $font-size-small;
+ }
}
\ No newline at end of file
diff --git a/public/pages/Administration/pages/Billing.page.tsx b/public/pages/Administration/pages/Billing.page.tsx
index 51b119dab..da2648fa2 100644
--- a/public/pages/Administration/pages/Billing.page.tsx
+++ b/public/pages/Administration/pages/Billing.page.tsx
@@ -5,12 +5,15 @@ import React from "react";
import { FaFileInvoice } from "react-icons/fa";
import { AdminBasePage } from "../components/AdminBasePage";
import { Segment, Button, CardInfo } from "@fider/components";
-import { PaymentInfo } from "@fider/models";
+import { PaymentInfo, BillingPlan } from "@fider/models";
import { Fider } from "@fider/services";
import PaymentInfoModal from "../components/PaymentInfoModal";
import { StripeProvider, Elements } from "react-stripe-elements";
+import { BillingPlanPanel } from "../components/BillingPlanPanel";
interface BillingPageProps {
+ plans: BillingPlan[];
+ tenantUserCount: number;
paymentInfo?: PaymentInfo;
countries: Array<{ code: string; name: string }>;
}
@@ -74,7 +77,7 @@ export default class BillingPage extends AdminBasePage<BillingPageProps, Billing
</StripeProvider>
)}
<div className="row">
- <div className="col-md-4">
+ <div className="col-md-12">
<Segment className="l-payment-info">
<h4>Payment Info</h4>
{this.props.paymentInfo && (
@@ -96,6 +99,13 @@ export default class BillingPage extends AdminBasePage<BillingPageProps, Billing
)}
</Segment>
</div>
+ <div className="col-md-12">
+ <BillingPlanPanel
+ tenantUserCount={this.props.tenantUserCount}
+ disabled={!this.props.paymentInfo}
+ plans={this.props.plans}
+ />
+ </div>
</div>
</>
);
diff --git a/public/services/actions/billing.ts b/public/services/actions/billing.ts
index 5bfbc8008..88430a978 100644
--- a/public/services/actions/billing.ts
+++ b/public/services/actions/billing.ts
@@ -18,3 +18,13 @@ interface UpdatePaymentInfoRequest {
export const updatePaymentInfo = async (request: UpdatePaymentInfoRequest): Promise<Result> => {
return http.post("/_api/admin/billing/paymentinfo", request).then(http.event("billing", "updatepaymentinfo"));
};
+
+export const billingSubscribe = async (planID: string): Promise<Result> => {
+ return http.post(`/_api/admin/billing/subscription/${planID}`).then(http.event("billing", "billingsubscribe"));
+};
+
+export const cancelBillingSubscription = async (planID: string): Promise<Result> => {
+ return http
+ .delete(`/_api/admin/billing/subscription/${planID}`)
+ .then(http.event("billing", "cancelbillingsubscription"));
+};
diff --git a/public/services/utils.ts b/public/services/utils.ts
index a982e241d..222203737 100644
--- a/public/services/utils.ts
+++ b/public/services/utils.ts
@@ -33,7 +33,7 @@ const monthNames = [
];
const twoDigits = (value: number): string => {
- return value < 9 ? `0${value}` : value.toString();
+ return value <= 9 ? `0${value}` : value.toString();
};
export const formatDate = (input: Date | string): string => {