Debian Codegraph @

frontend/src/entries/cost.ts

raw
1 import { day as format_day, type FormatterContext } from "../format";
2 import {
3 date,
4 number,
5 object,
6 optional,
7 optional_string,
8 string,
9 type Validator,
10 } from "../lib/validation";
11
12 /** A cost is a pair of number and currency with date and an optional label. */
13 export class Cost {
14 constructor(
15 readonly number: number,
16 readonly currency: string,
17 readonly date: Date | null,
18 readonly label: string | null,
19 ) {}
20
21 /** Render to a string. */
22 str($ctx: FormatterContext): string {
23 const strs = [$ctx.amount(this.number, this.currency)];
24 if (this.date) {
25 strs.push(format_day(this.date));
26 }
27 if (this.label != null && this.label) {
28 strs.push(`"${this.label}"`);
29 }
30 return strs.join(", ");
31 }
32
33 private static raw_validator = object({
34 number,
35 currency: string,
36 date: optional(date),
37 label: optional_string,
38 });
39
40 static validator: Validator<Cost> = (json) =>
41 Cost.raw_validator(json).map(
42 ({ number, currency, date, label }) =>
43 new Cost(number, currency, date, label),
44 );
45 }