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
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';
12 export default abstract class Form<I = unknown> {
13 abstract readonly name: string;
15 abstract readonly lines: { [key: string]: Line<any> };
17 readonly supportsMultipleCopies: boolean = false;
19 private readonly _input?: I;
21 constructor(input?: I) {
26 for (const id in this.lines) {
27 let l = this.lines[id];
33 person(): Person | undefined {
37 getLine<K extends keyof this['lines']>(id: K): this['lines'][K] {
38 if (!(id in this.lines))
39 throw new NotFoundError(`Form ${this.name} does not have line ${id.toString()}`);
40 // This coercion is safe: the method's generic constraint for K ensures
41 // a valid key in |lines|, and the abstract declaration of |lines| ensures
42 // the correct index type.
43 return this.lines[id as any] as this['lines'][K];
46 getValue<K extends keyof this['lines']>(tr: TaxReturn, id: K): ReturnType<this['lines'][K]['value']> {
47 const line = this.getLine(id);
48 return line.value(tr);
51 getInput<K extends keyof I>(name: K): I[K] {
52 if (!(name in this._input)) {
53 throw new NotFoundError(`No input with key ${String(name)} on form ${this.name}`);
55 Trace.mark(`${this.name} input: ${String(name)}`);
56 return this._input[name];
59 hasInput<K extends keyof I>(name: K): boolean {
60 return this._input !== undefined && name in this._input;
64 export type FormClass<T extends Form> = new (...args: any[]) => T;
66 export function isFormT<T extends Form>(form: Form,
67 formClass: FormClass<T>):
69 for (let proto = form; proto !== null; proto = Object.getPrototypeOf(proto)) {
70 if (proto.constructor === formClass)