mirror of
https://github.com/warmbly/warmbly.git
synced 2026-11-20 16:08:12 +00:00
feat: add an automatic top-up for an agency's send pool that buys a pack on the saved card when the pool runs low, up to a set number of packs a period, turns itself off and tells the owners when the card is refused, and show on agency billing what a pack costs and what happens when sends run out
This commit is contained in:
@@ -694,7 +694,7 @@ These changes require the session to have confirmed the account holder within th
|
||||
| Invite or remove a member, change a member's role or change their access scope | `POST /organization/members/invite`, `DELETE /organization/members/:id`, `PATCH /organization/members/:id`, `PUT /organization/members/:id/access` |
|
||||
| Create, edit or delete a custom role | `POST /organization/roles`, `PATCH /organization/roles/:id`, `DELETE /organization/roles/:id` |
|
||||
| Export or import a whole workspace | `POST /organization/current/export`, `POST /organization/current/import` |
|
||||
| Add, change or remove agency staff, bring a workspace into an agency or detach one, take a workspace out of its agency, move AI balance into a client, start an agency checkout, top-up or AI balance purchase, switch its plan, or open its billing portal | `POST /agency/:agencyId/members`, `PATCH /agency/:agencyId/members/:userId`, `DELETE /agency/:agencyId/members/:userId`, `POST /agency/:agencyId/clients/attach`, `DELETE /agency/:agencyId/clients/:orgId`, `POST /agency/:agencyId/clients/:orgId/ai-balance`, `POST /organization/agency/leave`, `POST /agency/:agencyId/billing/checkout`, `POST /agency/:agencyId/billing/change`, `POST /agency/:agencyId/billing/topup`, `POST /agency/:agencyId/billing/ai-topup`, `POST /agency/:agencyId/billing/portal` |
|
||||
| Add, change or remove agency staff, bring a workspace into an agency or detach one, take a workspace out of its agency, move AI balance into a client, start an agency checkout, top-up or AI balance purchase, switch its plan, change its automatic top-up, or open its billing portal | `POST /agency/:agencyId/members`, `PATCH /agency/:agencyId/members/:userId`, `DELETE /agency/:agencyId/members/:userId`, `POST /agency/:agencyId/clients/attach`, `DELETE /agency/:agencyId/clients/:orgId`, `POST /agency/:agencyId/clients/:orgId/ai-balance`, `POST /organization/agency/leave`, `POST /agency/:agencyId/billing/checkout`, `POST /agency/:agencyId/billing/change`, `PUT /agency/:agencyId/billing/auto-topup`, `POST /agency/:agencyId/billing/topup`, `POST /agency/:agencyId/billing/ai-topup`, `POST /agency/:agencyId/billing/portal` |
|
||||
| Create, edit or revoke an agency API key | `POST /agency/:agencyId/api-keys`, `PATCH /agency/:agencyId/api-keys/:keyId`, `DELETE /agency/:agencyId/api-keys/:keyId` |
|
||||
| Schedule a workspace or account for deletion | `POST /organization/current/danger-zone/delete`, `POST /me/danger-zone/delete` |
|
||||
| Approve a self-hosted instance's warmup pool link (always refused with `403` `pool_link_closed`) | `POST /pool-link/codes/:code/approve` |
|
||||
@@ -931,6 +931,8 @@ A key passes the recent-confirmation check the session routes ask for, since it
|
||||
| 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`, 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 |
|
||||
| GET | `/agency/:agencyId/billing/auto-topup` | Staff: the automatic top-up, `enabled`, `threshold_sends`, `max_packs`, `bought_this_period`, `pack_sends`, `pack_price_cents`, the saved `card` (`brand`, `last4`) when there is one, `available`, and `failure` (`no_payment_method` or `card_declined`) when it turned itself off |
|
||||
| PUT | `/agency/:agencyId/billing/auto-topup` | Owner, admin: `enabled`, `threshold_sends` (0 to 10,000,000) and `max_packs` (1 to 20). When on, a pack is bought on the saved card once that many sends or fewer are left, up to that many packs a period. Answers the settings; a pool already under the threshold is topped up at once |
|
||||
| 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 |
|
||||
|
||||
@@ -694,6 +694,7 @@ The [agency](/guides/agencies/) routes answer these codes.
|
||||
| `invalid_monthly_send_limit` | 400 | `monthly_send_limit` is below 0 or above 100,000,000, or is not a whole number |
|
||||
| `invalid_monthly_ai_limit` | 400 | `monthly_ai_limit_usd` is below $0 or above $50,000, or is not a number |
|
||||
| `invalid_ai_amount` | 400 | `amount_usd` is outside $1 to $5,000 for a move into a client, or $5 to $5,000 for an AI balance purchase |
|
||||
| `invalid_auto_topup` | 400 | `threshold_sends` is outside 0 to 10,000,000 or `max_packs` is outside 1 to 20 on the automatic top-up |
|
||||
| `agency_plan_unavailable` | 400 | The plan is not an agency plan, or has no price for that interval yet |
|
||||
| `agency_no_subscription` | 400 | A top-up, an AI balance purchase, a plan switch or the billing portal before the agency has a plan, or a plan switch while its subscription is not active |
|
||||
| `agency_pool_unlimited` | 400 | A top-up on a plan with no send pool cap |
|
||||
@@ -712,6 +713,7 @@ The [agency](/guides/agencies/) routes answer these codes.
|
||||
| `agency_client_taken` | 409 | The workspace already belongs to an agency |
|
||||
| `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_no_payment_method` | 409 | Automatic top-up turned on for an agency with no saved card |
|
||||
| `agency_plan_unchanged` | 409 | A plan switch to the plan and billing period the agency is already on |
|
||||
| `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 |
|
||||
|
||||
@@ -139,6 +139,17 @@ Moving to a smaller pool is refused while the current period has already used mo
|
||||
|
||||
When the pool runs low, buy a **top-up pack** under **Agency > Billing**: 50,000 more sends, $85 on Agency or $60 on Agency Pro. A pack is a one-off payment, added to the current period's pool, and does not carry into the next period. A pack that is fully refunded leaves the pool.
|
||||
|
||||
#### Automatic top-up
|
||||
|
||||
Turn on **Automatic top-up** under **Agency > Billing** and Warmbly buys a pack for you when the pool runs low, so campaigns do not pause for lack of sends. You set two things:
|
||||
|
||||
- **When to buy:** a pack is bought once this many sends or fewer are left in the period. The default is 10,000.
|
||||
- **How many:** the most packs it may buy in one period, from 1 to 20. The page shows what that comes to. The default is 2.
|
||||
|
||||
Each pack is charged to the card your subscription is paid with, at your plan's pack price, and has its own invoice. Owners and admins are told each time one is bought. It is checked every ten minutes, and once when you turn it on, and it buys one pack at a time. An agency with no saved card cannot turn it on: a plan arranged directly has none until you add a card under **Invoices and payment**.
|
||||
|
||||
If the card is declined, automatic top-up turns itself off and tells the owners and admins; nothing stays owing. Update the card and turn it on again. Turning it on needs a recent confirmation of your identity, because it lets the card be charged with nobody present.
|
||||
|
||||
Like every Warmbly checkout, the agency plan, top-up packs and AI balance purchases ask for your company's legal name and billing address, and for its VAT or other business tax ID if it has one. Prices exclude taxes.
|
||||
|
||||
Owners and admins manage the plan, top-ups, AI balance purchases, invoices and payment method. **Invoices and payment** opens the billing portal. If a payment fails, client workspaces keep the plan while Stripe retries; if the subscription ends, they keep it until a few days after the period it paid for, then go back to their own plans.
|
||||
|
||||
@@ -567,6 +567,47 @@ func (h *Handler) ChangeAgencyPlan(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, a)
|
||||
}
|
||||
|
||||
// GetAgencyAutoTopup is GET /agency/:agencyId/billing/auto-topup: the automatic top-up settings and the card a pack is charged to.
|
||||
func (h *Handler) GetAgencyAutoTopup(c *gin.Context) {
|
||||
userID, agencyID, ok := h.agencyCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
view, xerr := h.AgencyService.AutoTopup(c.Request.Context(), agencyID, userID)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, view)
|
||||
}
|
||||
|
||||
// SetAgencyAutoTopup is PUT /agency/:agencyId/billing/auto-topup: turn the automatic top-up on or off and set its limits.
|
||||
func (h *Handler) SetAgencyAutoTopup(c *gin.Context) {
|
||||
userID, agencyID, ok := h.agencyCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ThresholdSends int `json:"threshold_sends"`
|
||||
MaxPacks int `json:"max_packs"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
view, xerr := h.AgencyService.SetAutoTopup(c.Request.Context(), agencyID, userID, req.Enabled, req.ThresholdSends, req.MaxPacks)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
h.auditAgency(c, agencyID, models.AuditActionUpdate, map[string]string{
|
||||
"action": "auto_topup", "enabled": strconv.FormatBool(req.Enabled),
|
||||
"threshold_sends": strconv.Itoa(req.ThresholdSends), "max_packs": strconv.Itoa(req.MaxPacks),
|
||||
})
|
||||
c.JSON(http.StatusOK, view)
|
||||
}
|
||||
|
||||
type agencyReturnRequest struct {
|
||||
SuccessURL string `json:"success_url"`
|
||||
CancelURL string `json:"cancel_url"`
|
||||
|
||||
@@ -1790,6 +1790,9 @@ func Run(
|
||||
agencyRoutes.POST("/:agencyId/billing/checkout", sessionOnly, middleware.RequireFreshAuth(), m.IdempotencyMiddleware(), h.AgencyCheckout)
|
||||
agencyRoutes.GET("/:agencyId/billing/change/preview", sessionOnly, h.PreviewAgencyPlanChange)
|
||||
agencyRoutes.POST("/:agencyId/billing/change", sessionOnly, middleware.RequireFreshAuth(), m.IdempotencyMiddleware(), h.ChangeAgencyPlan)
|
||||
agencyRoutes.GET("/:agencyId/billing/auto-topup", sessionOnly, h.GetAgencyAutoTopup)
|
||||
// Turning it on lets the saved card be charged with nobody present.
|
||||
agencyRoutes.PUT("/:agencyId/billing/auto-topup", sessionOnly, middleware.RequireFreshAuth(), h.SetAgencyAutoTopup)
|
||||
agencyRoutes.POST("/:agencyId/billing/topup", sessionOnly, middleware.RequireFreshAuth(), m.IdempotencyMiddleware(), h.AgencyTopup)
|
||||
agencyRoutes.POST("/:agencyId/billing/ai-topup", sessionOnly, middleware.RequireFreshAuth(), m.IdempotencyMiddleware(), h.AgencyAITopup)
|
||||
agencyRoutes.POST("/:agencyId/billing/portal", sessionOnly, middleware.RequireFreshAuth(), h.AgencyPortal)
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
package agency
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stripe/stripe-go/v86"
|
||||
"github.com/stripe/stripe-go/v86/customer"
|
||||
"github.com/stripe/stripe-go/v86/invoice"
|
||||
"github.com/stripe/stripe-go/v86/invoiceitem"
|
||||
"github.com/stripe/stripe-go/v86/subscription"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/observability/errs"
|
||||
)
|
||||
|
||||
const purposeAgencyAutoTopup = "agency_topup_auto"
|
||||
|
||||
// SavedCard is the card an agency's subscription is paid with, as the dashboard shows it.
|
||||
type SavedCard struct {
|
||||
ID string `json:"-"`
|
||||
Brand string `json:"brand"`
|
||||
Last4 string `json:"last4"`
|
||||
}
|
||||
|
||||
// AutoTopup is an agency's automatic top-up as its billing page shows it.
|
||||
type AutoTopup struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ThresholdSends int `json:"threshold_sends"`
|
||||
MaxPacks int `json:"max_packs"`
|
||||
// BoughtThisPeriod is how many packs it has bought in the current period.
|
||||
BoughtThisPeriod int `json:"bought_this_period"`
|
||||
// Failure says why it turned itself off: no_payment_method or card_declined.
|
||||
Failure string `json:"failure,omitempty"`
|
||||
PackSends int `json:"pack_sends"`
|
||||
PackCents int64 `json:"pack_price_cents"`
|
||||
// Card is the card a pack is charged to; absent when the agency has none saved.
|
||||
Card *SavedCard `json:"card,omitempty"`
|
||||
// Available is false when the agency has no pool to top up: no plan in force, or a plan with no cap.
|
||||
Available bool `json:"available"`
|
||||
}
|
||||
|
||||
// packCharger charges a send pack to an agency's saved card.
|
||||
type packCharger interface {
|
||||
// Card is the agency's saved card; nil when it has none.
|
||||
Card(ctx context.Context, a *models.Agency) (*SavedCard, error)
|
||||
// Charge bills cents to the card once per key and returns the payment's reference; declined reports a refusal by the card.
|
||||
Charge(ctx context.Context, a *models.Agency, card *SavedCard, cents int64, key string, meta map[string]string) (ref string, declined bool, err error)
|
||||
}
|
||||
|
||||
func (s *Service) packs() packCharger {
|
||||
if s.charger != nil {
|
||||
return s.charger
|
||||
}
|
||||
return stripeCharger{}
|
||||
}
|
||||
|
||||
func (s *Service) autoTopupView(ctx context.Context, a *models.Agency, withCard bool) (*AutoTopup, *errx.Error) {
|
||||
now := s.now()
|
||||
start, _ := models.AgencyPeriod(a.CurrentPeriodStart, a.CurrentPeriodEnd, now)
|
||||
bought, err := s.repo.AutoTopupCount(ctx, a.ID, start)
|
||||
if err != nil {
|
||||
return nil, internal(err)
|
||||
}
|
||||
_, unlimited, active := s.poolSize(ctx, a)
|
||||
out := &AutoTopup{
|
||||
Enabled: a.AutoTopupEnabled, ThresholdSends: a.AutoTopupThreshold, MaxPacks: a.AutoTopupMaxPacks, BoughtThisPeriod: bought,
|
||||
PackSends: models.AgencyTopupSends, PackCents: models.AgencyTopupPriceCents(a.EffectivePlanID(now)),
|
||||
Available: active && !unlimited,
|
||||
}
|
||||
if a.AutoTopupFailure != nil {
|
||||
out.Failure = *a.AutoTopupFailure
|
||||
}
|
||||
if withCard && s.billing {
|
||||
// A card that cannot be read is shown as none; the page then asks for one.
|
||||
if card, cerr := s.packs().Card(ctx, a); cerr == nil {
|
||||
out.Card = card
|
||||
} else {
|
||||
errs.CaptureException(fmt.Errorf("agency saved card: %w", cerr))
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// AutoTopup is the agency's automatic top-up settings, with the card a pack would be charged to.
|
||||
func (s *Service) AutoTopup(ctx context.Context, agencyID, userID uuid.UUID) (*AutoTopup, *errx.Error) {
|
||||
if !s.billing {
|
||||
return nil, errBillingDisabled
|
||||
}
|
||||
a, _, xerr := s.access(ctx, agencyID, userID, false)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
return s.autoTopupView(ctx, a, true)
|
||||
}
|
||||
|
||||
// SetAutoTopup turns the automatic top-up on or off and sets when it buys and how many packs a period.
|
||||
func (s *Service) SetAutoTopup(ctx context.Context, agencyID, actorID uuid.UUID, enabled bool, threshold, maxPacks int) (*AutoTopup, *errx.Error) {
|
||||
if !s.billing {
|
||||
return nil, errBillingDisabled
|
||||
}
|
||||
a, _, xerr := s.access(ctx, agencyID, actorID, true)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
if threshold < 0 || threshold > models.AgencyAutoTopupMaxThreshold {
|
||||
return nil, errx.NewWithIdentifier(errx.BadRequest, "invalid_auto_topup", "The threshold must be between 0 and 10,000,000 sends.")
|
||||
}
|
||||
if maxPacks < 1 || maxPacks > models.AgencyAutoTopupMaxPacks {
|
||||
return nil, errx.NewWithIdentifier(errx.BadRequest, "invalid_auto_topup", "Choose between 1 and 20 packs a period.")
|
||||
}
|
||||
var card *SavedCard
|
||||
if enabled {
|
||||
if _, unlimited, active := s.poolSize(ctx, a); !active {
|
||||
return nil, errx.NewWithIdentifier(errx.BadRequest, "agency_no_subscription", "Choose an agency plan before turning on automatic top-up.")
|
||||
} else if unlimited {
|
||||
return nil, errx.NewWithIdentifier(errx.BadRequest, "agency_pool_unlimited", "This agency's plan has no send pool to top up.")
|
||||
}
|
||||
// A pack is charged without anyone present, so there has to be a card to charge.
|
||||
c, err := s.packs().Card(ctx, a)
|
||||
if err != nil {
|
||||
errs.CaptureException(fmt.Errorf("agency saved card: %w", err))
|
||||
return nil, errx.New(errx.Internal, "failed to read the saved card")
|
||||
}
|
||||
if c == nil {
|
||||
return nil, errx.NewWithIdentifier(errx.Conflict, "agency_no_payment_method",
|
||||
"This agency has no saved card. Automatic top-up charges the card its subscription is paid with.")
|
||||
}
|
||||
card = c
|
||||
}
|
||||
if err := s.repo.SetAutoTopup(ctx, agencyID, enabled, threshold, maxPacks); err != nil {
|
||||
return nil, internal(err)
|
||||
}
|
||||
a.AutoTopupEnabled, a.AutoTopupThreshold, a.AutoTopupMaxPacks, a.AutoTopupFailure = enabled, threshold, maxPacks, nil
|
||||
view, xerr := s.autoTopupView(ctx, a, false)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
view.Card = card
|
||||
// A pool already under the new threshold is topped up now, not at the next sweep.
|
||||
if enabled {
|
||||
s.autoTopup(ctx, a)
|
||||
if fresh, err := s.repo.Get(ctx, agencyID); err == nil && fresh != nil {
|
||||
if v, xerr := s.autoTopupView(ctx, fresh, false); xerr == nil {
|
||||
v.Card = card
|
||||
view = v
|
||||
}
|
||||
}
|
||||
}
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// autoTopup buys one pack when the agency's pool is at or under its threshold
|
||||
// and the period has packs left to buy. One pack a call: the next sweep buys
|
||||
// another if the pool is still low. Best-effort; a refusal by the card turns
|
||||
// it off and tells the people who manage the agency.
|
||||
func (s *Service) autoTopup(ctx context.Context, a *models.Agency) {
|
||||
if !s.billing || !a.AutoTopupEnabled || a.StripeCustomerID == nil || *a.StripeCustomerID == "" {
|
||||
return
|
||||
}
|
||||
if _, unlimited, active := s.poolSize(ctx, a); unlimited || !active {
|
||||
return
|
||||
}
|
||||
lock := s.switching(a.ID)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
s.forgetAgency(a.ID)
|
||||
u, xerr := s.usage(ctx, a)
|
||||
if xerr != nil || u.Remaining > int64(a.AutoTopupThreshold) {
|
||||
return
|
||||
}
|
||||
bought, err := s.repo.AutoTopupCount(ctx, a.ID, u.PeriodStart)
|
||||
if err != nil {
|
||||
errs.CaptureException(err)
|
||||
return
|
||||
}
|
||||
if bought >= a.AutoTopupMaxPacks {
|
||||
return
|
||||
}
|
||||
charger := s.packs()
|
||||
card, err := charger.Card(ctx, a)
|
||||
if err != nil {
|
||||
errs.CaptureException(fmt.Errorf("agency auto top-up card: %w", err))
|
||||
return
|
||||
}
|
||||
if card == nil {
|
||||
s.autoTopupOff(ctx, a, models.AgencyAutoTopupNoCard)
|
||||
return
|
||||
}
|
||||
cents := models.AgencyTopupPriceCents(a.EffectivePlanID(s.now()))
|
||||
// One key per pack of a period, so every replica that reaches this asks Stripe for the same charge.
|
||||
key := fmt.Sprintf("agency-autotopup-%s-%d-%d", a.ID, u.PeriodStart.Unix(), bought+1)
|
||||
meta := map[string]string{
|
||||
metaPurpose: purposeAgencyAutoTopup, metaAgencyID: a.ID.String(),
|
||||
"sends": strconv.Itoa(models.AgencyTopupSends), "amount_cents": strconv.FormatInt(cents, 10),
|
||||
}
|
||||
ref, declined, err := charger.Charge(ctx, a, card, cents, key, meta)
|
||||
if declined {
|
||||
s.autoTopupOff(ctx, a, models.AgencyAutoTopupDeclined)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
errs.CaptureException(fmt.Errorf("agency auto top-up %s: %w", a.ID, err))
|
||||
return
|
||||
}
|
||||
reason := "auto_topup"
|
||||
added, err := s.repo.RecordTopup(ctx, &models.AgencyPoolTopup{
|
||||
AgencyID: a.ID, Sends: models.AgencyTopupSends, AmountCents: cents, StripePaymentIntentID: &ref,
|
||||
PeriodStart: u.PeriodStart, Reason: &reason, Automatic: true,
|
||||
})
|
||||
if err != nil {
|
||||
errs.CaptureException(err)
|
||||
return
|
||||
}
|
||||
s.forgetAgency(a.ID)
|
||||
if added {
|
||||
s.tellManagers(ctx, a, "A top-up pack was added automatically",
|
||||
fmt.Sprintf("Your agency was down to %d sends, so %d more were added for $%.2f. Pack %d of %d this period.",
|
||||
u.Remaining, models.AgencyTopupSends, float64(cents)/100, bought+1, a.AutoTopupMaxPacks),
|
||||
map[string]any{"agency_id": a.ID.String(), "auto_topup": "bought"})
|
||||
}
|
||||
}
|
||||
|
||||
// autoTopupOff turns the automatic top-up off after a failure and says so.
|
||||
func (s *Service) autoTopupOff(ctx context.Context, a *models.Agency, failure string) {
|
||||
if err := s.repo.DisableAutoTopup(ctx, a.ID, failure); err != nil {
|
||||
errs.CaptureException(err)
|
||||
return
|
||||
}
|
||||
body := "The card on file was declined, so automatic top-up is off. Update the card under Agency > Billing and turn it on again, or buy a pack there."
|
||||
if failure == models.AgencyAutoTopupNoCard {
|
||||
body = "There is no saved card to charge, so automatic top-up is off. Add a card under Agency > Billing and turn it on again, or buy a pack there."
|
||||
}
|
||||
s.tellManagers(ctx, a, "Automatic top-up could not add sends", body, map[string]any{"agency_id": a.ID.String(), "auto_topup": failure})
|
||||
}
|
||||
|
||||
// tellManagers notifies the agency's owner and admins. Notifications are addressed within a workspace; staff are members of every client.
|
||||
func (s *Service) tellManagers(ctx context.Context, a *models.Agency, title, body string, meta map[string]any) {
|
||||
if s.notifier == nil {
|
||||
return
|
||||
}
|
||||
clients, err := s.repo.ListClientOrganizations(ctx, a.ID)
|
||||
if err != nil || len(clients) == 0 {
|
||||
return
|
||||
}
|
||||
staff, err := s.repo.ListMembers(ctx, a.ID)
|
||||
if err != nil {
|
||||
errs.CaptureException(err)
|
||||
return
|
||||
}
|
||||
orgID := clients[0].OrganizationID
|
||||
for _, m := range staff {
|
||||
if m.Role.CanManage() {
|
||||
s.notifier.Notify(ctx, m.UserID, &orgID, models.NotifBillingAlert, title, body, "/app/agency/settings/billing", meta)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stripeCharger charges packs through Stripe invoices, so each one has an invoice like a pack bought at checkout.
|
||||
type stripeCharger struct{}
|
||||
|
||||
func cardOf(pm *stripe.PaymentMethod) *SavedCard {
|
||||
if pm == nil || pm.ID == "" {
|
||||
return nil
|
||||
}
|
||||
c := &SavedCard{ID: pm.ID}
|
||||
if pm.Card != nil {
|
||||
c.Brand, c.Last4 = string(pm.Card.Brand), pm.Card.Last4
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// Card reads the subscription's own card first, then the customer's default.
|
||||
func (stripeCharger) Card(ctx context.Context, a *models.Agency) (*SavedCard, error) {
|
||||
if a.StripeSubscriptionID != nil && *a.StripeSubscriptionID != "" {
|
||||
p := &stripe.SubscriptionParams{Params: stripe.Params{Context: ctx}}
|
||||
p.AddExpand("default_payment_method")
|
||||
sub, err := subscription.Get(*a.StripeSubscriptionID, p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c := cardOf(sub.DefaultPaymentMethod); c != nil {
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
if a.StripeCustomerID == nil || *a.StripeCustomerID == "" {
|
||||
return nil, nil
|
||||
}
|
||||
p := &stripe.CustomerParams{Params: stripe.Params{Context: ctx}}
|
||||
p.AddExpand("invoice_settings.default_payment_method")
|
||||
cust, err := customer.Get(*a.StripeCustomerID, p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cust.InvoiceSettings == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return cardOf(cust.InvoiceSettings.DefaultPaymentMethod), nil
|
||||
}
|
||||
|
||||
func (stripeCharger) Charge(ctx context.Context, a *models.Agency, card *SavedCard, cents int64, key string, meta map[string]string) (string, bool, error) {
|
||||
description := "Agency send pack: 50,000 sends (automatic top-up)"
|
||||
ip := &stripe.InvoiceParams{
|
||||
Params: stripe.Params{Context: ctx},
|
||||
Customer: a.StripeCustomerID,
|
||||
CollectionMethod: stripe.String("charge_automatically"),
|
||||
AutoAdvance: stripe.Bool(false),
|
||||
PendingInvoiceItemsBehavior: stripe.String("exclude"),
|
||||
AutomaticTax: &stripe.InvoiceAutomaticTaxParams{Enabled: stripe.Bool(false)},
|
||||
Description: stripe.String(description),
|
||||
Metadata: meta,
|
||||
}
|
||||
ip.SetIdempotencyKey(key + "-invoice")
|
||||
inv, err := invoice.New(ip)
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("create invoice: %w", err)
|
||||
}
|
||||
if inv.Status == stripe.InvoiceStatusDraft {
|
||||
item := &stripe.InvoiceItemParams{
|
||||
Params: stripe.Params{Context: ctx}, Customer: a.StripeCustomerID, Invoice: stripe.String(inv.ID),
|
||||
Amount: stripe.Int64(cents), Currency: stripe.String("usd"), Description: stripe.String(description),
|
||||
}
|
||||
item.SetIdempotencyKey(key + "-item")
|
||||
if _, err := invoiceitem.New(item); err != nil {
|
||||
return "", false, fmt.Errorf("add invoice line: %w", err)
|
||||
}
|
||||
fin := &stripe.InvoiceFinalizeInvoiceParams{Params: stripe.Params{Context: ctx}, AutoAdvance: stripe.Bool(false)}
|
||||
fin.SetIdempotencyKey(key + "-finalize")
|
||||
if inv, err = invoice.FinalizeInvoice(inv.ID, fin); err != nil {
|
||||
return "", false, fmt.Errorf("finalize invoice: %w", err)
|
||||
}
|
||||
}
|
||||
if inv.Status == stripe.InvoiceStatusVoid || inv.Status == stripe.InvoiceStatusUncollectible {
|
||||
return "", true, nil
|
||||
}
|
||||
if inv.Status != stripe.InvoiceStatusPaid {
|
||||
pay := &stripe.InvoicePayParams{Params: stripe.Params{Context: ctx}, OffSession: stripe.Bool(true), PaymentMethod: stripe.String(card.ID)}
|
||||
pay.SetIdempotencyKey(key + "-pay")
|
||||
paid, err := invoice.Pay(inv.ID, pay)
|
||||
var serr *stripe.Error
|
||||
if errors.As(err, &serr) && serr.Type == stripe.ErrorTypeCard {
|
||||
// A refused invoice is closed, so nothing stays open on the agency's account.
|
||||
void := &stripe.InvoiceVoidInvoiceParams{Params: stripe.Params{Context: ctx}}
|
||||
if _, verr := invoice.VoidInvoice(inv.ID, void); verr != nil {
|
||||
errs.CaptureException(fmt.Errorf("void refused agency top-up invoice: %w", verr))
|
||||
}
|
||||
return "", true, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("pay invoice: %w", err)
|
||||
}
|
||||
if paid == nil || paid.Status != stripe.InvoiceStatusPaid {
|
||||
return "", false, errors.New("the invoice is not paid yet")
|
||||
}
|
||||
}
|
||||
// The payment intent is what a refund names, so a refunded pack can be found again.
|
||||
gp := &stripe.InvoiceParams{Params: stripe.Params{Context: ctx}}
|
||||
gp.AddExpand("payments")
|
||||
if full, gerr := invoice.Get(inv.ID, gp); gerr == nil && full.Payments != nil {
|
||||
for _, p := range full.Payments.Data {
|
||||
if p.Payment != nil && p.Payment.PaymentIntent != nil && p.Payment.PaymentIntent.ID != "" {
|
||||
return p.Payment.PaymentIntent.ID, false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return inv.ID, false, nil
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package agency
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
// fakeCharger records what was charged and answers as told.
|
||||
type fakeCharger struct {
|
||||
card *SavedCard
|
||||
declined bool
|
||||
keys []string
|
||||
cents []int64
|
||||
}
|
||||
|
||||
func (f *fakeCharger) Card(context.Context, *models.Agency) (*SavedCard, error) { return f.card, nil }
|
||||
|
||||
func (f *fakeCharger) Charge(_ context.Context, _ *models.Agency, _ *SavedCard, cents int64, key string, _ map[string]string) (string, bool, error) {
|
||||
f.keys = append(f.keys, key)
|
||||
f.cents = append(f.cents, cents)
|
||||
if f.declined {
|
||||
return "", true, nil
|
||||
}
|
||||
return "pi_" + key, false, nil
|
||||
}
|
||||
|
||||
// topupRepo is operatorRepo plus the automatic top-up's own writes.
|
||||
type topupRepo struct {
|
||||
*operatorRepo
|
||||
disabled string
|
||||
}
|
||||
|
||||
func (r *topupRepo) AutoTopupCount(context.Context, uuid.UUID, time.Time) (int, error) {
|
||||
n := 0
|
||||
for _, t := range r.recorded {
|
||||
if t.Automatic {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r *topupRepo) DisableAutoTopup(_ context.Context, _ uuid.UUID, failure string) error {
|
||||
r.disabled = failure
|
||||
r.agency.AutoTopupEnabled = false
|
||||
r.agency.AutoTopupFailure = &failure
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *topupRepo) SetAutoTopup(_ context.Context, _ uuid.UUID, enabled bool, threshold, maxPacks int) error {
|
||||
r.agency.AutoTopupEnabled, r.agency.AutoTopupThreshold, r.agency.AutoTopupMaxPacks, r.agency.AutoTopupFailure = enabled, threshold, maxPacks, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func newTopupService(a *models.Agency, used int64, charger *fakeCharger, now time.Time) (*Service, *topupRepo, uuid.UUID) {
|
||||
actor := uuid.New()
|
||||
repo := &topupRepo{operatorRepo: &operatorRepo{
|
||||
fakeRepo: &fakeRepo{agency: a, grants: map[uuid.UUID]uuid.UUID{}, sends: map[uuid.UUID]int64{uuid.New(): used}},
|
||||
staff: map[uuid.UUID]bool{actor: true}, untils: map[uuid.UUID]*time.Time{},
|
||||
}}
|
||||
s := NewService(repo, operatorOrgs{}, operatorUsers{}, operatorSubs{}, fakePlans{pool: intp(150_000)})
|
||||
s.billing = true
|
||||
s.now = func() time.Time { return now }
|
||||
s.charger = charger
|
||||
return s, repo, actor
|
||||
}
|
||||
|
||||
func topupAgency(now time.Time, threshold, maxPacks int) *models.Agency {
|
||||
a := activeAgency(now)
|
||||
a.StripeCustomerID, a.StripeSubscriptionID = strp("cus_1"), strp("sub_1")
|
||||
a.AutoTopupEnabled, a.AutoTopupThreshold, a.AutoTopupMaxPacks = true, threshold, maxPacks
|
||||
return a
|
||||
}
|
||||
|
||||
func TestAutoTopupBuysOnePackWhenThePoolIsLow(t *testing.T) {
|
||||
now := time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC)
|
||||
a := topupAgency(now, 10_000, 2)
|
||||
charger := &fakeCharger{card: &SavedCard{ID: "pm_1", Brand: "visa", Last4: "4242"}}
|
||||
// 145,000 of 150,000 used: 5,000 left, under the 10,000 threshold.
|
||||
s, repo, _ := newTopupService(a, 145_000, charger, now)
|
||||
ctx := context.Background()
|
||||
|
||||
s.autoTopup(ctx, a)
|
||||
if len(repo.recorded) != 1 || !repo.recorded[0].Automatic || repo.recorded[0].Sends != models.AgencyTopupSends || repo.recorded[0].AmountCents != 8_500 {
|
||||
t.Fatalf("recorded: %+v", repo.recorded)
|
||||
}
|
||||
if len(charger.cents) != 1 || charger.cents[0] != 8_500 {
|
||||
t.Fatalf("charged: %v", charger.cents)
|
||||
}
|
||||
// 55,000 are left after the pack, so the next sweep buys nothing more.
|
||||
s.autoTopup(ctx, a)
|
||||
if len(charger.keys) != 1 {
|
||||
t.Fatalf("a pool back above its threshold was charged again: %v", charger.keys)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoTopupStopsAtThePeriodsPacks(t *testing.T) {
|
||||
now := time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC)
|
||||
a := topupAgency(now, 10_000, 2)
|
||||
charger := &fakeCharger{card: &SavedCard{ID: "pm_1"}}
|
||||
// So far over the pool that every pack leaves it empty.
|
||||
s, repo, _ := newTopupService(a, 400_000, charger, now)
|
||||
ctx := context.Background()
|
||||
for range 5 {
|
||||
s.autoTopup(ctx, a)
|
||||
}
|
||||
if len(repo.recorded) != 2 || len(charger.keys) != 2 {
|
||||
t.Fatalf("bought %d packs with %d charges, want the period's 2", len(repo.recorded), len(charger.keys))
|
||||
}
|
||||
if charger.keys[0] == charger.keys[1] {
|
||||
t.Fatal("each pack of a period needs its own charge key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoTopupLeavesAHealthyPoolAlone(t *testing.T) {
|
||||
now := time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC)
|
||||
a := topupAgency(now, 10_000, 2)
|
||||
charger := &fakeCharger{card: &SavedCard{ID: "pm_1"}}
|
||||
s, repo, _ := newTopupService(a, 20_000, charger, now)
|
||||
s.autoTopup(context.Background(), a)
|
||||
a.AutoTopupEnabled = false
|
||||
s.autoTopup(context.Background(), a)
|
||||
if len(charger.keys) != 0 || len(repo.recorded) != 0 {
|
||||
t.Fatalf("charged %v, recorded %v", charger.keys, repo.recorded)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoTopupTurnsItselfOffWhenTheCardRefuses(t *testing.T) {
|
||||
now := time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC)
|
||||
ctx := context.Background()
|
||||
|
||||
a := topupAgency(now, 10_000, 2)
|
||||
s, repo, _ := newTopupService(a, 149_000, &fakeCharger{card: &SavedCard{ID: "pm_1"}, declined: true}, now)
|
||||
s.autoTopup(ctx, a)
|
||||
if repo.disabled != models.AgencyAutoTopupDeclined || a.AutoTopupEnabled || len(repo.recorded) != 0 {
|
||||
t.Fatalf("declined: disabled=%q enabled=%v recorded=%v", repo.disabled, a.AutoTopupEnabled, repo.recorded)
|
||||
}
|
||||
|
||||
b := topupAgency(now, 10_000, 2)
|
||||
charger := &fakeCharger{}
|
||||
s, repo, _ = newTopupService(b, 149_000, charger, now)
|
||||
s.autoTopup(ctx, b)
|
||||
if repo.disabled != models.AgencyAutoTopupNoCard || len(charger.keys) != 0 {
|
||||
t.Fatalf("no card: disabled=%q charges=%v", repo.disabled, charger.keys)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetAutoTopupNeedsACardAndSaneLimits(t *testing.T) {
|
||||
now := time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC)
|
||||
ctx := context.Background()
|
||||
a := activeAgency(now)
|
||||
a.StripeCustomerID = strp("cus_1")
|
||||
charger := &fakeCharger{}
|
||||
s, _, actor := newTopupService(a, 0, charger, now)
|
||||
|
||||
if _, xerr := s.SetAutoTopup(ctx, a.ID, actor, true, 10_000, 2); xerr == nil || xerr.Identifier != "agency_no_payment_method" {
|
||||
t.Fatalf("no card: got %v", xerr)
|
||||
}
|
||||
charger.card = &SavedCard{ID: "pm_1", Brand: "visa", Last4: "4242"}
|
||||
for _, c := range [][2]int{{-1, 2}, {10_000, 0}, {10_000, 21}} {
|
||||
if _, xerr := s.SetAutoTopup(ctx, a.ID, actor, true, c[0], c[1]); xerr == nil || xerr.Identifier != "invalid_auto_topup" {
|
||||
t.Fatalf("threshold %d, packs %d: got %v", c[0], c[1], xerr)
|
||||
}
|
||||
}
|
||||
view, xerr := s.SetAutoTopup(ctx, a.ID, actor, true, 10_000, 3)
|
||||
if xerr != nil {
|
||||
t.Fatal(xerr)
|
||||
}
|
||||
if !view.Enabled || view.ThresholdSends != 10_000 || view.MaxPacks != 3 || view.Card == nil || view.Card.Last4 != "4242" || view.PackCents != 8_500 || !view.Available {
|
||||
t.Fatalf("view: %+v", view)
|
||||
}
|
||||
// Turning it off needs no card.
|
||||
charger.card = nil
|
||||
if view, xerr := s.SetAutoTopup(ctx, a.ID, actor, false, 10_000, 3); xerr != nil || view.Enabled {
|
||||
t.Fatalf("off: %+v %v", view, xerr)
|
||||
}
|
||||
}
|
||||
@@ -451,9 +451,19 @@ func (s *Service) HandleStripeEvent(ctx context.Context, event *stripe.Event) (b
|
||||
return false, nil
|
||||
}
|
||||
return s.refundTopup(ctx, &ch)
|
||||
case "invoice.payment_failed", "invoice.finalization_failed":
|
||||
// An automatic top-up's invoice is settled where it was charged; the event is only claimed here.
|
||||
var inv struct {
|
||||
Metadata map[string]string `json:"metadata"`
|
||||
}
|
||||
if json.Unmarshal(event.Data.Raw, &inv) == nil && inv.Metadata[metaPurpose] == purposeAgencyAutoTopup {
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
case "invoice.paid":
|
||||
var inv struct {
|
||||
Parent *struct {
|
||||
Metadata map[string]string `json:"metadata"`
|
||||
Parent *struct {
|
||||
SubscriptionDetails *struct {
|
||||
Subscription string `json:"subscription"`
|
||||
} `json:"subscription_details"`
|
||||
@@ -463,6 +473,9 @@ func (s *Service) HandleStripeEvent(ctx context.Context, event *stripe.Event) (b
|
||||
if err := json.Unmarshal(event.Data.Raw, &inv); err != nil {
|
||||
return false, nil
|
||||
}
|
||||
if inv.Metadata[metaPurpose] == purposeAgencyAutoTopup {
|
||||
return true, nil
|
||||
}
|
||||
subID := inv.Subscription
|
||||
if subID == "" && inv.Parent != nil && inv.Parent.SubscriptionDetails != nil {
|
||||
subID = inv.Parent.SubscriptionDetails.Subscription
|
||||
@@ -618,7 +631,8 @@ func (s *Service) completeTopup(ctx context.Context, agencyID uuid.UUID, sess *s
|
||||
// top-up out of the AI balance. A partial refund leaves it in; a charge that
|
||||
// paid for neither belongs to the workspace path.
|
||||
func (s *Service) refundTopup(ctx context.Context, ch *stripe.Charge) (bool, *errx.Error) {
|
||||
isTopup := ch.Metadata[metaPurpose] == purposeAgencyTopup || ch.Metadata[metaPurpose] == purposeAgencyAITopup
|
||||
purpose := ch.Metadata[metaPurpose]
|
||||
isTopup := purpose == purposeAgencyTopup || purpose == purposeAgencyAITopup || purpose == purposeAgencyAutoTopup
|
||||
if ch.PaymentIntent == nil || ch.PaymentIntent.ID == "" {
|
||||
return isTopup, nil
|
||||
}
|
||||
|
||||
@@ -146,6 +146,8 @@ func (s *Service) Sweep(ctx context.Context) error {
|
||||
if err := s.rollup(ctx, a); err != nil {
|
||||
errs.CaptureException(fmt.Errorf("agency pool rollup %s: %w", a.ID, err))
|
||||
}
|
||||
// Topped up before the alert is decided, so a pool the pack refilled raises none.
|
||||
s.autoTopup(ctx, a)
|
||||
s.checkAlerts(ctx, a)
|
||||
}
|
||||
if len(page) < 100 || ctx.Err() != nil {
|
||||
|
||||
@@ -71,6 +71,8 @@ type Service struct {
|
||||
billing bool
|
||||
now func() time.Time
|
||||
|
||||
// charger charges send packs to a saved card; nil uses Stripe.
|
||||
charger packCharger
|
||||
// switches are the locks plan switches take, picked by agency id.
|
||||
switches [64]sync.Mutex
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
ALTER TABLE agency_pool_topups
|
||||
DROP COLUMN IF EXISTS automatic;
|
||||
|
||||
ALTER TABLE agencies
|
||||
DROP COLUMN IF EXISTS auto_topup_failure,
|
||||
DROP COLUMN IF EXISTS auto_topup_max_packs,
|
||||
DROP COLUMN IF EXISTS auto_topup_threshold,
|
||||
DROP COLUMN IF EXISTS auto_topup_enabled;
|
||||
@@ -0,0 +1,13 @@
|
||||
-- An agency's automatic top-up: when its pool runs low, a send pack is bought
|
||||
-- on its saved card, up to a number of packs a period. Off by default.
|
||||
-- Expand only; the previous release ignores all of it.
|
||||
ALTER TABLE agencies
|
||||
ADD COLUMN IF NOT EXISTS auto_topup_enabled boolean NOT NULL DEFAULT false,
|
||||
-- A pack is bought once this many sends or fewer are left in the period.
|
||||
ADD COLUMN IF NOT EXISTS auto_topup_threshold integer NOT NULL DEFAULT 10000 CHECK (auto_topup_threshold >= 0),
|
||||
ADD COLUMN IF NOT EXISTS auto_topup_max_packs integer NOT NULL DEFAULT 2 CHECK (auto_topup_max_packs BETWEEN 1 AND 20),
|
||||
-- Why it turned itself off, until it is turned on again.
|
||||
ADD COLUMN IF NOT EXISTS auto_topup_failure text;
|
||||
|
||||
ALTER TABLE agency_pool_topups
|
||||
ADD COLUMN IF NOT EXISTS automatic boolean NOT NULL DEFAULT false;
|
||||
@@ -104,6 +104,11 @@ type Agency struct {
|
||||
OverrideReason *string `json:"-"`
|
||||
OverrideBy *uuid.UUID `json:"-"`
|
||||
OverrideAt *time.Time `json:"-"`
|
||||
// Automatic top-up: a pack is bought on the saved card once AutoTopupThreshold sends or fewer are left, up to AutoTopupMaxPacks a period.
|
||||
AutoTopupEnabled bool `json:"-"`
|
||||
AutoTopupThreshold int `json:"-"`
|
||||
AutoTopupMaxPacks int `json:"-"`
|
||||
AutoTopupFailure *string `json:"-"`
|
||||
// Grant is set while an operator's plan is in force, for the dashboard.
|
||||
Grant *AgencyGrant `json:"granted,omitempty"`
|
||||
// BillingInterval is "month" or "year" while a subscription is in force, read off its period.
|
||||
@@ -178,8 +183,22 @@ type AgencyPoolTopup struct {
|
||||
// GrantedBy and Reason are set on sends an operator added, which have no payment.
|
||||
GrantedBy *uuid.UUID `json:"-"`
|
||||
Reason *string `json:"-"`
|
||||
// Automatic marks a pack the automatic top-up bought.
|
||||
Automatic bool `json:"-"`
|
||||
}
|
||||
|
||||
// Bounds of an agency's automatic top-up settings.
|
||||
const (
|
||||
AgencyAutoTopupMaxThreshold = 10_000_000
|
||||
AgencyAutoTopupMaxPacks = 20
|
||||
)
|
||||
|
||||
// Why an automatic top-up turned itself off.
|
||||
const (
|
||||
AgencyAutoTopupNoCard = "no_payment_method"
|
||||
AgencyAutoTopupDeclined = "card_declined"
|
||||
)
|
||||
|
||||
// AgencyRef names the agency a workspace belongs to.
|
||||
type AgencyRef struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
|
||||
@@ -78,6 +78,12 @@ type AgencyRepository interface {
|
||||
// RefundTopup marks the pack paid by the payment intent refunded and
|
||||
// returns its agency; false when no pack was paid by it.
|
||||
RefundTopup(ctx context.Context, paymentIntentID string) (uuid.UUID, bool, error)
|
||||
// SetAutoTopup stores the automatic top-up settings and clears why it last turned itself off.
|
||||
SetAutoTopup(ctx context.Context, agencyID uuid.UUID, enabled bool, threshold, maxPacks int) error
|
||||
// DisableAutoTopup turns the automatic top-up off and records why.
|
||||
DisableAutoTopup(ctx context.Context, agencyID uuid.UUID, failure string) error
|
||||
// AutoTopupCount is how many packs the automatic top-up bought in the period, refunded ones included.
|
||||
AutoTopupCount(ctx context.Context, agencyID uuid.UUID, periodStart time.Time) (int, error)
|
||||
// ClaimPoolAlert raises the period's alert level; false when it was already that high.
|
||||
ClaimPoolAlert(ctx context.Context, agencyID uuid.UUID, periodStart time.Time, level int) (bool, error)
|
||||
|
||||
@@ -115,7 +121,8 @@ const agencyColumns = `a.id, a.name, a.owner_user_id, a.plan_id, a.stripe_custom
|
||||
a.created_at, a.updated_at,
|
||||
(SELECT COUNT(*) FROM agency_clients ac WHERE ac.agency_id = a.id),
|
||||
a.managed_plan_id, a.managed_at, a.managed_by, a.managed_reason, a.managed_until,
|
||||
a.pool_override, a.ai_allowance_override_micro, a.override_reason, a.override_by, a.override_at`
|
||||
a.pool_override, a.ai_allowance_override_micro, a.override_reason, a.override_by, a.override_at,
|
||||
a.auto_topup_enabled, a.auto_topup_threshold, a.auto_topup_max_packs, a.auto_topup_failure`
|
||||
|
||||
func scanAgency(row pgx.Row, extra ...any) (*models.Agency, error) {
|
||||
var a models.Agency
|
||||
@@ -123,7 +130,8 @@ func scanAgency(row pgx.Row, extra ...any) (*models.Agency, error) {
|
||||
&a.CurrentPeriodStart, &a.CurrentPeriodEnd, &a.CancelAtPeriodEnd, &a.PoolAlertLevel, &a.PoolAlertPeriod,
|
||||
&a.CreatedAt, &a.UpdatedAt, &a.ClientCount,
|
||||
&a.ManagedPlanID, &a.ManagedAt, &a.ManagedBy, &a.ManagedReason, &a.ManagedUntil,
|
||||
&a.PoolOverride, &a.AIAllowanceOverride, &a.OverrideReason, &a.OverrideBy, &a.OverrideAt}
|
||||
&a.PoolOverride, &a.AIAllowanceOverride, &a.OverrideReason, &a.OverrideBy, &a.OverrideAt,
|
||||
&a.AutoTopupEnabled, &a.AutoTopupThreshold, &a.AutoTopupMaxPacks, &a.AutoTopupFailure}
|
||||
if err := row.Scan(append(dest, extra...)...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -502,15 +510,32 @@ func (r *agencyRepository) RecordTopup(ctx context.Context, t *models.AgencyPool
|
||||
if t.ID == uuid.Nil {
|
||||
t.ID = uuid.New()
|
||||
}
|
||||
tag, err := r.db.Exec(ctx, `INSERT INTO agency_pool_topups (id, agency_id, sends, amount_cents, stripe_payment_intent_id, period_start, granted_by, reason)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT (stripe_payment_intent_id) DO NOTHING`,
|
||||
t.ID, t.AgencyID, t.Sends, t.AmountCents, t.StripePaymentIntentID, t.PeriodStart, t.GrantedBy, t.Reason)
|
||||
tag, err := r.db.Exec(ctx, `INSERT INTO agency_pool_topups (id, agency_id, sends, amount_cents, stripe_payment_intent_id, period_start, granted_by, reason, automatic)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) ON CONFLICT (stripe_payment_intent_id) DO NOTHING`,
|
||||
t.ID, t.AgencyID, t.Sends, t.AmountCents, t.StripePaymentIntentID, t.PeriodStart, t.GrantedBy, t.Reason, t.Automatic)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return tag.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
func (r *agencyRepository) SetAutoTopup(ctx context.Context, agencyID uuid.UUID, enabled bool, threshold, maxPacks int) error {
|
||||
_, err := r.db.Exec(ctx, `UPDATE agencies SET auto_topup_enabled = $2, auto_topup_threshold = $3, auto_topup_max_packs = $4,
|
||||
auto_topup_failure = NULL, updated_at = now() WHERE id = $1`, agencyID, enabled, threshold, maxPacks)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *agencyRepository) DisableAutoTopup(ctx context.Context, agencyID uuid.UUID, failure string) error {
|
||||
_, err := r.db.Exec(ctx, `UPDATE agencies SET auto_topup_enabled = false, auto_topup_failure = $2, updated_at = now() WHERE id = $1`, agencyID, failure)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *agencyRepository) AutoTopupCount(ctx context.Context, agencyID uuid.UUID, periodStart time.Time) (int, error) {
|
||||
var n int
|
||||
err := r.db.QueryRow(ctx, `SELECT COUNT(*) FROM agency_pool_topups WHERE agency_id = $1 AND period_start = $2 AND automatic`, agencyID, periodStart).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (r *agencyRepository) ClaimPoolAlert(ctx context.Context, agencyID uuid.UUID, periodStart time.Time, level int) (bool, error) {
|
||||
tag, err := r.db.Exec(ctx, `UPDATE agencies SET pool_alert_level = $3, pool_alert_period = $2
|
||||
WHERE id = $1 AND (pool_alert_period IS DISTINCT FROM $2 OR pool_alert_level < $3)`, agencyID, periodStart, level)
|
||||
|
||||
@@ -199,6 +199,11 @@ just given. Stop the admin server and the stack afterward.
|
||||
and watching the preview follow. Run it against the dashboard, without `QA_WEB_URL`:
|
||||
`QA_ADMIN_AGENCY_FIXTURES=1 pnpm proof agency-branding-look`.
|
||||
|
||||
`flows/agency-extra-sends.flow.ts` records the **Extra sends** section of **Agency > Billing**: the pack price,
|
||||
automatic top-up and what happens when sends run out. It needs the same fixture with a plan in force on the
|
||||
agency (set `plan_id`, `status = 'active'` and a current period on its row). No step charges a card:
|
||||
`QA_ADMIN_AGENCY_FIXTURES=1 pnpm proof agency-extra-sends`.
|
||||
|
||||
## Member access proof fixtures
|
||||
|
||||
`flows/member-access.flow.ts` is opt-in: apply `fixtures/member-access.sql` to
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { expect, test } from "../lib/proof.ts";
|
||||
|
||||
// Agency > Billing: what extra sends cost and the automatic top-up. Needs fixtures/admin-agencies.sql with a plan in force; see the README.
|
||||
test("agency billing explains extra sends and automatic top-up", async ({ page, proof }) => {
|
||||
test.skip(process.env.QA_ADMIN_AGENCY_FIXTURES !== "1", "Apply fixtures/admin-agencies.sql, give the agency a plan, and set QA_ADMIN_AGENCY_FIXTURES=1.");
|
||||
await page.goto("/app/agency/billing");
|
||||
await expect(page.getByText("Automatic top-up", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText(/50,000 more sends for \$60/)).toBeVisible();
|
||||
await expect(page.getByText(/up to \$120 a period/)).toBeVisible();
|
||||
await proof.dwell(900);
|
||||
await proof.shot("agency-extra-sends", { caption: "Agency billing: the price of a pack, automatic top-up and what happens when sends run out" });
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { AgencyPage } from "@/components/app/agency/AgencyPage";
|
||||
import React from "react";
|
||||
import { CheckIcon, ExternalLinkIcon, Loader2Icon, PlusIcon, SparklesIcon } from "lucide-react";
|
||||
import { CheckIcon, ExternalLinkIcon, Loader2Icon, SparklesIcon } from "lucide-react";
|
||||
import toast from "react-hot-toast/headless";
|
||||
import { EmptyBlock, PageBody, SectionBar } from "@/components/layout/Page";
|
||||
import { NumberInput } from "@/components/ui/field";
|
||||
@@ -22,6 +22,7 @@ import type { AppError } from "@/lib/api/client/normalizeError";
|
||||
import buildError from "@/lib/helper/buildError";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatNumber } from "@/components/app/agency/styles";
|
||||
import ExtraSends from "@/components/app/agency/ExtraSends";
|
||||
import { AGENCY_PLAN_FEATURES } from "@/components/app/agency/planFeatures";
|
||||
import { fmtUsd, fmtUsdTrim, roundCents } from "@/lib/money";
|
||||
|
||||
@@ -248,29 +249,8 @@ function AgencyBilling() {
|
||||
|
||||
{active && u && !u.unlimited && (
|
||||
<>
|
||||
<SectionBar label="Top-up packs" />
|
||||
<div className="px-5 py-4 border-b border-slate-200 flex flex-wrap items-center gap-3">
|
||||
<div className="flex-1 min-w-[220px]">
|
||||
<div className="text-[12.5px] text-slate-900">
|
||||
{formatNumber(u.topup_sends)} more sends for {money(u.topup_price_cents / 100)}
|
||||
</div>
|
||||
<div className="text-[11.5px] text-slate-500">
|
||||
One-off, added to this period's pool and gone when the period renews.
|
||||
{u.topups > 0 && ` ${formatNumber(u.topups)} added this period.`}
|
||||
</div>
|
||||
</div>
|
||||
{canManage && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void go(topup.mutateAsync())}
|
||||
disabled={topup.isPending}
|
||||
className="h-7 px-2.5 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12px] font-medium inline-flex items-center gap-1.5 disabled:opacity-60"
|
||||
>
|
||||
{topup.isPending ? <Loader2Icon className="w-3 h-3 animate-spin" /> : <PlusIcon className="w-3 h-3" />}
|
||||
Buy a pack
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<SectionBar label="Extra sends" />
|
||||
<ExtraSends agencyId={agencyId} usage={u} canManage={canManage} buying={topup.isPending} onBuy={() => void go(topup.mutateAsync())} />
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
// Agency > Billing: what extra sends cost, what happens when the pool runs out, and the
|
||||
// automatic top-up that buys a pack on the saved card before it does.
|
||||
|
||||
import React from "react";
|
||||
import { AlertTriangleIcon, CreditCardIcon, Loader2Icon, PlusIcon } from "lucide-react";
|
||||
import toast from "react-hot-toast/headless";
|
||||
|
||||
import { Toggle } from "@/components/app/campaigns/preferences/components/CampaignPreferenceBoolBox";
|
||||
import { NumberInput } from "@/components/ui/field";
|
||||
import { useAgencyAutoTopup, useSetAgencyAutoTopup } from "@/lib/api/hooks/app/agency/useAgency";
|
||||
import type { AgencyAutoTopup, AgencyUsage } from "@/lib/api/models/app/agency/Agency";
|
||||
import type { AppError } from "@/lib/api/client/normalizeError";
|
||||
import buildError from "@/lib/helper/buildError";
|
||||
import { fmtUsdTrim } from "@/lib/money";
|
||||
import { formatNumber } from "./styles";
|
||||
|
||||
const FAILURES: Record<NonNullable<AgencyAutoTopup["failure"]>, string> = {
|
||||
card_declined: "The card on file was declined, so automatic top-up turned itself off. Update the card under Invoices and payment, then turn it on again.",
|
||||
no_payment_method: "There was no saved card to charge, so automatic top-up turned itself off. Add a card under Invoices and payment, then turn it on again.",
|
||||
};
|
||||
|
||||
function cardName(card: NonNullable<AgencyAutoTopup["card"]>) {
|
||||
const brand = card.brand ? card.brand.charAt(0).toUpperCase() + card.brand.slice(1) : "Card";
|
||||
return card.last4 ? `${brand} ending ${card.last4}` : brand;
|
||||
}
|
||||
|
||||
export default function ExtraSends({
|
||||
agencyId,
|
||||
usage,
|
||||
canManage,
|
||||
buying,
|
||||
onBuy,
|
||||
}: {
|
||||
agencyId: string;
|
||||
usage: AgencyUsage;
|
||||
canManage: boolean;
|
||||
/** A pack's checkout is opening. */
|
||||
buying: boolean;
|
||||
onBuy: () => void;
|
||||
}) {
|
||||
const auto = useAgencyAutoTopup(agencyId);
|
||||
const save = useSetAgencyAutoTopup(agencyId);
|
||||
const data = auto.data;
|
||||
const price = usage.topup_price_cents / 100;
|
||||
|
||||
// The two limits are typed freely and saved when the field is left, so a half-typed number is never sent.
|
||||
const [threshold, setThreshold] = React.useState<number | null>(null);
|
||||
const [maxPacks, setMaxPacks] = React.useState<number | null>(null);
|
||||
const shownThreshold = threshold ?? data?.threshold_sends ?? 10_000;
|
||||
const shownMax = maxPacks ?? data?.max_packs ?? 2;
|
||||
|
||||
const apply = async (input: { enabled: boolean; threshold_sends: number; max_packs: number }) => {
|
||||
try {
|
||||
const before = data?.bought_this_period ?? 0;
|
||||
const res = await save.mutateAsync(input);
|
||||
setThreshold(null);
|
||||
setMaxPacks(null);
|
||||
if (res.bought_this_period > before) toast.success(`${formatNumber(res.pack_sends)} sends were added now, because the pool was already low`);
|
||||
else if (input.enabled && !data?.enabled) toast.success("Automatic top-up is on");
|
||||
} catch (e) {
|
||||
toast.error(buildError(e as AppError));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="border-b border-slate-200">
|
||||
<div className="px-5 py-4 flex flex-wrap items-center gap-3">
|
||||
<div className="flex-1 min-w-[220px]">
|
||||
<div className="text-[12.5px] font-medium text-slate-900">
|
||||
{formatNumber(usage.topup_sends)} more sends for {fmtUsdTrim(price)}
|
||||
</div>
|
||||
<div className="mt-0.5 text-[11.5px] leading-relaxed text-slate-500">
|
||||
A one-off pack, added to this period's pool and gone when the period renews.
|
||||
{usage.topups > 0 && ` ${formatNumber(usage.topups)} added this period.`}
|
||||
</div>
|
||||
</div>
|
||||
{canManage && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onBuy}
|
||||
disabled={buying}
|
||||
className="h-7 px-2.5 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12px] font-medium inline-flex items-center gap-1.5 disabled:opacity-60"
|
||||
>
|
||||
{buying ? <Loader2Icon className="w-3 h-3 animate-spin" /> : <PlusIcon className="w-3 h-3" />}
|
||||
Buy a pack
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mx-5 mb-4 rounded-lg border border-slate-200">
|
||||
<div className="px-4 py-3 flex items-start gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[12.5px] font-medium text-slate-900">Automatic top-up</div>
|
||||
<p className="mt-0.5 text-[11.5px] leading-relaxed text-slate-500">
|
||||
Buys a pack on your saved card when the pool runs low, so campaigns never pause for lack of sends.
|
||||
</p>
|
||||
</div>
|
||||
{auto.isPending ? (
|
||||
<Loader2Icon className="mt-0.5 w-3.5 h-3.5 animate-spin text-slate-300" />
|
||||
) : (
|
||||
data && (
|
||||
<Toggle
|
||||
value={data.enabled}
|
||||
onChange={(enabled) => void apply({ enabled, threshold_sends: shownThreshold, max_packs: shownMax })}
|
||||
disabled={!canManage || save.isPending || !data.available}
|
||||
ariaLabel="Automatic top-up"
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
|
||||
{data?.failure && !data.enabled && (
|
||||
<p className="mx-4 mb-3 flex gap-2 rounded-md bg-amber-50 px-3 py-2 text-[11.5px] leading-relaxed text-amber-800">
|
||||
<AlertTriangleIcon className="mt-px w-3.5 h-3.5 shrink-0" />
|
||||
{FAILURES[data.failure]}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{data && (
|
||||
<div className="border-t border-slate-200 px-4 py-3 grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-3">
|
||||
<label className="block">
|
||||
<span className="block text-[12px] font-medium text-slate-700">Buy a pack when this many sends are left</span>
|
||||
<span className="mt-1.5 block w-40">
|
||||
<NumberInput
|
||||
value={shownThreshold}
|
||||
onChange={setThreshold}
|
||||
onCommit={(v) => {
|
||||
if (data.enabled && v !== data.threshold_sends) void apply({ enabled: true, threshold_sends: v, max_packs: shownMax });
|
||||
}}
|
||||
min={0}
|
||||
max={10_000_000}
|
||||
step={1000}
|
||||
disabled={!canManage || save.isPending}
|
||||
/>
|
||||
</span>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="block text-[12px] font-medium text-slate-700">At most this many packs a period</span>
|
||||
<span className="mt-1.5 flex items-center gap-2">
|
||||
<span className="block w-24">
|
||||
<NumberInput
|
||||
value={shownMax}
|
||||
onChange={setMaxPacks}
|
||||
onCommit={(v) => {
|
||||
if (data.enabled && v !== data.max_packs) void apply({ enabled: true, threshold_sends: shownThreshold, max_packs: v });
|
||||
}}
|
||||
min={1}
|
||||
max={20}
|
||||
disabled={!canManage || save.isPending}
|
||||
/>
|
||||
</span>
|
||||
<span className="text-[11.5px] text-slate-500 tabular-nums">up to {fmtUsdTrim(shownMax * price)} a period</span>
|
||||
</span>
|
||||
</label>
|
||||
<p className="sm:col-span-2 flex items-center gap-1.5 text-[11.5px] text-slate-500">
|
||||
<CreditCardIcon className="w-3.5 h-3.5 text-slate-400 shrink-0" />
|
||||
{data.card
|
||||
? `Charged to ${cardName(data.card)}, with an invoice for each pack.`
|
||||
: "No saved card yet. The card your subscription is paid with is the one charged."}
|
||||
{data.enabled && ` ${data.bought_this_period} of ${data.max_packs} bought this period.`}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="px-5 pb-4 text-[11.5px] leading-relaxed text-slate-500">
|
||||
When the pool is used up, campaigns across your clients pause until the period renews or sends are added. Warmup keeps
|
||||
running. Owners and admins are told at 80% and at 100%.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,10 +5,12 @@ export const AGENCY_PLAN_FEATURES: Record<string, string[]> = {
|
||||
"The API and webhooks in every client workspace",
|
||||
"Your logo, colour and portal domain on client pages",
|
||||
"Shared send pool and AI balance across clients",
|
||||
"Extra sends when you need them: 50,000 for $85",
|
||||
],
|
||||
"Agency Pro": [
|
||||
"Everything in Agency",
|
||||
"No \"Powered by Warmbly\" on client pages",
|
||||
"Sending kept apart from other customers",
|
||||
"Extra sends when you need them: 50,000 for $60",
|
||||
],
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import Request from "../../Request";
|
||||
import type { AgenciesResult, Agency, AgencyAIBalance, AgencyAITransferResult, AgencyClient, AgencyClientPatch, AgencyInvitation, AgencyMember, AgencyPlanChangePreview, AgencyPlansResult, AgencyRole, AgencyStaffResult, AgencyUsage } from "@/lib/api/models/app/agency/Agency";
|
||||
import type { AgenciesResult, Agency, AgencyAIBalance, AgencyAITransferResult, AgencyAutoTopup, AgencyClient, AgencyClientPatch, AgencyInvitation, AgencyMember, AgencyPlanChangePreview, AgencyPlansResult, AgencyRole, AgencyStaffResult, AgencyUsage } from "@/lib/api/models/app/agency/Agency";
|
||||
|
||||
const idem = () => ({ "Idempotency-Key": crypto.randomUUID() });
|
||||
|
||||
@@ -122,6 +122,12 @@ export const changeAgencyPlan = (
|
||||
authorization: true,
|
||||
});
|
||||
|
||||
export const getAgencyAutoTopup = (agencyId: string) =>
|
||||
Request<AgencyAutoTopup>({ method: "GET", url: `/agency/${agencyId}/billing/auto-topup`, authorization: true });
|
||||
|
||||
export const setAgencyAutoTopup = (agencyId: string, input: { enabled: boolean; threshold_sends: number; max_packs: number }) =>
|
||||
Request<AgencyAutoTopup>({ method: "PUT", url: `/agency/${agencyId}/billing/auto-topup`, data: input, authorization: true });
|
||||
|
||||
export const agencyTopup = (agencyId: string) =>
|
||||
Request<{ checkout_url: string }>({ method: "POST", url: `/agency/${agencyId}/billing/topup`, data: {}, headers: idem(), authorization: true });
|
||||
|
||||
|
||||
@@ -24,6 +24,8 @@ import {
|
||||
updateAgencyClient,
|
||||
updateAgencyStaff,
|
||||
changeAgencyPlan,
|
||||
getAgencyAutoTopup,
|
||||
setAgencyAutoTopup,
|
||||
} from "@/lib/api/client/app/agency/agency";
|
||||
import type { Agency, AgencyClient, AgencyClientPatch, AgencyRole, AgencyPlanChangePreview } from "@/lib/api/models/app/agency/Agency";
|
||||
import { currentPortal, portalAgencies } from "@/lib/portal";
|
||||
@@ -341,6 +343,27 @@ export function useChangeAgencyPlan(agencyId: string) {
|
||||
});
|
||||
}
|
||||
|
||||
export const agencyAutoTopupQuery = (agencyId: string) =>
|
||||
queryOptions({
|
||||
queryKey: ["agency", agencyId, "auto-topup"],
|
||||
queryFn: () => getAgencyAutoTopup(agencyId),
|
||||
enabled: !!agencyId,
|
||||
});
|
||||
|
||||
export function useAgencyAutoTopup(agencyId?: string) {
|
||||
return useQuery(agencyAutoTopupQuery(agencyId ?? ""));
|
||||
}
|
||||
|
||||
// The server checks the card and may buy a pack at once, so nothing is patched before it answers.
|
||||
export function useSetAgencyAutoTopup(agencyId: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (input: { enabled: boolean; threshold_sends: number; max_packs: number }) => setAgencyAutoTopup(agencyId, input),
|
||||
onSuccess: (data) => qc.setQueryData(agencyAutoTopupQuery(agencyId).queryKey, data),
|
||||
onSettled: () => void qc.invalidateQueries({ queryKey: ["agency"] }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useAgencyTopup(agencyId: string) {
|
||||
return useMutation({ mutationFn: () => agencyTopup(agencyId) });
|
||||
}
|
||||
|
||||
@@ -167,3 +167,19 @@ export interface AgencyRef {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/** An agency's automatic top-up: a send pack bought on its saved card when the pool runs low. */
|
||||
export interface AgencyAutoTopup {
|
||||
enabled: boolean;
|
||||
/** A pack is bought once this many sends or fewer are left in the period. */
|
||||
threshold_sends: number;
|
||||
max_packs: number;
|
||||
bought_this_period: number;
|
||||
/** Why it turned itself off. */
|
||||
failure?: "no_payment_method" | "card_declined";
|
||||
pack_sends: number;
|
||||
pack_price_cents: number;
|
||||
card?: { brand: string; last4: string };
|
||||
/** False when the agency has no pool to top up. */
|
||||
available: boolean;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user