feat: add a 3% processing fee on top of every card payment into the workspace balance and the agency AI balance (one-click, Checkout, automatic reload and AI auto top-up), billed as its own invoice line with the balance credited the chosen amount, and show the fee and total in the add funds, auto top-up, store round-up and agency billing UI and docs

This commit is contained in:
Matthew Meszaros
2026-11-21 17:21:14 +01:00
parent 53e3caaee4
commit b8519ecff5
25 changed files with 208 additions and 89 deletions
@@ -2412,7 +2412,7 @@ The workspace balance in US dollars: the plan's monthly allowance plus money the
"failure_code": null,
"failed_at": null
},
"top_up": { "min_usd": 5, "max_usd": 5000, "presets_usd": [10, 25, 50, 100, 250], "default_usd": 25 },
"top_up": { "min_usd": 5, "max_usd": 5000, "presets_usd": [10, 25, 50, 100, 250], "default_usd": 25, "fee_bps": 300 },
"burn": {
"per_day_usd": 1.12,
"mailboxes_per_day_usd": 0.3,
@@ -2437,7 +2437,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 `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.
Charges the saved card now, billed as a Stripe invoice, and answers `200` with `{"status": "paid", "amount_usd": 25, "charged_usd": 25.75, "balance_usd": 46.4375, "charge_in_progress": false}`. The card is charged `amount_usd` plus the processing fee of `top_up.fee_bps` basis points (3%), rounded half up to the cent and billed as its own invoice line; `amount_usd` is what the balance gains and `charged_usd` what the card paid. 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 |
|--------|------|---------|
@@ -2449,7 +2449,7 @@ Charges the saved card now, billed as a Stripe invoice, and answers `200` with `
`POST /subscription/balance/checkout`
Takes the same `amount_usd` and returns `{"session_id": "cs_...", "checkout_url": "https://checkout.stripe.com/..."}`. Checkout saves the card for later one-click payments. The money is added when Stripe confirms the payment, in the webhook, exactly once.
Takes the same `amount_usd` and returns `{"session_id": "cs_...", "checkout_url": "https://checkout.stripe.com/..."}`. Checkout shows the amount and the 3% processing fee as two lines, and the balance gains `amount_usd`. Checkout saves the card for later one-click payments. The money is added when Stripe confirms the payment, in the webhook, exactly once.
#### Save or replace the card
@@ -2477,8 +2477,8 @@ No body. Returns `{"client_secret": "seti_..._secret_...", "publishable_key": "p
|-------|------|----------|-------------|
| `enabled` | boolean | yes | Turns automatic reload on or off. Turning it on needs a saved card and an active paid plan. |
| `threshold_usd` | number | yes | Reload when the balance falls below this, `0.01` to `1000`. |
| `amount_usd` | number | yes | What each reload adds, `5` to `5000`, more than `threshold_usd`. |
| `monthly_limit_usd` | number | yes | The most reloaded in a calendar month, at least `amount_usd` and at most `50000`. |
| `amount_usd` | number | yes | What each reload adds, `5` to `5000`, more than `threshold_usd`. Each reload charges it plus the 3% processing fee. |
| `monthly_limit_usd` | number | yes | The most reloaded in a calendar month (added to the balance, the fee not counted), at least `amount_usd` and at most `50000`. |
Answers with the body of `GET /subscription/balance`. Refusals: `422` `recharge_too_small` (the amount is not above the threshold), `422` `monthly_limit_too_small` (the limit is below one reload or above the maximum), `409` `payment_method_required`.
+3 -3
View File
@@ -153,8 +153,8 @@ When the pool runs low, buy a **top-up pack** under **Agency > Billing**: 50,000
| | Sends | Shared AI balance |
| --- | --- | --- |
| Tops up when | This few sends are left in the month (default 10,000) | Less than this is left (default $5) |
| Each top-up | One pack: 50,000 sends at your plan's pack price ($85 on Agency, $60 on Agency Pro) | The amount you choose, $5 to $5,000 (default $25), added dollar for dollar |
| Monthly limit | A number of top-ups, 1 to 20 (default 2) | A total you choose, at least one top-up (default $100) |
| Each top-up | One pack: 50,000 sends at your plan's pack price ($85 on Agency, $60 on Agency Pro) | The amount you choose, $5 to $5,000 (default $25), added dollar for dollar, charged with a 3% processing fee on top |
| Monthly limit | A number of top-ups, 1 to 20 (default 2) | A total added to the balance you choose, at least one top-up (default $100); the fee does not count toward it |
| Checked | Every ten minutes, and when you turn it on | Right after a client's AI use draws on the balance, every ten minutes, and when you turn it on |
Each top-up is charged to the card your plan is paid with and has its own invoice, with tax added where it applies. Owners and admins are told each time one happens. One top-up is made at a time and each is charged once, so the limit is never passed. The numbers are saved together with **Save changes**; nothing you type is acted on before that. If you are already below the new level when you save or turn it on, one top-up is charged right away. Once the month's limit is reached nothing more is charged: campaigns pause when sends run out, and AI features stop when the balance does, until the month renews or you add more yourself.
@@ -186,7 +186,7 @@ The included amount is the agency's, not each client's, so opening more workspac
- **Renewal.** The included amount refills every month on the day the agency's billing period started, on an annual plan too. What is left of it does not carry over. Money the agency bought never expires.
- **A cap per client.** Give a client an **AI cap** on the Clients page to hold it to part of the agency balance each period. A cap of `$0` keeps the client to its own balance. Select **No cap** to remove it. The cap counts only what the client spent from the agency balance, net of refunds, and starts over each period.
- **Add balance to a client.** **Add balance** in a client's row menu moves an amount, from $1 to $5,000, out of the agency balance into that workspace's own balance, where it stays and does not expire. It is refused when the agency balance holds less. Moving money asks you to confirm it is you, and does not count toward the client's AI cap.
- **Buy more.** **Agency > Billing > AI balance** adds money to the agency balance through checkout, dollar for dollar, from $5 to $5,000, while the agency has a plan. A purchase that is fully refunded leaves the balance, except for what was already spent.
- **Buy more.** **Agency > Billing > AI balance** adds money to the agency balance through checkout, dollar for dollar, from $5 to $5,000, while the agency has a plan. Each card payment into the AI balance adds a 3% processing fee on top, on its own invoice line, so adding $100 charges $103.00. The fee is not refunded: a purchase refunded for the amount added leaves the balance, except for what was already spent. Send packs carry no fee.
- **Refunds.** When a charge is refunded (a placement test that delivered nothing, for example), the agency's part goes back to the agency balance and the workspace's part to the workspace.
**Agency > Usage** shows the balance next to the send pool: the included amount and what is left of it, what was bought, what clients spent from it this period, what was moved to clients, and each client's spend against its cap. A client workspace's own billing page counts the agency balance as available, so it is not shown as out of balance while the agency can still pay.
+5 -3
View File
@@ -23,7 +23,7 @@ On **One-time**, pick **$10**, **$25**, **$50**, **$100** or **$250** ($25 is pi
<Step>
Select **Pay**. The saved card is charged and the money is added at once. With no saved card, or after **Change**, enter a card right in the dialog; it is saved for next time and becomes the card charged from then on, before anything is charged, with any check your bank asks for shown there. **Pay another way** finishes in Stripe Checkout instead.
Below the amount, the dialog shows the 3% processing fee and the total, and **Pay** names the total: adding $25 charges $25.75. Select **Pay**. The saved card is charged and the money is added at once. With no saved card, or after **Change**, enter a card right in the dialog; it is saved for next time and becomes the card charged from then on, before anything is charged, with any check your bank asks for shown there. **Pay another way** finishes in Stripe Checkout instead.
</Step>
@@ -153,6 +153,8 @@ 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** ($10 or the store's minimum card charge where the store is on), in whole cents. Adding money needs an active paid plan.
Every card payment into the balance adds a **3% processing fee** on top of the amount you add, rounded to the nearest cent, so the balance always grows by exactly the amount you chose: adding $100 charges $103.00. This covers one-click payments, Stripe Checkout and automatic reload. The fee is its own line on the invoice and receipt. It is not refunded, so a refund returns at most the amount that was added to the balance. [Store charges](/guides/buy-mailboxes/#paying) that pay an order carry no fee.
- **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.
- **A new card in the dialog.** With no saved card, or after **Change**, the card is entered in the dialog, saved and made the workspace's card before it is charged, so a replaced card is never the one billed. If your bank asks to confirm, the check opens in the page.
- **Pay another way.** With a saved card, opens Stripe Checkout for the amount, to pay with another card or method.
@@ -167,7 +169,7 @@ The card shown is the one on the workspace's Stripe billing account (brand and l
## Automatic reload
Automatic reload adds money on the saved card when the balance falls below a threshold, so AI never pauses for an empty balance. Turning it on needs a saved card and an active paid plan; turning it off never does, so a workspace whose plan lapsed can still switch it off. Set it on the **Auto top-up** tab of **Add funds**, which starts from the values below.
Automatic reload adds money on the saved card when the balance falls below a threshold, so AI never pauses for an empty balance. Each reload is charged with the 3% processing fee on top, so a $25 reload charges $25.75; the dialog shows both. Turning it on needs a saved card and an active paid plan; turning it off never does, so a workspace whose plan lapsed can still switch it off. Set it on the **Auto top-up** tab of **Add funds**, which starts from the values below.
| Setting | Default | Range |
|---------|---------|-------|
@@ -177,7 +179,7 @@ Automatic reload adds money on the saved card when the balance falls below a thr
Where the store is on, a first setup starts at next month's mailbox charge (at least $10) for the threshold, $100 for each reload and $500 a month, and each reload adds at least the store's minimum card charge.
The monthly limit counts every automatic reload in the calendar month. When less than a full reload is left under it, Warmbly adds what is left if that is at least $5, and otherwise waits for next month.
The monthly limit counts what automatic reload added to the balance in the calendar month, not the fee. When less than a full reload is left under it, Warmbly adds what is left if that is at least $5, and otherwise waits for next month.
When a reload is declined:
+1 -1
View File
@@ -225,7 +225,7 @@ The admin mailbox carries an **Admin** badge in its **Subscription** card, with
## Paying
Every store charge is automatic. The order is paid from money you added to the workspace balance, and when that does not cover it, Warmbly charges your saved card in the same step and adds that to the balance first. The card is charged at least $10 (or your automatic reload amount, when that is larger), so a $3 shortfall adds $10: $3 pays the order and $7 stays on the balance for the next charge. Fewer, larger card charges keep card fees down. Checkout shows this before you pay, for example **Adds $10.00 to your balance · $3.00 used now, $7.00 left**. You never need to top up the balance or turn on automatic reload first. When the balance covers the order, the summary says **Paid from your balance** with what is left, and no card is asked for. When it is short, a chip such as **Add $100 instead** rounds the card charge up to a larger amount, which then stays on the balance.
Every store charge is automatic. The order is paid from money you added to the workspace balance, and when that does not cover it, Warmbly charges your saved card in the same step and adds that to the balance first. The card is charged at least $10 (or your automatic reload amount, when that is larger), so a $3 shortfall adds $10: $3 pays the order and $7 stays on the balance for the next charge. Fewer, larger card charges keep card fees down. Checkout shows this before you pay, for example **Adds $10.00 to your balance · $3.00 used now, $7.00 left**. You never need to top up the balance or turn on automatic reload first. When the balance covers the order, the summary says **Paid from your balance** with what is left, and no card is asked for. When it is short, a chip such as **Add $100 instead** rounds the card charge up to a larger amount, which then stays on the balance. That is a balance top-up, so it carries the 3% processing fee and **Pay** shows the total with it; a store charge that only pays the order carries no fee. Automatic reload also adds the fee to each reload (see [balance and usage](/guides/ai-credits/#adding-money-and-your-saved-card)).
Store charges come only from money you added to the balance, or from your card. The monthly AI allowance your plan includes pays for AI usage and never for domains or mailboxes, so a workspace with allowance left and nothing added pays the store by card. Checkout shows the money you added as the balance it pays from. Without a saved card, the summary shows a card field: **Pay** saves the card for the monthly charges (running any 3-D Secure check your bank asks for in the page) and places the order in the same press. If the card field cannot load, for example when a browser extension blocks it, **Pay** takes you to Stripe's page to add the card, and when you come back the order is placed for you at the total you saw. If a price changed meanwhile, the new total is shown and waits for you to pay.
+2 -1
View File
@@ -156,6 +156,7 @@ func (h *Handler) GetBalance(c *gin.Context) {
"top_up": gin.H{
"min_usd": usd(credits.TopUpMin), "max_usd": usd(credits.TopUpMax),
"presets_usd": []int{10, 25, 50, 100, 250}, "default_usd": 25,
"fee_bps": models.TopUpFeeBasisPoints,
},
}
// What the workspace's agency balance would add, so the dashboard does not call a funded client out of balance.
@@ -316,7 +317,7 @@ func (h *Handler) TopUpBalance(c *gin.Context) {
status = http.StatusAccepted
}
c.JSON(status, gin.H{
"status": res.Status, "amount_usd": usd(res.Amount), "balance_usd": usd(bal),
"status": res.Status, "amount_usd": usd(res.Amount), "charged_usd": float64(res.ChargedCents) / 100, "balance_usd": usd(bal),
"charge_in_progress": res.Status != "paid",
})
}
+7 -14
View File
@@ -90,6 +90,7 @@ func (s *Service) aiBalance(ctx context.Context, a *models.Agency) (*models.Agen
Clients: []models.AgencyAIClient{},
TopUp: models.AgencyAITopUpInfo{
MinUSD: credits.TopUpMin.USD(), MaxUSD: credits.TopUpMax.USD(), PresetsUSD: aiTopUpPresets, DefaultUSD: 25,
FeeBps: models.TopUpFeeBasisPoints,
},
}
var spent, moved models.Micro
@@ -200,21 +201,13 @@ func (s *Service) AITopup(ctx context.Context, agencyID, actorID uuid.UUID, amou
metaPurpose: purposeAgencyAITopup, metaAgencyID: a.ID.String(), "user_id": actorID.String(),
"amount_cents": strconv.FormatInt(cents, 10),
}
fee, _ := models.TopUpCharge(cents)
meta["fee_cents"] = strconv.FormatInt(fee, 10)
params := &stripe.CheckoutSessionParams{
Params: stripe.Params{Context: ctx},
Mode: stripe.String(string(stripe.CheckoutSessionModePayment)),
InvoiceCreation: &stripe.CheckoutSessionInvoiceCreationParams{Enabled: stripe.Bool(true)},
LineItems: []*stripe.CheckoutSessionLineItemParams{{
Quantity: stripe.Int64(1),
PriceData: &stripe.CheckoutSessionLineItemPriceDataParams{
Currency: stripe.String("usd"),
UnitAmount: stripe.Int64(cents),
TaxBehavior: stripe.String(businesscheckout.TaxExclusive),
ProductData: &stripe.CheckoutSessionLineItemPriceDataProductDataParams{
Name: stripe.String("Agency AI balance"),
},
},
}},
Params: stripe.Params{Context: ctx},
Mode: stripe.String(string(stripe.CheckoutSessionModePayment)),
InvoiceCreation: &stripe.CheckoutSessionInvoiceCreationParams{Enabled: stripe.Bool(true)},
LineItems: businesscheckout.TopUpLineItems("Agency AI balance", cents),
PaymentIntentData: &stripe.CheckoutSessionPaymentIntentDataParams{Metadata: meta},
ClientReferenceID: stripe.String(a.ID.String()),
SuccessURL: stripe.String(successURL),
+24 -8
View File
@@ -53,8 +53,10 @@ type AutoTopup struct {
type chargeRequest struct {
ClaimID uuid.UUID
// InvoiceID is the invoice already made for it; empty until Saved has run.
InvoiceID string
Cents int64
InvoiceID string
Cents int64
// FeeCents is the processing fee charged on top of Cents, on its own line; 0 for a send pack.
FeeCents int64
Description string
Meta map[string]string
// Cancel closes an unpaid invoice without charging it.
@@ -372,14 +374,16 @@ func (s *Service) settleAutoTopup(ctx context.Context, a *models.Agency, c *mode
}
noCard := card == nil && !cancel
description := "Agency send pack: 50,000 sends (automatic top-up)"
var fee int64
if c.Kind == models.AgencyAutoTopupAI {
description = "Agency AI balance (automatic top-up)"
fee, _ = models.TopUpCharge(c.AmountCents)
}
res, err := charger.Charge(ctx, a, card, chargeRequest{
ClaimID: c.ID, InvoiceID: c.StripeInvoiceID, Cents: c.AmountCents, Description: description,
ClaimID: c.ID, InvoiceID: c.StripeInvoiceID, Cents: c.AmountCents, FeeCents: fee, Description: description,
Meta: map[string]string{
metaPurpose: purposeAgencyAutoTopup, metaAgencyID: a.ID.String(), "claim_id": c.ID.String(), "kind": string(c.Kind),
"sends": strconv.Itoa(c.Sends), "amount_cents": strconv.FormatInt(c.AmountCents, 10),
"sends": strconv.Itoa(c.Sends), "amount_cents": strconv.FormatInt(c.AmountCents, 10), "fee_cents": strconv.FormatInt(fee, 10),
},
Cancel: cancel || noCard,
Saved: func(invoiceID string) error {
@@ -625,15 +629,27 @@ func (c stripeCharger) Charge(ctx context.Context, a *models.Agency, card *Saved
}
return chargeResult{Cancelled: true}, nil
}
if inv.Total == 0 {
line := func(cents int64, description, key string) error {
item := &stripe.InvoiceItemParams{
Params: stripe.Params{Context: ctx}, Customer: a.StripeCustomerID, Invoice: stripe.String(inv.ID),
Amount: stripe.Int64(req.Cents), Currency: stripe.String("usd"), Description: stripe.String(req.Description),
Amount: stripe.Int64(cents), Currency: stripe.String("usd"), Description: stripe.String(description),
}
item.SetIdempotencyKey("agency-autotopup-" + req.ClaimID.String() + "-item")
if _, err := invoiceitem.New(item); err != nil {
item.SetIdempotencyKey("agency-autotopup-" + req.ClaimID.String() + key)
_, err := invoiceitem.New(item)
return err
}
// Whichever of the two lines a crash left out is added now.
total := inv.Total
if total == 0 {
if err := line(req.Cents, req.Description, "-item"); err != nil {
return chargeResult{}, fmt.Errorf("add invoice line: %w", err)
}
total = req.Cents
}
if req.FeeCents > 0 && total < req.Cents+req.FeeCents {
if err := line(req.Cents+req.FeeCents-total, models.TopUpFeeLabel, "-fee"); err != nil {
return chargeResult{}, fmt.Errorf("add fee line: %w", err)
}
}
fin := &stripe.InvoiceFinalizeInvoiceParams{Params: stripe.Params{Context: ctx}, AutoAdvance: stripe.Bool(false)}
if inv, err = invoice.FinalizeInvoice(inv.ID, fin); err != nil {
+6 -1
View File
@@ -641,7 +641,12 @@ func (s *Service) refundTopup(ctx context.Context, ch *stripe.Charge) (bool, *er
if ch.PaymentIntent == nil || ch.PaymentIntent.ID == "" {
return isTopup, nil
}
if !ch.Refunded && (ch.Amount == 0 || ch.AmountRefunded < ch.Amount) {
// The processing fee on an AI top-up is not refunded, so a refund of the amount added counts as full.
due := ch.Amount
if added, err := strconv.ParseInt(ch.Metadata["amount_cents"], 10, 64); err == nil && purpose != purposeAgencyTopup && added > 0 && added < due {
due = added
}
if !ch.Refunded && (ch.Amount == 0 || ch.AmountRefunded < due) {
return isTopup, nil
}
agencyID, found, err := s.repo.RefundTopup(ctx, ch.PaymentIntent.ID)
+15 -4
View File
@@ -208,7 +208,7 @@ func (s *Service) Reload(ctx context.Context, orgID uuid.UUID) error {
return nil
}
c, err := s.charges.Create(ctx, &models.SavedCardCharge{
OrgID: orgID, Kind: models.SavedCardAutoReload, Amount: amount, AmountCents: amount.Cents(),
OrgID: orgID, Kind: models.SavedCardAutoReload, Amount: amount, AmountCents: chargedCents(models.SavedCardAutoReload, amount),
Currency: "usd", CustomerID: customerID, PaymentMethodID: pm.ID,
})
if errors.Is(err, repository.ErrChargeInFlight) {
@@ -220,6 +220,15 @@ func (s *Service) Reload(ctx context.Context, orgID uuid.UUID) error {
return s.run(ctx, c, true)
}
// chargedCents is what a charge puts on the card: a balance top-up adds the processing fee, a store charge pays its order as priced.
func chargedCents(kind string, amount models.Micro) int64 {
if kind == models.SavedCardStore {
return amount.Cents()
}
_, total := models.TopUpCharge(amount.Cents())
return total
}
func (s *Service) paymentMethod(ctx context.Context, orgID uuid.UUID) (string, *stripe.PaymentMethodSummary, error) {
sub, err := s.subs.GetByOrganizationID(ctx, orgID)
if err != nil {
@@ -437,6 +446,8 @@ func (s *Service) changed(ctx context.Context, orgID uuid.UUID) {
type TopUpResult struct {
Status string
Amount models.Micro
// ChargedCents is what the card pays, the processing fee included.
ChargedCents int64
}
// TopUp charges the saved card now, with the buyer present. A refusal comes
@@ -488,7 +499,7 @@ func (s *Service) chargeCard(ctx context.Context, in *models.SavedCardCharge, of
if pm == nil {
return nil, ErrNoPaymentMethod
}
in.AmountCents, in.Currency, in.CustomerID, in.PaymentMethodID = in.Amount.Cents(), "usd", customerID, pm.ID
in.AmountCents, in.Currency, in.CustomerID, in.PaymentMethodID = chargedCents(in.Kind, in.Amount), "usd", customerID, pm.ID
c, err = s.charges.Create(ctx, in)
if errors.Is(err, ErrChargeInFlight) && s.supersedeSnoozedReload(ctx, in.OrgID) {
c, err = s.charges.Create(ctx, in)
@@ -513,12 +524,12 @@ func (s *Service) chargeCard(ctx context.Context, in *models.SavedCardCharge, of
}
switch done.Status {
case "succeeded":
return &TopUpResult{Status: "paid", Amount: done.Amount}, nil
return &TopUpResult{Status: "paid", Amount: done.Amount, ChargedCents: done.AmountCents}, nil
case "pending":
if runErr != nil {
log.Warn().Err(runErr).Str("charge_id", c.ID.String()).Msg("card charge left for the sweep to finish")
}
return &TopUpResult{Status: "processing", Amount: done.Amount}, nil
return &TopUpResult{Status: "processing", Amount: done.Amount, ChargedCents: done.AmountCents}, nil
case "failed":
// Final for its key, whatever ended it, so the caller moves on rather than waiting on it.
return nil, &DeclinedError{Code: chargeFailureCode(done.FailureCode)}
+29 -22
View File
@@ -153,6 +153,7 @@ func (s *stripeService) ChargeSavedCard(ctx context.Context, c *models.SavedCard
Metadata: map[string]string{
"purpose": purposeBalanceCharge, "org_id": c.OrgID.String(), "charge_id": c.ID.String(),
"kind": c.Kind, "amount_micro": strconv.FormatInt(int64(c.Amount), 10),
"fee_cents": strconv.FormatInt(max(c.AmountCents-c.Amount.Cents(), 0), 10),
},
}
params.SetIdempotencyKey(key + "-invoice")
@@ -175,19 +176,19 @@ func (s *stripeService) ChargeSavedCard(ctx context.Context, c *models.SavedCard
out.Declined = models.ReloadPaymentFailed
return out, nil
case stripe.InvoiceStatusDraft:
if inv.Total == 0 {
item := &stripe.InvoiceItemParams{
Params: stripe.Params{Context: ctx},
Customer: stripe.String(c.CustomerID),
Invoice: stripe.String(inv.ID),
Amount: stripe.Int64(c.AmountCents),
Currency: stripe.String(c.Currency),
Description: stripe.String(chargeDescription(c)),
}
item.SetIdempotencyKey(key + "-item")
if _, err := invoiceitem.New(item); err != nil {
// The amount and the processing fee are separate lines; whichever a crash left out is added now.
fee := max(c.AmountCents-c.Amount.Cents(), 0)
total := inv.Total
if total == 0 {
if err := addChargeLine(ctx, c, inv.ID, c.AmountCents-fee, chargeDescription(c), key+"-item"); err != nil {
return nil, fmt.Errorf("add charge line: %w", err)
}
total = c.AmountCents - fee
}
if fee > 0 && total < c.AmountCents {
if err := addChargeLine(ctx, c, inv.ID, c.AmountCents-total, models.TopUpFeeLabel, key+"-fee"); err != nil {
return nil, fmt.Errorf("add fee line: %w", err)
}
}
fin := &stripe.InvoiceFinalizeInvoiceParams{Params: stripe.Params{Context: ctx}, AutoAdvance: stripe.Bool(false)}
fin.SetIdempotencyKey(key + "-finalize")
@@ -218,6 +219,20 @@ func (s *stripeService) ChargeSavedCard(ctx context.Context, c *models.SavedCard
return nil, fmt.Errorf("pay charge invoice: %w", err)
}
func addChargeLine(ctx context.Context, c *models.SavedCardCharge, invoiceID string, cents int64, description, key string) error {
item := &stripe.InvoiceItemParams{
Params: stripe.Params{Context: ctx},
Customer: stripe.String(c.CustomerID),
Invoice: stripe.String(invoiceID),
Amount: stripe.Int64(cents),
Currency: stripe.String(c.Currency),
Description: stripe.String(description),
}
item.SetIdempotencyKey(key)
_, err := invoiceitem.New(item)
return err
}
func chargeDescription(c *models.SavedCardCharge) string {
if c.Kind == models.SavedCardStore && c.Description != "" {
return c.Description
@@ -276,21 +291,13 @@ func (s *stripeService) CreateBalanceCheckout(ctx context.Context, userID, orgID
"purpose": purposeBalanceCheckout, metaActor: userID.String(), "org_id": orgID.String(),
"amount_micro": strconv.FormatInt(int64(amount), 10),
}
fee, _ := models.TopUpCharge(amount.Cents())
meta["fee_cents"] = strconv.FormatInt(fee, 10)
params := &stripe.CheckoutSessionParams{
Params: stripe.Params{Context: ctx},
Mode: stripe.String(string(stripe.CheckoutSessionModePayment)),
InvoiceCreation: &stripe.CheckoutSessionInvoiceCreationParams{Enabled: stripe.Bool(true)},
LineItems: []*stripe.CheckoutSessionLineItemParams{{
Quantity: stripe.Int64(1),
PriceData: &stripe.CheckoutSessionLineItemPriceDataParams{
Currency: stripe.String("usd"),
UnitAmount: stripe.Int64(amount.Cents()),
TaxBehavior: stripe.String(businesscheckout.TaxExclusive),
ProductData: &stripe.CheckoutSessionLineItemPriceDataProductDataParams{
Name: stripe.String("Warmbly balance"),
},
},
}},
LineItems: businesscheckout.TopUpLineItems("Warmbly balance", amount.Cents()),
PaymentIntentData: &stripe.CheckoutSessionPaymentIntentDataParams{
SetupFutureUsage: stripe.String("off_session"),
Metadata: meta,
+2
View File
@@ -571,6 +571,8 @@ type AgencyAITopUpInfo struct {
MaxUSD float64 `json:"max_usd"`
PresetsUSD []int `json:"presets_usd"`
DefaultUSD int `json:"default_usd"`
// FeeBps is the card processing fee charged on top of the amount, in basis points.
FeeBps int `json:"fee_bps"`
}
// AgencyAITransfer is a move of agency balance into a client workspace's own balance.
+15
View File
@@ -40,3 +40,18 @@ func CreditsFromMicro(m Micro) int {
}
return int(m / LegacyCreditMicro)
}
// TopUpFeeBasisPoints is the processing fee a card payment into a balance adds on top of the amount added: 3%.
const TopUpFeeBasisPoints = 300
// TopUpFeeLabel is the fee's receipt line.
const TopUpFeeLabel = "Processing fee (3%)"
// TopUpCharge is what adding cents to a balance by card costs: the fee, rounded half up to the cent, and the total charged.
func TopUpCharge(cents int64) (fee, total int64) {
if cents <= 0 {
return 0, cents
}
fee = (cents*TopUpFeeBasisPoints + 5_000) / 10_000
return fee, cents + fee
}
@@ -2,7 +2,11 @@
// opens carries: it is sold to businesses, with taxes excluded.
package businesscheckout
import "github.com/stripe/stripe-go/v86"
import (
"github.com/stripe/stripe-go/v86"
"github.com/warmbly/warmbly/internal/models"
)
// Notice sits beside the pay button; it states the terms' business-only and tax clauses.
const Notice = "Warmbly is sold to businesses for business use only. Prices exclude taxes: where we do not charge tax, your business accounts for any tax due in its own country, for example under the reverse charge."
@@ -24,3 +28,23 @@ func Apply(p *stripe.CheckoutSessionParams) {
// TaxExclusive is the tax behaviour of every price built inside a Checkout.
const TaxExclusive = "exclusive"
// TopUpLineItems are a balance top-up's lines: the amount added, then the processing fee on its own line.
func TopUpLineItems(name string, cents int64) []*stripe.CheckoutSessionLineItemParams {
line := func(name string, cents int64) *stripe.CheckoutSessionLineItemParams {
return &stripe.CheckoutSessionLineItemParams{
Quantity: stripe.Int64(1),
PriceData: &stripe.CheckoutSessionLineItemPriceDataParams{
Currency: stripe.String("usd"),
UnitAmount: stripe.Int64(cents),
TaxBehavior: stripe.String(TaxExclusive),
ProductData: &stripe.CheckoutSessionLineItemPriceDataProductDataParams{Name: stripe.String(name)},
},
}
}
items := []*stripe.CheckoutSessionLineItemParams{line(name, cents)}
if fee, _ := models.TopUpCharge(cents); fee > 0 {
items = append(items, line(models.TopUpFeeLabel, fee))
}
return items
}
+9 -3
View File
@@ -25,7 +25,7 @@ import { formatNumber } from "@/components/app/agency/styles";
import ExtraSends from "@/components/app/agency/ExtraSends";
import { AIAutoTopup } from "@/components/app/agency/AutoTopup";
import { AGENCY_PLAN_FEATURES } from "@/components/app/agency/planFeatures";
import { fmtUsd, fmtUsdTrim, roundCents } from "@/lib/money";
import { TOP_UP_FEE_LABEL, fmtUsd, fmtUsdTrim, roundCents, topUpCharge } from "@/lib/money";
const STATUS_LABEL: Record<string, string> = {
active: "Active",
@@ -61,6 +61,7 @@ function BuyAIBalance({ agencyId, balance, canManage }: { agencyId: string; bala
const [amount, setAmount] = React.useState(balance.top_up.default_usd || 25);
const usd = roundCents(amount);
const valid = usd >= balance.top_up.min_usd && usd <= balance.top_up.max_usd;
const charge = topUpCharge(usd);
const buy = async () => {
if (!valid) return;
@@ -77,7 +78,7 @@ function BuyAIBalance({ agencyId, balance, canManage }: { agencyId: string; bala
<div className="flex-1 min-w-[220px]">
<div className="text-[12.5px] text-slate-900">{fmtUsd(balance.balance_usd)} left in the shared AI balance</div>
<div className="text-[11.5px] text-slate-500">
Dollar for dollar. Bought balance never expires and is spent after this period's {fmtUsd(balance.allowance_usd)}{" "}
Dollar for dollar, plus a 3% card processing fee. Bought balance never expires and is spent after this period's {fmtUsd(balance.allowance_usd)}{" "}
included with the plan.
</div>
</div>
@@ -115,10 +116,15 @@ function BuyAIBalance({ agencyId, balance, canManage }: { agencyId: string; bala
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" /> : <SparklesIcon className="w-3 h-3" />}
Buy AI balance
{valid ? `Pay ${fmtUsd(charge.totalUsd)}` : "Buy AI balance"}
</button>
</div>
)}
{canManage && valid && (
<p className="basis-full text-right text-[11px] text-slate-400 tabular-nums">
{TOP_UP_FEE_LABEL} {fmtUsd(charge.feeUsd)} · Charged {fmtUsd(charge.totalUsd)}
</p>
)}
{canManage && !valid && (
<p className="basis-full text-[11.5px] text-red-600">
Enter an amount from {fmtUsdTrim(balance.top_up.min_usd)} to {fmtUsdTrim(balance.top_up.max_usd)}.
@@ -136,7 +136,7 @@ describe("Billing > Balance", () => {
it("lets a lapsed workspace see and turn off its auto top-up", async () => {
api.updateAutoReload.mockImplementation(async (patch) => balance({ can_add_money: false, auto_reload: reload({ ...patch }) }));
await open(balance({ can_add_money: false, auto_reload: reload({ enabled: true }) }));
expect(screen.getByText(/Auto top-up adds \$25 when the balance drops below \$5\.00/)).toBeInTheDocument();
expect(screen.getByText(/Auto top-up adds \$25 \(charged \$25\.75 with the 3% processing fee\) when the balance drops below \$5\.00/)).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Change" }));
await screen.findByRole("dialog");
fireEvent.click(within(dialog()!).getByRole("switch", { name: "Auto top-up" }));
+6 -6
View File
@@ -17,7 +17,7 @@ import {
import type { AgencyAutoTopup } 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 { fmtUsd, fmtUsdTrim, topUpCharge } from "@/lib/money";
import { cn } from "@/lib/utils";
import { formatNumber } from "./styles";
@@ -320,7 +320,7 @@ export function AIAutoTopup({ agencyId, canManage }: { agencyId: string; canMana
name="Automatic top-up of AI balance"
summary={
data.enabled
? `When less than ${fmtUsdTrim(data.threshold_usd)} is left in the shared AI balance, we add ${fmtUsdTrim(data.amount_usd)} and charge your card. We stop once ${fmtUsdTrim(data.limit_usd)} has been added in a month.`
? `When less than ${fmtUsdTrim(data.threshold_usd)} is left in the shared AI balance, we add ${fmtUsdTrim(data.amount_usd)} and charge your card ${fmtUsd(topUpCharge(data.amount_usd).totalUsd)}, the 3% processing fee included. We stop once ${fmtUsdTrim(data.limit_usd)} has been added in a month.`
: `Turn this on and we add ${fmtUsdTrim(each)} of AI balance whenever it runs low, so AI features never stop for your clients. Until then you add balance yourself.`
}
enabled={data.enabled}
@@ -356,10 +356,10 @@ export function AIAutoTopup({ agencyId, canManage }: { agencyId: string; canMana
</Setting>
</div>
<Costs
each={fmtUsdTrim(each)}
eachNote="added to the shared AI balance, dollar for dollar"
most={fmtUsdTrim(times * each)}
mostNote={`up to ${times} ${times === 1 ? "top-up" : "top-ups"} of ${fmtUsdTrim(each)}, plus tax where it applies`}
each={fmtUsd(topUpCharge(each).totalUsd)}
eachNote={`${fmtUsdTrim(each)} added to the shared AI balance, plus the 3% processing fee`}
most={fmtUsd(times * topUpCharge(each).totalUsd)}
mostNote={`up to ${times} ${times === 1 ? "top-up" : "top-ups"} of ${fmtUsdTrim(each)} with the fee, plus tax where it applies`}
/>
</Panel>
);
@@ -20,7 +20,7 @@ import {
import type { Balance } from "@/lib/api/models/app/subscription/Credits";
import buildError from "@/lib/helper/buildError";
import { EASE, PRESS_SPRING } from "@/lib/buy/motion";
import { MAX_TOP_UP_USD, fmtUsd, fmtUsdTrim, roundCents } from "@/lib/money";
import { MAX_TOP_UP_USD, TOP_UP_FEE_LABEL, fmtUsd, fmtUsdTrim, roundCents, topUpCharge } from "@/lib/money";
import { cn } from "@/lib/utils";
import { RELOAD_FAILURE_COPY, expiresSoon, fmtClock, fmtDay, paymentMethodExpiry, paymentMethodLabel } from "./balanceModel";
import { DEFAULT_FUND_USD, FUND_STEP_USD, RELOAD_THRESHOLD_MIN_USD, clampFund, lastsDays, lastsLabel, type FundsPolicy } from "./funds";
@@ -271,6 +271,7 @@ function OneTime({ b, policy, canBuy, onBusy, onDone }: { b: Balance; policy: Fu
const inFlight = !!b.charge_in_progress;
const busy = saving || pay.isPending || checkout.isPending;
React.useEffect(() => onBusy(busy), [busy, onBusy]);
const { feeUsd, totalUsd } = topUpCharge(amount);
const reason = !canBuy
? "Adding funds needs an active paid plan."
@@ -359,12 +360,22 @@ function OneTime({ b, policy, canBuy, onBusy, onDone }: { b: Balance; policy: Fu
</p>
)}
<div className="mt-5 -mx-5 px-5 pt-4 border-t border-slate-100 flex items-baseline justify-between">
<div className="mt-5 -mx-5 px-5 pt-4 border-t border-slate-100 space-y-1 text-[12px] tabular-nums">
<div className="flex items-baseline justify-between text-slate-500">
<span>Added to balance</span>
<span className="text-slate-700">{fmtUsd(amount)}</span>
</div>
<div className="flex items-baseline justify-between text-slate-500">
<span>{TOP_UP_FEE_LABEL}</span>
<span className="text-slate-700">{fmtUsd(feeUsd)}</span>
</div>
</div>
<div className="mt-2 flex items-baseline justify-between">
<span className="text-[12.5px] text-slate-500">Total</span>
<span className="text-[22px] font-semibold tracking-[-0.02em] text-slate-900 tabular-nums">{fmtUsd(amount)}</span>
<span className="text-[22px] font-semibold tracking-[-0.02em] text-slate-900 tabular-nums">{fmtUsd(totalUsd)}</span>
</div>
<PrimaryButton busy={busy} blocked={!!reason} onClick={() => void submit()}>
{busy ? (saving && card.entering ? "Saving your card…" : "Paying…") : card.pm || card.inline ? `Pay ${fmtUsd(amount)}` : `Continue to pay ${fmtUsd(amount)}`}
{busy ? (saving && card.entering ? "Saving your card…" : "Paying…") : card.pm || card.inline ? `Pay ${fmtUsd(totalUsd)}` : `Continue to pay ${fmtUsd(totalUsd)}`}
</PrimaryButton>
{card.pm && !card.entering && (
<button
@@ -418,6 +429,7 @@ function AutoTopUp({
const [saving, setSaving] = React.useState(false);
const busy = saving || save.isPending || addCard.isPending;
React.useEffect(() => onBusy(busy), [busy, onBusy]);
const charge = topUpCharge(amount);
const needsCard = enabled && !card.pm;
// Only turning it on needs a paid plan; a lapsed workspace can always turn it off.
@@ -491,6 +503,11 @@ function AutoTopUp({
<AmountField id="auto-limit" label="At most a month" value={limit} onChange={setLimit} min={Math.max(minUsd, amount)} max={LIMIT_MAX} disabled={!enabled} />
</div>
</div>
{enabled && amount > 0 && (
<p className="mt-2 text-[11px] text-slate-400 tabular-nums">
{TOP_UP_FEE_LABEL} {fmtUsd(charge.feeUsd)} · Charged {fmtUsd(charge.totalUsd)} each top-up
</p>
)}
{bundle > 0 && enabled && (
<p className="mt-2 text-[11px] text-slate-400">Next month&apos;s mailboxes come to {fmtUsdTrim(bundle)}, so a threshold at or above it keeps them paid from the balance.</p>
)}
@@ -8,7 +8,7 @@ import { useStoreEnabled } from "@/lib/api/hooks/app/store/useStore";
import type { Balance } from "@/lib/api/models/app/subscription/Credits";
import { fmtMonthly } from "@/lib/buy/money";
import { HOVER_LIFT, PRESS_SPRING } from "@/lib/buy/motion";
import { fmtUsd, fmtUsdTrim } from "@/lib/money";
import { fmtUsd, fmtUsdTrim, topUpCharge } from "@/lib/money";
import { cn } from "@/lib/utils";
import { RELOAD_FAILURE_COPY, balanceAlert, expiresSoon, fmtClock, fmtDay, paymentMethodExpiry, paymentMethodLabel, reloadCovers } from "./balanceModel";
import type { FundsTab } from "./AddFundsDialog";
@@ -132,7 +132,7 @@ function BalanceCard({ b, canBuy, onAddFunds, onPaymentMethod }: { b: Balance; c
<RefreshCwIcon className="w-3 h-3 text-slate-400 shrink-0" />
<span className="min-w-0">
{ar.enabled
? `Auto top-up adds ${fmtUsdTrim(ar.amount_usd)} when the balance drops below ${fmtUsd(ar.threshold_usd)}, up to ${fmtUsdTrim(ar.monthly_limit_usd)} a month.`
? `Auto top-up adds ${fmtUsdTrim(ar.amount_usd)} (charged ${fmtUsd(topUpCharge(ar.amount_usd).totalUsd)} with the 3% processing fee) when the balance drops below ${fmtUsd(ar.threshold_usd)}, up to ${fmtUsdTrim(ar.monthly_limit_usd)} a month.`
: "Auto top-up is off."}{" "}
{(ar.enabled || canBuy) && (
<button type="button" onClick={() => onAddFunds("auto")} className="font-medium text-sky-700 hover:text-sky-900 transition-colors">
@@ -11,7 +11,7 @@ import useFeatureAccess from "@/hooks/useFeatureAccess";
import { useUpgradeDialog } from "@/hooks/context/upgrade";
import { useBalance, useBalanceCheckout, useTopUp } from "@/lib/api/hooks/app/subscription/useBalance";
import { onInsufficientBalance } from "@/lib/insufficientBalance";
import { DEFAULT_TOP_UP_USD, fmtUsd, fmtUsdTrim } from "@/lib/money";
import { DEFAULT_TOP_UP_USD, fmtUsd, fmtUsdTrim, topUpCharge } from "@/lib/money";
import { fmtDay, paymentMethodLabel } from "./balanceModel";
export default function InsufficientBalanceDialog() {
@@ -130,7 +130,7 @@ function DialogBody({ onClose }: { onClose: () => void }) {
className="h-7 px-3 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors disabled:opacity-60"
>
{busy ? <Loader2Icon className="w-3 h-3 animate-spin" /> : pm ? <CreditCardIcon className="w-3 h-3" /> : null}
{pm ? `Pay ${fmtUsdTrim(amount)} with ${paymentMethodLabel(pm)}` : `Add ${fmtUsdTrim(amount)}`}
{pm ? `Pay ${fmtUsd(topUpCharge(amount).totalUsd)} with ${paymentMethodLabel(pm)}` : `Add ${fmtUsdTrim(amount)}`}
</button>
</>
) : canManage && access.billing ? (
@@ -11,7 +11,7 @@ import type { QuoteLine, StoreStatus } from "@/lib/api/models/app/store/Store";
import { domainMailboxes, effectiveProvider, mailboxCount, type Cart, type PriceBook } from "@/lib/buy/cart";
import { autoReloadLine, balanceLine, monthlyLine, type PayStep } from "@/lib/buy/checkout";
import { fmtMicros, fmtMonthly, fmtYearly } from "@/lib/buy/money";
import { fmtUsdTrim } from "@/lib/money";
import { fmtUsd, fmtUsdTrim, topUpCharge } from "@/lib/money";
import { EASE, PRESS_SPRING } from "@/lib/buy/motion";
import { normalizePhone, REGISTRANT_LABELS, registrantProblems, type RegistrantField } from "@/lib/buy/registrant";
import { cn } from "@/lib/utils";
@@ -228,7 +228,9 @@ function SummaryBody({ cart, status, prices, checkout }: Props) {
: "border-slate-200 bg-white text-slate-600 hover:border-slate-300 hover:text-slate-900",
)}
>
{checkout.topUp.chosen !== null ? `Adding ${fmtUsdTrim(checkout.topUp.offer)} · Undo` : `Add ${fmtUsdTrim(checkout.topUp.offer)} instead`}
{checkout.topUp.chosen !== null
? `Adding ${fmtUsdTrim(checkout.topUp.offer)} + ${fmtUsd(topUpCharge(checkout.topUp.offer).feeUsd)} fee · Undo`
: `Add ${fmtUsdTrim(checkout.topUp.offer)} instead (+3% fee)`}
</button>
)}
{checkout.autoReload.view?.kind === "offer" ? (
+1 -1
View File
@@ -210,7 +210,7 @@ export function useCheckout({
});
const label = payLabel({
metered,
due: plan && plan.cardCharge > 0 ? plan.cardCharge : due,
due: plan && plan.cardCharge > 0 ? plan.cardCharge + (plan.topUpFee ?? 0) : due,
card: savedCard,
cardEntry: wantsCard ? cardEntry : "inline",
fromBalance: !!plan?.balanceCovers,
@@ -31,6 +31,8 @@ export interface TopUpBounds {
max_usd: number;
presets_usd: number[];
default_usd: number;
/** The card processing fee charged on top of the amount, in basis points; absent from an older backend. */
fee_bps?: number;
}
// GET /subscription/balance. With billing off only `unlimited: true` is sent.
+2 -2
View File
@@ -42,8 +42,8 @@ describe("checkout summary", () => {
const plan = paymentPlan(p, 0, 3_000_000);
expect(balanceLine(plan, 3_000_000)).toBe("Adds $10.00 to your balance · $3.00 used now, $7.00 left for next month");
expect(payLabel({ metered: true, due: plan.cardCharge, card: visa, cardEntry: "inline" })).toBe("Pay $10.00");
expect(autoReloadLine({ kind: "offer", amount: plan.autoReload!.amount })).toBe("Keep my balance topped up · adds $10.00 when it won't cover next month's mailboxes");
expect(autoReloadLine({ kind: "on", amount: 10_000_000, threshold: 3_000_000 })).toBe("Balance tops up by $10.00 when it falls below $3.00");
expect(autoReloadLine({ kind: "offer", amount: plan.autoReload!.amount })).toBe("Keep my balance topped up · adds $10.00 (+3% processing fee) when it won't cover next month's mailboxes");
expect(autoReloadLine({ kind: "on", amount: 10_000_000, threshold: 3_000_000 })).toBe("Balance tops up by $10.00 (+3% processing fee) when it falls below $3.00");
// Rounding the card charge up to a preset leaves the difference on the balance.
const rounded = withTopUp(plan, 100_000_000, 3_000_000);
expect(balanceLine(rounded, 3_000_000)).toBe("Adds $100.00 to your balance · $3.00 used now, $97.00 left for next month");
+7 -3
View File
@@ -1,5 +1,6 @@
// What the order summary says: the Pay button's label, why it cannot be pressed yet, and how the months after are paid.
import type { QuotePayment, StoreCard } from "@/lib/api/models/app/store/Store";
import { topUpCharge } from "@/lib/money";
import { cardLabel, fmtMicros, fmtMonthly } from "./money";
/** How a workspace with no saved card adds one: in the page with Stripe.js, or on Stripe's page when that cannot load. */
@@ -60,6 +61,8 @@ export function monthlyLine(monthly: number, metered: boolean, payer: MonthlyPay
export interface PaymentPlan {
/** What the card is charged today; 0 when the balance covers it. */
cardCharge: number;
/** The processing fee the card adds on a top-up the buyer chose, on top of cardCharge; absent otherwise. */
topUpFee?: number;
fromBalance: number;
/** The balance once the order is paid, or null while there is no total yet. */
balanceAfter: number | null;
@@ -91,7 +94,8 @@ export function paymentPlan(p: QuotePayment | undefined, balance: number, due: n
export function withTopUp(plan: PaymentPlan, topUpMicros: number, due: number | null): PaymentPlan {
if (due === null || topUpMicros <= plan.cardCharge) return plan;
const before = (plan.balanceAfter ?? 0) - plan.cardCharge + due;
return { ...plan, cardCharge: topUpMicros, balanceAfter: before + topUpMicros - due };
const fee = Math.round(topUpCharge(topUpMicros / 1_000_000).feeUsd * 1_000_000);
return { ...plan, cardCharge: topUpMicros, topUpFee: fee, balanceAfter: before + topUpMicros - due };
}
/** The one line under the total on how today is paid, or null when the card simply pays what is due. */
@@ -110,8 +114,8 @@ export type ReloadView = { kind: "on"; amount: number; threshold: number } | { k
/** What the automatic top-up already does, or what turning it on would. */
export function autoReloadLine(r: NonNullable<ReloadView>): string {
if (r.kind === "on") return `Balance tops up by ${fmtMicros(r.amount)} when it falls below ${fmtMicros(r.threshold)}`;
return `Keep my balance topped up · adds ${fmtMicros(r.amount)} when it won't cover next month's mailboxes`;
if (r.kind === "on") return `Balance tops up by ${fmtMicros(r.amount)} (+3% processing fee) when it falls below ${fmtMicros(r.threshold)}`;
return `Keep my balance topped up · adds ${fmtMicros(r.amount)} (+3% processing fee) when it won't cover next month's mailboxes`;
}
/** One thing the order still needs before it can be paid, ticked off as it is done. */
+12
View File
@@ -49,3 +49,15 @@ export function parseUsd(text: string): number | null {
export function roundCents(n: number): number {
return Math.round(n * 100) / 100;
}
/** A card payment into a balance adds a 3% processing fee on top of the amount added (models.TopUpFeeBasisPoints). */
export const TOP_UP_FEE_BPS = 300;
export const TOP_UP_FEE_LABEL = "Processing fee (3%)";
/** What adding an amount by card costs: the fee, rounded half up to the cent, and the total charged. */
export function topUpCharge(usd: number): { feeUsd: number; totalUsd: number } {
const cents = Math.round(usd * 100);
if (!(cents > 0)) return { feeUsd: 0, totalUsd: Math.max(0, cents) / 100 };
const fee = Math.floor((cents * TOP_UP_FEE_BPS + 5000) / 10000);
return { feeUsd: fee / 100, totalUsd: (cents + fee) / 100 };
}