-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadmin.service.ts
More file actions
1675 lines (1516 loc) · 50.3 KB
/
Copy pathadmin.service.ts
File metadata and controls
1675 lines (1516 loc) · 50.3 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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
Injectable,
HttpStatus,
NotFoundException,
BadRequestException,
UnauthorizedException,
} from '@nestjs/common';
import {
Prisma,
payment_status,
winnings_category,
winnings_type,
} 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 { PrizeType } from '../challenges/models';
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';
import {
TopcoderEngagementAssignment,
TopcoderEngagementDetails,
TopcoderEngagementsService,
} from 'src/shared/topcoder/engagements.service';
import { TopcoderMembersService } from 'src/shared/topcoder/members.service';
import {
TopcoderChallengeInfo,
TopcoderChallengesService,
} from 'src/shared/topcoder/challenges.service';
import { resolveChallengeMemberPaymentAmount } from 'src/shared/payments/challenge-payment-amount.util';
import {
PaymentCycle,
WinningPaymentDetailsDto,
} from './dto/payment-details.dto';
const PAYMENT_DECIMAL_PLACES = 2;
const BUDGET_LEDGER_DECIMAL_PLACES = 4;
interface ChallengeBudgetSyncTarget {
billingAccountId: number;
challengeId: string;
}
interface EngagementBudgetSyncTarget {
assignmentId: string;
billingAccountId: number;
}
/**
* 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,
private readonly topcoderEngagementsService: TopcoderEngagementsService,
private readonly tcMembersService: TopcoderMembersService,
private readonly topcoderChallengesService: TopcoderChallengesService,
) {}
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 getStringAttribute(
attributes: Prisma.JsonValue | null,
attributeName: string,
): string | undefined {
if (
!attributes ||
typeof attributes !== 'object' ||
Array.isArray(attributes)
) {
return undefined;
}
const value = (attributes as Record<string, unknown>)[attributeName];
if (typeof value !== 'string') {
return undefined;
}
const normalizedValue = value.trim();
return normalizedValue || undefined;
}
private getNumericAttribute(
attributes: Prisma.JsonValue | null,
attributeName: string,
): number | undefined {
if (
!attributes ||
typeof attributes !== 'object' ||
Array.isArray(attributes)
) {
return undefined;
}
const value = (attributes as Record<string, unknown>)[attributeName];
if (value === undefined || value === null || value === '') {
return undefined;
}
const parsedValue = Number(value);
return Number.isFinite(parsedValue) ? parsedValue : undefined;
}
private getWinningAssignmentId(
winning: Awaited<ReturnType<AdminService['getWinningById']>>,
): string | undefined {
if (
!winning?.attributes ||
typeof winning.attributes !== 'object' ||
Array.isArray(winning.attributes)
) {
return undefined;
}
const assignmentId = (winning.attributes as Record<string, unknown>)
.assignmentId;
if (typeof assignmentId === 'string') {
const normalizedAssignmentId = assignmentId.trim();
return normalizedAssignmentId || undefined;
}
if (typeof assignmentId === 'number' && Number.isFinite(assignmentId)) {
return String(assignmentId);
}
return undefined;
}
/**
* Resolves the wallet-admin payment creator into a handle for display.
*
* @param createdBy raw `created_by` value stored on the winnings row.
* @returns The resolved Topcoder handle, or the original identifier when the
* handle lookup fails.
* @throws This helper does not throw.
*/
private async getPaymentCreatorHandle(
createdBy: unknown,
): Promise<string | undefined> {
if (typeof createdBy !== 'string') {
return undefined;
}
const paymentCreatorId = createdBy.trim();
if (!paymentCreatorId) {
return undefined;
}
try {
const handles = await this.tcMembersService.getHandlesByUserIds([
paymentCreatorId,
]);
return handles[paymentCreatorId] ?? paymentCreatorId;
} catch (error) {
this.logger.warn(
`Failed to resolve payment creator handle for winnings creator ${paymentCreatorId}`,
error instanceof Error ? error.message : error,
);
return paymentCreatorId;
}
}
/**
* Finds the engagement assignment that best matches the current winning.
*
* @param assignments assignments returned by the engagements API.
* @param winnerId Topcoder member identifier stored on the winning.
* @param assignmentId optional assignment identifier captured on the winning.
* @returns the matched assignment, or the only assignment when the engagement
* has a single assignee.
* @throws This helper does not throw.
*/
private findMatchingEngagementAssignment(
assignments: TopcoderEngagementAssignment[] | null | undefined,
winnerId: string,
assignmentId?: string,
): TopcoderEngagementAssignment | undefined {
if (!Array.isArray(assignments) || assignments.length === 0) {
return undefined;
}
if (assignmentId) {
const assignmentMatch = assignments.find((item) => {
if (item.id === undefined || item.id === null) {
return false;
}
return String(item.id).trim() === assignmentId;
});
if (assignmentMatch) {
return assignmentMatch;
}
}
const winnerMatch = assignments.find((item) => {
if (item.memberId === undefined || item.memberId === null) {
return false;
}
return String(item.memberId).trim() === winnerId;
});
if (winnerMatch) {
return winnerMatch;
}
return assignments.length === 1 ? assignments[0] : undefined;
}
/**
* Builds wallet-admin engagement details from an engagement record.
*
* @param engagement engagement payload returned by the engagements API.
* @param assignment matched assignment for the winning, when available.
* @param assignmentId optional assignment identifier captured on the winning.
* @returns engagement details shaped for the payment details response.
* @throws This helper does not throw.
*/
private buildEngagementDetailsFromEngagement(
engagement: TopcoderEngagementDetails,
assignment?: TopcoderEngagementAssignment,
assignmentId?: string,
): WinningPaymentDetailsDto['engagementDetails'] {
const durationMonths =
assignment?.durationMonths !== undefined &&
assignment.durationMonths !== null
? Number(assignment.durationMonths)
: undefined;
const standardHoursPerWeek =
assignment?.standardHoursPerWeek !== undefined &&
assignment.standardHoursPerWeek !== null
? Number(assignment.standardHoursPerWeek)
: undefined;
const standardHoursPerDay =
assignment?.standardHoursPerDay !== undefined &&
assignment.standardHoursPerDay !== null
? Number(assignment.standardHoursPerDay)
: Number.isFinite(standardHoursPerWeek)
? Number(((standardHoursPerWeek ?? 0) / 5).toFixed(2))
: undefined;
const projectId = engagement.projectId ?? engagement.project?.id;
const projectName =
(engagement.projectName ?? engagement.project?.name)?.trim() ?? undefined;
const engagementId =
engagement.id !== undefined && engagement.id !== null
? String(engagement.id).trim() || undefined
: undefined;
return {
assignmentId:
assignment?.id !== undefined && assignment.id !== null
? String(assignment.id).trim() || assignmentId
: assignmentId,
engagementId,
projectId:
projectId !== undefined && projectId !== null
? String(projectId).trim() || undefined
: undefined,
projectName,
engagementTitle: engagement.title?.trim() ?? undefined,
billingStartDate: assignment?.startDate
? new Date(assignment.startDate)
: undefined,
durationMonths: Number.isFinite(durationMonths)
? durationMonths
: undefined,
ratePerHour: assignment?.ratePerHour?.trim() ?? undefined,
paymentCycle: (assignment?.paymentCycle?.trim() ||
'WEEKLY') as PaymentCycle,
standardHoursPerDay: Number.isFinite(standardHoursPerDay)
? standardHoursPerDay
: undefined,
standardHoursPerWeek: Number.isFinite(standardHoursPerWeek)
? standardHoursPerWeek
: undefined,
otherRemarks: assignment?.otherRemarks?.trim() ?? undefined,
};
}
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,
},
});
}
/**
* Normalizes billing-account identifiers read from persisted payment or
* challenge records.
*
* @param billingAccountId raw billing-account id value.
* @returns positive integer billing-account id, or `undefined` when the value
* is missing or malformed.
* @throws This helper does not throw.
*/
private normalizeBillingAccountId(
billingAccountId: unknown,
): number | undefined {
if (billingAccountId === undefined || billingAccountId === null) {
return undefined;
}
if (
typeof billingAccountId !== 'string' &&
typeof billingAccountId !== 'number'
) {
return undefined;
}
const normalizedBillingAccountId = String(billingAccountId).trim();
const parsedBillingAccountId = Number(normalizedBillingAccountId);
if (
!normalizedBillingAccountId ||
!/^\d+$/.test(normalizedBillingAccountId) ||
!Number.isSafeInteger(parsedBillingAccountId) ||
parsedBillingAccountId <= 0
) {
return undefined;
}
return parsedBillingAccountId;
}
/**
* Finds challenge billing-account rows that need to be recalculated after a
* wallet-admin payment status or amount change.
*
* @param payments payment rows selected by the update request.
* @returns unique challenge and billing-account pairs touched by USD
* challenge payments.
* @throws This helper does not throw.
*/
private getChallengeBudgetSyncTargets(
payments: Awaited<ReturnType<AdminService['getPaymentsByWinningsId']>>,
): ChallengeBudgetSyncTarget[] {
const targets = new Map<string, ChallengeBudgetSyncTarget>();
payments.forEach((payment) => {
const challengeId =
typeof payment.winnings.external_id === 'string'
? payment.winnings.external_id.trim()
: '';
if (
!challengeId ||
payment.winnings.type !== winnings_type.PAYMENT ||
payment.winnings.category === winnings_category.ENGAGEMENT_PAYMENT ||
(payment.currency ?? '') !== 'USD'
) {
return;
}
const billingAccountId = this.normalizeBillingAccountId(
payment.billing_account,
);
if (!billingAccountId) {
this.logger.warn(
`Skipping challenge budget sync for payment ${payment.payment_id}; invalid billing account ${String(payment.billing_account)}`,
);
return;
}
targets.set(`${challengeId}:${billingAccountId}`, {
billingAccountId,
challengeId,
});
});
return [...targets.values()];
}
/**
* Finds engagement billing-account rows that need to be reconciled after a
* wallet-admin payment status or amount change.
*
* @param payments payment rows selected by the update request.
* @returns unique engagement assignment and billing-account pairs touched by
* USD engagement payments.
* @throws This helper does not throw.
*/
private getEngagementBudgetSyncTargets(
payments: Awaited<ReturnType<AdminService['getPaymentsByWinningsId']>>,
): EngagementBudgetSyncTarget[] {
const targets = new Map<string, EngagementBudgetSyncTarget>();
payments.forEach((payment) => {
const assignmentId =
typeof payment.winnings.external_id === 'string'
? payment.winnings.external_id.trim()
: '';
if (
!assignmentId ||
payment.winnings.type !== winnings_type.PAYMENT ||
payment.winnings.category !== winnings_category.ENGAGEMENT_PAYMENT ||
(payment.currency ?? '') !== 'USD'
) {
return;
}
const billingAccountId = this.normalizeBillingAccountId(
payment.billing_account,
);
if (!billingAccountId) {
this.logger.warn(
`Skipping engagement budget sync for payment ${payment.payment_id}; invalid billing account ${String(payment.billing_account)}`,
);
return;
}
targets.set(`${assignmentId}:${billingAccountId}`, {
assignmentId,
billingAccountId,
});
});
return [...targets.values()];
}
/**
* Resolves the billing account to synchronize for a challenge.
*
* @param challenge challenge-api-v6 payload.
* @param fallbackBillingAccountId billing account from the payment row when
* challenge metadata does not expose one.
* @returns the configured challenge billing account when available, otherwise
* the payment-row billing account.
* @throws This helper does not throw.
*/
private resolveChallengeBudgetBillingAccountId(
challenge: TopcoderChallengeInfo,
fallbackBillingAccountId: number,
): number {
return (
this.normalizeBillingAccountId(challenge.billing?.billingAccountId) ??
fallbackBillingAccountId
);
}
/**
* Resolves the markup used when writing a challenge budget line item.
*
* @param challenge challenge-api-v6 payload.
* @param billingAccountId billing account being synchronized.
* @returns non-negative markup rate.
* @throws Error when no valid markup can be resolved.
*/
private async resolveChallengeBudgetMarkup(
challenge: TopcoderChallengeInfo,
billingAccountId: number,
): Promise<number> {
const candidateMarkups = [
challenge.billing?.clientBillingRate,
challenge.billing?.markup,
];
for (const candidateMarkup of candidateMarkups) {
const markup = Number(candidateMarkup);
if (Number.isFinite(markup) && markup >= 0) {
return markup;
}
}
const billingAccount =
await this.baService.getBillingAccountById(billingAccountId);
if (!Number.isFinite(billingAccount.markup) || billingAccount.markup < 0) {
throw new Error(`Billing account ${billingAccountId} has invalid markup`);
}
return billingAccount.markup;
}
/**
* Quantizes a payment total to the same two-decimal scale used by persisted
* payment rows.
*
* @param amount decimal amount to normalize.
* @returns JavaScript number rounded to two decimal places.
* @throws This helper does not throw.
*/
private toPaymentAmount(amount: Prisma.Decimal): number {
return Number(
amount
.toDecimalPlaces(PAYMENT_DECIMAL_PLACES, Prisma.Decimal.ROUND_HALF_UP)
.toFixed(PAYMENT_DECIMAL_PLACES),
);
}
/**
* Quantizes a billing-account ledger amount to the same four-decimal scale
* used by billing-accounts-api-v6.
*
* @param amount decimal amount to normalize.
* @returns JavaScript number rounded to four decimal places.
* @throws This helper does not throw.
*/
private toBillingLedgerAmount(amount: Prisma.Decimal): number {
return Number(
amount
.toDecimalPlaces(
BUDGET_LEDGER_DECIMAL_PLACES,
Prisma.Decimal.ROUND_HALF_UP,
)
.toFixed(BUDGET_LEDGER_DECIMAL_PLACES),
);
}
/**
* Recomputes the persisted engagement billing fee after an admin amount edit.
*
* Engagement consumed rows store payment total plus `payment.challenge_fee`.
* When wallet admin adjusts the payment total, the fee must be recalculated
* from the persisted markup before finance resyncs the BA consumed row.
*
* @param category winning category for the payment being edited.
* @param challengeMarkup markup persisted on the payment row.
* @param totalAmount new payment total amount.
* @returns recalculated fee for engagement payments, or `undefined` when the
* payment is not an engagement payment or has no valid persisted markup.
* @throws This helper does not throw.
*/
private calculateAdjustedChallengeFee(
category: winnings_category | null,
challengeMarkup: Prisma.Decimal | number | string | null,
totalAmount: number,
): number | undefined {
if (category !== winnings_category.ENGAGEMENT_PAYMENT) {
return undefined;
}
const markup = Number(challengeMarkup);
if (!Number.isFinite(markup) || markup < 0) {
return undefined;
}
return this.toPaymentAmount(
new Prisma.Decimal(totalAmount).mul(new Prisma.Decimal(markup)),
);
}
/**
* Sums non-cancelled USD member-payment rows for a challenge and billing
* account.
*
* @param challengeId challenge external id stored on winnings.
* @param billingAccountId billing account stored on payment rows.
* @returns Total member-payment amount that should remain locked or consumed
* for the challenge billing-account line item. `gross_amount` is used before
* `total_amount` so fee-inclusive totals are not marked up again.
* @throws Prisma errors when the aggregate query fails.
*/
private async getActiveChallengePaymentTotal(
challengeId: string,
billingAccountId: number,
): Promise<number> {
const payments = await this.prisma.payment.findMany({
select: {
gross_amount: true,
total_amount: true,
},
where: {
billing_account: String(billingAccountId),
currency: PrizeType.USD,
payment_status: { not: payment_status.CANCELLED },
winnings: {
external_id: challengeId,
type: 'PAYMENT',
},
},
});
const totalAmount = payments.reduce(
(sum, paymentRow) =>
sum.plus(
resolveChallengeMemberPaymentAmount({
grossAmount: paymentRow.gross_amount,
totalAmount: paymentRow.total_amount,
}),
),
new Prisma.Decimal(0),
);
return this.toPaymentAmount(totalAmount);
}
/**
* Rewrites challenge billing-account budget rows after a wallet-admin update
* changes the active payment total.
*
* @param targets unique challenge and billing-account pairs to synchronize.
* @returns promise resolved after every target has been sent to BA.
* @throws Error when BA synchronization fails.
*/
private async syncChallengeBudgetTargets(
targets: ChallengeBudgetSyncTarget[],
): Promise<void> {
await Promise.all(
targets.map(async (target) => {
const challenge = await this.topcoderChallengesService.getChallengeById(
target.challengeId,
);
if (!challenge?.id || !challenge.status) {
this.logger.warn(
`Skipping challenge budget sync for ${target.challengeId}; challenge metadata is unavailable`,
);
return;
}
const billingAccountId = this.resolveChallengeBudgetBillingAccountId(
challenge,
target.billingAccountId,
);
const markup = await this.resolveChallengeBudgetMarkup(
challenge,
billingAccountId,
);
const totalUsdAmount = await this.getActiveChallengePaymentTotal(
target.challengeId,
billingAccountId,
);
await this.baService.lockConsumeAmount({
billingAccountId,
challengeId: target.challengeId,
markup,
status: challenge.status,
totalPrizesInCents: totalUsdAmount * 100,
});
}),
);
}
/**
* Reads active engagement payment ledger amounts for one assignment.
*
* @param assignmentId engagement assignment external id stored on winnings.
* @param billingAccountId billing account stored on payment rows.
* @returns ledger-scale consumed amounts for non-cancelled finance payments,
* in the same order used when engagement consumed rows were created.
* @throws Prisma errors when the payment query fails.
*/
private async getActiveEngagementConsumeAmounts(
assignmentId: string,
billingAccountId: number,
): Promise<number[]> {
const payments = await this.prisma.payment.findMany({
select: {
challenge_fee: true,
total_amount: true,
},
where: {
billing_account: String(billingAccountId),
currency: PrizeType.USD,
payment_status: { not: payment_status.CANCELLED },
winnings: {
category: winnings_category.ENGAGEMENT_PAYMENT,
external_id: assignmentId,
type: winnings_type.PAYMENT,
},
},
orderBy: [{ created_at: 'asc' }, { payment_id: 'asc' }],
});
return payments.map((paymentRow) =>
this.toBillingLedgerAmount(
new Prisma.Decimal(paymentRow.total_amount ?? 0).plus(
new Prisma.Decimal(paymentRow.challenge_fee ?? 0),
),
),
);
}
/**
* Reconciles engagement billing-account consumed rows after a wallet-admin
* update changes the active payment amounts or active payment set.
*
* @param targets unique engagement assignment and billing-account pairs to
* synchronize.
* @returns promise resolved after every target has been reconciled in BA.
* @throws Error when BA synchronization fails.
*/
private async syncEngagementBudgetTargets(
targets: EngagementBudgetSyncTarget[],
): Promise<void> {
await Promise.all(
targets.map(async (target) => {
const amounts = await this.getActiveEngagementConsumeAmounts(
target.assignmentId,
target.billingAccountId,
);
await this.baService.syncEngagementConsumeAmounts({
amounts,
billingAccountId: target.billingAccountId,
externalId: target.assignmentId,
});
}),
);
}
/**
* 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();
const shouldSyncBudget =
body.paymentStatus === PaymentStatus.CANCELLED ||
body.paymentAmount !== undefined;
const challengeBudgetSyncTargets = shouldSyncBudget
? this.getChallengeBudgetSyncTargets(payments)
: [];
const engagementBudgetSyncTargets = shouldSyncBudget
? this.getEngagementBudgetSyncTargets(payments)
: [];
// 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 === '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');
}
}