providers: a key's typed balance may be in yuan and refill each month or week
tenacious_eagle_96548 asked, after v0.1.3281's typed balance, to type it
in RMB and to have it refill (e.g. $10 a month, on the 1st).
- A balance may be typed in yuan ("¥100", "100元", or a bare number while
Settings shows costs in CNY). What magpie counts spent stays in USD and
is turned into yuan at fx.Known(): the rate internal/fx last fetched
(cached 12h, fetched again in the background, never on a request).
fx.Known never returns fx.Fallback, so with no rate fetched and
something spent, what is left is unknown (left null; the card says
why), not a guess.
- An optional refill: monthly on day 1-31 (past a month's end, its last
day) or weekly on a weekday, at midnight in the user's local time.
Nothing is stored on a refill: the spend counts from the last boundary
after the balance was typed. Typing the amount again keeps the refill.
- GUI: the pill's menu gains Refills each month… (a day, in place),
Refills each week… (the app's menu of weekdays) and Never refills;
provider/keybalancerefill; keyownbalance takes currency cny. CLI:
magpie provider key-balance <id> <key> [usd|¥cny|off]
[--refill monthly[:day]|weekly[:mon…sun]|off]. Strings in zh, zh-TW,
ja, de. docs/subsystems/providers-accounts.md updated.
Run on mote at this tree (base origin/main 350599a0f):
- go test -tags nogui -count=1 -timeout 45m ./internal/fx ./internal/provider
./internal/cli ./internal/gui ./internal/usage: all ok (suite lock).
- GOOS=linux go vet -tags nogui ./... ok; GOOS=windows go vet ./... ok;
gofmt -l clean.
- key-own-balance.test.cjs 20/20 (chromium + webkit, en zh zh-TW ja de,
900 and 400px): yuan typed posts currency cny, monthly day (40
refused), weekly Friday, never. i18n-keys, i18n-en-no-cjk, old-webkit ok.
- Broken by hand, each red: Known returning Fallback
(TestKnownIsNeverAGuess); refill days taken in UTC
(TestTypedBalanceRefills, TestRefillDays); refill dropped on retype
(TestTypedBalanceRefills).
- Full GUI suite still running at push: 3502 ok, 6 red so far, none in a
file this touches: webkit By weight; webkit de 1100/420 Codex resets
used by themselves; chromium en named caller keys; chromium zh-TW 420
a key's several limits; webkit en gateway key held to its models.
They are run on origin/main next and filed if red there.
Not tried: a live rate fetch (tests stay offline), the real app window,
WebKitGTK.
Reported-by: tenacious_eagle_96548 (Discord)
This commit is contained in:
@@ -347,7 +347,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
|
||||
- An account's weight under `weight` routing is kept per account too (`AccountWeights`, by the account in lower case, 2–1000; one not in it weighs 1, and nothing sets one from the plan), as a key's is (`KeyAccount.Weight`), so a Max and a Pro account can share requests by how much more one allows (rubbzha on X). `SetAccountWeight` (GUI `provider/accountweight`, the chip beside each account in use in the editor while the routing is By weight; `magpie provider account-weight <id> [account [n|default]]`) sets it, `moveAccountSettings` carries it through a Copilot rename, and `withPicks` puts it on the accounts `All` gives, so the gateway's `keyWeight` reads it with no file read (`Provider.AccountWeight`).
|
||||
- A usage cap is kept per account (`AccountCaps`, 1–99) and, beside it, per window (`AccountWindowCaps`, by the account and the window's `capId`, its name in lower case: `WindowCapID`). A window's own share wins over the account's; 100 is no cap on that window. `CapsOf` gives both (`WindowCaps`), `CapHeld` and `capReached` judge each window by its own, and `SetWindowCap` (GUI `provider/windowcap`, `magpie provider account-cap <id> <account> --window <name>`) sets one; `SetWindowCaps` sets several at once, as the GUI's meter for a family of models (Antigravity's Gemini 3.1 Pro, High and Low) posts its models' windows in `windows`. An Antigravity pool's own windows ("Gemini · 7 days") are set aside for routing but capped (`WithCapped`, `capId` the pool's name and its own, as `LineName`): `allowanceOf` hangs each on its members' windows (`Limit.pool`), and `CapHeld` and `NearCap` count them through `capLimits`, so a cap on one holds that pool's models only (pluviophile714 on Discord, `TestPoolWindowCapHeld`). A config without window caps reads as before. How a pool ends at its caps is kept with the provider (plugins#349): `CapStop` answers 429 rather than going on to the fallbacks once every account in use is at its cap, and `CapCareful` reads usage again near a cap and holds an account whose usage can't be told (both off by default; within 5 points of its cap an account takes one turn at a time whatever they say, [gateway routing](gateway-routing.md); `SetCapStop`, `SetCapCareful`, GUI `provider/capstop` and `provider/capcareful`, ticks under the account list once an account has a cap). `UsageRead` says when an account's usage was last read well and whether the last try failed (a failed try keeps the good reading's time), and `ReadUsageNow` reads it again. `magpie provider pool <id> [--accounts a,b,…] [--cap percent|off] [--stop on|off] [--careful on|off]` shows and sets the whole pool in one command: which accounts are on and in what order, each one's cap, and both settings, and names the accounts in use with no cap.
|
||||
- A key's spend cap (`KeySpendCaps`, by the key's fingerprint, [`key_spend.go`](../../internal/provider/key_spend.go); sparkling_lemur_62868 on Discord: a team's OpenAI key whose granted credits other services spend from too) is how much magpie may spend on an API key, in USD, per calendar day or month in local time, or in all since it was set (`Since`, kept while the cap stays one in all, its amount changed or not). What counts is what the Usage page prices magpie's own calls on the key at (`usage.KeySpent`: records whose `ProviderKeyID` is the key, not turned away, not reported by an app; the log is read once and each new call added by `Append`, read again after 5 minutes), not the vendor's bill: a model with no known price counts nothing, and requests under way when it is reached still finish, so the key can go a little past it. At or past the cap the gateway passes the key over ([gateway routing](gateway-routing.md)). Only a key has one: `SetKeySpendCap` refuses a subscription, an amount not above 0 or over `MaxSpendCap` (1,000,000) and a period it doesn't know. `ReplaceKey` carries it to the new value. Set from the key's row in the editor (a pill: "$7.50 of $20.00 today", the app's menu, then the amount typed in place, drawn by `keyspend.js`, which app.js imports when it draws a key's row; GUI `provider/keyspendcap`, `key-spend-cap.test.cjs`) or `magpie provider spend-cap <id> [key [usd [day|month|total]|off]]`, which also lists each key's spend. `TestKeySpendCapSet`, `TestSpendCapWindow`, `TestParseSpendCap`, `TestKeySpentCountsTheKeysCalls`, `TestSpendCapCmd`.
|
||||
- A key's balance typed by hand (`KeyOwnBalances`, by the key's fingerprint: `{usd, at}`, [`key_balance_own.go`](../../internal/provider/key_balance_own.go); tenacious_eagle on Discord) is for a key whose vendor tells no balance magpie can read (`TakesOwnBalance`: an API key with no balance source, not Cline's or OpenCode Zen's, not on a plan's windows). The user types what the vendor's page says is left; the key's card on the Usage page and the tray then shows it less what the Usage page prices magpie's own calls on the key at since then (`usage.KeySpent` from `at`, through the `provider.KeySpent` hook usage sets), as `≈$12.50` with `Estimate` (`set`, `at`, `spent`) and below nothing as `≈$-2.00`. Typing it again counts from then. It is an estimate, not a reading: it is kept out of the balance history (no trend or runs-out), is never shared, and routing reads nothing from it; a low-balance alert reads its number. A balance the vendor tells always wins: with a Balance URL or a source magpie knows the card is the vendor's, and a relay whose query is looked for shows the typed one only when none is found (`errNoBalance`); the typed value stays saved as the user left it. `SetKeyOwnBalance` (GUI `provider/keyownbalance`, a pill in the key's row, "≈$12.50 left" or "Set balance", drawn by `keybalance.js` while `takesOwnBalance` and no balance was found; `magpie provider key-balance <id> [key [usd|off]]`) refuses a subscription and an amount outside 0 to `MaxOwnBalance` (1,000,000); nil takes it off, `ReplaceKey` carries it to the new value, and saving the editor keeps it. Each key with one gets `balance` in `/api/providers`' `keyList`. `TestTypedBalanceCountsDown`, `TestToldBalanceWinsOverTyped`, `TestOwnBalanceParsed`, `TestKeyOwnBalanceRoutes`, `key-own-balance.test.cjs`.
|
||||
- A key's balance typed by hand (`KeyOwnBalances`, by the key's fingerprint: `{usd | cny, at, refill}`, [`key_balance_own.go`](../../internal/provider/key_balance_own.go); tenacious_eagle on Discord) is for a key whose vendor tells no balance magpie can read (`TakesOwnBalance`: an API key with no balance source, not Cline's or OpenCode Zen's, not on a plan's windows). The user types what the vendor's page says is left; the key's card on the Usage page and the tray then shows it less what the Usage page prices magpie's own calls on the key at since then (`usage.KeySpent` from `at`, through the `provider.KeySpent` hook usage sets), as `≈$12.50` with `Estimate` (`set`, `at`, `spent`) and below nothing as `≈$-2.00`. Typing it again counts from then. It is an estimate, not a reading: it is kept out of the balance history (no trend or runs-out), is never shared, and routing reads nothing from it; a low-balance alert reads its number. A balance the vendor tells always wins: with a Balance URL or a source magpie knows the card is the vendor's, and a relay whose query is looked for shows the typed one only when none is found (`errNoBalance`); the typed value stays saved as the user left it. `SetKeyOwnBalance` (GUI `provider/keyownbalance`, a pill in the key's row, "≈$12.50 left" or "Set balance", drawn by `keybalance.js` while `takesOwnBalance` and no balance was found; `magpie provider key-balance <id> [key [usd|¥cny|off] [--refill …]]`) refuses a subscription, an amount outside 0 to `MaxOwnBalance` (1,000,000) in either currency, and any currency but USD and CNY; nil takes it off, `ReplaceKey` carries it to the new value, and saving the editor keeps it. It may be typed in yuan (`cny`, "¥100", or a bare number while Settings shows costs in CNY): what is spent is counted in USD and turned into yuan at `fx.Known()`, the rate `internal/fx` last fetched (cached 12h in `fxrate.json`, fetched again in the background, never on the request path); `fx.Known` never hands out `fx.Fallback`, so with no rate fetched yet and something spent the left is unknown (`left` null, the card's `Error` says why) rather than a guess. It may refill (`refill`: `{every: month, day: 1–31}`, a day past the month's end meaning its last, or `{every: week, day: 1 Monday–7 Sunday}`), at midnight in the user's local time: nothing is stored on a refill; the spend is counted from the last refill boundary after `at` (`From`), and `Next` is the next one. Typing the amount again keeps the refill. `SetKeyBalanceRefill` (GUI `provider/keybalancerefill`, the pill's menu: Refills each month…, Refills each week…, Never refills; CLI `--refill monthly[:day]|weekly[:mon…sun]|off`) refuses a key with no balance. Each key with one gets `balance` in `/api/providers`' `keyList` (`set`, `at`, `spent`, `currency`, `rate`, `left`, `from`, `refill`, `next`). `TestKnownIsNeverAGuess`, `TestTypedBalanceInYuan`, `TestTypedBalanceRefills`, `TestRefillDays`, `TestTypedBalanceCountsDown`, `TestToldBalanceWinsOverTyped`, `TestOwnBalanceParsed`, `TestKeyOwnBalanceRoutes`, `key-own-balance.test.cjs`.
|
||||
- A window whose reset time has passed has started again, whatever share it was read at (`resetPassed`). That holds for a reading kept from before (`AsOf`) and for a fresh one: Claude Code's `/usage` gives a reset to the minute and can lag it, so a run just after a reset can still say 100% with that reset. `claudeWindows` hands such a window back empty on every path, and `usedPast`, `usedUp`, `BackAt` and `capReached` leave it out when they judge an account spent, for Codex, Claude Code and `magpie quota wait` alike. A card can still show a kept reading as it was read (`reported`, for a Claude card while `/usage` is unavailable); that changes what it shows, never which account is used. A reset `/usage` gives as a time alone ("resets 3pm") can be read as its next one, a day on (`claudeResetTime`), and is then not seen as passed here.
|
||||
- A restart to update can run two magpies for up to the old one's drain
|
||||
([GUI shell](gui-shell.md#a-restart-to-update-hands-the-gateway-over)), each
|
||||
|
||||
@@ -2,19 +2,39 @@ package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
stats "github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
const keyBalanceUsage = "magpie provider key-balance <id> [key [usd|off]]"
|
||||
const keyBalanceUsage = "magpie provider key-balance <id> [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|off]]"
|
||||
|
||||
// keyBalanceCmd shows, or sets, the balance typed by hand on a provider's
|
||||
// API keys whose vendor tells none (tenacious_eagle on Discord): what is
|
||||
// left of it is the amount less what magpie priced the key's calls at
|
||||
// since it was typed (provider/key_balance_own.go).
|
||||
func keyBalanceCmd(rest []string) error {
|
||||
if len(rest) < 1 || len(rest) > 3 {
|
||||
// since it was typed, or since it last refilled
|
||||
// (provider/key_balance_own.go). An amount in yuan ("¥100", "100cny") is
|
||||
// counted down at the dollar's rate magpie last learned.
|
||||
func keyBalanceCmd(args []string) error {
|
||||
var rest []string
|
||||
var refill *string
|
||||
for i := 0; i < len(args); i++ {
|
||||
a := args[i]
|
||||
switch {
|
||||
case a == "--refill" && i+1 < len(args):
|
||||
i++
|
||||
refill = &args[i]
|
||||
case strings.HasPrefix(a, "--refill="):
|
||||
v := strings.TrimPrefix(a, "--refill=")
|
||||
refill = &v
|
||||
case strings.HasPrefix(a, "-") && a != "-":
|
||||
// a flag magpie doesn't know, or a negative amount: never data
|
||||
return fmt.Errorf("%s", keyBalanceUsage)
|
||||
default:
|
||||
rest = append(rest, a)
|
||||
}
|
||||
}
|
||||
if len(rest) < 1 || len(rest) > 3 || (refill != nil && len(rest) < 2) {
|
||||
return fmt.Errorf("%s", keyBalanceUsage)
|
||||
}
|
||||
p, err := provider.Find(rest[0])
|
||||
@@ -24,14 +44,43 @@ func keyBalanceCmd(rest []string) error {
|
||||
if p.Account != nil {
|
||||
return fmt.Errorf("%s is a subscription: a balance typed by hand is for an API key", p.Name)
|
||||
}
|
||||
var r *provider.Refill
|
||||
if refill != nil {
|
||||
if r, err = provider.ParseRefill(*refill); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var b *provider.OwnBalance
|
||||
if len(rest) > 2 {
|
||||
usd, err := provider.ParseOwnBalance(rest[2])
|
||||
if err != nil {
|
||||
if b, err = provider.ParseOwnBalance(rest[2]); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := provider.SetKeyOwnBalance(p.ID, rest[1], usd); err != nil {
|
||||
if b == nil && refill != nil {
|
||||
return fmt.Errorf("%s", keyBalanceUsage)
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case b != nil:
|
||||
b.Refill = r
|
||||
if err := provider.SetKeyOwnBalance(p.ID, rest[1], b); err != nil {
|
||||
return err
|
||||
}
|
||||
// typed again with --refill off: it refills no more
|
||||
if refill != nil && r == nil {
|
||||
if err := provider.SetKeyBalanceRefill(p.ID, rest[1], nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case len(rest) > 2:
|
||||
if err := provider.SetKeyOwnBalance(p.ID, rest[1], nil); err != nil {
|
||||
return err
|
||||
}
|
||||
case refill != nil:
|
||||
if err := provider.SetKeyBalanceRefill(p.ID, rest[1], r); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(rest) > 2 || refill != nil {
|
||||
if p, err = provider.Find(p.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -61,13 +110,39 @@ func keyBalanceCmd(rest []string) error {
|
||||
if k.Name != "" {
|
||||
name = k.Name + " " + muted.Render(k.Masked+" · "+k.ID)
|
||||
}
|
||||
b, ok := p.KeyOwnBalance(k.ID)
|
||||
e, ok := p.OwnBalanceEstimate(k.ID)
|
||||
if !ok {
|
||||
fmt.Println(name, muted.Render("· no balance typed"))
|
||||
continue
|
||||
}
|
||||
spent := stats.KeySpent(k.ID, b.At)
|
||||
fmt.Printf("%s · about $%.2f left · $%.2f typed %s, $%.2f spent since\n", name, b.USD-spent, b.USD, b.At.Local().Format("Jan 2 15:04"), spent)
|
||||
fmt.Println(name, "·", keyBalanceLine(e))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// keyBalanceLine is what is left of a balance typed, as the CLI says it.
|
||||
func keyBalanceLine(e provider.BalanceEstimate) string {
|
||||
money := func(v float64) string {
|
||||
if e.Currency == "cny" {
|
||||
return fmt.Sprintf("¥%.2f", v)
|
||||
}
|
||||
return fmt.Sprintf("$%.2f", v)
|
||||
}
|
||||
left := "what is left can't be told yet: the dollar's rate in yuan isn't known"
|
||||
if e.Left != nil {
|
||||
left = "about " + money(*e.Left) + " left"
|
||||
}
|
||||
from := "typed " + e.At.Local().Format("Jan 2 15:04")
|
||||
if e.From.After(e.At) {
|
||||
from = "refilled " + e.From.Local().Format("Jan 2 15:04")
|
||||
}
|
||||
spent := fmt.Sprintf("$%.2f spent since", e.Spent)
|
||||
if e.Currency == "cny" && e.Rate > 0 {
|
||||
spent += fmt.Sprintf(" at ¥%.4g a dollar", e.Rate)
|
||||
}
|
||||
out := fmt.Sprintf("%s · %s %s, %s", left, money(e.Set), from, spent)
|
||||
if e.Refill != nil && e.Next != nil {
|
||||
out += " · refills " + e.Refill.String() + ", next " + e.Next.Local().Format("Jan 2")
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -46,6 +46,34 @@ func TestKeyBalanceCmd(t *testing.T) {
|
||||
if b, _ := typed(); b.USD != 1250.5 {
|
||||
t.Fatalf("a refused value changed the balance: %+v", b)
|
||||
}
|
||||
// in yuan, refilled on the 1st of each month; then weekly, the
|
||||
// amount kept; then refilling no more
|
||||
if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "¥700", "--refill", "monthly:1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := typed(); b.CNY == nil || *b.CNY != 700 || b.USD != 0 || b.Refill == nil || *b.Refill != (provider.Refill{Every: provider.RefillMonth, Day: 1}) {
|
||||
t.Fatalf("¥700 monthly:1: %+v", b)
|
||||
}
|
||||
if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--refill=weekly:fri"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := typed(); b.CNY == nil || *b.CNY != 700 || b.Refill == nil || *b.Refill != (provider.Refill{Every: provider.RefillWeek, Day: 5}) {
|
||||
t.Fatalf("weekly:fri: %+v", b)
|
||||
}
|
||||
for _, bad := range [][]string{{"relay", "Team", "--refill", "yearly"}, {"relay", "--refill", "monthly"}, {"relay", "Team", "off", "--refill", "monthly"}, {"relay", "Team", "--refill"}} {
|
||||
if err := providerCmd(append([]string{"provider", "key-balance"}, bad...)); err == nil {
|
||||
t.Fatalf("%v taken", bad)
|
||||
}
|
||||
}
|
||||
if b, _ := typed(); b.Refill == nil || b.Refill.Every != provider.RefillWeek {
|
||||
t.Fatalf("a refused refill changed it: %+v", b)
|
||||
}
|
||||
if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--refill", "off"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := typed(); b.Refill != nil || b.CNY == nil {
|
||||
t.Fatalf("refill off: %+v", b)
|
||||
}
|
||||
if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "off"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -98,9 +98,10 @@ const providerUsage = `usage:
|
||||
how much an API key may spend, in USD as the Usage page prices its calls,
|
||||
a day (the default), a month or in all from now: at it, routing takes the
|
||||
key for used up and goes on to the other keys and the fallbacks
|
||||
magpie provider key-balance <id> [key [usd|off]]
|
||||
the balance on an API key whose vendor tells none, typed from its own page:
|
||||
the Usage page shows it less what magpie prices the key's calls at since
|
||||
magpie provider key-balance <id> [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|off]]
|
||||
the balance on an API key whose vendor tells none, typed from its own page
|
||||
in USD or in yuan (¥100): the Usage page shows it less what magpie prices the
|
||||
key's calls at since; with --refill it is whole again each month or week
|
||||
magpie provider account-weight <id> [account [n|default]]
|
||||
a subscription account's share of the requests with routing=weight:
|
||||
one weighing 3 takes three for each one weighing 1 takes (default 1)
|
||||
|
||||
+16
-3
@@ -134,6 +134,18 @@ var refreshing sync.Mutex
|
||||
// else Fallback — and, when that is stale, Get behind it (one at a time),
|
||||
// for the next look to have.
|
||||
func Soon() Rate {
|
||||
r, ok := Known()
|
||||
if !ok {
|
||||
return Rate{CNYPerUSD: Fallback}
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// Known is Soon without Fallback: the rate last learned, however old,
|
||||
// and false when magpie has never learned one, for a sum that must not be
|
||||
// counted at a guessed rate (a key's balance typed in yuan). A stale or
|
||||
// missing rate is asked for behind it, as Soon does.
|
||||
func Known() (Rate, bool) {
|
||||
path := CachePath()
|
||||
mu.Lock()
|
||||
if mem == nil {
|
||||
@@ -141,8 +153,9 @@ func Soon() Rate {
|
||||
mem = &r
|
||||
}
|
||||
}
|
||||
r := Rate{CNYPerUSD: Fallback}
|
||||
if mem != nil {
|
||||
var r Rate
|
||||
ok := mem != nil
|
||||
if ok {
|
||||
r = *mem
|
||||
}
|
||||
mu.Unlock()
|
||||
@@ -154,7 +167,7 @@ func Soon() Rate {
|
||||
getAt(ctx, path)
|
||||
}()
|
||||
}
|
||||
return r
|
||||
return r, ok
|
||||
}
|
||||
|
||||
// Settle waits for a fetch Soon started to end; for tests, whose home goes
|
||||
|
||||
@@ -177,3 +177,42 @@ func TestGetDoesNotRetryAFailedFetchAtOnce(t *testing.T) {
|
||||
t.Fatalf("fetched %d times after retryAfter, want 2", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// Known never hands out Fallback: with no rate ever learned (no cache,
|
||||
// the fetch refused) it says so, and a failed fetch leaves it unknown,
|
||||
// never 0, 1 or the guess. A rate learned before, however old, is known,
|
||||
// and a fresh one asked for behind it.
|
||||
func TestKnownIsNeverAGuess(t *testing.T) {
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
Reset()
|
||||
t.Cleanup(Reset)
|
||||
refused := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "down", http.StatusBadGateway)
|
||||
}))
|
||||
defer refused.Close()
|
||||
defer SetRateURL(refused.URL)()
|
||||
|
||||
if r, ok := Known(); ok || r.CNYPerUSD != 0 {
|
||||
t.Fatalf("no rate ever learned: %+v %v, want unknown", r, ok)
|
||||
}
|
||||
Settle()
|
||||
if r, ok := Known(); ok || r.CNYPerUSD != 0 {
|
||||
t.Fatalf("after a failed fetch: %+v %v, want unknown", r, ok)
|
||||
}
|
||||
if r := Soon(); r.CNYPerUSD != Fallback {
|
||||
t.Fatalf("Soon still shows the guess, got %+v", r)
|
||||
}
|
||||
Settle()
|
||||
|
||||
// a stale rate in the cache is known, as it was learned
|
||||
Reset()
|
||||
old := Rate{CNYPerUSD: 7.1, At: time.Now().Add(-3 * TTL)}
|
||||
writeCache(CachePath(), old)
|
||||
if r, ok := Known(); !ok || r.CNYPerUSD != 7.1 {
|
||||
t.Fatalf("a stale rate learned before: %+v %v", r, ok)
|
||||
}
|
||||
Settle()
|
||||
if r, ok := Known(); !ok || r.CNYPerUSD != 7.1 {
|
||||
t.Fatalf("a failed refresh changed the known rate: %+v %v", r, ok)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,15 +36,27 @@ const I18N = {
|
||||
"Spend cap, in USD": "消费上限(美元)",
|
||||
"≈{usd} left": "≈{usd} 剩余",
|
||||
"Set balance": "设置余额",
|
||||
"An estimate: {set} typed {when}, less {spent} magpie counted spent on this key since, at the prices the Usage page shows. Click to type it again": "估算:{when} 填写的 {set},减去此后 magpie 按用量页价格算出的这个 key 已花费的 {spent}。点击重新填写",
|
||||
"An estimate: {set} from {when}, less {spent} magpie counted spent on this key since, at the prices the Usage page shows. Click to change": "估算:{when} 起的 {set},减去此后 magpie 按用量页价格算出的这个 key 已花费的 {spent}。点击修改",
|
||||
"Type what the vendor's page says this key has left, and magpie counts down from it as it sends requests": "填入服务商页面显示的这个 key 剩余余额,magpie 会随请求从中扣减",
|
||||
"{who} has no balance typed": "{who} 未填写余额",
|
||||
"{who} has {usd} left": "{who} 剩余 {usd}",
|
||||
"Balance, in USD": "余额(美元)",
|
||||
"A balance is an amount in USD from 0 to 1,000,000": "余额是 0 到 1,000,000 之间的美元金额",
|
||||
"A balance is an amount from 0 to 1,000,000, in USD or in yuan (¥)": "余额是 0 到 1,000,000 之间的金额,美元或人民币(¥)",
|
||||
"Enter balance…": "填写余额…",
|
||||
"Counts down from now": "从现在开始扣减",
|
||||
"No balance": "无余额",
|
||||
"Balance, in CNY": "余额(人民币)",
|
||||
"The dollar's rate in yuan isn't known yet, so what is left can't be counted": "还不知道美元兑人民币的汇率,暂时算不出剩余多少",
|
||||
"Refills to {set} on {when}": "{when} 恢复为 {set}",
|
||||
"Refills each month…": "每月恢复…",
|
||||
"Refills each week…": "每周恢复…",
|
||||
"Never refills": "不恢复",
|
||||
"Refills on": "恢复于",
|
||||
"Refill day of the month": "每月恢复的日期",
|
||||
"A day of the month is a whole number from 1 to 31": "每月的日期是 1 到 31 之间的整数",
|
||||
"{who} no longer refills": "{who} 不再恢复余额",
|
||||
"{who} refills each {weekday}": "{who} 每{weekday}恢复余额",
|
||||
"{who} refills on day {day} of each month": "{who} 每月 {day} 日恢复余额",
|
||||
"A spend cap is an amount in USD above 0, up to 1,000,000": "消费上限是大于 0、不超过 1,000,000 的美元金额",
|
||||
"Spend cap": "消费上限",
|
||||
"At its spend cap · back {in}": "已达消费上限 · {in}恢复",
|
||||
@@ -4741,15 +4753,27 @@ const I18N = {
|
||||
"Spend cap, in USD": "消費上限(美元)",
|
||||
"≈{usd} left": "≈{usd} 剩餘",
|
||||
"Set balance": "設定餘額",
|
||||
"An estimate: {set} typed {when}, less {spent} magpie counted spent on this key since, at the prices the Usage page shows. Click to type it again": "估算:{when} 填寫的 {set},減去此後 magpie 依用量頁價格算出的這個 key 已花費的 {spent}。點擊重新填寫",
|
||||
"An estimate: {set} from {when}, less {spent} magpie counted spent on this key since, at the prices the Usage page shows. Click to change": "估算:{when} 起的 {set},減去此後 magpie 依用量頁價格算出的這個 key 已花費的 {spent}。點擊修改",
|
||||
"Type what the vendor's page says this key has left, and magpie counts down from it as it sends requests": "填入服務商頁面顯示的這個 key 剩餘餘額,magpie 會隨請求從中扣減",
|
||||
"{who} has no balance typed": "{who} 未填寫餘額",
|
||||
"{who} has {usd} left": "{who} 剩餘 {usd}",
|
||||
"Balance, in USD": "餘額(美元)",
|
||||
"A balance is an amount in USD from 0 to 1,000,000": "餘額是 0 到 1,000,000 之間的美元金額",
|
||||
"A balance is an amount from 0 to 1,000,000, in USD or in yuan (¥)": "餘額是 0 到 1,000,000 之間的金額,美元或人民幣(¥)",
|
||||
"Enter balance…": "填寫餘額…",
|
||||
"Counts down from now": "從現在開始扣減",
|
||||
"No balance": "無餘額",
|
||||
"Balance, in CNY": "餘額(人民幣)",
|
||||
"The dollar's rate in yuan isn't known yet, so what is left can't be counted": "還不知道美元兌人民幣的匯率,暫時算不出剩餘多少",
|
||||
"Refills to {set} on {when}": "{when} 恢復為 {set}",
|
||||
"Refills each month…": "每月恢復…",
|
||||
"Refills each week…": "每週恢復…",
|
||||
"Never refills": "不恢復",
|
||||
"Refills on": "恢復於",
|
||||
"Refill day of the month": "每月恢復的日期",
|
||||
"A day of the month is a whole number from 1 to 31": "每月的日期是 1 到 31 之間的整數",
|
||||
"{who} no longer refills": "{who} 不再恢復餘額",
|
||||
"{who} refills each {weekday}": "{who} 每{weekday}恢復餘額",
|
||||
"{who} refills on day {day} of each month": "{who} 每月 {day} 日恢復餘額",
|
||||
"A spend cap is an amount in USD above 0, up to 1,000,000": "消費上限是大於 0、不超過 1,000,000 的美元金額",
|
||||
"Spend cap": "消費上限",
|
||||
"At its spend cap · back {in}": "已達消費上限 · {in}恢復",
|
||||
@@ -9431,15 +9455,27 @@ const I18N = {
|
||||
"Spend cap, in USD": "支出上限(USD)",
|
||||
"≈{usd} left": "残り ≈{usd}",
|
||||
"Set balance": "残高を設定",
|
||||
"An estimate: {set} typed {when}, less {spent} magpie counted spent on this key since, at the prices the Usage page shows. Click to type it again": "推定:{when} に入力した {set} から、その後 magpie が使用量ページの価格でこのキーに数えた支出 {spent} を引いた額。クリックで入力し直す",
|
||||
"An estimate: {set} from {when}, less {spent} magpie counted spent on this key since, at the prices the Usage page shows. Click to change": "推定:{when} 時点の {set} から、その後 magpie が使用量ページの価格でこのキーに数えた支出 {spent} を引いた額。クリックで変更",
|
||||
"Type what the vendor's page says this key has left, and magpie counts down from it as it sends requests": "ベンダーのページに表示されるこのキーの残高を入力すると、magpie がリクエストごとに差し引きます",
|
||||
"{who} has no balance typed": "{who} の残高は未入力",
|
||||
"{who} has {usd} left": "{who} の残り {usd}",
|
||||
"Balance, in USD": "残高(USD)",
|
||||
"A balance is an amount in USD from 0 to 1,000,000": "残高は 0 から 1,000,000 までの USD 金額です",
|
||||
"A balance is an amount from 0 to 1,000,000, in USD or in yuan (¥)": "残高は 0 から 1,000,000 までの金額です(USD または人民元 ¥)",
|
||||
"Enter balance…": "残高を入力…",
|
||||
"Counts down from now": "今から差し引く",
|
||||
"No balance": "残高なし",
|
||||
"Balance, in CNY": "残高(人民元)",
|
||||
"The dollar's rate in yuan isn't known yet, so what is left can't be counted": "ドルの人民元レートがまだ分からないため、残りを計算できません",
|
||||
"Refills to {set} on {when}": "{when} に {set} へ戻る",
|
||||
"Refills each month…": "毎月戻す…",
|
||||
"Refills each week…": "毎週戻す…",
|
||||
"Never refills": "戻さない",
|
||||
"Refills on": "戻す曜日",
|
||||
"Refill day of the month": "毎月戻す日",
|
||||
"A day of the month is a whole number from 1 to 31": "日付は 1 から 31 までの整数です",
|
||||
"{who} no longer refills": "{who} の残高はもう戻りません",
|
||||
"{who} refills each {weekday}": "{who} の残高は毎週{weekday}に戻ります",
|
||||
"{who} refills on day {day} of each month": "{who} の残高は毎月 {day} 日に戻ります",
|
||||
"A spend cap is an amount in USD above 0, up to 1,000,000": "支出上限は 0 より大きく 1,000,000 以下の USD 金額です",
|
||||
"Spend cap": "支出上限",
|
||||
"At its spend cap · back {in}": "支出上限に到達 · {in}に復帰",
|
||||
@@ -14123,15 +14159,27 @@ const I18N = {
|
||||
"Spend cap, in USD": "Ausgabenlimit in USD",
|
||||
"≈{usd} left": "≈{usd} übrig",
|
||||
"Set balance": "Guthaben festlegen",
|
||||
"An estimate: {set} typed {when}, less {spent} magpie counted spent on this key since, at the prices the Usage page shows. Click to type it again": "Geschätzt: {set}, eingegeben {when}, abzüglich {spent}, die magpie seitdem für diesen Schlüssel zu den Preisen der Nutzungsseite gezählt hat. Klicken, um es neu einzugeben",
|
||||
"An estimate: {set} from {when}, less {spent} magpie counted spent on this key since, at the prices the Usage page shows. Click to change": "Geschätzt: {set} ab {when}, abzüglich {spent}, die magpie seitdem für diesen Schlüssel zu den Preisen der Nutzungsseite gezählt hat. Klicken, um es zu ändern",
|
||||
"Type what the vendor's page says this key has left, and magpie counts down from it as it sends requests": "Gib ein, was die Seite des Anbieters für diesen Schlüssel als Guthaben zeigt, und magpie zählt davon mit jeder Anfrage herunter",
|
||||
"{who} has no balance typed": "{who} hat kein eingegebenes Guthaben",
|
||||
"{who} has {usd} left": "{who} hat noch {usd}",
|
||||
"Balance, in USD": "Guthaben in USD",
|
||||
"A balance is an amount in USD from 0 to 1,000,000": "Ein Guthaben ist ein Betrag in USD von 0 bis 1.000.000",
|
||||
"A balance is an amount from 0 to 1,000,000, in USD or in yuan (¥)": "Ein Guthaben ist ein Betrag von 0 bis 1.000.000, in USD oder in Yuan (¥)",
|
||||
"Enter balance…": "Guthaben eingeben…",
|
||||
"Counts down from now": "Zählt ab jetzt herunter",
|
||||
"No balance": "Kein Guthaben",
|
||||
"Balance, in CNY": "Guthaben in CNY",
|
||||
"The dollar's rate in yuan isn't known yet, so what is left can't be counted": "Der Dollarkurs in Yuan ist noch nicht bekannt, daher lässt sich der Rest nicht berechnen",
|
||||
"Refills to {set} on {when}": "Wird am {when} wieder auf {set} aufgefüllt",
|
||||
"Refills each month…": "Monatlich auffüllen…",
|
||||
"Refills each week…": "Wöchentlich auffüllen…",
|
||||
"Never refills": "Nie auffüllen",
|
||||
"Refills on": "Auffüllen am",
|
||||
"Refill day of the month": "Tag des Monats zum Auffüllen",
|
||||
"A day of the month is a whole number from 1 to 31": "Ein Tag des Monats ist eine ganze Zahl von 1 bis 31",
|
||||
"{who} no longer refills": "{who} wird nicht mehr aufgefüllt",
|
||||
"{who} refills each {weekday}": "{who} wird jeden {weekday} aufgefüllt",
|
||||
"{who} refills on day {day} of each month": "{who} wird am {day}. jedes Monats aufgefüllt",
|
||||
"A spend cap is an amount in USD above 0, up to 1,000,000": "Ein Ausgabenlimit ist ein Betrag in USD über 0, bis 1.000.000",
|
||||
"Spend cap": "Ausgabenlimit",
|
||||
"At its spend cap · back {in}": "Am Ausgabenlimit · zurück {in}",
|
||||
|
||||
@@ -2,30 +2,64 @@
|
||||
// whose vendor tells no balance magpie can read, the user types what the
|
||||
// vendor's page says is left, and magpie counts down from it by what its
|
||||
// own usage prices the calls it sends on the key (provider/
|
||||
// key_balance_own.go). Typing it again sets it anew. keyspend.js imports this
|
||||
// when the provider editor draws a key's row, so it weighs nothing on the
|
||||
// core.
|
||||
const usdText = (v) => (v < 0 ? "-$" : "$") + Math.abs(v).toFixed(2);
|
||||
// key_balance_own.go). Typing it again sets it anew. It may be typed in
|
||||
// yuan ("¥100", or a bare number while Settings shows costs in CNY), and
|
||||
// may refill each month or week. keyspend.js imports this when the
|
||||
// provider editor draws a key's row, so it weighs nothing on the core.
|
||||
const moneyText = (v, cny) => (v < 0 ? "-" : "") + (cny ? "¥" : "$") + Math.abs(v).toFixed(2);
|
||||
// balanceAmount reads what was typed: an amount and whether it is in
|
||||
// yuan, a sign or a word saying which, else unit; null for none
|
||||
function balanceAmount(s, unit) {
|
||||
let a = s.trim().toLowerCase(), cny = unit === "cny";
|
||||
const yuan = /^(¥|¥|cny|rmb)\s*|\s*(元|cny|rmb|yuan)$/g, usd = /^\$\s*|\s*usd$/g;
|
||||
if (yuan.test(a)) { a = a.replace(yuan, ""); cny = true; }
|
||||
else if (usd.test(a)) { a = a.replace(usd, ""); cny = false; }
|
||||
a = a.replace(/,/g, "").trim();
|
||||
const n = Number(a);
|
||||
return a && n >= 0 && n <= 1e6 ? { n, cny } : null;
|
||||
}
|
||||
const weekdayName = (d) => new Date(2026, 10, 1 + d).toLocaleDateString(intlLang(), { weekday: "long" }); // 2026-11-02 is a Monday
|
||||
function keyBalancePill(p, k) {
|
||||
const b = k.balance, name = k.name || k.masked;
|
||||
const b = k.balance, name = k.name || k.masked, cny = b?.currency === "cny";
|
||||
const pill = el("button", "abal" + (b ? " set" : ""));
|
||||
pill.type = "button";
|
||||
const left = b ? b.set - (b.spent || 0) : 0;
|
||||
pill.textContent = b ? t("≈{usd} left", { usd: usdText(left) }) : t("Set balance");
|
||||
pill.title = b ? t("An estimate: {set} typed {when}, less {spent} magpie counted spent on this key since, at the prices the Usage page shows. Click to type it again", { set: usdText(b.set), when: new Date(b.at).toLocaleString(intlLang()), spent: usdText(b.spent || 0) })
|
||||
: t("Type what the vendor's page says this key has left, and magpie counts down from it as it sends requests");
|
||||
const set = (usd) => accountAction("provider/keyownbalance", { id: p.id, account: k.id, balance: usd },
|
||||
usd == null ? t("{who} has no balance typed", { who: name }) : t("{who} has {usd} left", { who: name, usd: usdText(usd) }));
|
||||
const amount = (s) => { const n = Number(s.replace(/^\$/, "").replace(/,/g, "").trim()); return s && n >= 0 && n <= 1e6 ? n : null; };
|
||||
const type = () => pillNumber(pill, b ? String(b.set) : "", "USD", "abal-in", t("Balance, in USD"), amount, t("A balance is an amount in USD from 0 to 1,000,000"), null, set);
|
||||
pill.textContent = b ? t("≈{usd} left", { usd: b.left == null ? (cny ? "¥" : "$") + "…" : moneyText(b.left, cny) }) : t("Set balance");
|
||||
pill.title = !b ? t("Type what the vendor's page says this key has left, and magpie counts down from it as it sends requests")
|
||||
: [t("An estimate: {set} from {when}, less {spent} magpie counted spent on this key since, at the prices the Usage page shows. Click to change", {
|
||||
set: moneyText(b.set, cny), when: new Date(b.from || b.at).toLocaleString(intlLang()),
|
||||
spent: moneyText(b.spent || 0, false) + (cny && b.rate ? " (" + moneyText((b.spent || 0) * b.rate, true) + ")" : ""),
|
||||
}),
|
||||
b.left == null ? t("The dollar's rate in yuan isn't known yet, so what is left can't be counted") : "",
|
||||
b.refill && b.next ? t("Refills to {set} on {when}", { set: moneyText(b.set, cny), when: new Date(b.next).toLocaleString(intlLang(), { dateStyle: "medium" }) }) : "",
|
||||
].filter(Boolean).join("\n");
|
||||
const set = (v) => accountAction("provider/keyownbalance", { id: p.id, account: k.id, balance: v ? v.n : null, ...v?.cny && { currency: "cny" } },
|
||||
!v ? t("{who} has no balance typed", { who: name }) : t("{who} has {usd} left", { who: name, usd: moneyText(v.n, v.cny) }));
|
||||
const refill = (r) => accountAction("provider/keybalancerefill", { id: p.id, account: k.id, refill: r },
|
||||
!r ? t("{who} no longer refills", { who: name })
|
||||
: r.every === "week" ? t("{who} refills each {weekday}", { who: name, weekday: weekdayName(r.day) })
|
||||
: t("{who} refills on day {day} of each month", { who: name, day: r.day }));
|
||||
// a bare number is in the balance's own currency, else in Settings' one
|
||||
const unit = b ? (cny ? "cny" : "usd") : currency === "cny" ? "cny" : "usd";
|
||||
const type = () => pillNumber(pill, b ? (cny ? "¥" : "") + b.set : "", unit === "cny" ? "CNY" : "USD", "abal-in",
|
||||
t(unit === "cny" ? "Balance, in CNY" : "Balance, in USD"), (s) => balanceAmount(s, unit),
|
||||
t("A balance is an amount from 0 to 1,000,000, in USD or in yuan (¥)"), null, set);
|
||||
const day = (s) => { const n = Number(s.trim()); return Number.isInteger(n) && n >= 1 && n <= 31 ? n : null; };
|
||||
const monthly = () => pillNumber(pill, String(b.refill?.every === "month" ? b.refill.day : 1), "1–31", "abal-in", t("Refill day of the month"), day,
|
||||
t("A day of the month is a whole number from 1 to 31"), b.refill?.every === "month" ? b.refill.day : null, (d) => refill({ every: "month", day: d }));
|
||||
const weekly = () => openProtoMenu(pill, [1, 2, 3, 4, 5, 6, 7].map((d) => ({ v: d, name: weekdayName(d), literalName: true, note: "" })),
|
||||
b.refill?.every === "week" ? b.refill.day : 0, (d) => refill({ every: "week", day: d }), "Refills on", "sess-menu");
|
||||
pill.onclick = (e) => {
|
||||
e.stopPropagation();
|
||||
if (!b) return type();
|
||||
if (pill.classList.contains("open")) return closeProtoMenu();
|
||||
openProtoMenu(pill, [
|
||||
{ v: "set", name: "Enter balance…", note: "Counts down from now" },
|
||||
{ v: "month", name: "Refills each month…", note: "" },
|
||||
{ v: "week", name: "Refills each week…", note: "" },
|
||||
{ v: "never", name: "Never refills", note: "" },
|
||||
{ v: "off", name: "No balance", note: "" },
|
||||
], "", (v) => v === "off" ? set(null) : type(), "Balance", "sess-menu");
|
||||
], b.refill?.every || "never", (v) => v === "off" ? set(null) : v === "month" ? monthly() : v === "week" ? weekly()
|
||||
: v === "never" ? b.refill && refill(null) : type(), "Balance", "sess-menu");
|
||||
};
|
||||
return pill;
|
||||
}
|
||||
|
||||
@@ -76,6 +76,29 @@ func TestKeyOwnBalanceRoutes(t *testing.T) {
|
||||
if _, b := listed(); b == nil || b.Set != 20 {
|
||||
t.Fatalf("the editor saved, the balance typed is gone: %+v", b)
|
||||
}
|
||||
// in yuan, refilled on the 1st; a currency it doesn't know refused
|
||||
call("POST", "/api/provider/keyownbalance", `{"id":"relay","account":"`+key+`","balance":700,"currency":"cny"}`)
|
||||
call("POST", "/api/provider/keybalancerefill", `{"id":"relay","account":"`+key+`","refill":{"every":"month","day":1}}`)
|
||||
if _, b := listed(); b == nil || b.Set != 700 || b.Currency != "cny" || b.Left == nil || *b.Left != 700 || b.Refill == nil || b.Refill.Day != 1 || b.Next == nil {
|
||||
t.Fatalf("¥700 refilled on the 1st: %+v", b)
|
||||
}
|
||||
for _, bad := range []struct{ path, body string }{
|
||||
{"keyownbalance", `{"id":"relay","account":"` + key + `","balance":7,"currency":"eur"}`},
|
||||
{"keybalancerefill", `{"id":"relay","account":"` + key + `","refill":{"every":"month","day":40}}`},
|
||||
} {
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/"+bad.path, strings.NewReader(bad.body)))
|
||||
if w.Code == 200 {
|
||||
t.Errorf("%s %s taken", bad.path, bad.body)
|
||||
}
|
||||
}
|
||||
if _, b := listed(); b.Currency != "cny" || b.Refill.Day != 1 {
|
||||
t.Fatalf("a refused change changed it: %+v", b)
|
||||
}
|
||||
call("POST", "/api/provider/keybalancerefill", `{"id":"relay","account":"`+key+`","refill":null}`)
|
||||
if _, b := listed(); b == nil || b.Refill != nil || b.Set != 700 {
|
||||
t.Fatalf("refill off: %+v", b)
|
||||
}
|
||||
call("POST", "/api/provider/keyownbalance", `{"id":"relay","account":"`+key+`","balance":null}`)
|
||||
if _, b := listed(); b != nil {
|
||||
t.Fatalf("taken off: %+v", b)
|
||||
|
||||
@@ -866,11 +866,9 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
|
||||
// Usage page shows the same, provider.ownBalanceCard)
|
||||
out.TakesOwnBalance = p.TakesOwnBalance()
|
||||
for i, k := range out.KeyList {
|
||||
b, ok := p.KeyOwnBalance(k.ID)
|
||||
if !ok {
|
||||
continue
|
||||
if e, ok := p.OwnBalanceEstimate(k.ID); ok {
|
||||
out.KeyList[i].Balance = &e
|
||||
}
|
||||
out.KeyList[i].Balance = &provider.BalanceEstimate{Set: b.USD, At: b.At, Spent: usage.KeySpent(k.ID, b.At)}
|
||||
}
|
||||
if !out.Key.Set && p.Ready() {
|
||||
out.Key.Optional = true
|
||||
@@ -1651,9 +1649,14 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
// (its id), in USD a day, a month or in all; none, or an
|
||||
// amount of 0, takes it off
|
||||
Spend *provider.SpendCap `json:"spend"`
|
||||
// Balance, for keyownbalance: the balance in USD typed for the
|
||||
// key Account (its id), counted from now; none takes it off
|
||||
Balance *float64 `json:"balance"`
|
||||
// Balance, for keyownbalance: the balance typed for the key
|
||||
// Account (its id), counted from now, in USD or, with Currency
|
||||
// "cny", in yuan; none takes it off
|
||||
Balance *float64 `json:"balance"`
|
||||
Currency string `json:"currency"`
|
||||
// Refill, for keybalancerefill: when the key's balance typed
|
||||
// is whole again; none for never
|
||||
Refill *provider.Refill `json:"refill"`
|
||||
// Alias, for accountname: the account's name of the user's
|
||||
// own, "" to take it off (#1515)
|
||||
Alias string `json:"alias"`
|
||||
@@ -2348,7 +2351,23 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
return
|
||||
}
|
||||
case "keyownbalance":
|
||||
if err := provider.SetKeyOwnBalance(in.ID, req.Account, req.Balance); err != nil {
|
||||
var b *provider.OwnBalance
|
||||
switch {
|
||||
case req.Balance == nil:
|
||||
case req.Currency == "cny":
|
||||
b = &provider.OwnBalance{CNY: req.Balance}
|
||||
case req.Currency == "" || req.Currency == "usd":
|
||||
b = &provider.OwnBalance{USD: *req.Balance}
|
||||
default:
|
||||
fail(rw, fmt.Errorf("a balance is in usd or cny, not %q", req.Currency))
|
||||
return
|
||||
}
|
||||
if err := provider.SetKeyOwnBalance(in.ID, req.Account, b); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
case "keybalancerefill":
|
||||
if err := provider.SetKeyBalanceRefill(in.ID, req.Account, req.Refill); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -4,9 +4,11 @@
|
||||
// has a pill: what is left of the balance typed, marked as an estimate
|
||||
// (≈), else Set balance (hover-only, as the row's other unset pills).
|
||||
// Set balance opens the amount in place; a balance set opens the app's
|
||||
// menu (no native select): Enter balance… or No balance, posted to
|
||||
// provider/keyownbalance. An amount that isn't one is refused and nothing
|
||||
// is posted. A click moves nothing; at a phone's width the row stays
|
||||
// menu (no native select): Enter balance…, a refill each month (a day)
|
||||
// or each week (a weekday), Never refills, or No balance, posted to
|
||||
// provider/keyownbalance and provider/keybalancerefill. An amount in yuan
|
||||
// ("¥100") is posted as CNY and shown in yuan. An amount that isn't one is
|
||||
// refused and nothing is posted. A click moves nothing; at a phone's width the row stays
|
||||
// inside the window. In every language.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
@@ -21,7 +23,7 @@ const fresh = () => ({
|
||||
key: { set: true, masked: "sk-…one" },
|
||||
takesOwnBalance: true,
|
||||
keyList: [
|
||||
{ id: "k1", name: "Main", masked: "sk-…one", on: true, balance: { set: 20, at: new Date(Date.now() - 864e5).toISOString(), spent: 7.5 } },
|
||||
{ id: "k1", name: "Main", masked: "sk-…one", on: true, balance: { set: 20, at: new Date(Date.now() - 864e5).toISOString(), spent: 7.5, left: 12.5 } },
|
||||
{ id: "k2", name: "Team", masked: "sk-…two", on: true },
|
||||
],
|
||||
balanceToken: { takes: false, set: false }, proxy: "",
|
||||
@@ -46,9 +48,14 @@ function serve(lang, posts) {
|
||||
posts.push({ action, body });
|
||||
if (action === "keyownbalance") {
|
||||
const k = relay.keyList.find((x) => x.id === body.account);
|
||||
if (body.balance != null) k.balance = { set: body.balance, at: new Date().toISOString(), spent: 0 };
|
||||
if (body.balance != null) k.balance = { set: body.balance, at: new Date().toISOString(), spent: 0, left: body.balance, ...body.currency && { currency: body.currency }, ...k.balance?.refill && { refill: k.balance.refill, next: k.balance.next } };
|
||||
else delete k.balance;
|
||||
}
|
||||
if (action === "keybalancerefill") {
|
||||
const k = relay.keyList.find((x) => x.id === body.account);
|
||||
if (body.refill) Object.assign(k.balance, { refill: body.refill, next: new Date(Date.now() + 5 * 864e5).toISOString() });
|
||||
else delete k.balance.refill, delete k.balance.next;
|
||||
}
|
||||
return json(providers);
|
||||
}
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
@@ -59,11 +66,11 @@ function serve(lang, posts) {
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: { k1: "≈$12.50 left", none: "Set balance", menu: "Balance", enter: "Enter balance…", off: "No balance", k2: "≈$5.00 left", k1again: "≈$40.00 left", bad: "A balance is an amount in USD from 0 to 1,000,000" },
|
||||
zh: { k1: "≈$12.50 剩余", none: "设置余额", menu: "余额", enter: "填写余额…", off: "无余额", k2: "≈$5.00 剩余", k1again: "≈$40.00 剩余", bad: "余额是 0 到 1,000,000 之间的美元金额" },
|
||||
"zh-TW": { k1: "≈$12.50 剩餘", none: "設定餘額", menu: "餘額", enter: "填寫餘額…", off: "無餘額", k2: "≈$5.00 剩餘", k1again: "≈$40.00 剩餘", bad: "餘額是 0 到 1,000,000 之間的美元金額" },
|
||||
ja: { k1: "残り ≈$12.50", none: "残高を設定", menu: "残高", enter: "残高を入力…", off: "残高なし", k2: "残り ≈$5.00", k1again: "残り ≈$40.00", bad: "残高は 0 から 1,000,000 までの USD 金額です" },
|
||||
de: { k1: "≈$12.50 übrig", none: "Guthaben festlegen", menu: "Guthaben", enter: "Guthaben eingeben…", off: "Kein Guthaben", k2: "≈$5.00 übrig", k1again: "≈$40.00 übrig", bad: "Ein Guthaben ist ein Betrag in USD von 0 bis 1.000.000" },
|
||||
en: { k1: "≈$12.50 left", none: "Set balance", menu: "Balance", enter: "Enter balance…", off: "No balance", k2: "≈$5.00 left", k1again: "≈$40.00 left", yuan: "≈¥100.00 left", bad: "A balance is an amount from 0 to 1,000,000, in USD or in yuan (¥)", month: "Refills each month…", week: "Refills each week…", never: "Never refills", on: "Refills on", refills: "Refills to $40.00 on" },
|
||||
zh: { k1: "≈$12.50 剩余", none: "设置余额", menu: "余额", enter: "填写余额…", off: "无余额", k2: "≈$5.00 剩余", k1again: "≈$40.00 剩余", yuan: "≈¥100.00 剩余", bad: "余额是 0 到 1,000,000 之间的金额,美元或人民币(¥)", month: "每月恢复…", week: "每周恢复…", never: "不恢复", on: "恢复于", refills: "恢复为 $40.00" },
|
||||
"zh-TW": { k1: "≈$12.50 剩餘", none: "設定餘額", menu: "餘額", enter: "填寫餘額…", off: "無餘額", k2: "≈$5.00 剩餘", k1again: "≈$40.00 剩餘", yuan: "≈¥100.00 剩餘", bad: "餘額是 0 到 1,000,000 之間的金額,美元或人民幣(¥)", month: "每月恢復…", week: "每週恢復…", never: "不恢復", on: "恢復於", refills: "恢復為 $40.00" },
|
||||
ja: { k1: "残り ≈$12.50", none: "残高を設定", menu: "残高", enter: "残高を入力…", off: "残高なし", k2: "残り ≈$5.00", k1again: "残り ≈$40.00", yuan: "残り ≈¥100.00", bad: "残高は 0 から 1,000,000 までの金額です(USD または人民元 ¥)", month: "毎月戻す…", week: "毎週戻す…", never: "戻さない", on: "戻す曜日", refills: "$40.00 へ戻る" },
|
||||
de: { k1: "≈$12.50 übrig", none: "Guthaben festlegen", menu: "Guthaben", enter: "Guthaben eingeben…", off: "Kein Guthaben", k2: "≈$5.00 übrig", k1again: "≈$40.00 übrig", yuan: "≈¥100.00 übrig", bad: "Ein Guthaben ist ein Betrag von 0 bis 1.000.000, in USD oder in Yuan (¥)", month: "Monatlich auffüllen…", week: "Wöchentlich auffüllen…", never: "Nie auffüllen", on: "Auffüllen am", refills: "wieder auf $40.00 aufgefüllt" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
@@ -160,6 +167,66 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
assert.deepEqual(p.body, { id: "relay", account: "k1", balance: 40 });
|
||||
await page.waitForTimeout(250);
|
||||
assert.equal(await pill("k1").textContent(), w.k1again);
|
||||
|
||||
// k1 refills on a day of each month, then each Friday, then never
|
||||
await still("k1");
|
||||
await menu.waitFor();
|
||||
await item(w.month).click();
|
||||
await box("k1").waitFor();
|
||||
n = posts.length;
|
||||
await box("k1").fill("40");
|
||||
await box("k1").press("Enter");
|
||||
await page.waitForTimeout(300);
|
||||
assert.equal(posts.length, n, "day 40 was posted");
|
||||
// the refused Enter can press the pill, which opens its menu
|
||||
await page.waitForTimeout(300);
|
||||
if (!(await box("k1").isVisible())) {
|
||||
if (!(await menu.isVisible())) await still("k1");
|
||||
await item(w.month).click();
|
||||
}
|
||||
await box("k1").waitFor();
|
||||
await box("k1").fill("1");
|
||||
await box("k1").press("Enter");
|
||||
p = await posted(n);
|
||||
assert.equal(p.action, "keybalancerefill");
|
||||
assert.deepEqual(p.body, { id: "relay", account: "k1", refill: { every: "month", day: 1 } });
|
||||
await page.waitForTimeout(250);
|
||||
assert.match(await pill("k1").getAttribute("title"), new RegExp(w.refills.replace(/[$.]/g, "\\$&")));
|
||||
await still("k1");
|
||||
await menu.waitFor();
|
||||
await item(w.week).click();
|
||||
await page.waitForTimeout(200);
|
||||
await menu.waitFor();
|
||||
assert.equal(await menu.locator(".pm-head").textContent(), w.on);
|
||||
assert.equal(await menu.locator(".pm-item").count(), 7);
|
||||
const friday = await page.evaluate(() => new Date(2026, 10, 6).toLocaleDateString(intlLang(), { weekday: "long" }));
|
||||
n = posts.length;
|
||||
await item(friday).click();
|
||||
p = await posted(n);
|
||||
assert.deepEqual(p.body, { id: "relay", account: "k1", refill: { every: "week", day: 5 } });
|
||||
await page.waitForTimeout(250);
|
||||
await still("k1");
|
||||
await menu.waitFor();
|
||||
n = posts.length;
|
||||
await item(w.never).click();
|
||||
p = await posted(n);
|
||||
assert.deepEqual(p.body, { id: "relay", account: "k1", refill: null });
|
||||
await page.waitForTimeout(250);
|
||||
assert.doesNotMatch(await pill("k1").getAttribute("title"), new RegExp(w.refills.replace(/[$.]/g, "\\$&")));
|
||||
|
||||
// k2 typed again in yuan
|
||||
await still("k2");
|
||||
await menu.waitFor();
|
||||
await item(w.enter).click();
|
||||
await box("k2").waitFor();
|
||||
n = posts.length;
|
||||
await box("k2").fill("¥100");
|
||||
await box("k2").press("Enter");
|
||||
p = await posted(n);
|
||||
assert.deepEqual(p.body, { id: "relay", account: "k2", balance: 100, currency: "cny" });
|
||||
await page.waitForTimeout(250);
|
||||
assert.equal(await pill("k2").textContent(), w.yuan);
|
||||
|
||||
await still("k1");
|
||||
await menu.waitFor();
|
||||
n = posts.length;
|
||||
|
||||
@@ -11,29 +11,128 @@ package provider
|
||||
// whose relay's query is found (balance_probe.go), shows that, and the
|
||||
// typed one stays saved, unused, as the user left it.
|
||||
|
||||
// The balance may be typed in yuan (tenacious_eagle_96548): the spend,
|
||||
// priced in USD, is then counted at the dollar's rate in yuan magpie last
|
||||
// learned (internal/fx, fetched behind the page and cached), and while it
|
||||
// has never learned one what is left is unknown, never counted at a guess.
|
||||
// It may refill (the same user: $10 a month from the 1st): at each refill,
|
||||
// at midnight local time on a day of the month or of the week, the amount
|
||||
// typed is whole again and the spend counted from then.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/fx"
|
||||
)
|
||||
|
||||
// OwnBalance is a key's balance as the user typed it: USD left at At.
|
||||
// OwnBalance is a key's balance as the user typed it: USD left at At, or,
|
||||
// with CNY set, that many yuan; with Refill, whole again at each refill.
|
||||
type OwnBalance struct {
|
||||
USD float64 `json:"usd"`
|
||||
At time.Time `json:"at"`
|
||||
USD float64 `json:"usd,omitempty"`
|
||||
// CNY is the amount when it was typed in yuan; USD is then unused
|
||||
CNY *float64 `json:"cny,omitempty"`
|
||||
At time.Time `json:"at"`
|
||||
Refill *Refill `json:"refill,omitempty"`
|
||||
}
|
||||
|
||||
// MaxOwnBalance bounds a balance typed by hand, in USD.
|
||||
// Amount is the balance typed and its currency, "cny" or "usd".
|
||||
func (b OwnBalance) Amount() (float64, string) {
|
||||
if b.CNY != nil {
|
||||
return *b.CNY, "cny"
|
||||
}
|
||||
return b.USD, "usd"
|
||||
}
|
||||
|
||||
// Refill is when a balance typed is whole again: at midnight, local time,
|
||||
// on Day of each month (1–31, a month without that day on its last) or of
|
||||
// each week (1 Monday to 7 Sunday).
|
||||
type Refill struct {
|
||||
Every string `json:"every"`
|
||||
Day int `json:"day"`
|
||||
}
|
||||
|
||||
// How often a balance typed refills.
|
||||
const (
|
||||
RefillMonth = "month"
|
||||
RefillWeek = "week"
|
||||
)
|
||||
|
||||
// Last is the last refill at or before now, in now's location.
|
||||
func (r Refill) Last(now time.Time) time.Time {
|
||||
y, m, d := now.Date()
|
||||
loc := now.Location()
|
||||
if r.Every == RefillWeek {
|
||||
iso := (int(now.Weekday())+6)%7 + 1
|
||||
return time.Date(y, m, d-(iso-r.Day+7)%7, 0, 0, 0, 0, loc)
|
||||
}
|
||||
t := monthDay(y, m, r.Day, loc)
|
||||
if t.After(now) {
|
||||
t = monthDay(y, m-1, r.Day, loc)
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// Next is the first refill after now, in now's location.
|
||||
func (r Refill) Next(now time.Time) time.Time {
|
||||
l := r.Last(now)
|
||||
y, m, d := l.Date()
|
||||
if r.Every == RefillWeek {
|
||||
return time.Date(y, m, d+7, 0, 0, 0, 0, l.Location())
|
||||
}
|
||||
return monthDay(y, m+1, r.Day, l.Location())
|
||||
}
|
||||
|
||||
// monthDay is midnight on day of month m of year y, or on the month's last
|
||||
// day when it has fewer.
|
||||
func monthDay(y int, m time.Month, day int, loc *time.Location) time.Time {
|
||||
last := time.Date(y, m+1, 0, 0, 0, 0, 0, loc).Day()
|
||||
return time.Date(y, m, min(day, last), 0, 0, 0, 0, loc)
|
||||
}
|
||||
|
||||
// check says what is wrong with r, nil when nothing is.
|
||||
func (r Refill) check() error {
|
||||
switch {
|
||||
case r.Every == RefillMonth && r.Day >= 1 && r.Day <= 31:
|
||||
case r.Every == RefillWeek && r.Day >= 1 && r.Day <= 7:
|
||||
default:
|
||||
return fmt.Errorf("a balance refills each month on a day from 1 to 31, or each week on a day from 1 (Monday) to 7 (Sunday), not %s %d", r.Every, r.Day)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// String is r as the CLI takes and shows it: monthly:1, weekly:mon.
|
||||
func (r Refill) String() string {
|
||||
if r.Every == RefillWeek {
|
||||
return "weekly:" + strings.ToLower(time.Weekday(r.Day % 7).String()[:3])
|
||||
}
|
||||
return fmt.Sprintf("monthly:%d", r.Day)
|
||||
}
|
||||
|
||||
// MaxOwnBalance bounds a balance typed by hand, in USD or in yuan.
|
||||
const MaxOwnBalance = 1_000_000
|
||||
|
||||
// BalanceEstimate is what a card shows of a balance typed by hand: the
|
||||
// amount typed, when, and what magpie counted spent on the key since.
|
||||
// amount typed (in Currency), when, and what magpie counted spent on the
|
||||
// key since (in USD), from the last refill when it refills.
|
||||
type BalanceEstimate struct {
|
||||
Set float64 `json:"set"`
|
||||
At time.Time `json:"at"`
|
||||
Spent float64 `json:"spent"`
|
||||
// Currency is the amount's, "cny" when typed in yuan, else unset (USD)
|
||||
Currency string `json:"currency,omitempty"`
|
||||
// Rate is the yuan a dollar is counted at, for one in yuan
|
||||
Rate float64 `json:"rate,omitempty"`
|
||||
// Left is what is left, in Currency; nil while it can't be told (in
|
||||
// yuan with spend counted and no rate ever learned)
|
||||
Left *float64 `json:"left"`
|
||||
// From is what the spend is counted from: At, or the last refill
|
||||
From time.Time `json:"from"`
|
||||
Refill *Refill `json:"refill,omitempty"`
|
||||
Next *time.Time `json:"next,omitempty"`
|
||||
}
|
||||
|
||||
// KeySpent is usage.KeySpent, which package usage sets: what the calls
|
||||
@@ -41,6 +140,17 @@ type BalanceEstimate struct {
|
||||
// of this package alone) counts nothing.
|
||||
var KeySpent func(keyID string, start time.Time) float64
|
||||
|
||||
// ownNow is the clock a balance typed is counted by: when it was typed,
|
||||
// and which refill is the last.
|
||||
var ownNow = time.Now
|
||||
|
||||
// cnyPerUSD is the dollar's rate in yuan magpie last learned, false when
|
||||
// it has never learned one; never waited for.
|
||||
var cnyPerUSD = func() (float64, bool) {
|
||||
r, ok := fx.Known()
|
||||
return r.CNYPerUSD, ok && r.CNYPerUSD > 0
|
||||
}
|
||||
|
||||
// KeyOwnBalance is the balance typed for p's key keyID, and whether it
|
||||
// has one.
|
||||
func (p Provider) KeyOwnBalance(keyID string) (OwnBalance, bool) {
|
||||
@@ -48,6 +158,45 @@ func (p Provider) KeyOwnBalance(keyID string) (OwnBalance, bool) {
|
||||
return b, ok
|
||||
}
|
||||
|
||||
// OwnBalanceEstimate is what is left of the balance typed for p's key
|
||||
// keyID, and whether it has one.
|
||||
func (p Provider) OwnBalanceEstimate(keyID string) (BalanceEstimate, bool) {
|
||||
b, ok := p.KeyOwnBalance(keyID)
|
||||
if !ok {
|
||||
return BalanceEstimate{}, false
|
||||
}
|
||||
now := ownNow()
|
||||
amount, cur := b.Amount()
|
||||
e := BalanceEstimate{Set: amount, At: b.At, From: b.At}
|
||||
if b.Refill != nil {
|
||||
r := *b.Refill
|
||||
e.Refill = &r
|
||||
// now in local time (ownNow's), as the user means "the 1st"
|
||||
if l := r.Last(now); l.After(e.From) {
|
||||
e.From = l
|
||||
}
|
||||
next := r.Next(now)
|
||||
e.Next = &next
|
||||
}
|
||||
if KeySpent != nil {
|
||||
e.Spent = KeySpent(keyID, e.From)
|
||||
}
|
||||
left := amount - e.Spent
|
||||
if cur == "cny" {
|
||||
e.Currency = cur
|
||||
rate, known := cnyPerUSD()
|
||||
switch {
|
||||
case known:
|
||||
e.Rate = rate
|
||||
left = amount - e.Spent*rate
|
||||
case e.Spent != 0:
|
||||
return e, true // spend counted at no rate: unknown
|
||||
}
|
||||
}
|
||||
e.Left = &left
|
||||
return e, true
|
||||
}
|
||||
|
||||
// TakesOwnBalance says p's keys may have a balance typed by hand: keys
|
||||
// whose vendor tells none magpie knows where to ask. A relay whose query
|
||||
// is looked for (probesBalance) takes one too: when none is found, the
|
||||
@@ -67,41 +216,81 @@ func (p Provider) TakesOwnBalance() bool {
|
||||
// hand, user naming it when p has several: what was typed less what was
|
||||
// spent since. false when the key has none.
|
||||
func ownBalanceCard(p Provider, key, user string) (SubscriptionQuota, bool) {
|
||||
id := keyID(key)
|
||||
b, ok := p.KeyOwnBalance(id)
|
||||
e, ok := p.OwnBalanceEstimate(keyID(key))
|
||||
if !ok {
|
||||
return SubscriptionQuota{}, false
|
||||
}
|
||||
var spent float64
|
||||
if KeySpent != nil {
|
||||
spent = KeySpent(id, b.At)
|
||||
}
|
||||
now := time.Now()
|
||||
return SubscriptionQuota{
|
||||
q := SubscriptionQuota{
|
||||
Provider: p.ID, Name: p.Name, Icon: p.Icon, User: user, Windows: []QuotaWindow{},
|
||||
Balance: ownBalanceText(b.USD - spent),
|
||||
Estimate: &BalanceEstimate{Set: b.USD, At: b.At, Spent: spent},
|
||||
Estimate: &e,
|
||||
ReadAt: &now,
|
||||
}, true
|
||||
}
|
||||
if e.Left == nil {
|
||||
q.Error = "the dollar's rate in yuan isn't known yet, so what is left of the balance in yuan can't be counted"
|
||||
} else {
|
||||
q.Balance = ownBalanceText(*e.Left, e.Currency)
|
||||
}
|
||||
return q, true
|
||||
}
|
||||
|
||||
// ownBalanceText is an estimated balance as a card shows it, "≈$12.34",
|
||||
// below nothing as "≈$-1.20": the calls priced since went past it.
|
||||
func ownBalanceText(usd float64) string {
|
||||
if math.Abs(usd) < 0.005 {
|
||||
usd = 0
|
||||
// ownBalanceText is an estimated balance as a card shows it, "≈$12.34" or
|
||||
// "≈¥88.00", below nothing as "≈$-1.20": the calls priced since went past
|
||||
// it.
|
||||
func ownBalanceText(v float64, currency string) string {
|
||||
if math.Abs(v) < 0.005 {
|
||||
v = 0
|
||||
}
|
||||
return fmt.Sprintf("≈$%.2f", usd)
|
||||
sign := "$"
|
||||
if currency == "cny" {
|
||||
sign = "¥"
|
||||
}
|
||||
return fmt.Sprintf("≈%s%.2f", sign, v)
|
||||
}
|
||||
|
||||
// SetKeyOwnBalance gives the key ref (its id or name) of the provider id
|
||||
// the balance usd, counted from now; nil takes it off.
|
||||
func SetKeyOwnBalance(id, ref string, usd *float64) error {
|
||||
if usd != nil {
|
||||
if err := checkOwnBalance(*usd); err != nil {
|
||||
// the balance b (its amount, in USD or CNY), counted from now; nil takes
|
||||
// it off. With no Refill of its own, b keeps the one the key had.
|
||||
func SetKeyOwnBalance(id, ref string, b *OwnBalance) error {
|
||||
if b != nil {
|
||||
if err := checkOwnBalance(*b); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return editOwnBalance(id, ref, func(had OwnBalance, ok bool) (*OwnBalance, error) {
|
||||
if b == nil {
|
||||
return nil, nil
|
||||
}
|
||||
v := *b
|
||||
v.At = ownNow().UTC()
|
||||
if v.Refill == nil && ok {
|
||||
v.Refill = had.Refill
|
||||
}
|
||||
return &v, nil
|
||||
})
|
||||
}
|
||||
|
||||
// SetKeyBalanceRefill gives the balance typed for the key ref of the
|
||||
// provider id the refill r, nil for none; its amount and when it was
|
||||
// typed stay. A key with no balance typed takes none.
|
||||
func SetKeyBalanceRefill(id, ref string, r *Refill) error {
|
||||
if r != nil {
|
||||
if err := r.check(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return editOwnBalance(id, ref, func(had OwnBalance, ok bool) (*OwnBalance, error) {
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("the key has no balance typed to refill: type one first")
|
||||
}
|
||||
had.Refill = r
|
||||
return &had, nil
|
||||
})
|
||||
}
|
||||
|
||||
// editOwnBalance saves what edit makes of the balance typed for the key
|
||||
// ref of the provider id, nil taking it off.
|
||||
func editOwnBalance(id, ref string, edit func(had OwnBalance, ok bool) (*OwnBalance, error)) error {
|
||||
p, err := Find(id)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -118,13 +307,18 @@ func SetKeyOwnBalance(id, ref string, usd *float64) error {
|
||||
for id, v := range p.KeyOwnBalances {
|
||||
m[id] = v
|
||||
}
|
||||
if usd == nil {
|
||||
if _, had := m[k]; !had {
|
||||
had, ok := m[k]
|
||||
b, err := edit(had, ok)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if b == nil {
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
delete(m, k)
|
||||
} else {
|
||||
m[k] = OwnBalance{USD: *usd, At: time.Now().UTC()}
|
||||
m[k] = *b
|
||||
}
|
||||
p.KeyOwnBalances = m
|
||||
if err := Save(*p); err != nil {
|
||||
@@ -140,29 +334,96 @@ func SetKeyOwnBalance(id, ref string, usd *float64) error {
|
||||
|
||||
// checkOwnBalance says what is wrong with a balance typed, nil when
|
||||
// nothing is.
|
||||
func checkOwnBalance(usd float64) error {
|
||||
if !(usd >= 0 && usd <= MaxOwnBalance) {
|
||||
return fmt.Errorf("a balance is an amount in USD from 0 to %d, not %v", MaxOwnBalance, usd)
|
||||
func checkOwnBalance(b OwnBalance) error {
|
||||
v, _ := b.Amount()
|
||||
if !(v >= 0 && v <= MaxOwnBalance) {
|
||||
return fmt.Errorf("a balance is an amount from 0 to %d, in USD or in yuan (¥), not %v", MaxOwnBalance, v)
|
||||
}
|
||||
if b.CNY != nil && b.USD != 0 {
|
||||
return fmt.Errorf("a balance is in USD or in yuan, not both")
|
||||
}
|
||||
if b.Refill != nil {
|
||||
return b.Refill.check()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseOwnBalance reads a balance as the CLI takes it, an amount in USD
|
||||
// ("20", "$20", "12.5"); off for none (nil).
|
||||
func ParseOwnBalance(amount string) (*float64, error) {
|
||||
// ("20", "$20", "12.5 usd") or in yuan ("¥100", "100cny", "100 rmb",
|
||||
// "100元"); off for none (nil).
|
||||
func ParseOwnBalance(amount string) (*OwnBalance, error) {
|
||||
a := strings.ToLower(strings.TrimSpace(amount))
|
||||
switch a {
|
||||
case "off", "none", "no", "-":
|
||||
return nil, nil
|
||||
}
|
||||
usd, err := strconv.ParseFloat(strings.ReplaceAll(strings.TrimPrefix(a, "$"), ",", ""), 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("a balance is an amount in USD (20, 12.5) or off, not %q", amount)
|
||||
cny := false
|
||||
for _, s := range []string{"¥", "¥", "cny", "rmb"} {
|
||||
if strings.HasPrefix(a, s) {
|
||||
a, cny = strings.TrimPrefix(a, s), true
|
||||
}
|
||||
}
|
||||
if err := checkOwnBalance(usd); err != nil {
|
||||
for _, s := range []string{"元", "cny", "rmb", "yuan"} {
|
||||
if strings.HasSuffix(a, s) {
|
||||
a, cny = strings.TrimSuffix(a, s), true
|
||||
}
|
||||
}
|
||||
if !cny {
|
||||
a = strings.TrimSuffix(strings.TrimPrefix(a, "$"), "usd")
|
||||
}
|
||||
v, err := strconv.ParseFloat(strings.ReplaceAll(strings.TrimSpace(a), ",", ""), 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("a balance is an amount in USD (20, 12.5), in yuan (¥140) or off, not %q", amount)
|
||||
}
|
||||
b := OwnBalance{USD: v}
|
||||
if cny {
|
||||
b = OwnBalance{CNY: &v}
|
||||
}
|
||||
if err := checkOwnBalance(b); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &usd, nil
|
||||
return &b, nil
|
||||
}
|
||||
|
||||
// ParseRefill reads a refill as the CLI takes it: monthly (on the 1st),
|
||||
// monthly:15, weekly (on Monday), weekly:fri or weekly:5; off or never
|
||||
// for none (nil).
|
||||
func ParseRefill(s string) (*Refill, error) {
|
||||
a := strings.ToLower(strings.TrimSpace(s))
|
||||
switch a {
|
||||
case "off", "none", "no", "never", "-":
|
||||
return nil, nil
|
||||
}
|
||||
every, day, _ := strings.Cut(a, ":")
|
||||
bad := fmt.Errorf("a refill is monthly[:day 1-31], weekly[:mon…sun] or off, not %q", s)
|
||||
var r Refill
|
||||
switch every {
|
||||
case "monthly", "month", "m":
|
||||
r = Refill{Every: RefillMonth, Day: 1}
|
||||
if day != "" {
|
||||
n, err := strconv.Atoi(day)
|
||||
if err != nil {
|
||||
return nil, bad
|
||||
}
|
||||
r.Day = n
|
||||
}
|
||||
case "weekly", "week", "w":
|
||||
r = Refill{Every: RefillWeek, Day: 1}
|
||||
if day != "" {
|
||||
r.Day = 0
|
||||
for i, w := range []string{"mon", "tue", "wed", "thu", "fri", "sat", "sun"} {
|
||||
if strings.HasPrefix(day, w) || day == strconv.Itoa(i+1) {
|
||||
r.Day = i + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
return nil, bad
|
||||
}
|
||||
if err := r.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &r, nil
|
||||
}
|
||||
|
||||
// normalKeyOwnBalances is m as it is kept: key ids in lower case, a
|
||||
@@ -172,7 +433,10 @@ func normalKeyOwnBalances(m map[string]OwnBalance) map[string]OwnBalance {
|
||||
var out map[string]OwnBalance
|
||||
for k, b := range m {
|
||||
k = strings.ToLower(strings.TrimSpace(k))
|
||||
if k == "" || checkOwnBalance(b.USD) != nil {
|
||||
if b.Refill != nil && b.Refill.check() != nil {
|
||||
b.Refill = nil // a refill that isn't one, written by hand
|
||||
}
|
||||
if k == "" || checkOwnBalance(b) != nil {
|
||||
continue
|
||||
}
|
||||
if out == nil {
|
||||
|
||||
@@ -61,12 +61,12 @@ func TestTypedBalanceCountsDown(t *testing.T) {
|
||||
if c := ownCards(t); len(c) != 0 {
|
||||
t.Fatalf("cards with nothing typed: %+v", c)
|
||||
}
|
||||
twenty, one := 20.0, 1.0
|
||||
twenty, one := &OwnBalance{USD: 20}, &OwnBalance{USD: 1}
|
||||
before := time.Now().UTC()
|
||||
for _, s := range []struct {
|
||||
ref string
|
||||
usd *float64
|
||||
}{{"Main", &twenty}, {spare, &one}, {"Off", &one}} {
|
||||
usd *OwnBalance
|
||||
}{{"Main", twenty}, {spare, one}, {"Off", one}} {
|
||||
if err := SetKeyOwnBalance("plain", s.ref, s.usd); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -94,8 +94,7 @@ func TestTypedBalanceCountsDown(t *testing.T) {
|
||||
|
||||
// typed again: counted from now
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
thirty := 30.0
|
||||
if err := SetKeyOwnBalance("plain", "Main", &thirty); err != nil {
|
||||
if err := SetKeyOwnBalance("plain", "Main", &OwnBalance{USD: 30}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if again := ownCards(t)["plain|Main"]; again.Balance != "≈$22.50" || !again.Estimate.At.After(m.Estimate.At) {
|
||||
@@ -120,11 +119,11 @@ func TestTypedBalanceCountsDown(t *testing.T) {
|
||||
t.Fatalf("the replaced key's balance %+v %v", b, ok)
|
||||
}
|
||||
// refused: a key the provider hasn't, an amount out of bounds
|
||||
if err := SetKeyOwnBalance("plain", "nobody", &one); err == nil {
|
||||
if err := SetKeyOwnBalance("plain", "nobody", one); err == nil {
|
||||
t.Error("a key the provider hasn't got a balance")
|
||||
}
|
||||
for _, bad := range []float64{-1, MaxOwnBalance + 1} {
|
||||
if err := SetKeyOwnBalance("plain", "Spare", &bad); err == nil {
|
||||
if err := SetKeyOwnBalance("plain", "Spare", &OwnBalance{USD: bad}); err == nil {
|
||||
t.Errorf("%v was taken", bad)
|
||||
}
|
||||
}
|
||||
@@ -173,7 +172,7 @@ func TestToldBalanceWinsOverTyped(t *testing.T) {
|
||||
// What the CLI and a hand-edited providers.json may hold.
|
||||
func TestOwnBalanceParsed(t *testing.T) {
|
||||
for in, want := range map[string]float64{"20": 20, "$12.5": 12.5, " 1,234.50 ": 1234.5, "0": 0} {
|
||||
if got, err := ParseOwnBalance(in); err != nil || got == nil || *got != want {
|
||||
if got, err := ParseOwnBalance(in); err != nil || got == nil || got.USD != want || got.CNY != nil {
|
||||
t.Errorf("%q: %v %v, want %v", in, got, err, want)
|
||||
}
|
||||
}
|
||||
@@ -191,10 +190,232 @@ func TestOwnBalanceParsed(t *testing.T) {
|
||||
if len(n) != 1 || n["abc"].USD != 5 {
|
||||
t.Errorf("normalised %+v", n)
|
||||
}
|
||||
if got := ownBalanceText(-0.001); got != "≈$0.00" {
|
||||
if got := ownBalanceText(-0.001, ""); got != "≈$0.00" {
|
||||
t.Errorf("a hair below nothing reads %q", got)
|
||||
}
|
||||
if !strings.HasPrefix(ownBalanceText(3), "≈") {
|
||||
if !strings.HasPrefix(ownBalanceText(3, "cny"), "≈¥") {
|
||||
t.Error("an estimate not marked")
|
||||
}
|
||||
}
|
||||
|
||||
// rateStub holds the dollar's rate in yuan magpie knows: ok false is
|
||||
// none ever learned.
|
||||
func rateStub(t *testing.T, rate float64, ok bool) {
|
||||
t.Helper()
|
||||
old := cnyPerUSD
|
||||
cnyPerUSD = func() (float64, bool) { return rate, ok }
|
||||
t.Cleanup(func() { cnyPerUSD = old })
|
||||
}
|
||||
|
||||
// clockStub holds the clock a balance typed is counted by.
|
||||
func clockStub(t *testing.T, now time.Time) {
|
||||
t.Helper()
|
||||
old := ownNow
|
||||
ownNow = func() time.Time { return now }
|
||||
t.Cleanup(func() { ownNow = old })
|
||||
}
|
||||
|
||||
// A balance typed in yuan (tenacious_eagle_96548 on Discord) is counted
|
||||
// down by the spend, priced in USD, at the dollar's rate magpie last
|
||||
// learned, and shown in yuan. While no rate was ever learned, what is
|
||||
// left with spend counted is unknown: never the spend at a rate of 0, 1
|
||||
// or a guess. With nothing spent yet, it needs no rate.
|
||||
func TestTypedBalanceInYuan(t *testing.T) {
|
||||
probeSandbox(t)
|
||||
probeLocal = false
|
||||
spentStub(t, map[string]float64{keyID("sk-cny"): 2})
|
||||
if err := Save(Provider{ID: "cnrelay", Name: "CN Relay", Chat: "http://127.0.0.1:1/v1", Key: "sk-cny",
|
||||
Keys: []KeyAccount{{Name: "Fresh", Key: "sk-fresh"}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := ParseOwnBalance("¥100")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, ref := range []string{keyID("sk-cny"), "Fresh"} {
|
||||
if err := SetKeyOwnBalance("cnrelay", ref, b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rateStub(t, 7.1, true)
|
||||
var q SubscriptionQuota
|
||||
for _, v := range ownCards(t) {
|
||||
if v.Estimate.Spent == 2 {
|
||||
q = v
|
||||
} else if v.Balance != "≈¥100.00" {
|
||||
t.Errorf("Fresh, nothing spent: %q", v.Balance)
|
||||
}
|
||||
}
|
||||
if q.Estimate == nil {
|
||||
t.Fatal("no card for the key spent on")
|
||||
}
|
||||
if q.Balance != "≈¥85.80" || q.Estimate.Currency != "cny" || q.Estimate.Rate != 7.1 || q.Estimate.Set != 100 {
|
||||
t.Fatalf("¥100 less $2 at 7.1: %+v %+v, want ≈¥85.80", q, q.Estimate)
|
||||
}
|
||||
if n, ok := BalanceNumber(q.Balance); !ok || n != 85.8 {
|
||||
t.Errorf("a low-balance alert reads %v %v from %q", n, ok, q.Balance)
|
||||
}
|
||||
|
||||
rateStub(t, 0, false)
|
||||
for _, q := range ownCards(t) {
|
||||
e := q.Estimate
|
||||
switch {
|
||||
case e.Spent == 2 && (q.Balance != "" || e.Left != nil || q.Error == ""):
|
||||
t.Errorf("spend counted at no rate: %+v %+v, want unknown", q, e)
|
||||
case e.Spent == 0 && q.Balance != "≈¥100.00":
|
||||
t.Errorf("nothing spent needs no rate: %q", q.Balance)
|
||||
}
|
||||
}
|
||||
p, _ := Find("cnrelay")
|
||||
if got, ok := p.KeyOwnBalance(keyID("sk-cny")); !ok || got.CNY == nil || *got.CNY != 100 || got.USD != 0 {
|
||||
t.Fatalf("kept as %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A balance that refills (tenacious_eagle_96548: $10 a month from the
|
||||
// 1st) is whole again at midnight local time on its day, and the spend
|
||||
// is counted from the last refill, or from when it was typed when that
|
||||
// came after. Held at a clock in UTC+14 and UTC-10, so the local day,
|
||||
// not UTC's, is the one that counts.
|
||||
func TestTypedBalanceRefills(t *testing.T) {
|
||||
probeSandbox(t)
|
||||
probeLocal = false
|
||||
asked := spentStub(t, map[string]float64{keyID("sk-r"): 3})
|
||||
if err := Save(Provider{ID: "monthly", Name: "Monthly", Chat: "http://127.0.0.1:1/v1", Key: "sk-r"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, zone := range []string{"Pacific/Kiritimati", "Pacific/Honolulu", "UTC"} {
|
||||
loc, err := time.LoadLocation(zone)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
typed := time.Date(2026, 10, 20, 9, 0, 0, 0, loc)
|
||||
clockStub(t, typed)
|
||||
if err := SetKeyOwnBalance("monthly", keyID("sk-r"), &OwnBalance{USD: 10, Refill: &Refill{Every: RefillMonth, Day: 1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// before the 1st: counted from when it was typed
|
||||
clockStub(t, time.Date(2026, 10, 31, 23, 59, 0, 0, loc))
|
||||
p, _ := Find("monthly")
|
||||
e, _ := p.OwnBalanceEstimate(keyID("sk-r"))
|
||||
if !e.From.Equal(typed) || *e.Left != 7 || !e.Next.Equal(time.Date(2026, 11, 1, 0, 0, 0, 0, loc)) {
|
||||
t.Fatalf("%s before the refill: from %v next %v left %v", zone, e.From, e.Next, *e.Left)
|
||||
}
|
||||
// past midnight on the 1st, local time: whole again
|
||||
clockStub(t, time.Date(2026, 11, 8, 10, 0, 0, 0, loc))
|
||||
q := ownCards(t)["monthly|"]
|
||||
nov1 := time.Date(2026, 11, 1, 0, 0, 0, 0, loc)
|
||||
if !q.Estimate.From.Equal(nov1) || !asked[keyID("sk-r")].Equal(nov1) || q.Balance != "≈$7.00" {
|
||||
t.Fatalf("%s after the refill: %+v from %v, asked from %v", zone, q, q.Estimate.From, asked[keyID("sk-r")])
|
||||
}
|
||||
if !q.Estimate.Next.Equal(time.Date(2026, 12, 1, 0, 0, 0, 0, loc)) {
|
||||
t.Errorf("%s next refill %v", zone, q.Estimate.Next)
|
||||
}
|
||||
}
|
||||
|
||||
// typed again: the refill stays; taken off: counted from when typed
|
||||
clockStub(t, time.Date(2026, 11, 8, 10, 0, 0, 0, time.UTC))
|
||||
if err := SetKeyOwnBalance("monthly", keyID("sk-r"), &OwnBalance{USD: 12}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, _ := Find("monthly")
|
||||
if b, _ := p.KeyOwnBalance(keyID("sk-r")); b.Refill == nil || b.Refill.Day != 1 {
|
||||
t.Fatalf("typed again, the refill went: %+v", b)
|
||||
}
|
||||
if err := SetKeyBalanceRefill("monthly", keyID("sk-r"), &Refill{Every: RefillWeek, Day: 5}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, _ = Find("monthly")
|
||||
if b, _ := p.KeyOwnBalance(keyID("sk-r")); b.USD != 12 || b.Refill.Every != RefillWeek || !b.At.Equal(time.Date(2026, 11, 8, 10, 0, 0, 0, time.UTC)) {
|
||||
t.Fatalf("a refill changed the amount or when it was typed: %+v", b)
|
||||
}
|
||||
if err := SetKeyBalanceRefill("monthly", keyID("sk-r"), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, _ = Find("monthly")
|
||||
if e, _ := p.OwnBalanceEstimate(keyID("sk-r")); e.Refill != nil || e.Next != nil {
|
||||
t.Fatalf("no refill: %+v", e)
|
||||
}
|
||||
// refused: a refill that isn't one; one for a key with no balance
|
||||
for _, bad := range []Refill{{RefillMonth, 0}, {RefillMonth, 32}, {RefillWeek, 8}, {"year", 1}} {
|
||||
if err := SetKeyBalanceRefill("monthly", keyID("sk-r"), &bad); err == nil {
|
||||
t.Errorf("%+v taken", bad)
|
||||
}
|
||||
}
|
||||
if err := Save(Provider{ID: "keyless", Name: "Keyless", Chat: "http://127.0.0.1:1/v1", Key: "sk-none"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SetKeyBalanceRefill("keyless", keyID("sk-none"), &Refill{RefillMonth, 1}); err == nil {
|
||||
t.Error("a refill for a key with no balance typed")
|
||||
}
|
||||
}
|
||||
|
||||
// When each refill falls: on the day, at local midnight; a month without
|
||||
// the day refills on its last; a week from Monday (1) to Sunday (7).
|
||||
func TestRefillDays(t *testing.T) {
|
||||
loc, err := time.LoadLocation("Asia/Shanghai")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
at := func(y int, m time.Month, d, h int) time.Time { return time.Date(y, m, d, h, 0, 0, 0, loc) }
|
||||
for _, c := range []struct {
|
||||
r Refill
|
||||
now time.Time
|
||||
last, next time.Time
|
||||
}{
|
||||
{Refill{RefillMonth, 1}, at(2026, 11, 8, 10), at(2026, 11, 1, 0), at(2026, 12, 1, 0)},
|
||||
{Refill{RefillMonth, 1}, at(2026, 11, 1, 0), at(2026, 11, 1, 0), at(2026, 12, 1, 0)},
|
||||
{Refill{RefillMonth, 15}, at(2026, 11, 8, 10), at(2026, 10, 15, 0), at(2026, 11, 15, 0)},
|
||||
{Refill{RefillMonth, 31}, at(2027, 3, 5, 0), at(2027, 2, 28, 0), at(2027, 3, 31, 0)},
|
||||
{Refill{RefillMonth, 31}, at(2028, 3, 5, 0), at(2028, 2, 29, 0), at(2028, 3, 31, 0)},
|
||||
{Refill{RefillMonth, 31}, at(2026, 12, 31, 12), at(2026, 12, 31, 0), at(2027, 1, 31, 0)},
|
||||
{Refill{RefillMonth, 5}, at(2027, 1, 3, 0), at(2026, 12, 5, 0), at(2027, 1, 5, 0)},
|
||||
// 2026-11-08 is a Sunday
|
||||
{Refill{RefillWeek, 1}, at(2026, 11, 8, 10), at(2026, 11, 2, 0), at(2026, 11, 9, 0)},
|
||||
{Refill{RefillWeek, 7}, at(2026, 11, 8, 10), at(2026, 11, 8, 0), at(2026, 11, 15, 0)},
|
||||
{Refill{RefillWeek, 5}, at(2026, 11, 8, 10), at(2026, 11, 6, 0), at(2026, 11, 13, 0)},
|
||||
} {
|
||||
if l, n := c.r.Last(c.now), c.r.Next(c.now); !l.Equal(c.last) || !n.Equal(c.next) {
|
||||
t.Errorf("%+v at %v: last %v next %v, want %v and %v", c.r, c.now, l, n, c.last, c.next)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// What the CLI takes for an amount in yuan and for a refill.
|
||||
func TestOwnBalanceParsedInYuanAndRefill(t *testing.T) {
|
||||
for _, in := range []string{"¥100", "¥100", "100cny", "100 CNY", "100 rmb", "100元", "cny 100", "¥1,00"} {
|
||||
b, err := ParseOwnBalance(in)
|
||||
if err != nil || b == nil || b.CNY == nil || *b.CNY != 100 || b.USD != 0 {
|
||||
t.Errorf("%q: %+v %v, want ¥100", in, b, err)
|
||||
}
|
||||
}
|
||||
if b, err := ParseOwnBalance("12 usd"); err != nil || b.CNY != nil || b.USD != 12 {
|
||||
t.Errorf("12 usd: %+v %v", b, err)
|
||||
}
|
||||
for _, in := range []string{"¥-1", "¥lots", "¥", "¥2000000"} {
|
||||
if _, err := ParseOwnBalance(in); err == nil {
|
||||
t.Errorf("%q taken", in)
|
||||
}
|
||||
}
|
||||
for in, want := range map[string]Refill{"monthly": {RefillMonth, 1}, "monthly:15": {RefillMonth, 15}, "weekly": {RefillWeek, 1},
|
||||
"weekly:fri": {RefillWeek, 5}, "weekly:Sunday": {RefillWeek, 7}, "weekly:3": {RefillWeek, 3}} {
|
||||
if r, err := ParseRefill(in); err != nil || r == nil || *r != want {
|
||||
t.Errorf("%q: %+v %v, want %+v", in, r, err, want)
|
||||
}
|
||||
if r, _ := ParseRefill(want.String()); r == nil || *r != want {
|
||||
t.Errorf("%+v as %q reads back %+v", want, want.String(), r)
|
||||
}
|
||||
}
|
||||
if r, err := ParseRefill("off"); err != nil || r != nil {
|
||||
t.Errorf("off: %+v %v", r, err)
|
||||
}
|
||||
for _, in := range []string{"monthly:0", "monthly:32", "monthly:x", "weekly:x", "yearly", "--help"} {
|
||||
if _, err := ParseRefill(in); err == nil {
|
||||
t.Errorf("%q taken", in)
|
||||
}
|
||||
}
|
||||
n := normalKeyOwnBalances(map[string]OwnBalance{"a": {USD: 5, Refill: &Refill{"year", 1}}})
|
||||
if n["a"].USD != 5 || n["a"].Refill != nil {
|
||||
t.Errorf("a refill that isn't one, written by hand: %+v", n)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user