@refactorlabs/recount 0.9.1 → 0.11.0

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.
package/llms.md CHANGED
@@ -174,7 +174,9 @@ recount.addSpan('table', 'Policy validation', {
174
174
  .appendRow([recount.spanCell('Total', 3)], 'info') // spanning cell
175
175
  .summary([{ text: 'Total: $7,590', highlight: 'info' }])
176
176
  .redact(['fieldName'])
177
- .round(2)
177
+ .format({ cost: { format: 'money', currency: 'AUD' } }) // Recount formats it; send numbers
178
+ .signHighlight('saving', { positive: 'success', negative: 'danger' })
179
+ .round(2) // not applied to formatted columns
178
180
  .build()
179
181
  });
180
182
 
@@ -189,6 +191,8 @@ Column names (and `fromObject` keys) are shown to readers as-is. Write keys as p
189
191
 
190
192
  Highlights: `'danger' | 'warn' | 'success' | 'info' | 'muted'`
191
193
 
194
+ Send numbers, not formatted strings. `.format()` takes `format` (`'money' | 'number' | 'percent' | 'integer' | 'text'`), `currency`, `unit` and `places`; a percent is a fraction (`0.045` shows as `4.5%`). In a `fromObject` table a formatted key becomes a typed cell, or make one yourself: `recount.cell(18481.65, { format: 'number', unit: 'MJ' })`.
195
+
192
196
  **Shorthand methods** (skip the builder chain):
193
197
 
194
198
  ```ts
@@ -199,7 +203,79 @@ recount.tableFromRecords({ data: rows, title?: string })
199
203
  recount.tableFromObject({ data: obj, title?: string })
200
204
  ```
201
205
 
202
- ## Chart builder
206
+ ## Calculations
207
+
208
+ Trace a calculation as numbers, units and formulas, not sentences. Recount draws the table, checks every line that claims a formula and lets anyone recompute it. Never format numbers yourself.
209
+
210
+ ```ts
211
+ import recount, { calculation, units } from '@refactorlabs/recount';
212
+
213
+ const estimate = calculation('estimate', {
214
+ title: 'Estimated annual cost',
215
+ currency: 'AUD',
216
+ tolerance: 0.01
217
+ })
218
+ .input('days', 365.25, { label: 'Days', unit: units.days })
219
+ .input('daily_usage', 50.6, {
220
+ label: 'Daily usage',
221
+ unit: 'MJ/day',
222
+ source: 'Benchmark'
223
+ })
224
+ .charge('supply', 'Supply', {
225
+ quantity: 'days',
226
+ rate: supplyRate,
227
+ value: supplyCharge
228
+ }) // checks quantity * rate
229
+ .tiers('usage', {
230
+ // a charge per band, then a subtotal `usage`
231
+ quantity: 'daily_usage',
232
+ periods: 'days',
233
+ unit: 'MJ',
234
+ per: 'day',
235
+ bands: [
236
+ { size: 20.71, rate: r1 },
237
+ { size: null, rate: r2 }
238
+ ], // size null = the rest
239
+ value: usageCharge // the engine's figure, checked against the bands
240
+ })
241
+ .percentOf('discount', 'Discount on usage', {
242
+ of: ['usage'],
243
+ rate: -0.03,
244
+ value: discount
245
+ })
246
+ .stated('concessions', 'Concessions', {
247
+ value: -50,
248
+ taxFree: true,
249
+ source: 'Current bill'
250
+ }) // not checked
251
+ .total(
252
+ 'total',
253
+ 'Estimated cost (incl. GST)',
254
+ "round(sum_kind('charge'), 2)",
255
+ { value: total }
256
+ )
257
+ .taxIncluded('gst', 'Includes GST', { rate: 0.1 }) // charges above not tagged tax_free; value worked out
258
+ .note('Tiers apply per day.');
259
+
260
+ recount.addCalculation('#1 Plan A', estimate, { public: true }); // one table span
261
+ // trace.calculation(name, calcs, opts) and g.calculation(...) inside addGroup work the same.
262
+ // Pass an array for several calculations in one span (up to 20); opts.side: 'input' for the input side.
263
+
264
+ // Workings as steps: step(key, label, formula, value?, opts?)
265
+ const usage = calculation('usage', { layout: 'steps', currency: 'AUD' })
266
+ .input('monthly_bill', monthlyBill, { label: 'Monthly bill' })
267
+ .input('days_per_month', 30.44, { label: 'Days per month', unit: 'days' })
268
+ .step('daily_bill', 'Daily bill', 'monthly_bill / days_per_month', dailyBill);
269
+ ```
270
+
271
+ - Formulas: `+ - * / ^`, brackets, keys of inputs and lines above, and `min max clamp abs round floor ceil mround sum sum_kind('kind') sum_tagged('tag') if(cond, a, b)`. No exponents or `%` in numbers.
272
+ - If the engine rounds, say so in the formula: `round(..., 2)`. Display rounding is Recount's.
273
+ - Leave `value` out when the engine has no figure of its own; Recount works it out (`computed`).
274
+ - Other helpers: `working(key, label, formula)` (muted, not summed), `subtotal`/`info(key, label, formula | null, opts)`, `line({...})` for any raw line.
275
+ - Line options: `value`, `unit`, `places`, `primary`, `tags`, `taxFree`, `highlight`, `detail`, `explain`, `source`, `sourceSpan`, `expected` (`{ value, source, tolerance, level, reason }`), `tolerance`, `alerts`, `redact`.
276
+ - Key `undefined` makes one from the label. The builder never throws: bad keys, units and formulas are repaired or reported in `c.problems` (and debug logs), so check `expect(c.problems).toEqual([])` in a unit test.
277
+ - `NaN` is sent as `null` (not calculated); `Infinity` too, so send text like `'Unlimited'`. Decimal strings (`'0.0316'`) and decimal.js / big.js values keep their precision.
278
+ - Checks always run; alerts only when the calculation opts in with `alerts: 'warn' | 'error'`.
203
279
 
