mirror of
https://github.com/warmbly/warmbly.git
synced 2026-11-17 08:18:51 +00:00
feat: bill an agency plan switch at the moment its preview priced it, run one switch per agency at a time, complete a switch Stripe already holds, scope retry keys on agency routes to the agency for staff with no workspace selected, and refresh the open workspace's plan after a switch
This commit is contained in:
@@ -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, `next_billing_date`, `currency`. Changes nothing |
|
||||
| POST | `/agency/:agencyId/billing/change` | Owner, admin: `plan_id` and `interval`. 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 |
|
||||
| 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 |
|
||||
| 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,6 +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_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 |
|
||||
|
||||
@@ -536,6 +536,8 @@ 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"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
@@ -545,7 +547,11 @@ func (h *Handler) ChangeAgencyPlan(c *gin.Context) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
a, xerr := h.AgencyService.ChangePlan(c.Request.Context(), agencyID, userID, planID, yearly)
|
||||
if req.ProrationDate < 0 {
|
||||
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)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
|
||||
@@ -22,6 +22,15 @@ const (
|
||||
IdempotencyReplayedHeader = "X-Idempotent-Replayed"
|
||||
)
|
||||
|
||||
// routeAgencyID is the agency an agency route names; the handler behind it still checks the caller belongs to it.
|
||||
func routeAgencyID(c *gin.Context) *uuid.UUID {
|
||||
id, err := uuid.Parse(c.Param("agencyId"))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return &id
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -49,6 +58,9 @@ func (h *Handler) IdempotencyMiddleware() gin.HandlerFunc {
|
||||
scope = idempotency.OrgScope(*orgID)
|
||||
case agencyID != nil:
|
||||
scope = idempotency.AgencyScope(*agencyID)
|
||||
case routeAgencyID(c) != nil:
|
||||
// Agency staff with no workspace selected: the agency the route names is the scope.
|
||||
scope = idempotency.AgencyScope(*routeAgencyID(c))
|
||||
default:
|
||||
errx.Handle(c, errx.New(errx.BadRequest, "Idempotency-Key requires an organization context"))
|
||||
c.Abort()
|
||||
|
||||
@@ -297,3 +297,38 @@ func TestIdempotencyStateAnswers(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// scopeRecorder is fakeIdempotencyService that keeps the scope each claim was made in.
|
||||
type scopeRecorder struct {
|
||||
fakeIdempotencyService
|
||||
scopes []idempotency.Scope
|
||||
}
|
||||
|
||||
func (s *scopeRecorder) Begin(ctx context.Context, scope idempotency.Scope, key, method, path, requestHash string) (*idempotency.Record, idempotency.State, *errx.Error) {
|
||||
s.scopes = append(s.scopes, scope)
|
||||
return s.fakeIdempotencyService.Begin(ctx, scope, key, method, path, requestHash)
|
||||
}
|
||||
|
||||
func TestIdempotencyScopesAnAgencyRouteToItsAgencyWithoutAWorkspace(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
svc := &scopeRecorder{}
|
||||
h := &Handler{IdempotencyService: svc}
|
||||
r := gin.New()
|
||||
r.Use(RequestIDMiddleware())
|
||||
ok := func(c *gin.Context) { c.Status(http.StatusOK) }
|
||||
// Agency staff signed in with no workspace selected.
|
||||
r.POST("/agency/:agencyId/billing/change", asUser(uuid.NewString()), h.IdempotencyMiddleware(), ok)
|
||||
r.POST("/contacts", asUser(uuid.NewString()), h.IdempotencyMiddleware(), ok)
|
||||
|
||||
agencyID := uuid.New()
|
||||
if w := sendIdempotent(r, http.MethodPost, "/agency/"+agencyID.String()+"/billing/change", "key-1", `{}`); w.Code != http.StatusOK {
|
||||
t.Fatalf("agency route: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
if len(svc.scopes) != 1 || svc.scopes[0] != idempotency.AgencyScope(agencyID) {
|
||||
t.Fatalf("scope: %+v", svc.scopes)
|
||||
}
|
||||
// A route that names no agency still needs a workspace.
|
||||
if w := sendIdempotent(r, http.MethodPost, "/contacts", "key-1", `{}`); w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("no scope at all: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -100,11 +101,15 @@ type PlanChangePreview struct {
|
||||
// ProrationCents is the prorated difference for the rest of the period; negative is a credit.
|
||||
ProrationCents int64 `json:"proration_cents"`
|
||||
// AmountDueCents is the total of the next invoice with the switch applied.
|
||||
AmountDueCents int64 `json:"amount_due_cents"`
|
||||
NextBillingDate time.Time `json:"next_billing_date"`
|
||||
Currency string `json:"currency"`
|
||||
AmountDueCents int64 `json:"amount_due_cents"`
|
||||
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"`
|
||||
}
|
||||
|
||||
// planChangePreviewTTL is how long a previewed price may be confirmed at; an older one is priced again.
|
||||
const planChangePreviewTTL = 30 * time.Minute
|
||||
|
||||
// planChange is one validated switch of the agency's own Stripe subscription.
|
||||
type planChange struct {
|
||||
agency *models.Agency
|
||||
@@ -112,6 +117,8 @@ type planChange struct {
|
||||
price string
|
||||
sub *stripe.Subscription
|
||||
itemID string
|
||||
// held is true when Stripe already has the subscription on this price.
|
||||
held bool
|
||||
}
|
||||
|
||||
// planChangeFor checks that the agency can move its subscription to the plan and period now.
|
||||
@@ -161,12 +168,11 @@ func (s *Service) planChangeFor(ctx context.Context, agencyID, actorID, planID u
|
||||
return nil, errx.New(errx.Internal, "the subscription has an unexpected shape")
|
||||
}
|
||||
item := sub.Items.Data[0]
|
||||
if item.Price != nil && item.Price.ID == price {
|
||||
return nil, errx.NewWithIdentifier(errx.Conflict, "agency_plan_unchanged", "The agency is already on that plan and billing period.")
|
||||
}
|
||||
return &planChange{agency: a, plan: plan, price: price, sub: sub, itemID: item.ID}, nil
|
||||
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.")
|
||||
|
||||
func intervalName(yearly bool) string {
|
||||
if yearly {
|
||||
return "year"
|
||||
@@ -180,6 +186,10 @@ 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()
|
||||
params := &stripe.InvoiceCreatePreviewParams{
|
||||
Params: stripe.Params{Context: ctx},
|
||||
AutomaticTax: &stripe.InvoiceCreatePreviewAutomaticTaxParams{Enabled: stripe.Bool(false)},
|
||||
@@ -187,6 +197,7 @@ func (s *Service) PreviewPlanChange(ctx context.Context, agencyID, actorID, plan
|
||||
SubscriptionDetails: &stripe.InvoiceCreatePreviewSubscriptionDetailsParams{
|
||||
Items: []*stripe.InvoiceCreatePreviewSubscriptionDetailsItemParams{{ID: stripe.String(c.itemID), Price: stripe.String(c.price)}},
|
||||
ProrationBehavior: stripe.String("create_prorations"),
|
||||
ProrationDate: stripe.Int64(at),
|
||||
},
|
||||
}
|
||||
if c.agency.StripeCustomerID != nil {
|
||||
@@ -198,7 +209,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,
|
||||
NextBillingDate: time.Unix(inv.PeriodEnd, 0).UTC(), Currency: string(inv.Currency)}
|
||||
Currency: string(inv.Currency), ProrationDate: at}
|
||||
if inv.Lines != nil {
|
||||
for _, line := range inv.Lines.Data {
|
||||
if lineIsProration(line) {
|
||||
@@ -222,29 +233,62 @@ 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.
|
||||
func (s *Service) switching(agencyID uuid.UUID) *sync.Mutex {
|
||||
l, _ := s.switches.LoadOrStore(agencyID, &sync.Mutex{})
|
||||
return l.(*sync.Mutex)
|
||||
}
|
||||
|
||||
// ChangePlan moves the agency's subscription to another agency plan or billing
|
||||
// period, prorated, and gives every client the new plan at once.
|
||||
func (s *Service) ChangePlan(ctx context.Context, agencyID, actorID, planID uuid.UUID, yearly bool) (*models.Agency, *errx.Error) {
|
||||
// period, prorated, and gives every client the new plan at once. prorationDate
|
||||
// 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) {
|
||||
now := s.now()
|
||||
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.")
|
||||
}
|
||||
}
|
||||
lock := s.switching(agencyID)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
c, xerr := s.planChangeFor(ctx, agencyID, actorID, planID, yearly)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
updated, err := subscription.Update(c.sub.ID, &stripe.SubscriptionParams{
|
||||
Params: stripe.Params{Context: ctx},
|
||||
Items: []*stripe.SubscriptionItemsParams{{ID: stripe.String(c.itemID), Price: stripe.String(c.price)}},
|
||||
ProrationBehavior: stripe.String("create_prorations"),
|
||||
AutomaticTax: &stripe.SubscriptionAutomaticTaxParams{Enabled: stripe.Bool(false)},
|
||||
})
|
||||
if err != nil {
|
||||
errs.CaptureException(fmt.Errorf("agency plan change: %w", err))
|
||||
return nil, errx.New(errx.Internal, "failed to switch the plan")
|
||||
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) {
|
||||
return nil, errPlanUnchanged
|
||||
}
|
||||
} else {
|
||||
params := &stripe.SubscriptionParams{
|
||||
Params: stripe.Params{Context: ctx},
|
||||
Items: []*stripe.SubscriptionItemsParams{{ID: stripe.String(c.itemID), Price: stripe.String(c.price)}},
|
||||
ProrationBehavior: stripe.String("create_prorations"),
|
||||
AutomaticTax: &stripe.SubscriptionAutomaticTaxParams{Enabled: stripe.Bool(false)},
|
||||
}
|
||||
if prorationDate != 0 {
|
||||
params.ProrationDate = stripe.Int64(prorationDate)
|
||||
}
|
||||
updated, err := subscription.Update(c.sub.ID, params)
|
||||
if err != nil {
|
||||
errs.CaptureException(fmt.Errorf("agency plan change: %w", err))
|
||||
return nil, errx.New(errx.Internal, "failed to switch the plan")
|
||||
}
|
||||
sub = updated
|
||||
}
|
||||
// Applied here as well as by the webhook, so the dashboard shows the new plan without waiting for it.
|
||||
var raw json.RawMessage
|
||||
if updated.LastResponse != nil {
|
||||
raw = updated.LastResponse.RawJSON
|
||||
if sub.LastResponse != nil {
|
||||
raw = sub.LastResponse.RawJSON
|
||||
}
|
||||
if xerr := s.applySubscription(ctx, agencyID, updated, raw, false); xerr != nil {
|
||||
if xerr := s.applySubscription(ctx, agencyID, sub, raw, false); xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
a, gerr := s.repo.Get(ctx, agencyID)
|
||||
|
||||
@@ -89,6 +89,18 @@ func TestPlanChangeRefusesAPoolThePeriodAlreadyExceeds(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlanChangeRefusesAStalePreview(t *testing.T) {
|
||||
now := time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC)
|
||||
a := activeAgency(now)
|
||||
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" {
|
||||
t.Fatalf("priced at %s: got %v", at, xerr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubscriptionInterval(t *testing.T) {
|
||||
start := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
|
||||
month, year := start.AddDate(0, 1, 0), start.AddDate(1, 0, 0)
|
||||
|
||||
@@ -71,6 +71,9 @@ type Service struct {
|
||||
billing bool
|
||||
now func() time.Time
|
||||
|
||||
// switches holds one lock per agency for plan switches.
|
||||
switches sync.Map
|
||||
|
||||
mu sync.Mutex
|
||||
pools map[uuid.UUID]poolEntry
|
||||
orgAgency map[uuid.UUID]orgEntry
|
||||
|
||||
@@ -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 });
|
||||
await change.mutateAsync({ planId: p.id, interval, prorationDate: preview.proration_date });
|
||||
toast.success(`Switched to ${p.name}`);
|
||||
} catch (e) {
|
||||
toast.error(buildError(e as AppError));
|
||||
|
||||
@@ -108,11 +108,11 @@ export const previewAgencyPlanChange = (agencyId: string, planId: string, interv
|
||||
authorization: true,
|
||||
});
|
||||
|
||||
export const changeAgencyPlan = (agencyId: string, planId: string, interval: "month" | "year") =>
|
||||
export const changeAgencyPlan = (agencyId: string, planId: string, interval: "month" | "year", prorationDate?: number) =>
|
||||
Request<Agency>({
|
||||
method: "POST",
|
||||
url: `/agency/${agencyId}/billing/change`,
|
||||
data: { plan_id: planId, interval },
|
||||
data: { plan_id: planId, interval, proration_date: prorationDate },
|
||||
headers: idem(),
|
||||
authorization: true,
|
||||
});
|
||||
|
||||
@@ -331,8 +331,13 @@ export function useAgencyCheckout(agencyId: string) {
|
||||
export function useChangeAgencyPlan(agencyId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({ planId, interval }: { planId: string; interval: "month" | "year" }) => changeAgencyPlan(agencyId, planId, interval),
|
||||
onSettled: () => void qc.invalidateQueries({ queryKey: ["agency"] }),
|
||||
mutationFn: ({ planId, interval, prorationDate }: { planId: string; interval: "month" | "year"; prorationDate?: number }) =>
|
||||
changeAgencyPlan(agencyId, planId, interval, prorationDate),
|
||||
// The open workspace may be one of the agency's clients, whose own plan just changed with it.
|
||||
onSettled: () => {
|
||||
void qc.invalidateQueries({ queryKey: ["agency"] });
|
||||
void qc.invalidateQueries({ queryKey: ["subscription"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -51,8 +51,9 @@ export interface AgencyPlanChangePreview {
|
||||
interval: "month" | "year";
|
||||
proration_cents: number;
|
||||
amount_due_cents: number;
|
||||
next_billing_date: string;
|
||||
currency: string;
|
||||
/** When the amounts were calculated; sent back with the switch so it bills exactly them. */
|
||||
proration_date: number;
|
||||
}
|
||||
|
||||
export interface AgenciesResult {
|
||||
|
||||
Reference in New Issue
Block a user