Extract constant values from fed2019 Forms as named definitions.
[ustaxlib.git] / src / core / TaxReturn.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 Form, { FormClass, isFormT } from './Form';
7 import Person, { Relation } from './Person';
8 import { NotFoundError, InconsistencyError, UnsupportedFeatureError } from './Errors';
9
10 export default abstract class TaxReturn {
11 private _people: Person[] = [];
12 private _forms: Form[] = [];
13
14 abstract readonly constants;
15
16 abstract get year(): number;
17
18 abstract get includeJointPersonForms(): boolean;
19
20 get forms(): Form[] {
21 return [...this._forms];
22 }
23
24 addPerson(person: Person) {
25 if (person.relation == Relation.Dependent) {
26 throw new UnsupportedFeatureError('Dependents are not supported');
27 }
28 if (person.relation == Relation.Self || person.relation == Relation.Spouse) {
29 const others = this._people.filter(p => p.relation == person.relation);
30 if (others.length > 0) {
31 throw new InconsistencyError('Cannot have more than one Self or Spouse');
32 }
33 }
34 this._people.push(person);
35 }
36
37 getPerson(name: RegExp | string): Person {
38 const people = this._people.filter(p => p.name.search(name) !== -1);
39 if (people.length != 1) {
40 throw new Error(`Person ${name} not found or too imprecise`);
41 }
42 return people[0];
43 }
44
45 addForm(form: Form) {
46 if (!form.supportsMultipleCopies) {
47 const other = this.findForms(form.constructor as FormClass<Form>);
48 if (other.length > 0) {
49 throw new InconsistencyError(`Cannot have more than one type of form ${form.name}`);
50 }
51 }
52 form.init();
53 this._forms.push(form);
54 }
55
56 findForm<T extends Form>(cls: FormClass<T>): T | null {
57 const forms = this.findForms(cls);
58 if (forms.length == 0)
59 return null;
60 if (forms.length > 1)
61 throw new InconsistencyError(`Form ${forms[0].name} has multiple copies`);
62 return forms[0];
63 }
64
65 findForms<T extends Form>(cls: FormClass<T>): T[] {
66 const forms: T[] = this._forms
67 .filter((form: Form): form is T => isFormT(form, cls))
68 .filter((form: T) => {
69 const person = form.person();
70 if (person === undefined)
71 return true;
72
73 if (person == Person.joint && this.includeJointPersonForms)
74 return true;
75
76 return this._people.includes(form.person());
77 });
78 return forms;
79 }
80
81 getForm<T extends Form>(cls: FormClass<T>): T {
82 const form = this.findForm(cls);
83 if (!form)
84 throw new NotFoundError(`No form ${cls.name}`);
85 return form;
86 }
87 };