Make Form._lines public and remove the accessor.
[ustaxlib.git] / src / core / Form.ts
1 // Copyright 2020 Blue Static <https://www.bluestatic.org>
2 // This program is free software licensed under the GNU General Public License,
3 // version 3.0. The full text of the license can be found in LICENSE.txt.
4 // SPDX-License-Identifier: GPL-3.0-only
5
6 import Person from './Person';
7 import TaxReturn from './TaxReturn';
8 import * as Trace from './Trace';
9 import { Line } from './Line';
10 import { InconsistencyError, NotFoundError } from './Errors';
11
12 export default abstract class Form<L extends { [key: string]: Line<any> },
13 I = unknown> {
14 abstract readonly name: string;
15
16 abstract readonly lines: L;
17
18 readonly supportsMultipleCopies: boolean = false;
19
20 private readonly _input?: I;
21
22 constructor(input?: I) {
23 this._input = input;
24 }
25
26 init() {
27 for (const id in this.lines) {
28 let l = this.lines[id];
29 l._id = id;
30 l.form = this;
31 }
32 }
33
34 person(): Person | undefined {
35 return undefined;
36 }
37
38 getLine<K extends keyof L>(id: K): L[K] {
39 if (!(id in this.lines))
40 throw new NotFoundError(`Form ${this.name} does not have line ${id}`);
41 return this.lines[id];
42 }
43
44 getValue<K extends keyof L>(tr: TaxReturn, id: K): ReturnType<L[K]['value']> {
45 const line: L[K] = this.getLine(id);
46 return line.value(tr);
47 }
48
49 getInput<K extends keyof I>(name: K): I[K] {
50 if (!(name in this._input)) {
51 throw new NotFoundError(`No input with key ${name} on form ${this.name}`);
52 }
53 Trace.mark(`${this.name} input: ${name}`);
54 return this._input[name];
55 }
56
57 hasInput<K extends keyof I>(name: K): boolean {
58 return this._input !== undefined && name in this._input;
59 }
60 };
61
62 export type FormClass<T extends Form<any>> = new (...args: any[]) => T;
63
64 export function isFormT<T extends Form<any>>(form: Form<any>,
65 formClass: FormClass<T>):
66 form is T {
67 return form.constructor === formClass;
68 }