204
280
  ```ts
205
281
  recount.addSpan('chart', 'Damage breakdown', {
@@ -371,16 +447,19 @@ const damage = [
371
447
  ];
372
448
  const total = damage.reduce((s, d) => s + d.estimatedCost, 0);
373
449
  const excess = 750;
450
+ const settlement = Math.max(total - excess, 0);
374
451
 
375
452
  await recount.startTrace(
376
453
  'Insurance claim - CLM-2024-03941',
377
- {
378
- metadata: { 'Claim ID': 'CLM-2024-03941' },
379
- input: recount.tableFromObject({
380
- data: { 'Claim ID': 'CLM-2024-03941', Vehicle: '2019 Toyota Camry' }
381
- })
382
- },
454
+ { metadata: { 'Claim ID': 'CLM-2024-03941' } },
383
455
  async () => {
456
+ // What the run started from goes in a span: startTrace takes no input.
457
+ recount.addSpan('table', 'Claim', {
458
+ input: recount.tableFromObject({
459
+ data: { 'Claim ID': 'CLM-2024-03941', Vehicle: '2019 Toyota Camry' }
460
+ })
461
+ });
462
+
384
463
  recount.addSpan('db', 'Policy lookup', {
385
464
  description:
386
465
  'Fetches the active policy record for the submitted claim number',
@@ -408,18 +487,28 @@ await recount.startTrace(
408
487
  ? 'warn'
409
488
  : 'muted'
410
489
  )
411
- .transformValues({
412
- estimatedCost: (v) => `$${Number(v).toLocaleString()}`
413
- })
414
- .summary([
415
- { text: `Total: $${total.toLocaleString()}`, highlight: 'info' },
416
- {
417
- text: `Settlement: $${(total - excess).toLocaleString()}`,
418
- highlight: 'success'
419
- }
420
- ])
490
+ .format({ estimatedCost: { format: 'money', currency: 'AUD' } })
421
491
  .build()
422
492
  });
493
+
494
+ // The settlement maths as a calculation: Recount checks each formula.
495
+ const calc = recount
496
+ .calculation('settlement', { currency: 'AUD' })
497
+ .input('excess', excess, { label: 'Policy excess', unit: 'AUD' });
498
+ for (const d of damage) {
499
+ calc.stated(undefined, d.component, {
500
+ value: d.estimatedCost,
501
+ source: 'Assessor estimate'
502
+ });
503
+ }
504
+ calc
505
+ .subtotal('total_damage', 'Total damage', "sum_kind('charge')", {
506
+ value: total
507
+ })
508
+ .total('settlement', 'Settlement', 'max(total_damage - excess, 0)', {
509
+ value: settlement
510
+ });
511
+ recount.addCalculation('Settlement', calc);
423
512
  if (total > 5_000) {
424
513
  recount.addAlert('High-value claim (>$5,000)', 'warn', {
425
514
  checks: [{ value: total }]
@@ -439,7 +528,7 @@ await recount.startTrace(
439
528
  });
440
529
 
441
530
  recount.addSpan('json', 'Outcome', {
442
- output: { decision: 'approved', settlement: total - excess }
531
+ output: { decision: 'approved', settlement }
443
532
  });
444
533
  }
445
534
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@refactorlabs/recount",
3
- "version": "0.9.1",
3
+ "version": "0.11.0",
4
4
  "description": "Node.js SDK for Recount",
5
5
  "homepage": "https://recount.refactor.gg",
6
6
  "license": "MIT",