@yaks/spend 0.0.0-stage → 0.2.36

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.
Files changed (69) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +159 -2
  3. package/_dist/graph.d.ts +26 -0
  4. package/_dist/graph.d.ts.map +1 -0
  5. package/_dist/mod.d.ts +11 -0
  6. package/_dist/mod.d.ts.map +1 -0
  7. package/_dist/routes.d.ts +10 -0
  8. package/_dist/routes.d.ts.map +1 -0
  9. package/_dist/service.d.ts +41 -0
  10. package/_dist/service.d.ts.map +1 -0
  11. package/_dist/tally.d.ts +111 -0
  12. package/_dist/tally.d.ts.map +1 -0
  13. package/_dist/tools.d.ts +52 -0
  14. package/_dist/tools.d.ts.map +1 -0
  15. package/_dist/use.d.ts +31 -0
  16. package/_dist/use.d.ts.map +1 -0
  17. package/_dist/views.d.ts +27 -0
  18. package/_dist/views.d.ts.map +1 -0
  19. package/_dist/vocab.d.ts +7 -0
  20. package/_dist/vocab.d.ts.map +1 -0
  21. package/_dist/window.d.ts +132 -0
  22. package/_dist/window.d.ts.map +1 -0
  23. package/_dist/words.d.ts +40 -0
  24. package/_dist/words.d.ts.map +1 -0
  25. package/budget.js +131 -0
  26. package/budget.js.map +1 -0
  27. package/budget.ts +128 -0
  28. package/day.js +336 -0
  29. package/day.js.map +1 -0
  30. package/day.ts +364 -0
  31. package/deno.json +1 -0
  32. package/graph.js +59 -0
  33. package/graph.js.map +1 -0
  34. package/graph.ts +61 -0
  35. package/mod.js +11 -0
  36. package/mod.js.map +1 -0
  37. package/mod.ts +34 -0
  38. package/package.json +57 -4
  39. package/page.js +352 -0
  40. package/page.js.map +1 -0
  41. package/page.ts +491 -0
  42. package/routes.js +22 -0
  43. package/routes.js.map +1 -0
  44. package/routes.ts +19 -0
  45. package/service.js +124 -0
  46. package/service.js.map +1 -0
  47. package/service.ts +149 -0
  48. package/tally.js +385 -0
  49. package/tally.js.map +1 -0
  50. package/tally.ts +424 -0
  51. package/tools.js +243 -0
  52. package/tools.js.map +1 -0
  53. package/tools.ts +357 -0
  54. package/use.js +172 -0
  55. package/use.js.map +1 -0
  56. package/use.ts +226 -0
  57. package/views.js +79 -0
  58. package/views.js.map +1 -0
  59. package/views.ts +96 -0
  60. package/vocab.js +17 -0
  61. package/vocab.js.map +1 -0
  62. package/vocab.json +237 -0
  63. package/vocab.ts +18 -0
  64. package/window.js +259 -0
  65. package/window.js.map +1 -0
  66. package/window.ts +336 -0
  67. package/words.js +47 -0
  68. package/words.js.map +1 -0
  69. package/words.ts +77 -0
