Add TaxReturn.maybeGetForm<T>()
[ustaxlib.git] / src / TaxReturn.ts
1 import Form 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[] = [];
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) {
41 if (!form.supportsMultipleCopies) {
42 const other = this.getForms(form.name);
43 if (other.length > 0) {
44 throw new InconsistencyError(`Cannot have more than one type of form ${form.name}`);
45 }
46 }
47 this._forms.push(form);
48 }
49
50 maybeGetForm<T extends Form>(name: string): T | null {
51 const forms = this.getForms<T>(name);
52 if (forms.length == 0) {
53 return null;
54 }
55 if (forms.length > 1) {
56 throw new InconsistencyError(`More than 1 form named ${name}`);
57 }
58 return forms[0];
59 }
60
61 getForm<T extends Form>(name: string): T {
62 const form = this.maybeGetForm<T>(name);
63 if (!form)
64 throw new NotFoundError(`No form named ${name}`);
65 return form;
66 }
67
68 getForms<T extends Form>(name: string): T[] {
69 return this._forms.filter(f => f.name == name) as T[];
70 }
71 };