-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadmin.service.ts
More file actions
771 lines (709 loc) · 22.1 KB
/
Copy pathadmin.service.ts
File metadata and controls
771 lines (709 loc) · 22.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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
import {
Injectable,
HttpStatus,
NotFoundException,
BadRequestException,
UnauthorizedException,
} from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from 'src/shared/global/prisma.service';
import { PaymentsService } from 'src/shared/payments';
import { AccessControlService } from 'src/shared/access-control/access-control.service';
import { ResponseDto } from 'src/dto/api-response.dto';
import { PaymentStatus } from 'src/dto/payment.dto';
import { WinningAuditDto, AuditPayoutDto } from './dto/audit.dto';
import { WinningUpdateRequestDto } from './dto/winnings.dto';
import { Logger } from 'src/shared/global';
import { BillingAccountsService } from 'src/shared/topcoder/billing-accounts.service';
/**
* The admin winning service.
*/
@Injectable()
export class AdminService {
private readonly logger = new Logger(AdminService.name);
/**
* Constructs the admin winning service with the given dependencies.
* @param prisma the prisma service.
*/
constructor(
private readonly prisma: PrismaService,
private readonly paymentsService: PaymentsService,
private readonly baService: BillingAccountsService,
private readonly accessControlService: AccessControlService,
) {}
async verifyUserAccessToWinning(
winningsId: string,
userId: string,
roles: string[] = [],
): Promise<void> {
try {
await this.accessControlService.verifyAccess(winningsId, userId, roles);
} catch (err) {
throw new UnauthorizedException(err?.message ?? 'access denied');
}
}
private getWinningById(winningId: string) {
return this.prisma.winnings.findFirst({ where: { winning_id: winningId } });
}
private getPaymentsByWinningsId(winningsId: string, paymentId?: string) {
return this.prisma.payment.findMany({
where: {
winnings_id: {
equals: winningsId,
},
payment_id: paymentId
? {
equals: paymentId,
}
: undefined,
},
include: {
winnings: true,
},
});
}
/**
* Verify that a BA admin user has access to the billing account(s)
* associated with the given winningsId. Throws BadRequestException when
* access is not allowed.
*/
async verifyBaAdminAccessToWinning(
winningsId: string,
userId: string,
): Promise<void> {
const payments = await this.prisma.payment.findMany({
where: {
winnings_id: {
equals: winningsId,
},
},
select: {
billing_account: true,
},
});
if (!payments || payments.length === 0) {
// nothing to check
return;
}
const allowedBAs = await this.baService.getBillingAccountsForUser(userId);
const paymentBAs = payments
.map((p) => p.billing_account)
.filter((b) => b !== null && b !== undefined);
const unauthorized = paymentBAs.some((ba) => !allowedBAs.includes(`${ba}`));
if (unauthorized) {
this.logger.warn(
`BA admin ${userId} attempted to access winnings ${winningsId} for unauthorized billing account(s)`,
);
throw new BadRequestException(
'BA admin user does not have access to the billing account for this winnings',
);
}
}
/**
* Update winnings with parameters
* @param body the request body
* @param userId the request user id
* @returns the Promise with response result
*/
async updateWinnings(
body: WinningUpdateRequestDto,
userId: string,
roles: string[] = [],
): Promise<ResponseDto<string>> {
const result = new ResponseDto<string>();
let needsReconciliation = false;
const winningsId = body.winningsId;
this.logger.log(
`updateWinnings called by ${userId} for winningsId=${winningsId}`,
);
this.logger.log(`updateWinnings payload: ${JSON.stringify(body)}`);
await this.verifyUserAccessToWinning(body.winningsId, userId, roles);
try {
const payments = await this.getPaymentsByWinningsId(
winningsId,
body.paymentId,
);
this.logger.log(
`Found ${payments.length} payment(s) for winningsId=${winningsId}`,
);
if (payments.length === 0) {
this.logger.warn(
`No payments found for winningsId=${winningsId}, paymentId=${body.paymentId}`,
);
throw new NotFoundException('failed to get current payments');
}
let releaseDate;
if (body.paymentStatus) {
releaseDate = await this.getPaymentReleaseDateByWinningsId(winningsId);
this.logger.log(
`Payment release date for winningsId=${winningsId}: ${releaseDate}`,
);
}
const transactions: ((
tx: Prisma.TransactionClient,
) => Promise<unknown>)[] = [];
const now = new Date().getTime();
// iterate payments and build transaction list
payments.forEach((payment) => {
this.logger.log(
`Processing payment ${payment.payment_id} (installment ${payment.installment_number}) with current status=${payment.payment_status}`,
);
if (
payment.payment_status &&
payment.payment_status === PaymentStatus.CANCELLED
) {
this.logger.warn(
`Attempt to update cancelled payment ${payment.payment_id} — rejecting`,
);
throw new BadRequestException('cannot update cancelled winnings');
}
let version = payment.version ?? 1;
const queuedActions: string[] = [];
if (body.description) {
transactions.push((tx) =>
tx.payment.update({
where: {
payment_id: payment.payment_id,
version: version,
},
data: {
winnings: {
update: {
data: {
description: body.description,
},
},
},
updated_at: new Date(),
updated_by: userId,
version,
},
}),
);
queuedActions.push(
`update description -> "${body.description}" (version ${version})`,
);
if (payment.installment_number === 1) {
transactions.push((tx) =>
this.addAudit(
userId,
winningsId,
`Modified payment description from "${payment.winnings.description}" to "${body.description}"`,
body.auditNote,
tx,
),
);
queuedActions.push('add audit for description change');
}
}
let paymentStatus = payment.payment_status as PaymentStatus;
// Update Payment Status if requested
if (body.paymentStatus) {
let errMessage = '';
switch (body.paymentStatus) {
case PaymentStatus.ON_HOLD_ADMIN:
errMessage = 'cannot put a processing payment on hold';
break;
case PaymentStatus.CANCELLED:
errMessage = 'cannot cancel processing payment';
break;
case PaymentStatus.OWED:
if (releaseDate) {
const sinceRelease =
(now - releaseDate.getTime()) / (3600 * 1000);
if (sinceRelease < 12) {
errMessage = `Cannot put a processing payment back to owed, unless it's been processing for at least 12 hours. Currently it's only been ${sinceRelease.toFixed(1)} hours`;
} else {
transactions.push((tx) =>
this.markPaymentReleaseAsFailedByWinningsId(winningsId, tx),
);
}
} else {
errMessage = 'cannot put a processing payment back to owed';
if (
payment.payment_status !== PaymentStatus.ON_HOLD_ADMIN &&
payment.payment_status !== PaymentStatus.PAID
) {
this.logger.warn(
`Invalid attempt to set OWED for payment ${payment.payment_id} when not on hold admin or paid`,
);
throw new BadRequestException(
"cannot put a payment back to owed unless it is on hold by an admin, or it's been paid",
);
}
}
break;
default:
this.logger.warn(
`Invalid payment status provided: ${body.paymentStatus}`,
);
throw new BadRequestException('invalid payment status provided');
}
if (
errMessage &&
payment.payment_status === PaymentStatus.PROCESSING
) {
this.logger.warn(
`Rejected status change for ${payment.payment_id}: ${errMessage}`,
);
throw new BadRequestException(errMessage);
}
transactions.push((tx) =>
this.updatePaymentStatus(
userId,
winningsId,
payment.payment_id,
payment.payment_status,
body.paymentStatus,
version++,
tx,
),
);
queuedActions.push(
`update status ${payment.payment_status} -> ${body.paymentStatus}`,
);
paymentStatus = body.paymentStatus as PaymentStatus;
if (body.paymentStatus === PaymentStatus.OWED) {
needsReconciliation = true;
this.logger.log(
`Payment ${payment.payment_id} marked OWED; will trigger reconciliation later`,
);
}
if (payment.installment_number === 1) {
transactions.push((tx) =>
this.addAudit(
userId,
winningsId,
`Modified payment status from ${payment.payment_status} to ${body.paymentStatus}`,
body.auditNote,
tx,
),
);
queuedActions.push('add audit for status change');
}
}
// Update Release Date if requested
if (body.releaseDate) {
const newReleaseDate = new Date(body.releaseDate);
if (
![
PaymentStatus.OWED,
PaymentStatus.ON_HOLD,
PaymentStatus.ON_HOLD_ADMIN,
].includes(paymentStatus)
) {
this.logger.warn(
`Cannot update release date for payment ${payment.payment_id} in status ${paymentStatus}`,
);
throw new BadRequestException(
`Cannot update release date for payment unless it's in one of the states: ${[
PaymentStatus.OWED,
PaymentStatus.ON_HOLD,
PaymentStatus.ON_HOLD_ADMIN,
].join(', ')}`,
);
}
transactions.push((tx) =>
this.updateReleaseDate(
userId,
winningsId,
payment.payment_id,
newReleaseDate,
version++,
tx,
),
);
queuedActions.push(
`update release_date ${payment.release_date?.toISOString()} -> ${newReleaseDate.toISOString()}`,
);
if (payment.installment_number === 1) {
transactions.push((tx) =>
this.addAudit(
userId,
winningsId,
`Modified release date from ${payment.release_date?.toISOString()} to ${newReleaseDate.toISOString()}`,
body.auditNote,
tx,
),
);
queuedActions.push('add audit for release date change');
}
}
// Update payment amount if requested
if (
body.paymentAmount !== undefined &&
(payment.payment_status === PaymentStatus.OWED ||
payment.payment_status === PaymentStatus.ON_HOLD ||
payment.payment_status === PaymentStatus.ON_HOLD_ADMIN)
) {
// ideally we should be maintaining the original split of the payment amount between installments - but we aren't really using splits anymore
if (payment.installment_number === 1) {
transactions.push((tx) =>
this.updatePaymentAmount(
userId,
winningsId,
payment.payment_id,
body.paymentAmount,
body.paymentAmount,
body.paymentAmount,
version,
tx,
),
);
transactions.push((tx) =>
this.addAudit(
userId,
winningsId,
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`Modified payment amount from ${payment.total_amount} to ${body.paymentAmount.toFixed(2)}`,
body.auditNote,
tx,
),
);
queuedActions.push(
`update amounts -> ${body.paymentAmount.toFixed(2)} (installment 1)`,
);
} else {
transactions.push((tx) =>
this.updatePaymentAmount(
userId,
winningsId,
payment.payment_id,
0,
0,
body.paymentAmount,
version,
tx,
),
);
queuedActions.push(
`update amounts -> total ${body.paymentAmount.toFixed(2)} (installment ${payment.installment_number})`,
);
}
}
this.logger.log(
`Queued ${queuedActions.length} action(s) for payment ${payment.payment_id}: ${queuedActions.join(
' ; ',
)}`,
);
});
this.logger.log(
`Executing ${transactions.length} transaction step(s) for winningsId=${winningsId}`,
);
// Run all transaction tasks in a single prisma transaction
await this.prisma.$transaction(async (tx) => {
for (let i = 0; i < transactions.length; i++) {
this.logger.log(
`Executing transaction ${i + 1}/${transactions.length}`,
);
await transactions[i](tx);
}
});
this.logger.log(
`Successfully executed transactions for winningsId=${winningsId}`,
);
if (needsReconciliation) {
const winning = await this.prisma.winnings.findFirst({
select: {
winner_id: true,
},
where: {
winning_id: winningsId,
},
});
if (winning?.winner_id) {
this.logger.log(
`Triggering payments reconciliation for user ${winning.winner_id}`,
);
await this.paymentsService.reconcileUserPayments(winning.winner_id);
this.logger.log(
`Reconciliation triggered for user ${winning.winner_id}`,
);
} else {
this.logger.warn(
`Needs reconciliation but no winner_id found for winningsId=${winningsId}`,
);
}
}
result.data = 'Successfully updated winnings';
this.logger.log(
`updateWinnings completed for winningsId=${winningsId}: ${result.data}`,
);
} catch (error) {
if (
error instanceof NotFoundException ||
error instanceof BadRequestException
) {
this.logger.warn(
`updateWinnings validation error for winningsId=${winningsId}: ${error.message}`,
);
throw error;
}
this.logger.error('Updating winnings failed', error);
const message = 'Updating winnings failed. ' + error;
result.error = {
code: HttpStatus.INTERNAL_SERVER_ERROR,
message,
};
}
return result;
}
private async getPaymentReleaseDateByWinningsId(
winningsId: string,
): Promise<Date | null | undefined> {
const paymentReleases = await this.prisma.payment_releases.findFirst({
where: {
payment_release_associations: {
some: {
payment: {
winnings_id: {
equals: winningsId,
},
},
},
},
},
include: {
payment_release_associations: {
include: {
payment: true,
},
},
},
});
return paymentReleases?.release_date;
}
private markPaymentReleaseAsFailedByWinningsId(
winningsId: string,
tx?: Prisma.TransactionClient,
) {
return (tx ?? this.prisma).payment_releases.updateMany({
where: {
payment_release_associations: {
some: {
payment: {
winnings_id: {
equals: winningsId,
},
},
},
},
},
data: {
status: 'FAILED',
},
});
}
private updatePaymentStatus(
userId: string,
winningsId: string,
paymentId: string,
oldPaymentStatus: string | null,
newPaymentStatus: PaymentStatus,
currentVersion: number,
tx?: Prisma.TransactionClient,
) {
let setDatePaidNull = false;
if (
[
PaymentStatus.PAID,
PaymentStatus.PROCESSING,
PaymentStatus.RETURNED,
PaymentStatus.FAILED,
].includes(oldPaymentStatus as PaymentStatus) &&
newPaymentStatus === PaymentStatus.OWED
) {
setDatePaidNull = true;
}
return (tx ?? this.prisma).payment.update({
where: {
payment_id: paymentId,
winnings_id: winningsId,
version: currentVersion,
},
data: {
payment_status: newPaymentStatus,
updated_at: new Date(),
updated_by: userId,
version: currentVersion + 1,
date_paid: setDatePaidNull ? null : undefined,
},
});
}
private addAudit(
userId: string,
winningsId: string,
action: string,
auditNote?: string,
tx?: Prisma.TransactionClient,
) {
return (tx ?? this.prisma).audit.create({
data: {
user_id: userId,
winnings_id: winningsId,
action,
note: auditNote,
},
});
}
private updateReleaseDate(
userId: string,
winningsId: string,
paymentId: string,
newReleaseDate: Date,
currentVersion: number,
tx?: Prisma.TransactionClient,
) {
return (tx ?? this.prisma).payment.update({
where: {
payment_id: paymentId,
winnings_id: winningsId,
version: currentVersion,
payment_status: {
in: [
PaymentStatus.OWED,
PaymentStatus.ON_HOLD,
PaymentStatus.ON_HOLD_ADMIN,
],
},
},
data: {
release_date: newReleaseDate,
updated_at: new Date(),
updated_by: userId,
version: currentVersion + 1,
},
});
}
private updatePaymentAmount(
userId: string,
winningsId: string,
paymentId: string,
netAmount: number,
grossAmount: number,
totalAmount: number,
currentVersion: number,
tx?: Prisma.TransactionClient,
) {
return (tx ?? this.prisma).payment.update({
where: {
payment_id: paymentId,
winnings_id: winningsId,
version: currentVersion,
payment_status: {
in: [
PaymentStatus.OWED,
PaymentStatus.ON_HOLD,
PaymentStatus.ON_HOLD_ADMIN,
PaymentStatus.PAID,
PaymentStatus.PROCESSING,
],
},
},
data: {
net_amount: netAmount,
gross_amount: grossAmount,
total_amount: totalAmount,
updated_at: new Date(),
updated_by: userId,
version: currentVersion + 1,
},
});
}
/**
* Get winning audit for winningId
* @param winningId the winningId
* @returns the Promise with response result
*/
async getWinningAudit(
winningId: string,
tx?: Prisma.TransactionClient,
): Promise<ResponseDto<WinningAuditDto[]>> {
const result = new ResponseDto<WinningAuditDto[]>();
try {
const audits = await (tx ?? this.prisma).audit.findMany({
where: {
winnings_id: {
equals: winningId,
},
},
take: 1000,
orderBy: { created_at: 'desc' },
});
result.data = audits.map((item) => ({
id: item.id,
winningsId: item.winnings_id,
userId: item.user_id,
action: item.action,
note: item.note,
createdAt: item.created_at,
}));
} catch (error) {
this.logger.error('Getting winnings audit failed', error);
const message = 'Searching winnings failed. ' + error;
result.error = {
code: HttpStatus.INTERNAL_SERVER_ERROR,
message,
};
}
return result;
}
/**
* Get winning audit for winningId
* @param winningId the winningId
* @returns the Promise with response result
*/
async getWinningAuditPayout(
winningId: string,
tx?: Prisma.TransactionClient,
): Promise<ResponseDto<AuditPayoutDto[]>> {
const result = new ResponseDto<AuditPayoutDto[]>();
try {
const paymentReleases = await (
tx ?? this.prisma
).payment_releases.findMany({
where: {
payment_release_associations: {
some: {
payment: {
winnings_id: {
equals: winningId,
},
},
},
},
},
include: {
payment_release_associations: {
include: {
payment: true,
},
},
payment_method: true,
},
orderBy: [
{
created_at: 'desc',
},
],
});
result.data = paymentReleases.map((item) => ({
externalTransactionId: item.external_transaction_id ?? '',
status: item.status ?? '',
totalNetAmount: item.total_net_amount.toNumber(),
createdAt: item.created_at!,
metadata: JSON.stringify(item.metadata),
paymentMethodUsed: item.payment_method.name,
externalTransactionDetails: {},
}));
} catch (error) {
this.logger.error('Getting winnings audit failed', error);
const message = 'Searching winnings failed. ' + error;
result.error = {
code: HttpStatus.INTERNAL_SERVER_ERROR,
message,
};
}
return result;
}
}