mirror of
https://github.com/warmbly/warmbly.git
synced 2026-11-17 08:18:51 +00:00
feat: confirm an agency plan switch only from the price and billing period its preview was made for, let a switch Stripe already holds be previewed and completed, hold keyed requests on agency routes to the agency's staff before any answer is recorded or replayed, and bound the switch locks
This commit is contained in:
@@ -390,6 +390,8 @@ func main() {
|
||||
// A portal session is held to its agency's clients; sign-in on the main address hands a portal its session.
|
||||
var portalHandoffService *portalhandoff.Service
|
||||
var portalClients middleware.PortalClients
|
||||
// agencyMembers holds keyed requests on agency routes to the agency's staff.
|
||||
var agencyMembers middleware.AgencyMembers
|
||||
// instanceSettings and the health registry are built after the handler
|
||||
// dependencies, so the pool is hoisted out of the connection block.
|
||||
var instanceSettings instancesettings.Service
|
||||
@@ -1529,6 +1531,7 @@ func main() {
|
||||
tokenService.WirePortalResolver(portals.Binding)
|
||||
portalHandoffService = portalhandoff.NewService(portalhandoff.RedisStore{Cache: cache}, portals, tokenService, userRepostory)
|
||||
portalClients = middleware.NewPortalClientCache(repository.NewAgencyRepository(primaryDB.Pool))
|
||||
agencyMembers = repository.NewAgencyRepository(primaryDB.Pool)
|
||||
go jobs.NewFormsDomainSweep(organizationRepoForHandler, customHosts).WithPortals(brandRepository, brandService).Start(ctx, time.Hour)
|
||||
// Behind a Cloudflare for SaaS zone of their own, verified agency portal domains are registered there as they verify.
|
||||
portalEdge := edgehost.Open(repository.NewEdgeHostnameRepository(primaryDB.Pool, repository.EdgePortal),
|
||||
@@ -2893,6 +2896,7 @@ func main() {
|
||||
PoolLinkService: poolLinkService,
|
||||
AgencyKeys: agencyKeyService,
|
||||
PortalClients: portalClients,
|
||||
AgencyMembers: agencyMembers,
|
||||
}
|
||||
if fleetNodeService != nil {
|
||||
m.NodeCredentials = fleetNodeService
|
||||
|
||||
@@ -929,8 +929,8 @@ A key passes the recent-confirmation check the session routes ask for, since it
|
||||
| GET | `/agency/:agencyId/inbox/thread` | Staff with inbox access in that client: `organization_id` and `thread_id`, the conversation's messages as `GET /unibox/thread` returns them, read-only |
|
||||
| GET | `/agency/:agencyId/inbox/messages/:messageId` | Staff with inbox access in that client: `organization_id`, one message with its body as `GET /unibox/:id` returns it, left unread |
|
||||
| POST | `/agency/:agencyId/billing/checkout` | Owner, admin: `plan_id` and `interval` (`month` or `year`) |
|
||||
| GET | `/agency/:agencyId/billing/change/preview` | Owner, admin: `plan_id` and `interval` (`month` or `year`) in the query. What switching the agency's subscription to that plan and period would bill: `proration_cents` (negative is a credit), `amount_due_cents` on the next invoice, `currency`, and the `proration_date` the amounts were calculated at. Changes nothing |
|
||||
| POST | `/agency/:agencyId/billing/change` | Owner, admin: `plan_id` and `interval`, and optionally the preview's `proration_date` so the switch bills exactly what the preview showed (valid for 30 minutes). Moves the agency's subscription to another agency plan or billing period, prorated; every client workspace has the new plan at once. Answers the agency. A switch Stripe already holds but the agency does not yet show is completed, not refused |
|
||||
| GET | `/agency/:agencyId/billing/change/preview` | Owner, admin: `plan_id` and `interval` (`month` or `year`) in the query. What switching the agency's subscription to that plan and period would bill: `proration_cents` (negative is a credit), `amount_due_cents` on the next invoice, `currency`, the `proration_date` the amounts were calculated at and the `from_price_id` the subscription was on. Changes nothing |
|
||||
| POST | `/agency/:agencyId/billing/change` | Owner, admin: `plan_id` and `interval`, and optionally the preview's `proration_date` and `from_price_id` so the switch bills exactly what the preview showed (valid for 30 minutes, within the same billing period and from the same price). Moves the agency's subscription to another agency plan or billing period, prorated; every client workspace has the new plan at once. Answers the agency. A switch Stripe already holds but the agency does not yet show is completed, not refused |
|
||||
| POST | `/agency/:agencyId/billing/topup` | Owner, admin: one 50,000-send pack |
|
||||
| POST | `/agency/:agencyId/billing/ai-topup` | Owner, admin: `amount_usd` ($5 to $5,000) added to the agency's AI balance through checkout. Answers `checkout_url` |
|
||||
| POST | `/agency/:agencyId/billing/portal` | Owner, admin |
|
||||
|
||||
@@ -713,7 +713,7 @@ The [agency](/guides/agencies/) routes answer these codes.
|
||||
| `agency_client_has_subscription` | 409 | The workspace pays for its own plan. Cancel it in the workspace's billing first |
|
||||
| `agency_already_subscribed` | 409 | The agency already has a plan; switch it with `POST /agency/:agencyId/billing/change` |
|
||||
| `agency_plan_unchanged` | 409 | A plan switch to the plan and billing period the agency is already on |
|
||||
| `agency_plan_preview_expired` | 409 | `proration_date` on a plan switch is more than 30 minutes old or in the future. Preview the switch again |
|
||||
| `agency_plan_preview_expired` | 409 | The preview a plan switch was confirmed from no longer holds: `proration_date` is more than 30 minutes old, in the future or before the current billing period, or the subscription is no longer on `from_price_id`. Preview the switch again |
|
||||
| `agency_pool_exceeds_plan` | 409 | A switch to a plan whose send pool, with this period's top-ups, is smaller than what the period has already used. Switch after the period renews |
|
||||
| `agency_billed` | 409 | `POST /subscription/checkout` on a client workspace, whose plan comes from its agency |
|
||||
| `agency_leave_agency_owner` | 409 | `POST /organization/agency/leave` on a workspace whose owner also owns the agency. Detach it with `DELETE /agency/:agencyId/clients/:orgId` instead |
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/app/agency"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
@@ -536,8 +537,9 @@ func (h *Handler) ChangeAgencyPlan(c *gin.Context) {
|
||||
var req struct {
|
||||
PlanID string `json:"plan_id"`
|
||||
Interval string `json:"interval"`
|
||||
// ProrationDate is the preview's, so the switch bills what was shown.
|
||||
ProrationDate int64 `json:"proration_date"`
|
||||
// ProrationDate and FromPriceID are the preview's, so the switch bills what was shown.
|
||||
ProrationDate int64 `json:"proration_date"`
|
||||
FromPriceID string `json:"from_price_id"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
@@ -551,7 +553,8 @@ func (h *Handler) ChangeAgencyPlan(c *gin.Context) {
|
||||
errx.JSON(c, errx.New(errx.BadRequest, "proration_date must be the value a preview returned"))
|
||||
return
|
||||
}
|
||||
a, xerr := h.AgencyService.ChangePlan(c.Request.Context(), agencyID, userID, planID, yearly, req.ProrationDate)
|
||||
a, xerr := h.AgencyService.ChangePlan(c.Request.Context(), agencyID, userID, planID, yearly,
|
||||
agency.PlanChangeQuote{ProrationDate: req.ProrationDate, FromPriceID: strings.TrimSpace(req.FromPriceID)})
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
|
||||
@@ -32,4 +32,6 @@ type Handler struct {
|
||||
AgencyKeys *apikey.AgencyKeyService
|
||||
// PortalClients holds a portal session to its agency's clients; nil lets a portal session reach no workspace.
|
||||
PortalClients PortalClients
|
||||
// AgencyMembers lets a keyed request on an agency route be held to that agency's staff before any answer is recorded or replayed; nil skips the check.
|
||||
AgencyMembers AgencyMembers
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/warmbly/warmbly/internal/app/idempotency"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -31,6 +32,26 @@ func routeAgencyID(c *gin.Context) *uuid.UUID {
|
||||
return &id
|
||||
}
|
||||
|
||||
// AgencyMembers reads one staff row; satisfied by repository.AgencyRepository.
|
||||
type AgencyMembers interface {
|
||||
GetMember(ctx context.Context, agencyID, userID uuid.UUID) (*models.AgencyMember, error)
|
||||
}
|
||||
|
||||
// onAgencyStaff reports whether a session caller is on the staff of the agency its route names.
|
||||
// Routes that name no agency, and agency keys (held to their agency elsewhere), pass.
|
||||
func (h *Handler) onAgencyStaff(c *gin.Context) (bool, error) {
|
||||
agencyID := routeAgencyID(c)
|
||||
if agencyID == nil || h.AgencyMembers == nil || GetAgencyKeyAgencyID(c) != nil {
|
||||
return true, nil
|
||||
}
|
||||
userID, err := GetUserUUID(c)
|
||||
if err != nil {
|
||||
return false, nil
|
||||
}
|
||||
m, err := h.AgencyMembers.GetMember(c.Request.Context(), *agencyID, userID)
|
||||
return m != nil, err
|
||||
}
|
||||
|
||||
// IdempotencyMiddleware implements Stripe-style retry safety for mutating API
|
||||
// requests. It is opt-in per request via Idempotency-Key and scoped by
|
||||
// organization, so the same key cannot collide across tenants.
|
||||
@@ -52,6 +73,17 @@ func (h *Handler) IdempotencyMiddleware() gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
// An agency's recorded answers are for its staff: checked before a key is claimed or replayed.
|
||||
if staff, err := h.onAgencyStaff(c); err != nil {
|
||||
errx.Handle(c, errx.InternalError())
|
||||
c.Abort()
|
||||
return
|
||||
} else if !staff {
|
||||
errx.Handle(c, errx.NewWithIdentifier(errx.NotFound, "agency_not_found", "That agency does not exist or you are not part of it."))
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
var scope idempotency.Scope
|
||||
switch orgID, agencyID := GetOrganizationID(c), GetAgencyKeyAgencyID(c); {
|
||||
case orgID != nil:
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/warmbly/warmbly/internal/app/idempotency"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
type idempotencyBegin struct {
|
||||
@@ -332,3 +333,40 @@ func TestIdempotencyScopesAnAgencyRouteToItsAgencyWithoutAWorkspace(t *testing.T
|
||||
t.Fatalf("no scope at all: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// staffOf is the agency's staff, by user id.
|
||||
type staffOf map[uuid.UUID]bool
|
||||
|
||||
func (s staffOf) GetMember(_ context.Context, _, userID uuid.UUID) (*models.AgencyMember, error) {
|
||||
if !s[userID] {
|
||||
return nil, nil
|
||||
}
|
||||
return &models.AgencyMember{UserID: userID, Role: models.AgencyRoleAdmin}, nil
|
||||
}
|
||||
|
||||
func TestIdempotencyHoldsAnAgencyRouteToItsStaff(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
staff, outsider := uuid.New(), uuid.New()
|
||||
svc := &scopeRecorder{}
|
||||
// A recorded answer is waiting to be replayed.
|
||||
svc.state = idempotency.StateReplay
|
||||
svc.record = &idempotency.Record{ID: uuid.New(), StatusCode: http.StatusOK}
|
||||
h := &Handler{IdempotencyService: svc, AgencyMembers: staffOf{staff: true}}
|
||||
ok := func(c *gin.Context) { c.Status(http.StatusOK) }
|
||||
path := "/agency/" + uuid.NewString() + "/billing/change"
|
||||
for _, c := range []struct {
|
||||
user uuid.UUID
|
||||
want int
|
||||
}{{outsider, http.StatusNotFound}, {staff, http.StatusOK}} {
|
||||
r := gin.New()
|
||||
r.Use(RequestIDMiddleware())
|
||||
r.POST("/agency/:agencyId/billing/change", asUser(c.user.String()), h.IdempotencyMiddleware(), ok)
|
||||
before := len(svc.scopes)
|
||||
if w := sendIdempotent(r, http.MethodPost, path, "key-1", `{}`); w.Code != c.want {
|
||||
t.Fatalf("user %s: %d %s", c.user, w.Code, w.Body.String())
|
||||
}
|
||||
if claimed := len(svc.scopes) > before; claimed != (c.want == http.StatusOK) {
|
||||
t.Fatalf("user %s: claimed=%v", c.user, claimed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,6 +105,8 @@ type PlanChangePreview struct {
|
||||
Currency string `json:"currency"`
|
||||
// ProrationDate is the moment the amounts were calculated at; sent back with the switch, it bills exactly them.
|
||||
ProrationDate int64 `json:"proration_date"`
|
||||
// FromPriceID is the price the subscription was on; sent back with the switch, it refuses one priced from another plan.
|
||||
FromPriceID string `json:"from_price_id"`
|
||||
}
|
||||
|
||||
// planChangePreviewTTL is how long a previewed price may be confirmed at; an older one is priced again.
|
||||
@@ -171,7 +173,16 @@ func (s *Service) planChangeFor(ctx context.Context, agencyID, actorID, planID u
|
||||
return &planChange{agency: a, plan: plan, price: price, sub: sub, itemID: item.ID, held: item.Price != nil && item.Price.ID == price}, nil
|
||||
}
|
||||
|
||||
var errPlanUnchanged = errx.NewWithIdentifier(errx.Conflict, "agency_plan_unchanged", "The agency is already on that plan and billing period.")
|
||||
var (
|
||||
errPlanUnchanged = errx.NewWithIdentifier(errx.Conflict, "agency_plan_unchanged", "The agency is already on that plan and billing period.")
|
||||
errPreviewExpired = errx.NewWithIdentifier(errx.Conflict, "agency_plan_preview_expired", "That price is no longer current. Review the switch again.")
|
||||
)
|
||||
|
||||
// PlanChangeQuote is what a preview returned, sent back so the switch bills what was shown; the zero value prices it now.
|
||||
type PlanChangeQuote struct {
|
||||
ProrationDate int64
|
||||
FromPriceID string
|
||||
}
|
||||
|
||||
func intervalName(yearly bool) string {
|
||||
if yearly {
|
||||
@@ -186,10 +197,14 @@ func (s *Service) PreviewPlanChange(ctx context.Context, agencyID, actorID, plan
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
if c.held {
|
||||
return nil, errPlanUnchanged
|
||||
}
|
||||
at := s.now().Unix()
|
||||
if c.held {
|
||||
if c.shows(yearly) {
|
||||
return nil, errPlanUnchanged
|
||||
}
|
||||
// Stripe already holds the switch and nothing more is billed; confirming it applies it here.
|
||||
return &PlanChangePreview{PlanID: c.plan.ID, Interval: intervalName(yearly), Currency: string(c.sub.Currency), ProrationDate: at, FromPriceID: c.fromPrice()}, nil
|
||||
}
|
||||
params := &stripe.InvoiceCreatePreviewParams{
|
||||
Params: stripe.Params{Context: ctx},
|
||||
AutomaticTax: &stripe.InvoiceCreatePreviewAutomaticTaxParams{Enabled: stripe.Bool(false)},
|
||||
@@ -209,7 +224,7 @@ func (s *Service) PreviewPlanChange(ctx context.Context, agencyID, actorID, plan
|
||||
return nil, errx.New(errx.Internal, "failed to price the switch")
|
||||
}
|
||||
out := &PlanChangePreview{PlanID: c.plan.ID, Interval: intervalName(yearly), AmountDueCents: inv.AmountDue,
|
||||
Currency: string(inv.Currency), ProrationDate: at}
|
||||
Currency: string(inv.Currency), ProrationDate: at, FromPriceID: c.fromPrice()}
|
||||
if inv.Lines != nil {
|
||||
for _, line := range inv.Lines.Data {
|
||||
if lineIsProration(line) {
|
||||
@@ -233,10 +248,23 @@ func lineIsProration(line *stripe.InvoiceLineItem) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// switching hands out one lock per agency, so a switch is validated, made and applied before the next one starts.
|
||||
// switching is the lock an agency's switches share, so one is validated, made and applied before the next starts.
|
||||
// A fixed set of locks keyed by the agency id: two agencies may share one, and nothing accumulates.
|
||||
func (s *Service) switching(agencyID uuid.UUID) *sync.Mutex {
|
||||
l, _ := s.switches.LoadOrStore(agencyID, &sync.Mutex{})
|
||||
return l.(*sync.Mutex)
|
||||
return &s.switches[int(agencyID[0])%len(s.switches)]
|
||||
}
|
||||
|
||||
// shows reports an agency that already has the switch applied.
|
||||
func (c *planChange) shows(yearly bool) bool {
|
||||
return c.agency.PlanID != nil && *c.agency.PlanID == c.plan.ID && c.agency.SubscriptionInterval() == intervalName(yearly)
|
||||
}
|
||||
|
||||
// fromPrice is the price the subscription is on before the switch.
|
||||
func (c *planChange) fromPrice() string {
|
||||
if item := c.sub.Items.Data[0]; item.Price != nil {
|
||||
return item.Price.ID
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ChangePlan moves the agency's subscription to another agency plan or billing
|
||||
@@ -244,12 +272,13 @@ func (s *Service) switching(agencyID uuid.UUID) *sync.Mutex {
|
||||
// is the moment a preview priced the switch at; zero prices it now. A switch
|
||||
// Stripe already holds is applied here again, so one whose result was not
|
||||
// recorded the first time completes on the next attempt.
|
||||
func (s *Service) ChangePlan(ctx context.Context, agencyID, actorID, planID uuid.UUID, yearly bool, prorationDate int64) (*models.Agency, *errx.Error) {
|
||||
func (s *Service) ChangePlan(ctx context.Context, agencyID, actorID, planID uuid.UUID, yearly bool, quote PlanChangeQuote) (*models.Agency, *errx.Error) {
|
||||
now := s.now()
|
||||
prorationDate := quote.ProrationDate
|
||||
if prorationDate != 0 {
|
||||
at := time.Unix(prorationDate, 0)
|
||||
if at.After(now.Add(time.Minute)) || now.Sub(at) > planChangePreviewTTL {
|
||||
return nil, errx.NewWithIdentifier(errx.Conflict, "agency_plan_preview_expired", "That price is no longer current. Review the switch again.")
|
||||
return nil, errPreviewExpired
|
||||
}
|
||||
}
|
||||
lock := s.switching(agencyID)
|
||||
@@ -263,10 +292,17 @@ func (s *Service) ChangePlan(ctx context.Context, agencyID, actorID, planID uuid
|
||||
sub := c.sub
|
||||
if c.held {
|
||||
// Nothing left to bill; only an agency that already shows the switch has nothing left to do.
|
||||
if c.agency.PlanID != nil && *c.agency.PlanID == c.plan.ID && c.agency.SubscriptionInterval() == intervalName(yearly) {
|
||||
if c.shows(yearly) {
|
||||
return nil, errPlanUnchanged
|
||||
}
|
||||
} else {
|
||||
// The quote was for a switch from one price inside one billing period; from anywhere else it is priced again.
|
||||
if quote.FromPriceID != "" && quote.FromPriceID != c.fromPrice() {
|
||||
return nil, errPreviewExpired
|
||||
}
|
||||
if start := c.sub.Items.Data[0].CurrentPeriodStart; prorationDate != 0 && start > 0 && prorationDate < start {
|
||||
return nil, errPreviewExpired
|
||||
}
|
||||
params := &stripe.SubscriptionParams{
|
||||
Params: stripe.Params{Context: ctx},
|
||||
Items: []*stripe.SubscriptionItemsParams{{ID: stripe.String(c.itemID), Price: stripe.String(c.price)}},
|
||||
|
||||
@@ -95,7 +95,7 @@ func TestPlanChangeRefusesAStalePreview(t *testing.T) {
|
||||
a.StripeSubscriptionID = strp("sub_1")
|
||||
s, actor := newSwitchService(t, a, 0, now)
|
||||
for _, at := range []time.Time{now.Add(-planChangePreviewTTL - time.Minute), now.Add(10 * time.Minute)} {
|
||||
if _, xerr := s.ChangePlan(context.Background(), a.ID, actor, models.AgencyProPlanID, false, at.Unix()); xerr == nil || xerr.Identifier != "agency_plan_preview_expired" {
|
||||
if _, xerr := s.ChangePlan(context.Background(), a.ID, actor, models.AgencyProPlanID, false, PlanChangeQuote{ProrationDate: at.Unix()}); xerr == nil || xerr.Identifier != "agency_plan_preview_expired" {
|
||||
t.Fatalf("priced at %s: got %v", at, xerr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,8 +71,8 @@ type Service struct {
|
||||
billing bool
|
||||
now func() time.Time
|
||||
|
||||
// switches holds one lock per agency for plan switches.
|
||||
switches sync.Map
|
||||
// switches are the locks plan switches take, picked by agency id.
|
||||
switches [64]sync.Mutex
|
||||
|
||||
mu sync.Mutex
|
||||
pools map[uuid.UUID]poolEntry
|
||||
|
||||
@@ -185,7 +185,7 @@ function AgencyBilling() {
|
||||
const preview = await previewAgencyPlanChange(agencyId, p.id, interval);
|
||||
confirm.show(switchText(p, interval, agency.billing_interval, preview), async () => {
|
||||
try {
|
||||
await change.mutateAsync({ planId: p.id, interval, prorationDate: preview.proration_date });
|
||||
await change.mutateAsync({ planId: p.id, interval, quote: preview });
|
||||
toast.success(`Switched to ${p.name}`);
|
||||
} catch (e) {
|
||||
toast.error(buildError(e as AppError));
|
||||
|
||||
@@ -108,11 +108,16 @@ export const previewAgencyPlanChange = (agencyId: string, planId: string, interv
|
||||
authorization: true,
|
||||
});
|
||||
|
||||
export const changeAgencyPlan = (agencyId: string, planId: string, interval: "month" | "year", prorationDate?: number) =>
|
||||
export const changeAgencyPlan = (
|
||||
agencyId: string,
|
||||
planId: string,
|
||||
interval: "month" | "year",
|
||||
quote?: Pick<AgencyPlanChangePreview, "proration_date" | "from_price_id">,
|
||||
) =>
|
||||
Request<Agency>({
|
||||
method: "POST",
|
||||
url: `/agency/${agencyId}/billing/change`,
|
||||
data: { plan_id: planId, interval, proration_date: prorationDate },
|
||||
data: { plan_id: planId, interval, proration_date: quote?.proration_date, from_price_id: quote?.from_price_id },
|
||||
headers: idem(),
|
||||
authorization: true,
|
||||
});
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
updateAgencyStaff,
|
||||
changeAgencyPlan,
|
||||
} from "@/lib/api/client/app/agency/agency";
|
||||
import type { Agency, AgencyClient, AgencyClientPatch, AgencyRole } from "@/lib/api/models/app/agency/Agency";
|
||||
import type { Agency, AgencyClient, AgencyClientPatch, AgencyRole, AgencyPlanChangePreview } from "@/lib/api/models/app/agency/Agency";
|
||||
import { currentPortal, portalAgencies } from "@/lib/portal";
|
||||
|
||||
// Every agency query sits under ["agency"], which the audit spine invalidates.
|
||||
@@ -331,8 +331,8 @@ export function useAgencyCheckout(agencyId: string) {
|
||||
export function useChangeAgencyPlan(agencyId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({ planId, interval, prorationDate }: { planId: string; interval: "month" | "year"; prorationDate?: number }) =>
|
||||
changeAgencyPlan(agencyId, planId, interval, prorationDate),
|
||||
mutationFn: ({ planId, interval, quote }: { planId: string; interval: "month" | "year"; quote?: AgencyPlanChangePreview }) =>
|
||||
changeAgencyPlan(agencyId, planId, interval, quote),
|
||||
// The open workspace may be one of the agency's clients, whose own plan just changed with it.
|
||||
onSettled: () => {
|
||||
void qc.invalidateQueries({ queryKey: ["agency"] });
|
||||
|
||||
@@ -54,6 +54,8 @@ export interface AgencyPlanChangePreview {
|
||||
currency: string;
|
||||
/** When the amounts were calculated; sent back with the switch so it bills exactly them. */
|
||||
proration_date: number;
|
||||
/** The price the subscription was on; sent back so a switch priced from another plan is refused. */
|
||||
from_price_id: string;
|
||||
}
|
||||
|
||||
export interface AgenciesResult {
|
||||
|
||||
Reference in New Issue
Block a user