mirror of
https://github.com/warmbly/warmbly.git
synced 2026-11-23 16:06:17 +00:00
feat: balance charges an automatic reload only while reload is on and the balance under its threshold and cancels a pending one when reload is turned off, answers a top-up still going through with 202 and honors Idempotency-Key on it, keeps user_id off checkout session metadata, gives the new reload its own auto_reload_enabled switch, sets plan monthly_credits to match the dollar allowances, closes stale legacy pack charges and fails a charge after eight unanswered attempts, and refreshes annual allowances oldest reset first
This commit is contained in:
@@ -804,7 +804,7 @@ The workspace balance, adding money, automatic reload, spend controls, the activ
|
||||
| PATCH | `/subscription/credits/settings` | `manage_billing` |
|
||||
|
||||
- `GET /subscription/balance` is everything the Balance tab shows: `balance_usd`, `monthly_usd`, `purchased_usd`, `monthly_allowance_usd`, `monthly_used_usd`, `next_reset_at`, the saved card (`payment_method`), `auto_reload`, `low_balance_usd`, `charge_in_progress`, and the `top_up` bounds and presets. On a deployment with `BILLING_PROVIDER=none` it answers only `{"unlimited": true}`.
|
||||
- `POST /subscription/balance/top-up` `{"amount_usd": 25}` charges the saved card now (from $5 to $5,000) and is billed as a Stripe invoice. A decline answers `402` with `card_declined`, `authentication_required` or `payment_failed`, which tells a client to offer Checkout instead; no saved card is `409` `payment_method_required`, and another payment still going through is `409` `charge_in_progress`. Needs an active paid plan.
|
||||
- `POST /subscription/balance/top-up` `{"amount_usd": 25}` charges the saved card now (from $5 to $5,000) and is billed as a Stripe invoice. It answers `200` with `status` `paid`, or `202` with `status` `processing` and `charge_in_progress` `true` while the payment is still going through and Warmbly finishes it in the background. It honors `Idempotency-Key`; without one, a retry while the first payment is pending answers `409` `charge_in_progress`, so it never charges twice. A decline answers `402` with `card_declined`, `authentication_required` or `payment_failed`, which tells a client to offer Checkout instead; no saved card is `409` `payment_method_required`, and another payment still going through is `409` `charge_in_progress`. Needs an active paid plan.
|
||||
- `POST /subscription/balance/checkout` `{"amount_usd": 25}` returns a Stripe Checkout `checkout_url` for the amount; the payment saves the card for next time. `POST /subscription/balance/payment-method` returns a Checkout `checkout_url` that saves or replaces the card without charging it. Money is added only in the Stripe webhook, never in the call, and exactly once.
|
||||
- `PATCH /subscription/balance/auto-reload` takes `enabled`, `threshold_usd` ($0.01 to $1,000), `amount_usd` ($5 to $5,000, more than the threshold) and `monthly_limit_usd` (at least the amount, at most $50,000), and answers with the same body as `GET /subscription/balance`. An amount not above the threshold is `422` `recharge_too_small`, a monthly limit out of range is `422` `monthly_limit_too_small`, and turning it on with no saved card is `409` `payment_method_required`.
|
||||
- `GET /subscription/balance/invoices` returns `data`: the latest Stripe invoices for the workspace, subscription and balance alike, each with `kind` (`subscription`, `top_up` or `auto_reload`), `status`, `amount_cents`, `currency`, `hosted_url` and `pdf_url`.
|
||||
|
||||
@@ -2397,7 +2397,7 @@ The workspace balance in US dollars: the plan's monthly allowance plus money the
|
||||
}
|
||||
```
|
||||
|
||||
`payment_method` is `null` with no saved card. `retry_at` and `retry_reason` are set while a declined automatic reload waits for its next try (1, 6 and 18 hours after the attempts before it). `failure_code` and `failed_at` record why automatic reload last turned itself off: `card_declined`, `authentication_required`, `no_payment_method` or `payment_failed`.
|
||||
`payment_method` is `null` with no saved card. `retry_at` and `retry_reason` are set while a declined automatic reload waits for its next try (1, 6 and 18 hours after the attempts before it). `failure_code` and `failed_at` record why automatic reload last turned itself off: `card_declined`, `authentication_required`, `no_payment_method`, `payment_failed`, or `unavailable` when Stripe could not be reached after 8 tries. A reload waiting for its next try is canceled when automatic reload is turned off or the balance is back above `threshold_usd`.
|
||||
|
||||
#### Add money on the saved card
|
||||
|
||||
@@ -2407,7 +2407,7 @@ The workspace balance in US dollars: the plan's monthly allowance plus money the
|
||||
|-------|------|----------|-------------|
|
||||
| `amount_usd` | number | yes | From `5` to `5000`, rounded to whole cents. |
|
||||
|
||||
Charges the saved card now, billed as a Stripe invoice, and answers `{"status": "paid", "amount_usd": 25, "balance_usd": 46.4375}`. `status` is `processing` when the card network has not confirmed yet; the money is added when it does. Needs an active paid plan (`403` otherwise).
|
||||
Charges the saved card now, billed as a Stripe invoice, and answers `200` with `{"status": "paid", "amount_usd": 25, "balance_usd": 46.4375, "charge_in_progress": false}`. While the payment is still going through (the card network has not confirmed, or Stripe did not answer and Warmbly retries it in the background) it answers `202` with `status` `processing` and `charge_in_progress` `true`; the money is added when the payment lands. Needs an active paid plan (`403` otherwise). Send an `Idempotency-Key` to retry the call safely; without one, a retry while the first payment is pending answers `409` `charge_in_progress` rather than charging twice.
|
||||
|
||||
| Status | Code | Meaning |
|
||||
|--------|------|---------|
|
||||
|
||||
@@ -138,7 +138,7 @@ The usage card above it shows spend today, this week and this month, a graph ove
|
||||
|
||||
You can add any amount from **$5 to $5,000**, in whole cents. Adding money needs an active paid plan.
|
||||
|
||||
- **One click on the saved card.** The card is charged at once and the money is added as soon as the payment goes through. Each charge is billed as a Stripe invoice, so it has its own invoice and receipt.
|
||||
- **One click on the saved card.** The card is charged at once and the money is added as soon as the payment goes through. If the payment is still going through when the page answers, the Balance tab says so and updates when it lands; Warmbly finishes it in the background, and another payment cannot start until it does. Each charge is billed as a Stripe invoice, so it has its own invoice and receipt.
|
||||
- **Pay another way.** Opens Stripe Checkout for the amount. Use it when there is no saved card, when you want another card, or when the saved card is declined or your bank asks to confirm the payment. Checkout saves the card for next time. Money arrives only after Stripe confirms the payment, so closing the checkout tab charges nothing, and a completed payment is added exactly once even if Stripe retries.
|
||||
- **Change the card.** Opens Stripe Checkout to save a new card, without charging anything.
|
||||
|
||||
@@ -164,6 +164,9 @@ When a reload is declined:
|
||||
|
||||
- **A temporary decline** (for example insufficient funds) is retried 1 hour, 6 hours and 18 hours later. If the last retry also fails, automatic reload turns off.
|
||||
- **A hard decline, or your bank asking to confirm the payment**, turns automatic reload off at once, so nothing else is charged. Everyone who manages billing is notified with the reason. Add money once (through Checkout if the bank needs you to confirm), update the card if it was declined, then turn automatic reload back on.
|
||||
- **Stripe keeps failing to answer**: the reload is given up after 8 tries and automatic reload turns off the same way.
|
||||
|
||||
A reload waiting for a retry is canceled, never charged, when you turn automatic reload off or the balance is back above the threshold by the time it is due.
|
||||
|
||||
The Balance tab shows the last reload, how much has been reloaded this month, and a pending retry with its time.
|
||||
|
||||
|
||||
@@ -227,9 +227,10 @@ func (h *Handler) requirePaidForBalance(c *gin.Context, orgID uuid.UUID) bool {
|
||||
}
|
||||
|
||||
// TopUpBalance — POST /subscription/balance/top-up {amount_usd}
|
||||
// Charges the saved card now. 402 card_declined or authentication_required
|
||||
// tells the dashboard to offer Checkout instead; 409 payment_method_required
|
||||
// when there is no card.
|
||||
// Charges the saved card now: 200 paid, or 202 processing while the payment
|
||||
// is still going through. 402 card_declined or authentication_required tells
|
||||
// the dashboard to offer Checkout instead; 409 payment_method_required when
|
||||
// there is no card.
|
||||
func (h *Handler) TopUpBalance(c *gin.Context) {
|
||||
orgID, ok := h.billingOrg(c)
|
||||
if !ok || !h.requirePaidForBalance(c, orgID) {
|
||||
@@ -264,7 +265,14 @@ func (h *Handler) TopUpBalance(c *gin.Context) {
|
||||
}
|
||||
// Settling the charge already logged it on the audit spine.
|
||||
bal, _ := h.CreditService.GetBalance(c.Request.Context(), orgID)
|
||||
c.JSON(http.StatusOK, gin.H{"status": res.Status, "amount_usd": usd(res.Amount), "balance_usd": usd(bal)})
|
||||
status := http.StatusOK
|
||||
if res.Status != "paid" {
|
||||
status = http.StatusAccepted
|
||||
}
|
||||
c.JSON(status, gin.H{
|
||||
"status": res.Status, "amount_usd": usd(res.Amount), "balance_usd": usd(bal),
|
||||
"charge_in_progress": res.Status != "paid",
|
||||
})
|
||||
}
|
||||
|
||||
// CreateBalanceCheckout — POST /subscription/balance/checkout {amount_usd}
|
||||
|
||||
@@ -1860,7 +1860,7 @@ func Run(
|
||||
// card, automatic reload, invoices. Charging and changing what is
|
||||
// charged need a fresh sign-in.
|
||||
subscriptions.GET("/balance", m.RequireOrganization(), m.RequirePermission(models.PermManageBilling), h.GetBalance)
|
||||
subscriptions.POST("/balance/top-up", m.RequireOrganization(), m.RequirePermission(models.PermManageBilling), middleware.RequireFreshAuth(), h.TopUpBalance)
|
||||
subscriptions.POST("/balance/top-up", m.RequireOrganization(), m.RequirePermission(models.PermManageBilling), middleware.RequireFreshAuth(), m.IdempotencyMiddleware(), h.TopUpBalance)
|
||||
subscriptions.POST("/balance/checkout", m.RequireOrganization(), m.RequirePermission(models.PermManageBilling), middleware.RequireFreshAuth(), h.CreateBalanceCheckout)
|
||||
subscriptions.POST("/balance/payment-method", m.RequireOrganization(), m.RequirePermission(models.PermManageBilling), middleware.RequireFreshAuth(), h.CreatePaymentMethodSetup)
|
||||
subscriptions.PATCH("/balance/auto-reload", m.RequireOrganization(), m.RequirePermission(models.PermManageBilling), middleware.RequireFreshAuth(), h.UpdateAutoReload)
|
||||
|
||||
+111
-21
@@ -45,6 +45,10 @@ const (
|
||||
// staleAfter is how long a pending charge may sit untouched (a crash
|
||||
// between steps) before the sweep resumes it.
|
||||
staleAfter = 5 * time.Minute
|
||||
// maxTries bounds the payment attempts on one charge, failed Stripe calls included.
|
||||
maxTries = 8
|
||||
// legacyPendingFor is how long a credit-pack charge the previous release started may stay pending.
|
||||
legacyPendingFor = 24 * time.Hour
|
||||
)
|
||||
|
||||
// Card is the slice of the Stripe service a charge needs.
|
||||
@@ -230,11 +234,19 @@ func (s *Service) paymentMethod(ctx context.Context, orgID uuid.UUID) (string, *
|
||||
|
||||
// run makes one payment attempt on a pending charge and acts on how it ended.
|
||||
func (s *Service) run(ctx context.Context, c *models.SavedCardCharge, offSession bool) error {
|
||||
// A card changed while a soft decline waited is the one to retry on.
|
||||
if c.Kind == models.SavedCardAutoReload && c.Tries > 0 {
|
||||
if _, pm, err := s.paymentMethod(ctx, c.OrgID); err == nil && pm != nil && pm.ID != c.PaymentMethodID {
|
||||
if err := s.charges.SetPaymentMethod(ctx, c.ID, pm.ID); err == nil {
|
||||
c.PaymentMethodID = pm.ID
|
||||
if c.Kind == models.SavedCardAutoReload {
|
||||
// An automatic reload is charged only while reload is on and the balance under its threshold.
|
||||
if wanted, err := s.reloadWanted(ctx, c.OrgID); err != nil {
|
||||
return err
|
||||
} else if !wanted {
|
||||
return s.cancel(ctx, c)
|
||||
}
|
||||
// A card changed while a soft decline waited is the one to retry on.
|
||||
if c.Tries > 0 {
|
||||
if _, pm, err := s.paymentMethod(ctx, c.OrgID); err == nil && pm != nil && pm.ID != c.PaymentMethodID {
|
||||
if err := s.charges.SetPaymentMethod(ctx, c.ID, pm.ID); err == nil {
|
||||
c.PaymentMethodID = pm.ID
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -243,9 +255,12 @@ func (s *Service) run(ctx context.Context, c *models.SavedCardCharge, offSession
|
||||
return err
|
||||
}
|
||||
res, err := s.card.ChargeSavedCard(ctx, c, tries, offSession)
|
||||
if err != nil {
|
||||
if err != nil && tries < maxTries {
|
||||
return err // left pending; the sweep resumes it
|
||||
}
|
||||
if err != nil {
|
||||
return s.giveUp(ctx, c, err)
|
||||
}
|
||||
c.InvoiceID = res.InvoiceID
|
||||
switch {
|
||||
case res.Paid:
|
||||
@@ -272,9 +287,61 @@ func (s *Service) run(ctx context.Context, c *models.SavedCardCharge, offSession
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) reloadWanted(ctx context.Context, orgID uuid.UUID) (bool, error) {
|
||||
cfg := s.config(ctx, orgID)
|
||||
if !cfg.AutoReloadEnabled {
|
||||
return false, nil
|
||||
}
|
||||
bal, xerr := s.credits.GetBalance(ctx, orgID)
|
||||
if xerr != nil {
|
||||
return false, xerr
|
||||
}
|
||||
return bal < cfg.AutoReloadThreshold, nil
|
||||
}
|
||||
|
||||
// cancel closes a pending charge nothing should collect any more.
|
||||
func (s *Service) cancel(ctx context.Context, c *models.SavedCardCharge) error {
|
||||
if s.card != nil {
|
||||
s.card.VoidChargeInvoice(ctx, c.InvoiceID)
|
||||
}
|
||||
if err := s.charges.MarkFailed(ctx, c.ID, models.ChargeCanceled); err != nil {
|
||||
return err
|
||||
}
|
||||
s.changed(ctx, c.OrgID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// cancelPendingReload closes the workspace's pending automatic reload, if any.
|
||||
func (s *Service) cancelPendingReload(ctx context.Context, orgID uuid.UUID) {
|
||||
c, err := s.charges.Pending(ctx, orgID)
|
||||
if err != nil || c == nil || c.Legacy || c.Kind != models.SavedCardAutoReload {
|
||||
return
|
||||
}
|
||||
if err := s.cancel(ctx, c); err != nil {
|
||||
log.Warn().Err(err).Str("charge_id", c.ID.String()).Msg("cancel pending automatic reload")
|
||||
}
|
||||
}
|
||||
|
||||
// giveUp fails a charge whose Stripe calls kept failing for maxTries attempts.
|
||||
func (s *Service) giveUp(ctx context.Context, c *models.SavedCardCharge, cause error) error {
|
||||
if cur, err := s.charges.Get(ctx, c.ID); err == nil && cur != nil {
|
||||
c.InvoiceID = cur.InvoiceID
|
||||
}
|
||||
s.card.VoidChargeInvoice(ctx, c.InvoiceID)
|
||||
if err := s.charges.MarkFailed(ctx, c.ID, models.ReloadUnavailable); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.Kind == models.SavedCardAutoReload {
|
||||
s.disable(ctx, c.OrgID, models.ReloadUnavailable)
|
||||
}
|
||||
s.changed(ctx, c.OrgID)
|
||||
return fmt.Errorf("charge %s failed after %d tries: %w", c.ID, maxTries, cause)
|
||||
}
|
||||
|
||||
// disable turns automatic reload off after a charge it cannot recover from,
|
||||
// so nothing else is charged, and tells whoever manages billing.
|
||||
func (s *Service) disable(ctx context.Context, orgID uuid.UUID, code string) {
|
||||
s.cancelPendingReload(ctx, orgID)
|
||||
turnedOff, err := s.settings.DisableAutoReload(ctx, orgID, code)
|
||||
if err != nil || !turnedOff {
|
||||
return
|
||||
@@ -348,8 +415,8 @@ func (s *Service) changed(ctx context.Context, orgID uuid.UUID) {
|
||||
}
|
||||
}
|
||||
|
||||
// TopUpResult is how a one-click top-up ended: "paid", or "processing" when the
|
||||
// card network has not answered yet and the webhook will finish it.
|
||||
// TopUpResult is how a one-click top-up ended: "paid", or "processing" while the
|
||||
// charge is still pending and the webhook or the sweep will finish it.
|
||||
type TopUpResult struct {
|
||||
Status string
|
||||
Amount models.Micro
|
||||
@@ -380,17 +447,33 @@ func (s *Service) TopUp(ctx context.Context, orgID uuid.UUID, amount models.Micr
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.run(ctx, c, false); err != nil {
|
||||
return nil, err
|
||||
runErr := s.run(ctx, c, false)
|
||||
var declined *DeclinedError
|
||||
if errors.As(runErr, &declined) {
|
||||
return nil, runErr
|
||||
}
|
||||
if done, _ := s.charges.Get(ctx, c.ID); done != nil && done.Status == "succeeded" {
|
||||
done, err := s.charges.Get(ctx, c.ID)
|
||||
if err != nil {
|
||||
return nil, errors.Join(runErr, err)
|
||||
}
|
||||
if done == nil {
|
||||
return nil, errors.Join(runErr, fmt.Errorf("top-up charge %s is gone", c.ID))
|
||||
}
|
||||
switch done.Status {
|
||||
case "succeeded":
|
||||
return &TopUpResult{Status: "paid", Amount: amount}, nil
|
||||
case "pending":
|
||||
if runErr != nil {
|
||||
log.Warn().Err(runErr).Str("charge_id", c.ID.String()).Msg("top-up left for the sweep to finish")
|
||||
}
|
||||
return &TopUpResult{Status: "processing", Amount: amount}, nil
|
||||
}
|
||||
return &TopUpResult{Status: "processing", Amount: amount}, nil
|
||||
return nil, errors.Join(runErr, fmt.Errorf("top-up charge %s ended %s", c.ID, done.Status))
|
||||
}
|
||||
|
||||
// SetAutoReload saves automatic reload. Turning it on needs a saved card, and
|
||||
// starts a reload right away when the balance is already under the threshold.
|
||||
// starts a reload right away when the balance is already under the threshold;
|
||||
// turning it off cancels a reload still pending.
|
||||
func (s *Service) SetAutoReload(ctx context.Context, orgID uuid.UUID, enabled bool, threshold, amount, monthlyLimit models.Micro) (*models.AISpendSettings, error) {
|
||||
if enabled && s.card != nil {
|
||||
if _, pm, err := s.paymentMethod(ctx, orgID); err != nil {
|
||||
@@ -403,15 +486,17 @@ func (s *Service) SetAutoReload(ctx context.Context, orgID uuid.UUID, enabled bo
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if enabled {
|
||||
go func() {
|
||||
rctx, cancel := context.WithTimeout(context.Background(), opTimeout)
|
||||
defer cancel()
|
||||
if err := s.Reload(rctx, orgID); err != nil {
|
||||
log.Warn().Err(err).Str("org_id", orgID.String()).Msg("automatic reload after enabling failed")
|
||||
}
|
||||
}()
|
||||
if !enabled {
|
||||
s.cancelPendingReload(ctx, orgID)
|
||||
return out, nil
|
||||
}
|
||||
go func() {
|
||||
rctx, cancel := context.WithTimeout(context.Background(), opTimeout)
|
||||
defer cancel()
|
||||
if err := s.Reload(rctx, orgID); err != nil {
|
||||
log.Warn().Err(err).Str("org_id", orgID.String()).Msg("automatic reload after enabling failed")
|
||||
}
|
||||
}()
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -441,6 +526,11 @@ func (s *Service) sweep(ctx context.Context) {
|
||||
} else if n > 0 {
|
||||
log.Info().Int("count", n).Msg("balance sweep: refreshed annual allowances")
|
||||
}
|
||||
if n, err := s.charges.CloseLegacy(ctx, time.Now().Add(-legacyPendingFor), models.ChargeExpired); err != nil {
|
||||
log.Warn().Err(err).Msg("balance sweep: close legacy charges")
|
||||
} else if n > 0 {
|
||||
log.Info().Int64("count", n).Msg("balance sweep: closed legacy charges")
|
||||
}
|
||||
due, err := s.charges.Due(ctx, time.Now(), staleAfter, 50)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Msg("balance sweep: list due charges")
|
||||
|
||||
@@ -2,6 +2,7 @@ package balance
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -42,6 +43,10 @@ func (f *fakeSettings) Get(context.Context, uuid.UUID) (*models.AISpendSettings,
|
||||
return f.cfg, nil
|
||||
}
|
||||
func (f *fakeSettings) RearmNotices(context.Context, uuid.UUID) error { return nil }
|
||||
func (f *fakeSettings) UpsertAutoReload(_ context.Context, _ uuid.UUID, enabled bool, threshold, amount, limit models.Micro) (*models.AISpendSettings, error) {
|
||||
f.cfg.AutoReloadEnabled, f.cfg.AutoReloadThreshold, f.cfg.AutoReloadAmount, f.cfg.AutoReloadMonthlyMax = enabled, threshold, amount, limit
|
||||
return f.cfg, nil
|
||||
}
|
||||
func (f *fakeSettings) DisableAutoReload(_ context.Context, _ uuid.UUID, code string) (bool, error) {
|
||||
if !f.cfg.AutoReloadEnabled {
|
||||
return false, nil
|
||||
@@ -115,10 +120,15 @@ type fakeCard struct {
|
||||
results []stripe.SavedCardResult
|
||||
charged []models.Micro
|
||||
voided []string
|
||||
// fail answers every charge with this error, as a Stripe outage would.
|
||||
fail error
|
||||
}
|
||||
|
||||
func (f *fakeCard) ChargeSavedCard(_ context.Context, c *models.SavedCardCharge, _ int, _ bool) (*stripe.SavedCardResult, error) {
|
||||
f.charged = append(f.charged, c.Amount)
|
||||
if f.fail != nil {
|
||||
return nil, f.fail
|
||||
}
|
||||
r := f.results[0]
|
||||
f.results = f.results[1:]
|
||||
return &r, nil
|
||||
@@ -220,3 +230,88 @@ func TestReloadNearTheMonthlyLimitTakesWhatIsLeft(t *testing.T) {
|
||||
t.Fatalf("charged %v under the minimum top-up", card2.charged)
|
||||
}
|
||||
}
|
||||
|
||||
func onlyCharge(t *testing.T, ch *fakeCharges) *models.SavedCardCharge {
|
||||
t.Helper()
|
||||
if len(ch.rows) != 1 {
|
||||
t.Fatalf("charges = %d, want 1", len(ch.rows))
|
||||
}
|
||||
for _, c := range ch.rows {
|
||||
return c
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestTurningReloadOffCancelsTheSnoozedReload(t *testing.T) {
|
||||
s, _, _, ch, card, _ := newTestService(0, stripe.SavedCardResult{InvoiceID: "in_1", Declined: models.ReloadCardDeclined, Soft: true})
|
||||
org := uuid.New()
|
||||
if err := s.Reload(context.Background(), org); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := onlyCharge(t, ch)
|
||||
c.InvoiceID = "in_1"
|
||||
if _, err := s.SetAutoReload(context.Background(), org, false, credits.DefaultReloadThreshold, credits.DefaultReloadAmount, credits.DefaultReloadMonthlyLimit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.Status != "failed" || c.FailureCode != models.ChargeCanceled || len(card.voided) != 1 || card.voided[0] != "in_1" {
|
||||
t.Fatalf("charge = %+v, voided %v; want canceled with its invoice voided", c, card.voided)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDueReloadIsNotChargedOnceUnwanted(t *testing.T) {
|
||||
for name, change := range map[string]func(*fakeCredits, *fakeSettings){
|
||||
"reload off": func(_ *fakeCredits, st *fakeSettings) { st.cfg.AutoReloadEnabled = false },
|
||||
"balance over again": func(cr *fakeCredits, st *fakeSettings) { cr.balance = st.cfg.AutoReloadThreshold },
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
s, cr, st, ch, card, _ := newTestService(0, stripe.SavedCardResult{InvoiceID: "in_1", Declined: models.ReloadCardDeclined, Soft: true})
|
||||
org := uuid.New()
|
||||
if err := s.Reload(context.Background(), org); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := onlyCharge(t, ch)
|
||||
c.InvoiceID, c.RetryAt = "in_1", nil
|
||||
change(cr, st)
|
||||
// The sweep resuming the due retry.
|
||||
due := *c
|
||||
if err := s.run(context.Background(), &due, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(card.charged) != 1 || c.Status != "failed" || c.FailureCode != models.ChargeCanceled || len(card.voided) != 1 {
|
||||
t.Fatalf("charged %v, charge %+v, voided %v; want no second charge and a canceled reload", card.charged, c, card.voided)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTopUpThatStripeDidNotAnswerIsStillProcessing(t *testing.T) {
|
||||
s, cr, _, ch, card, _ := newTestService(0)
|
||||
card.fail = errors.New("stripe: connection reset")
|
||||
res, err := s.TopUp(context.Background(), uuid.New(), 25*models.MicroPerUSD)
|
||||
if err != nil || res.Status != "processing" {
|
||||
t.Fatalf("TopUp = %+v, %v; want processing", res, err)
|
||||
}
|
||||
if c := onlyCharge(t, ch); c.Status != "pending" || cr.balance != 0 {
|
||||
t.Fatalf("charge = %+v, balance %v; want pending for the sweep", c, cr.balance)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChargeStripeKeepsFailingIsFailedAfterMaxTries(t *testing.T) {
|
||||
s, _, st, ch, card, n := newTestService(0)
|
||||
card.fail = errors.New("stripe: 500")
|
||||
org := uuid.New()
|
||||
if err := s.Reload(context.Background(), org); err == nil {
|
||||
t.Fatal("a failed Stripe call returned no error")
|
||||
}
|
||||
c := onlyCharge(t, ch)
|
||||
for c.Status == "pending" && c.Tries < maxTries+2 {
|
||||
due := *c
|
||||
_ = s.run(context.Background(), &due, true)
|
||||
}
|
||||
if c.Status != "failed" || c.Tries != maxTries || c.FailureCode != models.ReloadUnavailable {
|
||||
t.Fatalf("charge = %+v; want failed as unavailable after %d tries", c, maxTries)
|
||||
}
|
||||
if st.cfg.AutoReloadEnabled || st.disabled != models.ReloadUnavailable || len(n.titles) != 1 {
|
||||
t.Fatalf("reload on = %v (%q), notices %v; want it off and billing told", st.cfg.AutoReloadEnabled, st.disabled, n.titles)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -366,7 +366,7 @@ var Tables = []Table{
|
||||
Scope: scopeOrgAlt,
|
||||
// Automatic reload charges a card on the source instance's Stripe
|
||||
// account, so it arrives off with no failure or notice history.
|
||||
ResetOnImport: []string{"auto_topup_enabled", "auto_reload_failure_code", "auto_reload_failed_at",
|
||||
ResetOnImport: []string{"auto_reload_enabled", "auto_topup_enabled", "auto_reload_failure_code", "auto_reload_failed_at",
|
||||
"low_balance_notified_at", "balance_out_notified_at"},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -29,6 +29,9 @@ const (
|
||||
purposeCardSetup = "card_setup"
|
||||
)
|
||||
|
||||
// metaActor names who opened a balance Checkout; never user_id, which the previous release reads as a subscription checkout.
|
||||
const metaActor = "actor_user_id"
|
||||
|
||||
// BalanceSettler is the slice of the balance service the webhook flow drives:
|
||||
// a saved-card charge's invoice was paid. Injected via WireBalance so this
|
||||
// package needs no import of it.
|
||||
@@ -257,7 +260,7 @@ func (s *stripeService) VoidChargeInvoice(ctx context.Context, invoiceID string)
|
||||
// form. The webhook grants the amount; nothing changes here.
|
||||
func (s *stripeService) CreateBalanceCheckout(ctx context.Context, userID, orgID uuid.UUID, amount models.Micro, successURL, cancelURL string) (*stripe.CheckoutSession, *errx.Error) {
|
||||
meta := map[string]string{
|
||||
"purpose": purposeBalanceCheckout, "user_id": userID.String(), "org_id": orgID.String(),
|
||||
"purpose": purposeBalanceCheckout, metaActor: userID.String(), "org_id": orgID.String(),
|
||||
"amount_micro": strconv.FormatInt(int64(amount), 10),
|
||||
}
|
||||
params := &stripe.CheckoutSessionParams{
|
||||
@@ -301,7 +304,7 @@ func (s *stripeService) CreateBalanceCheckout(ctx context.Context, userID, orgID
|
||||
|
||||
// CreateCardSetupCheckout opens Stripe Checkout to save a card without paying.
|
||||
func (s *stripeService) CreateCardSetupCheckout(ctx context.Context, userID, orgID uuid.UUID, successURL, cancelURL string) (*stripe.CheckoutSession, *errx.Error) {
|
||||
meta := map[string]string{"purpose": purposeCardSetup, "user_id": userID.String(), "org_id": orgID.String()}
|
||||
meta := map[string]string{"purpose": purposeCardSetup, metaActor: userID.String(), "org_id": orgID.String()}
|
||||
params := &stripe.CheckoutSessionParams{
|
||||
Params: stripe.Params{Context: ctx},
|
||||
Mode: stripe.String(string(stripe.CheckoutSessionModeSetup)),
|
||||
@@ -400,7 +403,7 @@ func (s *stripeService) fulfillBalanceCheckout(ctx context.Context, sess *stripe
|
||||
s.ensureDefaultPaymentMethod(ctx, sess.Customer, sess.PaymentIntent.PaymentMethod)
|
||||
}
|
||||
if s.audit != nil {
|
||||
actorID, _ := uuid.Parse(sess.Metadata["user_id"])
|
||||
actorID, _ := uuid.Parse(sess.Metadata[metaActor])
|
||||
s.audit.LogAction(ctx, orgID, actorID, models.AuditActionCreate, models.AuditEntityCreditPurchase, nil, "", "", nil, map[string]string{
|
||||
"amount_usd": strconv.FormatFloat(models.Micro(amount).USD(), 'f', 2, 64),
|
||||
})
|
||||
@@ -424,7 +427,7 @@ func (s *stripeService) fulfillCardSetup(ctx context.Context, sess *stripe.Check
|
||||
}
|
||||
}
|
||||
if s.audit != nil {
|
||||
actorID, _ := uuid.Parse(sess.Metadata["user_id"])
|
||||
actorID, _ := uuid.Parse(sess.Metadata[metaActor])
|
||||
s.audit.LogAction(ctx, orgID, actorID, models.AuditActionUpdate, models.AuditEntitySubscription, nil, "", "", nil, map[string]string{
|
||||
"payment_method": "saved",
|
||||
})
|
||||
|
||||
@@ -131,6 +131,9 @@ func TestBalanceCheckoutCollectsTaxAndSavesTheCard(t *testing.T) {
|
||||
if r.Form.Get("payment_intent_data[setup_future_usage]") != "off_session" || r.Form.Get("line_items[0][price_data][unit_amount]") != "2500" || r.Form.Get("metadata[amount_micro]") != "25000000" {
|
||||
t.Errorf("balance checkout does not save the card or charge the amount: %v", r.Form)
|
||||
}
|
||||
if r.Form.Has("metadata[user_id]") || r.Form.Get("metadata[actor_user_id]") == "" {
|
||||
t.Errorf("balance checkout session metadata must name the actor without user_id: %v", r.Form)
|
||||
}
|
||||
if customerID == "" && r.Form.Get("customer_creation") != "always" {
|
||||
t.Errorf("credit checkout will not save the new customer: %v", r.Form)
|
||||
}
|
||||
@@ -153,6 +156,23 @@ func TestBalanceCheckoutCollectsTaxAndSavesTheCard(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCardSetupCheckoutSessionCarriesNoUserID(t *testing.T) {
|
||||
stripeAt(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Form.Get("mode") != "setup" || r.Form.Has("metadata[user_id]") || r.Form.Get("metadata[actor_user_id]") == "" || r.Form.Get("metadata[purpose]") != purposeCardSetup {
|
||||
t.Errorf("card setup checkout session metadata: %v", r.Form)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"id":"cs_setup","url":"https://checkout.stripe.com/test"}`))
|
||||
})
|
||||
s := &stripeService{subRepo: &billingSubRepo{sub: &models.Subscription{StripeCustomerID: "cus_existing"}}}
|
||||
if _, xerr := s.CreateCardSetupCheckout(context.Background(), uuid.New(), uuid.New(), "https://example.com/success", "https://example.com/cancel"); xerr != nil {
|
||||
t.Fatal(xerr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPortalRejectsMissingCustomer(t *testing.T) {
|
||||
for _, customerID := range []string{"", " \t"} {
|
||||
url, err := (&stripeService{}).CreatePortalSession(context.Background(), customerID, "https://example.com")
|
||||
|
||||
@@ -31,6 +31,7 @@ ALTER TABLE org_ai_settings
|
||||
DROP COLUMN IF EXISTS member_limit_weekly_micro,
|
||||
DROP COLUMN IF EXISTS member_limit_monthly_micro,
|
||||
DROP COLUMN IF EXISTS low_balance_threshold_micro,
|
||||
DROP COLUMN IF EXISTS auto_reload_enabled,
|
||||
DROP COLUMN IF EXISTS auto_reload_threshold_micro,
|
||||
DROP COLUMN IF EXISTS auto_reload_amount_micro,
|
||||
DROP COLUMN IF EXISTS auto_reload_monthly_limit_micro,
|
||||
|
||||
@@ -123,6 +123,11 @@ UPDATE plans SET monthly_allowance_micro = CASE
|
||||
ELSE monthly_credits::bigint * legacy_credit_micro()
|
||||
END;
|
||||
|
||||
-- The previous release refills a monthly pool from monthly_credits, so it has
|
||||
-- to grant the same dollars.
|
||||
UPDATE plans SET monthly_credits = (monthly_allowance_micro / legacy_credit_micro())::integer
|
||||
WHERE monthly_credits::bigint * legacy_credit_micro() <> monthly_allowance_micro;
|
||||
|
||||
-- ------------------------------------------------------- spend settings
|
||||
|
||||
ALTER TABLE org_ai_settings
|
||||
@@ -133,6 +138,7 @@ ALTER TABLE org_ai_settings
|
||||
ADD COLUMN IF NOT EXISTS member_limit_weekly_micro bigint CHECK (member_limit_weekly_micro IS NULL OR member_limit_weekly_micro > 0),
|
||||
ADD COLUMN IF NOT EXISTS member_limit_monthly_micro bigint CHECK (member_limit_monthly_micro IS NULL OR member_limit_monthly_micro > 0),
|
||||
ADD COLUMN IF NOT EXISTS low_balance_threshold_micro bigint NOT NULL DEFAULT 500000 CHECK (low_balance_threshold_micro >= 0),
|
||||
ADD COLUMN IF NOT EXISTS auto_reload_enabled boolean NOT NULL DEFAULT false,
|
||||
ADD COLUMN IF NOT EXISTS auto_reload_threshold_micro bigint NOT NULL DEFAULT 5000000
|
||||
CHECK (auto_reload_threshold_micro BETWEEN 10000 AND 1000000000),
|
||||
ADD COLUMN IF NOT EXISTS auto_reload_amount_micro bigint NOT NULL DEFAULT 25000000
|
||||
@@ -164,8 +170,12 @@ UPDATE org_ai_settings SET
|
||||
|
||||
-- An existing pack-based auto top-up keeps its shape: the pack becomes the
|
||||
-- reload amount, the credit threshold the dollar one, and the monthly count
|
||||
-- times the amount the monthly limit.
|
||||
-- times the amount the monthly limit. It moves to auto_reload_enabled, and the
|
||||
-- legacy switch goes off, so the previous release never charges a pack from
|
||||
-- a setting this release owns.
|
||||
UPDATE org_ai_settings SET
|
||||
auto_reload_enabled = true,
|
||||
auto_topup_enabled = false,
|
||||
auto_reload_amount_micro = GREATEST(CASE auto_topup_pack
|
||||
WHEN 'pack_2000' THEN 2000 WHEN 'pack_10000' THEN 10000 ELSE 500 END::bigint * legacy_credit_micro(), 5000000),
|
||||
auto_reload_threshold_micro = LEAST(GREATEST(auto_topup_threshold::bigint * legacy_credit_micro(), 10000),
|
||||
|
||||
@@ -118,6 +118,14 @@ const (
|
||||
ReloadUnavailable = "unavailable"
|
||||
)
|
||||
|
||||
// Failure codes only a charge row carries, never the settings row.
|
||||
const (
|
||||
// ChargeCanceled closes an automatic reload no longer wanted: reload off or the balance back over the threshold.
|
||||
ChargeCanceled = "canceled"
|
||||
// ChargeExpired closes a credit-pack charge the previous release left pending.
|
||||
ChargeExpired = "expired"
|
||||
)
|
||||
|
||||
// AISpendSettings is an org's spend-control row: optional spend limits per
|
||||
// calendar day, ISO week and calendar month for the workspace and for each
|
||||
// member (nil = no limit), the low-balance notice threshold, and automatic
|
||||
|
||||
@@ -99,6 +99,25 @@ func TestLiveBalanceChargesAndAutoReload(t *testing.T) {
|
||||
if cfg, _ := settings.UpsertAutoReload(ctx, orgID, true, 5*models.MicroPerUSD, 25*models.MicroPerUSD, 250*models.MicroPerUSD); cfg.AutoReloadFailureCode != "" {
|
||||
t.Fatal("turning reload back on kept the failure")
|
||||
}
|
||||
// The previous release's switch stays off whatever this release saves.
|
||||
var legacyOn bool
|
||||
if err := pool.QueryRow(ctx, `SELECT auto_topup_enabled FROM org_ai_settings WHERE org_id = $1`, orgID).Scan(&legacyOn); err != nil || legacyOn {
|
||||
t.Fatalf("auto_topup_enabled = %v, %v; want false", legacyOn, err)
|
||||
}
|
||||
|
||||
// A pack charge the previous release left pending frees the slot after a day.
|
||||
exec(`INSERT INTO credit_auto_topup_attempts (organization_id, pack_key, credits, created_at) VALUES ($1, 'pack_500', 500, now() - interval '25 hours')`, orgID)
|
||||
if n, err := charges.CloseLegacy(ctx, time.Now().Add(-24*time.Hour), models.ChargeExpired); err != nil || n < 1 {
|
||||
t.Fatalf("CloseLegacy = %d, %v", n, err)
|
||||
}
|
||||
if p, _ := charges.Pending(ctx, orgID); p != nil {
|
||||
t.Fatalf("a day-old legacy charge still holds the slot: %+v", p)
|
||||
}
|
||||
exec(`INSERT INTO credit_auto_topup_attempts (organization_id, pack_key, credits) VALUES ($1, 'pack_500', 500)`, orgID)
|
||||
_, _ = charges.CloseLegacy(ctx, time.Now().Add(-24*time.Hour), models.ChargeExpired)
|
||||
if p, _ := charges.Pending(ctx, orgID); p == nil || !p.Legacy {
|
||||
t.Fatal("a fresh legacy charge was closed")
|
||||
}
|
||||
}
|
||||
|
||||
func dueHasOrg(ids []uuid.UUID, id uuid.UUID) bool {
|
||||
|
||||
@@ -53,7 +53,7 @@ func NewAISettingsRepository(database *db.DB) AISettingsRepository {
|
||||
const aiSettingsCols = `org_id, spend_limit_daily_micro, spend_limit_weekly_micro, spend_limit_monthly_micro,
|
||||
member_limit_daily_micro, member_limit_weekly_micro, member_limit_monthly_micro,
|
||||
low_balance_threshold_micro, low_balance_notified_at, balance_out_notified_at,
|
||||
auto_topup_enabled, auto_reload_threshold_micro, auto_reload_amount_micro, auto_reload_monthly_limit_micro,
|
||||
auto_reload_enabled, auto_reload_threshold_micro, auto_reload_amount_micro, auto_reload_monthly_limit_micro,
|
||||
COALESCE(auto_reload_failure_code, ''), auto_reload_failed_at, created_at, updated_at`
|
||||
|
||||
func scanAISettings(row pgx.Row, s *models.AISpendSettings) error {
|
||||
@@ -104,15 +104,15 @@ func (r *aiSettingsRepository) UpsertLimits(ctx context.Context, in *models.AISp
|
||||
func (r *aiSettingsRepository) UpsertAutoReload(ctx context.Context, orgID uuid.UUID, enabled bool, threshold, amount, monthlyLimit models.Micro) (*models.AISpendSettings, error) {
|
||||
return r.one(ctx, `
|
||||
INSERT INTO org_ai_settings
|
||||
(org_id, auto_topup_enabled, auto_reload_threshold_micro, auto_reload_amount_micro, auto_reload_monthly_limit_micro)
|
||||
(org_id, auto_reload_enabled, auto_reload_threshold_micro, auto_reload_amount_micro, auto_reload_monthly_limit_micro)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (org_id) DO UPDATE SET
|
||||
auto_topup_enabled = EXCLUDED.auto_topup_enabled,
|
||||
auto_reload_enabled = EXCLUDED.auto_reload_enabled,
|
||||
auto_reload_threshold_micro = EXCLUDED.auto_reload_threshold_micro,
|
||||
auto_reload_amount_micro = EXCLUDED.auto_reload_amount_micro,
|
||||
auto_reload_monthly_limit_micro = EXCLUDED.auto_reload_monthly_limit_micro,
|
||||
auto_reload_failure_code = CASE WHEN EXCLUDED.auto_topup_enabled THEN NULL ELSE org_ai_settings.auto_reload_failure_code END,
|
||||
auto_reload_failed_at = CASE WHEN EXCLUDED.auto_topup_enabled THEN NULL ELSE org_ai_settings.auto_reload_failed_at END,
|
||||
auto_reload_failure_code = CASE WHEN EXCLUDED.auto_reload_enabled THEN NULL ELSE org_ai_settings.auto_reload_failure_code END,
|
||||
auto_reload_failed_at = CASE WHEN EXCLUDED.auto_reload_enabled THEN NULL ELSE org_ai_settings.auto_reload_failed_at END,
|
||||
updated_at = now()
|
||||
RETURNING `+aiSettingsCols,
|
||||
orgID, enabled, threshold, amount, monthlyLimit)
|
||||
@@ -121,8 +121,8 @@ func (r *aiSettingsRepository) UpsertAutoReload(ctx context.Context, orgID uuid.
|
||||
func (r *aiSettingsRepository) DisableAutoReload(ctx context.Context, orgID uuid.UUID, failureCode string) (bool, error) {
|
||||
tag, err := r.DB.Exec(ctx, `
|
||||
UPDATE org_ai_settings
|
||||
SET auto_topup_enabled = false, auto_reload_failure_code = $2, auto_reload_failed_at = now(), updated_at = now()
|
||||
WHERE org_id = $1 AND auto_topup_enabled`, orgID, failureCode)
|
||||
SET auto_reload_enabled = false, auto_reload_failure_code = $2, auto_reload_failed_at = now(), updated_at = now()
|
||||
WHERE org_id = $1 AND auto_reload_enabled`, orgID, failureCode)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -157,7 +157,7 @@ func (r *aiSettingsRepository) AutoReloadDue(ctx context.Context, limit int) ([]
|
||||
SELECT s.org_id
|
||||
FROM org_ai_settings s
|
||||
JOIN credit_ledger l ON l.org_id = s.org_id
|
||||
WHERE s.auto_topup_enabled
|
||||
WHERE s.auto_reload_enabled
|
||||
AND l.balance_micro + l.purchased_micro < s.auto_reload_threshold_micro
|
||||
AND NOT EXISTS (SELECT 1 FROM credit_auto_topup_attempts a
|
||||
WHERE a.organization_id = s.org_id AND a.status = 'pending')
|
||||
|
||||
@@ -59,7 +59,7 @@ type CreditRepository interface {
|
||||
|
||||
// AnnualAllowancesDue lists active subscriptions billed over more than a
|
||||
// month, with their period start, plan allowance and last reset, so the
|
||||
// allowance can refresh every month in between invoices.
|
||||
// allowance can refresh every month in between invoices. Oldest reset first.
|
||||
AnnualAllowancesDue(ctx context.Context, limit int) ([]AnnualAllowance, error)
|
||||
|
||||
ListTransactions(ctx context.Context, orgID uuid.UUID, limit int) ([]models.CreditTransaction, error)
|
||||
@@ -612,6 +612,7 @@ func (r *creditRepository) AnnualAllowancesDue(ctx context.Context, limit int) (
|
||||
AND s.current_period_end - s.current_period_start > interval '35 days'
|
||||
AND p.monthly_allowance_micro > 0
|
||||
AND COALESCE(l.month_reset_at, 'epoch'::timestamptz) < now() - interval '27 days'
|
||||
ORDER BY COALESCE(l.month_reset_at, 'epoch'::timestamptz), s.organization_id
|
||||
LIMIT $1`, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -41,6 +41,9 @@ type SavedCardChargeRepository interface {
|
||||
// Due lists pending charges whose retry time has come or that have sat
|
||||
// untouched longer than staleAfter, oldest first.
|
||||
Due(ctx context.Context, now time.Time, staleAfter time.Duration, limit int) ([]models.SavedCardCharge, error)
|
||||
// CloseLegacy fails credit-pack charges the previous release started that
|
||||
// are still pending since before a time, so they stop holding the slot.
|
||||
CloseLegacy(ctx context.Context, createdBefore time.Time, failureCode string) (int64, error)
|
||||
// SettleLegacyPaymentIntent settles a credit-pack charge the previous
|
||||
// release started on a payment intent.
|
||||
SettleLegacyPaymentIntent(ctx context.Context, paymentIntentID string) error
|
||||
@@ -175,6 +178,16 @@ func (r *savedCardChargeRepository) Due(ctx context.Context, now time.Time, stal
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (r *savedCardChargeRepository) CloseLegacy(ctx context.Context, createdBefore time.Time, failureCode string) (int64, error) {
|
||||
tag, err := r.DB.Exec(ctx, `UPDATE credit_auto_topup_attempts
|
||||
SET status = 'failed', failure_code = $2, failure_message = $2, retry_at = NULL, completed_at = now(), updated_at = now()
|
||||
WHERE status = 'pending' AND pack_key <> 'usd' AND created_at < $1`, createdBefore, failureCode)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
}
|
||||
|
||||
func (r *savedCardChargeRepository) SettleLegacyPaymentIntent(ctx context.Context, paymentIntentID string) error {
|
||||
_, err := r.DB.Exec(ctx, `
|
||||
UPDATE credit_auto_topup_attempts
|
||||
|
||||
@@ -92,11 +92,13 @@ export function useTopUp() {
|
||||
},
|
||||
onSuccess: (r) => {
|
||||
if (!r) return;
|
||||
qc.setQueryData<Balance>(balanceQuery.queryKey, (prev) => (prev ? { ...prev, balance_usd: r.balance_usd } : prev));
|
||||
qc.setQueryData<Balance>(balanceQuery.queryKey, (prev) =>
|
||||
prev ? { ...prev, balance_usd: r.balance_usd, charge_in_progress: r.charge_in_progress } : prev,
|
||||
);
|
||||
void qc.invalidateQueries({ queryKey: ["subscription", "credits"] });
|
||||
void qc.invalidateQueries({ queryKey: balanceInvoicesQuery.queryKey });
|
||||
if (r.status === "paid") toast.success(`${fmtUsd(r.amount_usd)} added to the balance`);
|
||||
else toast.success("Payment received. The money appears in a moment.");
|
||||
else toast("Your payment is still going through. The balance updates when it lands.");
|
||||
},
|
||||
onError: (e: AppError) => {
|
||||
toast.dismiss("balance-checkout");
|
||||
|
||||
@@ -58,10 +58,12 @@ export interface AutoReloadPatch {
|
||||
monthly_limit_usd: number;
|
||||
}
|
||||
|
||||
/** 200 is "paid"; 202 is "processing", the payment still going through. */
|
||||
export interface TopUpResult {
|
||||
status: "paid" | "processing";
|
||||
amount_usd: number;
|
||||
balance_usd: number;
|
||||
charge_in_progress: boolean;
|
||||
}
|
||||
|
||||
export interface BalanceInvoice {
|
||||
|
||||
Reference in New Issue
Block a user