-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathChallengeService.ts
More file actions
5900 lines (5390 loc) · 195 KB
/
Copy pathChallengeService.ts
File metadata and controls
5900 lines (5390 loc) · 195 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
/**
* This service provides operations of challenge.
*/
const _ = require("lodash");
const Joi = require("joi");
const { Prisma } = require("@prisma/client");
const { v4: uuid } = require("uuid");
const config = require("config");
const xss = require("xss");
const helper = require("../common/helper");
const logger = require("../common/logger");
const errors = require("../common/errors");
const constants = require("../../app-constants");
const ChallengeTimelineTemplateService = require("./ChallengeTimelineTemplateService");
const { BadRequestError } = require("../common/errors");
const phaseHelper = require("../common/phase-helper");
const projectHelper = require("../common/project-helper");
const challengeHelper = require("../common/challenge-helper");
const { getReviewClient } = require("../common/review-prisma");
const PhaseAdvancer = require("../phase-management/PhaseAdvancer");
const { hasAdminRole } = require("../common/role-helper");
const { enrichChallengeForResponse, convertToISOString } = require("../common/challenge-helper");
const deepEqual = require("deep-equal");
const prismaHelper = require("../common/prisma-helper");
const {
getClient,
ReviewTypeEnum,
DiscussionTypeEnum,
ChallengeStatusEnum,
PrizeSetTypeEnum,
ReviewOpportunityTypeEnum,
} = require("../common/prisma");
const prisma = getClient();
const BILLING_MARKUP_COPILOT_ROLES = new Set(["copilot", "connect copilot"]);
const BILLING_MARKUP_VISIBLE_ROLES = new Set([
"administrator",
"connect admin",
"connect manager",
"project manager",
"topcoder project manager",
"talent manager",
"topcoder talent manager",
]);
const CHALLENGE_BILLING_LOCK_STATUSES = new Set([
ChallengeStatusEnum.DRAFT,
ChallengeStatusEnum.APPROVED,
ChallengeStatusEnum.ACTIVE,
]);
const CHALLENGE_APPROVAL_STATUS = {
PENDING_APPROVAL: "PENDING_APPROVAL",
APPROVED: "APPROVED",
REJECTED: "REJECTED",
};
const CHALLENGE_APPROVAL_ACTION_STATUSES = new Set([
CHALLENGE_APPROVAL_STATUS.APPROVED,
CHALLENGE_APPROVAL_STATUS.REJECTED,
]);
const DEFAULT_ESTIMATED_SUBMISSIONS_COUNT = 2;
const CHECKPOINT_SUBMISSION_TYPE = "CHECKPOINT_SUBMISSION";
// Provide aliases for friendlier sortBy query params
const sortByAliases = {
updated: constants.validChallengeParams.Updated,
created: constants.validChallengeParams.Created,
};
const allowedSortByValues = _.uniq([
..._.values(constants.validChallengeParams),
...Object.keys(sortByAliases),
]);
const CANCELLED_CHALLENGE_STATUSES = new Set([
ChallengeStatusEnum.CANCELLED,
ChallengeStatusEnum.CANCELLED_REQUIREMENTS_INFEASIBLE,
ChallengeStatusEnum.CANCELLED_PAYMENT_FAILED,
ChallengeStatusEnum.CANCELLED_FAILED_REVIEW,
ChallengeStatusEnum.CANCELLED_FAILED_SCREENING,
ChallengeStatusEnum.CANCELLED_ZERO_SUBMISSIONS,
ChallengeStatusEnum.CANCELLED_WINNER_UNRESPONSIVE,
ChallengeStatusEnum.CANCELLED_CLIENT_REQUEST,
ChallengeStatusEnum.CANCELLED_ZERO_REGISTRATIONS,
]);
const TERMINAL_CHALLENGE_STATUSES = new Set([
ChallengeStatusEnum.COMPLETED,
...CANCELLED_CHALLENGE_STATUSES,
]);
/**
* Determines whether a challenge status is one of the terminal cancelled states.
* @param {String} status challenge status from the update payload or stored challenge
* @returns {Boolean} true when the status represents a cancelled challenge
*/
function isCancelledChallengeStatus(status) {
return CANCELLED_CHALLENGE_STATUSES.has(status);
}
/**
* Determines whether a challenge has reached a terminal status for test-data cleanup rules.
* Completed and every explicit cancelled status are terminal; draft, approved, active, deleted,
* and new challenges are not.
*
* @param {String} status challenge status from persistence
* @returns {Boolean} true for COMPLETED and CANCELLED* statuses
*/
function isTerminalChallengeStatus(status) {
return TERMINAL_CHALLENGE_STATUSES.has(status);
}
/**
* Reads the effective test-challenge flag from metadata using strict enabled semantics.
* Only the exact metadata pair `is_test_challenge: "true"` is enabled. Missing, false, and
* malformed values are disabled. Update protection and deletion eligibility use this method.
*
* @param {Array<Object>|undefined|null} metadata challenge metadata entries
* @returns {Boolean} true only when an exact enabled metadata entry exists
*/
function isTestChallengeMetadataEnabled(metadata) {
return _.some(metadata, {
name: constants.ChallengeMetadataNames.IS_TEST_CHALLENGE,
value: "true",
});
}
/**
* Prevents changing test-data classification in updates that start or finish terminal.
* Metadata arrays replace the stored array on update, so supplying an array without the flag has
* an effective false value. Omitting the metadata property entirely preserves the stored value.
* This guard runs before project lookups or persistence in updateChallenge.
*
* @param {Object} challenge current persisted challenge response
* @param {Object} data raw validated update payload
* @returns {void}
* @throws {BadRequestError} when a terminal update changes the effective test-challenge flag
*/
function ensureTerminalTestChallengeMetadataIsUnchanged(challenge, data) {
const currentStatus = _.get(challenge, "status");
const finalStatus = _.isNil(_.get(data, "status")) ? currentStatus : _.get(data, "status");
if (
_.isNil(data) ||
(!isTerminalChallengeStatus(currentStatus) && !isTerminalChallengeStatus(finalStatus)) ||
!Object.prototype.hasOwnProperty.call(data, "metadata")
) {
return;
}
const currentFlag = isTestChallengeMetadataEnabled(_.get(challenge, "metadata"));
const requestedFlag = isTestChallengeMetadataEnabled(data.metadata);
if (currentFlag !== requestedFlag) {
throw new errors.BadRequestError(
"is_test_challenge metadata cannot be changed when a challenge is or becomes COMPLETED or CANCELLED",
);
}
}
/**
* Loads submission counters for challenge responses from the review submission table.
*
* Community app badges normally show the number of members with submissions,
* so repeated uploads by the same member are counted once. Design challenges
* count every submission because each upload can be a unique concept.
*
* @param {Array<String>} challengeIds challenge identifiers to count submissions for
* @param {Array<String>} designChallengeIds Design challenge identifiers that count every upload
* @returns {Promise<Map<String, { numOfSubmissions: Number, numOfCheckpointSubmissions: Number }>>}
* counts keyed by challenge id
* @throws {Error} when the review database query fails
*/
async function getLatestSubmissionCountsByChallenge(challengeIds, designChallengeIds = []) {
const ids = _.uniq(
(challengeIds || [])
.map((challengeId) => _.toString(challengeId).trim())
.filter((challengeId) => !!challengeId),
);
const designIds = _.uniq(
(designChallengeIds || [])
.map((challengeId) => _.toString(challengeId).trim())
.filter((challengeId) => !!challengeId),
);
const countsByChallenge = new Map();
if (!ids.length || !config.REVIEW_DB_URL) {
return countsByChallenge;
}
const reviewSchema = _.toString(config.REVIEW_DB_SCHEMA || "").trim();
const submissionTable = reviewSchema
? Prisma.raw(`"${reviewSchema.replace(/"/g, '""')}"."submission"`)
: Prisma.raw('"submission"');
const submissionIdentity = designIds.length
? Prisma.sql`CASE
WHEN "challengeId" IN (${Prisma.join(designIds)}) THEN "id"
ELSE "memberId"
END`
: Prisma.sql`"memberId"`;
const reviewClient = getReviewClient();
const rows = await reviewClient.$queryRaw`
SELECT
"challengeId",
COUNT(DISTINCT CASE
WHEN "type"::text = ${CHECKPOINT_SUBMISSION_TYPE} THEN ${submissionIdentity}
END)::int AS "numOfCheckpointSubmissions",
COUNT(DISTINCT CASE
WHEN "type"::text <> ${CHECKPOINT_SUBMISSION_TYPE} THEN ${submissionIdentity}
END)::int AS "numOfSubmissions"
FROM ${submissionTable}
WHERE "challengeId" IN (${Prisma.join(ids)})
AND "memberId" IS NOT NULL
GROUP BY "challengeId"
`;
rows.forEach((row) => {
countsByChallenge.set(_.toString(row.challengeId), {
numOfSubmissions: Number(row.numOfSubmissions || 0),
numOfCheckpointSubmissions: Number(row.numOfCheckpointSubmissions || 0),
});
});
return countsByChallenge;
}
/**
* Applies submission counts to challenge records before response conversion.
*
* Design challenges count every submission as a separate concept. Other tracks
* count distinct submitting members so replacement attempts do not inflate the
* displayed total.
*
* If the review query succeeds, challenges without submission rows are reset to
* zero so stale stored counters are not shown. If the query cannot run, callers
* keep the stored counters and log a warning instead of failing challenge reads.
*
* @param {Array<Object>} challenges challenge records being returned by the API
* @returns {Promise<void>}
*/
async function applyLatestSubmissionCounts(challenges) {
const records = (challenges || []).filter((challenge) => challenge && challenge.id);
if (!records.length || !config.REVIEW_DB_URL) {
return;
}
let countsByChallenge;
try {
const designChallengeIds = records
.filter((challenge) => phaseHelper.isDesignTrack(challenge.track))
.map((challenge) => challenge.id);
countsByChallenge = await getLatestSubmissionCountsByChallenge(
records.map((challenge) => challenge.id),
designChallengeIds,
);
} catch (err) {
logger.warn(`Failed to load latest submission counts: ${err.message}`);
return;
}
records.forEach((challenge) => {
const counts = countsByChallenge.get(_.toString(challenge.id)) || {
numOfSubmissions: 0,
numOfCheckpointSubmissions: 0,
};
challenge.numOfSubmissions = counts.numOfSubmissions;
challenge.numOfCheckpointSubmissions = counts.numOfCheckpointSubmissions;
});
}
/**
* Loads the latest non-checkpoint Marathon Match submission per member from
* the review database.
*
* The close flow uses this to avoid selecting winners before parallel system
* scoring has produced a final summation for every member's latest attempt.
*
* @param {String} challengeId challenge identifier
* @returns {Promise<Array<Object>>} latest submission rows keyed by member
*/
async function getLatestMarathonMatchSubmissions(challengeId) {
if (!config.REVIEW_DB_URL) {
return [];
}
const reviewSchema = _.toString(config.REVIEW_DB_SCHEMA || "").trim();
const submissionTable = reviewSchema
? Prisma.raw(`"${reviewSchema.replace(/"/g, '""')}"."submission"`)
: Prisma.raw('"submission"');
const reviewClient = getReviewClient();
return reviewClient.$queryRaw`
SELECT
"id",
"memberId",
"submittedDate",
"createdAt",
"updatedAt"
FROM (
SELECT
"id",
"memberId",
"submittedDate",
"createdAt",
"updatedAt",
ROW_NUMBER() OVER (
PARTITION BY "memberId"
ORDER BY
COALESCE("isLatest", false) DESC,
COALESCE("submittedDate", "createdAt", "updatedAt") DESC,
"id" DESC
) AS "rowNumber"
FROM ${submissionTable}
WHERE "challengeId" = ${challengeId}
AND "memberId" IS NOT NULL
AND COALESCE("type"::text, '') <> ${CHECKPOINT_SUBMISSION_TYPE}
AND COALESCE("status"::text, '') <> 'DELETED'
) ranked
WHERE "rowNumber" = 1
`;
}
/**
* Normalizes identifiers used to match review summations to submissions.
* @param {*} value raw identifier value
* @returns {String} trimmed identifier, or an empty string when absent
*/
function normalizeMatchId(value) {
return _.toString(value || "").trim();
}
/**
* Reads a review summation timestamp for latest-result comparisons.
* @param {Object} summation review summation returned by Review API
* @returns {Number} timestamp in milliseconds, or zero when unavailable
*/
function getReviewSummationTimestampValue(summation) {
const candidate =
_.get(summation, "reviewedDate") ||
_.get(summation, "updatedAt") ||
_.get(summation, "createdAt");
const timestamp = new Date(candidate).getTime();
return Number.isFinite(timestamp) ? timestamp : 0;
}
/**
* Compares two review summations for the same submission or submitter.
* Newer summations win; ties keep the higher score.
*
* @param {Object|null} current currently selected summation
* @param {Object} candidate summation being considered
* @returns {Boolean} true when candidate should replace current
*/
function shouldReplaceSelectedReviewSummation(current, candidate) {
if (!current) {
return true;
}
const currentTimestamp = getReviewSummationTimestampValue(current);
const candidateTimestamp = getReviewSummationTimestampValue(candidate);
if (candidateTimestamp !== currentTimestamp) {
return candidateTimestamp > currentTimestamp;
}
return Number(candidate.aggregateScore) > Number(current.aggregateScore);
}
/**
* Finds the newest submission-scoped review summation per submitter.
*
* This is used as a fallback completeness signal when latest submission rows
* cannot be read directly from the review database.
*
* @param {Array<Object>} reviewSummations review summations returned by Review API
* @returns {Map<String, Object>} latest submission-scoped summation by submitter id
*/
function getLatestSubmissionScopedSummationsBySubmitter(reviewSummations) {
const latestBySubmitter = new Map();
(Array.isArray(reviewSummations) ? reviewSummations : []).forEach((summation) => {
const submitterId = normalizeMatchId(summation.submitterId);
const submissionId = normalizeMatchId(summation.submissionId);
if (!submitterId || !submissionId) {
return;
}
if (shouldReplaceSelectedReviewSummation(latestBySubmitter.get(submitterId), summation)) {
latestBySubmitter.set(submitterId, summation);
}
});
return latestBySubmitter;
}
/**
* Selects the final summations that should determine Marathon Match winners.
*
* When latest submission rows are available, every latest submission must have
* a matching final summation. Without submission rows, the function uses the
* newest submission-scoped summation per submitter as a fallback completeness
* signal before ranking the newest final summation per submitter.
*
* @param {String} challengeId challenge identifier used in error messages
* @param {Array<Object>} reviewSummations all review summations
* @param {Array<Object>} finalSummations final review summations
* @param {Array<Object>} latestSubmissions latest submission rows
* @returns {Array<Object>} selected final summations to rank
* @throws {BadRequestError} when any latest submission or fallback latest
* submitter summation has no final summation
*/
function selectMarathonMatchWinnerSummations(
challengeId,
reviewSummations,
finalSummations,
latestSubmissions,
) {
if (!Array.isArray(latestSubmissions) || latestSubmissions.length === 0) {
const latestBySubmitter = new Map();
finalSummations.forEach((summation) => {
const submitterId = normalizeMatchId(summation.submitterId);
if (!submitterId) {
return;
}
if (shouldReplaceSelectedReviewSummation(latestBySubmitter.get(submitterId), summation)) {
latestBySubmitter.set(submitterId, summation);
}
});
const latestKnownSummations = getLatestSubmissionScopedSummationsBySubmitter(reviewSummations);
const missingSubmitters = [];
latestKnownSummations.forEach((latestSummation, submitterId) => {
const selectedFinal = latestBySubmitter.get(submitterId);
if (
!selectedFinal ||
normalizeMatchId(selectedFinal.submissionId) !==
normalizeMatchId(latestSummation.submissionId)
) {
missingSubmitters.push(submitterId);
}
});
if (missingSubmitters.length > 0) {
throw new errors.BadRequestError(
`Cannot close Marathon Match challenge ${challengeId}: final system scoring is not complete for latest submitter summations. Missing final summations for submitterIds: ${missingSubmitters
.sort()
.join(", ")}`,
);
}
return Array.from(latestBySubmitter.values());
}
const finalBySubmission = new Map();
finalSummations.forEach((summation) => {
const submitterId = normalizeMatchId(summation.submitterId);
const submissionId = normalizeMatchId(summation.submissionId);
if (!submitterId || !submissionId) {
return;
}
const key = `${submitterId}:${submissionId}`;
if (shouldReplaceSelectedReviewSummation(finalBySubmission.get(key), summation)) {
finalBySubmission.set(key, summation);
}
});
const selectedSummations = [];
const missingSubmissions = [];
latestSubmissions.forEach((submission) => {
const memberId = normalizeMatchId(submission.memberId);
const submissionId = normalizeMatchId(submission.id);
if (!memberId || !submissionId) {
return;
}
const summation = finalBySubmission.get(`${memberId}:${submissionId}`);
if (summation) {
selectedSummations.push(summation);
} else {
missingSubmissions.push(submissionId);
}
});
if (missingSubmissions.length > 0) {
throw new errors.BadRequestError(
`Cannot close Marathon Match challenge ${challengeId}: final system scoring is not complete for latest submissions. Missing final summations for submissionIds: ${missingSubmissions.join(
", ",
)}`,
);
}
return selectedSummations;
}
function normalizeStatusSortValue(statusValue) {
if (_.isNil(statusValue)) {
return null;
}
const normalizedStatus = _.toString(statusValue).trim().toUpperCase();
if (!normalizedStatus) {
return null;
}
return normalizedStatus;
}
function normalizeApprovalStatus(value) {
if (_.isNil(value)) {
return null;
}
const normalized = _.toString(value).trim().toUpperCase();
if (!normalized) {
return null;
}
if (!Object.values(CHALLENGE_APPROVAL_STATUS).includes(normalized)) {
return null;
}
return normalized;
}
/**
* Normalizes a configured billing-account list for membership checks.
*
* @param {Array<string|number>|string|number|null|undefined} billingAccountIds Billing-account ids from config.
* @returns {Array<string>} Trimmed billing-account ids, with empty values removed.
*/
function normalizeConfiguredBillingAccountIds(billingAccountIds) {
if (_.isNil(billingAccountIds)) {
return [];
}
return _.flatMap([].concat(billingAccountIds), (billingAccountId) =>
_.toString(billingAccountId).split(","),
)
.map(normalizeOptionalString)
.filter(Boolean);
}
/**
* Resolves the billing account that should drive challenge approval decisions.
*
* @param {Object|null|undefined} challenge Existing or incoming challenge payload.
* @param {Object|null|undefined} data Incoming update payload, when applicable.
* @param {string|number|null|undefined} projectBillingAccountId Billing account returned by the project.
* @returns {string|null} The first available billing-account id, or `null` when none is present.
*/
function getApprovalFlowBillingAccountId(challenge, data?: any, projectBillingAccountId?: any) {
return (
normalizeOptionalString(projectBillingAccountId) ||
normalizeOptionalString(_.get(data, "billing.billingAccountId")) ||
normalizeOptionalString(_.get(challenge, "billing.billingAccountId")) ||
normalizeOptionalString(_.get(challenge, "billingRecord.billingAccountId")) ||
null
);
}
/**
* Determines whether the challenge approval flow should be bypassed.
*
* Fun challenges and challenges billed to configured Topgear billing accounts
* are auto-approved because they should not enter the manual budget approval flow.
*
* @param {string|number|null|undefined} billingAccountId Billing-account identifier.
* @param {boolean} [funChallenge=false] Effective Fun challenge flag from the create or update.
* @returns {boolean} `true` when challenge approval should be skipped.
* @throws This function does not throw.
* @remarks Used by challenge create, update, and launch validation to apply one approval policy.
*/
function shouldSkipChallengeApprovalFlow(billingAccountId, funChallenge = false) {
if (funChallenge === true) {
return true;
}
const normalizedBillingAccountId = normalizeOptionalString(billingAccountId);
if (!normalizedBillingAccountId) {
return false;
}
return _.includes(
normalizeConfiguredBillingAccountIds(config.TOPGEAR_BILLING_ACCOUNTS_ID),
normalizedBillingAccountId,
);
}
/**
* Applies the approval-flow bypass to a challenge payload.
*
* @param {Object} target Challenge create or update payload to mutate.
* @param {string|number|null|undefined} billingAccountId Billing-account identifier.
* @param {boolean} [funChallenge=false] Effective Fun challenge flag from the create or update.
* @returns {boolean} `true` when approval fields were forced to approved.
* @throws This function does not intentionally throw; callers provide a mutable challenge payload.
* @remarks Used before normal approval validation so bypassed challenges persist as approved.
*/
function applyChallengeApprovalFlowBypass(target, billingAccountId, funChallenge = false) {
if (!shouldSkipChallengeApprovalFlow(billingAccountId, funChallenge)) {
return false;
}
target.approvalStatus = CHALLENGE_APPROVAL_STATUS.APPROVED;
target.approvalRejectionReason = null;
target.approvalApprovedBy = null;
return true;
}
/**
* Determines whether challenge activation must wait for budget approval.
*
* @param {string|null|undefined} approvalStatus Effective approval status.
* @param {string|number|null|undefined} billingAccountId Billing-account identifier.
* @param {boolean} [funChallenge=false] Effective Fun challenge flag from the create or update.
* @returns {boolean} `true` when launch should be blocked by approval state.
* @throws This function does not throw.
* @remarks Used when a challenge update transitions its status to Active.
*/
function shouldBlockChallengeLaunchForApproval(
approvalStatus,
billingAccountId,
funChallenge = false,
) {
return (
!shouldSkipChallengeApprovalFlow(billingAccountId, funChallenge) &&
normalizeApprovalStatus(approvalStatus) !== CHALLENGE_APPROVAL_STATUS.APPROVED
);
}
async function userCanApproveChallengeBudget(currentUser, challengeOrProjectId) {
if (!currentUser) {
return false;
}
if (currentUser.isMachine || hasAdminRole(currentUser)) {
return true;
}
const projectId = _.isObject(challengeOrProjectId)
? _.get(challengeOrProjectId, "projectId")
: challengeOrProjectId;
return helper.userHasProjectManagerAccess(projectId, currentUser);
}
function compareStatusSortValues(aStatusValue, bStatusValue) {
const normalizedA = normalizeStatusSortValue(aStatusValue);
const normalizedB = normalizeStatusSortValue(bStatusValue);
if (normalizedA === normalizedB) {
return _.toString(aStatusValue).localeCompare(_.toString(bStatusValue));
}
if (_.isNil(normalizedA)) {
return 1;
}
if (_.isNil(normalizedB)) {
return -1;
}
return normalizedA.localeCompare(normalizedB);
}
/**
* Determines whether the challenge budget should remain locked.
*
* @param {string|undefined|null} status Challenge status from the request or persistence.
* @returns {boolean} True when the challenge should reserve billing-account budget.
*/
function isChallengeBillingLockStatus(status) {
return CHALLENGE_BILLING_LOCK_STATUSES.has(normalizeStatusSortValue(status));
}
/**
* Calculates the billable USD prize-set total for a challenge.
*
* @param {object} challenge Challenge model or response object.
* @returns {number|undefined} USD prize-set member-payment amount before markup,
* or `undefined` when prize sets are not loaded.
*/
function getChallengePrizeSetMemberPaymentAmount(challenge) {
const prizeSets = _.get(challenge, "prizeSets");
if (!Array.isArray(prizeSets)) {
return undefined;
}
return prizeSets.reduce((total, prizeSet) => {
const prizes = Array.isArray(prizeSet && prizeSet.prizes) ? prizeSet.prizes : [];
return (
total +
prizes.reduce((prizeTotal, prize) => {
if (_.toString(_.get(prize, "type")).toUpperCase() !== constants.prizeTypes.USD) {
return prizeTotal;
}
const prizeValue = _.toNumber(_.get(prize, "value"));
return Number.isFinite(prizeValue) ? prizeTotal + prizeValue : prizeTotal;
}, 0)
);
}, 0);
}
/**
* Reads the first-place placement prize used by reviewer cost estimates.
*
* @param {object} challenge Challenge model or response object.
* @returns {number|undefined} First-place USD placement prize amount, or undefined when unavailable.
*/
function getFirstPlacePrizeValue(challenge) {
const prizeSets = _.get(challenge, "prizeSets");
if (!Array.isArray(prizeSets)) {
return undefined;
}
const placementPrizeSet = _.find(
prizeSets,
(prizeSet) => _.toString(_.get(prizeSet, "type")).toUpperCase() === PrizeSetTypeEnum.PLACEMENT,
);
const firstPrize = _.get(placementPrizeSet, "prizes[0]");
if (_.toString(_.get(firstPrize, "type")).toUpperCase() !== constants.prizeTypes.USD) {
return undefined;
}
const prizeValue = _.toNumber(_.get(firstPrize, "value"));
return Number.isFinite(prizeValue) ? prizeValue : undefined;
}
/**
* Calculates the estimated member-review payment amount for billing locks.
*
* The work app shows review cost using a two-submission estimate, so draft
* budget locks need the same fixed and coefficient-based reviewer math.
*
* @param {object} challenge Challenge model or response object.
* @returns {number} Estimated member-review payment amount before markup.
*/
function getEstimatedReviewerPaymentAmount(challenge) {
const reviewers = _.get(challenge, "reviewers");
if (!Array.isArray(reviewers)) {
return 0;
}
const firstPlacePrizeValue = getFirstPlacePrizeValue(challenge);
if (_.isNil(firstPlacePrizeValue)) {
return 0;
}
return reviewers.reduce((total, reviewer) => {
if (_.get(reviewer, "isMemberReview") === false) {
return total;
}
const fixedAmount = _.toNumber(_.get(reviewer, "fixedAmount"));
const baseCoefficient = _.toNumber(_.get(reviewer, "baseCoefficient"));
const incrementalCoefficient = _.toNumber(_.get(reviewer, "incrementalCoefficient"));
const memberReviewerCount = Math.max(
1,
Math.trunc(_.toNumber(_.get(reviewer, "memberReviewerCount")) || 1),
);
const reviewerPayment =
(Number.isFinite(fixedAmount) ? fixedAmount : 0) +
((Number.isFinite(baseCoefficient) ? baseCoefficient : 0) +
(Number.isFinite(incrementalCoefficient) ? incrementalCoefficient : 0) *
DEFAULT_ESTIMATED_SUBMISSIONS_COUNT) *
firstPlacePrizeValue;
return total + reviewerPayment * memberReviewerCount;
}, 0);
}
/**
* Reads the currently persisted challenge member-payment total.
*
* @param {object} challenge Challenge model or response object.
* @returns {number|undefined} Total USD member-payment amount before markup,
* including estimated member-review cost when prize sets are loaded.
*/
function getChallengeMemberPaymentAmount(challenge) {
const prizeSetMemberPaymentAmount = getChallengePrizeSetMemberPaymentAmount(challenge);
if (!_.isNil(prizeSetMemberPaymentAmount)) {
return Number(
(prizeSetMemberPaymentAmount + getEstimatedReviewerPaymentAmount(challenge)).toFixed(2),
);
}
const totalPrizes = _.get(
challenge,
"overview.totalPrizes",
_.get(challenge, "overviewTotalPrizes"),
);
const amount = _.toNumber(totalPrizes);
return Number.isFinite(amount) ? amount : undefined;
}
/**
* Synchronizes the draft/active challenge budget lock to billing accounts.
*
* The challenge service owns the current estimated member-payment amount while
* finance later consumes the finalized payment amount after payment generation.
* This keeps draft challenge rows visible as locked budget in billing-account
* details until finance moves the row to consumed.
* Accounts configured to ignore challenge activation billing validation also
* skip this lock because the Billing Accounts API validates available funds
* when writing the lock.
*
* @param {object} challenge Challenge model or response object after persistence.
* @returns {Promise<void>} Resolves after the billing-account lock is written or skipped.
* @throws {Error} When the Billing Accounts API rejects the lock request.
*/
async function syncChallengeBillingAccountLock(challenge) {
if (!isChallengeBillingLockStatus(challenge && challenge.status)) {
return;
}
const billing = _.get(challenge, "billing", _.get(challenge, "billingRecord"));
const billingAccountId = _.get(billing, "billingAccountId");
const hasBillingAccountId = !_.isNil(billingAccountId) && _.toString(billingAccountId).trim();
const memberPaymentAmount = getChallengeMemberPaymentAmount(challenge);
if (shouldIgnoreChallengeActivationBillingValidation(billingAccountId)) {
logger.info("Skipping challenge billing lock sync for ignored billing account", {
billingAccountId,
challengeId: _.get(challenge, "id"),
});
return;
}
if (!hasBillingAccountId || _.isNil(memberPaymentAmount)) {
logger.warn("Skipping challenge billing lock sync due to missing billing context", {
challengeId: _.get(challenge, "id"),
hasBillingAccountId: Boolean(hasBillingAccountId),
hasMemberPaymentAmount: !_.isNil(memberPaymentAmount),
});
return;
}
await projectHelper.lockChallengeBillingAccountAmount({
billingAccountId,
challengeId: challenge.id,
markup: _.get(billing, "clientBillingRate", _.get(billing, "markup")),
memberPaymentAmount,
});
}
/**
* Returns normalized role names from the authenticated user payload.
* @param {Object} currentUser the authenticated user
* @returns {Set<String>} lower-cased role names
*/
function getNormalizedUserRoles(currentUser) {
const roles = _.get(currentUser, "roles", []);
const roleValues = Array.isArray(roles)
? roles
: _.toString(roles)
.split(",")
.map((role) => role.trim());
return new Set(
_.map(roleValues, (role) => _.toString(role).trim().toLowerCase()).filter(Boolean),
);
}
/**
* Determines whether challenge billing markup should be hidden from the caller.
* @param {Object} currentUser the authenticated user
* @returns {Boolean} true when the caller is copilot-only and should not see markup
*/
function shouldHideBillingMarkupForCopilot(currentUser) {
if (!currentUser || _.get(currentUser, "isMachine", false)) {
return false;
}
const roles = getNormalizedUserRoles(currentUser);
const hasCopilotRole = [...BILLING_MARKUP_COPILOT_ROLES].some((role) => roles.has(role));
if (!hasCopilotRole) {
return false;
}
return ![...BILLING_MARKUP_VISIBLE_ROLES].some((role) => roles.has(role));
}
/**
* Removes raw billing markup from challenge response data for copilot-only callers.
* @param {Object} currentUser the authenticated user
* @param {Object} challenge the challenge response object to sanitize
* @returns {Object} the same challenge object after response sanitization
*/
function sanitizeBillingMarkupForCaller(currentUser, challenge) {
if (shouldHideBillingMarkupForCopilot(currentUser)) {
_.unset(challenge, "billing.markup");
}
return challenge;
}
/**
* Keeps persisted billing markup intact when copilot-only callers submit billing data.
* @param {Object} currentUser the authenticated user
* @param {Object} data incoming update payload
* @param {Object} challenge persisted challenge response shape
* @returns {Object} the update payload with protected billing markup restored
*/
function preserveBillingMarkupForCopilotUpdate(currentUser, data, challenge) {
if (
shouldHideBillingMarkupForCopilot(currentUser) &&
_.has(data, "billing") &&
_.has(challenge, "billing.markup")
) {
_.set(data, "billing.markup", _.get(challenge, "billing.markup"));
}
return data;
}
// Minimal domain adapter for PhaseAdvancer to fetch phase-specific facts.
// For now this returns an empty factResponses array which makes the
// PhaseAdvancer default to conservative behavior when such facts are needed.
// This avoids runtime errors until a richer domain is implemented.
const challengeDomain = {
/**
* Retrieve phase-specific facts from downstream services (stubbed).
* @param {{ legacyId: number | null, facts: Array<number> }} _request
* @returns {Promise<{ factResponses: Array<{ response: object }> }>}
*/
async getPhaseFacts(_request) {
return { factResponses: [] };
},
};
const phaseAdvancer = new PhaseAdvancer(challengeDomain);
const REVIEW_STATUS_BLOCKING = Object.freeze(["IN_PROGRESS", "COMPLETED"]);
const CHECKPOINT_REVIEW_PHASE_NAME = "checkpoint review";
const REVIEW_PHASE_NAMES = Object.freeze([
CHECKPOINT_REVIEW_PHASE_NAME,
"checkpoint screening",
"screening",
"review",
"approval",
]);
const REVIEW_PHASE_NAME_SET = new Set(REVIEW_PHASE_NAMES);
const REQUIRED_REVIEW_PHASE_NAME_SET = new Set([...REVIEW_PHASE_NAMES, "iterative review"]);
const AI_SCREENING_PHASE_NAME = "ai screening";
const AI_REVIEW_PHASE_NAME = "ai review";
function normalizePhaseNameForComparison(phaseName) {
return _.toString(phaseName).replace(/-/g, " ").trim().toLowerCase();
}
/**
* Determines whether checkpoint winners are ready to be included in challenge responses.
* Detail and search response sanitization use this after Checkpoint Review has closed,
* while completed challenges preserve their existing winner visibility.
*
* @param {Object} challenge challenge data containing status and phase state
* @returns {Boolean} true when assigned checkpoint winners may be returned
* @throws {Error} this function does not throw
*/
function shouldExposeCheckpointWinners(challenge) {
if (challenge.status === ChallengeStatusEnum.COMPLETED) {
return true;
}
if (challenge.status !== ChallengeStatusEnum.ACTIVE) {
return false;
}
return _.some(
challenge.phases,
(phase) =>
normalizePhaseNameForComparison(phase.name) === CHECKPOINT_REVIEW_PHASE_NAME &&
phase.isOpen !== true &&
!_.isNil(phase.actualStartDate) &&
!_.isNil(phase.actualEndDate),
);
}
function extractSubmissionId(submission) {
const candidate =
_.get(submission, "id") ||
_.get(submission, "submissionId") ||
_.get(submission, "legacySubmissionId");
if (_.isNil(candidate)) {
return null;
}