day-card: a week, a month or all time as a receipt, with a Day/Week/Month/All switch (HeheLi29136651 on X)

usage:day takes a from (magpie with usage:day's span read); the page asks for the seven or thirty days ending on the date shown, or all, and prints the period, the days that had calls and the cost of one, in place of the streak against an average day. Arrows step a whole week or month. A magpie that answers a day and no from says to update. 0.3.0.

Run: bun test packages/day-card (17 pass, the new test red before the view change).
This commit is contained in:
yetone
2026-11-11 17:42:08 +08:00
parent 93cb4fe1c0
commit eaeca41125
7 changed files with 127 additions and 25 deletions
+5 -5
View File
@@ -1,14 +1,14 @@
# @magpie-community/page-day-card
A page in [magpie](https://usemagpie.ai)'s window that prints a day of your AI usage as a receipt, a "Daily AI statement" on paper over a backdrop of your choice. It has the day's API-equivalent cost, your streak, requests, errors and the day against your average day before it, then each agent and its models with their logos and costs, and the day's tokens: input, output and the cache hit rate. Its foot credits [nowdex](https://nowdex.app), whose share card the receipt's design follows. **Background** picks what the paper lies on: nothing (the paper alone, a transparent PNG), teal, fifteen patterns (gingham, graph paper, kraft, cyanotype, seigaiha waves, xuan paper and more), four landscape photos, or a picture of your own (pick one, drop it on the page or paste it). A slider sets the margin around the paper; a photo also has blur and dim. The choice is kept in the plugin's options. **Copy image** puts the card on the clipboard; **Save PNG** saves it in Downloads.
A page in [magpie](https://usemagpie.ai)'s window that prints a day of your AI usage (or a week, a month or all of it) as a receipt, a "Daily AI statement" on paper over a backdrop of your choice. It has the day's API-equivalent cost, your streak, requests, errors and the day against your average day before it, then each agent and its models with their logos and costs, and the day's tokens: input, output and the cache hit rate. Its foot credits [nowdex](https://nowdex.app), whose share card the receipt's design follows. **Background** picks what the paper lies on: nothing (the paper alone, a transparent PNG), teal, fifteen patterns (gingham, graph paper, kraft, cyanotype, seigaiha waves, xuan paper and more), four landscape photos, or a picture of your own (pick one, drop it on the page or paste it). A slider sets the margin around the paper; a photo also has blur and dim. The choice is kept in the plugin's options. **Copy image** puts the card on the clipboard; **Save PNG** saves it in Downloads.
Install it from magpie's **Plugins › Discover**, or with `magpie plugin add @magpie-community/page-day-card`. It then has a tab, **Day card** (titled in the window's language: 每日用量卡, 1日の使用量カード, Tageskarte), under Plugins in the sidebar, in the app and in `magpie web`. Pick an earlier day with the arrows or the date's menu. The card is shown as large as fits under the toolbar, so a whole day is on one screen; the picture you copy or save is full size.
Install it from magpie's **Plugins › Discover**, or with `magpie plugin add @magpie-community/page-day-card`. It then has a tab, **Day card** (titled in the window's language: 每日用量卡, 1日の使用量カード, Tageskarte), under Plugins in the sidebar, in the app and in `magpie web`. The switch at the left picks **Day**, **Week** (the seven days ending on the date shown), **Month** (the thirty) or **All** (every day with calls, up to today); a week's or a month's card has its period, the days that had calls and the cost of one such day in place of the streak against an average day. Pick an earlier day, or the date a week or month ends on, with the arrows (which step a whole week or month) or the date's menu. The card is shown as large as fits under the toolbar, so a whole day is on one screen; the picture you copy or save is full size.
It needs a magpie with the `usage:day` read and `magpie.image` (see `engines.magpie`). An older magpie refuses the read, and the page says to update.
It needs a magpie with the `usage:day` read and `magpie.image` (see `engines.magpie`). An older magpie refuses the read, and the page says to update; one from before the week, month and all-time spans (a `from` in `usage:day`) shows days only, and says to update when you pick another.
## What it reads
Only `usage:day`, the one permission its `package.json` declares (`magpie.permissions`): a day's totals, each agent's and model's, the days before it that had calls, and the agents' and providers' logos. Nothing in it is a key, an account, a session or a prompt.
Only `usage:day`, the one permission its `package.json` declares (`magpie.permissions`): a day's (or a span's) totals, each agent's and model's, the days before it that had calls, and the agents' and providers' logos. Nothing in it is a key, an account, a session or a prompt.
Like every plugin page, it runs in a sandboxed frame with no network (`connect-src 'none'`) and no inline scripts. The card is drawn on a canvas, the same in a light or dark theme, and its PNG goes to magpie through `_magpie/bridge.js`. In `magpie web` the browser copies or downloads it itself.
@@ -27,4 +27,4 @@ Like every plugin page, it runs in a sandboxed frame with no network (`connect-s
bun test packages/day-card
```
中文:在 magpie 窗口里加一个「每日用量卡」页面,把某一天的用量打印成一张小票(Daily AI Statement):当天按 API 价计的费用、连续使用天数、请求数、错误数、与此前日均的倍数,每个 Agent 及其模型(带图标和费用),以及输入、输出 token 和缓存命中率。小票底部注明设计灵感来自 [nowdex](https://nowdex.app)。「背景」可以换成 15 种图案、4 张风景照片或自己的图片(选择、拖入或粘贴),边距可调,照片还可调模糊和压暗。可以「复制图片」到剪贴板,或「保存 PNG」到下载文件夹。只读取声明过的 `usage:day`,运行在无网络的沙盒 frame 里。
中文:在 magpie 窗口里加一个「每日用量卡」页面,把某一天(或最近 7 天、30 天、全部)的用量打印成一张小票(Daily AI Statement):当天按 API 价计的费用、连续使用天数、请求数、错误数、与此前日均的倍数,每个 Agent 及其模型(带图标和费用),以及输入、输出 token 和缓存命中率。小票底部注明设计灵感来自 [nowdex](https://nowdex.app)。「背景」可以换成 15 种图案、4 张风景照片或自己的图片(选择、拖入或粘贴),边距可调,照片还可调模糊和压暗。左上角的开关切换「日 / 周 / 月 / 全部」。可以「复制图片」到剪贴板,或「保存 PNG」到下载文件夹。只读取声明过的 `usage:day`,运行在无网络的沙盒 frame 里。
+21
View File
@@ -119,6 +119,27 @@ test("the receipt: title, the day, its cost, then its parts", () => {
for (const lang of Object.keys(V.TEXT)) expect(V.card(day, lang, {}, now).credit).toContain("nowdex.app")
})
test("a week, a month or all time is a receipt of its own", () => {
const span = { ...day, from: "2026-11-03", days: [{ date: "2026-11-03", calls: 5, tokens: 10, cost: 1 }, { date: "2026-11-07", calls: 5, tokens: 10, cost: 1 }, { date: "2026-11-08", calls: 5, tokens: 10, cost: 1 }, { date: "2026-11-09", calls: 5, tokens: 10, cost: 1 }] }
const w = V.card(span, "en", { span: "week" }, now)
expect(w.title).toBe("WEEKLY AI STATEMENT")
expect(w.head[0]).toEqual({ label: "PERIOD", value: "NOV 3, 2026 – NOV 9, 2026" })
// 4 of the 7 days had calls, and $12.345 over them
expect(w.stats.slice(-2)).toEqual([{ label: "ACTIVE DAYS", value: "4 / 7" }, { label: "AVG ACTIVE DAY", value: "$3.09" }])
expect(w.stats.map((s) => s.label)).not.toContain("VS AVERAGE DAY")
expect(V.card(span, "en", { span: "month" }, now).title).toBe("MONTHLY AI STATEMENT")
const a = V.card(span, "zh", { span: "all" }, now)
expect(a.title).toBe("累计 AI 账单")
expect(a.stats.slice(-2)[0]).toEqual({ label: "活跃天数", value: "4 天" })
expect(V.card({ ...span, calls: 0 }, "en", { span: "week" }, now).empty).toBe("No calls in this period.")
// a magpie that answers a day (no from) draws a day, never a week's title
expect(V.card(day, "en", { span: "week" }, now).title).toBe("DAILY AI STATEMENT")
// what the read is asked, and the steps of the arrows
expect([V.spanFrom("day", "2026-11-09"), V.spanFrom("week", "2026-11-09"), V.spanFrom("month", "2026-11-09"), V.spanFrom("all", "2026-11-09")]).toEqual(["", "2026-11-03", "2026-10-11", "all"])
expect([V.stepDate("week", "2026-11-09", -1, "2026-11-11"), V.stepDate("week", "2026-11-09", 1, "2026-11-11"), V.stepDate("day", "2026-11-09", 1, "2026-11-11")]).toEqual(["2026-11-02", "2026-11-11", "2026-11-10"])
expect([V.fileName("2026-11-09"), V.fileName("2026-11-09", "week", "2026-11-03"), V.fileName("2026-11-09", "all", "2020-01-01")]).toEqual(["magpie 2026-11-09", "magpie 2026-11-03 to 2026-11-09", "magpie all 2026-11-09"])
})
test("agents and their models by cost, each with what was left out", () => {
const withCost = { ...day, agents: day.agents.map((a) => ({ ...a, models: a.models.map((m, i) => ({ ...m, cost: [1, 9][i] ?? 0 })) })) }
const c = V.card(withCost, "en", {}, now)
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "@magpie-community/page-day-card",
"version": "0.2.3",
"description": "A page in magpie's window that draws a day of your AI usage as a card: tokens, cost, each agent and its models, your streak and your average day. Copy it as a picture or save it as a PNG",
"version": "0.3.0",
"description": "A page in magpie's window that draws a day, week, month or all of your AI usage as a card: tokens, cost, each agent and its models, your streak and your average day. Copy it as a picture or save it as a PNG",
"files": ["page", "README.md"],
"keywords": ["magpie", "magpie-page", "usage", "tokens", "cost", "card"],
"license": "MIT",
+38 -12
View File
@@ -1,5 +1,5 @@
// The page: reads usage:day (the only read package.json declares) for the
// day picked, draws it on a canvas as a receipt, and hands that canvas's
// day picked, or the week, month or all time ending on it, draws it on a canvas as a receipt, and hands that canvas's
// PNG to magpie.image to copy or save.
(async () => {
const V = globalThis.DayView;
@@ -8,7 +8,7 @@
const theme = await magpie.ready;
let lang = theme.lang;
const zone = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || ""; } catch { return ""; } })();
const state = { date: "", day: null, icons: new Map(), loading: 0, drawn: 0, bg: B.norm(null) };
const state = { date: "", span: "day", day: null, icons: new Map(), loading: 0, drawn: 0, bg: B.norm(null) };
// ---- words ----
function words() {
@@ -331,7 +331,7 @@
const n = ++state.drawn;
const bg = state.bg;
await fonts;
const c = V.card(day, lang);
const c = V.card(day, lang, { span: state.span });
const icons = new Map();
const [img] = await Promise.all([
backdrop(bg),
@@ -404,8 +404,18 @@
async function load(date) {
const n = ++state.loading;
try {
const day = await magpie.read("usage:day", { date: date || "", tz: zone });
const span = state.span;
const params = { date: date || "", tz: zone };
if (span !== "day") {
// a week or a month ends on a date, so today's is worked out here
const end = date || state.day?.today || new Date().toLocaleDateString("en-CA");
params.date = end;
params.from = V.spanFrom(span, end);
}
const day = await magpie.read("usage:day", params);
if (n !== state.loading) return;
// a magpie from before spans answers one day and no `from`
if (span !== "day" && !day.from) throw new Error("usage:day from");
state.day = day;
state.date = day.date;
status("");
@@ -413,7 +423,7 @@
if (n !== state.loading) return;
const m = String(e?.message || e);
// a magpie from before usage:day refuses it as a read it doesn't have
status(/usage:day/.test(m) ? V.text(lang).update : `${V.text(lang).failed}: ${m}`, true, true);
status(m === "usage:day from" ? V.text(lang).updateSpan : /usage:day/.test(m) ? V.text(lang).update : `${V.text(lang).failed}: ${m}`, true, true);
}
paintBar();
await draw();
@@ -421,10 +431,19 @@
function paintBar() {
const d = state.day;
$("date-text").textContent = d ? V.dateLabel(d.date, lang) : "…";
$("next").disabled = !d || d.date >= d.today;
$("today").disabled = !d || d.date === d.today;
$("prev").disabled = !d;
const t = V.text(lang);
const span = state.span;
$("date-text").textContent = !d ? "…" : span === "all" ? t.allTime : span === "day" || !d.from ? V.dateLabel(d.date, lang) : `${V.dateLabel(d.from, lang, true)} – ${V.dateLabel(d.date, lang, true)}`;
const all = span === "all";
$("next").disabled = !d || all || d.date >= d.today;
$("today").disabled = !d || all || d.date === d.today;
$("prev").disabled = !d || all;
$("date").disabled = all;
for (const [id, key] of [["prev", span === "day" ? "prev" : "earlier"], ["next", span === "day" ? "next" : "later"]]) {
$(id).setAttribute("aria-label", t[key]);
$(id).title = t[key];
}
document.querySelectorAll("#spans [data-span]").forEach((b) => b.setAttribute("aria-checked", String(b.dataset.span === span)));
}
// ---- the day menu: the days that had calls, newest first ----
@@ -472,9 +491,16 @@
document.addEventListener("click", (e) => { if (!e.target.closest(".pick")) closeMenu(); });
document.addEventListener("keydown", (e) => { if (e.key === "Escape") closeMenu(); });
$("prev").addEventListener("click", () => state.date && load(V.shift(state.date, -1)));
$("next").addEventListener("click", () => state.date && state.day && state.date < state.day.today && load(V.shift(state.date, 1)));
$("prev").addEventListener("click", () => state.date && load(V.stepDate(state.span, state.date, -1, state.day?.today || state.date)));
$("next").addEventListener("click", () => state.date && state.day && state.date < state.day.today && load(V.stepDate(state.span, state.date, 1, state.day.today)));
$("today").addEventListener("click", () => load(""));
$("spans").addEventListener("click", (e) => {
const b = e.target.closest("[data-span]");
if (!b || b.dataset.span === state.span) return;
state.span = b.dataset.span;
paintBar();
load(state.date === state.day?.today ? "" : state.date);
});
// ---- the backdrop: a pattern, a photo from bg/, or the reader's picture ----
const images = new Map();
@@ -732,7 +758,7 @@
const b = $("save");
b.disabled = true;
try {
const r = await magpie.image.save(await png(), V.fileName(state.date));
const r = await magpie.image.save(await png(), V.fileName(state.date, state.span, state.day?.from));
if (r?.path) status(`${V.text(lang).saved} ${r.path}`);
} catch (e) {
status(`${V.text(lang).shareFailed}: ${e?.message || e}`, true);
+6
View File
@@ -13,6 +13,12 @@
</head>
<body>
<header>
<div class="spans" id="spans" role="radiogroup" data-t-label="spanLabel">
<button type="button" role="radio" data-span="day" data-t="spanDay">Day</button>
<button type="button" role="radio" data-span="week" data-t="spanWeek">Week</button>
<button type="button" role="radio" data-span="month" data-t="spanMonth">Month</button>
<button type="button" role="radio" data-span="all" data-t="spanAll">All</button>
</div>
<div class="days">
<button type="button" class="step" id="prev" aria-label="Previous day" data-t-label="prev"><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M10 3.5 5.5 8l4.5 4.5"/></svg></button>
<div class="pick">
+3
View File
@@ -10,6 +10,9 @@
html, body { margin: 0; background: var(--bg); color: var(--fg); }
body { padding: 16px 20px 32px; font: 13px/1.45 var(--magpie-font, -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif); }
header { display: flex; align-items: center; justify-content: space-between; gap: 8px 12px; flex-wrap: wrap; max-width: 760px; margin: 0 auto; }
.spans { display: inline-flex; padding: 2px; gap: 2px; background: var(--card); border: 1px solid var(--line); border-radius: 9px; }
.spans button { border: 0; background: transparent; border-radius: 7px; padding: 2px 10px; }
.spans button[aria-checked="true"] { background: var(--bg); box-shadow: 0 0 0 1px var(--line); }
.days, .share { display: flex; align-items: center; gap: 6px; }
button { font: inherit; color: var(--fg); background: var(--card); border: 1px solid var(--line); border-radius: 7px; padding: 4px 10px; cursor: default; transition: border-color .15s ease, transform .12s cubic-bezier(.23, 1, .32, 1); }
button:disabled { color: var(--muted); opacity: .6; }
+52 -6
View File
@@ -19,6 +19,9 @@
noAgent: "NO AGENT NAMED",
today: "Today", prev: "Previous day", next: "Next day", copy: "Copy image", copied: "Copied", save: "Save PNG", saved: "Saved to",
failed: "Couldn't read usage", shareFailed: "Couldn't share the picture", update: "This card needs a newer magpie. Update magpie, then open it again.",
titleWeek: "WEEKLY AI STATEMENT", titleMonth: "MONTHLY AI STATEMENT", titleAll: "ALL-TIME AI STATEMENT", period: "PERIOD", activeDays: "ACTIVE DAYS", avgDay: "AVG ACTIVE DAY",
noCallsSpan: "No calls in this period.", spanDay: "Day", spanWeek: "Week", spanMonth: "Month", spanAll: "All", spanLabel: "Period", earlier: "Earlier", later: "Later", allTime: "All time",
updateSpan: "Week, month and all-time need a newer magpie. Update magpie, then open it again.",
background: "Background", padding: "Padding", blur: "Blur", dim: "Dim", upload: "Add your own picture", imageFailed: "Couldn't use that picture", keepFailed: "Couldn't keep the background",
"bg-none": "No background", "bg-teal": "Teal", "bg-gingham": "Gingham", "bg-grid": "Graph paper", "bg-kraft": "Kraft paper", "bg-cyan": "Cyanotype", "bg-dots": "Night dots", "bg-deck": "Deckchair stripes", "bg-linen": "Olive linen", "bg-seigaiha": "Seigaiha waves", "bg-xuan": "Xuan paper", "bg-zigzag": "Zigzag", "bg-terracotta": "Terracotta", "bg-lilac": "Lilac lines", "bg-velvet": "Green velvet", "bg-polka": "Apricot polka", "bg-alpine": "Alpine dawn", "bg-sea": "Misty shore", "bg-dunes": "Dunes", "bg-lake": "Forest lake", "bg-custom": "Your picture",
},
@@ -35,6 +38,9 @@
noAgent: "未标明 AGENT",
today: "今天", prev: "前一天", next: "后一天", copy: "复制图片", copied: "已复制", save: "保存 PNG", saved: "已保存到",
failed: "读取用量失败", shareFailed: "分享图片失败", update: "这个卡片需要更新版本的 magpie。请更新 magpie 后再打开。",
titleWeek: "每周 AI 账单", titleMonth: "每月 AI 账单", titleAll: "累计 AI 账单", period: "区间", activeDays: "活跃天数", avgDay: "活跃日均",
noCallsSpan: "这段时间没有调用。", spanDay: "日", spanWeek: "周", spanMonth: "月", spanAll: "全部", spanLabel: "统计区间", earlier: "更早", later: "更晚", allTime: "全部时间",
updateSpan: "周、月和全部账单需要更新版本的 magpie。请更新 magpie 后再打开。",
background: "背景", padding: "边距", blur: "模糊", dim: "压暗", upload: "用自己的图片", imageFailed: "这张图片用不了", keepFailed: "背景没能保存",
"bg-none": "无背景", "bg-teal": "青绿", "bg-gingham": "野餐格", "bg-grid": "方格纸", "bg-kraft": "牛皮纸", "bg-cyan": "蓝晒", "bg-dots": "夜色网点", "bg-deck": "躺椅条纹", "bg-linen": "橄榄亚麻", "bg-seigaiha": "青海波", "bg-xuan": "宣纸", "bg-zigzag": "人字纹", "bg-terracotta": "赤陶", "bg-lilac": "雾紫细线", "bg-velvet": "墨绿丝绒", "bg-polka": "杏色波点", "bg-alpine": "雪山晨光", "bg-sea": "雾中海岸", "bg-dunes": "沙丘", "bg-lake": "林间湖", "bg-custom": "自己的图片",
},
@@ -51,6 +57,9 @@
noAgent: "未標明 AGENT",
today: "今天", prev: "前一天", next: "後一天", copy: "複製圖片", copied: "已複製", save: "儲存 PNG", saved: "已儲存到",
failed: "讀取用量失敗", shareFailed: "分享圖片失敗", update: "這張卡片需要更新版本的 magpie。請更新 magpie 後再開啟。",
titleWeek: "每週 AI 帳單", titleMonth: "每月 AI 帳單", titleAll: "累計 AI 帳單", period: "區間", activeDays: "活躍天數", avgDay: "活躍日均",
noCallsSpan: "這段時間沒有呼叫。", spanDay: "日", spanWeek: "週", spanMonth: "月", spanAll: "全部", spanLabel: "統計區間", earlier: "更早", later: "更晚", allTime: "全部時間",
updateSpan: "週、月和全部帳單需要更新版本的 magpie。請更新 magpie 後再開啟。",
background: "背景", padding: "邊距", blur: "模糊", dim: "壓暗", upload: "用自己的圖片", imageFailed: "這張圖片用不了", keepFailed: "背景沒能儲存",
"bg-none": "無背景", "bg-teal": "青綠", "bg-gingham": "野餐格", "bg-grid": "方格紙", "bg-kraft": "牛皮紙", "bg-cyan": "藍曬", "bg-dots": "夜色網點", "bg-deck": "躺椅條紋", "bg-linen": "橄欖亞麻", "bg-seigaiha": "青海波", "bg-xuan": "宣紙", "bg-zigzag": "人字紋", "bg-terracotta": "赤陶", "bg-lilac": "霧紫細線", "bg-velvet": "墨綠絲絨", "bg-polka": "杏色波點", "bg-alpine": "雪山晨光", "bg-sea": "霧中海岸", "bg-dunes": "沙丘", "bg-lake": "林間湖", "bg-custom": "自己的圖片",
},
@@ -67,6 +76,9 @@
noAgent: "エージェント名なし",
today: "今日", prev: "前の日", next: "次の日", copy: "画像をコピー", copied: "コピーしました", save: "PNG を保存", saved: "保存先",
failed: "使用量を読み込めませんでした", shareFailed: "画像を共有できませんでした", update: "このカードには新しい magpie が必要です。magpie を更新してから開き直してください。",
titleWeek: "週間 AI 明細", titleMonth: "月間 AI 明細", titleAll: "累計 AI 明細", period: "期間", activeDays: "稼働日数", avgDay: "稼働日平均",
noCallsSpan: "この期間の呼び出しはありません。", spanDay: "日", spanWeek: "週", spanMonth: "月", spanAll: "全期間", spanLabel: "期間", earlier: "前へ", later: "次へ", allTime: "全期間",
updateSpan: "週・月・全期間には新しい magpie が必要です。magpie を更新してから開き直してください。",
background: "背景", padding: "余白", blur: "ぼかし", dim: "暗さ", upload: "自分の画像を使う", imageFailed: "この画像は使えません", keepFailed: "背景を保存できませんでした",
"bg-none": "背景なし", "bg-teal": "ティール", "bg-gingham": "ギンガム", "bg-grid": "方眼紙", "bg-kraft": "クラフト紙", "bg-cyan": "青写真", "bg-dots": "夜のドット", "bg-deck": "デッキチェア", "bg-linen": "オリーブリネン", "bg-seigaiha": "青海波", "bg-xuan": "宣紙", "bg-zigzag": "ジグザグ", "bg-terracotta": "テラコッタ", "bg-lilac": "ライラック", "bg-velvet": "深緑ベルベット", "bg-polka": "アプリコット水玉", "bg-alpine": "雪山の朝", "bg-sea": "霧の海辺", "bg-dunes": "砂丘", "bg-lake": "森の湖", "bg-custom": "自分の画像",
},
@@ -83,6 +95,9 @@
noAgent: "OHNE AGENT",
today: "Heute", prev: "Vorheriger Tag", next: "Nächster Tag", copy: "Bild kopieren", copied: "Kopiert", save: "PNG sichern", saved: "Gesichert in",
failed: "Nutzung nicht lesbar", shareFailed: "Bild nicht teilbar", update: "Diese Karte braucht ein neueres magpie. Aktualisiere magpie und öffne sie dann erneut.",
titleWeek: "WÖCHENTLICHE KI-ABRECHNUNG", titleMonth: "MONATLICHE KI-ABRECHNUNG", titleAll: "GESAMTE KI-ABRECHNUNG", period: "ZEITRAUM", activeDays: "AKTIVE TAGE", avgDay: "Ø AKTIVER TAG",
noCallsSpan: "In diesem Zeitraum keine Aufrufe.", spanDay: "Tag", spanWeek: "Woche", spanMonth: "Monat", spanAll: "Alle", spanLabel: "Zeitraum", earlier: "Früher", later: "Später", allTime: "Gesamte Zeit",
updateSpan: "Woche, Monat und Gesamt brauchen ein neueres magpie. Aktualisiere magpie und öffne die Karte dann erneut.",
background: "Hintergrund", padding: "Rand", blur: "Weichzeichnen", dim: "Abdunkeln", upload: "Eigenes Bild wählen", imageFailed: "Dieses Bild geht nicht", keepFailed: "Hintergrund nicht gesichert",
"bg-none": "Kein Hintergrund", "bg-teal": "Türkis", "bg-gingham": "Vichy-Karo", "bg-grid": "Millimeterpapier", "bg-kraft": "Packpapier", "bg-cyan": "Cyanotypie", "bg-dots": "Nachtpunkte", "bg-deck": "Liegestuhlstreifen", "bg-linen": "Olivleinen", "bg-seigaiha": "Seigaiha", "bg-xuan": "Xuan-Papier", "bg-zigzag": "Zickzack", "bg-terracotta": "Terrakotta", "bg-lilac": "Fliederlinien", "bg-velvet": "Grüner Samt", "bg-polka": "Aprikosenpunkte", "bg-alpine": "Alpenmorgen", "bg-sea": "Nebelküste", "bg-dunes": "Dünen", "bg-lake": "Waldsee", "bg-custom": "Eigenes Bild",
},
@@ -170,6 +185,28 @@
}
}
// "NOV 5, 2026 – NOV 11, 2026": a span's dates on the receipt
function receiptRange(from, date, lang) {
return `${receiptDate(from, lang)} – ${receiptDate(date, lang)}`;
}
// the days a span covers: a week is the seven days ending at the date, a
// month the thirty, all time every day with calls up to it. `from` is
// what usage:day is asked ("" for a day alone)
const SPANS = ["day", "week", "month", "all"];
const SPAN_DAYS = { day: 1, week: 7, month: 30 };
function spanFrom(span, date) {
if (span === "all") return "all";
const n = SPAN_DAYS[span];
return n > 1 ? shift(date, 1 - n) : "";
}
// the date a step of the span ends on, never past today
function stepDate(span, date, dir, today) {
const n = SPAN_DAYS[span] || 1;
const to = shift(date, dir * n);
return to > today ? today : to;
}
// when the card was drawn: "NOV 9, 2026 AT 23:04", by this computer's clock
function issued(now, lang) {
const p = (n) => String(n).padStart(2, "0");
@@ -243,17 +280,26 @@
};
});
const hiddenAgents = Math.max(0, agents.length - maxAgents) + (Number(day.moreAgents) || 0);
const span = limits.span && limits.span !== "day" && day.from ? limits.span : "day";
const stats = [
{ label: t.streak, value: t.days(streak(day.days, day.date, day.today)) },
{ label: t.requests, value: calls.toLocaleString("en-US") },
];
if (errors) stats.push({ label: t.errors, value: errors.toLocaleString("en-US") });
stats.push({ label: t.vsAverage, value: versus(day, average(day.days, day.date)) });
if (span === "day") {
stats.push({ label: t.vsAverage, value: versus(day, average(day.days, day.date)) });
} else {
// the days of the span that had calls, and what one of them cost
const had = (day.days || []).filter((d) => d.date >= day.from && d.date <= day.date && Number(d.calls) > 0).length;
const length = span === "all" ? had : SPAN_DAYS[span];
stats.push({ label: t.activeDays, value: span === "all" ? t.days(had) : `${had} / ${length}` });
stats.push({ label: t.avgDay, value: had ? money((Number(day.cost) || 0) / had, cur, rate) : money(0, cur, rate) });
}
return {
title: t.title,
title: span === "day" ? t.title : t[{ week: "titleWeek", month: "titleMonth", all: "titleAll" }[span]],
tagline: t.tagline,
head: [
{ label: t.date, value: receiptDate(day.date, lang) },
span === "day" ? { label: t.date, value: receiptDate(day.date, lang) } : { label: t.period, value: receiptRange(day.from, day.date, lang) },
{ label: t.issued, value: issued(now, lang) },
],
totalLabel: t.total,
@@ -270,14 +316,14 @@
{ label: t.hit, value: percent(hitRate(day)) },
],
note: Number(day.unpriced) > 0 ? t.unpriced(Number(day.unpriced)) : "",
empty: calls === 0 ? t.noCalls : "",
empty: calls === 0 ? (span === "day" ? t.noCalls : t.noCallsSpan) : "",
footer: t.footer,
credit: t.credit,
};
}
// the file a saved card is named
const fileName = (date) => `magpie ${date}`;
const fileName = (date, span, from) => (span === "all" ? `magpie all ${date}` : span && span !== "day" && from ? `magpie ${from} to ${date}` : `magpie ${date}`);
globalThis.DayView = { TEXT, langOf, text, count, money, tokensOf, hitRate, percent, shift, dateLabel, receiptDate, issued, streak, average, versus, card, fileName };
globalThis.DayView = { TEXT, langOf, text, count, money, tokensOf, hitRate, percent, shift, dateLabel, receiptDate, receiptRange, SPANS, spanFrom, stepDate, issued, streak, average, versus, card, fileName };
})();