Open platform to collect and prioritize feedback
enhancement: improve subscription management
goenning47302f5a0554
diff --git a/app/handlers/billing.go b/app/handlers/billing.goindex ebb998e51..7685b4b0c 100644--- a/app/handlers/billing.go+++ b/app/handlers/billing.go@@ -41,7 +41,6 @@ func ManageBilling() web.HandlerFunc {func GenerateCheckoutLink() web.HandlerFunc {return func(c *web.Context) error {generateLink := &cmd.GenerateCheckoutLink{- Email: c.User().Email,ReturnURL: c.BaseURL() + "/admin/billing",Passthrough: dto.PaddlePassthrough{TenantID: c.Tenant().ID,diff --git a/app/jobs/job.go b/app/jobs/job.goindex cf5d3823d..a4e8c75a5 100644--- a/app/jobs/job.go+++ b/app/jobs/job.go@@ -32,6 +32,9 @@ func NewJob(ctx context.Context, name string, handler Handler) (string, fiderJob}func (j fiderJob) Run() {+ locked := false+ unlock := func() {}+ctx, trx, err := newJobContext()if err != nil {log.Error(ctx, err)@@ -41,8 +44,24 @@ func (j fiderJob) Run() {start := time.Now()ctx.LastSuccessfulRun = getLastSuccessfulRun(ctx, j.Name)+ logFinish := func() {+ elapsedMs := time.Since(start).Nanoseconds() / int64(time.Millisecond)+ log.Debugf(ctx, "Job '@{JobName}' finished in @{ElapsedMs:magenta}ms", dto.Props{+ "ElapsedMs": elapsedMs,+ "JobName": j.Name,+ })++ // Jobs should take at least 1sec before unlocking to avoid double execution+ if elapsedMs <= 1000 {+ waitMs := time.Duration(1000 - elapsedMs)+ time.Sleep(waitMs * time.Millisecond)+ }+ unlock()+ }+defer func() {if r := recover(); r != nil {+ logFinish()log.Error(ctx, errors.Panicked(r))setLastFailedRun(j.Name, start)trx.MustRollback()@@ -53,7 +72,7 @@ func (j fiderJob) Run() {"JobName": j.Name,})- locked, unlock := dbx.TryLock(ctx, trx, j.Name)+ locked, unlock = dbx.TryLock(ctx, trx, j.Name)if !locked {log.Debugf(ctx, "Job '@{JobName}' skipped, could not acquire lock", dto.Props{"JobName": j.Name,@@ -62,20 +81,7 @@ func (j fiderJob) Run() {return}- defer func() {- elapsedMs := time.Since(start).Nanoseconds() / int64(time.Millisecond)- log.Debugf(ctx, "Job '@{JobName}' finished in @{ElapsedMs:magenta}ms", dto.Props{- "ElapsedMs": elapsedMs,- "JobName": j.Name,- })-- // Jobs should take at least 1sec before unlocking to avoid double execution- if elapsedMs <= 1000 {- waitMs := time.Duration(1000 - elapsedMs)- time.Sleep(waitMs * time.Millisecond)- }- unlock()- }()+ defer logFinish()if err := j.Handler.Run(ctx); err != nil {log.Error(ctx, err)diff --git a/app/models/cmd/billing.go b/app/models/cmd/billing.goindex ea06757d7..8c6ff0ac1 100644--- a/app/models/cmd/billing.go+++ b/app/models/cmd/billing.go@@ -7,7 +7,6 @@ import ()type GenerateCheckoutLink struct {- Email stringReturnURL stringPassthrough dto.PaddlePassthroughdiff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.goindex 36f6576dd..70c902781 100644--- a/app/pkg/web/engine.go+++ b/app/pkg/web/engine.go@@ -35,7 +35,7 @@ var (cspObject = "object-src 'none'"cspFrame = "frame-src 'self'"cspMedia = "media-src 'none'"- cspConnect = "connect-src 'self' https://www.google-analytics.com %[2]s"+ cspConnect = "connect-src 'self' https://ipinfo.io https://www.google-analytics.com %[2]s"//CspPolicyTemplate is the template used to generate the policyCspPolicyTemplate = 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.goindex 9b4ffda60..8e599b981 100644--- a/app/services/billing/paddle/paddle.go+++ b/app/services/billing/paddle/paddle.go@@ -57,7 +57,6 @@ func generateCheckoutLink(ctx context.Context, c *cmd.GenerateCheckoutLink) erroparams.Set("vendor_id", env.Config.Paddle.VendorID)params.Set("vendor_auth_code", env.Config.Paddle.VendorAuthCode)params.Set("product_id", env.Config.Paddle.PlanID)- params.Set("customer_email", c.Email)params.Set("return_url", c.ReturnURL)params.Set("passthrough", string(passthrough))diff --git a/app/services/sqlstore/postgres/billing.go b/app/services/sqlstore/postgres/billing.goindex 8a7546b7d..ce2fa93b5 100644--- a/app/services/sqlstore/postgres/billing.go+++ b/app/services/sqlstore/postgres/billing.go@@ -10,6 +10,7 @@ import ("github.com/getfider/fider/app/models/query""github.com/getfider/fider/app/pkg/dbx""github.com/getfider/fider/app/pkg/errors"+ "github.com/lib/pq")type dbBillingState struct {@@ -72,6 +73,16 @@ func activateBillingSubscription(ctx context.Context, c *cmd.ActivateBillingSubsif err != nil {return errors.Wrap(err, "failed activate billing subscription")}++ _, err = trx.Execute(`+ UPDATE tenants+ SET status = $2+ WHERE id = $1+ `, c.TenantID, enum.TenantActive)+ if err != nil {+ return errors.Wrap(err, "failed activate tenant")+ }+return nil})}@@ -94,29 +105,43 @@ func lockExpiredTenants(ctx context.Context, c *cmd.LockExpiredTenants) error {return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {now := time.Now()- //Lock expired tenants in trial- countTrialLocked, err := trx.Execute(`- UPDATE tenants- SET status = $1- WHERE id IN (SELECT tenant_id FROM tenants_billing WHERE status = $2 AND trial_ends_at <= $3)- AND status <> $1- `, enum.TenantLocked, enum.BillingTrial, now)- if err != nil {- return errors.Wrap(err, "failed to lock expired trial tenants")+ type tenant struct {+ Id int `db:"id"`}- //Lock tenants with expired cancelled subscription- countCancelledLocked, err := trx.Execute(`- UPDATE tenants- SET status = $1- WHERE id IN (SELECT tenant_id FROM tenants_billing WHERE status = $2 AND subscription_ends_at <= $3)- AND status <> $1- `, enum.TenantLocked, enum.BillingCancelled, now)+ 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 (+ (tb.status = $2 AND trial_ends_at <= $4)+ OR (tb.status = $3 AND subscription_ends_at <= $4)+ )`, enum.TenantLocked, enum.BillingTrial, enum.BillingCancelled, now)if err != nil {- return errors.Wrap(err, "failed to lock expired cancelled tenants")+ 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.NumOfTenantsLocked = countTrialLocked + countCancelledLockedreturn nil})}diff --git a/public/components/ReadOnlyNotice.tsx b/public/components/ReadOnlyNotice.tsxindex 0b254cd4e..72490b2aa 100644--- a/public/components/ReadOnlyNotice.tsx+++ b/public/components/ReadOnlyNotice.tsx@@ -12,7 +12,7 @@ export const ReadOnlyNotice = () => {return (<Message alignment="center" type="warning">This website is currently in read-only mode because there is no active subscription. Visit{" "}- <a className="text-link" href="/billing">+ <a className="text-link" href="/admin/billing">Billing</a>{" "}to subscribe.diff --git a/public/pages/Administration/components/billing/SubscribeButton.tsx b/public/pages/Administration/components/billing/SubscribeButton.tsxnew file mode 100644index 000000000..53cb5e5b7--- /dev/null+++ b/public/pages/Administration/components/billing/SubscribeButton.tsx@@ -0,0 +1,60 @@+import React, { useEffect, useState } from "react"+import { Button } from "@fider/components"+import { getCountryCode } from "@fider/services"++interface SubscribeButtonProps {+ onClick: () => void+}++interface SubscriptionPrice {+ currency: string+ symbol: string+ countries: string[]+ amount: number+}++const prices = [+ { currency: "USD", symbol: "$", amount: 30, countries: ["US"] },+ {+ currency: "EUR",+ symbol: "€",+ amount: 28,+ countries: ["AD", "AT", "BE", "FI", "FR", "GF", "TF", "DE", "GR", "GP", "VA", "IE", "IT", "LU", "MQ", "YT", "MC", "NL", "PT", "RE", "PM", "SM", "CS", "ES"],+ },+ { currency: "GBP", symbol: "£", amount: 26, countries: ["GB", "UK"] },+]++const getPrice = async (): Promise<SubscriptionPrice> => {+ const countryCode = await getCountryCode()++ if (countryCode) {+ for (const price of prices) {+ if (price.countries.includes(countryCode)) {+ return price+ }+ }+ }++ return prices[0]+}++export const SubscribeButton = (props: SubscribeButtonProps) => {+ const [price, setPrice] = useState<SubscriptionPrice | undefined>()++ useEffect(() => {+ getPrice().then(setPrice)+ }, [])++ if (!price) {+ return null+ }++ return (+ <p>+ <Button variant="primary" onClick={props.onClick}>+ Resubscribe for {price.symbol} {price.amount}/mo+ </Button>+ <span className="block text-muted">Taxes may be added during checkout.</span>+ </p>+ )+}diff --git a/public/pages/Administration/pages/ManageBilling.page.tsx b/public/pages/Administration/pages/ManageBilling.page.tsxindex 136fb85e9..c6ac2fc3e 100644--- a/public/pages/Administration/pages/ManageBilling.page.tsx+++ b/public/pages/Administration/pages/ManageBilling.page.tsx@@ -1,4 +1,4 @@-import { Button, Moment, Money } from "@fider/components"+import { Moment, Money } from "@fider/components"import { VStack } from "@fider/components/layout"import { useFider } from "@fider/hooks"import { BillingStatus } from "@fider/models"@@ -6,6 +6,7 @@ import { actions } from "@fider/services"import React from "react"import { AdminPageContainer } from "../components/AdminBasePage"import { CardDetails } from "../components/billing/CardDetails"+import { SubscribeButton } from "../components/billing/SubscribeButton"interface ManageBillingPageProps {status: BillingStatus@@ -56,11 +57,11 @@ const ActiveSubscriptionInformation = (props: ManageBillingPageProps) => {</p><p>You can{" "}- <a rel="noopener" className="text-link" href={props.subscription.updateURL}>+ <a rel="noopener" target="_blank" className="text-link" href={props.subscription.updateURL}>update</a>{" "}your payment information or{" "}- <a rel="noopener" className="text-link" href={props.subscription.cancelURL}>+ <a rel="noopener" target="_blank" className="text-link" href={props.subscription.cancelURL}>cancel</a>{" "}your subscription.@@ -72,10 +73,11 @@ const ActiveSubscriptionInformation = (props: ManageBillingPageProps) => {const CancelledSubscriptionInformation = (props: ManageBillingPageProps) => {const fider = useFider()- const isExpired = new Date(props.trialEndsAt) <= new Date()+ const isExpired = new Date(props.subscriptionEndsAt) <= new Date()return (- <>+ <VStack>+ <h3 className="text-display">Your subscription was Cancelled</h3>{isExpired ? (<p>Your subscription expired on{" "}@@ -93,11 +95,8 @@ const CancelledSubscriptionInformation = (props: ManageBillingPageProps) => {. <br /> Resubscribe to avoid a service interruption.</p>)}-- <Button variant="primary" onClick={subscribe}>- Resubscribe for $30/mo + Tax- </Button>- </>+ <SubscribeButton onClick={subscribe} />+ </VStack>)}@@ -107,7 +106,8 @@ const TrialInformation = (props: ManageBillingPageProps) => {const isExpired = new Date(props.trialEndsAt) <= new Date()return (- <>+ <VStack>+ <h3 className="text-display">Trial</h3>{isExpired ? (<p>Your trial expired on{" "}@@ -127,29 +127,67 @@ const TrialInformation = (props: ManageBillingPageProps) => {</p>)}- <Button variant="primary" onClick={subscribe}>- Subscribe for $30/mo + Tax- </Button>- </>+ <SubscribeButton onClick={subscribe} />+ </VStack>+ )+}++const FreeForeverInformation = () => {+ return (+ <VStack>+ <h3 className="text-display">Free!</h3>+ <p>+ For some reason this site is under a <strong>Forever Free</strong> subscription, enjoy it! 🎉+ </p>+ <p>+ You can still help us fund the developer of Fider by contribution to our{" "}+ <a rel="noopener" target="_blank" className="text-link" href="https://opencollective.com/fider">+ OpenCollective+ </a>+ .+ </p>+ </VStack>+ )+}++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>Thanks for being a financial support! Keep your monthly donation active to avoid a service interruption.</p>+ </VStack>)}const ManageBillingPage = (props: ManageBillingPageProps) => {+ const showPaddleFooter = [BillingStatus.Active, BillingStatus.Cancelled, BillingStatus.Trial].includes(props.status)+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 />}- <p className="text-muted mt-4">- We use{" "}- <strong>- <a href="https://paddle.com" target="_blank" rel="noopener" className="text-link">- Paddle- </a>- </strong>{" "}- as our billing partner. You may see {'"PADDLE.COM FIDER"'} on your credit card.- </p>+ {showPaddleFooter && (+ <p className="text-muted mt-4">+ We use{" "}+ <strong>+ <a href="https://paddle.com" target="_blank" rel="noopener" className="text-link">+ Paddle+ </a>+ </strong>{" "}+ as our billing partner. You may see {'"PADDLE.NET* FIDERIO"'} on your credit card.+ </p>+ )}</AdminPageContainer>)}diff --git a/public/services/geo.ts b/public/services/geo.tsnew file mode 100644index 000000000..fdb8f05d7--- /dev/null+++ b/public/services/geo.ts@@ -0,0 +1,21 @@+import { cache } from "./cache"++const CACHE_COUNTRYCODE_KEY = "CountryCode"++export const getCountryCode = async (): Promise<string | undefined> => {+ const countryCode = cache.session.get(CACHE_COUNTRYCODE_KEY)+ if (countryCode) {+ return countryCode+ }++ try {+ const response = await fetch("https://ipinfo.io/json")+ if (response.status === 200) {+ const data = await response.json()+ cache.session.set(CACHE_COUNTRYCODE_KEY, data.country)+ return data.country+ }+ } catch (err) {+ console.error(err)+ }+}diff --git a/public/services/index.ts b/public/services/index.tsindex d941c04fc..09dc3097e 100644--- a/public/services/index.ts+++ b/public/services/index.ts@@ -3,6 +3,7 @@ export * from "./cache"export * from "./analytics"export * from "./fider"export * from "./jwt"+export * from "./geo"export * from "./utils"export * from "./i18n"import * as markdown from "./markdown"diff --git a/views/email/trial_1day.html b/views/email/trial_1day.htmlindex 7133c3a76..1324845e8 100644--- a/views/email/trial_1day.html+++ b/views/email/trial_1day.html@@ -5,7 +5,7 @@<td><h2 style="color:#1c262d">Hey {{ .name }},</h2><p style="color:#1c262d">Just a gently reminder that your Fider site <a href="{{ .url }}">{{ .url }}</a> will expire tomorrow and you won’t be able to access your site anymore.</p>- <p style="color:#1c262d">You can subscribe from the <a href="{{ .url }}/billing">Billing</a> page of your site.</p>+ <p style="color:#1c262d">You can subscribe from the <a href="{{ .url }}/admin/billing">Billing</a> page of your site.</p><p style="color:#1c262d">Let me know if you have any questions or need any assistance!</p><p></p><p style="color:#1c262d"> - Guilherme</p>diff --git a/views/email/trial_7days.html b/views/email/trial_7days.htmlindex c588eaa23..57d64e8f9 100644--- a/views/email/trial_7days.html+++ b/views/email/trial_7days.html@@ -7,7 +7,7 @@<p style="color:#1c262d">It’s been a fun journey, but unfortunately, we’re coming to the end of your trial period. We’d love to keep this going!</p><p style="color:#1c262d">In order to keep <a href="{{ .url }}">{{ .url }}</a> online, you’ll need to subscribe to our paid plan.</p><p style="color:#1c262d">Otherwise, your trial will end in 7 days and you won’t be able to access your site anymore.</p>- <p style="color:#1c262d">You can subscribe from the <a href="{{ .url }}/billing">Billing</a> page of your site.</p>+ <p style="color:#1c262d">You can subscribe from the <a href="{{ .url }}/admin/billing">Billing</a> page of your site.</p><p style="color:#1c262d">Let me know if you have any questions or need any assistance!</p><p></p><p style="color:#1c262d"> - Guilherme</p>