Open platform to collect and prioritize feedback
enhancement: general billing improvements (#718)
Guilherme Oenninge2f6589b1f59
diff --git a/app/actions/billing.go b/app/actions/billing.goindex 2a045ec49..b34c412cb 100644--- a/app/actions/billing.go+++ b/app/actions/billing.go@@ -92,6 +92,14 @@ func (input *CreateEditBillingPaymentInfo) Validate(user *models.User, services} else if isUpdate && input.Model.AddressCountry != current.CardCountry {result.AddFieldFailure("addressCountry", "Country doesn't match with card issue country.")}++ if isReplacing || isUpdate {+ prevIsEU := vat.IsEU(current.AddressCountry)+ nextIsEU := vat.IsEU(input.Model.AddressCountry)+ if prevIsEU != nextIsEU {+ result.AddFieldFailure("currency", "Billing currency cannot be changed.")+ }+ }}if input.Model.VATNumber != "" && vat.IsEU(input.Model.AddressCountry) && (isNew || input.Model.VATNumber != current.VATNumber) {diff --git a/app/cmd/routes.go b/app/cmd/routes.goindex 5819a6fb3..1bc35011f 100644--- a/app/cmd/routes.go+++ b/app/cmd/routes.go@@ -160,6 +160,7 @@ func routes(r *web.Engine) *web.Engine {ui.Use(middlewares.RequireBillingEnabled())ui.Get("/admin/billing", handlers.BillingPage())+ ui.Get("/_api/admin/billing/plans/:countryCode", handlers.GetBillingPlans())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())diff --git a/app/handlers/billing.go b/app/handlers/billing.goindex 97e14db56..811f4c883 100644--- a/app/handlers/billing.go+++ b/app/handlers/billing.go@@ -9,8 +9,9 @@ import (// BillingPage is the billing settings pagefunc BillingPage() web.HandlerFunc {return func(c web.Context) error {+ var err errorif c.Tenant().Billing.StripeCustomerID == "" {- _, err := c.Services().Billing.CreateCustomer("")+ _, err = c.Services().Billing.CreateCustomer("")if err != nil {return err}@@ -23,11 +24,10 @@ func BillingPage() web.HandlerFunc {var invoiceDue *models.UpcomingInvoiceif c.Tenant().Billing.StripeSubscriptionID != "" {- inv, err := c.Services().Billing.GetUpcomingInvoice()+ invoiceDue, err = c.Services().Billing.GetUpcomingInvoice()if err != nil {return c.Failure(err)}- invoiceDue = inv}paymentInfo, err := c.Services().Billing.GetPaymentInfo()@@ -35,9 +35,12 @@ func BillingPage() web.HandlerFunc {return c.Failure(err)}- plans, err := c.Services().Billing.ListPlans()- if err != nil {- return c.Failure(err)+ var plans []*models.BillingPlan+ if paymentInfo != nil {+ plans, err = c.Services().Billing.ListPlans(paymentInfo.AddressCountry)+ if err != nil {+ return c.Failure(err)+ }}tenantUserCount, err := c.Services().Users.Count()@@ -76,13 +79,29 @@ func UpdatePaymentInfo() web.HandlerFunc {}}+// GetBillingPlans returns a list of plans for given country code+func GetBillingPlans() web.HandlerFunc {+ return func(c web.Context) error {+ countryCode := c.Param("countryCode")+ plans, err := c.Services().Billing.ListPlans(countryCode)+ if err != nil {+ return c.Failure(err)+ }+ return c.Ok(plans)+ }+}+// BillingSubscribe subscribes current tenant to given plan on stripefunc BillingSubscribe() web.HandlerFunc {return func(c web.Context) error {- var plan *models.BillingPlanplanID := c.Param("planID")- plan, err := c.Services().Billing.GetPlanByID(planID)+ paymentInfo, err := c.Services().Billing.GetPaymentInfo()+ if err != nil {+ return c.Failure(err)+ }++ plan, err := c.Services().Billing.GetPlanByID(paymentInfo.AddressCountry, planID)if err != nil {return c.Failure(err)}diff --git a/app/middlewares/security_test.go b/app/middlewares/security_test.goindex f13b727f5..f15774b2a 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' 'nonce-" + ctxID + "' https://fonts.googleapis.com ; script-src 'self' 'nonce-" + ctxID + "' https://cdn.polyfill.io https://js.stripe.com https://www.google-analytics.com ; img-src 'self' https: data: ; font-src 'self' https://fonts.gstatic.com data: ; object-src 'none'; media-src 'none'; connect-src 'self' https://www.google-analytics.com https://js.stripe.com ; frame-src 'self' https://js.stripe.com"+ expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'nonce-" + ctxID + "' https://fonts.googleapis.com ; script-src 'self' 'nonce-" + ctxID + "' https://cdn.polyfill.io https://js.stripe.com https://www.google-analytics.com ; img-src 'self' https: data: ; font-src 'self' https://fonts.gstatic.com data: ; object-src 'none'; media-src 'none'; connect-src 'self' https://www.google-analytics.com https://ipinfo.io https://js.stripe.com ; frame-src 'self' https://js.stripe.com"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' 'nonce-" + ctxID + "' https://fonts.googleapis.com *.test.fider.io; script-src 'self' 'nonce-" + ctxID + "' https://cdn.polyfill.io https://js.stripe.com https://www.google-analytics.com *.test.fider.io; img-src 'self' https: data: *.test.fider.io; font-src 'self' https://fonts.gstatic.com data: *.test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' https://www.google-analytics.com https://js.stripe.com *.test.fider.io; frame-src 'self' https://js.stripe.com"+ expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'nonce-" + ctxID + "' https://fonts.googleapis.com *.test.fider.io; script-src 'self' 'nonce-" + ctxID + "' https://cdn.polyfill.io https://js.stripe.com https://www.google-analytics.com *.test.fider.io; img-src 'self' https: data: *.test.fider.io; font-src 'self' https://fonts.gstatic.com data: *.test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' https://www.google-analytics.com https://ipinfo.io https://js.stripe.com *.test.fider.io; frame-src 'self' https://js.stripe.com"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' 'nonce-" + ctxID + "' https://fonts.googleapis.com test.fider.io; script-src 'self' 'nonce-" + ctxID + "' https://cdn.polyfill.io https://js.stripe.com https://www.google-analytics.com test.fider.io; img-src 'self' https: data: test.fider.io; font-src 'self' https://fonts.gstatic.com data: test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' https://www.google-analytics.com https://js.stripe.com test.fider.io; frame-src 'self' https://js.stripe.com"+ expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'nonce-" + ctxID + "' https://fonts.googleapis.com test.fider.io; script-src 'self' 'nonce-" + ctxID + "' https://cdn.polyfill.io https://js.stripe.com https://www.google-analytics.com test.fider.io; img-src 'self' https: data: test.fider.io; font-src 'self' https://fonts.gstatic.com data: test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' https://www.google-analytics.com https://ipinfo.io https://js.stripe.com test.fider.io; frame-src 'self' https://js.stripe.com"Expect(status).Equals(http.StatusOK)Expect(response.Header().Get("Content-Security-Policy")).Equals(expectedPolicy)diff --git a/app/models/billing.go b/app/models/billing.goindex 74c888d2e..5cd40deb2 100644--- a/app/models/billing.go+++ b/app/models/billing.go@@ -47,6 +47,7 @@ type BillingPlan struct {ID string `json:"id"`Name string `json:"name"`Description string `json:"description"`+ Currency string `json:"currency"`MaxUsers int `json:"maxUsers"`Price int64 `json:"price"`Interval string `json:"interval"`@@ -54,6 +55,7 @@ type BillingPlan struct {// UpcomingInvoice is the model for upcoming invoice from Stripetype UpcomingInvoice struct {+ Currency string `json:"currency"`DueDate time.Time `json:"dueDate"`AmountDue int64 `json:"amountDue"`}diff --git a/app/pkg/billing/stripe.go b/app/pkg/billing/stripe.goindex 9a0e2a1d7..74f8e22c4 100644--- a/app/pkg/billing/stripe.go+++ b/app/pkg/billing/stripe.go@@ -4,9 +4,12 @@ import ("fmt""sort""strconv"+ "strings""sync""time"+ "github.com/goenning/vat"+"github.com/getfider/fider/app/models""github.com/getfider/fider/app/pkg/env""github.com/getfider/fider/app/pkg/errors"@@ -57,9 +60,10 @@ func (c *Client) CreateCustomer(email string) (string, error) {if c.tenant.Billing.StripeCustomerID == "" {params := &stripe.CustomerParams{Email: stripe.String(email),- Description: stripe.String(customerDesc(c.tenant)),+ Description: stripe.String(c.tenant.Name),}params.AddMetadata("tenant_id", strconv.Itoa(c.tenant.ID))+ params.AddMetadata("tenant_subdomain", c.tenant.Subdomain)customer, err := c.stripe.Customers.New(params)if err != nil {return "", errors.Wrap(err, "failed to create Stripe customer")@@ -146,7 +150,8 @@ func (c *Client) ClearPaymentInfo() error {if current != nil {customerID := c.tenant.Billing.StripeCustomerID_, err = c.stripe.Customers.Update(customerID, &stripe.CustomerParams{- Email: stripe.String(""),+ Description: stripe.String(c.tenant.Name),+ Email: stripe.String(""),TaxInfo: &stripe.CustomerTaxInfoParams{Type: stripe.String(string(stripe.CustomerTaxInfoTypeVAT)),TaxID: stripe.String(""),@@ -176,9 +181,14 @@ func (c *Client) UpdatePaymentInfo(input *models.CreateEditBillingPaymentInfo) ereturn err}+ if !vat.IsEU(input.AddressCountry) {+ input.VATNumber = ""+ }+// update customer infoparams := &stripe.CustomerParams{- Email: stripe.String(input.Email),+ Email: stripe.String(input.Email),+ Description: stripe.String(input.Name),Shipping: &stripe.CustomerShippingDetailsParams{Name: stripe.String(input.Name),Address: &stripe.AddressParams{@@ -190,7 +200,6 @@ func (c *Client) UpdatePaymentInfo(input *models.CreateEditBillingPaymentInfo) eState: stripe.String(input.AddressState),},},- Description: stripe.String(customerDesc(c.tenant)),TaxInfo: &stripe.CustomerTaxInfoParams{Type: stripe.String(string(stripe.CustomerTaxInfoTypeVAT)),TaxID: stripe.String(input.VATNumber),@@ -250,13 +259,9 @@ func (c *Client) UpdatePaymentInfo(input *models.CreateEditBillingPaymentInfo) ereturn nil}-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()+func (c *Client) GetPlanByID(countryCode, planID string) (*models.BillingPlan, error) {+ plans, err := c.ListPlans(countryCode)if err != nil {return nil, err}@@ -270,9 +275,9 @@ func (c *Client) GetPlanByID(planID string) (*models.BillingPlan, error) {}// ListPlans on Stripe-func (c *Client) ListPlans() ([]*models.BillingPlan, error) {+func (c *Client) ListPlans(countryCode string) ([]*models.BillingPlan, error) {if plans != nil {- return plans, nil+ return c.filterByCountryCode(plans, countryCode), nil}mu.Lock()@@ -285,13 +290,18 @@ func (c *Client) ListPlans() ([]*models.BillingPlan, error) {})for it.Next() {plan := it.Plan()+ name, ok := plan.Metadata["friendly_name"]+ if !ok {+ name = plan.Nickname+ }maxUsers, _ := strconv.Atoi(plan.Metadata["max_users"])plans = append(plans, &models.BillingPlan{ID: plan.ID,- Name: plan.Nickname,+ Name: name,Description: plan.Metadata["description"],MaxUsers: maxUsers,Price: plan.Amount,+ Currency: strings.ToUpper(string(plan.Currency)),Interval: string(plan.Interval),})}@@ -303,7 +313,22 @@ func (c *Client) ListPlans() ([]*models.BillingPlan, error) {})}- return plans, nil+ return c.filterByCountryCode(plans, countryCode), nil+}++func (c *Client) filterByCountryCode(plans []*models.BillingPlan, countryCode string) []*models.BillingPlan {+ currency := "USD"+ if vat.IsEU(countryCode) {+ currency = "EUR"+ }++ filteredPlans := make([]*models.BillingPlan, 0)+ for _, p := range plans {+ if p.Currency == currency {+ filteredPlans = append(filteredPlans, p)+ }+ }+ return filteredPlans}// Subscribe current tenant to given plan on Stripe@@ -370,11 +395,17 @@ func (c *Client) GetUpcomingInvoice() (*models.UpcomingInvoice, error) {Subscription: stripe.String(c.tenant.Billing.StripeSubscriptionID),})if err != nil {+ if stripeErr, ok := err.(*stripe.Error); ok {+ if stripeErr.HTTPStatusCode == 404 {+ return nil, nil+ }+ }return nil, errors.Wrap(err, "failed to get upcoming invoice")}dueDate := time.Unix(inv.Date, 0)return &models.UpcomingInvoice{+ Currency: strings.ToUpper(string(inv.Currency)),AmountDue: inv.AmountDue,DueDate: dueDate,}, nildiff --git a/app/pkg/billing/stripe_test.go b/app/pkg/billing/stripe_test.goindex 5a0e17a14..d478e53b8 100644--- a/app/pkg/billing/stripe_test.go+++ b/app/pkg/billing/stripe_test.go@@ -38,14 +38,15 @@ func TestCreateCustomer_WithSubscription(t *testing.T) {})Expect(err).IsNil()- err = client.Subscribe("plan_EIE1LpQIzPXxOn")+ err = client.Subscribe("plan_EKTT1YWe1Zmrtp")Expect(err).IsNil()Expect(tenant.Billing.StripeSubscriptionID).IsNotEmpty()- Expect(tenant.Billing.StripePlanID).Equals("plan_EIE1LpQIzPXxOn")+ Expect(tenant.Billing.StripePlanID).Equals("plan_EKTT1YWe1Zmrtp")inv, err := client.GetUpcomingInvoice()Expect(err).IsNil()Expect(int(inv.AmountDue)).Equals(900)+ Expect(inv.Currency).Equals("USD")err = client.CancelSubscription()Expect(err).IsNil()@@ -85,6 +86,7 @@ func TestUpdatePaymentInfo(t *testing.T) {Card: &models.CreateEditBillingPaymentInfoCard{Token: "tok_visa",},+ AddressCountry: "IE",})Expect(err).IsNil()@@ -169,13 +171,41 @@ func TestListPlans(t *testing.T) {}client := billing.NewClient()- plans, err := client.ListPlans()+ plans, err := client.ListPlans("US")Expect(err).IsNil()Expect(plans).HasLen(3)- Expect(plans[0].ID).Equals("plan_EIE1LpQIzPXxOn")- Expect(plans[0].Name).Equals("Fider Starter")++ Expect(plans[0].ID).Equals("plan_EKTT1YWe1Zmrtp")+ Expect(plans[0].Name).Equals("Starter")+ Expect(plans[0].Currency).Equals("USD")+ Expect(plans[0].MaxUsers).Equals(200)+Expect(plans[1].ID).Equals("plan_DoK187GZcnFpKY")- Expect(plans[1].Name).Equals("Fider Business (monthly)")+ Expect(plans[1].Name).Equals("Business (monthly)")+ Expect(plans[1].Currency).Equals("USD")+ Expect(plans[1].MaxUsers).Equals(0)+Expect(plans[2].ID).Equals("plan_DpN9SkJMjNTvLd")- Expect(plans[2].Name).Equals("Fider Business (yearly)")+ Expect(plans[2].Name).Equals("Business (yearly)")+ Expect(plans[2].Currency).Equals("USD")+ Expect(plans[2].MaxUsers).Equals(0)++ plans, err = client.ListPlans("DE")+ Expect(err).IsNil()+ Expect(plans).HasLen(3)++ Expect(plans[0].ID).Equals("plan_EKTSnrGmj5BuKI")+ Expect(plans[0].Name).Equals("Starter")+ Expect(plans[0].Currency).Equals("EUR")++ Expect(plans[0].MaxUsers).Equals(200)+ Expect(plans[1].ID).Equals("plan_EKPnahGhiTEnCc")+ Expect(plans[1].Name).Equals("Business (monthly)")+ Expect(plans[1].Currency).Equals("EUR")+ Expect(plans[1].MaxUsers).Equals(0)++ Expect(plans[2].ID).Equals("plan_EKTU4xD7LNI9dO")+ Expect(plans[2].Name).Equals("Business (yearly)")+ Expect(plans[2].Currency).Equals("EUR")+ Expect(plans[2].MaxUsers).Equals(0)}diff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.goindex bc36c08af..2bc0106e0 100644--- a/app/pkg/web/engine.go+++ b/app/pkg/web/engine.go@@ -33,7 +33,7 @@ var (cspObject = "object-src 'none'"cspFrame = "frame-src 'self' https://js.stripe.com"cspMedia = "media-src 'none'"- cspConnect = "connect-src 'self' https://www.google-analytics.com https://js.stripe.com %[2]s"+ cspConnect = "connect-src 'self' https://www.google-analytics.com https://ipinfo.io https://js.stripe.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/public/models/billing.ts b/public/models/billing.tsindex fad626289..12ec38f97 100644--- a/public/models/billing.ts+++ b/public/models/billing.ts@@ -15,6 +15,7 @@ export interface PaymentInfo {}export interface InvoiceDue {+ currency: string;amountDue: number;dueDate: string;}@@ -23,6 +24,7 @@ export interface BillingPlan {id: string;name: string;description: string;+ currency: string;maxUsers: number;price: number;interval: "month" | "year";diff --git a/public/pages/Administration/components/BillingPlanPanel.tsx b/public/pages/Administration/components/BillingPlanPanel.tsxindex a3ffad65a..29bed4b45 100644--- a/public/pages/Administration/components/BillingPlanPanel.tsx+++ b/public/pages/Administration/components/BillingPlanPanel.tsx@@ -1,7 +1,7 @@import React from "react";import { Segment, Button, Moment, Modal, ButtonClickEvent } from "@fider/components";import { BillingPlan, InvoiceDue } from "@fider/models";-import { Fider, actions, classSet } from "@fider/services";+import { Fider, actions, classSet, currencySymbol } from "@fider/services";interface BillingPlanOptionProps {tenantUserCount: number;@@ -23,7 +23,7 @@ const BillingPlanOption = (props: BillingPlanOptionProps) => {<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-currency">{currencySymbol(props.plan.currency)}</span><span className="l-price">{props.plan.price / 100}</span><span className="l-interval">/{props.plan.interval}</span></p>@@ -54,7 +54,7 @@ const BillingPlanOption = (props: BillingPlanOptionProps) => {};interface BillingPlanPanelProps {- invoiceDue: InvoiceDue;+ invoiceDue?: InvoiceDue;tenantUserCount: number;disabled: boolean;plans: BillingPlan[];@@ -127,7 +127,8 @@ export class BillingPlanPanel extends React.Component<BillingPlanPanelProps, Bil<p>You'll be billed a total of{" "}<strong>- ${this.state.confirmPlan!.price / 100} per {this.state.confirmPlan!.interval}+ {currencySymbol(this.state.confirmPlan!.currency)}+ {this.state.confirmPlan!.price / 100} per {this.state.confirmPlan!.interval}</strong>{" "}on your card.</p>@@ -178,14 +179,21 @@ export class BillingPlanPanel extends React.Component<BillingPlanPanelProps, Bil</strong>. Subscribe to a new plan and avoid a service interruption.</>- ) : (+ ) : this.props.invoiceDue ? (<>- Your upcoming invoice of <strong>${this.props.invoiceDue.amountDue / 100}</strong> is due on{" "}+ Your upcoming invoice of{" "}+ <strong>+ {currencySymbol(this.props.invoiceDue.currency)}+ {this.props.invoiceDue.amountDue / 100}+ </strong>{" "}+ is due on{" "}<strong><Moment date={this.props.invoiceDue.dueDate} format="full" /></strong>.</>+ ) : (+ <></>)}</p>)}diff --git a/public/pages/Administration/components/PaymentInfoModal.tsx b/public/pages/Administration/components/PaymentInfoModal.tsxindex e38499d4c..4d9fff932 100644--- a/public/pages/Administration/components/PaymentInfoModal.tsx+++ b/public/pages/Administration/components/PaymentInfoModal.tsx@@ -181,7 +181,7 @@ class PaymentInfoModal extends React.Component<PaymentInfoModalProps, PaymentInf<Field label="Credit/Debit Card" field="card"><CardElement /><p className="info">- We neither store or see your card information. We integrate directly with Stripe.+ We neither store nor see your card information. We integrate directly with Stripe.</p></Field></div>@@ -285,6 +285,16 @@ class PaymentInfoModal extends React.Component<PaymentInfoModalProps, PaymentInf/></div>)}+ {!!this.state.addressCountry && (+ <div className="col-md-12">+ <Field field="currency">+ <p className="info">+ Based on your Billing Address, your subscription will be charged in{" "}+ {this.isEUCountry() ? "Euro (EUR)" : "US Dollar (USD)"}.+ </p>+ </Field>+ </div>+ )}</div></Form></Modal.Content>diff --git a/public/pages/Administration/pages/Billing.page.scss b/public/pages/Administration/pages/Billing.page.scssindex 63317485a..e0107c1bf 100644--- a/public/pages/Administration/pages/Billing.page.scss+++ b/public/pages/Administration/pages/Billing.page.scss@@ -19,7 +19,7 @@min-height: 40px;}- span.l-dollar {+ span.l-currency {color: $gray-darker;font-size: $font-size-small;vertical-align: top;diff --git a/public/pages/Administration/pages/Billing.page.tsx b/public/pages/Administration/pages/Billing.page.tsxindex 9e8d1378e..0c98c707a 100644--- a/public/pages/Administration/pages/Billing.page.tsx+++ b/public/pages/Administration/pages/Billing.page.tsx@@ -6,20 +6,21 @@ import { FaFileInvoice } from "react-icons/fa";import { AdminBasePage } from "../components/AdminBasePage";import { Segment, Button, CardInfo, Message } from "@fider/components";import { PaymentInfo, BillingPlan, Country, InvoiceDue } from "@fider/models";-import { Fider } from "@fider/services";+import { Fider, actions, navigator } from "@fider/services";import PaymentInfoModal from "../components/PaymentInfoModal";import { StripeProvider, Elements } from "react-stripe-elements";import { BillingPlanPanel } from "../components/BillingPlanPanel";interface BillingPageProps {- invoiceDue: InvoiceDue;- plans: BillingPlan[];+ invoiceDue?: InvoiceDue;+ plans?: BillingPlan[];tenantUserCount: number;paymentInfo?: PaymentInfo;countries: Country[];}interface BillingPageState {+ plans?: BillingPlan[];stripe: stripe.Stripe | null;showModal: boolean;}@@ -35,7 +36,8 @@ export default class BillingPage extends AdminBasePage<BillingPageProps, Billingsuper(props);this.state = {stripe: null,- showModal: false+ showModal: false,+ plans: this.props.plans};}@@ -63,6 +65,20 @@ export default class BillingPage extends AdminBasePage<BillingPageProps, Billing});};+ public componentDidMount() {+ if (!this.props.paymentInfo) {+ navigator.getCountryCode().then(this.fetchPlans);+ }+ }++ private fetchPlans = (countryCode: string) => {+ actions.listBillingPlans(countryCode).then(res => {+ if (res.ok) {+ this.setState({ plans: res.data });+ }+ });+ };+public content() {return (<>@@ -100,14 +116,16 @@ export default class BillingPage extends AdminBasePage<BillingPageProps, Billing)}</Segment></div>- <div className="col-md-12">- <BillingPlanPanel- invoiceDue={this.props.invoiceDue}- tenantUserCount={this.props.tenantUserCount}- disabled={!this.props.paymentInfo}- plans={this.props.plans}- />- </div>+ {this.state.plans && (+ <div className="col-md-12">+ <BillingPlanPanel+ invoiceDue={this.props.invoiceDue}+ tenantUserCount={this.props.tenantUserCount}+ disabled={!this.props.paymentInfo}+ plans={this.state.plans}+ />+ </div>+ )}</div></>);diff --git a/public/services/actions/billing.ts b/public/services/actions/billing.tsindex 3f80ac554..4ac189c74 100644--- a/public/services/actions/billing.ts+++ b/public/services/actions/billing.ts@@ -1,4 +1,5 @@import { http, Result } from "@fider/services";+import { BillingPlan } from "@fider/models";interface UpdatePaymentInfoRequest {name: string;@@ -16,6 +17,10 @@ interface UpdatePaymentInfoRequest {vatNumber: string;}+export const listBillingPlans = async (countryCode: string): Promise<Result<BillingPlan[]>> => {+ return http.get(`/_api/admin/billing/plans/${countryCode}`);+};+export const updatePaymentInfo = async (request: UpdatePaymentInfoRequest): Promise<Result> => {return http.post("/_api/admin/billing/paymentinfo", request).then(http.event("billing", "updatepaymentinfo"));};diff --git a/public/services/navigator.ts b/public/services/navigator.tsindex 82018ee64..cb07d5d54 100644--- a/public/services/navigator.ts+++ b/public/services/navigator.ts@@ -1,4 +1,5 @@-import { Fider } from "@fider/services";+import { Fider, http } from "@fider/services";+import { cache } from "./cache";const navigator = {userAgent: () => {@@ -30,6 +31,19 @@ const navigator = {const newURL = Fider.settings.baseURL + path;window.history.replaceState({ path: newURL }, "", newURL);}+ },+ getCountryCode: (): Promise<string> => {+ const countryCode = cache.session.get("geolocation_countrycode");+ if (countryCode) {+ return Promise.resolve(countryCode);+ }++ return http.get<any>("https://ipinfo.io/geo").then(res => {+ if (res.ok) {+ cache.session.set("geolocation_countrycode", res.data.country);+ return res.data.country;+ }+ });}};diff --git a/public/services/utils.ts b/public/services/utils.tsindex 222203737..abc178cf4 100644--- a/public/services/utils.ts+++ b/public/services/utils.ts@@ -32,6 +32,17 @@ const monthNames = ["December"];+export const currencySymbol = (currencyCode: string): string => {+ currencyCode = currencyCode ? currencyCode.toLowerCase() : "";+ switch (currencyCode) {+ case "eur":+ return "€";+ case "usd":+ return "$";+ }+ throw new Error(`Invalid currency code '${currencyCode}'`);+};+const twoDigits = (value: number): string => {return value <= 9 ? `0${value}` : value.toString();};