package/service.ts ADDED
@@ -0,0 +1,149 @@
1
+ /**
2
+ * The tally, as a duty: the module a server imports at `@yaks/spend/service`.
3
+ * Every pass tallies today again from its requests (./day.ts), and yesterday
4
+ * too for the first hours of a day, while its last requests are still being
5
+ * read in, and every past day marked `untallied` because requests reached it
6
+ * late, as a transcript read in after the fact does (./graph.ts); then it
7
+ * keeps the Claude plan's newest limits (./budget.ts). A
8
+ * page that shows where the tokens went reads these rows, never the
9
+ * requests, so looking costs nothing.
10
+ *
11
+ * It is a loop because a tally is owed as time passes, not when one write
12
+ * commits: a day of requests is thousands of writes, and tallying after each
13
+ * would cost more than the tally saves.
14
+ *
15
+ * @module
16
+ */
17
+ import type { Eid, Graph } from 'jsr:@yaks/graph@0.2.36'
18
+ import { line } from '@yaks/query'
19
+ import { sleep } from '@yaks/fp'
20
+ import { recompute } from './day.js'
21
+ import { after, dayOf, midnight } from './window.js'
22
+ import { read } from './budget.js'
23
+ import { identityEid } from '@yaks/graph/identity'
24
+
25
+ // The plans a tally kept by provider, before each account kept its own.
26
+ let PROVIDERS = new Set(
27
+ ['claude', 'codex'].map((name) => identityEid('provider', [name])),
28
+ )
29
+
30
+ /** What a config can set for this duty. */
31
+ export type Options = {
32
+ /** how long a pass waits for the next, in milliseconds (default ten
33
+ * minutes) */
34
+ every?: number
35
+ /** where claude-status keeps its readings (default `$CLAUDE_USAGE_DIR` or
36
+ * `~/.cache/claude-usage`) */
37
+ usage?: string
38
+ }
39
+
40
+ /** How long a pass waits for the next. */
41
+ export let EVERY = 10 * 60 * 1000
42
+
43
+ /** How often the duty looks for days marked `untallied` between passes, so
44
+ * transcripts read in on a first `yak serve` show within a minute. */
45
+ export let LOOK = 60 * 1000
46
+
47
+ /** How long into a day yesterday is tallied again. */
48
+ export let LATE = 3 * 60 * 60 * 1000
49
+
50
+ /** One pass: today, yesterday while it may still be arriving, the days
51
+ * requests reached late, the limits.
52
+ * Returns the models its tallies met with no price, which are missing from
53
+ * the dollars, not zero in them. */
54
+ export let pass = async (
55
+ g: Graph,
56
+ now: number = Date.now(),
57
+ o: Options = {},
58
+ ): Promise<Eid[]> => {
59
+ let today = dayOf(now)
60
+ let unpriced = new Set<Eid>()
61
+ let tally = async (day: string) => {
62
+ for (let m of (await recompute(g, day)).unpriced) unpriced.add(m)
63
+ }
64
+ if (now - Date.parse(midnight(today)) < LATE) {
65
+ await tally(after(today, -1))
66
+ }
67
+ await tally(today)
68
+ for (let m of await owed(g)) unpriced.add(m)
69
+ // A day of the past week tallied before tallies kept their plans, or kept
70
+ // them by provider before each account had its own, is tallied again, so
71
+ // its week reads in each account's shares too.
72
+ let kept = await g.read(
73
+ line`.spend .spend.day>=${after(today, -8)} .fields=spend.day,spend.plans`,
74
+ )
75
+ for (let b of kept) {
76
+ let s = b.spend as { day: string; plans?: Record<Eid, unknown> }
77
+ let byProvider = Object.keys(s.plans ?? {}).some((k) => PROVIDERS.has(k))
78
+ if ((!s.plans || byProvider) && s.day != today) await tally(s.day)
79
+ }
80
+ await read(g, o.usage)
81
+ return [...unpriced]
82
+ }
83
+
84
+ /** Tally each day marked `untallied`. The mark comes off before the day is
85
+ * read, so a request written while it is tallied marks it again. Returns the
86
+ * models its tallies met with no price. */
87
+ export let owed = async (g: Graph): Promise<Eid[]> => {
88
+ let unpriced = new Set<Eid>()
89
+ for (let b of await g.read('.untallied .fields=untallied.day')) {
90
+ let day = String((b.untallied as { day: string }).day)
91
+ await g.apply([{ entity: b.entity, untallied: null }], { trusted: true })
92
+ for (let m of (await recompute(g, day)).unpriced) unpriced.add(m)
93
+ }
94
+ return [...unpriced]
95
+ }
96
+
97
+ /** Tally, then again every `every`, and the owed days every `LOOK`, until the signal aborts. An already
98
+ * aborted signal is one pass. */
99
+ export let service = async (
100
+ host: {
101
+ graph: Graph
102
+ report?: (
103
+ error: unknown,
104
+ context?: { tags?: Record<string, string> },
105
+ ) => unknown
106
+ },
107
+ options: Options = {},
108
+ signal: AbortSignal = AbortSignal.abort(),
109
+ ): Promise<void> => {
110
+ let told = new Set<Eid>()
111
+ let every = options.every ?? EVERY
112
+ let due = 0
113
+ for (;;) {
114
+ try {
115
+ let whole = Date.now() >= due
116
+ if (whole) due = Date.now() + every
117
+ let unpriced = whole
118
+ ? await pass(host.graph, Date.now(), options)
119
+ : await owed(host.graph)
120
+ for (let m of unpriced) {
121
+ if (told.has(m)) continue
122
+ told.add(m)
123
+ // A model with no price counts as nothing: a failure, fixed with a
124
+ // `price` on its row, told once while this server runs. A request
125
+ // that named no model is fixed where it was asked, so its ask names
126
+ // what ran (@yaks/spawn `asked`).
127
+ let row = m
128
+ ? (await host.graph.get([m], ['model']))[0]?.model as
129
+ | { name?: string }
130
+ | undefined
131
+ : undefined
132
+ ;(host.report ?? console.error)(
133
+ new Error(
134
+ m
135
+ ? `model ${row?.name ?? m} has no price`
136
+ : 'a request named no model, so it has no price',
137
+ ),
138
+ { tags: { step: 'spend unpriced', model: m } },
139
+ )
140
+ }
141
+ } catch (e) {
142
+ // A pass that failed is told, and the next one tallies again.
143
+ ;(host.report ?? console.error)(e, { tags: { step: 'spend pass' } })
144
+ }
145
+ if (signal.aborted) return
146
+ await sleep(Math.min(every, LOOK), signal)
147
+ if (signal.aborted) return
148
+ }
149
+ }
package/tally.js ADDED
@@ -0,0 +1,385 @@
1
+ /**
2
+ * A day's model requests, tallied: pure, over the rows a day's read returns
3
+ * (./day.ts). Each request is its entry: `usage`, the `cost` its provider
4
+ * reported or the hook weighed, and the `context_parts` the importer laid out
5
+ * (@yaks/session/parts). The fixed part it carries is spread over the pieces
6
+ * its session's `fixed` names; a request whose context was not recorded is one
7
+ * part, `unrecorded`. Dollars are weighed per part at the model's price, then
8
+ * scaled to what the provider reported where it did. Days add up (`merged`),
9
+ * so a week is its days.
10
+ *
11
+ * @module
12
+ */ import { dollars, hourly } from "@yaks/model/vocab";
13
+ let ROWS = [
14
+ 'parts',
15
+ 'sessions',
16
+ 'tasks',
17
+ 'models',
18
+ 'entries'
19
+ ];
20
+ /** How many entries a tally names. */ export let ENTRIES = 50;
21
+ let comp = (b, name)=>b[name] ?? {};
22
+ let sum = (ns)=>ns.reduce((a, b)=>a + b, 0);
23
+ /** An empty day. */ export let empty = (day)=>({
24
+ day,
25
+ requests: 0,
26
+ tokens: [
27
+ 0,
28
+ 0,
29
+ 0,
30
+ 0
31
+ ],
32
+ dollars: 0,
33
+ parts: {},
34
+ sessions: {},
35
+ tasks: {},
36
+ models: {},
37
+ entries: {},
38
+ plans: {},
39
+ unpriced: []
40
+ });
41
+ let unbilled = ()=>({
42
+ dollars: 0,
43
+ unpriced: [],
44
+ metered: {},
45
+ parts: {},
46
+ sessions: {},
47
+ tasks: {},
48
+ models: {},
49
+ entries: {}
50
+ });
51
+ // Add `n` to what a plan's `model` ran up in `session`.
52
+ let meter = (plan, model, session, n)=>{
53
+ if (!plan) return;
54
+ let at = (plan.metered ??= {})[model] ??= {};
55
+ at[session] = (at[session] ?? 0) + n;
56
+ };
57
+ // Name a model once in a list.
58
+ let name = (to, model)=>[
59
+ ...new Set([
60
+ ...to ?? [],
61
+ model
62
+ ])
63
+ ].sort();
64
+ // Add `dollars` to what a plan's `row` holds under `key`.
65
+ let bill = (plan, row, key, n)=>{
66
+ if (plan) plan[row][key] = (plan[row][key] ?? 0) + n;
67
+ };
68
+ // Add `more` into the tally `to` keeps under `key`.
69
+ let add = (to, key, more)=>{
70
+ let at = to[key] ??= more.map(()=>0);
71
+ more.forEach((n, i)=>at[i] += n);
72
+ };
73
+ // What a request used, as paid, where its context was not recorded.
74
+ let paid = (u)=>{
75
+ let read = u.cached_tokens ?? 0;
76
+ let write = u.cache_write_tokens ?? 0;
77
+ return [
78
+ read,
79
+ write,
80
+ Math.max(0, (u.input_tokens ?? 0) - read - write),
81
+ u.output_tokens ?? 0
82
+ ];
83
+ };
84
+ // The fixed part spread over its pieces, by their sizes.
85
+ let spread = (p, pieces)=>{
86
+ let total = sum(Object.values(pieces ?? {}));
87
+ return total ? Object.entries(pieces).map(([k, n])=>[
88
+ k,
89
+ p.map((t)=>t * n / total)
90
+ ]) : [
91
+ [
92
+ 'fixed',
93
+ p
94
+ ]
95
+ ];
96
+ };
97
+ // A request's parts, as paid.
98
+ let partsOf = (b, known)=>{
99
+ let cp = comp(b, 'context_parts');
100
+ let parts = cp.parts;
101
+ if (!parts) return [
102
+ [
103
+ 'unrecorded',
104
+ paid(comp(b, 'usage'))
105
+ ]
106
+ ];
107
+ let session = String(comp(b, 'entry').session ?? '');
108
+ return Object.entries(parts).flatMap(([k, p])=>k == 'fixed' ? spread(p, known.fixed.get(session)) : [
109
+ [
110
+ k,
111
+ p
112
+ ]
113
+ ]);
114
+ };
115
+ /**
116
+ * One day's tally of its requests.
117
+ *
118
+ * ```ts
119
+ * import { tally } from './tally.ts'
120
+ * import { equal } from '@yaks/testing'
121
+ *
122
+ * let ask = {
123
+ * entity: { eid: 'a' },
124
+ * entry: { session: 's' },
125
+ * ask: { to: 'm' },
126
+ * usage: { input_tokens: 2e6, cached_tokens: 1e6, output_tokens: 0 },
127
+ * context_parts: { parts: { fixed: [1e6, 0, 0, 0], input: [0, 0, 1e6, 0] } },
128
+ * }
129
+ * let t = tally('2026-10-20', [ask], {
130
+ * prices: new Map([['m', { input: 4, cached: 0.2, output: 20 }]]),
131
+ * fixed: new Map([['s', { 'tool Read': 3, skills: 1 }]]),
132
+ * tasks: new Map([['s', ['T-1', 'T-2']]]),
133
+ * plans: new Map([['a', 'claude']]),
134
+ * })
135
+ * equal(t.dollars, 4.2)
136
+ * equal([t.plans.claude.dollars, t.plans.claude.tasks], [4.2, { 'T-1': 2.1, 'T-2': 2.1 }])
137
+ * equal(t.plans.claude.metered, { m: { s: 4.2 } })
138
+ * equal(t.parts, {
139
+ * 'tool Read': [750000, 0, 0, 0, 0.15],
140
+ * skills: [250000, 0, 0, 0, 0.05],
141
+ * input: [0, 0, 1000000, 0, 4],
142
+ * })
143
+ * equal(t.tasks, { 'T-1': [1e6, 2.1], 'T-2': [1e6, 2.1] })
144
+ * ```
145
+ *
146
+ * A model with no price, whose request reported no dollars, is named as
147
+ * unpriced, on the day and on its plan:
148
+ *
149
+ * ```ts
150
+ * import { tally } from './tally.ts'
151
+ * import { equal } from '@yaks/testing'
152
+ *
153
+ * let ask = {
154
+ * entity: { eid: 'a' },
155
+ * entry: { session: 's' },
156
+ * ask: { to: 'free' },
157
+ * usage: { input_tokens: 10, output_tokens: 5 },
158
+ * }
159
+ * let t = tally('2026-10-20', [ask], {
160
+ * prices: new Map(),
161
+ * fixed: new Map(),
162
+ * tasks: new Map(),
163
+ * plans: new Map([['a', 'codex']]),
164
+ * })
165
+ * equal([t.dollars, t.unpriced, t.plans.codex.unpriced], [0, ['free'], ['free']])
166
+ * ```
167
+ */ export let tally = (day, rows, known)=>{
168
+ let out = empty(day);
169
+ for (let b of rows){
170
+ let u = comp(b, 'usage');
171
+ // Weighed at the price of the model that answered, else the one asked;
172
+ // with neither priced, the one that answered is the one to price.
173
+ let ask = comp(b, 'ask');
174
+ let models = [
175
+ ask.served,
176
+ ask.to ?? comp(b, 'using').model
177
+ ].filter((m)=>m != null).map(String);
178
+ let model = models.find((m)=>known.prices.has(m)) ?? models[0] ?? '';
179
+ let price = known.prices.get(model);
180
+ let hour = hourly(u);
181
+ let weigh = (p)=>price ? dollars(price, p, hour) : 0;
182
+ let parts = partsOf(b, known);
183
+ let weighed = sum(parts.map(([, p])=>weigh(p)));
184
+ let cost = comp(b, 'cost');
185
+ let reported = cost.reported && typeof cost.dollars == 'number';
186
+ let spent = reported ? cost.dollars : weighed;
187
+ // Dollars per part: weighed, scaled to what was reported; where nothing
188
+ // weighs (no price), by tokens.
189
+ let tokens = sum(parts.map(([, p])=>sum(p)));
190
+ let share = (p)=>weighed ? weigh(p) * spent / weighed : tokens ? sum(p) * spent / tokens : 0;
191
+ let at = known.plans?.get(b.entity.eid);
192
+ let plan = at ? out.plans[at] ??= unbilled() : undefined;
193
+ let all = [
194
+ 0,
195
+ 0,
196
+ 0,
197
+ 0
198
+ ];
199
+ for (let [k, p] of parts){
200
+ add(out.parts, k, [
201
+ ...p,
202
+ share(p)
203
+ ]);
204
+ bill(plan, 'parts', k, share(p));
205
+ p.forEach((n, i)=>all[i] += n);
206
+ }
207
+ if (!price && !reported && sum(all)) {
208
+ out.unpriced = name(out.unpriced, model);
209
+ if (plan) plan.unpriced = name(plan.unpriced, model);
210
+ }
211
+ let entries = comp(b, 'context_parts').entries ?? {};
212
+ for (let [eid, p] of Object.entries(entries)){
213
+ add(out.entries, eid, [
214
+ sum(p),
215
+ share(p)
216
+ ]);
217
+ bill(plan, 'entries', eid, share(p));
218
+ }
219
+ let session = String(comp(b, 'entry').session ?? '');
220
+ let total = sum(all);
221
+ add(out.sessions, session, [
222
+ total,
223
+ spent,
224
+ 1
225
+ ]);
226
+ bill(plan, 'sessions', session, spent);
227
+ let tasks = known.tasks.get(session) ?? [];
228
+ for (let t of tasks){
229
+ add(out.tasks, t, [
230
+ total / tasks.length,
231
+ spent / tasks.length
232
+ ]);
233
+ bill(plan, 'tasks', t, spent / tasks.length);
234
+ }
235
+ add(out.models, model, [
236
+ ...all,
237
+ spent,
238
+ 1
239
+ ]);
240
+ bill(plan, 'models', model, spent);
241
+ meter(plan, model, session, spent);
242
+ if (plan) plan.dollars += spent;
243
+ out.tokens = out.tokens.map((n, i)=>n + all[i]);
244
+ out.dollars += spent;
245
+ out.requests++;
246
+ }
247
+ return settled(out);
248
+ };
249
+ /** A tally's numbers rounded as kept: tokens whole, dollars to the
250
+ * hundredth of a cent, and its costliest entries alone. */ export let settled = (s)=>{
251
+ let whole = (ns, money)=>ns.map((n, i)=>money.includes(i) ? Math.round(n * 1e4) / 1e4 : Math.round(n));
252
+ let each = (m, money)=>Object.fromEntries(Object.entries(m).map(([k, ns])=>[
253
+ k,
254
+ whole(ns, money)
255
+ ]));
256
+ let entries = each(Object.fromEntries(ranked(s.entries, 1).slice(0, ENTRIES)), [
257
+ 1
258
+ ]);
259
+ let cents = (n)=>Math.round(n * 1e4) / 1e4;
260
+ let plan = (p)=>({
261
+ dollars: cents(p.dollars),
262
+ unpriced: p.unpriced ?? [],
263
+ metered: Object.fromEntries(Object.entries(p.metered ?? {}).map(([model, by])=>[
264
+ model,
265
+ Object.fromEntries(Object.entries(by).map(([k, n])=>[
266
+ k,
267
+ cents(n)
268
+ ]))
269
+ ])),
270
+ ...Object.fromEntries(ROWS.map((row)=>[
271
+ row,
272
+ Object.fromEntries(Object.entries(p[row]).filter(([k])=>row != 'entries' || k in entries).map(([k, n])=>[
273
+ k,
274
+ cents(n)
275
+ ]))
276
+ ]))
277
+ });
278
+ return {
279
+ ...s,
280
+ tokens: whole(s.tokens, []),
281
+ dollars: Math.round(s.dollars * 1e4) / 1e4,
282
+ parts: each(s.parts, [
283
+ 4
284
+ ]),
285
+ sessions: each(s.sessions, [
286
+ 1
287
+ ]),
288
+ tasks: each(s.tasks, [
289
+ 1
290
+ ]),
291
+ models: each(s.models, [
292
+ 4
293
+ ]),
294
+ entries,
295
+ plans: Object.fromEntries(Object.entries(s.plans ?? {}).map(([k, p])=>[
296
+ k,
297
+ plan(p)
298
+ ]))
299
+ };
300
+ };
301
+ /**
302
+ * Days added up, as one tally named by the first.
303
+ *
304
+ * ```ts
305
+ * import { empty, merged } from './tally.ts'
306
+ * import { equal } from '@yaks/testing'
307
+ *
308
+ * let a = { ...empty('2026-10-20'), requests: 2, dollars: 1, parts: { skills: [1, 0, 0, 0, 1] } }
309
+ * let b = { ...empty('2026-10-21'), requests: 1, dollars: 2, parts: { skills: [2, 0, 0, 0, 2] } }
310
+ * let m = merged([a, b])
311
+ * equal([m.day, m.requests, m.dollars, m.parts], ['2026-10-20', 3, 3, { skills: [3, 0, 0, 0, 3] }])
312
+ * ```
313
+ */ export let merged = (days)=>{
314
+ let out = empty(days[0]?.day ?? '');
315
+ for (let d of days){
316
+ out.requests += d.requests;
317
+ for (let m of d.unpriced ?? [])out.unpriced = name(out.unpriced, m);
318
+ out.dollars += d.dollars;
319
+ out.tokens = out.tokens.map((n, i)=>n + (d.tokens[i] ?? 0));
320
+ for (let k of ROWS){
321
+ for (let [key, ns] of Object.entries(d[k] ?? {}))add(out[k], key, ns);
322
+ }
323
+ for (let [at, p] of Object.entries(d.plans ?? {})){
324
+ let plan = out.plans[at] ??= unbilled();
325
+ plan.dollars += p.dollars;
326
+ for (let m of p.unpriced ?? [])plan.unpriced = name(plan.unpriced, m);
327
+ for (let [model, by] of Object.entries(p.metered ?? {})){
328
+ for (let [k, n] of Object.entries(by))meter(plan, model, k, n);
329
+ }
330
+ for (let row of ROWS){
331
+ for (let [k, n] of Object.entries(p[row] ?? {}))bill(plan, row, k, n);
332
+ }
333
+ }
334
+ }
335
+ return settled(out);
336
+ };
337
+ /** A tally's rows, costliest first, by the number at `at`. */ export let ranked = (m, at)=>Object.entries(m).sort((a, b)=>(b[1][at] ?? 0) - (a[1][at] ?? 0));
338
+ /** The spend a row holds, as a tally. */ export let spendOf = (b)=>{
339
+ let s = b?.spend;
340
+ return s?.day ? {
341
+ ...empty(s.day),
342
+ ...s
343
+ } : undefined;
344
+ };
345
+ /**
346
+ * The tasks completed each week and the dollars a tally charged them, as cash
347
+ * (paid by the token) and usage at list price (billed against a plan). The
348
+ * dollars are the tally's `tasks` split, an estimate: a session divided evenly
349
+ * across the tasks it worked on. `finished` is each task and the week it was
350
+ * completed in.
351
+ *
352
+ * ```ts
353
+ * import { done, empty } from './tally.ts'
354
+ * import { equal } from '@yaks/testing'
355
+ *
356
+ * let s = { ...empty('2026-11-09'), tasks: { a: [0, 5], b: [0, 1] },
357
+ * plans: { c: { dollars: 4, parts: {}, sessions: {}, tasks: { a: 4 }, models: {}, entries: {} } } }
358
+ * equal(done(s, [['a', '2026-11-09'], ['b', '2026-11-09'], ['z', '2026-11-16']]), [
359
+ * { week: '2026-11-09', tasks: 2, unpaid: 0, cash: 2, usage: 4 },
360
+ * { week: '2026-11-16', tasks: 1, unpaid: 1, cash: 0, usage: 0 },
361
+ * ])
362
+ * ```
363
+ */ export let done = (s, finished)=>{
364
+ let weeks = new Map();
365
+ let plans = Object.values(s.plans ?? {});
366
+ for (let [task, week] of finished){
367
+ let w = weeks.get(week) ?? weeks.set(week, {
368
+ week,
369
+ tasks: 0,
370
+ unpaid: 0,
371
+ cash: 0,
372
+ usage: 0
373
+ }).get(week);
374
+ let all = s.tasks[task]?.[1] ?? 0;
375
+ let usage = sum(plans.map((p)=>p.tasks?.[task] ?? 0));
376
+ w.tasks++;
377
+ if (!all) w.unpaid++;
378
+ w.usage += usage;
379
+ w.cash += Math.max(0, all - usage);
380
+ }
381
+ return [
382
+ ...weeks.values()
383
+ ].sort((a, b)=>a.week < b.week ? -1 : 1);
384
+ };
385
+ //# sourceMappingURL=tally.js.map
package/tally.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tally.js","sources":["./tally.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;CAWC,GAGD,SAAS,OAAO,EAAE,MAAM,iCAAsC;AA2C9D,IAAI,OAAe;EAAC;EAAS;EAAY;EAAS;EAAU;CAAU;AActE,oCAAoC,GACpC,OAAO,IAAI,UAAU,GAAE;AAEvB,IAAI,OAAO,CAAC,GAAW,OAAkB,CAAC,CAAC,KAAK,IAAI,CAAC;AACrD,IAAI,MAAM,CAAC,KAAiB,GAAG,MAAM,CAAC,CAAC,GAAG,IAAM,IAAI,GAAG;AAEvD,kBAAkB,GAClB,OAAO,IAAI,QAA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