Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require('dotenv').config({path: './.env'});
- const League = require('../models/leagues')
- const Pick = require('../models/picks')
- const User = require('../models/users')
- const Match = require('../models/matches')
- const Team = require('../models/teams')
- const Pool = require('../models/pools')
- const GlobalPick = require('../models/globalPicks')
- const co = require('co')
- const moment = require('moment')
- const logger = require('../services/logger')
- const errorHandler = require('./helper').errorHandler;
- const constants = require('../../src/constants')
- const axiosBase = require('axios')
- const bonusValue = 2;
- const axios = axiosBase.create({
- baseURL: 'https://api.football-data.org/',
- timeout: 20000,
- headers: { 'X-Auth-Token': process.env.FOOTBALL_API_KEY },
- withCredentials: true
- });
- exports.getMatches = function (leagueId, period) {
- co(function*() {
- try {
- const result = (yield axios({
- method: 'get',
- url: 'v2/competitions/' + leagueId + '/matches?dateFrom=' +
- moment().add(-1, period).format("YYYY-MM-DD") + '&dateTo=' + moment().add(1, period).format("YYYY-MM-DD"),
- })).data;
- logger.info(module, 'matches refresh', leagueId + ': ' + result.matches.length)
- if (!result.matches) return;
- for (let i = 0; i < result.matches.length; i++) {
- /*if (result.matches[i].status === 'IN_PLAY' || result.matches[i].status === 'PAUSED') {
- console.log(result.matches[i])
- }*/
- Match.findOneAndUpdate({id: result.matches[i].id}, result.matches[i], {upsert: true, new: true})
- .then((match) => {
- if (match.status === 'FINISHED' && !match.isScored) {
- if (match.score.fullTime.homeTeam > match.score.fullTime.awayTeam) match.score.winner = 'HOME_TEAM';
- if (match.score.fullTime.homeTeam < match.score.fullTime.awayTeam) match.score.winner = 'AWAY_TEAM';
- if (match.score.fullTime.homeTeam === match.score.fullTime.awayTeam) match.score.winner = 'DRAW';
- logger.info(module, 'match values', match.id + ': ' + match.score.winner);
- logger.info(module, 'match values', match.score.fullTime);
- }
- })
- }
- } catch (e) {
- errorHandler(null, null, e, 'DB: get matches error: league ' + leagueId);
- }
- });
- }
- exports.getTeams = function (leagueId, leagueType) {
- co(function*() {
- try {
- const league = (yield axios({method: 'get', url: 'v2/competitions/' + leagueId + '/teams'})).data
- for (let i = 0; i < league.teams.length; i++) {
- let team = league.teams[i];
- team[leagueType] = leagueId;
- Team.updateOne({id: team.id}, team, {upsert: true, new: true})
- .then((newTeam) => {
- console.log(team.name + ' updated')
- })
- }
- } catch (e) {
- errorHandler(null, null, e, 'DB: get teams error');
- }
- });
- }
- exports.matchdayCheck = function (leagueId) {
- co(function*() {
- try {
- logger.info(module, 'matchday check', leagueId);
- const {currentSeason, numberOfMatchDays} = (yield League.findOne({id: leagueId})
- .select('currentSeason numberOfMatchDays').lean().exec());
- const currentMatchday = currentSeason.currentMatchday;
- let lastDay = {}, ignoredMatchUpdates = [];
- for(let i = currentMatchday; i <= numberOfMatchDays; i++) {
- const matches = yield Match.find({'season.id': currentSeason.id, matchday: i})
- .select('status matchday isScored isIgnored score').lean().exec();
- if (matches.some(x => x.status === 'FINISHED' || x.status === 'AWARDED' || x.status === 'IN_PLAY' || x.status === 'PAUSED')
- || i === currentMatchday)
- lastDay = {index: i, matches: matches};
- else break;
- }
- let matchesToScore = lastDay.matches.map(x => {
- let isIgnored = x.isIgnored;
- if(!x.isIgnored && (x.status === 'POSTPONED' || x.status === 'SUSPENDED' || x.status === 'CANCELED')) {
- ignoredMatchUpdates.push(Match.findByIdAndUpdate(x._id, {$set: {isIgnored: true}}));
- isIgnored = true;
- }
- return {...x, isIgnored: isIgnored};
- }).filter(x => !x.isIgnored);
- yield Promise.all(ignoredMatchUpdates);
- if(!matchesToScore.every(match => match.status === 'FINISHED' || match.status === 'AWARDED'))
- return;
- let isScoredUpdated = false;
- for(let index in matchesToScore){
- if(!matchesToScore[index].isScored){
- yield scoreMatch(matchesToScore[index]);
- isScoredUpdated = true;
- }
- }
- if(
- isScoredUpdated && (yield Match.find({'season.id': currentSeason.id, matchday: lastDay.index})
- .select('isScored isIgnored').lean().exec()).filter(x => !x.isIgnored).every(x => x.isScored)
- )
- yield scoreWDL(lastDay.matches, lastDay.index);
- } catch (e) {
- errorHandler(null, null, e, 'DB: check match day error');
- }
- });
- };
- const scoreWDL = (matches, calculatedMatchday) => {
- return co(function*() {
- try {
- const picks = yield Pick.find({matchId: {$in: matches.map(x => x._id)}}).populate({path: 'poolId',
- select: 'status matchdays gameType gameTypeDifference type'}).lean().exec();
- let totals = {}, pools = {};
- picks.forEach(pick => {
- if (pick.poolId && pick.poolId.matchdays && pick.poolId.matchdays[calculatedMatchday] &&
- !pick.poolId.matchdays[calculatedMatchday].isScored && pick.poolId.type === constants.NATIONAL
- && !pick.poolId.gameType && pick.poolId.status === constants.poolStages.active) {
- //check if onevsone mode
- if (!pools[pick.poolId._id]) pools[pick.poolId._id] = {matchdays: pick.poolId.matchdays, gameTypeDifference: pick.poolId.gameTypeDifference};
- if (!totals[pick.poolId._id + pick.userId]) totals[pick.poolId._id + pick.userId] = 0;
- for (let i in pick.pickResult) {
- if (typeof(pick.pickResult[i]) === 'number') {
- totals[pick.poolId._id + pick.userId] += pick.pickResult[i];
- }
- }
- }
- });
- for (let i in pools) {
- logger.info(module, 'matchday check, pool calc: ', i);
- const matchday = pools[i].matchdays.find(x => x.matchday === calculatedMatchday);
- const gameTypeDiff = pools[i].gameTypeDifference;
- matchday.users.forEach(couple => {
- const total1 = totals[i + couple.user1] ? totals[i + couple.user1] : 0;
- const total2 = totals[i + couple.user2] ? totals[i + couple.user2] : 0;
- logger.info(module, 'couple calc');
- logger.info(module, `user1 (${couple.user1}) total: ${total1}`);
- logger.info(module, `user2 (${couple.user2}) total: ${total2}`);
- const diff = total1 - total2;
- if (diff > gameTypeDiff) { //user1 wins
- User.findOneAndUpdate({_id: couple.user1, 'pools.poolId': i}, { $addToSet: { "pools.$.score.win" : calculatedMatchday} })
- .then((user) => {console.log('updated')});
- User.findOneAndUpdate({_id: couple.user2, 'pools.poolId': i}, { $addToSet: { "pools.$.score.lose" : calculatedMatchday} })
- .then((user) => {console.log('updated')})
- } else if (diff < -gameTypeDiff) { //user2 wins
- User.findOneAndUpdate({_id: couple.user1, 'pools.poolId': i}, { $addToSet: { "pools.$.score.lose" : calculatedMatchday} })
- .then((user) => {console.log('updated')});
- User.findOneAndUpdate({_id: couple.user2, 'pools.poolId': i}, { $addToSet: { "pools.$.score.win" : calculatedMatchday} })
- .then((user) => {console.log('updated')})
- } else { //draw
- User.findOneAndUpdate({_id: couple.user1, 'pools.poolId': i}, { $addToSet: { "pools.$.score.draw" : calculatedMatchday} })
- .then((user) => {console.log('updated')});
- User.findOneAndUpdate({_id: couple.user2, 'pools.poolId': i}, { $addToSet: { "pools.$.score.draw" : calculatedMatchday} })
- .then((user) => {console.log('updated')})
- }
- });
- Pool.findOneAndUpdate({_id: i, 'matchdays.matchday': calculatedMatchday}, { $set: { "matchdays.$.isScored" : true} })
- .then(() => {
- console.log('updated')
- })
- }
- logger.info(module, 'Pools W/D/L updated');
- } catch (e) {
- errorHandler(null, null, e, 'DB: score w/d/l error');
- }
- })
- };
- exports.mixedMatchdayCheck = function () {
- co(function*() {
- try {
- logger.info(module, 'mixed matchday check')
- const weekStart = moment.utc().add(-2, 'days').startOf('week').add(1, 'days').hours(0).minutes(0).seconds(0).toDate();
- const weekEnd = moment.utc().add(-2, 'days').endOf('week').add(1, 'days').hours(23).minutes(59).seconds(59).toDate();
- const matches = yield Match.find({$and: [{utcDate: {$gte: weekStart}}, {utcDate: {$lte: weekEnd}}]}).select('status').lean().exec();
- const picks = yield Pick.find({matchId: {$in: matches.map(x => x._id)}}).populate({path: 'poolId',
- select: 'status matchdays gameType gameTypeDifference type'}).lean().exec();
- let totals = {}, pools = {};
- picks.forEach(pick => {
- const poolMatchday = moment.utc().diff(moment(pick.poolId.mixedStartDate), 'week') + 1;
- if (pick.poolId && pick.poolId.matchdays && pick.poolId.matchdays[poolMatchday] && !pick.poolId.matchdays[poolMatchday].isScored
- && !pick.poolId.gameType && pick.poolId.status === constants.poolStages.active && pick.poolId.type === constants.MIXED) {
- if (!pools[pick.poolId._id]) pools[pick.poolId._id] = {matchdays: pick.poolId.matchdays, gameTypeDifference: pick.poolId.gameTypeDifference};
- if (!totals[pick.poolId._id + pick.userId]) totals[pick.poolId._id + pick.userId] = 0;
- for (let i in pick.pickResult) {
- if (typeof(pick.pickResult[i]) === 'number') {
- totals[pick.poolId._id + pick.userId] += pick.pickResult[i];
- }
- }
- }
- });
- for (let i in pools) {
- logger.info(module, 'mixed matchday check, pool calc: ', i)
- const poolMatchday = moment.utc().diff(moment(pools[i].mixedStartDate), 'week') + 1;
- const matchday = pools[i].matchdays.find(x => x.matchday === poolMatchday);
- const gameTypeDiff = pools[i].gameTypeDifference;
- matchday.users.forEach(couple => {
- const total1 = totals[i + couple.user1] ? totals[i + couple.user1] : 0;
- const total2 = totals[i + couple.user2] ? totals[i + couple.user2] : 0;
- logger.info(module, 'couple calc')
- logger.info(module, `user1 (${couple.user1}) total: ${total1}`)
- logger.info(module, `user2 (${couple.user2}) total: ${total2}`)
- const diff = total1 - total2;
- if (diff > gameTypeDiff) { //user1 wins
- User.findOneAndUpdate({_id: couple.user1, 'pools.poolId': i}, { $addToSet: { "pools.$.score.win" : poolMatchday} })
- .then((user) => {console.log('updated')})
- User.findOneAndUpdate({_id: couple.user2, 'pools.poolId': i}, { $addToSet: { "pools.$.score.lose" : poolMatchday} })
- .then((user) => {console.log('updated')})
- } else if (diff < -gameTypeDiff) { //user2 wins
- User.findOneAndUpdate({_id: couple.user1, 'pools.poolId': i}, { $addToSet: { "pools.$.score.lose" : poolMatchday} })
- .then((user) => {console.log('updated')})
- User.findOneAndUpdate({_id: couple.user2, 'pools.poolId': i}, { $addToSet: { "pools.$.score.win" : poolMatchday} })
- .then((user) => {console.log('updated')})
- } else { //draw
- User.findOneAndUpdate({_id: couple.user1, 'pools.poolId': i}, { $addToSet: { "pools.$.score.draw" : poolMatchday} })
- .then((user) => {console.log('updated')})
- User.findOneAndUpdate({_id: couple.user2, 'pools.poolId': i}, { $addToSet: { "pools.$.score.draw" : poolMatchday} })
- .then((user) => {console.log('updated')})
- }
- });
- Pool.findOneAndUpdate({_id: i, 'matchdays.matchday': poolMatchday}, { $set: { "matchdays.$.isScored" : true} })
- .then(() => {
- console.log('updated')
- })
- }
- } catch (e) {
- errorHandler(null, null, e, 'DB: mixed matchday check error');
- }
- });
- }
- exports.getStandings = function (leagueId) {
- co(function*() {
- try {
- const league = (yield axios({method: 'get', url: 'v2/competitions/' + leagueId + '/standings'})).data
- const buf = constants.leagues.find(x => x.value === leagueId)
- const order = buf ? buf.order : 1000
- const numberOfMatchDays = buf ? buf.numberOfMatchDays : null
- yield League.updateOne({id: leagueId}, {
- $set: {
- standings: league.standings,
- importance: order,
- numberOfMatchDays: numberOfMatchDays,
- }
- })
- } catch (e) {
- errorHandler(null, null, e, 'DB: get standings error');
- }
- });
- }
- exports.getLeagues = function () {
- co(function*() {
- try {
- const result = (yield axios({
- method: 'get',
- url: 'v2/competitions/'
- })).data;
- if (!result.competitions) return;
- yield Promise.all(result.competitions.map(league => League.updateOne({id: league.id}, league, {upsert: true})))
- } catch (e) {
- errorHandler(null, null, e, 'DB: get leagues error');
- }
- });
- }
- const scoreMatch = (match) => {
- return co(function*() {
- try {
- const picks = yield Pick.find({matchId: match._id, isScored: false}).populate('poolId userId').lean().exec();
- //For each kind of the bet the users that bet against the 70% of the pool will obtain some bonus.
- // We will count all values of all types and we will result later:
- let poolsPercentCount = {};
- picks.forEach(pick => {
- if (!pick.poolId || pick.poolId.status !== constants.poolStages.active) return;
- if (pick.poolId.bonus) {
- for (let j in pick) {
- const betAddress = j === 'gameScore' ? pick[j].home + '-' + pick[j].away : pick[j];
- if (!poolsPercentCount[pick.poolId._id + j]) poolsPercentCount[pick.poolId._id + j] = {value: 0, moreThan70Type: null};
- if (!poolsPercentCount[pick.poolId._id + j + betAddress]) poolsPercentCount[pick.poolId._id + j + betAddress] = 0;
- poolsPercentCount[pick.poolId._id + j].value++;
- poolsPercentCount[pick.poolId._id + j + betAddress]++;
- poolsPercentCount[pick.poolId._id + j].moreThan70Type =
- poolsPercentCount[pick.poolId._id + j + betAddress] / poolsPercentCount[pick.poolId._id + j].value > 0.7 ? betAddress : null;
- }
- }
- });
- let prs = [];
- for (let i = 0; i < picks.length; i++) {
- const pick = picks[i];
- if (!pick.poolId ) continue;
- let bonus = 0, bonusTypes = {};
- for (let j in pick) {
- const bet = pick[j];
- switch (j) {
- case constants.betTypes.wdl:
- if (match.score.winner.toString() === bet.toString()) {
- prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
- { $inc: { "pools.$.score.wdl" : pick.poolId.betTypes.wdl.value} }));
- prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.wdl': pick.poolId.betTypes.wdl.value}}))
- bonusTypes.wdl = (pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.wdl] &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.wdl].moreThan70Type &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.wdl].moreThan70Type !== bet) ? bonusValue : 0;
- bonus = bonus + bonusTypes.wdl;
- }
- break;
- case constants.betTypes.un15:
- if (match.score.fullTime.homeTeam + match.score.fullTime.awayTeam < 1.5 === bet) {
- prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
- { $inc: { "pools.$.score.un15" : pick.poolId.betTypes.un15.value } }))
- prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.un15': pick.poolId.betTypes.un15.value}}))
- bonusTypes.un15 = ((pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.un15] &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.un15].moreThan70Type &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.un15].moreThan70Type !== bet) ? bonusValue : 0);
- bonus = bonus + bonusTypes.un15;
- }
- break;
- case constants.betTypes.un25:
- if (match.score.fullTime.homeTeam + match.score.fullTime.awayTeam < 2.5 === bet) {
- prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
- { $inc: { "pools.$.score.un25" : pick.poolId.betTypes.un25.value } }))
- prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.un25': pick.poolId.betTypes.un25.value}}))
- bonusTypes.un25 = ((pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.un25] &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.un25].moreThan70Type &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.un25].moreThan70Type !== bet) ? bonusValue : 0);
- bonus = bonus + bonusTypes.un25;
- }
- break;
- case constants.betTypes.un35:
- if (match.score.fullTime.homeTeam + match.score.fullTime.awayTeam < 3.5 === bet) {
- prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
- { $inc: { "pools.$.score.un35" : pick.poolId.betTypes.un35.value } }))
- prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.un35': pick.poolId.betTypes.un35.value}}))
- bonusTypes.un35 = ((pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.un35] &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.un35].moreThan70Type &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.un35].moreThan70Type !== bet) ? bonusValue : 0);
- bonus = bonus + bonusTypes.un35;
- }
- break;
- case constants.betTypes.hasGoal:
- if (((match.score.fullTime.homeTeam > 0) && (match.score.fullTime.awayTeam > 0) && !!bet) ||
- ((match.score.fullTime.homeTeam === 0 || match.score.fullTime.awayTeam === 0) && !bet)) {
- prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
- { $inc: { "pools.$.score.hasGoal" : pick.poolId.betTypes.hasGoal.value } }))
- prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.hasGoal': pick.poolId.betTypes.hasGoal.value}}))
- bonusTypes.hasGoal = ((pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.hasGoal] &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.hasGoal].moreThan70Type &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.hasGoal].moreThan70Type !== bet) ? bonusValue : 0);
- bonus = bonus + bonusTypes.hasGoal;
- }
- break;
- case constants.betTypes.doubleChance:
- if ((bet === constants.doubleChance.homeOrDraw && (match.score.winner === constants.winTypes.HOME_TEAM || match.score.winner === constants.winTypes.DRAW)) ||
- (bet === constants.doubleChance.homeOrAway && (match.score.winner === constants.winTypes.HOME_TEAM || match.score.winner === constants.winTypes.AWAY_TEAM)) ||
- (bet === constants.doubleChance.awayOrDraw && (match.score.winner === constants.winTypes.DRAW || match.score.winner === constants.winTypes.AWAY_TEAM))) {
- prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
- { $inc: { "pools.$.score.doubleChance" : pick.poolId.betTypes.doubleChance.value } }))
- prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.doubleChance': pick.poolId.betTypes.doubleChance.value}}))
- bonusTypes.doubleChance = ((pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.doubleChance] &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.doubleChance].moreThan70Type &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.doubleChance].moreThan70Type !== bet) ? bonusValue : 0);
- bonus = bonus + bonusTypes.doubleChance;
- }
- break;
- case constants.betTypes.gameScore:
- if ((match.score.fullTime.homeTeam === bet.home) && (match.score.fullTime.awayTeam === bet.away)) {
- prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
- { $inc: { "pools.$.score.gameScore" : pick.poolId.betTypes.gameScore.value } }))
- prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.gameScore': pick.poolId.betTypes.gameScore.value}}))
- bonusTypes.gameScore = ((pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.gameScore] &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.gameScore].moreThan70Type &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.gameScore].moreThan70Type !== (bet.home + '-' + bet.away)) ? bonusValue : 0);
- bonus = bonus + bonusTypes.gameScore;
- }
- break;
- case constants.betTypes.totalGoals:
- if ((match.score.fullTime.homeTeam + match.score.fullTime.awayTeam) === bet) {
- prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
- { $inc: { "pools.$.score.totalGoals" : pick.poolId.betTypes.totalGoals.value } }))
- prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.totalGoals': pick.poolId.betTypes.totalGoals.value}}))
- bonusTypes.totalGoals = ((pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.totalGoals] &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.totalGoals].moreThan70Type &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.totalGoals].moreThan70Type !== bet) ? bonusValue : 0);
- bonus = bonus + bonusTypes.totalGoals;
- }
- break;
- case constants.betTypes.handicap:
- const diff = match.score.fullTime.homeTeam - match.score.fullTime.awayTeam;
- if ((bet === constants.handicap.vXh1plus && diff === 1) ||
- (bet === constants.handicap.vXh1minus && diff === -1) ||
- (bet === constants.handicap.v1h1 && diff > 1) ||
- (bet === constants.handicap.v2h1 && diff < -1) ||
- (bet === constants.handicap.other && diff === 0)) {
- prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
- { $inc: { "pools.$.score.handicap" : pick.poolId.betTypes.handicap.value } }))
- prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.handicap': pick.poolId.betTypes.handicap.value}}))
- bonusTypes.handicap = ((pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.handicap] &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.handicap].moreThan70Type &&
- poolsPercentCount[pick.poolId._id + constants.betTypes.handicap].moreThan70Type !== bet) ? bonusValue : 0);
- bonus = bonus + bonusTypes.handicap;
- }
- break;
- }
- }
- prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
- { $inc: { "pools.$.score.bonus" : bonus } }))
- prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.bonus': bonus, 'pickResult.bonusTypes': bonusTypes, isScored: true}}))
- }
- yield Promise.all(prs);
- yield Match.findByIdAndUpdate(match._id, {$set: {isScored: true}});
- logger.info(module, 'Match scored', match._id);
- } catch (e) {
- errorHandler(null, null, e, 'DB: score match error');
- }
- });
- };
- exports.leagueStageCheck = function (leagueId) {
- co(function*() {
- try {
- let league = yield League.findOne({id: leagueId}).select('currentSeason scoredStages standings').lean().exec();
- if (!league.scoredStages){
- league = yield League.findByIdAndUpdate(league._id, {$set: {'scoredStages': {}}}, {new: true});
- }
- const matches = yield Match.find({'season.id': league.currentSeason.id}).select('stage status').lean().exec();
- let matchesByStages = {
- GROUP_STAGE: [],
- ROUND_OF_16: [],
- QUARTER_FINALS: [],
- SEMI_FINALS: [],
- FINAL: []
- };
- matches.forEach((match) =>{
- if (matchesByStages[match.stage]){
- matchesByStages[match.stage].push(match)
- }
- });
- if ((matchesByStages['GROUP_STAGE'].filter(x => x.status !== 'FINISHED').length === 0) &&
- (matchesByStages['GROUP_STAGE'].length !== 0) && !league.scoredStages['GROUP_STAGE']) { //end of group stage
- scoreGroups(league)
- } else
- if ((matchesByStages['ROUND_OF_16'].filter(x => x.status !== 'FINISHED').length === 0) &&
- (matchesByStages['ROUND_OF_16'].length !== 0) && !league.scoredStages['ROUND_OF_16']) {
- if (league.id === 2001) {
- scoreRoundUEFA(league, 'ROUND_OF_16', 'roundOf16')
- } else {
- scoreRound(league, 'ROUND_OF_16', 'roundOf16')
- }
- } else
- if ((matchesByStages['QUARTER_FINALS'].filter(x => x.status !== 'FINISHED').length === 0) &&
- (matchesByStages['QUARTER_FINALS'].length !== 0) && !league.scoredStages['QUARTER_FINALS']) {
- if (league.id === 2001) {
- scoreRoundUEFA(league, 'ROUND_OF_16', 'roundOf8')
- } else {
- scoreRound(league, 'ROUND_OF_16', 'roundOf8')
- }
- } else
- if ((matchesByStages['SEMI_FINALS'].filter(x => x.status !== 'FINISHED').length === 0) &&
- (matchesByStages['SEMI_FINALS'].length !== 0) && !league.scoredStages['SEMI_FINALS']) {
- if (league.id === 2001) {
- scoreRoundUEFA(league, 'ROUND_OF_16', 'roundOf4')
- } else {
- scoreRound(league, 'ROUND_OF_16', 'roundOf4')
- }
- } else
- if((matchesByStages['FINAL'].filter(x => x.status !== 'FINAL').length === 0) &&
- (matchesByStages['FINAL'].length !== 0) && !league.scoredStages['FINAL']) {
- if (league.id === 2001) {
- scoreRoundUEFA(league, 'ROUND_OF_16', 'roundOf2')
- } else {
- scoreRound(league, 'ROUND_OF_16', 'roundOf2')
- }
- }
- } catch (e) {
- errorHandler(null, null, e, 'DB: league stage check error');
- }
- });
- }
- const scoreGroups = function (league) {
- co(function*() {
- try {
- let prs = []
- const picks = yield GlobalPick.find({stage: 'GROUP_STAGE', leagueId: league._id})
- .populate({path: 'poolId', select: 'advancedPoints bonusPoints'}).lean().exec();
- const results = league.standings.filter(x => x.type === 'TOTAL' && x.stage === 'GROUP_STAGE')
- picks.forEach(pick => {
- let points = 0;
- for (let i in pick.groupStage) {
- const group = pick.groupStage[i];
- const result = results.find(x => x.group === i);
- const pickFirstPlace = result.table.find(x => x.team.id === group.firstPlace)
- const pickSecondPlace = result.table.find(x => x.team.id === group.secondPlace)
- if (pickFirstPlace.position < 3) {
- points = points + pick.poolId.advancedPoints;
- if (pickFirstPlace.position === 1) points = points + pick.poolId.bonusPoints;
- }
- if (pickSecondPlace.position < 3) {
- points = points + pick.poolId.advancedPoints;
- if (pickSecondPlace.position === 2) points = points + pick.poolId.bonusPoints;
- }
- }
- prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId._id}, { $inc: { "pools.$.score.groupStage" : points } })
- .then(() => {console.log('updated')}))
- prs.push(GlobalPick.findByIdAndUpdate(pick._id, { $set: { isScored : true } })
- .then(() => {console.log('updated')}))
- })
- yield Promise.all(prs);
- yield League.findByIdAndUpdate(league._id, {$set: {'scoredStages.GROUP_STAGE' : true}})
- } catch (e) {
- errorHandler(null, null, e, 'DB: league group stage error');
- }
- });
- }
- const scoreRoundUEFA = (league, stage, type) => {
- co(function*() {
- try {
- let prs = []
- const {matches, picks} = yield {
- matches: Match.find({'season.id': league.currentSeason.id, stage: stage, status: 'FINISHED'}).lean().exec(),
- picks: GlobalPick.find({stage: 'KNOCKOUT', leagueId: league._id, knockoutStage: stage})
- .populate({path: 'poolId', select: 'winPoints tiebreaker'}).lean().exec()
- }
- let games = {};
- matches.forEach(match => {
- const id = 'g'+match.homeTeam.id+match.awayTeam.id;
- if (!games[id]){
- games[match._id.toString()] = {
- homeTeam: {
- score: match.score.fullTime.homeTeam,
- id: match.homeTeam.id,
- wins: match.score.winner === 'HOME_TEAM' ? 1 : 0
- },
- awayTeam: {
- score: match.score.fullTime.awayTeam,
- id: match.awayTeam.id,
- wins: match.score.winner === 'AWAY_TEAM' ? 1 : 0
- }
- };
- games.homeTeamId = match.homeTeam.id;
- games.awayTeamId = match.awayTeam.id;
- } else {
- games[id].homeTeam.score += match.score.fullTime.homeTeam;
- games[id].homeTeam.wins += (match.score.winner === 'HOME_TEAM' ? 1 : 0)
- games[id].awayTeam.score += match.score.fullTime.awayTeam;
- games[id].awayTeam.wins += (match.score.winner === 'AWAY_TEAM' ? 1 : 0)
- }
- });
- let winners = [];
- for (let i in games) {
- const game = games[i];
- if (game.homeTeam.wins === 2) {
- winners.push('t' + game.homeTeam.id)
- } else if (game.awayTeam.wins === 2) {
- winners.push('t' + game.awayTeam.id)
- } else {
- winners.push('t' + (game.homeTeam.score > game.awayTeam.score ? game.homeTeam.id : game.awayTeam.id))
- }
- }
- console.log(winners)
- picks.forEach(pick => {
- let points = 0;
- pick[type].forEach(bet => {
- if (winners['t' + bet]) {
- points = points + pick.poolId.winPoints;
- }
- })
- if (stage === 'FINAL' && pick.tiebreaker === (matches[0].score.fullTime.homeTeam + matches[0].score.fullTime.awayTeam)) {
- points = points + pick.tiebreaker;
- }
- prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId._id}, { $inc: { ["pools.$.score." + type] : points } })
- .then(() => {console.log('updated')}))
- prs.push(GlobalPick.findByIdAndUpdate(pick._id, { $set: { isScored : true } })
- .then(() => {console.log('updated')}))
- })
- yield Promise.all(prs);
- yield League.findByIdAndUpdate(league._id, {$set: {['scoredStages.' + stage] : true}})
- } catch (e) {
- errorHandler(null, null, e, 'DB: league stage error');
- }
- });
- }
- const scoreRound = (league, stage, type) => {
- co(function*() {
- try {
- let prs = []
- const {matches, picks} = yield {
- matches: Match.find({'season.id': league.currentSeason.id, stage: stage, status: 'FINISHED'}).lean().exec(),
- picks: GlobalPick.find({stage: 'KNOCKOUT', leagueId: league._id})
- .populate({path: 'poolId', select: 'winPoints tiebreaker'}).lean().exec()
- }
- let winners = {};
- matches.forEach(match => {
- const winner = match.score.winner === constants.winTypes.HOME_TEAM ? match.homeTeam.id : match.awayTeam.id;
- winners['t' + winner] = true;
- });
- picks.forEach(pick => {
- let points = 0;
- pick[type].forEach(bet => {
- if (winners['t' + bet]) {
- points = points + pick.poolId.winPoints;
- }
- })
- if (stage === 'FINAL' && pick.tiebreaker === (matches[0].score.fullTime.homeTeam + matches[0].score.fullTime.awayTeam)) {
- points = points + pick.tiebreaker;
- }
- prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId._id}, { $inc: { ["pools.$.score." + type] : points } })
- .then(() => {console.log('updated')}))
- prs.push(GlobalPick.findByIdAndUpdate(pick._id, { $set: { isScored : true } })
- .then(() => {console.log('updated')}))
- })
- yield Promise.all(prs);
- yield League.findByIdAndUpdate(league._id, {$set: {['scoredStages.' + stage] : true}})
- } catch (e) {
- errorHandler(null, null, e, 'DB: league stage error');
- }
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement