provider: a key's typed balance can refill each day (Kelen_Yc on X)

A key's balance typed by hand refilled each month or each week. A relay
key with a daily allowance had no way to say so. Now it can refill each
day, at local midnight, like the others:

- provider: Refill{Every: "day", Day: 0} (RefillDay). Last is today's
  midnight in now's location, Next tomorrow's. check takes it with day 0
  only; ParseRefill reads daily/day/d (daily:1 refused); String is
  "daily". A magpie before this drops such a refill on read, as one
  written by hand that isn't one, and counts from when it was typed.
- CLI: `magpie provider key-balance <id> <key> --refill daily`; usage
  lines updated.
- GUI: the pill's menu has "Refills each day" after "Refills each
  week…", posting {every: day, day: 0} at once (no day to pick, so no
  ellipsis), with its toast; en, zh, zh-TW, ja, de.
- docs/subsystems/providers-accounts.md names it.

Tests: TestRefillDays gains daily rows (midday, exactly midnight, a
month's and a year's end, Asia/Shanghai). New
TestTypedBalanceRefillsDaily holds the clock in Pacific/Kiritimati
(UTC+14), Pacific/Pago_Pago (UTC-11) and UTC: a minute before local
midnight the spend counts from when it was typed, a minute after it
counts from local midnight and the next refill is the following one.
TestOwnBalanceParsedInYuanAndRefill and TestTypedBalanceRefills cover
parsing, the bad {day, 1}, and read-back; TestKeyBalanceCmd sets
--refill daily. key-own-balance.test.cjs picks Refills each day in
every language, both engines, 900 and 400px, checks the post and that
the menu then shows it picked.

Run on mica at 889758605 + this: go test -count=1
./internal/provider ./internal/cli ./internal/gui ok; go vet darwin,
GOOS=linux -tags nogui, GOOS=windows ok; gofmt clean; GUI
key-own-balance, i18n-keys, i18n-en-no-cjk, key-balance-expiring in
chromium and webkit ok (48/48). Rebased on c5adcbaab (library, site;
nothing of this change's files), then at the pushed head: go test
./internal/gui, ./internal/provider -run Refill|TypedBalance|OwnBalance|
KeyOwnBalance|Budget ok, i18n-keys and i18n-en-no-cjk ok. key-balance-card is red in de at 560px
(view-usage 635>560) in both engines on the clean base 889758605 too:
#6414.

Broken by hand: daily Last taken from UTC's midnight instead of local:
TestRefillDays and TestTypedBalanceRefillsDaily (Kiritimati) red.

Not tried: the real app with a real relay key; the full suite (started
after the tag).
This commit is contained in:
yetone
2026-11-13 11:59:54 +08:00
parent a095e40279
commit 70f4593e62
9 changed files with 125 additions and 22 deletions
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/yetone/magpie/internal/provider"
)
const keyBalanceUsage = "magpie provider key-balance <id> [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|off] [--expiring amount@yyyy-mm-dd|off]… [--expiring-remove [amount@]yyyy-mm-dd]…]"
const keyBalanceUsage = "magpie provider key-balance <id> [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|daily|off] [--expiring amount@yyyy-mm-dd|off]… [--expiring-remove [amount@]yyyy-mm-dd]…]"
// 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
+9
View File
@@ -60,6 +60,15 @@ func TestKeyBalanceCmd(t *testing.T) {
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)
}
if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--refill", "daily"}); err != nil {
t.Fatal(err)
}
if b, _ := typed(); b.CNY == nil || *b.CNY != 700 || b.Refill == nil || *b.Refill != (provider.Refill{Every: provider.RefillDay}) {
t.Fatalf("daily: %+v", b)
}
if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--refill=weekly:fri"}); err != nil {
t.Fatal(err)
}
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)
+1 -1
View File
@@ -108,7 +108,7 @@ 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|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|off] [--expiring amount@yyyy-mm-dd|off]… [--expiring-remove [amount@]yyyy-mm-dd]…]
magpie provider key-balance <id> [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|daily|off] [--expiring amount@yyyy-mm-dd|off]… [--expiring-remove [amount@]yyyy-mm-dd]…]
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;
+8
View File
@@ -147,12 +147,14 @@ const I18N = {
"No credit that expires": "去掉限期额度",
"Refills each month…": "每月恢复…",
"Refills each week…": "每周恢复…",
"Refills each day": "每日恢复",
"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 each day": "{who} 每日恢复余额",
"{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": "消费上限",
@@ -5300,12 +5302,14 @@ const I18N = {
"No credit that expires": "去掉限期額度",
"Refills each month…": "每月恢復…",
"Refills each week…": "每週恢復…",
"Refills each day": "每日恢復",
"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 each day": "{who} 每日恢復餘額",
"{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": "消費上限",
@@ -10438,12 +10442,14 @@ const I18N = {
"No credit that expires": "期限付きクレジットなし",
"Refills each month…": "毎月戻す…",
"Refills each week…": "毎週戻す…",
"Refills each day": "毎日戻す",
"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 each day": "{who} の残高は毎日戻ります",
"{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": "支出上限",
@@ -15578,12 +15584,14 @@ const I18N = {
"No credit that expires": "Kein ablaufendes Guthaben",
"Refills each month…": "Monatlich auffüllen…",
"Refills each week…": "Wöchentlich auffüllen…",
"Refills each day": "Täglich 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 each day": "{who} wird jeden Tag 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",
+5 -1
View File
@@ -4,7 +4,8 @@
// own usage prices the calls it sends on the key (provider/
// key_balance_own.go). Typing it again sets it anew. It may be typed in
// yuan ("¥100", or picked beside the field, which starts at the balance's
// own currency, else Settings' one), and may refill each month or week.
// own currency, else Settings' one), and may refill each month, week or
// day (Kelen_Yc on X).
// Credit may come on top that expires on a day, in grants (promotional
// credit twice, gone on two days: tenacious_eagle_96548), the one that
// goes soonest spent first: the pill says how much of each is left and in
@@ -71,6 +72,7 @@ function keyBalancePill(p, k) {
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) })
: r.every === "day" ? t("{who} refills each day", { who: name })
: t("{who} refills on day {day} of each month", { who: name, day: r.day }));
const expiring = (v) => accountAction("provider/keyexpiring", { id: p.id, account: k.id, expiring: v },
!v ? t("{who} has no credit that expires", { who: name }) : t("{who} has {amount} that counts through {last}", { who: name, amount: moneyText(v.amount, cny), last: dateText(v.until) }));
@@ -187,9 +189,11 @@ function keyBalancePill(p, k) {
...xs.length > 1 || b.expired ? [{ v: "noexp", name: "No credit that expires", note: "" }] : [],
{ v: "month", name: "Refills each month…", note: "" },
{ v: "week", name: "Refills each week…", note: "" },
{ v: "day", name: "Refills each day", note: "" },
{ v: "never", name: "Never refills", note: "" },
{ v: "off", name: "No balance", note: "" },
], b.refill?.every || "never", (v) => v === "off" ? set(null) : v === "exp" ? credit() : v === "noexp" ? expiring(null) : v === "month" ? monthly() : v === "week" ? weekly()
: v === "day" ? refill({ every: "day", day: 0 })
: v === "never" ? b.refill && refill(null) : v[0] === "x" ? unexpiring(xs[+v.slice(1)]) : type(), "Balance", "sess-menu");
// a grant that goes within a week says so in amber, as on the pill
const items = protoMenu?.box.querySelectorAll(".pm-item");
+21 -6
View File
@@ -67,11 +67,11 @@ function serve(lang, posts) {
}
const words = {
en: { currency: "Currency", yuan40: "≈¥40.00 left", usd100: "≈$100.00 left", 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 -1,000,000 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: { currency: "货币", yuan40: "≈¥40.00 剩余", usd100: "≈$100.00 剩余", k1: "≈$12.50 剩余", none: "设置余额", menu: "余额", enter: "填写余额…", off: "无余额", k2: "≈$5.00 剩余", k1again: "≈$40.00 剩余", yuan: "≈¥100.00 剩余", bad: "余额是 -1,000,000 到 1,000,000 之间的金额,美元或人民币(¥)", month: "每月恢复…", week: "每周恢复…", never: "不恢复", on: "恢复于", refills: "恢复为 $40.00" },
"zh-TW": { currency: "貨幣", yuan40: "≈¥40.00 剩餘", usd100: "≈$100.00 剩餘", k1: "≈$12.50 剩餘", none: "設定餘額", menu: "餘額", enter: "填寫餘額…", off: "無餘額", k2: "≈$5.00 剩餘", k1again: "≈$40.00 剩餘", yuan: "≈¥100.00 剩餘", bad: "餘額是 -1,000,000 到 1,000,000 之間的金額,美元或人民幣(¥)", month: "每月恢復…", week: "每週恢復…", never: "不恢復", on: "恢復於", refills: "恢復為 $40.00" },
ja: { currency: "通貨", yuan40: "残り ≈¥40.00", usd100: "残り ≈$100.00", k1: "残り ≈$12.50", none: "残高を設定", menu: "残高", enter: "残高を入力…", off: "残高なし", k2: "残り ≈$5.00", k1again: "残り ≈$40.00", yuan: "残り ≈¥100.00", bad: "残高は -1,000,000 から 1,000,000 までの金額です(USD または人民元 ¥)", month: "毎月戻す…", week: "毎週戻す…", never: "戻さない", on: "戻す曜日", refills: "$40.00 へ戻る" },
de: { currency: "Währung", yuan40: "≈¥40.00 übrig", usd100: "≈$100.00 übrig", 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 -1.000.000 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" },
en: { currency: "Currency", yuan40: "≈¥40.00 left", usd100: "≈$100.00 left", 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 -1,000,000 to 1,000,000, in USD or in yuan (¥)", month: "Refills each month…", week: "Refills each week…", day: "Refills each day", never: "Never refills", on: "Refills on", refills: "Refills to $40.00 on" },
zh: { currency: "货币", yuan40: "≈¥40.00 剩余", usd100: "≈$100.00 剩余", k1: "≈$12.50 剩余", none: "设置余额", menu: "余额", enter: "填写余额…", off: "无余额", k2: "≈$5.00 剩余", k1again: "≈$40.00 剩余", yuan: "≈¥100.00 剩余", bad: "余额是 -1,000,000 到 1,000,000 之间的金额,美元或人民币(¥)", month: "每月恢复…", week: "每周恢复…", day: "每日恢复", never: "不恢复", on: "恢复于", refills: "恢复为 $40.00" },
"zh-TW": { currency: "貨幣", yuan40: "≈¥40.00 剩餘", usd100: "≈$100.00 剩餘", k1: "≈$12.50 剩餘", none: "設定餘額", menu: "餘額", enter: "填寫餘額…", off: "無餘額", k2: "≈$5.00 剩餘", k1again: "≈$40.00 剩餘", yuan: "≈¥100.00 剩餘", bad: "餘額是 -1,000,000 到 1,000,000 之間的金額,美元或人民幣(¥)", month: "每月恢復…", week: "每週恢復…", day: "每日恢復", never: "不恢復", on: "恢復於", refills: "恢復為 $40.00" },
ja: { currency: "通貨", yuan40: "残り ≈¥40.00", usd100: "残り ≈$100.00", k1: "残り ≈$12.50", none: "残高を設定", menu: "残高", enter: "残高を入力…", off: "残高なし", k2: "残り ≈$5.00", k1again: "残り ≈$40.00", yuan: "残り ≈¥100.00", bad: "残高は -1,000,000 から 1,000,000 までの金額です(USD または人民元 ¥)", month: "毎月戻す…", week: "毎週戻す…", day: "毎日戻す", never: "戻さない", on: "戻す曜日", refills: "$40.00 へ戻る" },
de: { currency: "Währung", yuan40: "≈¥40.00 übrig", usd100: "≈$100.00 übrig", 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 -1.000.000 bis 1.000.000, in USD oder in Yuan (¥)", month: "Monatlich auffüllen…", week: "Wöchentlich auffüllen…", day: "Täglich 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"])) {
@@ -196,7 +196,7 @@ 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);
// k1 refills on a day of each month, then each Friday, then never
// k1 refills on a day of each month, then each Friday, then each day, then never
await still("k1");
await menu.waitFor();
await item(w.month).click();
@@ -233,6 +233,21 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
p = await posted(n);
assert.deepEqual(p.body, { id: "relay", account: "k1", refill: { every: "week", day: 5 } });
await page.waitForTimeout(250);
// each day (Kelen_Yc on X): picked at once, no day to choose, and
// the menu shows it picked
await still("k1");
await menu.waitFor();
n = posts.length;
await item(w.day).click();
p = await posted(n);
assert.deepEqual(p.body, { id: "relay", account: "k1", refill: { every: "day", day: 0 } });
await page.waitForTimeout(250);
assert.equal(await page.locator(".proto-menu").count(), 0, "a daily refill asked for more");
await still("k1");
await menu.waitFor();
assert.equal(await item(w.day).getAttribute("aria-checked"), "true");
await page.keyboard.press("Escape");
await page.waitForTimeout(200);
await still("k1");
await menu.waitFor();
n = posts.length;
+25 -8
View File
@@ -16,8 +16,9 @@ package provider
// 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.
// at midnight local time on a day of the month or of the week, or every
// midnight (Kelen_Yc on X: a relay key with a daily allowance), the
// amount typed is whole again and the spend counted from then.
// It may have credit that expires on top of it (the same user: some
// vendors split a balance into money that stays and credit good until a
@@ -118,7 +119,7 @@ func (b OwnBalance) Amount() (float64, string) {
// 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).
// each week (1 Monday to 7 Sunday), or each day (Day 0).
type Refill struct {
Every string `json:"every"`
Day int `json:"day"`
@@ -128,12 +129,16 @@ type Refill struct {
const (
RefillMonth = "month"
RefillWeek = "week"
RefillDay = "day"
)
// 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 == RefillDay {
return time.Date(y, m, d, 0, 0, 0, 0, loc)
}
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)
@@ -149,6 +154,9 @@ func (r Refill) Last(now time.Time) time.Time {
func (r Refill) Next(now time.Time) time.Time {
l := r.Last(now)
y, m, d := l.Date()
if r.Every == RefillDay {
return time.Date(y, m, d+1, 0, 0, 0, 0, l.Location())
}
if r.Every == RefillWeek {
return time.Date(y, m, d+7, 0, 0, 0, 0, l.Location())
}
@@ -167,14 +175,18 @@ 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:
case r.Every == RefillDay && r.Day == 0:
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 fmt.Errorf("a balance refills each month on a day from 1 to 31, each week on a day from 1 (Monday) to 7 (Sunday), or each day (day 0), not %s %d", r.Every, r.Day)
}
return nil
}
// String is r as the CLI takes and shows it: monthly:1, weekly:mon.
// String is r as the CLI takes and shows it: monthly:1, weekly:mon, daily.
func (r Refill) String() string {
if r.Every == RefillDay {
return "daily"
}
if r.Every == RefillWeek {
return "weekly:" + strings.ToLower(time.Weekday(r.Day % 7).String()[:3])
}
@@ -746,8 +758,8 @@ func ParseOwnBalance(amount string) (*OwnBalance, error) {
}
// 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).
// monthly:15, weekly (on Monday), weekly:fri or weekly:5, daily (each
// midnight); off or never for none (nil).
func ParseRefill(s string) (*Refill, error) {
a := strings.ToLower(strings.TrimSpace(s))
switch a {
@@ -755,7 +767,7 @@ func ParseRefill(s string) (*Refill, error) {
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)
bad := fmt.Errorf("a refill is monthly[:day 1-31], weekly[:mon…sun], daily or off, not %q", s)
var r Refill
switch every {
case "monthly", "month", "m":
@@ -767,6 +779,11 @@ func ParseRefill(s string) (*Refill, error) {
}
r.Day = n
}
case "daily", "day", "d":
if day != "" {
return nil, bad
}
r = Refill{Every: RefillDay}
case "weekly", "week", "w":
r = Refill{Every: RefillWeek, Day: 1}
if day != "" {
+54 -4
View File
@@ -344,7 +344,7 @@ func TestTypedBalanceRefills(t *testing.T) {
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}} {
for _, bad := range []Refill{{RefillMonth, 0}, {RefillMonth, 32}, {RefillWeek, 8}, {"year", 1}, {RefillDay, 1}} {
if err := SetKeyBalanceRefill("monthly", keyID("sk-r"), &bad); err == nil {
t.Errorf("%+v taken", bad)
}
@@ -357,6 +357,47 @@ func TestTypedBalanceRefills(t *testing.T) {
}
}
// A balance that refills each day (Kelen_Yc on X: a relay key with a
// daily allowance) is whole again at local midnight, not UTC's: held in
// UTC+14 and UTC-11, where the local day and UTC's differ, the spend is
// counted from the midnight just past and the next is the one after.
func TestTypedBalanceRefillsDaily(t *testing.T) {
probeSandbox(t)
probeLocal = false
asked := spentStub(t, map[string]float64{keyID("sk-d"): 2})
if err := Save(Provider{ID: "daily", Name: "Daily", Chat: "http://127.0.0.1:1/v1", Key: "sk-d"}); err != nil {
t.Fatal(err)
}
for _, zone := range []string{"Pacific/Kiritimati", "Pacific/Pago_Pago", "UTC"} {
loc, err := time.LoadLocation(zone)
if err != nil {
t.Fatal(err)
}
typed := time.Date(2026, 11, 12, 9, 0, 0, 0, loc)
clockStub(t, typed)
if err := SetKeyOwnBalance("daily", keyID("sk-d"), &OwnBalance{USD: 5, Refill: &Refill{Every: RefillDay}}); err != nil {
t.Fatal(err)
}
// the same local day, a minute before midnight: from when typed
clockStub(t, time.Date(2026, 11, 12, 23, 59, 0, 0, loc))
p, _ := Find("daily")
e, _ := p.OwnBalanceEstimate(keyID("sk-d"))
if !e.From.Equal(typed) || *e.Left != 3 || !e.Next.Equal(time.Date(2026, 11, 13, 0, 0, 0, 0, loc)) {
t.Fatalf("%s before midnight: from %v next %v left %v", zone, e.From, e.Next, *e.Left)
}
// a minute past local midnight: whole again, counted from then
clockStub(t, time.Date(2026, 11, 13, 0, 1, 0, 0, loc))
q := ownCards(t)["daily|"]
mid := time.Date(2026, 11, 13, 0, 0, 0, 0, loc)
if !q.Estimate.From.Equal(mid) || !asked[keyID("sk-d")].Equal(mid) || q.Balance != "≈$3.00" {
t.Fatalf("%s after midnight: %+v from %v, asked from %v", zone, q, q.Estimate.From, asked[keyID("sk-d")])
}
if !q.Estimate.Next.Equal(time.Date(2026, 11, 14, 0, 0, 0, 0, loc)) {
t.Errorf("%s next refill %v", zone, q.Estimate.Next)
}
}
}
// 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) {
@@ -381,6 +422,12 @@ func TestRefillDays(t *testing.T) {
{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)},
// each day (Kelen_Yc on X): the midnight before, the one after,
// across a month's and a year's end
{Refill{RefillDay, 0}, at(2026, 11, 8, 10), at(2026, 11, 8, 0), at(2026, 11, 9, 0)},
{Refill{RefillDay, 0}, at(2026, 11, 8, 0), at(2026, 11, 8, 0), at(2026, 11, 9, 0)},
{Refill{RefillDay, 0}, at(2026, 11, 30, 23), at(2026, 11, 30, 0), at(2026, 12, 1, 0)},
{Refill{RefillDay, 0}, at(2026, 12, 31, 23), at(2026, 12, 31, 0), at(2027, 1, 1, 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)
@@ -416,7 +463,7 @@ func TestOwnBalanceParsedInYuanAndRefill(t *testing.T) {
}
}
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}} {
"weekly:fri": {RefillWeek, 5}, "weekly:Sunday": {RefillWeek, 7}, "weekly:3": {RefillWeek, 3}, "daily": {RefillDay, 0}, "Day": {RefillDay, 0}} {
if r, err := ParseRefill(in); err != nil || r == nil || *r != want {
t.Errorf("%q: %+v %v, want %+v", in, r, err, want)
}
@@ -427,15 +474,18 @@ func TestOwnBalanceParsedInYuanAndRefill(t *testing.T) {
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"} {
for _, in := range []string{"monthly:0", "monthly:32", "monthly:x", "weekly:x", "yearly", "--help", "daily:1"} {
if _, err := ParseRefill(in); err == nil {
t.Errorf("%q taken", in)
}
}
n := normalKeyOwnBalances(map[string]OwnBalance{"a": {USD: 5, Refill: &Refill{"year", 1}}})
n := normalKeyOwnBalances(map[string]OwnBalance{"a": {USD: 5, Refill: &Refill{"year", 1}}, "b": {USD: 5, Refill: &Refill{RefillDay, 0}}})
if n["a"].USD != 5 || n["a"].Refill != nil {
t.Errorf("a refill that isn't one, written by hand: %+v", n)
}
if n["b"].Refill == nil || *n["b"].Refill != (Refill{RefillDay, 0}) {
t.Errorf("a daily refill was dropped as read back: %+v", n["b"])
}
}
// spendAt stubs usage.KeySpent with calls at given times: what the key