Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

Removed paddle and trial logic

Matt Robertsf140f192bf11
diff --git a/CLAUDE.md b/CLAUDE.md
index f83c3ca37..e556319bc 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -112,7 +112,7 @@ The application includes pluggable services for:
- **Email**: SMTP, Mailgun, AWS SES
- **Blob Storage**: Filesystem, S3, SQL
- **OAuth**: Custom providers, GitHub, Google, etc.
-- **Billing**: Paddle integration (optional)
+- **Billing**: Stripe integration (optional)
- **Webhooks**: Outbound event notifications
## Development Setup Requirements
diff --git a/app/actions/billing.go b/app/actions/billing.go
deleted file mode 100644
index 0e8e9b121..000000000
--- a/app/actions/billing.go
+++ /dev/null
@@ -1,33 +0,0 @@
-package actions
-
-import (
- "context"
-
- "github.com/getfider/fider/app/models/entity"
- "github.com/getfider/fider/app/pkg/env"
-
- "github.com/getfider/fider/app/pkg/validate"
-)
-
-// GenerateCheckoutLink is used to generate a Paddle-hosted checkout link for the service subscription
-type GenerateCheckoutLink struct {
- PlanID string `json:"planId"`
-}
-
-// IsAuthorized returns true if current user is authorized to perform this action
-func (action *GenerateCheckoutLink) IsAuthorized(ctx context.Context, user *entity.User) bool {
- return user.IsAdministrator()
-}
-
-// Validate if current model is valid
-func (action *GenerateCheckoutLink) Validate(ctx context.Context, user *entity.User) *validate.Result {
- result := validate.Success()
-
- if !env.IsBillingEnabled() {
- result.AddFieldFailure("plan_id", "Billing is not enabled.")
- } else if action.PlanID != env.Config.Paddle.MonthlyPlanID && action.PlanID != env.Config.Paddle.YearlyPlanID {
- result.AddFieldFailure("plan_id", "Invalid Plan ID.")
- }
-
- return result
-}
diff --git a/app/cmd/routes.go b/app/cmd/routes.go
index 0b159da21..4c20a58f9 100644
--- a/app/cmd/routes.go
+++ b/app/cmd/routes.go
@@ -70,13 +70,6 @@ func routes(r *web.Engine) *web.Engine {
r.Get("/privacy", handlers.LegalPage("Privacy Policy", "privacy.md"))
- if env.IsBillingEnabled() {
- wh := r.Group()
- {
- wh.Post("/webhooks/paddle", webhooks.IncomingPaddleWebhook())
- }
- }
-
// Stripe webhooks (before CSRF middleware)
stripeWh := r.Group()
{
@@ -205,13 +198,9 @@ func routes(r *web.Engine) *web.Engine {
if env.IsBillingEnabled() {
ui.Get("/admin/billing", handlers.ManageBilling())
- ui.Post("/_api/billing/checkout-link", handlers.GenerateCheckoutLink())
+ ui.Post("/_api/admin/billing/portal", handlers.CreateStripePortalSession())
+ ui.Post("/_api/admin/billing/checkout", handlers.CreateStripeCheckoutSession())
}
-
- // Stripe billing (experimental)
- ui.Get("/admin/billing2", handlers.ManageBilling2())
- ui.Post("/_api/admin/billing2/portal", handlers.CreateStripePortalSession())
- ui.Post("/_api/admin/billing2/checkout", handlers.CreateStripeCheckoutSession())
}
// Public operations
diff --git a/app/cmd/server.go b/app/cmd/server.go
index 540a531bf..b9c1ae12c 100644
--- a/app/cmd/server.go
+++ b/app/cmd/server.go
@@ -17,7 +17,6 @@ import (
"github.com/getfider/fider/app/pkg/web"
"github.com/robfig/cron"
- _ "github.com/getfider/fider/app/services/billing/paddle"
_ "github.com/getfider/fider/app/services/blob/fs"
_ "github.com/getfider/fider/app/services/blob/s3"
_ "github.com/getfider/fider/app/services/blob/sql"
@@ -60,10 +59,6 @@ func startJobs(ctx context.Context) {
_ = c.AddJob(jobs.NewJob(ctx, "PurgeExpiredNotificationsJob", jobs.PurgeExpiredNotificationsJobHandler{}))
_ = c.AddJob(jobs.NewJob(ctx, "EmailSupressionJob", jobs.EmailSupressionJobHandler{}))
- if env.IsBillingEnabled() {
- _ = c.AddJob(jobs.NewJob(ctx, "LockExpiredTenantsJob", jobs.LockExpiredTenantsJobHandler{}))
- }
-
c.Start()
}
diff --git a/app/handlers/billing.go b/app/handlers/billing.go
index 301c33843..4f141bd48 100644
--- a/app/handlers/billing.go
+++ b/app/handlers/billing.go
@@ -4,80 +4,101 @@ import (
"fmt"
"net/http"
- "github.com/getfider/fider/app/actions"
- "github.com/getfider/fider/app/models/cmd"
- "github.com/getfider/fider/app/models/dto"
- "github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/web"
+ "github.com/stripe/stripe-go/v83"
+ portalsession "github.com/stripe/stripe-go/v83/billingportal/session"
+ checkoutsession "github.com/stripe/stripe-go/v83/checkout/session"
)
-// ManageBilling is the page used by administrators for billing settings
+// ManageBilling is the page used by administrators for Stripe billing settings
func ManageBilling() web.HandlerFunc {
return func(c *web.Context) error {
-
- // It's not possible to use custom domains on billing page, so redirect to Fider url
- if c.Request.IsCustomDomain() {
- url := fmt.Sprintf("https://%s.%s/admin/billing", c.Tenant().Subdomain, env.Config.HostDomain)
- return c.Redirect(url)
- }
-
- billingState := &query.GetBillingState{}
+ billingState := &query.GetStripeBillingState{}
if err := bus.Dispatch(c, billingState); err != nil {
return c.Failure(err)
}
- billingSubscription := &query.GetBillingSubscription{
- SubscriptionID: billingState.Result.SubscriptionID,
- }
- if billingState.Result.Status == enum.BillingActive {
- if err := bus.Dispatch(c, billingSubscription); err != nil {
- return c.Failure(err)
- }
- }
-
return c.Page(http.StatusOK, web.Props{
Page: "Administration/pages/ManageBilling.page",
Title: "Manage Billing · Site Settings",
Data: web.Map{
- "paddle": web.Map{
- "isSandbox": env.Config.Paddle.IsSandbox,
- "vendorId": env.Config.Paddle.VendorID,
- "monthlyPlanId": env.Config.Paddle.MonthlyPlanID,
- "yearlyPlanId": env.Config.Paddle.YearlyPlanID,
- },
- "status": billingState.Result.Status,
- "trialEndsAt": billingState.Result.TrialEndsAt,
- "subscriptionEndsAt": billingState.Result.SubscriptionEndsAt,
- "subscription": billingSubscription.Result,
+ "stripeCustomerID": billingState.Result.CustomerID,
+ "stripeSubscriptionID": billingState.Result.SubscriptionID,
},
})
}
}
-// GenerateCheckoutLink generates a Paddle-hosted checkout link for the service subscription
-func GenerateCheckoutLink() web.HandlerFunc {
+// CreateStripePortalSession creates a Stripe customer portal session
+func CreateStripePortalSession() web.HandlerFunc {
return func(c *web.Context) error {
- action := new(actions.GenerateCheckoutLink)
- if result := c.BindTo(action); !result.Ok {
- return c.HandleValidation(result)
+ billingState := &query.GetStripeBillingState{}
+ if err := bus.Dispatch(c, billingState); err != nil {
+ return c.Failure(err)
+ }
+
+ if billingState.Result.CustomerID == "" {
+ return c.BadRequest(web.Map{"message": "No Stripe customer found"})
+ }
+
+ stripe.Key = env.Config.Stripe.SecretKey
+
+ returnURL := c.BaseURL() + "/admin/billing"
+
+ params := &stripe.BillingPortalSessionParams{
+ Customer: stripe.String(billingState.Result.CustomerID),
+ ReturnURL: stripe.String(returnURL),
}
- generateLink := &cmd.GenerateCheckoutLink{
- PlanID: action.PlanID,
- Passthrough: dto.PaddlePassthrough{
- TenantID: c.Tenant().ID,
+ s, err := portalsession.New(params)
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ return c.Ok(web.Map{
+ "url": s.URL,
+ })
+ }
+}
+
+// CreateStripeCheckoutSession creates a Stripe checkout session for new subscriptions
+func CreateStripeCheckoutSession() web.HandlerFunc {
+ return func(c *web.Context) error {
+ stripe.Key = env.Config.Stripe.SecretKey
+
+ returnURL := c.BaseURL() + "/admin/billing"
+ tenantID := c.Tenant().ID
+
+ params := &stripe.CheckoutSessionParams{
+ Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
+ LineItems: []*stripe.CheckoutSessionLineItemParams{
+ {
+ Price: stripe.String(env.Config.Stripe.PriceID),
+ Quantity: stripe.Int64(1),
+ },
+ },
+ SuccessURL: stripe.String(returnURL + "?checkout=success"),
+ CancelURL: stripe.String(returnURL + "?checkout=cancelled"),
+ Metadata: map[string]string{
+ "tenant_id": fmt.Sprintf("%d", tenantID),
+ },
+ SubscriptionData: &stripe.CheckoutSessionSubscriptionDataParams{
+ Metadata: map[string]string{
+ "tenant_id": fmt.Sprintf("%d", tenantID),
+ },
},
}
- if err := bus.Dispatch(c, generateLink); err != nil {
+ s, err := checkoutsession.New(params)
+ if err != nil {
return c.Failure(err)
}
return c.Ok(web.Map{
- "url": generateLink.URL,
+ "url": s.URL,
})
}
}
diff --git a/app/handlers/billing2.go b/app/handlers/billing2.go
deleted file mode 100644
index 51019e134..000000000
--- a/app/handlers/billing2.go
+++ /dev/null
@@ -1,104 +0,0 @@
-package handlers
-
-import (
- "fmt"
- "net/http"
-
- "github.com/getfider/fider/app/models/query"
- "github.com/getfider/fider/app/pkg/bus"
- "github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/web"
- "github.com/stripe/stripe-go/v83"
- portalsession "github.com/stripe/stripe-go/v83/billingportal/session"
- checkoutsession "github.com/stripe/stripe-go/v83/checkout/session"
-)
-
-// ManageBilling2 is the page used by administrators for Stripe billing settings
-func ManageBilling2() web.HandlerFunc {
- return func(c *web.Context) error {
- billingState := &query.GetStripeBillingState{}
- if err := bus.Dispatch(c, billingState); err != nil {
- return c.Failure(err)
- }
-
- return c.Page(http.StatusOK, web.Props{
- Page: "Administration/pages/ManageBilling2.page",
- Title: "Manage Billing · Site Settings",
- Data: web.Map{
- "stripeCustomerID": billingState.Result.CustomerID,
- "stripeSubscriptionID": billingState.Result.SubscriptionID,
- },
- })
- }
-}
-
-// CreateStripePortalSession creates a Stripe customer portal session
-func CreateStripePortalSession() web.HandlerFunc {
- return func(c *web.Context) error {
- billingState := &query.GetStripeBillingState{}
- if err := bus.Dispatch(c, billingState); err != nil {
- return c.Failure(err)
- }
-
- if billingState.Result.CustomerID == "" {
- return c.BadRequest(web.Map{"message": "No Stripe customer found"})
- }
-
- stripe.Key = env.Config.Stripe.SecretKey
-
- returnURL := c.BaseURL() + "/admin/billing2"
-
- params := &stripe.BillingPortalSessionParams{
- Customer: stripe.String(billingState.Result.CustomerID),
- ReturnURL: stripe.String(returnURL),
- }
-
- s, err := portalsession.New(params)
- if err != nil {
- return c.Failure(err)
- }
-
- return c.Ok(web.Map{
- "url": s.URL,
- })
- }
-}
-
-// CreateStripeCheckoutSession creates a Stripe checkout session for new subscriptions
-func CreateStripeCheckoutSession() web.HandlerFunc {
- return func(c *web.Context) error {
- stripe.Key = env.Config.Stripe.SecretKey
-
- returnURL := c.BaseURL() + "/admin/billing2"
- tenantID := c.Tenant().ID
-
- params := &stripe.CheckoutSessionParams{
- Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
- LineItems: []*stripe.CheckoutSessionLineItemParams{
- {
- Price: stripe.String(env.Config.Stripe.PriceID),
- Quantity: stripe.Int64(1),
- },
- },
- SuccessURL: stripe.String(returnURL + "?checkout=success"),
- CancelURL: stripe.String(returnURL + "?checkout=cancelled"),
- Metadata: map[string]string{
- "tenant_id": fmt.Sprintf("%d", tenantID),
- },
- SubscriptionData: &stripe.CheckoutSessionSubscriptionDataParams{
- Metadata: map[string]string{
- "tenant_id": fmt.Sprintf("%d", tenantID),
- },
- },
- }
-
- s, err := checkoutsession.New(params)
- if err != nil {
- return c.Failure(err)
- }
-
- return c.Ok(web.Map{
- "url": s.URL,
- })
- }
-}
diff --git a/app/handlers/billing_test.go b/app/handlers/billing_test.go
deleted file mode 100644
index 34236ab22..000000000
--- a/app/handlers/billing_test.go
+++ /dev/null
@@ -1,118 +0,0 @@
-package handlers_test
-
-import (
- "context"
- "net/http"
- "testing"
- "time"
-
- "github.com/getfider/fider/app/models/cmd"
- "github.com/getfider/fider/app/models/dto"
- "github.com/getfider/fider/app/models/entity"
- "github.com/getfider/fider/app/models/enum"
-
- "github.com/getfider/fider/app/models/query"
- . "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/bus"
- "github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/mock"
-
- "github.com/getfider/fider/app/handlers"
-)
-
-func TestManageBillingHandler_RedirectWhenUsingCNAME(t *testing.T) {
- RegisterT(t)
-
- server := mock.NewServer()
- code, response := server.
- OnTenant(mock.DemoTenant).
- AsUser(mock.JonSnow).
- WithURL("https://feedback.demo.com/admin/billing").
- Execute(handlers.ManageBilling())
-
- Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("https://demo.test.fider.io/admin/billing")
-}
-
-func TestManageBillingHandler_ReturnsCorrectBillingInformation(t *testing.T) {
- RegisterT(t)
-
- bus.AddHandler(func(ctx context.Context, q *query.GetBillingState) error {
- trialEndsAt := time.Date(2021, time.February, 2, 4, 2, 2, 0, time.UTC)
- q.Result = &entity.BillingState{
- Status: enum.BillingActive,
- PlanID: "PLAN-123",
- SubscriptionID: "SUB-123",
- TrialEndsAt: &trialEndsAt,
- }
- return nil
- })
-
- bus.AddHandler(func(ctx context.Context, q *query.GetBillingSubscription) error {
- Expect(q.SubscriptionID).Equals("SUB-123")
-
- q.Result = &entity.BillingSubscription{
- UpdateURL: "https://sandbox-subscription-management.paddle.com/subscription/SUB-123/hash/1111/update",
- CancelURL: "https://sandbox-subscription-management.paddle.com/subscription/SUB-123/hash/1111/cancel",
- PaymentInformation: entity.BillingPaymentInformation{
- PaymentMethod: "card",
- CardType: "visa",
- LastFourDigits: "1111",
- ExpiryDate: "10/2031",
- },
- LastPayment: entity.BillingPayment{
- Amount: float64(30),
- Currency: "USD",
- Date: "2021-11-09",
- },
- }
- return nil
- })
-
- server := mock.NewServer()
- code, page := server.
- OnTenant(mock.DemoTenant).
- AsUser(mock.JonSnow).
- WithURL("https://demo.test.fider.io/admin/billing").
- ExecuteAsPage(handlers.ManageBilling())
-
- Expect(code).Equals(http.StatusOK)
- Expect(page.Data).ContainsProps(dto.Props{
- "status": float64(2),
- "trialEndsAt": "2021-02-02T04:02:02Z",
- "subscriptionEndsAt": nil,
- })
-
- Expect(page.Data["subscription"]).ContainsProps(dto.Props{
- "updateURL": "https://sandbox-subscription-management.paddle.com/subscription/SUB-123/hash/1111/update",
- "cancelURL": "https://sandbox-subscription-management.paddle.com/subscription/SUB-123/hash/1111/cancel",
- })
-
- ExpectHandler(&query.GetBillingState{}).CalledOnce()
- ExpectHandler(&query.GetBillingSubscription{}).CalledOnce()
-}
-
-func TestGenerateCheckoutLinkHandler(t *testing.T) {
- RegisterT(t)
-
- env.Config.Paddle.VendorID = "123"
- env.Config.Paddle.VendorAuthCode = "456"
- env.Config.Paddle.MonthlyPlanID = "PLAN_M"
- env.Config.Paddle.YearlyPlanID = "PLAN_Y"
-
- bus.AddHandler(func(ctx context.Context, c *cmd.GenerateCheckoutLink) error {
- c.URL = "https://paddle.com/fake-checkout-url"
- return nil
- })
-
- server := mock.NewServer()
- code, json := server.
- WithURL("http://demo.test.fider.io/_api/billing/checkout-link").
- OnTenant(mock.DemoTenant).
- AsUser(mock.JonSnow).
- ExecutePostAsJSON(handlers.GenerateCheckoutLink(), "{ \"planID\": \"PLAN_M\" }")
-
- Expect(code).Equals(http.StatusOK)
- Expect(json.String("url")).Equals("https://paddle.com/fake-checkout-url")
- ExpectHandler(&cmd.GenerateCheckoutLink{}).CalledOnce()
-}
diff --git a/app/handlers/webhooks/paddle.go b/app/handlers/webhooks/paddle.go
deleted file mode 100644
index 9469b6e56..000000000
--- a/app/handlers/webhooks/paddle.go
+++ /dev/null
@@ -1,163 +0,0 @@
-package webhooks
-
-import (
- "crypto"
- "crypto/rsa"
- "crypto/sha1"
- "crypto/x509"
- "encoding/base64"
- "encoding/json"
- "encoding/pem"
- "fmt"
- "net/url"
- "sort"
- "time"
-
- "github.com/getfider/fider/app/models/cmd"
- "github.com/getfider/fider/app/models/dto"
- "github.com/getfider/fider/app/models/enum"
- "github.com/getfider/fider/app/pkg/bus"
- "github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/errors"
- "github.com/getfider/fider/app/pkg/log"
- "github.com/getfider/fider/app/pkg/web"
- "github.com/getfider/fider/app/tasks"
-)
-
-// IncomingPaddleWebhook handles all incoming requests from Paddle Webhooks
-func IncomingPaddleWebhook() web.HandlerFunc {
- return func(c *web.Context) error {
- params, err := url.ParseQuery(c.Request.Body)
- if err != nil {
- return c.Failure(err)
- }
-
- err = verifyPaddleSig(params, env.Config.Paddle.PublicKey)
- if err != nil {
- return c.Failure(errors.Wrap(err, "failed to verity paddle signature"))
- }
-
- action := params.Get("alert_name")
- switch action {
- case "subscription_created":
- return handlePaddleSubscriptionCreated(c, params)
- case "subscription_cancelled":
- return handlePaddleSubscriptionCancelled(c, params)
- default:
- log.Warnf(c, "Unsupported Paddle webhook action: '@{Action}'", dto.Props{
- "Action": action,
- })
- return c.Ok(web.Map{})
- }
- }
-}
-
-func handlePaddleSubscriptionCreated(c *web.Context, params url.Values) error {
- passthrough := dto.PaddlePassthrough{}
- if err := json.Unmarshal([]byte(params.Get("passthrough")), &passthrough); err != nil {
- return c.Failure(err)
- }
-
- activate := &cmd.ActivateBillingSubscription{
- TenantID: passthrough.TenantID,
- SubscriptionID: params.Get("subscription_id"),
- PlanID: params.Get("subscription_plan_id"),
- }
-
- if err := bus.Dispatch(c, activate); err != nil {
- return c.Failure(err)
- }
-
- // Handle userlist.
- if env.Config.UserList.Enabled {
- c.Enqueue(tasks.UserListUpdateCompany(&dto.UserListUpdateCompany{
- TenantID: passthrough.TenantID,
- BillingStatus: enum.BillingActive,
- }))
- }
-
- return c.Ok(web.Map{})
-}
-
-func handlePaddleSubscriptionCancelled(c *web.Context, params url.Values) error {
- passthrough := dto.PaddlePassthrough{}
- if err := json.Unmarshal([]byte(params.Get("passthrough")), &passthrough); err != nil {
- return c.Failure(err)
- }
-
- cancellationEffectiveDate := params.Get("cancellation_effective_date")
- subscriptionEndsAt, err := time.Parse("2006-01-02", cancellationEffectiveDate)
- if err != nil {
- log.Error(c, errors.Wrap(err, "failed to parse date '%s'", cancellationEffectiveDate))
- subscriptionEndsAt = time.Now().AddDate(0, 0, 30)
- }
-
- cancel := &cmd.CancelBillingSubscription{
- TenantID: passthrough.TenantID,
- SubscriptionEndsAt: subscriptionEndsAt,
- }
-
- if err := bus.Dispatch(c, cancel); err != nil {
- return c.Failure(err)
- }
-
- // Handle userlist.
- if env.Config.UserList.Enabled {
- c.Enqueue(tasks.UserListUpdateCompany(&dto.UserListUpdateCompany{
- TenantID: passthrough.TenantID,
- BillingStatus: enum.BillingCancelled,
- }))
- }
-
- return c.Ok(web.Map{})
-}
-
-// verifyPaddleSig verifies the p_signature parameter sent
-// in Paddle webhooks. 'values' is the decoded form values sent
-// in the webhook response body.
-func verifyPaddleSig(values url.Values, publicKeyPEM string) error {
- der, _ := pem.Decode([]byte(publicKeyPEM))
- if der == nil {
- return errors.New("Could not parse public key pem")
- }
-
- pub, err := x509.ParsePKIXPublicKey(der.Bytes)
- if err != nil {
- return errors.New("Could not parse public key pem der")
- }
-
- signingKey, ok := pub.(*rsa.PublicKey)
- if !ok {
- return errors.New("Not the correct key format")
- }
-
- sig, err := base64.StdEncoding.DecodeString(values.Get("p_signature"))
- if err != nil {
- return err
- }
-
- values.Del("p_signature")
- sha1Sum := sha1.Sum(phpserialize(values))
- err = rsa.VerifyPKCS1v15(signingKey, crypto.SHA1, sha1Sum[:], sig)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func phpserialize(form url.Values) []byte {
- var keys []string
- for k := range form {
- keys = append(keys, k)
- }
- sort.Strings(keys)
-
- serialized := fmt.Sprintf("a:%d:{", len(keys))
- for _, k := range keys {
- serialized += fmt.Sprintf("s:%d:\"%s\";s:%d:\"%s\";", len(k), k, len(form.Get(k)), form.Get(k))
- }
- serialized += "}"
-
- return []byte(serialized)
-}
diff --git a/app/jobs/lock_expired_tenants_job.go b/app/jobs/lock_expired_tenants_job.go
deleted file mode 100644
index 3128ff0a1..000000000
--- a/app/jobs/lock_expired_tenants_job.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package jobs
-
-import (
- "github.com/getfider/fider/app/models/cmd"
- "github.com/getfider/fider/app/models/dto"
- "github.com/getfider/fider/app/models/enum"
- "github.com/getfider/fider/app/pkg/bus"
- "github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/log"
-)
-
-type LockExpiredTenantsJobHandler struct {
-}
-
-func (e LockExpiredTenantsJobHandler) Schedule() string {
- return "0 0 0 * * *" // every day at 0:00
-}
-
-func (e LockExpiredTenantsJobHandler) Run(ctx Context) error {
- c := &cmd.LockExpiredTenants{}
- err := bus.Dispatch(ctx, c)
- if err != nil {
- return err
- }
-
- log.Debugf(ctx, "@{Count} tenants marked as locked", dto.Props{
- "Count": c.NumOfTenantsLocked,
- })
-
- // Handle userlist
- if env.Config.UserList.Enabled && c.NumOfTenantsLocked > 0 {
- for _, tenant := range c.TenantsLocked {
- err := bus.Dispatch(ctx, &cmd.UserListUpdateCompany{TenantId: tenant, BillingStatus: enum.BillingCancelled})
- if err != nil {
- return err
- }
- }
-
- }
-
- return nil
-}
diff --git a/app/jobs/lock_expired_tenants_job_test.go b/app/jobs/lock_expired_tenants_job_test.go
deleted file mode 100644
index 35c86cc14..000000000
--- a/app/jobs/lock_expired_tenants_job_test.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package jobs_test
-
-import (
- "context"
- "testing"
-
- "github.com/getfider/fider/app/jobs"
- "github.com/getfider/fider/app/models/cmd"
- . "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/bus"
-)
-
-func TestLockExpiredTenantsJob_Schedule_IsCorrect(t *testing.T) {
- RegisterT(t)
-
- job := &jobs.LockExpiredTenantsJobHandler{}
- Expect(job.Schedule()).Equals("0 0 0 * * *")
-}
-
-func TestLockExpiredTenantsJob_ShouldJustDispatchCommand(t *testing.T) {
- RegisterT(t)
-
- bus.AddHandler(func(ctx context.Context, c *cmd.LockExpiredTenants) error {
- return nil
- })
-
- job := &jobs.LockExpiredTenantsJobHandler{}
- err := job.Run(jobs.Context{
- Context: context.Background(),
- })
- Expect(err).IsNil()
-}
diff --git a/app/middlewares/security.go b/app/middlewares/security.go
index c48216809..0f407ec74 100644
--- a/app/middlewares/security.go
+++ b/app/middlewares/security.go
@@ -15,8 +15,11 @@ func Secure() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
return func(c *web.Context) error {
cdnHost := env.Config.CDN.Host
- if cdnHost != "" && !env.IsSingleHostMode() {
- cdnHost = "*." + cdnHost
+ if cdnHost != "" {
+ if !env.IsSingleHostMode() {
+ cdnHost = "*." + cdnHost
+ }
+ cdnHost = " " + cdnHost
}
csp := fmt.Sprintf(web.CspPolicyTemplate, c.ContextID(), cdnHost)
diff --git a/app/middlewares/security_test.go b/app/middlewares/security_test.go
index cec889bcc..d0e73dafe 100644
--- a/app/middlewares/security_test.go
+++ b/app/middlewares/security_test.go
@@ -23,7 +23,7 @@ func TestSecureWithoutCDN(t *testing.T) {
return c.NoContent(http.StatusOK)
})
- expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline' https://*.paddle.com ; script-src 'self' 'nonce-" + ctxID + "' https://www.google-analytics.com https://*.paddle.com ; img-src 'self' https: data: ; font-src 'self' data: ; object-src 'none'; media-src 'none'; connect-src 'self' https://www.google-analytics.com ; frame-src 'self' https://*.paddle.com"
+ expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'nonce-" + ctxID + "' https://www.google-analytics.com; img-src 'self' https: data:; font-src 'self' data:; object-src 'none'; media-src 'none'; connect-src 'self' https://www.google-analytics.com; frame-src 'self'"
Expect(status).Equals(http.StatusOK)
Expect(response.Header().Get("Content-Security-Policy")).Equals(expectedPolicy)
@@ -46,7 +46,7 @@ func TestSecureWithCDN(t *testing.T) {
return c.NoContent(http.StatusOK)
})
- expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline' https://*.paddle.com *.test.fider.io; script-src 'self' 'nonce-" + ctxID + "' https://www.google-analytics.com https://*.paddle.com *.test.fider.io; img-src 'self' https: data: *.test.fider.io; font-src 'self' data: *.test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' https://www.google-analytics.com *.test.fider.io; frame-src 'self' https://*.paddle.com"
+ expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline' *.test.fider.io; script-src 'self' 'nonce-" + ctxID + "' https://www.google-analytics.com *.test.fider.io; img-src 'self' https: data: *.test.fider.io; font-src 'self' data: *.test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' https://www.google-analytics.com *.test.fider.io; frame-src 'self'"
Expect(status).Equals(http.StatusOK)
Expect(response.Header().Get("Content-Security-Policy")).Equals(expectedPolicy)
@@ -69,7 +69,7 @@ func TestSecureWithCDN_SingleHost(t *testing.T) {
return c.NoContent(http.StatusOK)
})
- expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline' https://*.paddle.com test.fider.io; script-src 'self' 'nonce-" + ctxID + "' https://www.google-analytics.com https://*.paddle.com test.fider.io; img-src 'self' https: data: test.fider.io; font-src 'self' data: test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' https://www.google-analytics.com test.fider.io; frame-src 'self' https://*.paddle.com"
+ expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline' test.fider.io; script-src 'self' 'nonce-" + ctxID + "' https://www.google-analytics.com test.fider.io; img-src 'self' https: data: test.fider.io; font-src 'self' data: test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' https://www.google-analytics.com test.fider.io; frame-src 'self'"
Expect(status).Equals(http.StatusOK)
Expect(response.Header().Get("Content-Security-Policy")).Equals(expectedPolicy)
diff --git a/app/models/cmd/billing.go b/app/models/cmd/billing.go
index 735b25528..ea300d574 100644
--- a/app/models/cmd/billing.go
+++ b/app/models/cmd/billing.go
@@ -2,22 +2,10 @@ package cmd
import (
"time"
-
- "github.com/getfider/fider/app/models/dto"
)
-type GenerateCheckoutLink struct {
- PlanID string
- Passthrough dto.PaddlePassthrough
-
- // Output
- URL string
-}
-
type ActivateBillingSubscription struct {
- TenantID int
- SubscriptionID string
- PlanID string
+ TenantID int
}
type CancelBillingSubscription struct {
@@ -25,12 +13,6 @@ type CancelBillingSubscription struct {
SubscriptionEndsAt time.Time
}
-type LockExpiredTenants struct {
- //Output
- NumOfTenantsLocked int64
- TenantsLocked []int
-}
-
type ActivateStripeSubscription struct {
TenantID int
CustomerID string
diff --git a/app/models/dto/billing.go b/app/models/dto/billing.go
deleted file mode 100644
index b644483b4..000000000
--- a/app/models/dto/billing.go
+++ /dev/null
@@ -1,5 +0,0 @@
-package dto
-
-type PaddlePassthrough struct {
- TenantID int `json:"tenant_id"`
-}
diff --git a/app/models/entity/billing.go b/app/models/entity/billing.go
index 660869de2..6c05577e5 100644
--- a/app/models/entity/billing.go
+++ b/app/models/entity/billing.go
@@ -8,9 +8,6 @@ import (
type BillingState struct {
Status enum.BillingStatus `json:"status"`
- PlanID string `json:"planID"`
- SubscriptionID string `json:"subscriptionID"`
- TrialEndsAt *time.Time `json:"trialEndsAt"`
SubscriptionEndsAt *time.Time `json:"subscriptionEndsAt"`
}
diff --git a/app/models/enum/billing.go b/app/models/enum/billing.go
index b80178e79..e5ba540f8 100644
--- a/app/models/enum/billing.go
+++ b/app/models/enum/billing.go
@@ -3,8 +3,6 @@ package enum
type BillingStatus int
var (
- //BillingTrial is used for tenants in trial
- BillingTrial BillingStatus = 1
//BillingActive is used for tenants with an active subscription
BillingActive BillingStatus = 2
//BillingCancelled is used for tenants that had an active subscription, but have cancelled it
@@ -16,7 +14,6 @@ var (
)
var billingStatusIDs = map[BillingStatus]string{
- BillingTrial: "trial",
BillingActive: "active",
BillingCancelled: "cancelled",
BillingFreeForever: "free_forever",
diff --git a/app/models/query/tenant.go b/app/models/query/tenant.go
index fddc71c7a..6cdba0fd3 100644
--- a/app/models/query/tenant.go
+++ b/app/models/query/tenant.go
@@ -1,8 +1,6 @@
package query
import (
- "time"
-
"github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
)
@@ -51,13 +49,6 @@ type GetTenantByDomain struct {
Result *entity.Tenant
}
-type GetTrialingTenantContacts struct {
- TrialExpiresOn time.Time
-
- // Output
- Contacts []*entity.User
-}
-
type GetPendingSignUpVerification struct {
// Output
Result *entity.EmailVerification
diff --git a/app/pkg/dbx/setup.sql b/app/pkg/dbx/setup.sql
index a5f07306e..17badcfb8 100644
--- a/app/pkg/dbx/setup.sql
+++ b/app/pkg/dbx/setup.sql
@@ -31,13 +31,13 @@ VALUES ('The Hulk', '[email protected]', 2, now(), 1, 1, 2, '');
INSERT INTO user_providers (user_id, tenant_id, provider, provider_uid, created_at)
VALUES (5, 2, 'google', 'GO1111', now());
--- Create a tenant that has reached the end of it's trial period
+-- Create a tenant with a cancelled subscription
INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale, is_email_auth_allowed, is_feed_enabled, prevent_indexing, is_moderation_enabled )
-VALUES ('Trial Expired', 'trial-expired', now(), 'feedback.trial-expired.com', '', '', 1, false, '', '', 'en', true, true, false, false);
-INSERT INTO tenants_billing (tenant_id, paddle_plan_id, paddle_subscription_id, status, subscription_ends_at, trial_ends_at)
-VALUES (3, 1, 1,1, now(), CURRENT_DATE - INTERVAL '10 days');
+VALUES ('Cancelled Subscription', 'cancelled-sub', now(), 'feedback.cancelled-sub.com', '', '', 1, false, '', '', 'en', true, true, false, false);
+INSERT INTO tenants_billing (tenant_id, status, subscription_ends_at)
+VALUES (3, 3, now());
INSERT INTO users (name, email, tenant_id, created_at, role, status, avatar_type, avatar_bkey)
-VALUES ('Trial Expired', '[email protected]', 3, now(), 3, 1, 2, '');
+VALUES ('Cancelled Admin', '[email protected]', 3, now(), 3, 1, 2, '');
INSERT INTO user_providers (user_id, tenant_id, provider, provider_uid, created_at)
VALUES (6, 3, 'facebook', 'FB3333', now());
diff --git a/app/pkg/env/env.go b/app/pkg/env/env.go
index e49ed89dc..211ccc7b8 100644
--- a/app/pkg/env/env.go
+++ b/app/pkg/env/env.go
@@ -56,15 +56,7 @@ type config struct {
JWTSecret string `env:"JWT_SECRET,required"`
PostCreationWithTagsEnabled bool `env:"POST_CREATION_WITH_TAGS_ENABLED,default=false"`
AllowAllowedSchemes bool `env:"ALLOW_ALLOWED_SCHEMES,default=true"`
- Paddle struct {
- IsSandbox bool `env:"PADDLE_SANDBOX,default=false"`
- VendorID string `env:"PADDLE_VENDOR_ID"`
- VendorAuthCode string `env:"PADDLE_VENDOR_AUTHCODE"`
- MonthlyPlanID string `env:"PADDLE_MONTHLY_PLAN_ID"`
- YearlyPlanID string `env:"PADDLE_YEARLY_PLAN_ID"`
- PublicKey string `env:"PADDLE_PUBLIC_KEY"`
- }
- Stripe struct {
+ Stripe struct {
SecretKey string `env:"STRIPE_SECRET_KEY"`
WebhookSecret string `env:"STRIPE_WEBHOOK_SECRET"`
PriceID string `env:"STRIPE_PRICE_ID"`
@@ -249,9 +241,9 @@ func MultiTenantDomain() string {
return ""
}
-// IsBillingEnabled returns true if Paddle is configured
+// IsBillingEnabled returns true if Stripe is configured
func IsBillingEnabled() bool {
- return Config.Paddle.VendorID != "" && Config.Paddle.VendorAuthCode != ""
+ return Config.Stripe.SecretKey != ""
}
// IsCommercialEnabled returns true if commercial features are enabled
diff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.go
index 17b368229..204a13791 100644
--- a/app/pkg/web/engine.go
+++ b/app/pkg/web/engine.go
@@ -27,14 +27,14 @@ import (
var (
cspBase = "base-uri 'self'"
cspDefault = "default-src 'self'"
- cspStyle = "style-src 'self' 'unsafe-inline' https://*.paddle.com %[2]s"
- cspScript = "script-src 'self' 'nonce-%[1]s' https://www.google-analytics.com https://*.paddle.com %[2]s"
- cspFont = "font-src 'self' data: %[2]s"
- cspImage = "img-src 'self' https: data: %[2]s"
+ cspStyle = "style-src 'self' 'unsafe-inline'%[2]s"
+ cspScript = "script-src 'self' 'nonce-%[1]s' https://www.google-analytics.com%[2]s"
+ cspFont = "font-src 'self' data:%[2]s"
+ cspImage = "img-src 'self' https: data:%[2]s"
cspObject = "object-src 'none'"
- cspFrame = "frame-src 'self' https://*.paddle.com"
+ cspFrame = "frame-src 'self'"
cspMedia = "media-src 'none'"
- cspConnect = "connect-src 'self' https://www.google-analytics.com %[2]s"
+ cspConnect = "connect-src 'self' https://www.google-analytics.com%[2]s"
//CspPolicyTemplate is the template used to generate the policy
CspPolicyTemplate = fmt.Sprintf("%s; %s; %s; %s; %s; %s; %s; %s; %s; %s", cspBase, cspDefault, cspStyle, cspScript, cspImage, cspFont, cspObject, cspMedia, cspConnect, cspFrame)
diff --git a/app/services/billing/paddle/paddle.go b/app/services/billing/paddle/paddle.go
deleted file mode 100644
index b0d4ea597..000000000
--- a/app/services/billing/paddle/paddle.go
+++ /dev/null
@@ -1,153 +0,0 @@
-package paddle
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "net/http"
- "net/url"
- "strings"
-
- "github.com/getfider/fider/app/models/cmd"
- "github.com/getfider/fider/app/models/entity"
- "github.com/getfider/fider/app/models/query"
- "github.com/getfider/fider/app/pkg/bus"
- "github.com/getfider/fider/app/pkg/env"
- "github.com/getfider/fider/app/pkg/errors"
- "github.com/getfider/fider/app/pkg/jsonq"
-)
-
-func init() {
- bus.Register(Service{})
-}
-
-type Service struct{}
-
-func (s Service) Name() string {
- return "Paddle"
-}
-
-func (s Service) Category() string {
- return "billing"
-}
-
-func (s Service) Enabled() bool {
- return env.IsBillingEnabled()
-}
-
-func (s Service) Init() {
- bus.AddHandler(generateCheckoutLink)
- bus.AddHandler(getBillingSubscription)
-}
-
-func getApiBasePath() string {
- if env.Config.Paddle.IsSandbox {
- return "https://sandbox-vendors.paddle.com"
- }
- return "https://vendors.paddle.com"
-}
-
-// generateCheckoutLink generates a checkout link using Paddle API
-func generateCheckoutLink(ctx context.Context, c *cmd.GenerateCheckoutLink) error {
- passthrough, err := json.Marshal(c.Passthrough)
- if err != nil {
- return errors.Wrap(err, "failed to marshal Passthrough object")
- }
-
- params := url.Values{}
- params.Set("vendor_id", env.Config.Paddle.VendorID)
- params.Set("vendor_auth_code", env.Config.Paddle.VendorAuthCode)
- params.Set("product_id", c.PlanID)
- params.Set("passthrough", string(passthrough))
-
- req := &cmd.HTTPRequest{
- URL: fmt.Sprintf("%s/api/2.0/product/generate_pay_link", getApiBasePath()),
- Body: strings.NewReader(params.Encode()),
- Method: http.MethodPost,
- Headers: map[string]string{
- "Content-Type": "application/x-www-form-urlencoded",
- },
- }
-
- if err := bus.Dispatch(ctx, req); err != nil {
- return errors.Wrap(err, "failed to generate paddle checkout link")
- }
-
- if req.ResponseStatusCode >= 300 {
- return errors.New("unexpected status code while generating a paddle checkout link: %d", req.ResponseStatusCode)
- }
-
- res := &PaddleResponse{}
- if err := json.Unmarshal(req.ResponseBody, &res); err != nil {
- return errors.Wrap(err, "failed to unmarshal response body")
- }
-
- if !res.IsSuccess {
- return errors.New("failed to generate paddle checkout link with '%s (%d)'", res.Error.Message, res.Error.Code)
- }
-
- c.URL = jsonq.New(string(res.Response)).String("url")
- return nil
-}
-
-func getBillingSubscription(ctx context.Context, q *query.GetBillingSubscription) error {
- params := url.Values{}
- params.Set("vendor_id", env.Config.Paddle.VendorID)
- params.Set("vendor_auth_code", env.Config.Paddle.VendorAuthCode)
- params.Set("subscription_id", q.SubscriptionID)
-
- req := &cmd.HTTPRequest{
- URL: fmt.Sprintf("%s/api/2.0/subscription/users", getApiBasePath()),
- Body: strings.NewReader(params.Encode()),
- Method: http.MethodPost,
- Headers: map[string]string{
- "Content-Type": "application/x-www-form-urlencoded",
- },
- }
-
- if err := bus.Dispatch(ctx, req); err != nil {
- return errors.Wrap(err, "failed to get paddle subscription details")
- }
-
- if req.ResponseStatusCode >= 300 {
- return errors.New("unexpected status code while fetching paddle subscription details: %d", req.ResponseStatusCode)
- }
-
- res := &PaddleResponse{}
- if err := json.Unmarshal(req.ResponseBody, &res); err != nil {
- return errors.Wrap(err, "failed to unmarshal response body")
- }
-
- if !res.IsSuccess {
- return errors.New("failed to fetch paddle subscription details with '%s (%d)'", res.Error.Message, res.Error.Code)
- }
-
- sub := []PaddleSubscriptionItem{}
- if err := json.Unmarshal(res.Response, &sub); err != nil {
- return errors.Wrap(err, "failed to unmarshal response body")
- }
-
- if len(sub) > 0 {
- q.Result = &entity.BillingSubscription{
- CancelURL: sub[0].CancelURL,
- UpdateURL: sub[0].UpdateURL,
- PaymentInformation: entity.BillingPaymentInformation{
- PaymentMethod: sub[0].PaymentInformation.PaymentMethod,
- CardType: sub[0].PaymentInformation.CardType,
- LastFourDigits: sub[0].PaymentInformation.LastFourDigits,
- ExpiryDate: sub[0].PaymentInformation.ExpiryDate,
- },
- LastPayment: entity.BillingPayment{
- Amount: sub[0].LastPayment.Amount,
- Currency: sub[0].LastPayment.Currency,
- Date: sub[0].LastPayment.Date,
- },
- NextPayment: entity.BillingPayment{
- Amount: sub[0].NextPayment.Amount,
- Currency: sub[0].NextPayment.Currency,
- Date: sub[0].NextPayment.Date,
- },
- }
- }
- return nil
-}
diff --git a/app/services/billing/paddle/response.go b/app/services/billing/paddle/response.go
deleted file mode 100644
index 74685844a..000000000
--- a/app/services/billing/paddle/response.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package paddle
-
-import "encoding/json"
-
-type PaddleResponse struct {
- IsSuccess bool `json:"success"`
- Response json.RawMessage `json:"response"`
- Error struct {
- Code int `json:"code"`
- Message string `json:"message"`
- }
-}
-
-type PaddleSubscriptionItem struct {
- SignupDate string `json:"signup_date"`
- UpdateURL string `json:"update_url"`
- CancelURL string `json:"cancel_url"`
- PaymentInformation struct {
- PaymentMethod string `json:"payment_method"`
- CardType string `json:"card_type"`
- LastFourDigits string `json:"last_four_digits"`
- ExpiryDate string `json:"expiry_date"`
- } `json:"payment_information"`
- LastPayment struct {
- Amount float64 `json:"amount"`
- Currency string `json:"currency"`
- Date string `json:"date"`
- } `json:"last_payment"`
- NextPayment struct {
- Amount float64 `json:"amount"`
- Currency string `json:"currency"`
- Date string `json:"date"`
- } `json:"next_payment"`
-}
diff --git a/app/services/sqlstore/dbEntities/billing.go b/app/services/sqlstore/dbEntities/billing.go
index 918848679..f89679a56 100644
--- a/app/services/sqlstore/dbEntities/billing.go
+++ b/app/services/sqlstore/dbEntities/billing.go
@@ -10,9 +10,6 @@ import (
type BillingState struct {
Status int `db:"status"`
- PlanID string `db:"paddle_plan_id"`
- SubscriptionID string `db:"paddle_subscription_id"`
- TrialEndsAt dbx.NullTime `db:"trial_ends_at"`
SubscriptionEndsAt dbx.NullTime `db:"subscription_ends_at"`
}
@@ -23,13 +20,7 @@ type StripeBillingState struct {
func (s *BillingState) ToModel(ctx context.Context) *entity.BillingState {
model := &entity.BillingState{
- Status: enum.BillingStatus(s.Status),
- PlanID: s.PlanID,
- SubscriptionID: s.SubscriptionID,
- }
-
- if s.TrialEndsAt.Valid {
- model.TrialEndsAt = &s.TrialEndsAt.Time
+ Status: enum.BillingStatus(s.Status),
}
if s.SubscriptionEndsAt.Valid {
diff --git a/app/services/sqlstore/postgres/billing.go b/app/services/sqlstore/postgres/billing.go
index d945da8db..516045d7b 100644
--- a/app/services/sqlstore/postgres/billing.go
+++ b/app/services/sqlstore/postgres/billing.go
@@ -2,7 +2,6 @@ package postgres
import (
"context"
- "time"
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models/cmd"
@@ -12,7 +11,6 @@ import (
"github.com/getfider/fider/app/pkg/dbx"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/services/sqlstore/dbEntities"
- "github.com/lib/pq"
)
func getBillingState(ctx context.Context, q *query.GetBillingState) error {
@@ -22,10 +20,7 @@ func getBillingState(ctx context.Context, q *query.GetBillingState) error {
state := dbEntities.BillingState{}
err := trx.Get(&state,
`SELECT
- trial_ends_at,
subscription_ends_at,
- paddle_subscription_id,
- paddle_plan_id,
status
FROM tenants_billing
WHERE tenant_id = $1`, tenant.ID)
@@ -43,9 +38,9 @@ func activateBillingSubscription(ctx context.Context, c *cmd.ActivateBillingSubs
return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {
_, err := trx.Execute(`
UPDATE tenants_billing
- SET subscription_ends_at = null, paddle_subscription_id = $2, paddle_plan_id = $3, status = $4
+ SET subscription_ends_at = null, status = $2
WHERE tenant_id = $1
- `, c.TenantID, c.SubscriptionID, c.PlanID, enum.BillingActive)
+ `, c.TenantID, enum.BillingActive)
if err != nil {
return errors.Wrap(err, "failed activate billing subscription")
}
@@ -77,82 +72,6 @@ func cancelBillingSubscription(ctx context.Context, c *cmd.CancelBillingSubscrip
})
}
-func lockExpiredTenants(ctx context.Context, c *cmd.LockExpiredTenants) error {
- return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {
- now := time.Now()
-
- type tenant struct {
- Id int `db:"id"`
- }
-
- tenants := []*tenant{}
- err := trx.Select(&tenants, `
- SELECT id
- FROM tenants t
- INNER JOIN tenants_billing tb
- ON t.id = tb.tenant_id
- WHERE t.status <> $1 AND t.status <> $2
- AND (
- (tb.status = $3 AND trial_ends_at <= $5)
- OR (tb.status = $4 AND subscription_ends_at <= $5)
- )`, enum.TenantLocked, enum.TenantDisabled, enum.BillingTrial, enum.BillingCancelled, now)
- if err != nil {
- return errors.Wrap(err, "failed to get expired trial/cancelled tenants")
- }
-
- if len(tenants) > 0 {
- ids := make([]int, 0)
- for _, tenant := range tenants {
- ids = append(ids, tenant.Id)
- }
-
- count, err := trx.Execute(`
- UPDATE tenants
- SET status = $1
- WHERE id = ANY($2)
- `, enum.TenantLocked, pq.Array(ids))
- if err != nil {
- return errors.Wrap(err, "failed to lock trial/cancelled tenants")
- }
-
- c.NumOfTenantsLocked = count
- c.TenantsLocked = ids
- }
-
- return nil
- })
-}
-
-func getTrialingTenantContacts(ctx context.Context, q *query.GetTrialingTenantContacts) error {
- return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {
- var users []*dbEntities.User
- err := trx.Select(&users, `
- SELECT
- u.name,
- u.email,
- u.role,
- u.status,
- t.subdomain as tenant_subdomain
- FROM tenants_billing tb
- INNER JOIN tenants t
- ON t.id = tb.tenant_id
- INNER JOIN users u
- ON u.tenant_id = tb.tenant_id
- AND u.role = $1
- WHERE date(trial_ends_at) = date($2)
- AND tb.status = $3`, enum.RoleAdministrator, q.TrialExpiresOn, enum.BillingTrial)
- if err != nil {
- return errors.Wrap(err, "failed to get trialing tenant contacts")
- }
-
- q.Contacts = make([]*entity.User, len(users))
- for i, user := range users {
- q.Contacts[i] = user.ToModel(ctx)
- }
- return nil
- })
-}
-
func getStripeBillingState(ctx context.Context, q *query.GetStripeBillingState) error {
return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
state := dbEntities.StripeBillingState{}
@@ -181,8 +100,8 @@ func getStripeBillingState(ctx context.Context, q *query.GetStripeBillingState)
func activateStripeSubscription(ctx context.Context, c *cmd.ActivateStripeSubscription) error {
return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {
_, err := trx.Execute(`
- INSERT INTO tenants_billing (tenant_id, trial_ends_at, paddle_subscription_id, paddle_plan_id, status, stripe_customer_id, stripe_subscription_id)
- VALUES ($1, NOW(), '', '', 0, $2, $3)
+ INSERT INTO tenants_billing (tenant_id, status, stripe_customer_id, stripe_subscription_id)
+ VALUES ($1, 0, $2, $3)
ON CONFLICT (tenant_id) DO UPDATE
SET stripe_customer_id = $2, stripe_subscription_id = $3
`, c.TenantID, c.CustomerID, c.SubscriptionID)
diff --git a/app/services/sqlstore/postgres/billing_test.go b/app/services/sqlstore/postgres/billing_test.go
deleted file mode 100644
index a34445b42..000000000
--- a/app/services/sqlstore/postgres/billing_test.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package postgres_test
-
-import (
- "testing"
-
- "github.com/getfider/fider/app/models/cmd"
-
- . "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/bus"
-)
-
-func TestLockExpiredTenants_ShouldTriggerForOneTenant(t *testing.T) {
- ctx := SetupDatabaseTest(t)
- defer TeardownDatabaseTest()
-
- // There is a tenant with an expired trial setup in the seed for the test database.
- q := &cmd.LockExpiredTenants{}
-
- err := bus.Dispatch(ctx, q)
- Expect(err).IsNil()
- Expect(q.NumOfTenantsLocked).Equals(int64(1))
- Expect(q.TenantsLocked).Equals([]int{3})
-
-}
diff --git a/app/services/sqlstore/postgres/postgres.go b/app/services/sqlstore/postgres/postgres.go
index 613ff18a9..b1a67eef8 100644
--- a/app/services/sqlstore/postgres/postgres.go
+++ b/app/services/sqlstore/postgres/postgres.go
@@ -140,8 +140,6 @@ func (s Service) Init() {
bus.AddHandler(getBillingState)
bus.AddHandler(activateBillingSubscription)
bus.AddHandler(cancelBillingSubscription)
- bus.AddHandler(lockExpiredTenants)
- bus.AddHandler(getTrialingTenantContacts)
bus.AddHandler(getStripeBillingState)
bus.AddHandler(activateStripeSubscription)
bus.AddHandler(cancelStripeSubscription)
diff --git a/app/services/sqlstore/postgres/tenant.go b/app/services/sqlstore/postgres/tenant.go
index 1ad496e45..5cc88510e 100644
--- a/app/services/sqlstore/postgres/tenant.go
+++ b/app/services/sqlstore/postgres/tenant.go
@@ -196,10 +196,9 @@ func createTenant(ctx context.Context, c *cmd.CreateTenant) error {
}
if env.IsBillingEnabled() {
- trialEndsAt := time.Now().AddDate(0, 0, 15) // 15 days
_, err := trx.Execute(
- `INSERT INTO tenants_billing (tenant_id, trial_ends_at, status, paddle_subscription_id, paddle_plan_id)
- VALUES ($1, $2, $3, '', '')`, id, trialEndsAt, enum.BillingTrial)
+ `INSERT INTO tenants_billing (tenant_id, status)
+ VALUES ($1, $2)`, id, enum.BillingActive)
if err != nil {
return err
}
diff --git a/app/tasks/userlist.go b/app/tasks/userlist.go
index c5e7ea729..e7aed5579 100644
--- a/app/tasks/userlist.go
+++ b/app/tasks/userlist.go
@@ -22,7 +22,7 @@ func UserListCreateCompany(tenant entity.Tenant, user entity.User) worker.Task {
Name: tenant.Name,
TenantId: tenant.ID,
SignedUpAt: time.Now().Format(time.RFC3339),
- BillingStatus: enum.BillingTrial.String(),
+ BillingStatus: enum.BillingActive.String(),
Subdomain: tenant.Subdomain,
UserId: user.ID,
UserEmail: user.Email,
diff --git a/migrations/202511251500_remove_paddle_trial_columns.sql b/migrations/202511251500_remove_paddle_trial_columns.sql
new file mode 100644
index 000000000..61d71a224
--- /dev/null
+++ b/migrations/202511251500_remove_paddle_trial_columns.sql
@@ -0,0 +1,6 @@
+-- Remove Paddle and trial-related columns from tenants_billing
+-- We're moving to Stripe-only billing with no trial periods
+
+ALTER TABLE tenants_billing DROP COLUMN IF EXISTS paddle_subscription_id;
+ALTER TABLE tenants_billing DROP COLUMN IF EXISTS paddle_plan_id;
+ALTER TABLE tenants_billing DROP COLUMN IF EXISTS trial_ends_at;
diff --git a/public/models/billing.ts b/public/models/billing.ts
index f79bd3136..2165c934d 100644
--- a/public/models/billing.ts
+++ b/public/models/billing.ts
@@ -1,5 +1,4 @@
export enum BillingStatus {
- Trial = 1,
Active = 2,
Cancelled = 3,
FreeForever = 4,
diff --git a/public/pages/Administration/components/SideMenu.tsx b/public/pages/Administration/components/SideMenu.tsx
index 088973fd9..acde6b97c 100644
--- a/public/pages/Administration/components/SideMenu.tsx
+++ b/public/pages/Administration/components/SideMenu.tsx
@@ -49,7 +49,7 @@ export const SideMenu = (props: SiteMenuProps) => {
<SideMenuItem name="advanced" title="Advanced" href="/admin/advanced" isActive={activeItem === "advanced"} />
{fider.session.user.isAdministrator && (
<>
- {fider.settings.isBillingEnabled && <SideMenuItem name="billing" title="Billing" href="/admin/billing2" isActive={activeItem === "billing"} />}
+ {fider.settings.isBillingEnabled && <SideMenuItem name="billing" title="Billing" href="/admin/billing" isActive={activeItem === "billing"} />}
<SideMenuItem name="webhooks" title="Webhooks" href="/admin/webhooks" isActive={activeItem === "webhooks"} />
<SideMenuItem name="export" title="Export" href="/admin/export" isActive={activeItem === "export"} />
</>
diff --git a/public/pages/Administration/hooks/use-paddle.ts b/public/pages/Administration/hooks/use-paddle.ts
deleted file mode 100644
index 8c92d6f44..000000000
--- a/public/pages/Administration/hooks/use-paddle.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { useCache, useScript } from "@fider/hooks"
-import { actions } from "@fider/services"
-import { useEffect, useState } from "react"
-
-interface UsePaddleParams {
- isSandbox: boolean
- vendorId: string
- monthlyPlanId: string
- yearlyPlanId: string
-}
-
-export function usePaddle(params: UsePaddleParams) {
- const status = useScript("https://cdn.paddle.com/paddle/paddle.js")
- const [monthlyPrice, setMonthlyPrice] = useCache("monthlyPrice", "$30")
- const [yearlyPrice, setYearlyPrice] = useCache("yearlyPrice", "$300")
- const [isReady, setIsReady] = useState(false)
-
- useEffect(() => {
- if (status !== "ready" || !params) return
-
- if (params.isSandbox) {
- window.Paddle.Environment.set("sandbox")
- }
-
- const vendor = parseInt(params.vendorId, 10)
- window.Paddle.Setup({ vendor })
- setIsReady(true)
-
- window.Paddle.Product.Prices(parseInt(params.monthlyPlanId, 10), (resp) => {
- setMonthlyPrice(resp.price.net.replace(/\.00/g, ""))
- })
- window.Paddle.Product.Prices(parseInt(params.yearlyPlanId, 10), (resp) => {
- setYearlyPrice(resp.price.net.replace(/\.00/g, ""))
- })
- }, [status])
-
- const openUrl = (url: string) => {
- window.Paddle.Checkout.open({
- override: url,
- closeCallback: () => {
- location.reload()
- },
- })
- }
-
- const subscribeMonthly = async () => {
- const result = await actions.generateCheckoutLink(params.monthlyPlanId)
- if (result.ok) {
- openUrl(result.data.url)
- }
- }
-
- const subscribeYearly = async () => {
- const result = await actions.generateCheckoutLink(params.yearlyPlanId)
- if (result.ok) {
- openUrl(result.data.url)
- }
- }
-
- return { isReady, monthlyPrice, yearlyPrice, openUrl, subscribeMonthly, subscribeYearly }
-}
diff --git a/public/pages/Administration/pages/ManageBilling2.page.scss b/public/pages/Administration/pages/ManageBilling.page.scss
similarity index 100%
rename from public/pages/Administration/pages/ManageBilling2.page.scss
rename to public/pages/Administration/pages/ManageBilling.page.scss
diff --git a/public/pages/Administration/pages/ManageBilling.page.tsx b/public/pages/Administration/pages/ManageBilling.page.tsx
index 05a2ee743..9557fb02f 100644
--- a/public/pages/Administration/pages/ManageBilling.page.tsx
+++ b/public/pages/Administration/pages/ManageBilling.page.tsx
@@ -1,249 +1,135 @@
-import React from "react"
-import { Button, Moment, Money } from "@fider/components"
+import React, { useState } from "react"
+import { Button, Icon } from "@fider/components"
import { HStack, VStack } from "@fider/components/layout"
-import { useFider } from "@fider/hooks"
-import { BillingStatus } from "@fider/models"
import { AdminPageContainer } from "../components/AdminBasePage"
-import { CardDetails } from "../components/billing/CardDetails"
-import { usePaddle } from "../hooks/use-paddle"
+import { http } from "@fider/services"
+import IconCheck from "@fider/assets/images/heroicons-check.svg"
+
+import "./ManageBilling.page.scss"
interface ManageBillingPageProps {
- paddle: {
- isSandbox: boolean
- vendorId: string
- monthlyPlanId: string
- yearlyPlanId: string
- }
- status: BillingStatus
- trialEndsAt: string
- subscriptionEndsAt: string
- subscription: {
- updateURL: string
- cancelURL: string
- paymentInformation: {
- paymentMethod: string
- cardType: string
- lastFourDigits: string
- expiryDate: string
- }
- lastPayment: {
- amount: number
- currency: string
- date: string
- }
- nextPayment: {
- amount: number
- currency: string
- date: string
- }
- }
+ stripeCustomerID: string
+ stripeSubscriptionID: string
}
-const SubscribePanel = (props: { monthlyPrice: string; subscribeMonthly: () => void; yearlyPrice: string; subscribeYearly: () => void }) => {
- return (
- <div>
- <HStack spacing={4}>
- <VStack spacing={4} className="py-2 px-4 shadow rounded text-center">
- <div>
- <span className="block text-xs p-1 rounded mb-2">&nbsp;</span>
- <span className="text-category">Monthy Subscription</span>
- </div>
- <span className="text-display2 block">
- {props.monthlyPrice}
- <span className="text-title">/month</span>
- </span>
- <Button variant="secondary" size="small" className="mx-auto" onClick={props.subscribeMonthly}>
- Subscribe
- </Button>
- </VStack>
- <VStack spacing={4} className="py-2 px-4 shadow rounded text-center">
- <div>
- <span className="block text-xs bg-yellow-100 p-1 rounded mb-2">
- <strong>2 months free!</strong>
- </span>
- <span className="text-category">Yearly Subscription</span>
- </div>
- <span className="text-display2 block">
- {props.yearlyPrice}
- <span className="text-title">/year</span>
- </span>
- <Button variant="secondary" size="small" className="mx-auto" onClick={props.subscribeYearly}>
- Subscribe
- </Button>
- </VStack>
- </HStack>
-
- <span className="block mt-4 text-muted">VAT/Tax may be added during checkout.</span>
- </div>
- )
+interface PlanCardProps {
+ name: string
+ price: string
+ period: string
+ description: string
+ features: string[]
+ isCurrent: boolean
+ isHighlighted?: boolean
+ buttonText: string
+ buttonVariant: "primary" | "secondary"
+ onButtonClick?: () => void
+ isLoading: boolean
}
-const ActiveSubscriptionInformation = (props: ManageBillingPageProps) => {
- const fider = useFider()
- const { isReady, openUrl } = usePaddle({ ...props.paddle })
-
- const open = (url: string) => () => {
- if (isReady) {
- openUrl(url)
- }
- }
+const PlanCard = (props: PlanCardProps) => {
+ const showButton = !!props.onButtonClick
+ const showCurrentLabel = props.isCurrent && !props.onButtonClick
- return (
- <VStack>
- <h3 className="text-display">Your subscription is Active</h3>
- <CardDetails {...props.subscription.paymentInformation} />
- <p>
- Your next payment is{" "}
- <strong>
- <Money amount={props.subscription.nextPayment.amount} currency={props.subscription.nextPayment.currency} locale={fider.currentLocale} />
- </strong>{" "}
- on{" "}
- <strong>
- <Moment locale={fider.currentLocale} format="date" date={props.subscription.nextPayment.date} />
- </strong>
- .
- </p>
- <p>
- You can{" "}
- <a href="#" rel="noopener" className="text-link" onClick={open(props.subscription.updateURL)}>
- update
- </a>{" "}
- your payment information or{" "}
- <a href="#" rel="noopener" className="text-link" onClick={open(props.subscription.cancelURL)}>
- cancel
- </a>{" "}
- your subscription at any time.
- </p>
- <p>
- To change your billing interval from monthly to yearly or vice-versa, please contact us at{" "}
- <a className="text-link" href="mailto:[email protected]">
- </a>
- .
- </p>
- </VStack>
+ const cardClasses = ["c-plan-card p-6", props.isHighlighted ? "c-plan-card--highlighted" : "bg-gray-100", props.isCurrent ? "c-plan-card--current" : ""].join(
+ " "
)
-}
-
-const CancelledSubscriptionInformation = (props: ManageBillingPageProps) => {
- const fider = useFider()
- const paddle = usePaddle({ ...props.paddle })
- const isExpired = new Date(props.subscriptionEndsAt) <= new Date()
+ const textColor = props.isHighlighted ? "text-white" : "text-gray-900"
return (
- <VStack>
- <h3 className="text-display">Your subscription was Cancelled</h3>
- {isExpired ? (
- <p>
- Your subscription expired on{" "}
- <strong>
- <Moment locale={fider.currentLocale} format="date" date={props.subscriptionEndsAt} />
- </strong>
- . Resubscribe to remove the read-only constraint from this site.
- </p>
- ) : (
- <p>
- Your subscription is currently cancelled. This site will stay active until{" "}
- <strong>
- <Moment locale={fider.currentLocale} format="date" date={props.subscriptionEndsAt} />
- </strong>
- . <br /> Resubscribe to avoid a service interruption.
- </p>
- )}
- <SubscribePanel {...paddle} />
- </VStack>
+ <div className={cardClasses}>
+ <VStack spacing={4}>
+ <HStack justify="between" align="center">
+ <span className={`text-title ${textColor}`}>{props.name}</span>
+ {props.isCurrent && <span className="text-xs text-semibold px-2 py-1 rounded-full bg-green-100 text-green-700">CURRENT</span>}
+ </HStack>
+
+ <div className="flex flex-items-baseline">
+ <span className={`text-2xl text-bold ${textColor}`}>{props.price}</span>
+ {props.period && <span className={`text-sm c-plan-card__muted ${props.isHighlighted ? "" : "text-gray-500"}`}>/{props.period}</span>}
+ </div>
+
+ <p className={`text-sm c-plan-card__muted ${props.isHighlighted ? "" : "text-gray-600"}`}>{props.description}</p>
+
+ {showButton && (
+ <Button variant={props.buttonVariant} onClick={props.onButtonClick} disabled={props.isLoading}>
+ {props.isLoading ? "Loading..." : props.buttonText}
+ </Button>
+ )}
+ {showCurrentLabel && <div className="text-center py-2 px-4 text-sm text-medium text-gray-500 bg-gray-200 rounded-md">Current Plan</div>}
+
+ <VStack spacing={2} className={`pt-4 border-t c-plan-card__light ${props.isHighlighted ? "border-gray-700" : "border-gray-200 text-gray-700"}`}>
+ {props.features.map((feature, index) => (
+ <HStack key={index} spacing={2} align="start">
+ <Icon sprite={IconCheck} className="text-green-500" height="16" />
+ <span className="text-sm">{feature}</span>
+ </HStack>
+ ))}
+ </VStack>
+ </VStack>
+ </div>
)
}
-const TrialInformation = (props: ManageBillingPageProps) => {
- const fider = useFider()
- const paddle = usePaddle({ ...props.paddle })
-
- const isExpired = new Date(props.trialEndsAt) <= new Date()
-
- return (
- <VStack>
- <h3 className="text-display">Trial</h3>
- {isExpired ? (
- <p>
- Your trial expired on{" "}
- <strong>
- <Moment locale={fider.currentLocale} format="date" date={props.trialEndsAt} />
- </strong>
- . Subscribe to remove the read-only constraint from this site.
- </p>
- ) : (
- <p>
- Your account is currently on a trial until{" "}
- <strong>
- <Moment locale={fider.currentLocale} format="date" date={props.trialEndsAt} />
- </strong>
- . <br />
- Subscribe before the end of your trial to avoid a service interruption.
- </p>
- )}
-
- <SubscribePanel {...paddle} />
- </VStack>
- )
-}
+const ManageBillingPage = (props: ManageBillingPageProps) => {
+ const [isLoading, setIsLoading] = useState(false)
+ const hasSubscription = !!props.stripeSubscriptionID
+
+ const openPortal = async () => {
+ setIsLoading(true)
+ const result = await http.post<{ url: string }>("/_api/admin/billing/portal")
+ if (result.ok) {
+ window.location.href = result.data.url
+ } else {
+ setIsLoading(false)
+ }
+ }
-const FreeForeverInformation = () => {
- return (
- <VStack>
- <h3 className="text-display">Free!</h3>
- <p>
- This site is on a <strong>Forever Free</strong> subscription, enjoy it! 🎉
- </p>
- <p className="text-muted">
- You can still help us fund the development of Fider by contribution to our{" "}
- <a rel="noopener" target="_blank" className="text-link" href="https://opencollective.com/fider">
- OpenCollective
- </a>
- .
- </p>
- </VStack>
- )
-}
+ const startCheckout = async () => {
+ setIsLoading(true)
+ const result = await http.post<{ url: string }>("/_api/admin/billing/checkout")
+ if (result.ok) {
+ window.location.href = result.data.url
+ } else {
+ setIsLoading(false)
+ }
+ }
-const OpenCollectiveInformation = () => {
- return (
- <VStack>
- <h3 className="text-display">Open Source Subscription</h3>
- <p>
- This site is linked to a monthly{" "}
- <a rel="noopener" target="_blank" className="text-link" href="https://opencollective.com/fider">
- OpenCollective
- </a>{" "}
- donation.
- </p>
- <p className="text-muted">Thanks for being a financial support! Keep your monthly donation active to avoid a service interruption.</p>
- </VStack>
- )
-}
+ const freeFeatures = ["Unlimited feedback posts", "Unlimited voters", "Your own subdomain or custom domain", "All core functionality", "Email notifications"]
-const ManageBillingPage = (props: ManageBillingPageProps) => {
- const showPaddleFooter = [BillingStatus.Active, BillingStatus.Cancelled, BillingStatus.Trial].includes(props.status)
+ const proFeatures = ["Everything in Free", "Content Moderation", "Responsive email support", "Priority support"]
return (
- <AdminPageContainer id="p-admin-billing" name="billing" title="Billing" subtitle="Manage your billing settings">
- {props.status === BillingStatus.Trial && <TrialInformation {...props} />}
- {props.status === BillingStatus.Active && <ActiveSubscriptionInformation {...props} />}
- {props.status === BillingStatus.Cancelled && <CancelledSubscriptionInformation {...props} />}
- {props.status === BillingStatus.FreeForever && <FreeForeverInformation />}
- {props.status === BillingStatus.OpenCollective && <OpenCollectiveInformation />}
-
- {showPaddleFooter && (
- <p className="text-muted mt-4">
- <strong>
- <a href="https://paddle.com" target="_blank" rel="noopener" className="text-link">
- Paddle
- </a>
- </strong>{" "}
- is our billing partner. You may see {'"PADDLE.NET* FIDER"'} on your credit card.
- </p>
- )}
+ <AdminPageContainer id="p-admin-billing" name="billing" title="Billing" subtitle="Manage your subscription and billing">
+ <p>Fider is free forever. But if you need advanced features and support, consider upgrading to Pro.</p>
+ <div className="c-billing-plans">
+ <PlanCard
+ name="Free"
+ price="$0"
+ period="month"
+ description="Perfect for getting started with feedback collection."
+ features={freeFeatures}
+ isCurrent={!hasSubscription}
+ buttonText="Downgrade"
+ buttonVariant="secondary"
+ onButtonClick={hasSubscription ? openPortal : undefined}
+ isLoading={isLoading && hasSubscription}
+ />
+
+ <PlanCard
+ name="Pro"
+ price="$25"
+ period="month"
+ description="For teams that need advanced features and support."
+ features={proFeatures}
+ isCurrent={hasSubscription}
+ isHighlighted={true}
+ buttonText={hasSubscription ? "Manage Billing" : "Upgrade to Pro"}
+ buttonVariant="primary"
+ onButtonClick={hasSubscription ? openPortal : startCheckout}
+ isLoading={isLoading}
+ />
+ </div>
</AdminPageContainer>
)
}
diff --git a/public/pages/Administration/pages/ManageBilling2.page.tsx b/public/pages/Administration/pages/ManageBilling2.page.tsx
deleted file mode 100644
index 2a60ead10..000000000
--- a/public/pages/Administration/pages/ManageBilling2.page.tsx
+++ /dev/null
@@ -1,137 +0,0 @@
-import React, { useState } from "react"
-import { Button, Icon } from "@fider/components"
-import { HStack, VStack } from "@fider/components/layout"
-import { AdminPageContainer } from "../components/AdminBasePage"
-import { http } from "@fider/services"
-import IconCheck from "@fider/assets/images/heroicons-check.svg"
-
-import "./ManageBilling2.page.scss"
-
-interface ManageBilling2PageProps {
- stripeCustomerID: string
- stripeSubscriptionID: string
-}
-
-interface PlanCardProps {
- name: string
- price: string
- period: string
- description: string
- features: string[]
- isCurrent: boolean
- isHighlighted?: boolean
- buttonText: string
- buttonVariant: "primary" | "secondary"
- onButtonClick?: () => void
- isLoading: boolean
-}
-
-const PlanCard = (props: PlanCardProps) => {
- const showButton = !!props.onButtonClick
- const showCurrentLabel = props.isCurrent && !props.onButtonClick
-
- const cardClasses = ["c-plan-card p-6", props.isHighlighted ? "c-plan-card--highlighted" : "bg-gray-100", props.isCurrent ? "c-plan-card--current" : ""].join(
- " "
- )
-
- const textColor = props.isHighlighted ? "text-white" : "text-gray-900"
-
- return (
- <div className={cardClasses}>
- <VStack spacing={4}>
- <HStack justify="between" align="center">
- <span className={`text-title ${textColor}`}>{props.name}</span>
- {props.isCurrent && <span className="text-xs text-semibold px-2 py-1 rounded-full bg-green-100 text-green-700">CURRENT</span>}
- </HStack>
-
- <div className="flex flex-items-baseline">
- <span className={`text-2xl text-bold ${textColor}`}>{props.price}</span>
- {props.period && <span className={`text-sm c-plan-card__muted ${props.isHighlighted ? "" : "text-gray-500"}`}>/{props.period}</span>}
- </div>
-
- <p className={`text-sm c-plan-card__muted ${props.isHighlighted ? "" : "text-gray-600"}`}>{props.description}</p>
-
- {showButton && (
- <Button variant={props.buttonVariant} onClick={props.onButtonClick} disabled={props.isLoading}>
- {props.isLoading ? "Loading..." : props.buttonText}
- </Button>
- )}
- {showCurrentLabel && <div className="text-center py-2 px-4 text-sm text-medium text-gray-500 bg-gray-200 rounded-md">Current Plan</div>}
-
- <VStack spacing={2} className={`pt-4 border-t c-plan-card__light ${props.isHighlighted ? "border-gray-700" : "border-gray-200 text-gray-700"}`}>
- {props.features.map((feature, index) => (
- <HStack key={index} spacing={2} align="start">
- <Icon sprite={IconCheck} className="text-green-500" height="16" />
- <span className="text-sm">{feature}</span>
- </HStack>
- ))}
- </VStack>
- </VStack>
- </div>
- )
-}
-
-const ManageBilling2Page = (props: ManageBilling2PageProps) => {
- const [isLoading, setIsLoading] = useState(false)
- const hasSubscription = !!props.stripeSubscriptionID
-
- const openPortal = async () => {
- setIsLoading(true)
- const result = await http.post<{ url: string }>("/_api/admin/billing2/portal")
- if (result.ok) {
- window.location.href = result.data.url
- } else {
- setIsLoading(false)
- }
- }
-
- const startCheckout = async () => {
- setIsLoading(true)
- const result = await http.post<{ url: string }>("/_api/admin/billing2/checkout")
- if (result.ok) {
- window.location.href = result.data.url
- } else {
- setIsLoading(false)
- }
- }
-
- const freeFeatures = ["Unlimited feedback posts", "Unlimited voters", "Your own subdomain or custom domain", "All core functionality", "Email notifications"]
-
- const proFeatures = ["Everything in Free", "Content Moderation", "Responsive email support", "Priority support"]
-
- return (
- <AdminPageContainer id="p-admin-billing2" name="billing" title="Billing" subtitle="Manage your subscription and billing">
- <p>Fider is free forever. But if you need advanced features and support, consider upgrading to Pro.</p>
- <div className="c-billing-plans">
- <PlanCard
- name="Free"
- price="$0"
- period="month"
- description="Perfect for getting started with feedback collection."
- features={freeFeatures}
- isCurrent={!hasSubscription}
- buttonText="Downgrade"
- buttonVariant="secondary"
- onButtonClick={hasSubscription ? openPortal : undefined}
- isLoading={isLoading && hasSubscription}
- />
-
- <PlanCard
- name="Pro"
- price="$25"
- period="month"
- description="For teams that need advanced features and support."
- features={proFeatures}
- isCurrent={hasSubscription}
- isHighlighted={true}
- buttonText={hasSubscription ? "Manage Billing" : "Upgrade to Pro"}
- buttonVariant="primary"
- onButtonClick={hasSubscription ? openPortal : startCheckout}
- isLoading={isLoading}
- />
- </div>
- </AdminPageContainer>
- )
-}
-
-export default ManageBilling2Page
diff --git a/public/services/actions/billing.ts b/public/services/actions/billing.ts
deleted file mode 100644
index 942a823be..000000000
--- a/public/services/actions/billing.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { http, Result } from "../http"
-
-interface CheckoutPageLink {
- url: string
-}
-
-export const generateCheckoutLink = async (planId: string): Promise<Result<CheckoutPageLink>> => {
- return await http.post("/_api/billing/checkout-link", { planId })
-}
diff --git a/public/services/actions/index.ts b/public/services/actions/index.ts
index 41b5764d9..4aef473aa 100644
--- a/public/services/actions/index.ts
+++ b/public/services/actions/index.ts
@@ -6,4 +6,3 @@ export * from "./notification"
export * from "./invite"
export * from "./infra"
export * from "./webhook"
-export * from "./billing"