-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransaction.ts
More file actions
645 lines (581 loc) · 26.1 KB
/
transaction.ts
File metadata and controls
645 lines (581 loc) · 26.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
import Boom from "@hapi/boom";
import { plainToClass } from "class-transformer";
import { DataSource, In } from "typeorm";
import { Claim } from "../../entities/Claim";
import { PurchaseLineItem } from "../../entities/PurchaseLineItem";
import {
CreateClaimDTO,
CreateClaimResponse,
DeleteClaimDTO,
DeleteClaimResponse,
DeletePurchaseLineItemResponse,
GetClaimByIdResponse,
GetClaimInProgressForCompanyResponse,
GetClaimsByCompanyIdResponse,
GetPurchaseLineItemsForClaimResponse,
LinkClaimToLineItemDTO,
LinkClaimToLineItemResponse,
LinkClaimToPurchaseDTO,
LinkClaimToPurchaseResponse,
UpdateClaimStatusDTO,
UpdateClaimStatusResponse,
} from "../../types/Claim";
import { ClaimStatusInProgressTypes, ClaimStatusType } from "../../types/ClaimStatusType";
import { logMessageToFile } from "../../utilities/logger";
import { InvoiceTransaction } from "../invoice/transaction";
import { IPurchaseLineItemTransaction, PurchaseLineItemTransaction } from "../purchase-line-item/transaction";
import { UserTransaction } from "../user/transaction";
import { PurchaseTransaction } from "../purchase/transaction";
import { ClaimDataForPDF } from "./types";
import { Document } from "../../entities/Document";
export interface IClaimTransaction {
/**
* Creates a new claim in the database
* @param payload Claim to be inserted into the database
* @returns A promise that resolves to the created claim or null
*/
createClaim(payload: CreateClaimDTO, companyId: string): Promise<CreateClaimResponse | null>;
/**
* Gets a claim by its id
* @param payload ID of the claim to be fetched
* @returns Promise resolving to fetched claim or null if not found
*/
getClaimsByCompanyId(companyId: string): Promise<GetClaimsByCompanyIdResponse | null>;
/**
* Deletes a claim by its id
* @param payload ID of the claim to be deleted
* @returns Promise resolving delete operation or null if not present
*/
deleteClaim(payload: DeleteClaimDTO, companyId: string): Promise<DeleteClaimResponse | null>;
/**
* Adds a link (row in the bridge table) between a claim and a purchase line item
*
* @param payload id of both the claim and the purchase line item
* @returns Promise resolving to linked claim id and purchase line item id or null if either not found
*/
linkClaimToLineItem(payload: LinkClaimToLineItemDTO): Promise<LinkClaimToLineItemResponse | null>;
/**
* Adds a link (row in the bridge table) between a claim and every line item for a purchase
*
* @param payload if of the claim and the purchase whose line items must be linked
* @returns Promise resolving to an array with objects containing claim id and each linked purchase line
* item id or null if either not found
*/
linkClaimToPurchaseItems(payload: LinkClaimToPurchaseDTO): Promise<LinkClaimToPurchaseResponse | null>;
/**
* Gets all the linked purchase line items to a claim
*
* @param claimId of the desired claim
* @returns Promise resolving to an array of the linked purchase line items
*/
getLinkedPurchaseLineItems(claimId: string): Promise<GetPurchaseLineItemsForClaimResponse | null>;
/**
* Deletes the link between a purchase line item and a claim
* @param claimId from the desired claim
* @param lineItemId from the desired purchase line item
* @returns Promise resolving to linked claim id and purchase line item id or null if either not found
*/
deletePurchaseLineItem(claimId: string, lineItemId: string): Promise<DeletePurchaseLineItemResponse | null>;
/**
* Gets the most recent Claim that is in progress, if there is one
* If there are more than one, gets the most recently created one
* If there are none, returns NULL
* @param companyId the id of the company to look for
* @returns either the found Claim or null if none found
*/
getClaimInProgressForCompany(companyId: string): Promise<GetClaimInProgressForCompanyResponse>;
/**
* To retrieve and package the relevant information to generate a pdf for a claim.
* @param claimId from the desired claim.
* @param userId for the user who is making the claim
* @returns the necessary claim, user, and invoice data to make the pdf
*/
retrieveDataForPDF(claimId: string, userId: string): Promise<ClaimDataForPDF>;
/**
* Gets a single claim by ID with all relations
* @param claimId ID of the claim to fetch
* @param companyId ID of the company (for authorization)
* @returns Promise resolving to the claim with relations or null if not found
*/
getClaimById(claimId: string, companyId: string): Promise<GetClaimByIdResponse | null>;
/**
* Updates a claim's status and related fields
* @param claimId ID of the claim to update
* @param payload Update data including status
* @param companyId ID of the company (for authorization)
* @returns Promise resolving to the updated claim or null if not found
*/
updateClaimStatus(
claimId: string,
payload: UpdateClaimStatusDTO,
companyId: string
): Promise<UpdateClaimStatusResponse | null>;
linkClaimToDocument(claimId: string, documentId: string): Promise<void>;
getAllDocumentsAssociatedWithClaim(claimId: string): Promise<Document[]>;
}
export class ClaimTransaction implements IClaimTransaction {
private db: DataSource;
constructor(db: DataSource) {
this.db = db;
}
async createClaim(payload: CreateClaimDTO, companyId: string): Promise<CreateClaimResponse | null> {
if (ClaimStatusInProgressTypes.includes(payload.status)) {
const exists = await this.getClaimInProgressForCompany(companyId);
if (exists !== null) {
throw Boom.badRequest("Cannot have more than one claim in progress per company");
}
}
try {
const claim: Claim = plainToClass(Claim, {
...payload,
companyId: companyId,
});
const result: Claim = await this.db.manager.save(Claim, claim);
return {
...result,
status: result.status as ClaimStatusType,
createdAt: claim.createdAt.toISOString(),
updatedAt: claim.updatedAt?.toISOString(),
femaDisaster: result.femaDisaster
? {
...result.femaDisaster,
declarationDate: result.femaDisaster.declarationDate.toISOString(),
incidentBeginDate: result.femaDisaster.incidentBeginDate?.toISOString(),
incidentEndDate: result.femaDisaster.incidentEndDate?.toISOString(),
}
: undefined,
selfDisaster: claim.selfDisaster
? {
...claim.selfDisaster,
startDate: claim.selfDisaster.startDate.toISOString(),
endDate: claim.selfDisaster.endDate?.toISOString(),
createdAt: claim.selfDisaster.createdAt.toISOString(),
updatedAt: claim.selfDisaster.updatedAt.toISOString(),
}
: undefined,
insurancePolicy: result.insurancePolicy
? {
...result.insurancePolicy,
updatedAt: result.insurancePolicy.updatedAt.toISOString(),
createdAt: result.insurancePolicy.createdAt.toISOString(),
}
: undefined,
claimLocations: result.claimLocations
?.map((cl) => cl.locationAddress)
.filter((loc) => loc !== null && loc !== undefined),
};
} catch (error) {
logMessageToFile(`Transaction error: ${error}`);
return null;
}
}
async getClaimsByCompanyId(companyId: string): Promise<GetClaimsByCompanyIdResponse | null> {
try {
const result: Claim[] = await this.db.getRepository(Claim).find({
where: { companyId: companyId },
relations: {
femaDisaster: true,
selfDisaster: true,
insurancePolicy: true,
claimLocations: {
locationAddress: true,
},
purchaseLineItems: true,
},
});
return result.map((claim) => ({
id: claim.id,
name: claim.name,
status: claim.status,
createdAt: claim.createdAt.toISOString(),
updatedAt: claim.updatedAt?.toISOString(),
companyId: claim.companyId,
femaDisaster: claim.femaDisaster
? {
...claim.femaDisaster,
declarationDate: claim.femaDisaster.declarationDate.toISOString(),
incidentBeginDate: claim.femaDisaster.incidentBeginDate?.toISOString() || undefined,
incidentEndDate: claim.femaDisaster.incidentEndDate?.toISOString() || undefined,
}
: undefined,
selfDisaster: claim.selfDisaster
? {
...claim.selfDisaster,
startDate: claim.selfDisaster.startDate.toISOString(),
endDate: claim.selfDisaster.endDate?.toISOString(),
createdAt: claim.selfDisaster.createdAt.toISOString(),
updatedAt: claim.selfDisaster.updatedAt.toISOString(),
}
: undefined,
insurancePolicy: claim.insurancePolicy
? {
...claim.insurancePolicy,
updatedAt: claim.insurancePolicy.updatedAt.toISOString(),
createdAt: claim.insurancePolicy.createdAt.toISOString(),
}
: undefined,
claimLocations: claim.claimLocations
?.map((cl) => cl.locationAddress)
.filter((loc) => loc !== null && loc !== undefined),
purchaseLineItemIds: claim.purchaseLineItems?.map((item) => item.id) ?? [],
}));
} catch (error) {
logMessageToFile(`Transaction error: ${error}`);
return null;
}
}
async deleteClaim(payload: DeleteClaimDTO, companyId: string): Promise<DeleteClaimResponse | null> {
try {
const result = await this.db.manager.delete(Claim, { id: payload.id, companyId: companyId });
if (result.affected === 1) {
return { id: payload.id };
} else {
// TypeORM does not throw an error if the enity to be deleted is not found
logMessageToFile(`Transaction error: claim not found`);
return null;
}
} catch (error) {
logMessageToFile(`Transaction error: ${error}`);
return null;
}
}
async linkClaimToLineItem(payload: LinkClaimToLineItemDTO): Promise<LinkClaimToLineItemResponse | null> {
try {
const existingLink = await this.db.manager
.createQueryBuilder()
.from("claim_purchase_line_items", "bridge")
.where("bridge.claimId = :claimId", { claimId: payload.claimId })
.andWhere("bridge.purchaseLineItemId = :purchaseLineItemId", {
purchaseLineItemId: payload.purchaseLineItemId,
})
.getRawOne();
if (existingLink) {
return payload;
}
await this.db.manager
.createQueryBuilder()
.relation(Claim, "purchaseLineItems")
.of(payload.claimId)
.add(payload.purchaseLineItemId);
return payload;
} catch (error) {
logMessageToFile(`Transaction error: ${error}`);
return null;
}
}
async linkClaimToPurchaseItems(payload: LinkClaimToPurchaseDTO): Promise<LinkClaimToPurchaseResponse | null> {
const purchaseLineItemTransaction: IPurchaseLineItemTransaction = new PurchaseLineItemTransaction(this.db);
const lineItems = await purchaseLineItemTransaction.getPurchaseLineItemsForPurchase(payload.purchaseId);
const lineItemIds = lineItems.map((item) => item.id);
try {
await this.db.manager
.createQueryBuilder()
.relation(Claim, "purchaseLineItems")
.of(payload.claimId)
.add(lineItemIds);
} catch {
return null;
}
const result = lineItemIds.map((id) => ({
claimId: payload.claimId,
purchaseLineItemId: id,
}));
return result;
}
async getLinkedPurchaseLineItems(claimId: string): Promise<GetPurchaseLineItemsForClaimResponse | null> {
const claim = await this.db.manager.findOne(Claim, {
where: { id: claimId },
});
if (!claim) {
return null;
}
const lineItems = await this.db.manager
.createQueryBuilder(PurchaseLineItem, "lineItem")
// this is needed because the claim-line item link is unilateral
.innerJoin("claim_purchase_line_items", "bridge", "bridge.purchaseLineItemId = lineItem.id")
.where("bridge.claimId = :claimId", { claimId })
.getMany();
return lineItems.map((item) => ({
...item,
dateCreated: item.dateCreated.toISOString(),
lastUpdated: item.lastUpdated.toISOString(),
quickbooksDateCreated: item.quickbooksDateCreated?.toISOString(),
}));
}
async deletePurchaseLineItem(claimId: string, lineItemId: string): Promise<DeletePurchaseLineItemResponse | null> {
try {
const claim = await this.db.manager.findOne(Claim, { where: { id: claimId } });
const lineItem = await this.db.manager.findOne(PurchaseLineItem, { where: { id: lineItemId } });
if (!claim || !lineItem) {
return null;
}
await this.db.manager
.createQueryBuilder()
.relation(Claim, "purchaseLineItems")
.of(claimId)
.remove(lineItemId);
return { claimId: claimId, purchaseLineItemId: lineItemId };
} catch (error) {
console.log(error);
logMessageToFile(`Transaction error: ${error}`);
return null;
}
}
async getClaimInProgressForCompany(companyId: string): Promise<GetClaimInProgressForCompanyResponse> {
const claim: Claim | null = await this.db.getRepository(Claim).findOne({
where: {
companyId,
status: In(ClaimStatusInProgressTypes),
},
order: { createdAt: "DESC" },
relations: {
femaDisaster: true,
selfDisaster: true,
insurancePolicy: true,
claimLocations: {
locationAddress: true,
},
purchaseLineItems: true,
},
});
if (claim) {
return {
...claim,
status: claim.status as ClaimStatusType,
createdAt: claim.createdAt.toISOString(),
updatedAt: claim.updatedAt?.toISOString(),
femaDisaster: claim.femaDisaster
? {
...claim.femaDisaster,
declarationDate: claim.femaDisaster.declarationDate.toISOString(),
incidentBeginDate: claim.femaDisaster.incidentBeginDate?.toISOString(),
incidentEndDate: claim.femaDisaster.incidentEndDate?.toISOString(),
}
: undefined,
selfDisaster: claim.selfDisaster
? {
...claim.selfDisaster,
startDate: claim.selfDisaster.startDate.toISOString(),
endDate: claim.selfDisaster.endDate?.toISOString(),
createdAt: claim.selfDisaster.createdAt.toISOString(),
updatedAt: claim.selfDisaster.updatedAt.toISOString(),
}
: undefined,
insurancePolicy: claim.insurancePolicy
? {
...claim.insurancePolicy,
updatedAt: claim.insurancePolicy.updatedAt.toISOString(),
createdAt: claim.insurancePolicy.createdAt.toISOString(),
}
: undefined,
claimLocations: claim.claimLocations
?.map((cl) => cl.locationAddress)
.filter((loc) => loc !== null && loc !== undefined),
purchaseLineItemIds: claim.purchaseLineItems?.map((item) => item.id) ?? [],
};
}
return null;
}
async retrieveDataForPDF(claimId: string, userId: string): Promise<ClaimDataForPDF> {
const claimInfo = await this.db.manager.findOne(Claim, {
where: { id: claimId },
relations: {
company: true,
femaDisaster: true,
selfDisaster: true,
claimLocations: {
locationAddress: true,
},
purchaseLineItems: true,
insurancePolicy: true,
},
});
const userTransaction = new UserTransaction(this.db);
const invoiceTransaction = new InvoiceTransaction(this.db);
const purchaseTransaction = new PurchaseTransaction(this.db);
const user = await userTransaction.getUser({ id: userId });
if (!claimInfo) {
throw Boom.notFound("Could not find the claim");
}
if (!user) {
throw Boom.notFound("Could not find the associated user");
}
const revenues = [];
const purchases = [];
for (let i = 0; i < 3; i++) {
const year = new Date().getFullYear() - 1 - i;
const revenue = await invoiceTransaction.sumInvoicesByCompanyAndDateRange({
companyId: claimInfo.companyId,
startDate: new Date(year, 0, 1).toISOString(),
endDate: new Date(year, 11, 31).toISOString(),
});
revenues.push({ year: year, amountCents: revenue });
const purchaseAmount = await purchaseTransaction.sumPurchasesByCompanyAndDateRange({
companyId: claimInfo.companyId,
startDate: new Date(year, 0, 1).toISOString(),
endDate: new Date(year, 11, 31).toISOString(),
});
purchases.push({ year: year, amountCents: purchaseAmount });
}
const incomeLastThreeYears = await invoiceTransaction.sumInvoicesByCompanyAndDateRange({
companyId: claimInfo.companyId,
startDate: new Date(new Date().setFullYear(new Date().getFullYear() - 4)).toISOString(),
endDate: new Date(new Date().setFullYear(new Date().getFullYear() - 1)).toISOString(),
});
return {
...claimInfo,
user: user,
averageIncome: incomeLastThreeYears / 3,
pastRevenues: revenues,
pastPurchases: purchases,
insuranceInfo: claimInfo.insurancePolicy || undefined,
};
}
async getClaimById(claimId: string, companyId: string): Promise<GetClaimByIdResponse | null> {
try {
const claim = await this.db.getRepository(Claim).findOne({
where: { id: claimId, companyId: companyId },
relations: {
femaDisaster: true,
selfDisaster: true,
insurancePolicy: true,
claimLocations: {
locationAddress: true,
},
purchaseLineItems: true,
},
});
if (!claim) {
return null;
}
return {
id: claim.id,
name: claim.name,
status: claim.status,
createdAt: claim.createdAt.toISOString(),
updatedAt: claim.updatedAt?.toISOString(),
femaDisaster: claim.femaDisaster
? {
...claim.femaDisaster,
declarationDate: claim.femaDisaster.declarationDate.toISOString(),
incidentBeginDate: claim.femaDisaster.incidentBeginDate?.toISOString(),
incidentEndDate: claim.femaDisaster.incidentEndDate?.toISOString(),
}
: undefined,
selfDisaster: claim.selfDisaster
? {
...claim.selfDisaster,
startDate: claim.selfDisaster.startDate.toISOString(),
endDate: claim.selfDisaster.endDate?.toISOString(),
createdAt: claim.selfDisaster.createdAt.toISOString(),
updatedAt: claim.selfDisaster.updatedAt.toISOString(),
}
: undefined,
insurancePolicy: claim.insurancePolicy
? {
...claim.insurancePolicy,
updatedAt: claim.insurancePolicy.updatedAt.toISOString(),
createdAt: claim.insurancePolicy.createdAt.toISOString(),
}
: undefined,
claimLocations: claim.claimLocations
?.map((cl) => cl.locationAddress)
.filter((loc) => loc !== null && loc !== undefined),
purchaseLineItemIds: claim.purchaseLineItems?.map((item) => item.id) ?? [],
};
} catch (error) {
logMessageToFile(`Transaction error: ${error}`);
return null;
}
}
async updateClaimStatus(
claimId: string,
payload: UpdateClaimStatusDTO,
companyId: string
): Promise<UpdateClaimStatusResponse | null> {
try {
const claim = await this.db.getRepository(Claim).findOne({
where: { id: claimId, companyId: companyId },
relations: {
femaDisaster: true,
selfDisaster: true,
insurancePolicy: true,
purchaseLineItems: true,
},
});
if (!claim) {
return null;
}
// Update the status
claim.status = payload.status;
// Update insurance policy if provided
if (payload.insurancePolicyId !== undefined) {
claim.insurancePolicyId = payload.insurancePolicyId;
}
const updatedClaim = await this.db.manager.save(Claim, claim);
// Reload to get updated relations
const result = await this.db.getRepository(Claim).findOne({
where: { id: updatedClaim.id },
relations: {
femaDisaster: true,
selfDisaster: true,
insurancePolicy: true,
claimLocations: {
locationAddress: true,
},
},
});
if (!result) {
return null;
}
return {
id: result.id,
name: result.name,
status: result.status,
createdAt: result.createdAt.toISOString(),
updatedAt: result.updatedAt?.toISOString(),
femaDisaster: result.femaDisaster
? {
...result.femaDisaster,
declarationDate: result.femaDisaster.declarationDate.toISOString(),
incidentBeginDate: result.femaDisaster.incidentBeginDate?.toISOString(),
incidentEndDate: result.femaDisaster.incidentEndDate?.toISOString(),
}
: undefined,
selfDisaster: result.selfDisaster
? {
...result.selfDisaster,
startDate: result.selfDisaster.startDate.toISOString(),
endDate: result.selfDisaster.endDate?.toISOString(),
createdAt: result.selfDisaster.createdAt.toISOString(),
updatedAt: result.selfDisaster.updatedAt.toISOString(),
}
: undefined,
insurancePolicy: result.insurancePolicy
? {
...result.insurancePolicy,
updatedAt: result.insurancePolicy.updatedAt.toISOString(),
createdAt: result.insurancePolicy.createdAt.toISOString(),
}
: undefined,
claimLocations: result.claimLocations
?.map((cl) => cl.locationAddress)
.filter((loc) => loc !== null && loc !== undefined),
purchaseLineItemIds: result.purchaseLineItems?.map((item) => item.id) ?? [],
};
} catch (error) {
logMessageToFile(`Transaction error: ${error}`);
return null;
}
}
async linkClaimToDocument(claimId: string, documentId: string): Promise<void> {
await this.db.manager.createQueryBuilder().relation(Claim, "documents").of(claimId).add(documentId);
}
async getAllDocumentsAssociatedWithClaim(claimId: string): Promise<Document[]> {
const claim = await this.db.getRepository(Claim).findOne({
where: { id: claimId },
relations: ["documents"],
});
return claim?.documents || [];
}
}