tods-competition-factory 2.0.0-alpha.1 → 2.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  function factoryVersion() {
6
- return '2.0.0-alpha.1';
6
+ return '2.0.0-beta.0';
7
7
  }
8
8
 
9
9
  /******************************************************************************
@@ -26950,7 +26950,7 @@ function tallyParticipantResults(_a) {
26950
26950
  var completedTieMatchUps = matchUps.every(function (_a) {
26951
26951
  var matchUpType = _a.matchUpType, tieMatchUps = _a.tieMatchUps;
26952
26952
  return matchUpType === TEAM$1 &&
26953
- tieMatchUps.every(function (matchUp) { return checkMatchUpIsComplete({ matchUp: matchUp }); });
26953
+ (tieMatchUps === null || tieMatchUps === void 0 ? void 0 : tieMatchUps.every(function (matchUp) { return checkMatchUpIsComplete({ matchUp: matchUp }); }));
26954
26954
  });
26955
26955
  var tallyPolicy = policyDefinitions === null || policyDefinitions === void 0 ? void 0 : policyDefinitions[POLICY_TYPE_ROUND_ROBIN_TALLY];
26956
26956
  var consideredMatchUps = matchUps.filter(function (matchUp) {
@@ -36328,49 +36328,6 @@ function removeAdHocRound(_a) {
36328
36328
  return __assign({ deletedMatchUpsCount: deletedMatchUpIds.length, roundRemoved: roundRemoved }, SUCCESS);
36329
36329
  }
36330
36330
 
36331
- function addAdHocMatchUps(_a) {
36332
- var _b;
36333
- var _c, _d, _e, _f, _g, _h, _j;
36334
- var tournamentRecord = _a.tournamentRecord, drawDefinition = _a.drawDefinition, structureId = _a.structureId, matchUps = _a.matchUps;
36335
- if (typeof drawDefinition !== 'object')
36336
- return { error: MISSING_DRAW_DEFINITION };
36337
- if (!structureId && ((_c = drawDefinition.structures) === null || _c === void 0 ? void 0 : _c.length) === 1)
36338
- structureId = (_e = (_d = drawDefinition.structures) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.structureId;
36339
- if (typeof structureId !== 'string')
36340
- return { error: MISSING_STRUCTURE_ID };
36341
- if (!validMatchUps(matchUps))
36342
- return { error: INVALID_VALUES, info: mustBeAnArray('matchUps') };
36343
- var structure = (_f = drawDefinition.structures) === null || _f === void 0 ? void 0 : _f.find(function (structure) { return structure.structureId === structureId; });
36344
- if (!structure)
36345
- return { error: STRUCTURE_NOT_FOUND };
36346
- var existingMatchUps = structure === null || structure === void 0 ? void 0 : structure.matchUps;
36347
- var structureHasRoundPositions = existingMatchUps.find(function (matchUp) { return !!matchUp.roundPosition; });
36348
- if (structure.structures ||
36349
- structureHasRoundPositions ||
36350
- structure.finishingPosition === ROUND_OUTCOME) {
36351
- return { error: INVALID_STRUCTURE };
36352
- }
36353
- var existingMatchUpIds = (_j = (_h = (_g = allTournamentMatchUps({
36354
- tournamentRecord: tournamentRecord,
36355
- inContext: false,
36356
- })) === null || _g === void 0 ? void 0 : _g.matchUps) === null || _h === void 0 ? void 0 : _h.map(getMatchUpId)) !== null && _j !== void 0 ? _j : [];
36357
- var newMatchUpIds = matchUps.map(getMatchUpId);
36358
- if (overlap(existingMatchUpIds, newMatchUpIds)) {
36359
- return {
36360
- error: EXISTING_MATCHUP_ID,
36361
- info: 'One or more matchUpIds already present in tournamentRecord',
36362
- };
36363
- }
36364
- (_b = structure.matchUps).push.apply(_b, __spreadArray([], __read(matchUps), false));
36365
- addMatchUpsNotice({
36366
- tournamentId: tournamentRecord === null || tournamentRecord === void 0 ? void 0 : tournamentRecord.tournamentId,
36367
- drawDefinition: drawDefinition,
36368
- matchUps: matchUps,
36369
- });
36370
- modifyDrawNotice({ drawDefinition: drawDefinition, structureIds: [structureId] });
36371
- return __assign({}, SUCCESS);
36372
- }
36373
-
36374
36331
  function aggregateTieFormats(_a) {
36375
36332
  var e_1, _b;
36376
36333
  var _c, _d, _e, _f, _g;
@@ -37264,1279 +37221,1327 @@ function modifyEventEntries(_a) {
37264
37221
  return __assign({}, SUCCESS);
37265
37222
  }
37266
37223
 
37267
- function attachFlightProfile(_a) {
37268
- var _b;
37269
- var deleteExisting = _a.deleteExisting, event = _a.event, flightProfile = _a.flightProfile;
37270
- var stack = 'attachFlightProfile';
37271
- if (!flightProfile)
37272
- return decorateResult({ result: { error: MISSING_VALUE }, stack: stack });
37273
- if (!event)
37274
- return decorateResult({ result: { error: MISSING_EVENT }, stack: stack });
37275
- var existingFlightProfile = getFlightProfile({ event: event }).flightProfile;
37276
- if (existingFlightProfile && !deleteExisting)
37277
- return decorateResult({ result: { error: EXISTING_PROFILE }, stack: stack });
37278
- if ((_b = event.drawDefinitions) === null || _b === void 0 ? void 0 : _b.length)
37279
- return decorateResult({
37280
- result: { error: EXISTING_DRAW_DEFINITIONS },
37281
- stack: stack,
37224
+ function generateAdHocMatchUps(_a) {
37225
+ var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
37226
+ var participantIdPairings = _a.participantIdPairings, _q = _a.matchUpIds, matchUpIds = _q === void 0 ? [] : _q, drawDefinition = _a.drawDefinition, matchUpsCount = _a.matchUpsCount, roundNumber = _a.roundNumber, structureId = _a.structureId, newRound = _a.newRound, isMock = _a.isMock, event = _a.event;
37227
+ if (typeof drawDefinition !== 'object')
37228
+ return { error: MISSING_DRAW_DEFINITION };
37229
+ if (!structureId && ((_b = drawDefinition.structures) === null || _b === void 0 ? void 0 : _b.length) === 1)
37230
+ structureId = (_d = (_c = drawDefinition.structures) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.structureId;
37231
+ if (typeof structureId !== 'string')
37232
+ return { error: MISSING_STRUCTURE_ID };
37233
+ // if drawDefinition and structureId are provided it is possible to infer roundNumber
37234
+ var structure = (_e = drawDefinition.structures) === null || _e === void 0 ? void 0 : _e.find(function (structure) { return structure.structureId === structureId; });
37235
+ if (!structure)
37236
+ return { error: STRUCTURE_NOT_FOUND };
37237
+ var structureHasRoundPositions;
37238
+ var existingMatchUps = (_f = structure.matchUps) !== null && _f !== void 0 ? _f : [];
37239
+ var lastRoundNumber = existingMatchUps === null || existingMatchUps === void 0 ? void 0 : existingMatchUps.reduce(function (roundNumber, matchUp) {
37240
+ if (matchUp.roundPosition)
37241
+ structureHasRoundPositions = true;
37242
+ return ((matchUp === null || matchUp === void 0 ? void 0 : matchUp.roundNumber) || 0) > roundNumber
37243
+ ? matchUp.roundNumber
37244
+ : roundNumber;
37245
+ }, 0);
37246
+ if (!matchUpsCount) {
37247
+ var selectedEntries = (_h = (_g = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.entries) === null || _g === void 0 ? void 0 : _g.filter(function (entry) {
37248
+ var entryStatus = entry.entryStatus;
37249
+ return STRUCTURE_SELECTED_STATUSES.includes(entryStatus);
37250
+ })) !== null && _h !== void 0 ? _h : [];
37251
+ var roundMatchUpsCount = Math.floor((selectedEntries === null || selectedEntries === void 0 ? void 0 : selectedEntries.length) / 2) || 1;
37252
+ if (newRound) {
37253
+ matchUpsCount = roundMatchUpsCount;
37254
+ }
37255
+ else {
37256
+ var targetRoundNumber_1 = (_j = roundNumber !== null && roundNumber !== void 0 ? roundNumber : lastRoundNumber) !== null && _j !== void 0 ? _j : 1;
37257
+ var existingRoundMatchUps = (_m = (_l = (_k = structure.matchUps) === null || _k === void 0 ? void 0 : _k.filter(function (matchUp) { return matchUp.roundNumber === targetRoundNumber_1; })) === null || _l === void 0 ? void 0 : _l.length) !== null && _m !== void 0 ? _m : 0;
37258
+ var maxRemaining = roundMatchUpsCount - existingRoundMatchUps;
37259
+ if (maxRemaining > 0)
37260
+ matchUpsCount = maxRemaining;
37261
+ }
37262
+ }
37263
+ if ((participantIdPairings && !Array.isArray(participantIdPairings)) ||
37264
+ (matchUpsCount && !isConvertableInteger(matchUpsCount)) ||
37265
+ (matchUpIds && !Array.isArray(matchUpIds)) ||
37266
+ (!participantIdPairings && !matchUpsCount)) {
37267
+ return { error: INVALID_VALUES, info: 'matchUpsCount or pairings error' };
37268
+ }
37269
+ // structure must not be a container of other structures
37270
+ // structure must not contain matchUps with roundPosition
37271
+ // structure must not determine finishingPosition by ROUND_OUTCOME
37272
+ if (structure.structures ||
37273
+ structureHasRoundPositions ||
37274
+ structure.finishingPosition === ROUND_OUTCOME) {
37275
+ return { error: INVALID_STRUCTURE };
37276
+ }
37277
+ if (roundNumber && roundNumber - 1 > (lastRoundNumber || 0))
37278
+ return { error: INVALID_VALUES, info: 'roundNumber error' };
37279
+ var nextRoundNumber = roundNumber !== null && roundNumber !== void 0 ? roundNumber : ((newRound && (lastRoundNumber !== null && lastRoundNumber !== void 0 ? lastRoundNumber : 0) + 1) || lastRoundNumber || 1);
37280
+ participantIdPairings =
37281
+ participantIdPairings !== null && participantIdPairings !== void 0 ? participantIdPairings : generateRange(0, matchUpsCount).map(function () { return ({
37282
+ participantIds: [undefined, undefined],
37283
+ }); });
37284
+ var matchUps = participantIdPairings === null || participantIdPairings === void 0 ? void 0 : participantIdPairings.map(function (pairing) {
37285
+ var _a, _b;
37286
+ var idStack = (_a = pairing === null || pairing === void 0 ? void 0 : pairing.participantIds) !== null && _a !== void 0 ? _a : [undefined, undefined];
37287
+ // ensure there are always 2 sides in generated matchUps
37288
+ idStack.push.apply(idStack, [undefined, undefined]);
37289
+ var participantIds = idStack.slice(0, 2);
37290
+ var sides = participantIds.map(function (participantId, i) {
37291
+ return definedAttributes({
37292
+ sideNumber: i + 1,
37293
+ participantId: participantId,
37294
+ });
37282
37295
  });
37283
- var extension = {
37284
- name: FLIGHT_PROFILE,
37285
- value: flightProfile,
37286
- };
37287
- addEventExtension({ event: event, extension: extension });
37288
- return __assign({ flightProfile: makeDeepCopy(flightProfile, false, true) }, SUCCESS);
37296
+ return {
37297
+ matchUpId: (_b = matchUpIds.pop()) !== null && _b !== void 0 ? _b : UUID(),
37298
+ roundNumber: nextRoundNumber,
37299
+ matchUpStatus: TO_BE_PLAYED,
37300
+ sides: sides,
37301
+ };
37302
+ });
37303
+ if (matchUps === null || matchUps === void 0 ? void 0 : matchUps.length) {
37304
+ var tieFormat_1 = (_o = resolveTieFormat({ drawDefinition: drawDefinition, event: event })) === null || _o === void 0 ? void 0 : _o.tieFormat;
37305
+ if (tieFormat_1) {
37306
+ matchUps.forEach(function (matchUp) {
37307
+ var tieMatchUps = generateTieMatchUps({ tieFormat: tieFormat_1, isMock: isMock }).tieMatchUps;
37308
+ Object.assign(matchUp, { tieMatchUps: tieMatchUps, matchUpType: TEAM$1 });
37309
+ });
37310
+ }
37311
+ }
37312
+ return __assign({ matchUpsCount: (_p = matchUps === null || matchUps === void 0 ? void 0 : matchUps.length) !== null && _p !== void 0 ? _p : 0, matchUps: matchUps }, SUCCESS);
37289
37313
  }
37290
37314
 
37291
- /**
37292
- *
37293
- * @param {object} tournamentRecord - passed automatically if tournamentEngine.setState()
37294
- * @param {string[]} participantIds
37295
- * @param {string} scaleAttributes - { scaleType, scaleName, eventType }
37296
- * @returns {boolean} { success: true } or { error }
37297
- */
37298
- function removeParticipantsScaleItems(_a) {
37299
- var _b;
37300
- var tournamentRecord = _a.tournamentRecord, scaleAttributes = _a.scaleAttributes, participantIds = _a.participantIds;
37301
- if (!tournamentRecord)
37302
- return { error: MISSING_TOURNAMENT_RECORD };
37303
- if (!participantIds)
37304
- return { error: MISSING_PARTICIPANT_IDS };
37305
- if (!scaleAttributes)
37306
- return { error: MISSING_VALUE, info: 'scaleAttributes required' };
37307
- var scaleType = scaleAttributes.scaleType, eventType = scaleAttributes.eventType, scaleName = scaleAttributes.scaleName;
37308
- var itemType = [SCALE, scaleType, eventType, scaleName].join('.');
37309
- (_b = tournamentRecord.participants) === null || _b === void 0 ? void 0 : _b.forEach(function (participant) {
37310
- if (participantIds.includes(participant.participantId) &&
37311
- participant.timeItems) {
37312
- participant.timeItems = participant.timeItems.filter(function (timeItem) {
37313
- return timeItem && (timeItem === null || timeItem === void 0 ? void 0 : timeItem.itemType) !== itemType;
37314
- });
37315
+ function generateCandidate(_a) {
37316
+ var _b = _a.maxIterations, maxIterations = _b === void 0 ? 4000 : _b, // cap the processing intensity of the candidate generator
37317
+ valueSortedPairings = _a.valueSortedPairings, // pairings sorted by value from low to high
37318
+ pairingValues = _a.pairingValues, valueObjects = _a.valueObjects, deltaObjects = _a.deltaObjects;
37319
+ var pairingValueMap = Object.assign.apply(Object, __spreadArray([{}], __read(valueSortedPairings.map(function (rm) {
37320
+ var _a;
37321
+ return (_a = {}, _a[rm.pairing] = rm.value, _a);
37322
+ })), false));
37323
+ var actors = Object.keys(pairingValues);
37324
+ var proposedCandidates = [];
37325
+ // generate an initial candidate value with no stipulated pairings
37326
+ var initialProposal = roundCandidate({
37327
+ actorsCount: actors.length,
37328
+ valueSortedPairings: valueSortedPairings,
37329
+ pairingValueMap: pairingValueMap,
37330
+ deltaObjects: deltaObjects,
37331
+ valueObjects: valueObjects,
37332
+ });
37333
+ var candidateHashes = [candidateHash(initialProposal)];
37334
+ proposedCandidates.push(initialProposal);
37335
+ var lowCandidateValue = initialProposal.value;
37336
+ var deltaCandidate = initialProposal;
37337
+ // iterations is the number of loops over valueSortedPairings
37338
+ var candidatesCount = 0;
37339
+ var iterations = 0;
37340
+ var opponentCount = actors.length;
37341
+ var calculatedIterations;
37342
+ // calculate the number of opponents to consider for each participantId
37343
+ do {
37344
+ opponentCount -= 1;
37345
+ calculatedIterations = actors.length * pairingValues[actors[0]].length;
37346
+ } while (calculatedIterations > maxIterations && opponentCount > 5);
37347
+ // keep track of proposed pairings
37348
+ var stipulatedPairs = [];
37349
+ // for each actor generate a roundCandidate using opponentCount of pairing values
37350
+ actors.forEach(function (actor) {
37351
+ var participantIdPairings = pairingValues[actor];
37352
+ // opponentCount limits the number of opponents to consider
37353
+ participantIdPairings.slice(0, opponentCount).forEach(function (pairing) {
37354
+ iterations += 1;
37355
+ var stipulatedPair = pairingHash(actor, pairing.opponent);
37356
+ if (!stipulatedPairs.includes(stipulatedPair)) {
37357
+ var proposed = roundCandidate({
37358
+ // each roundCandidate starts with stipulated pairings
37359
+ stipulated: [[actor, pairing.opponent]],
37360
+ actorsCount: actors.length,
37361
+ valueSortedPairings: valueSortedPairings,
37362
+ pairingValueMap: pairingValueMap,
37363
+ deltaObjects: deltaObjects,
37364
+ valueObjects: valueObjects,
37365
+ });
37366
+ // ensure no duplicate candidates are considered
37367
+ if (!candidateHashes.includes(candidateHash(proposed))) {
37368
+ candidateHashes.push(candidateHash(proposed));
37369
+ proposedCandidates.push(proposed);
37370
+ var maxDelta = proposed.maxDelta, value = proposed.value;
37371
+ if (maxDelta < deltaCandidate.maxDelta)
37372
+ deltaCandidate = proposed;
37373
+ if (value < lowCandidateValue ||
37374
+ (value === lowCandidateValue && Math.round(Math.random())) // randomize if equivalent values
37375
+ ) {
37376
+ lowCandidateValue = value;
37377
+ }
37378
+ stipulatedPairs.push(stipulatedPair);
37379
+ candidatesCount += 1;
37380
+ }
37381
+ }
37382
+ });
37383
+ proposedCandidates = proposedCandidates.filter(function (proposed) { return Math.abs(proposed.value - lowCandidateValue) < 5; });
37384
+ });
37385
+ proposedCandidates.sort(function (a, b) { return a.maxDiff - b.maxDiff; });
37386
+ var candidate = randomPop(proposedCandidates);
37387
+ return {
37388
+ candidatesCount: candidatesCount,
37389
+ deltaCandidate: deltaCandidate,
37390
+ maxIterations: maxIterations,
37391
+ iterations: iterations,
37392
+ candidate: candidate,
37393
+ };
37394
+ }
37395
+ function candidateHash(candidate) {
37396
+ return candidate.participantIdPairings
37397
+ .map(function (_a) {
37398
+ var participantIds = _a.participantIds;
37399
+ return participantIds.sort().join('|');
37400
+ })
37401
+ .sort()
37402
+ .join('/');
37403
+ }
37404
+ function roundCandidate(_a) {
37405
+ var valueSortedPairings = _a.valueSortedPairings, _b = _a.stipulated, stipulated = _b === void 0 ? [] : _b, pairingValueMap = _a.pairingValueMap, deltaObjects = _a.deltaObjects, valueObjects = _a.valueObjects, actorsCount = _a.actorsCount;
37406
+ // roundPlayers starts with the stipulated pairing
37407
+ var roundPlayers = [].concat.apply([], __spreadArray([], __read(stipulated), false));
37408
+ // aggregates the pairings generated for a roundCandidate
37409
+ var participantIdPairings = [];
37410
+ // candidateValue is the sum of all participantIdPairings in a roundCandidate
37411
+ // the winning candidate has the LOWEST total value
37412
+ var candidateValue = 0;
37413
+ // candidateValue is initialized with any stipulated pairings
37414
+ stipulated.filter(Boolean).forEach(function (participantIds) {
37415
+ var _a = __read(participantIds, 2), p1 = _a[0], p2 = _a[1];
37416
+ var pairing = pairingHash(p1, p2);
37417
+ var value = pairingValueMap[pairing];
37418
+ participantIdPairings.push({ participantIds: participantIds, value: value });
37419
+ candidateValue += pairingValueMap[pairing];
37420
+ });
37421
+ // valueSortedPairings is an array sorted from lowest value to highest value
37422
+ // introduce random shuffling of chunks of valueSortedPairings
37423
+ var consideredPairings = chunkArray(valueSortedPairings, actorsCount)
37424
+ .map(function (pairings) {
37425
+ return shuffleArray(pairings).map(function (pairing) { return (__assign(__assign({}, pairing), { value: pairing.value + Math.random() * Math.round(Math.random()) })); });
37426
+ })
37427
+ .flat();
37428
+ // go through the valueSortedPairings (of all possible unique pairings)
37429
+ consideredPairings.forEach(function (rankedPairing) {
37430
+ var participantIds = rankedPairing.pairing.split('|');
37431
+ var opponentExists = participantIds.reduce(function (p, c) { return roundPlayers.includes(c) || p; }, false);
37432
+ if (!opponentExists) {
37433
+ roundPlayers.push.apply(roundPlayers, __spreadArray([], __read(participantIds), false));
37434
+ var value = rankedPairing.value;
37435
+ candidateValue += value;
37436
+ participantIdPairings.push({ participantIds: participantIds, value: value });
37315
37437
  }
37316
37438
  });
37317
- return __assign({}, SUCCESS);
37439
+ // sort the candidate's proposed pairings by value
37440
+ participantIdPairings.sort(function (a, b) { return a.value - b.value; });
37441
+ // determine the greatest delta in the candidate's pairings
37442
+ var maxDelta = participantIdPairings.reduce(function (p, c) {
37443
+ var _a = __read(c.participantIds, 2), p1 = _a[0], p2 = _a[1];
37444
+ var hash = pairingHash(p1, p2);
37445
+ var delta = deltaObjects[hash];
37446
+ return delta > p ? delta : p;
37447
+ }, 0);
37448
+ // determine the greatest delta in the candidate's pairings
37449
+ var maxDiff = participantIdPairings.reduce(function (p, c) {
37450
+ var _a = __read(c.participantIds, 2), p1 = _a[0], p2 = _a[1];
37451
+ var hash = pairingHash(p1, p2);
37452
+ var diff = valueObjects[hash];
37453
+ return diff > p ? diff : p;
37454
+ }, 0);
37455
+ return { value: candidateValue, participantIdPairings: participantIdPairings, maxDelta: maxDelta, maxDiff: maxDiff };
37456
+ }
37457
+ function pairingHash(id1, id2) {
37458
+ return [id1, id2].sort(stringSort).join('|');
37318
37459
  }
37319
37460
 
37320
- /**
37321
- *
37322
- * @param {object} tournamentRecord - passed automatically if tournamentEngine.setState()
37323
- * @param {string} eventId - resolves to event
37324
- * @param {string} drawId - OPTIONAL - resolves drawDefinition - scopes participants to clear to drawDefinition.entries or flightProfile.flight.drawEntries
37325
- * @param {string} scaleAttributes - { scaleType, scaleName, eventType }
37326
- * @param {string} stage - OPTIONAL - filter event or draw entries by stage
37327
- * @returns {boolean} { success: true } or { error }
37328
- */
37329
- function removeScaleValues(_a) {
37330
- var _b;
37331
- var tournamentRecord = _a.tournamentRecord, scaleAttributes = _a.scaleAttributes, drawDefinition = _a.drawDefinition, entryStatuses = _a.entryStatuses, drawId = _a.drawId, event = _a.event, stage = _a.stage;
37332
- if (!event)
37333
- return { error: MISSING_EVENT };
37334
- if (entryStatuses && !Array.isArray(entryStatuses))
37335
- return decorateResult({
37336
- result: { error: INVALID_VALUES },
37337
- info: mustBeAnArray('entryStatus'),
37338
- stack: 'removeScaleValues',
37461
+ function getPairingsData(_a) {
37462
+ var participantIds = _a.participantIds;
37463
+ var possiblePairings = {};
37464
+ var uniquePairings = [];
37465
+ participantIds.forEach(function (participantId) {
37466
+ possiblePairings[participantId] = participantIds.filter(function (id) { return id !== participantId; });
37467
+ possiblePairings[participantId].forEach(function (id) {
37468
+ var pairing = pairingHash(id, participantId);
37469
+ if (!uniquePairings.includes(pairing))
37470
+ uniquePairings.push(pairing);
37339
37471
  });
37340
- var entries = event.entries;
37341
- if (drawId) {
37342
- var flightProfile = getFlightProfile({ event: event }).flightProfile;
37343
- var flight = (_b = flightProfile === null || flightProfile === void 0 ? void 0 : flightProfile.flights) === null || _b === void 0 ? void 0 : _b.find(function (flight) { return flight.drawId === drawId; });
37344
- if (flight) {
37345
- entries = flight.drawEntries;
37472
+ });
37473
+ var deltaObjects = Object.assign.apply(Object, __spreadArray([{}], __read(uniquePairings.map(function (pairing) {
37474
+ var _a;
37475
+ return (_a = {}, _a[pairing] = 0, _a);
37476
+ })), false));
37477
+ return { uniquePairings: uniquePairings, possiblePairings: possiblePairings, deltaObjects: deltaObjects };
37478
+ }
37479
+
37480
+ function getEncounters(_a) {
37481
+ var e_1, _b;
37482
+ var matchUps = _a.matchUps;
37483
+ var encounters = [];
37484
+ try {
37485
+ for (var matchUps_1 = __values(matchUps), matchUps_1_1 = matchUps_1.next(); !matchUps_1_1.done; matchUps_1_1 = matchUps_1.next()) {
37486
+ var matchUp = matchUps_1_1.value;
37487
+ var participantIds = matchUp.sides.map(extractAttributes('participantId'));
37488
+ if (participantIds.length === 2) {
37489
+ var _c = __read(participantIds, 2), p1 = _c[0], p2 = _c[1];
37490
+ var pairing = pairingHash(p1, p2);
37491
+ if (!encounters.includes(pairing))
37492
+ encounters.push(pairing);
37493
+ }
37346
37494
  }
37347
- else {
37348
- entries = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.entries;
37495
+ }
37496
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
37497
+ finally {
37498
+ try {
37499
+ if (matchUps_1_1 && !matchUps_1_1.done && (_b = matchUps_1.return)) _b.call(matchUps_1);
37349
37500
  }
37501
+ finally { if (e_1) throw e_1.error; }
37350
37502
  }
37351
- var stageEntries = (entries || []).filter(function (entry) {
37352
- return (!stage || !entry.entryStage || entry.entryStage === stage) &&
37353
- (!entryStatuses || entryStatuses.includes(entry.entryStatus));
37354
- });
37355
- var participantIds = stageEntries.map(getParticipantId);
37356
- return removeParticipantsScaleItems({
37357
- tournamentRecord: tournamentRecord,
37358
- scaleAttributes: scaleAttributes,
37359
- participantIds: participantIds,
37360
- });
37503
+ return { encounters: encounters };
37361
37504
  }
37362
37505
 
37363
- function applyLineUps(_a) {
37364
- var e_1, _b, e_2, _c, e_3, _d, e_4, _e;
37365
- var _f, _g, _h, _j;
37366
- var tournamentRecord = _a.tournamentRecord, drawDefinition = _a.drawDefinition, matchUpId = _a.matchUpId, lineUps = _a.lineUps, event = _a.event;
37367
- if (!tournamentRecord)
37368
- return { error: MISSING_TOURNAMENT_RECORD };
37369
- if (!drawDefinition)
37370
- return { error: DRAW_DEFINITION_NOT_FOUND };
37371
- if (typeof matchUpId !== 'string')
37372
- return { error: INVALID_MATCHUP };
37373
- if (!Array.isArray(lineUps))
37374
- return { error: INVALID_VALUES, lineUps: lineUps };
37375
- var stack = 'applyLineUps';
37376
- var tournamentParticipants = tournamentRecord.participants || [];
37377
- var result = findDrawMatchUp({
37378
- tournamentParticipants: tournamentParticipants,
37379
- inContext: true,
37380
- drawDefinition: drawDefinition,
37381
- matchUpId: matchUpId,
37382
- });
37383
- if (result.error)
37384
- return result;
37385
- if (!result.matchUp)
37386
- return { error: MATCHUP_NOT_FOUND };
37387
- var inContextMatchUp = result.matchUp, structure = result.structure;
37388
- var drawPositions = inContextMatchUp.drawPositions, matchUpType = inContextMatchUp.matchUpType;
37389
- if (matchUpType !== TEAM$1)
37390
- return { error: INVALID_MATCHUP };
37391
- if (!(drawPositions === null || drawPositions === void 0 ? void 0 : drawPositions.length))
37392
- return { error: MISSING_DRAW_POSITIONS };
37393
- var tieFormat = (_f = resolveTieFormat({
37394
- matchUp: inContextMatchUp,
37395
- drawDefinition: drawDefinition,
37396
- structure: structure,
37397
- event: event,
37398
- })) === null || _f === void 0 ? void 0 : _f.tieFormat;
37399
- // verify integrity of lineUps...
37400
- // 1. all participantIds must be valid individualParticipantIds
37401
- // 2. there should be at most one participantId for a given collectionPosition in singles
37402
- // 3. there should be at most two participantIds for a given collectionPosition in doubles
37403
- var sideAssignments = {};
37506
+ function getParticipantPairingValues(_a) {
37507
+ var e_1, _b;
37508
+ var possiblePairings = _a.possiblePairings, valueObjects = _a.valueObjects;
37509
+ var pairingValues = {};
37510
+ var _loop_1 = function (participantId) {
37511
+ var participantValues = possiblePairings[participantId].map(function (opponent) {
37512
+ return pairingValue(participantId, opponent);
37513
+ });
37514
+ pairingValues[participantId] = participantValues.sort(function (a, b) { return a.value - b.value; });
37515
+ };
37404
37516
  try {
37405
- for (var lineUps_1 = __values(lineUps), lineUps_1_1 = lineUps_1.next(); !lineUps_1_1.done; lineUps_1_1 = lineUps_1.next()) {
37406
- var lineUp = lineUps_1_1.value;
37407
- if (!Array.isArray(lineUp))
37408
- return { error: INVALID_VALUES, lineUp: lineUp };
37409
- // maintain mapping of collectionId|collectionPosition to the participantIds assigned
37410
- var collectionParticipantIds = {};
37411
- var sideNumbers = [];
37412
- var _loop_1 = function (lineUpAssignment) {
37413
- var e_5, _m;
37414
- if (typeof lineUpAssignment !== 'object')
37415
- return { value: { error: INVALID_VALUES, lineUpAssignment: lineUpAssignment } };
37416
- var participantId = lineUpAssignment.participantId, _o = lineUpAssignment.collectionAssignments, collectionAssignments = _o === void 0 ? [] : _o;
37417
- if (!Array.isArray(collectionAssignments))
37418
- return { value: { error: INVALID_VALUES, collectionAssignments: collectionAssignments } };
37419
- var participant = tournamentParticipants.find(function (participant) { return participant.participantId === participantId; });
37420
- if (!participant)
37421
- return { value: { error: PARTICIPANT_NOT_FOUND } };
37422
- if (participant.participantType !== INDIVIDUAL)
37423
- return { value: { error: INVALID_PARTICIPANT_TYPE } };
37424
- var sideNumber_1 = (_h = (_g = inContextMatchUp.sides) === null || _g === void 0 ? void 0 : _g.find(function (side) { var _a, _b; return (_b = (_a = side.participant) === null || _a === void 0 ? void 0 : _a.individualParticipantIds) === null || _b === void 0 ? void 0 : _b.includes(participantId); })) === null || _h === void 0 ? void 0 : _h.sideNumber;
37425
- if (sideNumber_1)
37426
- sideNumbers.push(sideNumber_1);
37427
- var _loop_3 = function (collectionAssignment) {
37428
- if (typeof collectionAssignment !== 'object')
37429
- return { value: { error: INVALID_VALUES, collectionAssignment: collectionAssignment } };
37430
- var collectionId = collectionAssignment.collectionId, collectionPosition = collectionAssignment.collectionPosition;
37431
- var collectionDefinition = (_j = tieFormat === null || tieFormat === void 0 ? void 0 : tieFormat.collectionDefinitions) === null || _j === void 0 ? void 0 : _j.find(function (collectionDefinition) {
37432
- return collectionDefinition.collectionId === collectionId;
37433
- });
37434
- // all collectionIds in the lineUp must be present in the tieFormat collectionDefinitions
37435
- if (!collectionDefinition)
37436
- return { value: { error: INVALID_VALUES, collectionId: collectionId } };
37437
- var aggregator = "".concat(collectionId, "-").concat(collectionPosition);
37438
- if (!collectionParticipantIds[aggregator]) {
37439
- collectionParticipantIds[aggregator] = [];
37440
- }
37441
- var participantsCount = collectionParticipantIds[aggregator].length;
37442
- if ((collectionDefinition.matchUpType === SINGLES && participantsCount) ||
37443
- (collectionDefinition.matchUpType === DOUBLES &&
37444
- participantsCount > 1)) {
37445
- return { value: {
37446
- info: 'Excessive collectionPosition assignments',
37447
- error: INVALID_VALUES,
37448
- } };
37449
- }
37450
- collectionParticipantIds[aggregator].push(participantId);
37451
- };
37452
- try {
37453
- for (var collectionAssignments_1 = (e_5 = void 0, __values(collectionAssignments)), collectionAssignments_1_1 = collectionAssignments_1.next(); !collectionAssignments_1_1.done; collectionAssignments_1_1 = collectionAssignments_1.next()) {
37454
- var collectionAssignment = collectionAssignments_1_1.value;
37455
- var state_2 = _loop_3(collectionAssignment);
37456
- if (typeof state_2 === "object")
37457
- return state_2;
37458
- }
37459
- }
37460
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
37461
- finally {
37462
- try {
37463
- if (collectionAssignments_1_1 && !collectionAssignments_1_1.done && (_m = collectionAssignments_1.return)) _m.call(collectionAssignments_1);
37464
- }
37465
- finally { if (e_5) throw e_5.error; }
37466
- }
37467
- };
37468
- try {
37469
- for (var lineUp_1 = (e_2 = void 0, __values(lineUp)), lineUp_1_1 = lineUp_1.next(); !lineUp_1_1.done; lineUp_1_1 = lineUp_1.next()) {
37470
- var lineUpAssignment = lineUp_1_1.value;
37471
- var state_1 = _loop_1(lineUpAssignment);
37472
- if (typeof state_1 === "object")
37473
- return state_1.value;
37474
- }
37475
- }
37476
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
37477
- finally {
37478
- try {
37479
- if (lineUp_1_1 && !lineUp_1_1.done && (_c = lineUp_1.return)) _c.call(lineUp_1);
37480
- }
37481
- finally { if (e_2) throw e_2.error; }
37482
- }
37483
- // ensure that doubles pair participants exist, otherwise create
37484
- var collectionParticipantIdPairs = Object.values(collectionParticipantIds);
37485
- try {
37486
- for (var collectionParticipantIdPairs_1 = (e_3 = void 0, __values(collectionParticipantIdPairs)), collectionParticipantIdPairs_1_1 = collectionParticipantIdPairs_1.next(); !collectionParticipantIdPairs_1_1.done; collectionParticipantIdPairs_1_1 = collectionParticipantIdPairs_1.next()) {
37487
- var participantIds = collectionParticipantIdPairs_1_1.value;
37488
- if (participantIds.length === 2) {
37489
- var pairedParticipant = getPairedParticipant({
37490
- tournamentParticipants: tournamentParticipants,
37491
- participantIds: participantIds,
37492
- }).participant;
37493
- if (!pairedParticipant) {
37494
- // create pair participant
37495
- var newPairParticipant = {
37496
- participantType: PAIR,
37497
- participantRole: COMPETITOR,
37498
- individualParticipantIds: participantIds,
37499
- };
37500
- var result_1 = addParticipant({
37501
- participant: newPairParticipant,
37502
- pairOverride: true,
37503
- tournamentRecord: tournamentRecord,
37504
- });
37505
- if (result_1.error)
37506
- return result_1;
37507
- }
37508
- }
37509
- }
37510
- }
37511
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
37512
- finally {
37513
- try {
37514
- if (collectionParticipantIdPairs_1_1 && !collectionParticipantIdPairs_1_1.done && (_d = collectionParticipantIdPairs_1.return)) _d.call(collectionParticipantIdPairs_1);
37515
- }
37516
- finally { if (e_3) throw e_3.error; }
37517
- }
37518
- // determine sideNumber based on instances of participants appearing in team participants assigned to sides
37519
- // allows for some team members to be "borrowed"
37520
- var instances = instanceCount(sideNumbers);
37521
- var sideNumber = ((instances[1] || 0) > (instances[2] || 0) && 1) ||
37522
- ((instances[2] || 0) > (instances[1] || 0) && 2) ||
37523
- undefined;
37524
- // if side not previously assigned, map sideNumber to lineUp
37525
- var sideAssignmentKeys = Object.keys(sideAssignments).map(function (key) {
37526
- return parseInt(key);
37527
- });
37528
- if (sideNumber && !sideAssignmentKeys.includes(sideNumber)) {
37529
- sideAssignments[sideNumber] = lineUp;
37530
- }
37517
+ for (var _c = __values(Object.keys(possiblePairings)), _d = _c.next(); !_d.done; _d = _c.next()) {
37518
+ var participantId = _d.value;
37519
+ _loop_1(participantId);
37531
37520
  }
37532
37521
  }
37533
37522
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
37534
37523
  finally {
37535
37524
  try {
37536
- if (lineUps_1_1 && !lineUps_1_1.done && (_b = lineUps_1.return)) _b.call(lineUps_1);
37525
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
37537
37526
  }
37538
37527
  finally { if (e_1) throw e_1.error; }
37539
37528
  }
37540
- if (!Object.keys(sideAssignments).length)
37541
- return { error: VALUE_UNCHANGED };
37542
- result = findDrawMatchUp({ drawDefinition: drawDefinition, matchUpId: matchUpId });
37543
- if (result.error)
37544
- return result;
37545
- if (!result.matchUp)
37546
- return { error: MATCHUP_NOT_FOUND };
37547
- var matchUp = result.matchUp;
37548
- if (!matchUp.sides)
37549
- matchUp.sides = [];
37550
- var _loop_2 = function (sideNumber) {
37551
- var side = matchUp.sides.find(function (side) { return side.sideNumber === sideNumber; });
37552
- var assignment = sideAssignments[sideNumber];
37553
- if (!assignment) {
37554
- return "continue";
37555
- }
37556
- else if (!side) {
37557
- matchUp.sides.push({ lineUp: assignment, sideNumber: sideNumber });
37529
+ function pairingValue(participantId, opponent) {
37530
+ var key = pairingHash(participantId, opponent);
37531
+ return { opponent: opponent, value: valueObjects[key] };
37532
+ }
37533
+ return { pairingValues: pairingValues };
37534
+ }
37535
+
37536
+ var ELO = 'ELO';
37537
+ var NTRP = 'NTRP';
37538
+ var TRN = 'TRN';
37539
+ var UTR = 'UTR';
37540
+ var WTN = 'WTN';
37541
+ var ratingConstants = {
37542
+ ELO: ELO,
37543
+ NTRP: NTRP,
37544
+ TRN: TRN,
37545
+ UTR: UTR,
37546
+ WTN: WTN,
37547
+ };
37548
+
37549
+ var _a$e;
37550
+ var ratingsParameters = (_a$e = {},
37551
+ _a$e[ELO] = {
37552
+ defaultInitialization: 1500,
37553
+ decimalsCount: 0,
37554
+ range: [0, 3000],
37555
+ ascending: true,
37556
+ },
37557
+ _a$e[NTRP] = {
37558
+ accessors: ['ntrpRating', 'dntrpRatingHundredths'],
37559
+ attributes: { ustaRatingType: '' },
37560
+ accessor: 'dntrpRatingHundredths',
37561
+ defaultInitialization: 3,
37562
+ decimalsCount: 1,
37563
+ ascending: true,
37564
+ range: [1, 7],
37565
+ },
37566
+ _a$e[UTR] = {
37567
+ defaultInitialization: 6,
37568
+ accessors: ['utrRating'],
37569
+ accessor: 'utrRating',
37570
+ decimalsCount: 2,
37571
+ ascending: true,
37572
+ range: [1, 16],
37573
+ },
37574
+ _a$e[WTN] = {
37575
+ attributes: { confidence: { generator: true, range: [60, 100] } },
37576
+ accessors: ['wtnRating', 'confidence'],
37577
+ defaultInitialization: 23,
37578
+ accessor: 'wtnRating',
37579
+ ascending: false,
37580
+ decimalsCount: 2,
37581
+ range: [40, 1],
37582
+ },
37583
+ _a$e);
37584
+
37585
+ var DEFAULT_RATING = 0;
37586
+ function getSideRatings(_a) {
37587
+ var _b, _c;
37588
+ var tournamentParticipants = _a.tournamentParticipants, adHocRatings = _a.adHocRatings, eventType = _a.eventType, scaleName = _a.scaleName, pairing = _a.pairing;
37589
+ var defaultRating = (_c = (_b = ratingsParameters[scaleName]) === null || _b === void 0 ? void 0 : _b.defaultInitialization) !== null && _c !== void 0 ? _c : DEFAULT_RATING;
37590
+ return pairing.split('|').map(function (participantId) {
37591
+ var _a;
37592
+ if (eventType === DOUBLES$1) {
37593
+ var individualParticipantIds = (_a = tournamentParticipants === null || tournamentParticipants === void 0 ? void 0 : tournamentParticipants.find(function (participant) { return participant.participantId === participantId; })) === null || _a === void 0 ? void 0 : _a.individualParticipantIds;
37594
+ return !individualParticipantIds
37595
+ ? defaultRating * 2
37596
+ : individualParticipantIds === null || individualParticipantIds === void 0 ? void 0 : individualParticipantIds.map(function (participantId) { return adHocRatings[participantId] || defaultRating; });
37558
37597
  }
37559
37598
  else {
37560
- side.lineUp = assignment;
37561
- }
37562
- };
37563
- try {
37564
- for (var _k = __values([1, 2]), _l = _k.next(); !_l.done; _l = _k.next()) {
37565
- var sideNumber = _l.value;
37566
- _loop_2(sideNumber);
37567
- }
37568
- }
37569
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
37570
- finally {
37571
- try {
37572
- if (_l && !_l.done && (_e = _k.return)) _e.call(_k);
37599
+ return adHocRatings[participantId] || defaultRating;
37573
37600
  }
37574
- finally { if (e_4) throw e_4.error; }
37575
- }
37576
- modifyMatchUpNotice({
37577
- tournamentId: tournamentRecord === null || tournamentRecord === void 0 ? void 0 : tournamentRecord.tournamentId,
37578
- context: stack,
37579
- drawDefinition: drawDefinition,
37580
- matchUp: matchUp,
37581
37601
  });
37582
- return __assign({}, SUCCESS);
37583
37602
  }
37584
37603
 
37585
- function resetTieFormat(params) {
37586
- var _a, _b, e_1, _c, e_2, _d;
37587
- var _e, _f, _g;
37588
- var stack = 'resetTieFormat';
37589
- var drawDefinition = params.drawDefinition, event = params.event, uuids = params.uuids;
37590
- var paramCheck = checkRequiredParameters(params, [(_a = {}, _a[TOURNAMENT_RECORD] = true, _a[MATCHUP_ID] = true, _a)], stack);
37591
- if (paramCheck.error)
37592
- return paramCheck;
37593
- var resolutions = resolveFromParameters(params, [(_b = {}, _b[PARAM] = MATCHUP, _b)]);
37594
- if (resolutions[ERROR])
37595
- return resolutions;
37596
- var tournamentId = (_e = params.tournamentRecord) === null || _e === void 0 ? void 0 : _e.tournamentId;
37597
- var _h = (_f = resolutions === null || resolutions === void 0 ? void 0 : resolutions.matchUp) !== null && _f !== void 0 ? _f : {}, matchUp = _h.matchUp, structure = _h.structure;
37598
- if (!(matchUp === null || matchUp === void 0 ? void 0 : matchUp.tieMatchUps))
37599
- return decorateResult({
37600
- result: { error: INVALID_MATCHUP },
37601
- info: 'Must be a TEAM matchUp',
37602
- stack: stack,
37603
- });
37604
- // if there is no tieFormat there is nothing to do
37605
- if (!matchUp.tieFormat)
37606
- return __assign({}, SUCCESS);
37607
- var tieFormat = (_g = resolveTieFormat({
37608
- structure: structure,
37609
- drawDefinition: drawDefinition,
37610
- event: event,
37611
- })) === null || _g === void 0 ? void 0 : _g.tieFormat;
37612
- if (!tieFormat)
37613
- return decorateResult({
37614
- result: { error: NOT_FOUND },
37615
- info: 'No inherited tieFormat',
37616
- stack: stack,
37604
+ function getPairings(_a) {
37605
+ var tournamentParticipants = _a.tournamentParticipants, _b = _a.adHocRatings, adHocRatings = _b === void 0 ? {} : _b, possiblePairings = _a.possiblePairings, // participant keyed; provides array of possible opponents
37606
+ uniquePairings = _a.uniquePairings, // hashes of all possible participantId pairings
37607
+ maxIterations = _a.maxIterations, deltaObjects = _a.deltaObjects, // difference in rating between paired participants
37608
+ valueObjects = _a.valueObjects, // calculated value of a pairing of participants, used for sorting pairings
37609
+ eventType = _a.eventType, scaleName = _a.scaleName, salted = _a.salted;
37610
+ // modify valueObjects by ratings ratingsDifference squared
37611
+ // update deltaObjects to reflect the current difference between participant's ratings
37612
+ uniquePairings.forEach(function (pairing) {
37613
+ var ratings = getSideRatings({
37614
+ tournamentParticipants: tournamentParticipants,
37615
+ adHocRatings: adHocRatings,
37616
+ scaleName: scaleName,
37617
+ eventType: eventType,
37618
+ pairing: pairing,
37617
37619
  });
37618
- var deletedMatchUpIds = [];
37619
- var collectionIds = [];
37620
- var tieMatchUps = [];
37621
- var newMatchUps = [];
37622
- var _loop_1 = function (collectionDefinition) {
37623
- // delete any matchUp.tieMatchUps that are not found in the ancestor tieFormat collectionDefinitions
37624
- var matchUpCount = collectionDefinition.matchUpCount, collectionId = collectionDefinition.collectionId;
37625
- collectionIds.push(collectionId);
37626
- var existingCollectionMatchUps = (matchUp.tieMatchUps || []).filter(function (matchUp) { return matchUp.collectionId === collectionId; });
37627
- if (existingCollectionMatchUps.length > matchUpCount) {
37628
- // sort by matchUpStatus to prioritize active or completed matchUpsA
37629
- existingCollectionMatchUps.sort(function (a, b) {
37630
- return (a.matchUpStatus === TO_BE_PLAYED ? 1 : 0) -
37631
- (b.matchUpStatus === TO_BE_PLAYED ? 1 : 0);
37632
- });
37633
- tieMatchUps.push.apply(tieMatchUps, __spreadArray([], __read(existingCollectionMatchUps.slice(0, matchUpCount)), false));
37634
- deletedMatchUpIds.push.apply(deletedMatchUpIds, __spreadArray([], __read(existingCollectionMatchUps.slice(3).map(getMatchUpId)), false));
37635
- }
37636
- else {
37637
- tieMatchUps.push.apply(tieMatchUps, __spreadArray([], __read(existingCollectionMatchUps), false));
37638
- if (existingCollectionMatchUps.length < matchUpCount) {
37639
- var matchUpsLimit = matchUpCount - existingCollectionMatchUps.length;
37640
- var matchUps = generateCollectionMatchUps({
37641
- collectionDefinition: collectionDefinition,
37642
- matchUpsLimit: matchUpsLimit,
37643
- uuids: uuids,
37644
- });
37645
- newMatchUps.push.apply(newMatchUps, __spreadArray([], __read(matchUps), false));
37646
- }
37647
- }
37620
+ var salting = (typeof salted === 'number' && salted) || 0.5;
37621
+ var salt = (salted && (Math.round(Math.random()) ? salting : salting * -1)) || 0;
37622
+ var ratingsDifference = Math.abs(ratings[0] - ratings[1]) + salt;
37623
+ var pairingDelta = Math.abs(ratings[0] - ratings[1]);
37624
+ deltaObjects[pairing] = pairingDelta;
37625
+ if (!valueObjects[pairing])
37626
+ valueObjects[pairing] = 0;
37627
+ valueObjects[pairing] += ratingsDifference
37628
+ ? Math.pow(ratingsDifference, 2)
37629
+ : 0;
37630
+ });
37631
+ /**
37632
+ * valueSortedPairings are uniquePairings sorted by the ratings difference of the pairings, lowest to highest
37633
+ */
37634
+ var valueSortedPairings = uniquePairings
37635
+ .map(function (pairing) { return ({ pairing: pairing, value: valueObjects[pairing] }); })
37636
+ .sort(function (a, b) { return a.value - b.value; });
37637
+ /**
37638
+ * pairingValues is keyed by participantId and provides a value-sorted array of pairings for each participantId
37639
+ * 'actorId': [
37640
+ { opponent: 'potentialId1', value: 1 },
37641
+ { opponent: 'potentialId2', value: 1 },
37642
+ */
37643
+ var pairingValues = getParticipantPairingValues({
37644
+ possiblePairings: possiblePairings,
37645
+ valueObjects: valueObjects,
37646
+ }).pairingValues;
37647
+ var _c = generateCandidate({
37648
+ valueSortedPairings: valueSortedPairings,
37649
+ maxIterations: maxIterations,
37650
+ pairingValues: pairingValues,
37651
+ deltaObjects: deltaObjects,
37652
+ valueObjects: valueObjects,
37653
+ }), candidate = _c.candidate, candidatesCount = _c.candidatesCount, deltaCandidate = _c.deltaCandidate, iterations = _c.iterations;
37654
+ var participantIdPairings = candidate.participantIdPairings;
37655
+ return {
37656
+ participantIdPairings: participantIdPairings,
37657
+ candidatesCount: candidatesCount,
37658
+ deltaCandidate: deltaCandidate,
37659
+ iterations: iterations,
37660
+ candidate: candidate,
37648
37661
  };
37649
- try {
37650
- for (var _j = __values(tieFormat.collectionDefinitions), _k = _j.next(); !_k.done; _k = _j.next()) {
37651
- var collectionDefinition = _k.value;
37652
- _loop_1(collectionDefinition);
37653
- }
37662
+ }
37663
+
37664
+ // this should be in policyDefinitions
37665
+ var ENCOUNTER_VALUE = 100;
37666
+ var SAME_TEAM_VALUE = 100;
37667
+ var MAX_ITERATIONS = 4000;
37668
+ function generateDrawMaticRound(_a) {
37669
+ var e_1, _b, e_2, _c, e_3, _d;
37670
+ var _e, _f;
37671
+ var _g = _a.encounterValue, encounterValue = _g === void 0 ? ENCOUNTER_VALUE : _g, _h = _a.sameTeamValue, sameTeamValue = _h === void 0 ? SAME_TEAM_VALUE : _h, _j = _a.maxIterations, maxIterations = _j === void 0 ? MAX_ITERATIONS : _j, _k = _a.generateMatchUps, generateMatchUps = _k === void 0 ? true : _k, tournamentParticipants = _a.tournamentParticipants, participantIds = _a.participantIds, drawDefinition = _a.drawDefinition, adHocRatings = _a.adHocRatings, structureId = _a.structureId, _l = _a.salted, salted = _l === void 0 ? 0.5 : _l, matchUpIds = _a.matchUpIds, eventType = _a.eventType, structure = _a.structure, scaleName = _a.scaleName, isMock = _a.isMock, event = _a.event;
37672
+ if (!drawDefinition)
37673
+ return { error: MISSING_DRAW_DEFINITION };
37674
+ if (!structure && !structureId)
37675
+ return { error: STRUCTURE_NOT_FOUND };
37676
+ if (!structure) {
37677
+ structure = findStructure({ drawDefinition: drawDefinition, structureId: structureId }).structure;
37654
37678
  }
37655
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
37656
- finally {
37657
- try {
37658
- if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
37659
- }
37660
- finally { if (e_1) throw e_1.error; }
37679
+ if (!isObject(structure))
37680
+ return { error: MISSING_STRUCTURE };
37681
+ if (!(participantIds === null || participantIds === void 0 ? void 0 : participantIds.length)) {
37682
+ return { error: MISSING_PARTICIPANT_IDS };
37661
37683
  }
37684
+ // create valueObject for each previous encounter within the structure
37685
+ var encounters = getEncounters({ matchUps: (_e = structure === null || structure === void 0 ? void 0 : structure.matchUps) !== null && _e !== void 0 ? _e : [] }).encounters;
37686
+ // valueObjects provide "weighting" to each possible pairing of participants
37687
+ // {
37688
+ // 'P-I-0|P-I-1': 1,
37689
+ // 'P-I-0|P-I-2': 1,
37690
+ // 'P-I-0|P-I-3': 1
37691
+ // }
37692
+ var valueObjects = {};
37662
37693
  try {
37663
- for (var _l = __values((matchUp === null || matchUp === void 0 ? void 0 : matchUp.tieMatchUps) || []), _m = _l.next(); !_m.done; _m = _l.next()) {
37664
- var tieMatchUp = _m.value;
37665
- if (tieMatchUp.collectionId &&
37666
- !collectionIds.includes(tieMatchUp.collectionId))
37667
- deletedMatchUpIds.push(tieMatchUp.matchUpId);
37694
+ for (var encounters_1 = __values(encounters), encounters_1_1 = encounters_1.next(); !encounters_1_1.done; encounters_1_1 = encounters_1.next()) {
37695
+ var pairing = encounters_1_1.value;
37696
+ if (!valueObjects[pairing])
37697
+ valueObjects[pairing] = 0;
37698
+ valueObjects[pairing] += encounterValue;
37668
37699
  }
37669
37700
  }
37670
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
37701
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
37671
37702
  finally {
37672
37703
  try {
37673
- if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
37704
+ if (encounters_1_1 && !encounters_1_1.done && (_b = encounters_1.return)) _b.call(encounters_1);
37674
37705
  }
37675
- finally { if (e_2) throw e_2.error; }
37676
- }
37677
- if (newMatchUps.length) {
37678
- tieMatchUps.push.apply(tieMatchUps, __spreadArray([], __read(newMatchUps), false));
37679
- addMatchUpsNotice({
37680
- eventId: event === null || event === void 0 ? void 0 : event.eventId,
37681
- matchUps: newMatchUps,
37682
- drawDefinition: drawDefinition,
37683
- tournamentId: tournamentId,
37684
- });
37685
- }
37686
- if (deletedMatchUpIds.length) {
37687
- deleteMatchUpsNotice({
37688
- matchUpIds: deletedMatchUpIds,
37689
- eventId: event === null || event === void 0 ? void 0 : event.eventId,
37690
- drawDefinition: drawDefinition,
37691
- tournamentId: tournamentId,
37692
- });
37693
- }
37694
- if (matchUp) {
37695
- matchUp.tieMatchUps = tieMatchUps;
37696
- matchUp.tieFormatId = undefined;
37697
- matchUp.tieFormat = undefined;
37698
- modifyMatchUpNotice({
37699
- structureId: structure === null || structure === void 0 ? void 0 : structure.structureId,
37700
- eventId: event === null || event === void 0 ? void 0 : event.eventId,
37701
- context: stack,
37702
- drawDefinition: drawDefinition,
37703
- tournamentId: tournamentId,
37704
- matchUp: matchUp,
37705
- });
37706
+ finally { if (e_1) throw e_1.error; }
37706
37707
  }
37707
- return __assign(__assign({}, SUCCESS), { newMatchUps: newMatchUps, deletedMatchUpIds: deletedMatchUpIds });
37708
- }
37709
-
37710
- function resetScorecard(params) {
37711
- var e_1, _a;
37712
- var _b, _c;
37713
- var tournamentRecord = params.tournamentRecord, drawDefinition = params.drawDefinition, matchUpId = params.matchUpId, event = params.event;
37714
- var stack = 'resetScorecard';
37715
- // Check for missing parameters ---------------------------------------------
37716
- if (!drawDefinition)
37717
- return decorateResult({
37718
- result: { error: MISSING_DRAW_DEFINITION },
37719
- stack: stack,
37720
- });
37721
- if (!matchUpId)
37722
- return decorateResult({ result: { error: MISSING_MATCHUP_ID }, stack: stack });
37723
- if (!isString(matchUpId))
37724
- return decorateResult({
37725
- result: { error: INVALID_VALUES, matchUpId: matchUpId },
37726
- stack: stack,
37727
- });
37728
- // Get map of all drawMatchUps and inContextDrawMatchUPs ---------------------
37729
- var matchUpsMap = getMatchUpsMap({ drawDefinition: drawDefinition });
37730
- var inContextDrawMatchUps = getAllDrawMatchUps({
37731
- nextMatchUps: true,
37732
- inContext: true,
37733
- drawDefinition: drawDefinition,
37734
- matchUpsMap: matchUpsMap,
37735
- }).matchUps;
37736
- // Find target matchUp ------------------------------------------------------
37737
- var matchUp = matchUpsMap.drawMatchUps.find(function (matchUp) { return matchUp.matchUpId === matchUpId; });
37738
- var inContextMatchUp = inContextDrawMatchUps === null || inContextDrawMatchUps === void 0 ? void 0 : inContextDrawMatchUps.find(function (matchUp) { return matchUp.matchUpId === matchUpId; });
37739
- if (!matchUp || !inContextDrawMatchUps)
37740
- return { error: MATCHUP_NOT_FOUND };
37741
- // only accept matchUpType: TEAM
37742
- if (matchUp.matchUpType !== TEAM_EVENT)
37743
- return { error: INVALID_MATCHUP };
37744
- // Get winner/loser position targets ----------------------------------------
37745
- var targetData = positionTargets({
37746
- inContextDrawMatchUps: inContextDrawMatchUps,
37747
- drawDefinition: drawDefinition,
37748
- matchUpId: matchUpId,
37749
- });
37750
- var structureId = inContextMatchUp === null || inContextMatchUp === void 0 ? void 0 : inContextMatchUp.structureId;
37751
- var structure = findStructure({ drawDefinition: drawDefinition, structureId: structureId }).structure;
37752
- Object.assign(params, {
37753
- inContextDrawMatchUps: inContextDrawMatchUps,
37754
- inContextMatchUp: inContextMatchUp,
37755
- matchUpsMap: matchUpsMap,
37756
- targetData: targetData,
37757
- structure: structure,
37758
- matchUp: matchUp,
37708
+ var teamParticipants = tournamentParticipants === null || tournamentParticipants === void 0 ? void 0 : tournamentParticipants.filter(function (_a) {
37709
+ var participantType = _a.participantType;
37710
+ return participantType === TEAM;
37759
37711
  });
37760
- // with propagating winningSide changes, activeDownstream only applies to eventType: TEAM
37761
- var activeDownstream = isActiveDownstream(params);
37762
- if (activeDownstream)
37763
- return { error: CANNOT_CHANGE_WINNING_SIDE };
37764
- if ((_b = matchUp.tieMatchUps) === null || _b === void 0 ? void 0 : _b.length) {
37712
+ if (teamParticipants) {
37765
37713
  try {
37766
- for (var _d = __values(matchUp.tieMatchUps), _e = _d.next(); !_e.done; _e = _d.next()) {
37767
- var tieMatchUp = _e.value;
37768
- var result_1 = setMatchUpState({
37769
- matchUpId: tieMatchUp.matchUpId,
37770
- matchUpTieId: matchUpId,
37771
- winningSide: undefined,
37772
- removeScore: true,
37773
- tournamentRecord: tournamentRecord,
37774
- drawDefinition: drawDefinition,
37775
- event: event,
37776
- });
37777
- if (result_1.error)
37778
- return decorateResult({ result: result_1, stack: stack });
37714
+ // add SAME_TEAM_VALUE for participants who appear on the same team
37715
+ for (var teamParticipants_1 = __values(teamParticipants), teamParticipants_1_1 = teamParticipants_1.next(); !teamParticipants_1_1.done; teamParticipants_1_1 = teamParticipants_1.next()) {
37716
+ var teamParticipant = teamParticipants_1_1.value;
37717
+ var participantIds_1 = (_f = teamParticipant.individualParticipantIds) !== null && _f !== void 0 ? _f : [];
37718
+ var uniquePairings_2 = getPairingsData({ participantIds: participantIds_1 }).uniquePairings;
37719
+ try {
37720
+ for (var uniquePairings_1 = (e_3 = void 0, __values(uniquePairings_2)), uniquePairings_1_1 = uniquePairings_1.next(); !uniquePairings_1_1.done; uniquePairings_1_1 = uniquePairings_1.next()) {
37721
+ var pairing = uniquePairings_1_1.value;
37722
+ if (!valueObjects[pairing])
37723
+ valueObjects[pairing] = 0;
37724
+ valueObjects[pairing] += sameTeamValue;
37725
+ }
37726
+ }
37727
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
37728
+ finally {
37729
+ try {
37730
+ if (uniquePairings_1_1 && !uniquePairings_1_1.done && (_d = uniquePairings_1.return)) _d.call(uniquePairings_1);
37731
+ }
37732
+ finally { if (e_3) throw e_3.error; }
37733
+ }
37779
37734
  }
37780
37735
  }
37781
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
37736
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
37782
37737
  finally {
37783
37738
  try {
37784
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
37739
+ if (teamParticipants_1_1 && !teamParticipants_1_1.done && (_c = teamParticipants_1.return)) _c.call(teamParticipants_1);
37785
37740
  }
37786
- finally { if (e_1) throw e_1.error; }
37741
+ finally { if (e_2) throw e_2.error; }
37787
37742
  }
37788
37743
  }
37789
- var result = updateTieMatchUpScore({
37790
- event: params.event,
37791
- removeScore: true,
37792
- tournamentRecord: tournamentRecord,
37744
+ // deltaObjects contain the difference in ratings between two participants
37745
+ // {
37746
+ // 'P-I-0|P-I-1': 0,
37747
+ // 'P-I-0|P-I-2': 0,
37748
+ // 'P-I-0|P-I-3': 0
37749
+ // }
37750
+ var _m = getPairingsData({
37751
+ participantIds: participantIds,
37752
+ }), uniquePairings = _m.uniquePairings, possiblePairings = _m.possiblePairings, deltaObjects = _m.deltaObjects;
37753
+ var params = {
37754
+ tournamentParticipants: tournamentParticipants,
37755
+ possiblePairings: possiblePairings,
37793
37756
  drawDefinition: drawDefinition,
37794
- matchUpsMap: matchUpsMap,
37795
- matchUpId: matchUpId,
37796
- });
37797
- if (result.error)
37798
- return decorateResult({ result: result, stack: stack });
37799
- if (params.tiebreakReset && !result.tieFormatRemoved) {
37800
- // check for scenarios where an added "Tiebreaker" collectionDefinition/matchUp has been added
37801
- var inheritedTieFormat = (_c = resolveTieFormat({
37802
- drawDefinition: drawDefinition,
37803
- structure: structure,
37804
- event: event,
37805
- })) === null || _c === void 0 ? void 0 : _c.tieFormat;
37806
- if (matchUp.tieFormat && inheritedTieFormat) {
37807
- var _f = compareTieFormats({
37808
- descendant: matchUp.tieFormat,
37809
- ancestor: inheritedTieFormat,
37810
- }), matchUpCountDifference = _f.matchUpCountDifference, descendantDifferences = _f.descendantDifferences, ancestorDifferences = _f.ancestorDifferences, valueDifference = _f.valueDifference;
37811
- if (descendantDifferences.collectionIds.length === 1 &&
37812
- !ancestorDifferences.collectionIds.length &&
37813
- !ancestorDifferences.groupsCount &&
37814
- matchUpCountDifference === 1 &&
37815
- valueDifference === 1) {
37816
- var result_2 = resetTieFormat({
37817
- tournamentRecord: tournamentRecord,
37818
- drawDefinition: drawDefinition,
37819
- matchUpId: matchUpId,
37820
- event: event,
37821
- });
37822
- if (result_2.error)
37823
- return result_2;
37824
- }
37825
- }
37757
+ participantIds: participantIds,
37758
+ uniquePairings: uniquePairings,
37759
+ maxIterations: maxIterations,
37760
+ adHocRatings: adHocRatings,
37761
+ deltaObjects: deltaObjects,
37762
+ valueObjects: valueObjects,
37763
+ eventType: eventType,
37764
+ scaleName: scaleName,
37765
+ structure: structure,
37766
+ salted: salted,
37767
+ };
37768
+ var _o = getPairings(params), candidatesCount = _o.candidatesCount, participantIdPairings = _o.participantIdPairings, iterations = _o.iterations, candidate = _o.candidate;
37769
+ if (!candidatesCount)
37770
+ return { error: NO_CANDIDATES };
37771
+ var matchUps;
37772
+ if (generateMatchUps) {
37773
+ var result = generateAdHocMatchUps({
37774
+ structureId: structure === null || structure === void 0 ? void 0 : structure.structureId,
37775
+ participantIdPairings: participantIdPairings,
37776
+ newRound: true,
37777
+ drawDefinition: drawDefinition,
37778
+ matchUpIds: matchUpIds,
37779
+ isMock: isMock,
37780
+ event: event,
37781
+ });
37782
+ if (result.error)
37783
+ return result;
37784
+ matchUps = result.matchUps;
37826
37785
  }
37827
- return __assign({}, SUCCESS);
37786
+ var maxDelta = candidate.maxDelta, maxDiff = candidate.maxDiff;
37787
+ return __assign(__assign({}, SUCCESS), { participantIdPairings: participantIdPairings, candidatesCount: candidatesCount, iterations: iterations, matchUps: matchUps, maxDelta: maxDelta, maxDiff: maxDiff });
37828
37788
  }
37829
37789
 
37830
- function removeSeeding(_a) {
37831
- var _b, _c;
37832
- var tournamentRecord = _a.tournamentRecord, drawDefinition = _a.drawDefinition, entryStatuses = _a.entryStatuses, scaleName = _a.scaleName, drawId = _a.drawId, event = _a.event, stage = _a.stage;
37833
- if (!tournamentRecord)
37834
- return { error: MISSING_TOURNAMENT_RECORD };
37835
- if (!event)
37836
- return { error: MISSING_EVENT };
37837
- scaleName =
37838
- scaleName ||
37839
- ((_b = event.category) === null || _b === void 0 ? void 0 : _b.categoryName) ||
37840
- ((_c = event.category) === null || _c === void 0 ? void 0 : _c.ageCategoryCode);
37841
- var scaleAttributes = {
37842
- eventType: event.eventType,
37843
- scaleType: SEEDING$1,
37844
- scaleName: scaleName,
37790
+ function drawMatic(_a) {
37791
+ var e_1, _b;
37792
+ var _c, _d, _e, _f, _g;
37793
+ var restrictEntryStatus = _a.restrictEntryStatus, _h = _a.adHocRatings, adHocRatings = _h === void 0 ? {} : _h, generateMatchUps = _a.generateMatchUps, tournamentRecord = _a.tournamentRecord, participantIds = _a.participantIds, encounterValue = _a.encounterValue, sameTeamValue = _a.sameTeamValue, drawDefinition = _a.drawDefinition, scaleAccessor = _a.scaleAccessor, maxIterations = _a.maxIterations, structureId = _a.structureId, matchUpIds = _a.matchUpIds, scaleName = _a.scaleName, // custom rating name to seed dynamic ratings
37794
+ eventType = _a.eventType, isMock = _a.isMock, salted = _a.salted, event = _a.event;
37795
+ if (typeof drawDefinition !== 'object' ||
37796
+ (drawDefinition.drawType && drawDefinition.drawType !== AD_HOC)) {
37797
+ return { error: INVALID_DRAW_DEFINITION };
37798
+ }
37799
+ if (!Array.isArray(drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.entries) &&
37800
+ participantIds &&
37801
+ !Array.isArray(participantIds)) {
37802
+ return { error: INVALID_VALUES, info: 'Missing Entries' };
37803
+ }
37804
+ eventType = eventType !== null && eventType !== void 0 ? eventType : event === null || event === void 0 ? void 0 : event.eventType;
37805
+ var enteredParticipantIds = (_c = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.entries) === null || _c === void 0 ? void 0 : _c.filter(function (entry) {
37806
+ var entryStatus = entry.entryStatus;
37807
+ return (!restrictEntryStatus ||
37808
+ STRUCTURE_SELECTED_STATUSES.includes(entryStatus));
37809
+ }).map(getParticipantId);
37810
+ if (participantIds) {
37811
+ // ensure all participantIds are in drawDefinition.entries
37812
+ var invalidParticipantIds = participantIds.filter(function (participantId) { return !(enteredParticipantIds === null || enteredParticipantIds === void 0 ? void 0 : enteredParticipantIds.includes(participantId)); });
37813
+ if (invalidParticipantIds === null || invalidParticipantIds === void 0 ? void 0 : invalidParticipantIds.length)
37814
+ return decorateResult({
37815
+ result: { error: INVALID_PARTICIPANT_ID },
37816
+ info: { invalidParticipantIds: invalidParticipantIds },
37817
+ });
37818
+ }
37819
+ else {
37820
+ participantIds = enteredParticipantIds;
37821
+ }
37822
+ // if no structureId is specified find the latest AD_HOC stage which has matchUps
37823
+ if (!structureId) {
37824
+ var targetStructure = (_e = (_d = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.structures) === null || _d === void 0 ? void 0 : _d.filter(function (structure) { return structure.stageSequence === 1; })) === null || _e === void 0 ? void 0 : _e.reduce(function (targetStructure, structure) {
37825
+ var orderNumber = structure.stage && stageOrder$1[structure.stage];
37826
+ var structureIsAdHoc = isAdHoc({ drawDefinition: drawDefinition, structure: structure });
37827
+ return structureIsAdHoc &&
37828
+ orderNumber > (stageOrder$1[targetStructure === null || targetStructure === void 0 ? void 0 : targetStructure.stage] || 1)
37829
+ ? structure
37830
+ : targetStructure;
37831
+ }, undefined);
37832
+ structureId = targetStructure === null || targetStructure === void 0 ? void 0 : targetStructure.structureId;
37833
+ }
37834
+ var structure = (_f = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.structures) === null || _f === void 0 ? void 0 : _f.find(function (structure) { return structure.structureId === structureId; });
37835
+ if (!structure)
37836
+ return { error: STRUCTURE_NOT_FOUND };
37837
+ // an AD_HOC structure is one that has no child structures and in which no matchUps have roundPosition
37838
+ var structureIsAdHoc = isAdHoc({ drawDefinition: drawDefinition, structure: structure });
37839
+ if (!structureIsAdHoc)
37840
+ return { error: INVALID_DRAW_DEFINITION };
37841
+ var tournamentParticipants = (_g = tournamentRecord.participants) !== null && _g !== void 0 ? _g : [];
37842
+ var _loop_1 = function (participantId) {
37843
+ var participant = tournamentParticipants === null || tournamentParticipants === void 0 ? void 0 : tournamentParticipants.find(function (participant) { return participant.participantId === participantId; });
37844
+ // first see if there is already a dynamic value
37845
+ var scaleValue = getScaleValue({
37846
+ scaleName: "".concat(scaleName, ".").concat(DYNAMIC),
37847
+ scaleAccessor: scaleAccessor,
37848
+ participant: participant,
37849
+ eventType: eventType,
37850
+ });
37851
+ // if no dynamic value found and a seeding scaleValue is provided...
37852
+ if (!scaleValue && scaleName) {
37853
+ scaleValue = getScaleValue({
37854
+ scaleAccessor: scaleAccessor,
37855
+ participant: participant,
37856
+ scaleName: scaleName,
37857
+ eventType: eventType,
37858
+ });
37859
+ }
37860
+ if (scaleValue && !adHocRatings[participantId])
37861
+ adHocRatings[participantId] = scaleValue;
37845
37862
  };
37846
- return removeScaleValues({
37847
- tournamentRecord: tournamentRecord,
37848
- scaleAttributes: scaleAttributes,
37863
+ try {
37864
+ for (var _j = __values(participantIds !== null && participantIds !== void 0 ? participantIds : []), _k = _j.next(); !_k.done; _k = _j.next()) {
37865
+ var participantId = _k.value;
37866
+ _loop_1(participantId);
37867
+ }
37868
+ }
37869
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
37870
+ finally {
37871
+ try {
37872
+ if (_k && !_k.done && (_b = _j.return)) _b.call(_j);
37873
+ }
37874
+ finally { if (e_1) throw e_1.error; }
37875
+ }
37876
+ // TODO: update dynamic ratings based on matchUps present from last played round
37877
+ // use scaleEngine.generateDynamicRatings(); see dynamicCalculations.test.ts
37878
+ return generateDrawMaticRound({
37879
+ tournamentParticipants: tournamentParticipants,
37880
+ generateMatchUps: generateMatchUps,
37881
+ participantIds: participantIds,
37882
+ encounterValue: encounterValue,
37883
+ sameTeamValue: sameTeamValue,
37849
37884
  drawDefinition: drawDefinition,
37850
- entryStatuses: entryStatuses,
37851
- drawId: drawId,
37885
+ maxIterations: maxIterations,
37886
+ adHocRatings: adHocRatings,
37887
+ matchUpIds: matchUpIds,
37888
+ structure: structure,
37889
+ eventType: eventType,
37890
+ salted: salted,
37891
+ isMock: isMock,
37852
37892
  event: event,
37853
- stage: stage,
37854
37893
  });
37855
37894
  }
37895
+ function getScaleValue(_a) {
37896
+ var _b;
37897
+ var _c = _a.scaleType, scaleType = _c === void 0 ? RATING$2 : _c, scaleAccessor = _a.scaleAccessor, participant = _a.participant, scaleName = _a.scaleName, eventType = _a.eventType;
37898
+ var scaleAttributes = {
37899
+ eventType: eventType !== null && eventType !== void 0 ? eventType : SINGLES_EVENT,
37900
+ scaleType: scaleType,
37901
+ scaleName: scaleName,
37902
+ };
37903
+ var result = participant &&
37904
+ participantScaleItem({
37905
+ scaleAttributes: scaleAttributes,
37906
+ participant: participant,
37907
+ });
37908
+ var scaleValue = (_b = result === null || result === void 0 ? void 0 : result.scaleItem) === null || _b === void 0 ? void 0 : _b.scaleValue;
37909
+ return scaleAccessor && isObject(scaleValue)
37910
+ ? scaleValue[scaleAccessor]
37911
+ : scaleValue;
37912
+ }
37856
37913
 
37857
- function generateAdHocMatchUps(_a) {
37858
- var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
37859
- var participantIdPairings = _a.participantIdPairings, _p = _a.matchUpIds, matchUpIds = _p === void 0 ? [] : _p, drawDefinition = _a.drawDefinition, matchUpsCount = _a.matchUpsCount, roundNumber = _a.roundNumber, structureId = _a.structureId, newRound = _a.newRound;
37914
+ function addAdHocMatchUps(_a) {
37915
+ var _b;
37916
+ var _c, _d, _e, _f, _g, _h, _j;
37917
+ var tournamentRecord = _a.tournamentRecord, drawDefinition = _a.drawDefinition, structureId = _a.structureId, matchUps = _a.matchUps;
37860
37918
  if (typeof drawDefinition !== 'object')
37861
37919
  return { error: MISSING_DRAW_DEFINITION };
37862
- if (!structureId && ((_b = drawDefinition.structures) === null || _b === void 0 ? void 0 : _b.length) === 1)
37863
- structureId = (_d = (_c = drawDefinition.structures) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.structureId;
37920
+ if (!structureId && ((_c = drawDefinition.structures) === null || _c === void 0 ? void 0 : _c.length) === 1)
37921
+ structureId = (_e = (_d = drawDefinition.structures) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.structureId;
37864
37922
  if (typeof structureId !== 'string')
37865
37923
  return { error: MISSING_STRUCTURE_ID };
37866
- // if drawDefinition and structureId are provided it is possible to infer roundNumber
37867
- var structure = (_e = drawDefinition.structures) === null || _e === void 0 ? void 0 : _e.find(function (structure) { return structure.structureId === structureId; });
37924
+ if (!validMatchUps(matchUps))
37925
+ return { error: INVALID_VALUES, info: mustBeAnArray('matchUps') };
37926
+ var structure = (_f = drawDefinition.structures) === null || _f === void 0 ? void 0 : _f.find(function (structure) { return structure.structureId === structureId; });
37868
37927
  if (!structure)
37869
37928
  return { error: STRUCTURE_NOT_FOUND };
37870
- var structureHasRoundPositions;
37871
- var existingMatchUps = (_f = structure.matchUps) !== null && _f !== void 0 ? _f : [];
37872
- var lastRoundNumber = existingMatchUps === null || existingMatchUps === void 0 ? void 0 : existingMatchUps.reduce(function (roundNumber, matchUp) {
37873
- if (matchUp.roundPosition)
37874
- structureHasRoundPositions = true;
37875
- return ((matchUp === null || matchUp === void 0 ? void 0 : matchUp.roundNumber) || 0) > roundNumber
37876
- ? matchUp.roundNumber
37877
- : roundNumber;
37878
- }, 0);
37879
- if (!matchUpsCount) {
37880
- var selectedEntries = (_h = (_g = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.entries) === null || _g === void 0 ? void 0 : _g.filter(function (entry) {
37881
- var entryStatus = entry.entryStatus;
37882
- return STRUCTURE_SELECTED_STATUSES.includes(entryStatus);
37883
- })) !== null && _h !== void 0 ? _h : [];
37884
- var roundMatchUpsCount = Math.floor((selectedEntries === null || selectedEntries === void 0 ? void 0 : selectedEntries.length) / 2) || 1;
37885
- if (newRound) {
37886
- matchUpsCount = roundMatchUpsCount;
37887
- }
37888
- else {
37889
- var targetRoundNumber_1 = (_j = roundNumber !== null && roundNumber !== void 0 ? roundNumber : lastRoundNumber) !== null && _j !== void 0 ? _j : 1;
37890
- var existingRoundMatchUps = (_m = (_l = (_k = structure.matchUps) === null || _k === void 0 ? void 0 : _k.filter(function (matchUp) { return matchUp.roundNumber === targetRoundNumber_1; })) === null || _l === void 0 ? void 0 : _l.length) !== null && _m !== void 0 ? _m : 0;
37891
- var maxRemaining = roundMatchUpsCount - existingRoundMatchUps;
37892
- if (maxRemaining > 0)
37893
- matchUpsCount = maxRemaining;
37894
- }
37895
- }
37896
- if ((participantIdPairings && !Array.isArray(participantIdPairings)) ||
37897
- (matchUpsCount && !isConvertableInteger(matchUpsCount)) ||
37898
- (matchUpIds && !Array.isArray(matchUpIds)) ||
37899
- (!participantIdPairings && !matchUpsCount)) {
37900
- return { error: INVALID_VALUES, info: 'matchUpsCount or pairings error' };
37901
- }
37902
- // structure must not be a container of other structures
37903
- // structure must not contain matchUps with roundPosition
37904
- // structure must not determine finishingPosition by ROUND_OUTCOME
37929
+ var existingMatchUps = structure === null || structure === void 0 ? void 0 : structure.matchUps;
37930
+ var structureHasRoundPositions = existingMatchUps.find(function (matchUp) { return !!matchUp.roundPosition; });
37905
37931
  if (structure.structures ||
37906
37932
  structureHasRoundPositions ||
37907
37933
  structure.finishingPosition === ROUND_OUTCOME) {
37908
37934
  return { error: INVALID_STRUCTURE };
37909
37935
  }
37910
- if (roundNumber && roundNumber - 1 > (lastRoundNumber || 0))
37911
- return { error: INVALID_VALUES, info: 'roundNumber error' };
37912
- var nextRoundNumber = roundNumber !== null && roundNumber !== void 0 ? roundNumber : ((newRound && (lastRoundNumber !== null && lastRoundNumber !== void 0 ? lastRoundNumber : 0) + 1) || lastRoundNumber || 1);
37913
- participantIdPairings =
37914
- participantIdPairings !== null && participantIdPairings !== void 0 ? participantIdPairings : generateRange(0, matchUpsCount).map(function () { return ({
37915
- participantIds: [undefined, undefined],
37916
- }); });
37917
- var matchUps = participantIdPairings === null || participantIdPairings === void 0 ? void 0 : participantIdPairings.map(function (pairing) {
37918
- var _a, _b;
37919
- var idStack = (_a = pairing === null || pairing === void 0 ? void 0 : pairing.participantIds) !== null && _a !== void 0 ? _a : [undefined, undefined];
37920
- // ensure there are always 2 sides in generated matchUps
37921
- idStack.push.apply(idStack, [undefined, undefined]);
37922
- var participantIds = idStack.slice(0, 2);
37923
- var sides = participantIds.map(function (participantId, i) {
37924
- return definedAttributes({
37925
- sideNumber: i + 1,
37926
- participantId: participantId,
37927
- });
37928
- });
37936
+ var existingMatchUpIds = (_j = (_h = (_g = allTournamentMatchUps({
37937
+ tournamentRecord: tournamentRecord,
37938
+ inContext: false,
37939
+ })) === null || _g === void 0 ? void 0 : _g.matchUps) === null || _h === void 0 ? void 0 : _h.map(getMatchUpId)) !== null && _j !== void 0 ? _j : [];
37940
+ var newMatchUpIds = matchUps.map(getMatchUpId);
37941
+ if (overlap(existingMatchUpIds, newMatchUpIds)) {
37929
37942
  return {
37930
- matchUpId: (_b = matchUpIds.pop()) !== null && _b !== void 0 ? _b : UUID(),
37931
- roundNumber: nextRoundNumber,
37932
- matchUpStatus: TO_BE_PLAYED,
37933
- sides: sides,
37943
+ error: EXISTING_MATCHUP_ID,
37944
+ info: 'One or more matchUpIds already present in tournamentRecord',
37934
37945
  };
37946
+ }
37947
+ (_b = structure.matchUps).push.apply(_b, __spreadArray([], __read(matchUps), false));
37948
+ addMatchUpsNotice({
37949
+ tournamentId: tournamentRecord === null || tournamentRecord === void 0 ? void 0 : tournamentRecord.tournamentId,
37950
+ drawDefinition: drawDefinition,
37951
+ matchUps: matchUps,
37935
37952
  });
37936
- return __assign({ matchUpsCount: (_o = matchUps === null || matchUps === void 0 ? void 0 : matchUps.length) !== null && _o !== void 0 ? _o : 0, matchUps: matchUps }, SUCCESS);
37953
+ modifyDrawNotice({ drawDefinition: drawDefinition, structureIds: [structureId] });
37954
+ return __assign({}, SUCCESS);
37937
37955
  }
37938
37956
 
37939
- function generateCandidate(_a) {
37940
- var _b = _a.maxIterations, maxIterations = _b === void 0 ? 4000 : _b, // cap the processing intensity of the candidate generator
37941
- valueSortedPairings = _a.valueSortedPairings, // pairings sorted by value from low to high
37942
- pairingValues = _a.pairingValues, valueObjects = _a.valueObjects, deltaObjects = _a.deltaObjects;
37943
- var pairingValueMap = Object.assign.apply(Object, __spreadArray([{}], __read(valueSortedPairings.map(function (rm) {
37944
- var _a;
37945
- return (_a = {}, _a[rm.pairing] = rm.value, _a);
37946
- })), false));
37947
- var actors = Object.keys(pairingValues);
37948
- var proposedCandidates = [];
37949
- // generate an initial candidate value with no stipulated pairings
37950
- var initialProposal = roundCandidate({
37951
- actorsCount: actors.length,
37952
- valueSortedPairings: valueSortedPairings,
37953
- pairingValueMap: pairingValueMap,
37954
- deltaObjects: deltaObjects,
37955
- valueObjects: valueObjects,
37956
- });
37957
- var candidateHashes = [candidateHash(initialProposal)];
37958
- proposedCandidates.push(initialProposal);
37959
- var lowCandidateValue = initialProposal.value;
37960
- var deltaCandidate = initialProposal;
37961
- // iterations is the number of loops over valueSortedPairings
37962
- var candidatesCount = 0;
37963
- var iterations = 0;
37964
- var opponentCount = actors.length;
37965
- var calculatedIterations;
37966
- // calculate the number of opponents to consider for each participantId
37967
- do {
37968
- opponentCount -= 1;
37969
- calculatedIterations = actors.length * pairingValues[actors[0]].length;
37970
- } while (calculatedIterations > maxIterations && opponentCount > 5);
37971
- // keep track of proposed pairings
37972
- var stipulatedPairs = [];
37973
- // for each actor generate a roundCandidate using opponentCount of pairing values
37974
- actors.forEach(function (actor) {
37975
- var participantIdPairings = pairingValues[actor];
37976
- // opponentCount limits the number of opponents to consider
37977
- participantIdPairings.slice(0, opponentCount).forEach(function (pairing) {
37978
- iterations += 1;
37979
- var stipulatedPair = pairingHash(actor, pairing.opponent);
37980
- if (!stipulatedPairs.includes(stipulatedPair)) {
37981
- var proposed = roundCandidate({
37982
- // each roundCandidate starts with stipulated pairings
37983
- stipulated: [[actor, pairing.opponent]],
37984
- actorsCount: actors.length,
37985
- valueSortedPairings: valueSortedPairings,
37986
- pairingValueMap: pairingValueMap,
37987
- deltaObjects: deltaObjects,
37988
- valueObjects: valueObjects,
37989
- });
37990
- // ensure no duplicate candidates are considered
37991
- if (!candidateHashes.includes(candidateHash(proposed))) {
37992
- candidateHashes.push(candidateHash(proposed));
37993
- proposedCandidates.push(proposed);
37994
- var maxDelta = proposed.maxDelta, value = proposed.value;
37995
- if (maxDelta < deltaCandidate.maxDelta)
37996
- deltaCandidate = proposed;
37997
- if (value < lowCandidateValue ||
37998
- (value === lowCandidateValue && Math.round(Math.random())) // randomize if equivalent values
37999
- ) {
38000
- lowCandidateValue = value;
38001
- }
38002
- stipulatedPairs.push(stipulatedPair);
38003
- candidatesCount += 1;
38004
- }
38005
- }
37957
+ function attachFlightProfile(_a) {
37958
+ var _b;
37959
+ var deleteExisting = _a.deleteExisting, event = _a.event, flightProfile = _a.flightProfile;
37960
+ var stack = 'attachFlightProfile';
37961
+ if (!flightProfile)
37962
+ return decorateResult({ result: { error: MISSING_VALUE }, stack: stack });
37963
+ if (!event)
37964
+ return decorateResult({ result: { error: MISSING_EVENT }, stack: stack });
37965
+ var existingFlightProfile = getFlightProfile({ event: event }).flightProfile;
37966
+ if (existingFlightProfile && !deleteExisting)
37967
+ return decorateResult({ result: { error: EXISTING_PROFILE }, stack: stack });
37968
+ if ((_b = event.drawDefinitions) === null || _b === void 0 ? void 0 : _b.length)
37969
+ return decorateResult({
37970
+ result: { error: EXISTING_DRAW_DEFINITIONS },
37971
+ stack: stack,
38006
37972
  });
38007
- proposedCandidates = proposedCandidates.filter(function (proposed) { return Math.abs(proposed.value - lowCandidateValue) < 5; });
38008
- });
38009
- proposedCandidates.sort(function (a, b) { return a.maxDiff - b.maxDiff; });
38010
- var candidate = randomPop(proposedCandidates);
38011
- return {
38012
- candidatesCount: candidatesCount,
38013
- deltaCandidate: deltaCandidate,
38014
- maxIterations: maxIterations,
38015
- iterations: iterations,
38016
- candidate: candidate,
37973
+ var extension = {
37974
+ name: FLIGHT_PROFILE,
37975
+ value: flightProfile,
38017
37976
  };
37977
+ addEventExtension({ event: event, extension: extension });
37978
+ return __assign({ flightProfile: makeDeepCopy(flightProfile, false, true) }, SUCCESS);
38018
37979
  }
38019
- function candidateHash(candidate) {
38020
- return candidate.participantIdPairings
38021
- .map(function (_a) {
38022
- var participantIds = _a.participantIds;
38023
- return participantIds.sort().join('|');
38024
- })
38025
- .sort()
38026
- .join('/');
38027
- }
38028
- function roundCandidate(_a) {
38029
- var valueSortedPairings = _a.valueSortedPairings, _b = _a.stipulated, stipulated = _b === void 0 ? [] : _b, pairingValueMap = _a.pairingValueMap, deltaObjects = _a.deltaObjects, valueObjects = _a.valueObjects, actorsCount = _a.actorsCount;
38030
- // roundPlayers starts with the stipulated pairing
38031
- var roundPlayers = [].concat.apply([], __spreadArray([], __read(stipulated), false));
38032
- // aggregates the pairings generated for a roundCandidate
38033
- var participantIdPairings = [];
38034
- // candidateValue is the sum of all participantIdPairings in a roundCandidate
38035
- // the winning candidate has the LOWEST total value
38036
- var candidateValue = 0;
38037
- // candidateValue is initialized with any stipulated pairings
38038
- stipulated.filter(Boolean).forEach(function (participantIds) {
38039
- var _a = __read(participantIds, 2), p1 = _a[0], p2 = _a[1];
38040
- var pairing = pairingHash(p1, p2);
38041
- var value = pairingValueMap[pairing];
38042
- participantIdPairings.push({ participantIds: participantIds, value: value });
38043
- candidateValue += pairingValueMap[pairing];
38044
- });
38045
- // valueSortedPairings is an array sorted from lowest value to highest value
38046
- // introduce random shuffling of chunks of valueSortedPairings
38047
- var consideredPairings = chunkArray(valueSortedPairings, actorsCount)
38048
- .map(function (pairings) {
38049
- return shuffleArray(pairings).map(function (pairing) { return (__assign(__assign({}, pairing), { value: pairing.value + Math.random() * Math.round(Math.random()) })); });
38050
- })
38051
- .flat();
38052
- // go through the valueSortedPairings (of all possible unique pairings)
38053
- consideredPairings.forEach(function (rankedPairing) {
38054
- var participantIds = rankedPairing.pairing.split('|');
38055
- var opponentExists = participantIds.reduce(function (p, c) { return roundPlayers.includes(c) || p; }, false);
38056
- if (!opponentExists) {
38057
- roundPlayers.push.apply(roundPlayers, __spreadArray([], __read(participantIds), false));
38058
- var value = rankedPairing.value;
38059
- candidateValue += value;
38060
- participantIdPairings.push({ participantIds: participantIds, value: value });
37980
+
37981
+ /**
37982
+ *
37983
+ * @param {object} tournamentRecord - passed automatically if tournamentEngine.setState()
37984
+ * @param {string[]} participantIds
37985
+ * @param {string} scaleAttributes - { scaleType, scaleName, eventType }
37986
+ * @returns {boolean} { success: true } or { error }
37987
+ */
37988
+ function removeParticipantsScaleItems(_a) {
37989
+ var _b;
37990
+ var tournamentRecord = _a.tournamentRecord, scaleAttributes = _a.scaleAttributes, participantIds = _a.participantIds;
37991
+ if (!tournamentRecord)
37992
+ return { error: MISSING_TOURNAMENT_RECORD };
37993
+ if (!participantIds)
37994
+ return { error: MISSING_PARTICIPANT_IDS };
37995
+ if (!scaleAttributes)
37996
+ return { error: MISSING_VALUE, info: 'scaleAttributes required' };
37997
+ var scaleType = scaleAttributes.scaleType, eventType = scaleAttributes.eventType, scaleName = scaleAttributes.scaleName;
37998
+ var itemType = [SCALE, scaleType, eventType, scaleName].join('.');
37999
+ (_b = tournamentRecord.participants) === null || _b === void 0 ? void 0 : _b.forEach(function (participant) {
38000
+ if (participantIds.includes(participant.participantId) &&
38001
+ participant.timeItems) {
38002
+ participant.timeItems = participant.timeItems.filter(function (timeItem) {
38003
+ return timeItem && (timeItem === null || timeItem === void 0 ? void 0 : timeItem.itemType) !== itemType;
38004
+ });
38061
38005
  }
38062
38006
  });
38063
- // sort the candidate's proposed pairings by value
38064
- participantIdPairings.sort(function (a, b) { return a.value - b.value; });
38065
- // determine the greatest delta in the candidate's pairings
38066
- var maxDelta = participantIdPairings.reduce(function (p, c) {
38067
- var _a = __read(c.participantIds, 2), p1 = _a[0], p2 = _a[1];
38068
- var hash = pairingHash(p1, p2);
38069
- var delta = deltaObjects[hash];
38070
- return delta > p ? delta : p;
38071
- }, 0);
38072
- // determine the greatest delta in the candidate's pairings
38073
- var maxDiff = participantIdPairings.reduce(function (p, c) {
38074
- var _a = __read(c.participantIds, 2), p1 = _a[0], p2 = _a[1];
38075
- var hash = pairingHash(p1, p2);
38076
- var diff = valueObjects[hash];
38077
- return diff > p ? diff : p;
38078
- }, 0);
38079
- return { value: candidateValue, participantIdPairings: participantIdPairings, maxDelta: maxDelta, maxDiff: maxDiff };
38080
- }
38081
- function pairingHash(id1, id2) {
38082
- return [id1, id2].sort(stringSort).join('|');
38007
+ return __assign({}, SUCCESS);
38083
38008
  }
38084
38009
 
38085
- function getPairingsData(_a) {
38086
- var participantIds = _a.participantIds;
38087
- var possiblePairings = {};
38088
- var uniquePairings = [];
38089
- participantIds.forEach(function (participantId) {
38090
- possiblePairings[participantId] = participantIds.filter(function (id) { return id !== participantId; });
38091
- possiblePairings[participantId].forEach(function (id) {
38092
- var pairing = pairingHash(id, participantId);
38093
- if (!uniquePairings.includes(pairing))
38094
- uniquePairings.push(pairing);
38010
+ /**
38011
+ *
38012
+ * @param {object} tournamentRecord - passed automatically if tournamentEngine.setState()
38013
+ * @param {string} eventId - resolves to event
38014
+ * @param {string} drawId - OPTIONAL - resolves drawDefinition - scopes participants to clear to drawDefinition.entries or flightProfile.flight.drawEntries
38015
+ * @param {string} scaleAttributes - { scaleType, scaleName, eventType }
38016
+ * @param {string} stage - OPTIONAL - filter event or draw entries by stage
38017
+ * @returns {boolean} { success: true } or { error }
38018
+ */
38019
+ function removeScaleValues(_a) {
38020
+ var _b;
38021
+ var tournamentRecord = _a.tournamentRecord, scaleAttributes = _a.scaleAttributes, drawDefinition = _a.drawDefinition, entryStatuses = _a.entryStatuses, drawId = _a.drawId, event = _a.event, stage = _a.stage;
38022
+ if (!event)
38023
+ return { error: MISSING_EVENT };
38024
+ if (entryStatuses && !Array.isArray(entryStatuses))
38025
+ return decorateResult({
38026
+ result: { error: INVALID_VALUES },
38027
+ info: mustBeAnArray('entryStatus'),
38028
+ stack: 'removeScaleValues',
38095
38029
  });
38030
+ var entries = event.entries;
38031
+ if (drawId) {
38032
+ var flightProfile = getFlightProfile({ event: event }).flightProfile;
38033
+ var flight = (_b = flightProfile === null || flightProfile === void 0 ? void 0 : flightProfile.flights) === null || _b === void 0 ? void 0 : _b.find(function (flight) { return flight.drawId === drawId; });
38034
+ if (flight) {
38035
+ entries = flight.drawEntries;
38036
+ }
38037
+ else {
38038
+ entries = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.entries;
38039
+ }
38040
+ }
38041
+ var stageEntries = (entries || []).filter(function (entry) {
38042
+ return (!stage || !entry.entryStage || entry.entryStage === stage) &&
38043
+ (!entryStatuses || entryStatuses.includes(entry.entryStatus));
38044
+ });
38045
+ var participantIds = stageEntries.map(getParticipantId);
38046
+ return removeParticipantsScaleItems({
38047
+ tournamentRecord: tournamentRecord,
38048
+ scaleAttributes: scaleAttributes,
38049
+ participantIds: participantIds,
38096
38050
  });
38097
- var deltaObjects = Object.assign.apply(Object, __spreadArray([{}], __read(uniquePairings.map(function (pairing) {
38098
- var _a;
38099
- return (_a = {}, _a[pairing] = 0, _a);
38100
- })), false));
38101
- return { uniquePairings: uniquePairings, possiblePairings: possiblePairings, deltaObjects: deltaObjects };
38102
38051
  }
38103
38052
 
38104
- function getEncounters(_a) {
38105
- var e_1, _b;
38106
- var matchUps = _a.matchUps;
38107
- var encounters = [];
38053
+ function applyLineUps(_a) {
38054
+ var e_1, _b, e_2, _c, e_3, _d, e_4, _e;
38055
+ var _f, _g, _h, _j;
38056
+ var tournamentRecord = _a.tournamentRecord, drawDefinition = _a.drawDefinition, matchUpId = _a.matchUpId, lineUps = _a.lineUps, event = _a.event;
38057
+ if (!tournamentRecord)
38058
+ return { error: MISSING_TOURNAMENT_RECORD };
38059
+ if (!drawDefinition)
38060
+ return { error: DRAW_DEFINITION_NOT_FOUND };
38061
+ if (typeof matchUpId !== 'string')
38062
+ return { error: INVALID_MATCHUP };
38063
+ if (!Array.isArray(lineUps))
38064
+ return { error: INVALID_VALUES, lineUps: lineUps };
38065
+ var stack = 'applyLineUps';
38066
+ var tournamentParticipants = tournamentRecord.participants || [];
38067
+ var result = findDrawMatchUp({
38068
+ tournamentParticipants: tournamentParticipants,
38069
+ inContext: true,
38070
+ drawDefinition: drawDefinition,
38071
+ matchUpId: matchUpId,
38072
+ });
38073
+ if (result.error)
38074
+ return result;
38075
+ if (!result.matchUp)
38076
+ return { error: MATCHUP_NOT_FOUND };
38077
+ var inContextMatchUp = result.matchUp, structure = result.structure;
38078
+ var drawPositions = inContextMatchUp.drawPositions, matchUpType = inContextMatchUp.matchUpType;
38079
+ if (matchUpType !== TEAM$1)
38080
+ return { error: INVALID_MATCHUP };
38081
+ if (!(drawPositions === null || drawPositions === void 0 ? void 0 : drawPositions.length))
38082
+ return { error: MISSING_DRAW_POSITIONS };
38083
+ var tieFormat = (_f = resolveTieFormat({
38084
+ matchUp: inContextMatchUp,
38085
+ drawDefinition: drawDefinition,
38086
+ structure: structure,
38087
+ event: event,
38088
+ })) === null || _f === void 0 ? void 0 : _f.tieFormat;
38089
+ // verify integrity of lineUps...
38090
+ // 1. all participantIds must be valid individualParticipantIds
38091
+ // 2. there should be at most one participantId for a given collectionPosition in singles
38092
+ // 3. there should be at most two participantIds for a given collectionPosition in doubles
38093
+ var sideAssignments = {};
38108
38094
  try {
38109
- for (var matchUps_1 = __values(matchUps), matchUps_1_1 = matchUps_1.next(); !matchUps_1_1.done; matchUps_1_1 = matchUps_1.next()) {
38110
- var matchUp = matchUps_1_1.value;
38111
- var participantIds = matchUp.sides.map(extractAttributes('participantId'));
38112
- if (participantIds.length === 2) {
38113
- var _c = __read(participantIds, 2), p1 = _c[0], p2 = _c[1];
38114
- var pairing = pairingHash(p1, p2);
38115
- if (!encounters.includes(pairing))
38116
- encounters.push(pairing);
38095
+ for (var lineUps_1 = __values(lineUps), lineUps_1_1 = lineUps_1.next(); !lineUps_1_1.done; lineUps_1_1 = lineUps_1.next()) {
38096
+ var lineUp = lineUps_1_1.value;
38097
+ if (!Array.isArray(lineUp))
38098
+ return { error: INVALID_VALUES, lineUp: lineUp };
38099
+ // maintain mapping of collectionId|collectionPosition to the participantIds assigned
38100
+ var collectionParticipantIds = {};
38101
+ var sideNumbers = [];
38102
+ var _loop_1 = function (lineUpAssignment) {
38103
+ var e_5, _m;
38104
+ if (typeof lineUpAssignment !== 'object')
38105
+ return { value: { error: INVALID_VALUES, lineUpAssignment: lineUpAssignment } };
38106
+ var participantId = lineUpAssignment.participantId, _o = lineUpAssignment.collectionAssignments, collectionAssignments = _o === void 0 ? [] : _o;
38107
+ if (!Array.isArray(collectionAssignments))
38108
+ return { value: { error: INVALID_VALUES, collectionAssignments: collectionAssignments } };
38109
+ var participant = tournamentParticipants.find(function (participant) { return participant.participantId === participantId; });
38110
+ if (!participant)
38111
+ return { value: { error: PARTICIPANT_NOT_FOUND } };
38112
+ if (participant.participantType !== INDIVIDUAL)
38113
+ return { value: { error: INVALID_PARTICIPANT_TYPE } };
38114
+ var sideNumber_1 = (_h = (_g = inContextMatchUp.sides) === null || _g === void 0 ? void 0 : _g.find(function (side) { var _a, _b; return (_b = (_a = side.participant) === null || _a === void 0 ? void 0 : _a.individualParticipantIds) === null || _b === void 0 ? void 0 : _b.includes(participantId); })) === null || _h === void 0 ? void 0 : _h.sideNumber;
38115
+ if (sideNumber_1)
38116
+ sideNumbers.push(sideNumber_1);
38117
+ var _loop_3 = function (collectionAssignment) {
38118
+ if (typeof collectionAssignment !== 'object')
38119
+ return { value: { error: INVALID_VALUES, collectionAssignment: collectionAssignment } };
38120
+ var collectionId = collectionAssignment.collectionId, collectionPosition = collectionAssignment.collectionPosition;
38121
+ var collectionDefinition = (_j = tieFormat === null || tieFormat === void 0 ? void 0 : tieFormat.collectionDefinitions) === null || _j === void 0 ? void 0 : _j.find(function (collectionDefinition) {
38122
+ return collectionDefinition.collectionId === collectionId;
38123
+ });
38124
+ // all collectionIds in the lineUp must be present in the tieFormat collectionDefinitions
38125
+ if (!collectionDefinition)
38126
+ return { value: { error: INVALID_VALUES, collectionId: collectionId } };
38127
+ var aggregator = "".concat(collectionId, "-").concat(collectionPosition);
38128
+ if (!collectionParticipantIds[aggregator]) {
38129
+ collectionParticipantIds[aggregator] = [];
38130
+ }
38131
+ var participantsCount = collectionParticipantIds[aggregator].length;
38132
+ if ((collectionDefinition.matchUpType === SINGLES && participantsCount) ||
38133
+ (collectionDefinition.matchUpType === DOUBLES &&
38134
+ participantsCount > 1)) {
38135
+ return { value: {
38136
+ info: 'Excessive collectionPosition assignments',
38137
+ error: INVALID_VALUES,
38138
+ } };
38139
+ }
38140
+ collectionParticipantIds[aggregator].push(participantId);
38141
+ };
38142
+ try {
38143
+ for (var collectionAssignments_1 = (e_5 = void 0, __values(collectionAssignments)), collectionAssignments_1_1 = collectionAssignments_1.next(); !collectionAssignments_1_1.done; collectionAssignments_1_1 = collectionAssignments_1.next()) {
38144
+ var collectionAssignment = collectionAssignments_1_1.value;
38145
+ var state_2 = _loop_3(collectionAssignment);
38146
+ if (typeof state_2 === "object")
38147
+ return state_2;
38148
+ }
38149
+ }
38150
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
38151
+ finally {
38152
+ try {
38153
+ if (collectionAssignments_1_1 && !collectionAssignments_1_1.done && (_m = collectionAssignments_1.return)) _m.call(collectionAssignments_1);
38154
+ }
38155
+ finally { if (e_5) throw e_5.error; }
38156
+ }
38157
+ };
38158
+ try {
38159
+ for (var lineUp_1 = (e_2 = void 0, __values(lineUp)), lineUp_1_1 = lineUp_1.next(); !lineUp_1_1.done; lineUp_1_1 = lineUp_1.next()) {
38160
+ var lineUpAssignment = lineUp_1_1.value;
38161
+ var state_1 = _loop_1(lineUpAssignment);
38162
+ if (typeof state_1 === "object")
38163
+ return state_1.value;
38164
+ }
38165
+ }
38166
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
38167
+ finally {
38168
+ try {
38169
+ if (lineUp_1_1 && !lineUp_1_1.done && (_c = lineUp_1.return)) _c.call(lineUp_1);
38170
+ }
38171
+ finally { if (e_2) throw e_2.error; }
38172
+ }
38173
+ // ensure that doubles pair participants exist, otherwise create
38174
+ var collectionParticipantIdPairs = Object.values(collectionParticipantIds);
38175
+ try {
38176
+ for (var collectionParticipantIdPairs_1 = (e_3 = void 0, __values(collectionParticipantIdPairs)), collectionParticipantIdPairs_1_1 = collectionParticipantIdPairs_1.next(); !collectionParticipantIdPairs_1_1.done; collectionParticipantIdPairs_1_1 = collectionParticipantIdPairs_1.next()) {
38177
+ var participantIds = collectionParticipantIdPairs_1_1.value;
38178
+ if (participantIds.length === 2) {
38179
+ var pairedParticipant = getPairedParticipant({
38180
+ tournamentParticipants: tournamentParticipants,
38181
+ participantIds: participantIds,
38182
+ }).participant;
38183
+ if (!pairedParticipant) {
38184
+ // create pair participant
38185
+ var newPairParticipant = {
38186
+ participantType: PAIR,
38187
+ participantRole: COMPETITOR,
38188
+ individualParticipantIds: participantIds,
38189
+ };
38190
+ var result_1 = addParticipant({
38191
+ participant: newPairParticipant,
38192
+ pairOverride: true,
38193
+ tournamentRecord: tournamentRecord,
38194
+ });
38195
+ if (result_1.error)
38196
+ return result_1;
38197
+ }
38198
+ }
38199
+ }
38200
+ }
38201
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
38202
+ finally {
38203
+ try {
38204
+ if (collectionParticipantIdPairs_1_1 && !collectionParticipantIdPairs_1_1.done && (_d = collectionParticipantIdPairs_1.return)) _d.call(collectionParticipantIdPairs_1);
38205
+ }
38206
+ finally { if (e_3) throw e_3.error; }
38207
+ }
38208
+ // determine sideNumber based on instances of participants appearing in team participants assigned to sides
38209
+ // allows for some team members to be "borrowed"
38210
+ var instances = instanceCount(sideNumbers);
38211
+ var sideNumber = ((instances[1] || 0) > (instances[2] || 0) && 1) ||
38212
+ ((instances[2] || 0) > (instances[1] || 0) && 2) ||
38213
+ undefined;
38214
+ // if side not previously assigned, map sideNumber to lineUp
38215
+ var sideAssignmentKeys = Object.keys(sideAssignments).map(function (key) {
38216
+ return parseInt(key);
38217
+ });
38218
+ if (sideNumber && !sideAssignmentKeys.includes(sideNumber)) {
38219
+ sideAssignments[sideNumber] = lineUp;
38117
38220
  }
38118
38221
  }
38119
38222
  }
38120
38223
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
38121
38224
  finally {
38122
38225
  try {
38123
- if (matchUps_1_1 && !matchUps_1_1.done && (_b = matchUps_1.return)) _b.call(matchUps_1);
38226
+ if (lineUps_1_1 && !lineUps_1_1.done && (_b = lineUps_1.return)) _b.call(lineUps_1);
38124
38227
  }
38125
38228
  finally { if (e_1) throw e_1.error; }
38126
38229
  }
38127
- return { encounters: encounters };
38128
- }
38129
-
38130
- function getParticipantPairingValues(_a) {
38131
- var e_1, _b;
38132
- var possiblePairings = _a.possiblePairings, valueObjects = _a.valueObjects;
38133
- var pairingValues = {};
38134
- var _loop_1 = function (participantId) {
38135
- var participantValues = possiblePairings[participantId].map(function (opponent) {
38136
- return pairingValue(participantId, opponent);
38137
- });
38138
- pairingValues[participantId] = participantValues.sort(function (a, b) { return a.value - b.value; });
38230
+ if (!Object.keys(sideAssignments).length)
38231
+ return { error: VALUE_UNCHANGED };
38232
+ result = findDrawMatchUp({ drawDefinition: drawDefinition, matchUpId: matchUpId });
38233
+ if (result.error)
38234
+ return result;
38235
+ if (!result.matchUp)
38236
+ return { error: MATCHUP_NOT_FOUND };
38237
+ var matchUp = result.matchUp;
38238
+ if (!matchUp.sides)
38239
+ matchUp.sides = [];
38240
+ var _loop_2 = function (sideNumber) {
38241
+ var side = matchUp.sides.find(function (side) { return side.sideNumber === sideNumber; });
38242
+ var assignment = sideAssignments[sideNumber];
38243
+ if (!assignment) {
38244
+ return "continue";
38245
+ }
38246
+ else if (!side) {
38247
+ matchUp.sides.push({ lineUp: assignment, sideNumber: sideNumber });
38248
+ }
38249
+ else {
38250
+ side.lineUp = assignment;
38251
+ }
38139
38252
  };
38140
38253
  try {
38141
- for (var _c = __values(Object.keys(possiblePairings)), _d = _c.next(); !_d.done; _d = _c.next()) {
38142
- var participantId = _d.value;
38143
- _loop_1(participantId);
38254
+ for (var _k = __values([1, 2]), _l = _k.next(); !_l.done; _l = _k.next()) {
38255
+ var sideNumber = _l.value;
38256
+ _loop_2(sideNumber);
38144
38257
  }
38145
38258
  }
38146
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
38259
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
38147
38260
  finally {
38148
38261
  try {
38149
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
38262
+ if (_l && !_l.done && (_e = _k.return)) _e.call(_k);
38150
38263
  }
38151
- finally { if (e_1) throw e_1.error; }
38152
- }
38153
- function pairingValue(participantId, opponent) {
38154
- var key = pairingHash(participantId, opponent);
38155
- return { opponent: opponent, value: valueObjects[key] };
38264
+ finally { if (e_4) throw e_4.error; }
38156
38265
  }
38157
- return { pairingValues: pairingValues };
38158
- }
38159
-
38160
- var ELO = 'ELO';
38161
- var NTRP = 'NTRP';
38162
- var TRN = 'TRN';
38163
- var UTR = 'UTR';
38164
- var WTN = 'WTN';
38165
- var ratingConstants = {
38166
- ELO: ELO,
38167
- NTRP: NTRP,
38168
- TRN: TRN,
38169
- UTR: UTR,
38170
- WTN: WTN,
38171
- };
38172
-
38173
- var _a$e;
38174
- var ratingsParameters = (_a$e = {},
38175
- _a$e[ELO] = {
38176
- defaultInitialization: 1500,
38177
- decimalsCount: 0,
38178
- range: [0, 3000],
38179
- ascending: true,
38180
- },
38181
- _a$e[NTRP] = {
38182
- accessors: ['ntrpRating', 'dntrpRatingHundredths'],
38183
- attributes: { ustaRatingType: '' },
38184
- accessor: 'dntrpRatingHundredths',
38185
- defaultInitialization: 3,
38186
- decimalsCount: 1,
38187
- ascending: true,
38188
- range: [1, 7],
38189
- },
38190
- _a$e[UTR] = {
38191
- defaultInitialization: 6,
38192
- accessors: ['utrRating'],
38193
- accessor: 'utrRating',
38194
- decimalsCount: 2,
38195
- ascending: true,
38196
- range: [1, 16],
38197
- },
38198
- _a$e[WTN] = {
38199
- attributes: { confidence: { generator: true, range: [60, 100] } },
38200
- accessors: ['wtnRating', 'confidence'],
38201
- defaultInitialization: 23,
38202
- accessor: 'wtnRating',
38203
- ascending: false,
38204
- decimalsCount: 2,
38205
- range: [40, 1],
38206
- },
38207
- _a$e);
38208
-
38209
- var DEFAULT_RATING = 0;
38210
- function getSideRatings(_a) {
38211
- var _b, _c;
38212
- var tournamentParticipants = _a.tournamentParticipants, adHocRatings = _a.adHocRatings, eventType = _a.eventType, scaleName = _a.scaleName, pairing = _a.pairing;
38213
- var defaultRating = (_c = (_b = ratingsParameters[scaleName]) === null || _b === void 0 ? void 0 : _b.defaultInitialization) !== null && _c !== void 0 ? _c : DEFAULT_RATING;
38214
- return pairing.split('|').map(function (participantId) {
38215
- var _a;
38216
- if (eventType === DOUBLES$1) {
38217
- var individualParticipantIds = (_a = tournamentParticipants === null || tournamentParticipants === void 0 ? void 0 : tournamentParticipants.find(function (participant) { return participant.participantId === participantId; })) === null || _a === void 0 ? void 0 : _a.individualParticipantIds;
38218
- return !individualParticipantIds
38219
- ? defaultRating * 2
38220
- : individualParticipantIds === null || individualParticipantIds === void 0 ? void 0 : individualParticipantIds.map(function (participantId) { return adHocRatings[participantId] || defaultRating; });
38221
- }
38222
- else {
38223
- return adHocRatings[participantId] || defaultRating;
38224
- }
38266
+ modifyMatchUpNotice({
38267
+ tournamentId: tournamentRecord === null || tournamentRecord === void 0 ? void 0 : tournamentRecord.tournamentId,
38268
+ context: stack,
38269
+ drawDefinition: drawDefinition,
38270
+ matchUp: matchUp,
38225
38271
  });
38272
+ return __assign({}, SUCCESS);
38226
38273
  }
38227
38274
 
38228
- function getPairings(_a) {
38229
- var tournamentParticipants = _a.tournamentParticipants, _b = _a.adHocRatings, adHocRatings = _b === void 0 ? {} : _b, possiblePairings = _a.possiblePairings, // participant keyed; provides array of possible opponents
38230
- uniquePairings = _a.uniquePairings, // hashes of all possible participantId pairings
38231
- maxIterations = _a.maxIterations, deltaObjects = _a.deltaObjects, // difference in rating between paired participants
38232
- valueObjects = _a.valueObjects, // calculated value of a pairing of participants, used for sorting pairings
38233
- eventType = _a.eventType, scaleName = _a.scaleName, salted = _a.salted;
38234
- // modify valueObjects by ratings ratingsDifference squared
38235
- // update deltaObjects to reflect the current difference between participant's ratings
38236
- uniquePairings.forEach(function (pairing) {
38237
- var ratings = getSideRatings({
38238
- tournamentParticipants: tournamentParticipants,
38239
- adHocRatings: adHocRatings,
38240
- scaleName: scaleName,
38241
- eventType: eventType,
38242
- pairing: pairing,
38275
+ function resetTieFormat(params) {
38276
+ var _a, _b, e_1, _c, e_2, _d;
38277
+ var _e, _f, _g;
38278
+ var stack = 'resetTieFormat';
38279
+ var drawDefinition = params.drawDefinition, event = params.event, uuids = params.uuids;
38280
+ var paramCheck = checkRequiredParameters(params, [(_a = {}, _a[TOURNAMENT_RECORD] = true, _a[MATCHUP_ID] = true, _a)], stack);
38281
+ if (paramCheck.error)
38282
+ return paramCheck;
38283
+ var resolutions = resolveFromParameters(params, [(_b = {}, _b[PARAM] = MATCHUP, _b)]);
38284
+ if (resolutions[ERROR])
38285
+ return resolutions;
38286
+ var tournamentId = (_e = params.tournamentRecord) === null || _e === void 0 ? void 0 : _e.tournamentId;
38287
+ var _h = (_f = resolutions === null || resolutions === void 0 ? void 0 : resolutions.matchUp) !== null && _f !== void 0 ? _f : {}, matchUp = _h.matchUp, structure = _h.structure;
38288
+ if (!(matchUp === null || matchUp === void 0 ? void 0 : matchUp.tieMatchUps))
38289
+ return decorateResult({
38290
+ result: { error: INVALID_MATCHUP },
38291
+ info: 'Must be a TEAM matchUp',
38292
+ stack: stack,
38243
38293
  });
38244
- var salting = (typeof salted === 'number' && salted) || 0.5;
38245
- var salt = (salted && (Math.round(Math.random()) ? salting : salting * -1)) || 0;
38246
- var ratingsDifference = Math.abs(ratings[0] - ratings[1]) + salt;
38247
- var pairingDelta = Math.abs(ratings[0] - ratings[1]);
38248
- deltaObjects[pairing] = pairingDelta;
38249
- if (!valueObjects[pairing])
38250
- valueObjects[pairing] = 0;
38251
- valueObjects[pairing] += ratingsDifference
38252
- ? Math.pow(ratingsDifference, 2)
38253
- : 0;
38254
- });
38255
- /**
38256
- * valueSortedPairings are uniquePairings sorted by the ratings difference of the pairings, lowest to highest
38257
- */
38258
- var valueSortedPairings = uniquePairings
38259
- .map(function (pairing) { return ({ pairing: pairing, value: valueObjects[pairing] }); })
38260
- .sort(function (a, b) { return a.value - b.value; });
38261
- /**
38262
- * pairingValues is keyed by participantId and provides a value-sorted array of pairings for each participantId
38263
- * 'actorId': [
38264
- { opponent: 'potentialId1', value: 1 },
38265
- { opponent: 'potentialId2', value: 1 },
38266
- */
38267
- var pairingValues = getParticipantPairingValues({
38268
- possiblePairings: possiblePairings,
38269
- valueObjects: valueObjects,
38270
- }).pairingValues;
38271
- var _c = generateCandidate({
38272
- valueSortedPairings: valueSortedPairings,
38273
- maxIterations: maxIterations,
38274
- pairingValues: pairingValues,
38275
- deltaObjects: deltaObjects,
38276
- valueObjects: valueObjects,
38277
- }), candidate = _c.candidate, candidatesCount = _c.candidatesCount, deltaCandidate = _c.deltaCandidate, iterations = _c.iterations;
38278
- var participantIdPairings = candidate.participantIdPairings;
38279
- return {
38280
- participantIdPairings: participantIdPairings,
38281
- candidatesCount: candidatesCount,
38282
- deltaCandidate: deltaCandidate,
38283
- iterations: iterations,
38284
- candidate: candidate,
38294
+ // if there is no tieFormat there is nothing to do
38295
+ if (!matchUp.tieFormat)
38296
+ return __assign({}, SUCCESS);
38297
+ var tieFormat = (_g = resolveTieFormat({
38298
+ structure: structure,
38299
+ drawDefinition: drawDefinition,
38300
+ event: event,
38301
+ })) === null || _g === void 0 ? void 0 : _g.tieFormat;
38302
+ if (!tieFormat)
38303
+ return decorateResult({
38304
+ result: { error: NOT_FOUND },
38305
+ info: 'No inherited tieFormat',
38306
+ stack: stack,
38307
+ });
38308
+ var deletedMatchUpIds = [];
38309
+ var collectionIds = [];
38310
+ var tieMatchUps = [];
38311
+ var newMatchUps = [];
38312
+ var _loop_1 = function (collectionDefinition) {
38313
+ // delete any matchUp.tieMatchUps that are not found in the ancestor tieFormat collectionDefinitions
38314
+ var matchUpCount = collectionDefinition.matchUpCount, collectionId = collectionDefinition.collectionId;
38315
+ collectionIds.push(collectionId);
38316
+ var existingCollectionMatchUps = (matchUp.tieMatchUps || []).filter(function (matchUp) { return matchUp.collectionId === collectionId; });
38317
+ if (existingCollectionMatchUps.length > matchUpCount) {
38318
+ // sort by matchUpStatus to prioritize active or completed matchUpsA
38319
+ existingCollectionMatchUps.sort(function (a, b) {
38320
+ return (a.matchUpStatus === TO_BE_PLAYED ? 1 : 0) -
38321
+ (b.matchUpStatus === TO_BE_PLAYED ? 1 : 0);
38322
+ });
38323
+ tieMatchUps.push.apply(tieMatchUps, __spreadArray([], __read(existingCollectionMatchUps.slice(0, matchUpCount)), false));
38324
+ deletedMatchUpIds.push.apply(deletedMatchUpIds, __spreadArray([], __read(existingCollectionMatchUps.slice(3).map(getMatchUpId)), false));
38325
+ }
38326
+ else {
38327
+ tieMatchUps.push.apply(tieMatchUps, __spreadArray([], __read(existingCollectionMatchUps), false));
38328
+ if (existingCollectionMatchUps.length < matchUpCount) {
38329
+ var matchUpsLimit = matchUpCount - existingCollectionMatchUps.length;
38330
+ var matchUps = generateCollectionMatchUps({
38331
+ collectionDefinition: collectionDefinition,
38332
+ matchUpsLimit: matchUpsLimit,
38333
+ uuids: uuids,
38334
+ });
38335
+ newMatchUps.push.apply(newMatchUps, __spreadArray([], __read(matchUps), false));
38336
+ }
38337
+ }
38285
38338
  };
38286
- }
38287
-
38288
- // this should be in policyDefinitions
38289
- var ENCOUNTER_VALUE = 100;
38290
- var SAME_TEAM_VALUE = 100;
38291
- var MAX_ITERATIONS = 4000;
38292
- function generateDrawMaticRound(_a) {
38293
- var e_1, _b, e_2, _c, e_3, _d;
38294
- var _e, _f;
38295
- var _g = _a.encounterValue, encounterValue = _g === void 0 ? ENCOUNTER_VALUE : _g, _h = _a.sameTeamValue, sameTeamValue = _h === void 0 ? SAME_TEAM_VALUE : _h, _j = _a.maxIterations, maxIterations = _j === void 0 ? MAX_ITERATIONS : _j, _k = _a.generateMatchUps, generateMatchUps = _k === void 0 ? true : _k, tournamentParticipants = _a.tournamentParticipants, participantIds = _a.participantIds, drawDefinition = _a.drawDefinition, adHocRatings = _a.adHocRatings, structureId = _a.structureId, _l = _a.salted, salted = _l === void 0 ? 0.5 : _l, matchUpIds = _a.matchUpIds, eventType = _a.eventType, structure = _a.structure, scaleName = _a.scaleName;
38296
- if (!drawDefinition)
38297
- return { error: MISSING_DRAW_DEFINITION };
38298
- if (!structure && !structureId)
38299
- return { error: STRUCTURE_NOT_FOUND };
38300
- if (!structure) {
38301
- structure = findStructure({ drawDefinition: drawDefinition, structureId: structureId }).structure;
38302
- }
38303
- if (!isObject(structure))
38304
- return { error: MISSING_STRUCTURE };
38305
- if (!(participantIds === null || participantIds === void 0 ? void 0 : participantIds.length)) {
38306
- return { error: MISSING_PARTICIPANT_IDS };
38307
- }
38308
- // create valueObject for each previous encounter within the structure
38309
- var encounters = getEncounters({ matchUps: (_e = structure === null || structure === void 0 ? void 0 : structure.matchUps) !== null && _e !== void 0 ? _e : [] }).encounters;
38310
- // valueObjects provide "weighting" to each possible pairing of participants
38311
- // {
38312
- // 'P-I-0|P-I-1': 1,
38313
- // 'P-I-0|P-I-2': 1,
38314
- // 'P-I-0|P-I-3': 1
38315
- // }
38316
- var valueObjects = {};
38317
38339
  try {
38318
- for (var encounters_1 = __values(encounters), encounters_1_1 = encounters_1.next(); !encounters_1_1.done; encounters_1_1 = encounters_1.next()) {
38319
- var pairing = encounters_1_1.value;
38320
- if (!valueObjects[pairing])
38321
- valueObjects[pairing] = 0;
38322
- valueObjects[pairing] += encounterValue;
38340
+ for (var _j = __values(tieFormat.collectionDefinitions), _k = _j.next(); !_k.done; _k = _j.next()) {
38341
+ var collectionDefinition = _k.value;
38342
+ _loop_1(collectionDefinition);
38323
38343
  }
38324
38344
  }
38325
38345
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
38326
38346
  finally {
38327
38347
  try {
38328
- if (encounters_1_1 && !encounters_1_1.done && (_b = encounters_1.return)) _b.call(encounters_1);
38348
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
38329
38349
  }
38330
38350
  finally { if (e_1) throw e_1.error; }
38331
38351
  }
38332
- var teamParticipants = tournamentParticipants === null || tournamentParticipants === void 0 ? void 0 : tournamentParticipants.filter(function (_a) {
38333
- var participantType = _a.participantType;
38334
- return participantType === TEAM;
38335
- });
38336
- if (teamParticipants) {
38337
- try {
38338
- // add SAME_TEAM_VALUE for participants who appear on the same team
38339
- for (var teamParticipants_1 = __values(teamParticipants), teamParticipants_1_1 = teamParticipants_1.next(); !teamParticipants_1_1.done; teamParticipants_1_1 = teamParticipants_1.next()) {
38340
- var teamParticipant = teamParticipants_1_1.value;
38341
- var participantIds_1 = (_f = teamParticipant.individualParticipantIds) !== null && _f !== void 0 ? _f : [];
38342
- var uniquePairings_2 = getPairingsData({ participantIds: participantIds_1 }).uniquePairings;
38343
- try {
38344
- for (var uniquePairings_1 = (e_3 = void 0, __values(uniquePairings_2)), uniquePairings_1_1 = uniquePairings_1.next(); !uniquePairings_1_1.done; uniquePairings_1_1 = uniquePairings_1.next()) {
38345
- var pairing = uniquePairings_1_1.value;
38346
- if (!valueObjects[pairing])
38347
- valueObjects[pairing] = 0;
38348
- valueObjects[pairing] += sameTeamValue;
38349
- }
38350
- }
38351
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
38352
- finally {
38353
- try {
38354
- if (uniquePairings_1_1 && !uniquePairings_1_1.done && (_d = uniquePairings_1.return)) _d.call(uniquePairings_1);
38355
- }
38356
- finally { if (e_3) throw e_3.error; }
38357
- }
38358
- }
38352
+ try {
38353
+ for (var _l = __values((matchUp === null || matchUp === void 0 ? void 0 : matchUp.tieMatchUps) || []), _m = _l.next(); !_m.done; _m = _l.next()) {
38354
+ var tieMatchUp = _m.value;
38355
+ if (tieMatchUp.collectionId &&
38356
+ !collectionIds.includes(tieMatchUp.collectionId))
38357
+ deletedMatchUpIds.push(tieMatchUp.matchUpId);
38359
38358
  }
38360
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
38361
- finally {
38362
- try {
38363
- if (teamParticipants_1_1 && !teamParticipants_1_1.done && (_c = teamParticipants_1.return)) _c.call(teamParticipants_1);
38364
- }
38365
- finally { if (e_2) throw e_2.error; }
38359
+ }
38360
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
38361
+ finally {
38362
+ try {
38363
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
38366
38364
  }
38365
+ finally { if (e_2) throw e_2.error; }
38367
38366
  }
38368
- // deltaObjects contain the difference in ratings between two participants
38369
- // {
38370
- // 'P-I-0|P-I-1': 0,
38371
- // 'P-I-0|P-I-2': 0,
38372
- // 'P-I-0|P-I-3': 0
38373
- // }
38374
- var _m = getPairingsData({
38375
- participantIds: participantIds,
38376
- }), uniquePairings = _m.uniquePairings, possiblePairings = _m.possiblePairings, deltaObjects = _m.deltaObjects;
38377
- var params = {
38378
- tournamentParticipants: tournamentParticipants,
38379
- possiblePairings: possiblePairings,
38380
- drawDefinition: drawDefinition,
38381
- participantIds: participantIds,
38382
- uniquePairings: uniquePairings,
38383
- maxIterations: maxIterations,
38384
- adHocRatings: adHocRatings,
38385
- deltaObjects: deltaObjects,
38386
- valueObjects: valueObjects,
38387
- eventType: eventType,
38388
- scaleName: scaleName,
38389
- structure: structure,
38390
- salted: salted,
38391
- };
38392
- var _o = getPairings(params), candidatesCount = _o.candidatesCount, participantIdPairings = _o.participantIdPairings, iterations = _o.iterations, candidate = _o.candidate;
38393
- if (!candidatesCount)
38394
- return { error: NO_CANDIDATES };
38395
- var matchUps;
38396
- if (generateMatchUps) {
38397
- var result = generateAdHocMatchUps({
38367
+ if (newMatchUps.length) {
38368
+ tieMatchUps.push.apply(tieMatchUps, __spreadArray([], __read(newMatchUps), false));
38369
+ addMatchUpsNotice({
38370
+ eventId: event === null || event === void 0 ? void 0 : event.eventId,
38371
+ matchUps: newMatchUps,
38372
+ drawDefinition: drawDefinition,
38373
+ tournamentId: tournamentId,
38374
+ });
38375
+ }
38376
+ if (deletedMatchUpIds.length) {
38377
+ deleteMatchUpsNotice({
38378
+ matchUpIds: deletedMatchUpIds,
38379
+ eventId: event === null || event === void 0 ? void 0 : event.eventId,
38380
+ drawDefinition: drawDefinition,
38381
+ tournamentId: tournamentId,
38382
+ });
38383
+ }
38384
+ if (matchUp) {
38385
+ matchUp.tieMatchUps = tieMatchUps;
38386
+ matchUp.tieFormatId = undefined;
38387
+ matchUp.tieFormat = undefined;
38388
+ modifyMatchUpNotice({
38398
38389
  structureId: structure === null || structure === void 0 ? void 0 : structure.structureId,
38399
- participantIdPairings: participantIdPairings,
38400
- newRound: true,
38390
+ eventId: event === null || event === void 0 ? void 0 : event.eventId,
38391
+ context: stack,
38401
38392
  drawDefinition: drawDefinition,
38402
- matchUpIds: matchUpIds,
38393
+ tournamentId: tournamentId,
38394
+ matchUp: matchUp,
38403
38395
  });
38404
- if (result.error)
38405
- return result;
38406
- matchUps = result.matchUps;
38407
38396
  }
38408
- var maxDelta = candidate.maxDelta, maxDiff = candidate.maxDiff;
38409
- return __assign(__assign({}, SUCCESS), { participantIdPairings: participantIdPairings, candidatesCount: candidatesCount, iterations: iterations, matchUps: matchUps, maxDelta: maxDelta, maxDiff: maxDiff });
38397
+ return __assign(__assign({}, SUCCESS), { newMatchUps: newMatchUps, deletedMatchUpIds: deletedMatchUpIds });
38410
38398
  }
38411
38399
 
38412
- function drawMatic$1(_a) {
38413
- var e_1, _b;
38414
- var _c, _d, _e, _f, _g;
38415
- var tournamentParticipants = _a.tournamentParticipants, restrictEntryStatus = _a.restrictEntryStatus, _h = _a.adHocRatings, adHocRatings = _h === void 0 ? {} : _h, generateMatchUps = _a.generateMatchUps, tournamentRecord = _a.tournamentRecord, participantIds = _a.participantIds, encounterValue = _a.encounterValue, sameTeamValue = _a.sameTeamValue, drawDefinition = _a.drawDefinition, scaleAccessor = _a.scaleAccessor, maxIterations = _a.maxIterations, structureId = _a.structureId, matchUpIds = _a.matchUpIds, scaleName = _a.scaleName, // custom rating name to seed dynamic ratings
38416
- eventType = _a.eventType, salted = _a.salted, event = _a.event;
38417
- if (typeof drawDefinition !== 'object' ||
38418
- (drawDefinition.drawType && drawDefinition.drawType !== AD_HOC)) {
38419
- return { error: INVALID_DRAW_DEFINITION };
38420
- }
38421
- if (!Array.isArray(drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.entries) &&
38422
- participantIds &&
38423
- !Array.isArray(participantIds)) {
38424
- return { error: INVALID_VALUES, info: 'Missing Entries' };
38425
- }
38426
- eventType = eventType !== null && eventType !== void 0 ? eventType : event === null || event === void 0 ? void 0 : event.eventType;
38427
- var enteredParticipantIds = (_c = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.entries) === null || _c === void 0 ? void 0 : _c.filter(function (entry) {
38428
- var entryStatus = entry.entryStatus;
38429
- return (!restrictEntryStatus ||
38430
- STRUCTURE_SELECTED_STATUSES.includes(entryStatus));
38431
- }).map(getParticipantId);
38432
- if (participantIds) {
38433
- // ensure all participantIds are in drawDefinition.entries
38434
- var invalidParticipantIds = participantIds.filter(function (participantId) { return !(enteredParticipantIds === null || enteredParticipantIds === void 0 ? void 0 : enteredParticipantIds.includes(participantId)); });
38435
- if (invalidParticipantIds === null || invalidParticipantIds === void 0 ? void 0 : invalidParticipantIds.length)
38436
- return decorateResult({
38437
- result: { error: INVALID_PARTICIPANT_ID },
38438
- info: { invalidParticipantIds: invalidParticipantIds },
38439
- });
38440
- }
38441
- else {
38442
- participantIds = enteredParticipantIds;
38443
- }
38444
- // if no structureId is specified find the latest AD_HOC stage which has matchUps
38445
- if (!structureId) {
38446
- var targetStructure = (_e = (_d = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.structures) === null || _d === void 0 ? void 0 : _d.filter(function (structure) { return structure.stageSequence === 1; })) === null || _e === void 0 ? void 0 : _e.reduce(function (targetStructure, structure) {
38447
- var orderNumber = structure.stage && stageOrder$1[structure.stage];
38448
- var structureIsAdHoc = isAdHoc({ drawDefinition: drawDefinition, structure: structure });
38449
- return structureIsAdHoc &&
38450
- orderNumber > (stageOrder$1[targetStructure === null || targetStructure === void 0 ? void 0 : targetStructure.stage] || 1)
38451
- ? structure
38452
- : targetStructure;
38453
- }, undefined);
38454
- structureId = targetStructure === null || targetStructure === void 0 ? void 0 : targetStructure.structureId;
38455
- }
38456
- var structure = (_f = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.structures) === null || _f === void 0 ? void 0 : _f.find(function (structure) { return structure.structureId === structureId; });
38457
- if (!structure)
38458
- return { error: STRUCTURE_NOT_FOUND };
38459
- // an AD_HOC structure is one that has no child structures and in which no matchUps have roundPosition
38460
- var structureIsAdHoc = isAdHoc({ drawDefinition: drawDefinition, structure: structure });
38461
- if (!structureIsAdHoc)
38462
- return { error: INVALID_DRAW_DEFINITION };
38463
- tournamentParticipants =
38464
- (_g = tournamentParticipants !== null && tournamentParticipants !== void 0 ? tournamentParticipants : tournamentRecord.participants) !== null && _g !== void 0 ? _g : [];
38465
- var _loop_1 = function (participantId) {
38466
- var participant = tournamentParticipants === null || tournamentParticipants === void 0 ? void 0 : tournamentParticipants.find(function (participant) { return participant.participantId === participantId; });
38467
- // first see if there is already a dynamic value
38468
- var scaleValue = getScaleValue({
38469
- scaleName: "".concat(scaleName, ".").concat(DYNAMIC),
38470
- scaleAccessor: scaleAccessor,
38471
- participant: participant,
38472
- eventType: eventType,
38400
+ function resetScorecard(params) {
38401
+ var e_1, _a;
38402
+ var _b, _c;
38403
+ var tournamentRecord = params.tournamentRecord, drawDefinition = params.drawDefinition, matchUpId = params.matchUpId, event = params.event;
38404
+ var stack = 'resetScorecard';
38405
+ // Check for missing parameters ---------------------------------------------
38406
+ if (!drawDefinition)
38407
+ return decorateResult({
38408
+ result: { error: MISSING_DRAW_DEFINITION },
38409
+ stack: stack,
38473
38410
  });
38474
- // if no dynamic value found and a seeding scaleValue is provided...
38475
- if (!scaleValue && scaleName) {
38476
- scaleValue = getScaleValue({
38477
- scaleAccessor: scaleAccessor,
38478
- participant: participant,
38479
- scaleName: scaleName,
38480
- eventType: eventType,
38481
- });
38482
- }
38483
- if (scaleValue && !adHocRatings[participantId])
38484
- adHocRatings[participantId] = scaleValue;
38485
- };
38486
- try {
38487
- for (var _j = __values(participantIds !== null && participantIds !== void 0 ? participantIds : []), _k = _j.next(); !_k.done; _k = _j.next()) {
38488
- var participantId = _k.value;
38489
- _loop_1(participantId);
38490
- }
38491
- }
38492
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
38493
- finally {
38411
+ if (!matchUpId)
38412
+ return decorateResult({ result: { error: MISSING_MATCHUP_ID }, stack: stack });
38413
+ if (!isString(matchUpId))
38414
+ return decorateResult({
38415
+ result: { error: INVALID_VALUES, matchUpId: matchUpId },
38416
+ stack: stack,
38417
+ });
38418
+ // Get map of all drawMatchUps and inContextDrawMatchUPs ---------------------
38419
+ var matchUpsMap = getMatchUpsMap({ drawDefinition: drawDefinition });
38420
+ var inContextDrawMatchUps = getAllDrawMatchUps({
38421
+ nextMatchUps: true,
38422
+ inContext: true,
38423
+ drawDefinition: drawDefinition,
38424
+ matchUpsMap: matchUpsMap,
38425
+ }).matchUps;
38426
+ // Find target matchUp ------------------------------------------------------
38427
+ var matchUp = matchUpsMap.drawMatchUps.find(function (matchUp) { return matchUp.matchUpId === matchUpId; });
38428
+ var inContextMatchUp = inContextDrawMatchUps === null || inContextDrawMatchUps === void 0 ? void 0 : inContextDrawMatchUps.find(function (matchUp) { return matchUp.matchUpId === matchUpId; });
38429
+ if (!matchUp || !inContextDrawMatchUps)
38430
+ return { error: MATCHUP_NOT_FOUND };
38431
+ // only accept matchUpType: TEAM
38432
+ if (matchUp.matchUpType !== TEAM_EVENT)
38433
+ return { error: INVALID_MATCHUP };
38434
+ // Get winner/loser position targets ----------------------------------------
38435
+ var targetData = positionTargets({
38436
+ inContextDrawMatchUps: inContextDrawMatchUps,
38437
+ drawDefinition: drawDefinition,
38438
+ matchUpId: matchUpId,
38439
+ });
38440
+ var structureId = inContextMatchUp === null || inContextMatchUp === void 0 ? void 0 : inContextMatchUp.structureId;
38441
+ var structure = findStructure({ drawDefinition: drawDefinition, structureId: structureId }).structure;
38442
+ Object.assign(params, {
38443
+ inContextDrawMatchUps: inContextDrawMatchUps,
38444
+ inContextMatchUp: inContextMatchUp,
38445
+ matchUpsMap: matchUpsMap,
38446
+ targetData: targetData,
38447
+ structure: structure,
38448
+ matchUp: matchUp,
38449
+ });
38450
+ // with propagating winningSide changes, activeDownstream only applies to eventType: TEAM
38451
+ var activeDownstream = isActiveDownstream(params);
38452
+ if (activeDownstream)
38453
+ return { error: CANNOT_CHANGE_WINNING_SIDE };
38454
+ if ((_b = matchUp.tieMatchUps) === null || _b === void 0 ? void 0 : _b.length) {
38494
38455
  try {
38495
- if (_k && !_k.done && (_b = _j.return)) _b.call(_j);
38456
+ for (var _d = __values(matchUp.tieMatchUps), _e = _d.next(); !_e.done; _e = _d.next()) {
38457
+ var tieMatchUp = _e.value;
38458
+ var result_1 = setMatchUpState({
38459
+ matchUpId: tieMatchUp.matchUpId,
38460
+ matchUpTieId: matchUpId,
38461
+ winningSide: undefined,
38462
+ removeScore: true,
38463
+ tournamentRecord: tournamentRecord,
38464
+ drawDefinition: drawDefinition,
38465
+ event: event,
38466
+ });
38467
+ if (result_1.error)
38468
+ return decorateResult({ result: result_1, stack: stack });
38469
+ }
38470
+ }
38471
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
38472
+ finally {
38473
+ try {
38474
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
38475
+ }
38476
+ finally { if (e_1) throw e_1.error; }
38496
38477
  }
38497
- finally { if (e_1) throw e_1.error; }
38498
38478
  }
38499
- // TODO: update dynamic ratings based on matchUps present from last played round
38500
- // use scaleEngine.generateDynamicRatings(); see dynamicCalculations.test.ts
38501
- return generateDrawMaticRound({
38502
- tournamentParticipants: tournamentParticipants,
38503
- generateMatchUps: generateMatchUps,
38504
- participantIds: participantIds,
38505
- encounterValue: encounterValue,
38506
- sameTeamValue: sameTeamValue,
38479
+ var result = updateTieMatchUpScore({
38480
+ event: params.event,
38481
+ removeScore: true,
38482
+ tournamentRecord: tournamentRecord,
38507
38483
  drawDefinition: drawDefinition,
38508
- maxIterations: maxIterations,
38509
- adHocRatings: adHocRatings,
38510
- matchUpIds: matchUpIds,
38511
- structure: structure,
38512
- eventType: eventType,
38513
- salted: salted,
38484
+ matchUpsMap: matchUpsMap,
38485
+ matchUpId: matchUpId,
38514
38486
  });
38487
+ if (result.error)
38488
+ return decorateResult({ result: result, stack: stack });
38489
+ if (params.tiebreakReset && !result.tieFormatRemoved) {
38490
+ // check for scenarios where an added "Tiebreaker" collectionDefinition/matchUp has been added
38491
+ var inheritedTieFormat = (_c = resolveTieFormat({
38492
+ drawDefinition: drawDefinition,
38493
+ structure: structure,
38494
+ event: event,
38495
+ })) === null || _c === void 0 ? void 0 : _c.tieFormat;
38496
+ if (matchUp.tieFormat && inheritedTieFormat) {
38497
+ var _f = compareTieFormats({
38498
+ descendant: matchUp.tieFormat,
38499
+ ancestor: inheritedTieFormat,
38500
+ }), matchUpCountDifference = _f.matchUpCountDifference, descendantDifferences = _f.descendantDifferences, ancestorDifferences = _f.ancestorDifferences, valueDifference = _f.valueDifference;
38501
+ if (descendantDifferences.collectionIds.length === 1 &&
38502
+ !ancestorDifferences.collectionIds.length &&
38503
+ !ancestorDifferences.groupsCount &&
38504
+ matchUpCountDifference === 1 &&
38505
+ valueDifference === 1) {
38506
+ var result_2 = resetTieFormat({
38507
+ tournamentRecord: tournamentRecord,
38508
+ drawDefinition: drawDefinition,
38509
+ matchUpId: matchUpId,
38510
+ event: event,
38511
+ });
38512
+ if (result_2.error)
38513
+ return result_2;
38514
+ }
38515
+ }
38516
+ }
38517
+ return __assign({}, SUCCESS);
38515
38518
  }
38516
- function getScaleValue(_a) {
38517
- var _b;
38518
- var _c = _a.scaleType, scaleType = _c === void 0 ? RATING$2 : _c, scaleAccessor = _a.scaleAccessor, participant = _a.participant, scaleName = _a.scaleName, eventType = _a.eventType;
38519
+
38520
+ function removeSeeding(_a) {
38521
+ var _b, _c;
38522
+ var tournamentRecord = _a.tournamentRecord, drawDefinition = _a.drawDefinition, entryStatuses = _a.entryStatuses, scaleName = _a.scaleName, drawId = _a.drawId, event = _a.event, stage = _a.stage;
38523
+ if (!tournamentRecord)
38524
+ return { error: MISSING_TOURNAMENT_RECORD };
38525
+ if (!event)
38526
+ return { error: MISSING_EVENT };
38527
+ scaleName =
38528
+ scaleName ||
38529
+ ((_b = event.category) === null || _b === void 0 ? void 0 : _b.categoryName) ||
38530
+ ((_c = event.category) === null || _c === void 0 ? void 0 : _c.ageCategoryCode);
38519
38531
  var scaleAttributes = {
38520
- eventType: eventType !== null && eventType !== void 0 ? eventType : SINGLES_EVENT,
38521
- scaleType: scaleType,
38532
+ eventType: event.eventType,
38533
+ scaleType: SEEDING$1,
38522
38534
  scaleName: scaleName,
38523
38535
  };
38524
- var result = participant &&
38525
- participantScaleItem({
38526
- scaleAttributes: scaleAttributes,
38527
- participant: participant,
38528
- });
38529
- var scaleValue = (_b = result === null || result === void 0 ? void 0 : result.scaleItem) === null || _b === void 0 ? void 0 : _b.scaleValue;
38530
- return scaleAccessor && isObject(scaleValue)
38531
- ? scaleValue[scaleAccessor]
38532
- : scaleValue;
38533
- }
38534
-
38535
- function drawMatic(params) {
38536
- var _a;
38537
- var tournamentParticipants = (_a = params.tournamentRecord) === null || _a === void 0 ? void 0 : _a.participants;
38538
- Object.assign(params, { tournamentParticipants: tournamentParticipants });
38539
- return drawMatic$1(params);
38536
+ return removeScaleValues({
38537
+ tournamentRecord: tournamentRecord,
38538
+ scaleAttributes: scaleAttributes,
38539
+ drawDefinition: drawDefinition,
38540
+ entryStatuses: entryStatuses,
38541
+ drawId: drawId,
38542
+ event: event,
38543
+ stage: stage,
38544
+ });
38540
38545
  }
38541
38546
 
38542
38547
  function setSubOrder(_a) {
@@ -42596,7 +42601,7 @@ function generateDrawDefinition(params) {
42596
42601
  var _a, _b, _c;
42597
42602
  if (params.automated) {
42598
42603
  var _d = (_a = params.drawMatic) !== null && _a !== void 0 ? _a : {}, restrictEntryStatus = _d.restrictEntryStatus, generateMatchUps = _d.generateMatchUps, structureId_1 = _d.structureId, matchUpIds = _d.matchUpIds, scaleName = _d.scaleName;
42599
- var matchUps = drawMatic$1({
42604
+ var matchUps = drawMatic({
42600
42605
  eventType: (_c = (_b = params.drawMatic) === null || _b === void 0 ? void 0 : _b.eventType) !== null && _c !== void 0 ? _c : matchUpType,
42601
42606
  generateMatchUps: generateMatchUps !== null && generateMatchUps !== void 0 ? generateMatchUps : true,
42602
42607
  restrictEntryStatus: restrictEntryStatus,
@@ -42605,7 +42610,8 @@ function generateDrawDefinition(params) {
42605
42610
  drawDefinition: drawDefinition,
42606
42611
  structureId: structureId_1,
42607
42612
  matchUpIds: matchUpIds,
42608
- scaleName: scaleName,
42613
+ scaleName: scaleName, // custom rating name to seed dynamic ratings
42614
+ event: event,
42609
42615
  }).matchUps;
42610
42616
  addAdHocMatchUps({
42611
42617
  tournamentRecord: tournamentRecord,
@@ -42619,6 +42625,7 @@ function generateDrawDefinition(params) {
42619
42625
  newRound: true,
42620
42626
  drawDefinition: drawDefinition,
42621
42627
  matchUpsCount: matchUpsCount_1,
42628
+ event: event,
42622
42629
  }).matchUps;
42623
42630
  addAdHocMatchUps({
42624
42631
  tournamentRecord: tournamentRecord,
@@ -52549,7 +52556,6 @@ var publishingGovernor = {
52549
52556
  getDrawData: getDrawData,
52550
52557
  getEventData: getEventData,
52551
52558
  getPublishState: getPublishState,
52552
- getTournamentInfo: getTournamentInfo,
52553
52559
  getVenueData: getVenueData,
52554
52560
  publishEvent: publishEvent,
52555
52561
  publishEventSeeding: publishEventSeeding,
@@ -54126,6 +54132,53 @@ function getParticipantMembership(_a) {
54126
54132
  }, {});
54127
54133
  }
54128
54134
 
54135
+ /**
54136
+ *
54137
+ * @param {object[]} outcomes - array of outcomes to be applied to matchUps, relevent attributes: { eventId: string; drawId: string; }
54138
+ *
54139
+ */
54140
+ function bulkUpdatePublishedEventIds(_a) {
54141
+ var _b;
54142
+ var tournamentRecord = _a.tournamentRecord, outcomes = _a.outcomes;
54143
+ if (!tournamentRecord)
54144
+ return { error: MISSING_TOURNAMENT_RECORD };
54145
+ if (!(outcomes === null || outcomes === void 0 ? void 0 : outcomes.length))
54146
+ return { error: MISSING_VALUE, info: 'Missing outcomes' };
54147
+ var eventIdsMap = outcomes.reduce(function (eventIdsMap, outcome) {
54148
+ var drawId = outcome.drawId, eventId = outcome.eventId;
54149
+ if (eventId && drawId) {
54150
+ if (!eventIdsMap[eventId]) {
54151
+ eventIdsMap[eventId] = [drawId];
54152
+ }
54153
+ else if (!eventIdsMap[eventId].includes(drawId)) {
54154
+ eventIdsMap[eventId].push(drawId);
54155
+ }
54156
+ }
54157
+ return eventIdsMap;
54158
+ }, {});
54159
+ var relevantEventsIds = Object.keys(eventIdsMap);
54160
+ var relevantEvents = (_b = tournamentRecord.events) === null || _b === void 0 ? void 0 : _b.filter(function (event) {
54161
+ return relevantEventsIds.includes(event.eventId);
54162
+ });
54163
+ var publishedEventIds = relevantEvents
54164
+ .filter(function (event) {
54165
+ var pubStatus = getEventPublishStatus({ event: event });
54166
+ var _a = pubStatus !== null && pubStatus !== void 0 ? pubStatus : {}, drawDetails = _a.drawDetails, drawIds = _a.drawIds;
54167
+ var eventId = event.eventId;
54168
+ var publishedDrawIds = eventIdsMap[eventId].filter(function (drawId) {
54169
+ var keyedDrawIds = drawDetails
54170
+ ? Object.keys(pubStatus.drawDetails).filter(function (drawId) {
54171
+ return getDrawPublishStatus({ drawId: drawId, drawDetails: drawDetails });
54172
+ })
54173
+ : [];
54174
+ return (drawIds === null || drawIds === void 0 ? void 0 : drawIds.includes(drawId)) || keyedDrawIds.includes(drawId);
54175
+ });
54176
+ return publishedDrawIds.length;
54177
+ })
54178
+ .map(function (event) { return event.eventId; });
54179
+ return { publishedEventIds: publishedEventIds, eventIdPublishedDrawIdsMap: eventIdsMap };
54180
+ }
54181
+
54129
54182
  function getSourceStructureIdsAndRelevantLinks(_a) {
54130
54183
  var targetRoundNumber = _a.targetRoundNumber, finishingPosition = _a.finishingPosition, drawDefinition = _a.drawDefinition, structureId = _a.structureId, // structure for which source and target links are to be found
54131
54184
  linkType = _a.linkType;
@@ -56463,53 +56516,6 @@ function getMatchUpFormat(params) {
56463
56516
  };
56464
56517
  }
56465
56518
 
56466
- /**
56467
- *
56468
- * @param {object[]} outcomes - array of outcomes to be applied to matchUps, relevent attributes: { eventId: string; drawId: string; }
56469
- *
56470
- */
56471
- function bulkUpdatePublishedEventIds(_a) {
56472
- var _b;
56473
- var tournamentRecord = _a.tournamentRecord, outcomes = _a.outcomes;
56474
- if (!tournamentRecord)
56475
- return { error: MISSING_TOURNAMENT_RECORD };
56476
- if (!(outcomes === null || outcomes === void 0 ? void 0 : outcomes.length))
56477
- return { error: MISSING_VALUE, info: 'Missing outcomes' };
56478
- var eventIdsMap = outcomes.reduce(function (eventIdsMap, outcome) {
56479
- var drawId = outcome.drawId, eventId = outcome.eventId;
56480
- if (eventId && drawId) {
56481
- if (!eventIdsMap[eventId]) {
56482
- eventIdsMap[eventId] = [drawId];
56483
- }
56484
- else if (!eventIdsMap[eventId].includes(drawId)) {
56485
- eventIdsMap[eventId].push(drawId);
56486
- }
56487
- }
56488
- return eventIdsMap;
56489
- }, {});
56490
- var relevantEventsIds = Object.keys(eventIdsMap);
56491
- var relevantEvents = (_b = tournamentRecord.events) === null || _b === void 0 ? void 0 : _b.filter(function (event) {
56492
- return relevantEventsIds.includes(event.eventId);
56493
- });
56494
- var publishedEventIds = relevantEvents
56495
- .filter(function (event) {
56496
- var pubStatus = getEventPublishStatus({ event: event });
56497
- var _a = pubStatus !== null && pubStatus !== void 0 ? pubStatus : {}, drawDetails = _a.drawDetails, drawIds = _a.drawIds;
56498
- var eventId = event.eventId;
56499
- var publishedDrawIds = eventIdsMap[eventId].filter(function (drawId) {
56500
- var keyedDrawIds = drawDetails
56501
- ? Object.keys(pubStatus.drawDetails).filter(function (drawId) {
56502
- return getDrawPublishStatus({ drawId: drawId, drawDetails: drawDetails });
56503
- })
56504
- : [];
56505
- return (drawIds === null || drawIds === void 0 ? void 0 : drawIds.includes(drawId)) || keyedDrawIds.includes(drawId);
56506
- });
56507
- return publishedDrawIds.length;
56508
- })
56509
- .map(function (event) { return event.eventId; });
56510
- return { publishedEventIds: publishedEventIds, eventIdPublishedDrawIdsMap: eventIdsMap };
56511
- }
56512
-
56513
56519
  function publicFindParticipant(params) {
56514
56520
  var _a, e_1, _b;
56515
56521
  var tournamentRecord = params.tournamentRecord, policyDefinitions = params.policyDefinitions, contextProfile = params.contextProfile, participantId = params.participantId, personId = params.personId;
@@ -57656,6 +57662,7 @@ var queryGovernor = {
57656
57662
  getTeamLineUp: getTeamLineUp,
57657
57663
  getTieFormat: getTieFormat,
57658
57664
  getTournamentIds: getTournamentIds,
57665
+ getTournamentInfo: getTournamentInfo,
57659
57666
  getTournamentPenalties: getTournamentPenalties,
57660
57667
  getTournamentPersons: getTournamentPersons,
57661
57668
  getTournamentStructures: getTournamentStructures,
@@ -66043,7 +66050,7 @@ function asyncExecutionQueue(engine, directives, rollbackOnError) {
66043
66050
  var e_1, _a;
66044
66051
  return __generator(this, function (_b) {
66045
66052
  if (!Array.isArray(directives))
66046
- return [2 /*return*/, { error: INVALID_VALUES }];
66053
+ return [2 /*return*/, { error: INVALID_VALUES, message: 'directives must be an array' }];
66047
66054
  methods = getMethods();
66048
66055
  start = Date.now();
66049
66056
  snapshot = rollbackOnError && makeDeepCopy(getTournamentRecords(), false, true);
@@ -66052,7 +66059,7 @@ function asyncExecutionQueue(engine, directives, rollbackOnError) {
66052
66059
  for (directives_1 = __values(directives), directives_1_1 = directives_1.next(); !directives_1_1.done; directives_1_1 = directives_1.next()) {
66053
66060
  directive = directives_1_1.value;
66054
66061
  if (typeof directive !== 'object')
66055
- return [2 /*return*/, { error: INVALID_VALUES }];
66062
+ return [2 /*return*/, { error: INVALID_VALUES, message: 'directive must be an object' }];
66056
66063
  methodName = directive.method, params = directive.params;
66057
66064
  if (!methods[methodName])
66058
66065
  return [2 /*return*/, logMethodNotFound({ methodName: methodName, start: start, params: params })];
@@ -66090,15 +66097,18 @@ function asyncEngineInvoke(engine, args) {
66090
66097
  switch (_d.label) {
66091
66098
  case 0:
66092
66099
  if (!isObject(args))
66093
- return [2 /*return*/, { error: INVALID_VALUES }];
66100
+ return [2 /*return*/, { error: INVALID_VALUES, message: 'args must be an object' }];
66094
66101
  methodsCount = Object.values(args).filter(isFunction).length;
66095
66102
  if (methodsCount > 1)
66096
- return [2 /*return*/, { error: INVALID_VALUES }];
66103
+ return [2 /*return*/, {
66104
+ message: 'there must be only one arg with typeof function',
66105
+ error: INVALID_VALUES,
66106
+ }];
66097
66107
  methodName = methodsCount
66098
66108
  ? Object.keys(args).find(function (key) { return isFunction(args[key]); })
66099
66109
  : isString(args.method) && args.method;
66100
66110
  if (!methodName)
66101
- return [2 /*return*/, { error: INVALID_VALUES }];
66111
+ return [2 /*return*/, { error: METHOD_NOT_FOUND }];
66102
66112
  _b = args, _c = methodName, passedMethod = _b[_c], remainingArgs = __rest(_b, [typeof _c === "symbol" ? _c : _c + ""]);
66103
66113
  params = (args === null || args === void 0 ? void 0 : args.params) || __assign({}, remainingArgs);
66104
66114
  snapshot = params.rollbackOnError && makeDeepCopy(getTournamentRecords(), false, true);
@@ -66253,15 +66263,18 @@ function asyncEngine(test) {
66253
66263
 
66254
66264
  function askInvoke(engine, args) {
66255
66265
  if (!isObject(args))
66256
- return { error: INVALID_VALUES };
66266
+ return { error: INVALID_VALUES, message: 'args must be an object' };
66257
66267
  var methodsCount = Object.values(args).filter(isFunction).length;
66258
66268
  if (methodsCount > 1)
66259
- return { error: INVALID_VALUES };
66269
+ return {
66270
+ message: 'there must be only one arg with typeof function',
66271
+ error: INVALID_VALUES,
66272
+ };
66260
66273
  var methodName = methodsCount
66261
66274
  ? Object.keys(args).find(function (key) { return isFunction(args[key]); })
66262
66275
  : isString(args.method) && args.method;
66263
66276
  if (!methodName)
66264
- return { error: INVALID_VALUES };
66277
+ return { error: METHOD_NOT_FOUND };
66265
66278
  var _a = args, _b = methodName, passedMethod = _a[_b], remainingArgs = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
66266
66279
  var params = (args === null || args === void 0 ? void 0 : args.params) || __assign({}, remainingArgs);
66267
66280
  var method = passedMethod || engine[methodName] || getMethods$1()[methodName];
@@ -66281,7 +66294,7 @@ var askEngine = (function () {
66281
66294
  function executionQueue(engine, directives, rollbackOnError) {
66282
66295
  var e_1, _a;
66283
66296
  if (!Array.isArray(directives))
66284
- return { error: INVALID_VALUES };
66297
+ return { error: INVALID_VALUES, message: 'directives must be an array' };
66285
66298
  var methods = getMethods();
66286
66299
  var start = Date.now();
66287
66300
  var snapshot = rollbackOnError && makeDeepCopy(getTournamentRecords(), false, true);
@@ -66290,7 +66303,7 @@ function executionQueue(engine, directives, rollbackOnError) {
66290
66303
  for (var directives_1 = __values(directives), directives_1_1 = directives_1.next(); !directives_1_1.done; directives_1_1 = directives_1.next()) {
66291
66304
  var directive = directives_1_1.value;
66292
66305
  if (typeof directive !== 'object')
66293
- return { error: INVALID_VALUES };
66306
+ return { error: INVALID_VALUES, message: 'directive must be an object' };
66294
66307
  var methodName = directive.method, params = directive.params;
66295
66308
  if (!methods[methodName])
66296
66309
  return logMethodNotFound({ methodName: methodName, start: start, params: params });
@@ -66321,15 +66334,18 @@ function executionQueue(engine, directives, rollbackOnError) {
66321
66334
  function engineInvoke(engine, args) {
66322
66335
  var _a;
66323
66336
  if (!isObject(args))
66324
- return { error: INVALID_VALUES };
66337
+ return { error: INVALID_VALUES, message: 'args must be an object' };
66325
66338
  var methodsCount = Object.values(args).filter(isFunction).length;
66326
66339
  if (methodsCount > 1)
66327
- return { error: INVALID_VALUES };
66340
+ return {
66341
+ message: 'there must be only one arg with typeof function',
66342
+ error: INVALID_VALUES,
66343
+ };
66328
66344
  var methodName = methodsCount
66329
66345
  ? Object.keys(args).find(function (key) { return isFunction(args[key]); })
66330
66346
  : isString(args.method) && args.method;
66331
66347
  if (!methodName)
66332
- return { error: INVALID_VALUES };
66348
+ return { error: METHOD_NOT_FOUND };
66333
66349
  var _b = args, _c = methodName, passedMethod = _b[_c], remainingArgs = __rest(_b, [typeof _c === "symbol" ? _c : _c + ""]);
66334
66350
  var params = (args === null || args === void 0 ? void 0 : args.params) || __assign({}, remainingArgs);
66335
66351
  var snapshot = params.rollbackOnError && makeDeepCopy(getTournamentRecords(), false, true);