xovris 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,118 @@
1
+ import { i as tokenFor, u as Api } from "./apicmd-BHGPPVbb.js";
2
+
3
+ //#region src/spend.ts
4
+ /** The ask as `xovris spend` takes it, or why it cannot be read: --since <n>d (1 to 31, the bill's own days) and --group-by. */
5
+ function spendOptions(a) {
6
+ const by = a.groupBy ?? "service";
7
+ if (![
8
+ "service",
9
+ "account",
10
+ "day"
11
+ ].includes(by)) return { problem: `Group the bill by service, account or day: xovris spend --group-by day - "${a.groupBy}" is none of them.` };
12
+ const m = a.since === null ? ["30d", "30"] : /^(\d{1,2})d$/.exec(a.since);
13
+ const days = m ? Number(m[1]) : NaN;
14
+ if (!Number.isInteger(days) || days < 1 || days > 31) return { problem: "Say how far back in days, 1 to 31 (the bill is read by day over the last 31): xovris spend --since 30d" };
15
+ return {
16
+ days,
17
+ by
18
+ };
19
+ }
20
+ /** Each day's spend from month-to-date totals at each day's end: the day's total less the day before's, a fall a new month from
21
+ * nothing, the first day read known only on a month's first. */
22
+ function daysOf(daily) {
23
+ return (daily ?? []).flatMap((d, i, all) => {
24
+ const prev = i ? all[i - 1] : null;
25
+ const spend = prev ? d.total >= prev.total ? d.total - prev.total : d.total : d.day.endsWith("-01") ? d.total : null;
26
+ return spend === null ? [] : [{
27
+ day: d.day,
28
+ spend: Math.round(spend * 100) / 100
29
+ }];
30
+ });
31
+ }
32
+ const money = (n, cur) => `${cur === "USD" ? "$" : `${cur} `}${n.toFixed(2)}`;
33
+ /** The bill as lines a person reads, one block per currency. */
34
+ function spendLines(conns, o, now) {
35
+ const bills = conns.flatMap((c) => c.firstRead?.bill ? [{
36
+ c,
37
+ b: c.firstRead.bill
38
+ }] : []);
39
+ if (!bills.length) return ["No cloud bill read yet - connect a cloud account on Cloud and Xovris reads its bill with it."];
40
+ const out = [];
41
+ const since = (/* @__PURE__ */ new Date(now.getTime() - (o.days - 1) * 864e5)).toISOString().slice(0, 10);
42
+ for (const cur of [...new Set(bills.map((x) => x.b.currency))]) {
43
+ const mine = bills.filter((x) => x.b.currency === cur);
44
+ const total = mine.reduce((n, x) => n + x.b.total, 0);
45
+ out.push(`${money(total, cur)} this month so far across ${mine.length} account${mine.length === 1 ? "" : "s"} (${cur})`);
46
+ const rows = [];
47
+ if (o.by === "account") for (const x of mine) rows.push([`${x.c.provider} ${x.c.accountId ?? x.c.id}`, x.b.total]);
48
+ if (o.by === "service") {
49
+ const by = /* @__PURE__ */ new Map();
50
+ const byDay = mine.every((x) => (x.b.byItem ?? []).every((i) => i.daily?.length));
51
+ for (const x of mine) for (const i of x.b.byItem ?? []) {
52
+ const v = byDay ? daysOf(i.daily).filter((d) => d.day >= since).reduce((n, d) => n + d.spend, 0) : i.amount ?? 0;
53
+ if (v > 0) by.set(i.name, (by.get(i.name) ?? 0) + v);
54
+ }
55
+ rows.push(...by);
56
+ out.push(byDay ? `By service over the last ${o.days} day${o.days === 1 ? "" : "s"}:` : "By service, this month so far (the bill is not read by day for every service):");
57
+ }
58
+ if (o.by === "day") {
59
+ const by = /* @__PURE__ */ new Map();
60
+ for (const x of mine) for (const d of daysOf(x.b.daily)) if (d.day >= since) by.set(d.day, (by.get(d.day) ?? 0) + d.spend);
61
+ rows.push(...[...by].sort((a, b) => a[0].localeCompare(b[0])));
62
+ out.push(rows.length ? `By day over the last ${o.days} day${o.days === 1 ? "" : "s"}:` : "Not read by day yet - the next read of the account adds its days.");
63
+ }
64
+ const sum = rows.reduce((n, r) => n + r[1], 0);
65
+ const ranked = o.by === "day" ? rows : [...rows].sort((a, b) => b[1] - a[1]);
66
+ const w = Math.max(0, ...ranked.map((r) => r[0].length));
67
+ for (const [name, v] of ranked) out.push(` ${name.padEnd(w)} ${money(v, cur).padStart(11)} ${sum > 0 ? `${Math.round(v / sum * 100)}%`.padStart(4) : ""}`);
68
+ if (o.by === "day" && rows.length) out.push(` ${money(sum / rows.length, cur)} on an average day`);
69
+ }
70
+ return out;
71
+ }
72
+ async function spendCommand(a, o, sys, secrets, io, now = /* @__PURE__ */ new Date()) {
73
+ const opts = spendOptions(a);
74
+ if ("problem" in opts) {
75
+ io.err(`${opts.problem}\n`);
76
+ return 2;
77
+ }
78
+ const token = await tokenFor(o.api);
79
+ if (!token) {
80
+ io.err("Not signed in. Run xovris login, or set XOVRIS_TOKEN to a key from Settings, Developers.\n");
81
+ return 1;
82
+ }
83
+ secrets.add(token);
84
+ const api = new Api(o.api, sys);
85
+ api.token = token;
86
+ let res;
87
+ try {
88
+ res = await api.raw("GET", "/cloud/connections", void 0, {});
89
+ } catch {
90
+ io.err(`${o.api} gave this computer no answer - run xovris spend again once its connection is back, or name another address with --api.\n`);
91
+ return 1;
92
+ }
93
+ const text = await res.text();
94
+ let body = null;
95
+ try {
96
+ body = text ? JSON.parse(text) : null;
97
+ } catch {}
98
+ if (res.status < 200 || res.status >= 300) {
99
+ const e = body?.error;
100
+ io.err(`${secrets.redact(e ? `${e.message ?? ""} ${e.nextStep ?? ""}`.trim() : text || `HTTP ${res.status}`)}\n`);
101
+ return 1;
102
+ }
103
+ const conns = body?.items ?? body?.connections ?? [];
104
+ if (a.json) {
105
+ io.out(`${secrets.redact(JSON.stringify(conns.map((c) => ({
106
+ id: c.id,
107
+ provider: c.provider,
108
+ accountId: c.accountId,
109
+ bill: c.firstRead?.bill ?? null
110
+ })), null, 2))}\n`);
111
+ return 0;
112
+ }
113
+ io.out(`${spendLines(conns, opts, now).join("\n")}\n`);
114
+ return 0;
115
+ }
116
+
117
+ //#endregion
118
+ export { daysOf, spendCommand, spendLines, spendOptions };