Add a test for Form8959.
[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 addPerson(person: Person) {
20 if (person.relation == Relation.Dependent) {
21 throw new UnsupportedFeatureError('Dependents are not supported');
22 }
23 if (person.relation == Relation.Self || person.relation == Relation.Spouse) {
24 const others = this._people.filter(p => p.relation == person.relation);
25 if (others.length > 0) {
26 throw new InconsistencyError('Cannot have more than one Self or Spouse');
27 }
28 }
29 this._people.push(person);
30 }
31
32 getPerson(name: RegExp | string): Person {
33 const people = this._people.filter(p => p.name.search(name) !== -1);
34 if (people.length != 1) {
35 throw new Error(`Person ${name} not found or too imprecise`);
36 }
37 return people[0];
38 }
39
40 addForm(form: Form<any>) {
41 if (!form.supportsMultipleCopies) {
42 const other = this.findForms(form.constructor as FormClass<Form<any>>);
43 if (other.length > 0) {
44 throw new InconsistencyError(`Cannot have more than one type of form ${form.name}`);
45 }
46 }
47 form.init();
48 this._forms.push(form);
49 }
50
51 findForm<T extends Form<any>>(cls: FormClass<T>): T | null {
52 const forms = this.findForms(cls);
53 if (forms.length == 0)
54 return null;
55 if (forms.length > 1)
56 throw new InconsistencyError(`Form ${forms[0].name} has multiple copies`);
57 return forms[0];
58 }
59
60 findForms<T extends Form<any>>(cls: FormClass<T>): T[] {
61 const forms: T[] = this._forms.filter((form: Form<any>): form is T => isFormT(form, cls));
62 return forms;
63 }
64
65 getForm<T extends Form<any>>(cls: FormClass<T>): T {
66 const form = this.findForm(cls);
67 if (!form)
68 throw new NotFoundError(`No form ${cls.name}`);
69 return form;
70 }
71 };