Add a forms accessor to TaxReturn.
[ustaxlib.git] / src / TaxReturn.ts
1 import Form, { FormClass, isFormT } from './Form';
2 import Person, { Relation } from './Person';
3 import { NotFoundError, InconsistencyError, UnsupportedFeatureError } from './Errors';
4
5 export default class TaxReturn {
6 private _year: number;
7
8 private _people: Person[] = [];
9 private _forms: Form<any, unknown>[] = [];
10
11 constructor(year: number) {
12 this._year = year;
13 }
14
15 get year(): number {
16 return this._year;
17 }
18
19 get forms(): Form<any, unknown>[] {
20 return [...this._forms];
21 }
22
23 addPerson(person: Person) {
24 if (person.relation == Relation.Dependent) {
25 throw new UnsupportedFeatureError('Dependents are not supported');
26 }
27 if (person.relation == Relation.Self || person.relation == Relation.Spouse) {
28 const others = this._people.filter(p => p.relation == person.relation);
29 if (others.length > 0) {
30 throw new InconsistencyError('Cannot have more than one Self or Spouse');
31 }
32 }
33 this._people.push(person);
34 }
35
36 getPerson(name: RegExp | string): Person {
37 const people = this._people.filter(p => p.name.search(name) !== -1);
38 if (people.length != 1) {
39 throw new Error(`Person ${name} not found or too imprecise`);
40 }
41 return people[0];
42 }
43
44 addForm(form: Form<any>) {
45 if (!form.supportsMultipleCopies) {
46 const other = this.findForms(form.constructor as FormClass<Form<any>>);
47 if (other.length > 0) {
48 throw new InconsistencyError(`Cannot have more than one type of form ${form.name}`);
49 }
50 }
51 form.init();
52 this._forms.push(form);
53 }
54
55 findForm<T extends Form<any>>(cls: FormClass<T>): T | null {
56 const forms = this.findForms(cls);
57 if (forms.length == 0)
58 return null;
59 if (forms.length > 1)
60 throw new InconsistencyError(`Form ${forms[0].name} has multiple copies`);
61 return forms[0];
62 }
63
64 findForms<T extends Form<any>>(cls: FormClass<T>): T[] {
65 const forms: T[] = this._forms.filter((form: Form<any>): form is T => isFormT(form, cls));
66 return forms;
67 }
68
69 getForm<T extends Form<any>>(cls: FormClass<T>): T {
70 const form = this.findForm(cls);
71 if (!form)
72 throw new NotFoundError(`No form ${cls.name}`);
73 return form;
74 }
75 };