Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. require('dotenv').config({path: './.env'});
  2. const League = require('../models/leagues')
  3. const Pick = require('../models/picks')
  4. const User = require('../models/users')
  5. const Match = require('../models/matches')
  6. const Team = require('../models/teams')
  7. const Pool = require('../models/pools')
  8. const GlobalPick = require('../models/globalPicks')
  9. const co = require('co')
  10. const moment = require('moment')
  11. const logger = require('../services/logger')
  12. const errorHandler = require('./helper').errorHandler;
  13. const constants = require('../../src/constants')
  14. const axiosBase = require('axios')
  15.  
  16. const bonusValue = 2;
  17.  
  18. const axios = axiosBase.create({
  19.   baseURL: 'https://api.football-data.org/',
  20.   timeout: 20000,
  21.   headers: { 'X-Auth-Token': process.env.FOOTBALL_API_KEY },
  22.   withCredentials: true
  23. });
  24.  
  25. exports.getMatches = function (leagueId, period) {
  26.   co(function*() {
  27.     try {
  28.       const result = (yield axios({
  29.         method: 'get',
  30.         url:  'v2/competitions/' + leagueId + '/matches?dateFrom=' +
  31.           moment().add(-1, period).format("YYYY-MM-DD") + '&dateTo=' + moment().add(1, period).format("YYYY-MM-DD"),
  32.       })).data;
  33.  
  34.       logger.info(module, 'matches refresh', leagueId + ': ' + result.matches.length)
  35.       if (!result.matches) return;
  36.       for (let i = 0; i < result.matches.length; i++) {
  37.         /*if (result.matches[i].status === 'IN_PLAY' || result.matches[i].status === 'PAUSED') {
  38.           console.log(result.matches[i])
  39.         }*/
  40.         Match.findOneAndUpdate({id: result.matches[i].id}, result.matches[i], {upsert: true, new: true})
  41.           .then((match) => {
  42.             if (match.status === 'FINISHED' && !match.isScored) {
  43.               if (match.score.fullTime.homeTeam > match.score.fullTime.awayTeam) match.score.winner = 'HOME_TEAM';
  44.               if (match.score.fullTime.homeTeam < match.score.fullTime.awayTeam) match.score.winner = 'AWAY_TEAM';
  45.               if (match.score.fullTime.homeTeam === match.score.fullTime.awayTeam) match.score.winner = 'DRAW';
  46.               logger.info(module, 'match values', match.id + ': ' + match.score.winner);
  47.               logger.info(module, 'match values', match.score.fullTime);
  48.             }
  49.           })
  50.       }
  51.     } catch (e) {
  52.       errorHandler(null, null, e, 'DB: get matches error: league ' + leagueId);
  53.     }
  54.   });
  55. }
  56.  
  57. exports.getTeams = function (leagueId, leagueType) {
  58.   co(function*() {
  59.     try {
  60.       const league = (yield axios({method: 'get', url:  'v2/competitions/' + leagueId + '/teams'})).data
  61.       for (let i = 0; i < league.teams.length; i++) {
  62.         let team = league.teams[i];
  63.         team[leagueType] = leagueId;
  64.         Team.updateOne({id: team.id}, team, {upsert: true, new: true})
  65.           .then((newTeam) => {
  66.             console.log(team.name + ' updated')
  67.           })
  68.       }
  69.     } catch (e) {
  70.       errorHandler(null, null, e, 'DB: get teams error');
  71.     }
  72.   });
  73. }
  74.  
  75. exports.matchdayCheck = function (leagueId) {
  76.   co(function*() {
  77.     try {
  78.       logger.info(module, 'matchday check', leagueId);
  79.  
  80.       const {currentSeason,  numberOfMatchDays} = (yield League.findOne({id: leagueId})
  81.         .select('currentSeason numberOfMatchDays').lean().exec());
  82.  
  83.       const currentMatchday = currentSeason.currentMatchday;
  84.       let lastDay = {}, ignoredMatchUpdates = [];
  85.       for(let i = currentMatchday; i <= numberOfMatchDays; i++) {
  86.         const matches = yield Match.find({'season.id': currentSeason.id, matchday: i})
  87.           .select('status matchday isScored isIgnored score').lean().exec();
  88.  
  89.         if (matches.some(x => x.status === 'FINISHED' || x.status === 'AWARDED' || x.status === 'IN_PLAY' || x.status === 'PAUSED')
  90.           || i === currentMatchday)
  91.           lastDay = {index: i, matches: matches};
  92.         else break;
  93.       }
  94.  
  95.       let matchesToScore = lastDay.matches.map(x => {
  96.         let isIgnored = x.isIgnored;
  97.         if(!x.isIgnored && (x.status === 'POSTPONED' || x.status === 'SUSPENDED' || x.status === 'CANCELED')) {
  98.           ignoredMatchUpdates.push(Match.findByIdAndUpdate(x._id, {$set: {isIgnored: true}}));
  99.           isIgnored = true;
  100.         }
  101.         return {...x, isIgnored: isIgnored};
  102.       }).filter(x => !x.isIgnored);
  103.  
  104.       yield Promise.all(ignoredMatchUpdates);
  105.  
  106.       if(!matchesToScore.every(match => match.status === 'FINISHED' || match.status === 'AWARDED'))
  107.         return;
  108.  
  109.       let isScoredUpdated = false;
  110.       for(let index in matchesToScore){
  111.         if(!matchesToScore[index].isScored){
  112.           yield scoreMatch(matchesToScore[index]);
  113.           isScoredUpdated = true;
  114.         }
  115.       }
  116.  
  117.       if(
  118.         isScoredUpdated && (yield Match.find({'season.id': currentSeason.id, matchday: lastDay.index})
  119.         .select('isScored isIgnored').lean().exec()).filter(x => !x.isIgnored).every(x => x.isScored)
  120.       )
  121.         yield scoreWDL(lastDay.matches, lastDay.index);
  122.  
  123.     } catch (e) {
  124.       errorHandler(null, null, e, 'DB: check match day error');
  125.     }
  126.   });
  127. };
  128.  
  129.  
  130. const scoreWDL = (matches, calculatedMatchday) => {
  131.   return co(function*() {
  132.     try {
  133.  
  134.       const picks = yield Pick.find({matchId: {$in: matches.map(x => x._id)}}).populate({path: 'poolId',
  135.         select: 'status matchdays gameType gameTypeDifference type'}).lean().exec();
  136.  
  137.       let totals = {}, pools = {};
  138.  
  139.       picks.forEach(pick => {
  140.         if (pick.poolId && pick.poolId.matchdays && pick.poolId.matchdays[calculatedMatchday] &&
  141.           !pick.poolId.matchdays[calculatedMatchday].isScored && pick.poolId.type === constants.NATIONAL
  142.           && !pick.poolId.gameType && pick.poolId.status === constants.poolStages.active) {
  143.           //check if onevsone mode
  144.           if (!pools[pick.poolId._id]) pools[pick.poolId._id] = {matchdays: pick.poolId.matchdays, gameTypeDifference: pick.poolId.gameTypeDifference};
  145.           if (!totals[pick.poolId._id + pick.userId]) totals[pick.poolId._id + pick.userId] = 0;
  146.           for (let i in pick.pickResult) {
  147.             if (typeof(pick.pickResult[i]) === 'number') {
  148.               totals[pick.poolId._id + pick.userId] += pick.pickResult[i];
  149.             }
  150.           }
  151.         }
  152.       });
  153.       for (let i in pools) {
  154.         logger.info(module, 'matchday check, pool calc: ', i);
  155.         const matchday = pools[i].matchdays.find(x => x.matchday === calculatedMatchday);
  156.         const gameTypeDiff = pools[i].gameTypeDifference;
  157.         matchday.users.forEach(couple => {
  158.           const total1 = totals[i + couple.user1] ? totals[i + couple.user1] : 0;
  159.           const total2 = totals[i + couple.user2] ? totals[i + couple.user2] : 0;
  160.           logger.info(module, 'couple calc');
  161.           logger.info(module, `user1 (${couple.user1}) total: ${total1}`);
  162.           logger.info(module, `user2 (${couple.user2}) total: ${total2}`);
  163.           const diff = total1 - total2;
  164.           if (diff > gameTypeDiff) { //user1 wins
  165.             User.findOneAndUpdate({_id: couple.user1, 'pools.poolId': i}, { $addToSet: { "pools.$.score.win" : calculatedMatchday} })
  166.               .then((user) => {console.log('updated')});
  167.             User.findOneAndUpdate({_id: couple.user2, 'pools.poolId': i}, { $addToSet: { "pools.$.score.lose" : calculatedMatchday} })
  168.               .then((user) => {console.log('updated')})
  169.           } else if (diff < -gameTypeDiff) { //user2 wins
  170.             User.findOneAndUpdate({_id: couple.user1, 'pools.poolId': i}, { $addToSet: { "pools.$.score.lose" : calculatedMatchday} })
  171.               .then((user) => {console.log('updated')});
  172.             User.findOneAndUpdate({_id: couple.user2, 'pools.poolId': i}, { $addToSet: { "pools.$.score.win" : calculatedMatchday} })
  173.               .then((user) => {console.log('updated')})
  174.           } else { //draw
  175.             User.findOneAndUpdate({_id: couple.user1, 'pools.poolId': i}, { $addToSet: { "pools.$.score.draw" : calculatedMatchday} })
  176.               .then((user) => {console.log('updated')});
  177.             User.findOneAndUpdate({_id: couple.user2, 'pools.poolId': i}, { $addToSet: { "pools.$.score.draw" : calculatedMatchday} })
  178.               .then((user) => {console.log('updated')})
  179.           }
  180.         });
  181.         Pool.findOneAndUpdate({_id: i, 'matchdays.matchday': calculatedMatchday},  { $set: { "matchdays.$.isScored" : true} })
  182.           .then(() => {
  183.             console.log('updated')
  184.           })
  185.       }
  186.       logger.info(module, 'Pools W/D/L updated');
  187.     } catch (e) {
  188.       errorHandler(null, null, e, 'DB: score w/d/l error');
  189.     }
  190.   })
  191. };
  192.  
  193. exports.mixedMatchdayCheck = function () {
  194.   co(function*() {
  195.     try {
  196.       logger.info(module, 'mixed matchday check')
  197.       const weekStart = moment.utc().add(-2, 'days').startOf('week').add(1, 'days').hours(0).minutes(0).seconds(0).toDate();
  198.       const weekEnd = moment.utc().add(-2, 'days').endOf('week').add(1, 'days').hours(23).minutes(59).seconds(59).toDate();
  199.  
  200.       const matches = yield Match.find({$and: [{utcDate: {$gte: weekStart}}, {utcDate: {$lte: weekEnd}}]}).select('status').lean().exec();
  201.       const picks = yield Pick.find({matchId: {$in: matches.map(x => x._id)}}).populate({path: 'poolId',
  202.         select: 'status matchdays gameType gameTypeDifference type'}).lean().exec();
  203.       let totals = {}, pools = {};
  204.  
  205.       picks.forEach(pick => {
  206.         const poolMatchday = moment.utc().diff(moment(pick.poolId.mixedStartDate), 'week') + 1;
  207.         if (pick.poolId && pick.poolId.matchdays && pick.poolId.matchdays[poolMatchday] && !pick.poolId.matchdays[poolMatchday].isScored
  208.           && !pick.poolId.gameType && pick.poolId.status === constants.poolStages.active && pick.poolId.type === constants.MIXED) {
  209.           if (!pools[pick.poolId._id]) pools[pick.poolId._id] = {matchdays: pick.poolId.matchdays, gameTypeDifference: pick.poolId.gameTypeDifference};
  210.           if (!totals[pick.poolId._id + pick.userId]) totals[pick.poolId._id + pick.userId] = 0;
  211.           for (let i in pick.pickResult) {
  212.             if (typeof(pick.pickResult[i]) === 'number') {
  213.               totals[pick.poolId._id + pick.userId] += pick.pickResult[i];
  214.             }
  215.           }
  216.         }
  217.       });
  218.  
  219.       for (let i in pools) {
  220.         logger.info(module, 'mixed matchday check, pool calc: ', i)
  221.         const poolMatchday = moment.utc().diff(moment(pools[i].mixedStartDate), 'week') + 1;
  222.         const matchday = pools[i].matchdays.find(x => x.matchday === poolMatchday);
  223.         const gameTypeDiff = pools[i].gameTypeDifference;
  224.         matchday.users.forEach(couple => {
  225.           const total1 = totals[i + couple.user1] ? totals[i + couple.user1] : 0;
  226.           const total2 = totals[i + couple.user2] ? totals[i + couple.user2] : 0;
  227.           logger.info(module, 'couple calc')
  228.           logger.info(module, `user1 (${couple.user1}) total: ${total1}`)
  229.           logger.info(module, `user2 (${couple.user2}) total: ${total2}`)
  230.           const diff = total1 - total2;
  231.           if (diff > gameTypeDiff) { //user1 wins
  232.             User.findOneAndUpdate({_id: couple.user1, 'pools.poolId': i}, { $addToSet: { "pools.$.score.win" : poolMatchday} })
  233.               .then((user) => {console.log('updated')})
  234.             User.findOneAndUpdate({_id: couple.user2, 'pools.poolId': i}, { $addToSet: { "pools.$.score.lose" : poolMatchday} })
  235.               .then((user) => {console.log('updated')})
  236.           } else if (diff < -gameTypeDiff) { //user2 wins
  237.             User.findOneAndUpdate({_id: couple.user1, 'pools.poolId': i}, { $addToSet: { "pools.$.score.lose" : poolMatchday} })
  238.               .then((user) => {console.log('updated')})
  239.             User.findOneAndUpdate({_id: couple.user2, 'pools.poolId': i}, { $addToSet: { "pools.$.score.win" : poolMatchday} })
  240.               .then((user) => {console.log('updated')})
  241.           } else { //draw
  242.             User.findOneAndUpdate({_id: couple.user1, 'pools.poolId': i}, { $addToSet: { "pools.$.score.draw" : poolMatchday} })
  243.               .then((user) => {console.log('updated')})
  244.             User.findOneAndUpdate({_id: couple.user2, 'pools.poolId': i}, { $addToSet: { "pools.$.score.draw" : poolMatchday} })
  245.               .then((user) => {console.log('updated')})
  246.           }
  247.         });
  248.         Pool.findOneAndUpdate({_id: i, 'matchdays.matchday': poolMatchday},  { $set: { "matchdays.$.isScored" : true} })
  249.           .then(() => {
  250.             console.log('updated')
  251.           })
  252.       }
  253.     } catch (e) {
  254.       errorHandler(null, null, e, 'DB: mixed matchday check error');
  255.     }
  256.   });
  257. }
  258.  
  259. exports.getStandings = function (leagueId) {
  260.   co(function*() {
  261.     try {
  262.       const league = (yield axios({method: 'get', url:  'v2/competitions/' + leagueId + '/standings'})).data
  263.       const buf = constants.leagues.find(x => x.value === leagueId)
  264.       const order = buf ? buf.order : 1000
  265.       const numberOfMatchDays = buf ? buf.numberOfMatchDays : null
  266.       yield League.updateOne({id: leagueId}, {
  267.         $set: {
  268.           standings: league.standings,
  269.           importance: order,
  270.           numberOfMatchDays: numberOfMatchDays,
  271.         }
  272.       })
  273.     } catch (e) {
  274.       errorHandler(null, null, e, 'DB: get standings error');
  275.     }
  276.   });
  277. }
  278.  
  279. exports.getLeagues = function () {
  280.   co(function*() {
  281.     try {
  282.       const result = (yield axios({
  283.         method: 'get',
  284.         url:  'v2/competitions/'
  285.       })).data;
  286.  
  287.       if (!result.competitions) return;
  288.       yield Promise.all(result.competitions.map(league => League.updateOne({id: league.id}, league, {upsert: true})))
  289.     } catch (e) {
  290.       errorHandler(null, null, e, 'DB: get leagues error');
  291.     }
  292.   });
  293. }
  294.  
  295. const scoreMatch = (match) => {
  296.   return co(function*() {
  297.     try {
  298.       const picks = yield Pick.find({matchId: match._id, isScored: false}).populate('poolId userId').lean().exec();
  299.       //For each kind of the bet the users that bet against the 70% of the pool will obtain some bonus.
  300.       // We will count all values of all types and we will result later:
  301.       let poolsPercentCount = {};
  302.       picks.forEach(pick => {
  303.         if (!pick.poolId || pick.poolId.status !== constants.poolStages.active) return;
  304.         if (pick.poolId.bonus) {
  305.           for (let j in pick) {
  306.             const betAddress = j === 'gameScore' ? pick[j].home + '-' + pick[j].away : pick[j];
  307.             if (!poolsPercentCount[pick.poolId._id + j]) poolsPercentCount[pick.poolId._id + j] = {value: 0, moreThan70Type: null};
  308.             if (!poolsPercentCount[pick.poolId._id + j + betAddress]) poolsPercentCount[pick.poolId._id + j + betAddress] = 0;
  309.             poolsPercentCount[pick.poolId._id + j].value++;
  310.             poolsPercentCount[pick.poolId._id + j + betAddress]++;
  311.             poolsPercentCount[pick.poolId._id + j].moreThan70Type =
  312.               poolsPercentCount[pick.poolId._id + j + betAddress] / poolsPercentCount[pick.poolId._id + j].value > 0.7 ? betAddress : null;
  313.           }
  314.         }
  315.       });
  316.  
  317.       let prs = [];
  318.       for (let i = 0; i < picks.length; i++) {
  319.         const pick = picks[i];
  320.         if (!pick.poolId ) continue;
  321.         let bonus = 0, bonusTypes = {};
  322.         for (let j in pick) {
  323.           const bet = pick[j];
  324.           switch (j) {
  325.             case constants.betTypes.wdl:
  326.               if (match.score.winner.toString() === bet.toString()) {
  327.                 prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
  328.                   { $inc: { "pools.$.score.wdl" : pick.poolId.betTypes.wdl.value} }));
  329.                 prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.wdl': pick.poolId.betTypes.wdl.value}}))
  330.                 bonusTypes.wdl = (pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.wdl] &&
  331.                   poolsPercentCount[pick.poolId._id + constants.betTypes.wdl].moreThan70Type &&
  332.                   poolsPercentCount[pick.poolId._id + constants.betTypes.wdl].moreThan70Type !== bet) ? bonusValue : 0;
  333.                 bonus = bonus + bonusTypes.wdl;
  334.               }
  335.               break;
  336.             case constants.betTypes.un15:
  337.               if (match.score.fullTime.homeTeam + match.score.fullTime.awayTeam < 1.5 === bet) {
  338.                 prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
  339.                   { $inc: { "pools.$.score.un15" : pick.poolId.betTypes.un15.value } }))
  340.                 prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.un15': pick.poolId.betTypes.un15.value}}))
  341.                 bonusTypes.un15 =  ((pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.un15] &&
  342.                   poolsPercentCount[pick.poolId._id + constants.betTypes.un15].moreThan70Type &&
  343.                   poolsPercentCount[pick.poolId._id + constants.betTypes.un15].moreThan70Type !== bet) ? bonusValue : 0);
  344.                 bonus = bonus + bonusTypes.un15;
  345.               }
  346.               break;
  347.             case constants.betTypes.un25:
  348.               if (match.score.fullTime.homeTeam + match.score.fullTime.awayTeam < 2.5 === bet) {
  349.                 prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
  350.                   { $inc: { "pools.$.score.un25" : pick.poolId.betTypes.un25.value } }))
  351.                 prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.un25': pick.poolId.betTypes.un25.value}}))
  352.                 bonusTypes.un25 =  ((pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.un25] &&
  353.                   poolsPercentCount[pick.poolId._id + constants.betTypes.un25].moreThan70Type &&
  354.                   poolsPercentCount[pick.poolId._id + constants.betTypes.un25].moreThan70Type !== bet) ? bonusValue : 0);
  355.                 bonus = bonus + bonusTypes.un25;
  356.               }
  357.               break;
  358.             case constants.betTypes.un35:
  359.               if (match.score.fullTime.homeTeam + match.score.fullTime.awayTeam < 3.5 === bet) {
  360.                 prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
  361.                   { $inc: { "pools.$.score.un35" : pick.poolId.betTypes.un35.value } }))
  362.                 prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.un35': pick.poolId.betTypes.un35.value}}))
  363.                 bonusTypes.un35 = ((pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.un35] &&
  364.                   poolsPercentCount[pick.poolId._id + constants.betTypes.un35].moreThan70Type &&
  365.                   poolsPercentCount[pick.poolId._id + constants.betTypes.un35].moreThan70Type !== bet) ? bonusValue : 0);
  366.                 bonus = bonus + bonusTypes.un35;
  367.               }
  368.               break;
  369.             case constants.betTypes.hasGoal:
  370.               if (((match.score.fullTime.homeTeam > 0) && (match.score.fullTime.awayTeam > 0) && !!bet) ||
  371.                 ((match.score.fullTime.homeTeam === 0 || match.score.fullTime.awayTeam === 0) && !bet)) {
  372.                 prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
  373.                   { $inc: { "pools.$.score.hasGoal" : pick.poolId.betTypes.hasGoal.value } }))
  374.                 prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.hasGoal': pick.poolId.betTypes.hasGoal.value}}))
  375.                 bonusTypes.hasGoal = ((pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.hasGoal] &&
  376.                   poolsPercentCount[pick.poolId._id + constants.betTypes.hasGoal].moreThan70Type &&
  377.                   poolsPercentCount[pick.poolId._id + constants.betTypes.hasGoal].moreThan70Type !== bet) ? bonusValue : 0);
  378.                 bonus = bonus + bonusTypes.hasGoal;
  379.               }
  380.               break;
  381.  
  382.             case constants.betTypes.doubleChance:
  383.               if ((bet === constants.doubleChance.homeOrDraw && (match.score.winner === constants.winTypes.HOME_TEAM || match.score.winner === constants.winTypes.DRAW)) ||
  384.                 (bet === constants.doubleChance.homeOrAway && (match.score.winner === constants.winTypes.HOME_TEAM || match.score.winner === constants.winTypes.AWAY_TEAM)) ||
  385.                 (bet === constants.doubleChance.awayOrDraw && (match.score.winner === constants.winTypes.DRAW || match.score.winner === constants.winTypes.AWAY_TEAM))) {
  386.                 prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
  387.                   { $inc: { "pools.$.score.doubleChance" : pick.poolId.betTypes.doubleChance.value } }))
  388.                 prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.doubleChance': pick.poolId.betTypes.doubleChance.value}}))
  389.                 bonusTypes.doubleChance = ((pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.doubleChance] &&
  390.                   poolsPercentCount[pick.poolId._id + constants.betTypes.doubleChance].moreThan70Type &&
  391.                   poolsPercentCount[pick.poolId._id + constants.betTypes.doubleChance].moreThan70Type !== bet) ? bonusValue : 0);
  392.                 bonus = bonus + bonusTypes.doubleChance;
  393.               }
  394.               break;
  395.             case constants.betTypes.gameScore:
  396.               if ((match.score.fullTime.homeTeam === bet.home) && (match.score.fullTime.awayTeam === bet.away)) {
  397.                 prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
  398.                   { $inc: { "pools.$.score.gameScore" : pick.poolId.betTypes.gameScore.value } }))
  399.                 prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.gameScore': pick.poolId.betTypes.gameScore.value}}))
  400.                 bonusTypes.gameScore = ((pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.gameScore] &&
  401.                   poolsPercentCount[pick.poolId._id + constants.betTypes.gameScore].moreThan70Type &&
  402.                   poolsPercentCount[pick.poolId._id + constants.betTypes.gameScore].moreThan70Type !== (bet.home + '-' + bet.away)) ? bonusValue : 0);
  403.                 bonus = bonus + bonusTypes.gameScore;
  404.               }
  405.               break;
  406.             case constants.betTypes.totalGoals:
  407.               if ((match.score.fullTime.homeTeam + match.score.fullTime.awayTeam) === bet) {
  408.                 prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
  409.                   { $inc: { "pools.$.score.totalGoals" : pick.poolId.betTypes.totalGoals.value } }))
  410.                 prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.totalGoals': pick.poolId.betTypes.totalGoals.value}}))
  411.                 bonusTypes.totalGoals = ((pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.totalGoals] &&
  412.                   poolsPercentCount[pick.poolId._id + constants.betTypes.totalGoals].moreThan70Type &&
  413.                   poolsPercentCount[pick.poolId._id + constants.betTypes.totalGoals].moreThan70Type !== bet) ? bonusValue : 0);
  414.                 bonus = bonus + bonusTypes.totalGoals;
  415.               }
  416.               break;
  417.             case constants.betTypes.handicap:
  418.               const diff = match.score.fullTime.homeTeam - match.score.fullTime.awayTeam;
  419.               if ((bet === constants.handicap.vXh1plus && diff === 1) ||
  420.                 (bet === constants.handicap.vXh1minus && diff === -1) ||
  421.                 (bet === constants.handicap.v1h1 && diff > 1) ||
  422.                 (bet === constants.handicap.v2h1 && diff < -1) ||
  423.                 (bet === constants.handicap.other && diff === 0)) {
  424.                 prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
  425.                   { $inc: { "pools.$.score.handicap" : pick.poolId.betTypes.handicap.value } }))
  426.                 prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.handicap': pick.poolId.betTypes.handicap.value}}))
  427.                 bonusTypes.handicap = ((pick.poolId.bonus && poolsPercentCount[pick.poolId._id + constants.betTypes.handicap] &&
  428.                   poolsPercentCount[pick.poolId._id + constants.betTypes.handicap].moreThan70Type &&
  429.                   poolsPercentCount[pick.poolId._id + constants.betTypes.handicap].moreThan70Type !== bet) ? bonusValue : 0);
  430.                 bonus = bonus + bonusTypes.handicap;
  431.               }
  432.               break;
  433.           }
  434.         }
  435.         prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId},
  436.           { $inc: { "pools.$.score.bonus" : bonus } }))
  437.         prs.push(Pick.findByIdAndUpdate(pick._id, {$set: {'pickResult.bonus': bonus, 'pickResult.bonusTypes': bonusTypes, isScored: true}}))
  438.       }
  439.       yield Promise.all(prs);
  440.       yield Match.findByIdAndUpdate(match._id, {$set: {isScored: true}});
  441.       logger.info(module, 'Match scored', match._id);
  442.     } catch (e) {
  443.       errorHandler(null, null, e, 'DB: score match error');
  444.     }
  445.   });
  446. };
  447.  
  448. exports.leagueStageCheck = function (leagueId) {
  449.   co(function*() {
  450.     try {
  451.       let league = yield League.findOne({id: leagueId}).select('currentSeason scoredStages standings').lean().exec();
  452.       if (!league.scoredStages){
  453.         league = yield League.findByIdAndUpdate(league._id, {$set: {'scoredStages': {}}}, {new: true});
  454.       }
  455.       const matches = yield Match.find({'season.id': league.currentSeason.id}).select('stage status').lean().exec();
  456.       let matchesByStages = {
  457.         GROUP_STAGE: [],
  458.         ROUND_OF_16: [],
  459.         QUARTER_FINALS: [],
  460.         SEMI_FINALS: [],
  461.         FINAL: []
  462.       };
  463.       matches.forEach((match) =>{
  464.         if (matchesByStages[match.stage]){
  465.           matchesByStages[match.stage].push(match)
  466.         }
  467.       });
  468.       if ((matchesByStages['GROUP_STAGE'].filter(x => x.status !== 'FINISHED').length === 0) &&
  469.         (matchesByStages['GROUP_STAGE'].length !== 0) && !league.scoredStages['GROUP_STAGE']) { //end of group stage
  470.         scoreGroups(league)
  471.       } else
  472.       if ((matchesByStages['ROUND_OF_16'].filter(x => x.status !== 'FINISHED').length === 0) &&
  473.         (matchesByStages['ROUND_OF_16'].length !== 0) && !league.scoredStages['ROUND_OF_16']) {
  474.         if (league.id === 2001) {
  475.           scoreRoundUEFA(league, 'ROUND_OF_16', 'roundOf16')
  476.         } else {
  477.           scoreRound(league, 'ROUND_OF_16', 'roundOf16')
  478.         }
  479.       } else
  480.       if ((matchesByStages['QUARTER_FINALS'].filter(x => x.status !== 'FINISHED').length === 0) &&
  481.         (matchesByStages['QUARTER_FINALS'].length !== 0) && !league.scoredStages['QUARTER_FINALS']) {
  482.         if (league.id === 2001) {
  483.           scoreRoundUEFA(league, 'ROUND_OF_16', 'roundOf8')
  484.         } else {
  485.           scoreRound(league, 'ROUND_OF_16', 'roundOf8')
  486.         }
  487.       } else
  488.       if ((matchesByStages['SEMI_FINALS'].filter(x => x.status !== 'FINISHED').length === 0) &&
  489.         (matchesByStages['SEMI_FINALS'].length !== 0) && !league.scoredStages['SEMI_FINALS']) {
  490.         if (league.id === 2001) {
  491.           scoreRoundUEFA(league, 'ROUND_OF_16', 'roundOf4')
  492.         } else {
  493.           scoreRound(league, 'ROUND_OF_16', 'roundOf4')
  494.         }
  495.       } else
  496.       if((matchesByStages['FINAL'].filter(x => x.status !== 'FINAL').length === 0) &&
  497.         (matchesByStages['FINAL'].length !== 0) && !league.scoredStages['FINAL']) {
  498.         if (league.id === 2001) {
  499.           scoreRoundUEFA(league, 'ROUND_OF_16', 'roundOf2')
  500.         } else {
  501.           scoreRound(league, 'ROUND_OF_16', 'roundOf2')
  502.         }
  503.       }
  504.     } catch (e) {
  505.       errorHandler(null, null, e, 'DB: league stage check error');
  506.     }
  507.   });
  508. }
  509.  
  510. const scoreGroups = function (league) {
  511.   co(function*() {
  512.     try {
  513.       let prs = []
  514.       const picks = yield GlobalPick.find({stage: 'GROUP_STAGE', leagueId: league._id})
  515.         .populate({path: 'poolId', select: 'advancedPoints bonusPoints'}).lean().exec();
  516.       const results = league.standings.filter(x => x.type === 'TOTAL' && x.stage === 'GROUP_STAGE')
  517.       picks.forEach(pick => {
  518.         let points = 0;
  519.         for (let i in pick.groupStage) {
  520.           const group = pick.groupStage[i];
  521.           const result = results.find(x => x.group === i);
  522.           const pickFirstPlace = result.table.find(x => x.team.id === group.firstPlace)
  523.           const pickSecondPlace = result.table.find(x => x.team.id === group.secondPlace)
  524.           if (pickFirstPlace.position < 3) {
  525.             points = points + pick.poolId.advancedPoints;
  526.             if (pickFirstPlace.position === 1) points = points + pick.poolId.bonusPoints;
  527.           }
  528.  
  529.           if (pickSecondPlace.position < 3) {
  530.             points = points + pick.poolId.advancedPoints;
  531.             if (pickSecondPlace.position === 2) points = points + pick.poolId.bonusPoints;
  532.           }
  533.  
  534.         }
  535.         prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId._id}, { $inc: { "pools.$.score.groupStage" : points } })
  536.           .then(() => {console.log('updated')}))
  537.         prs.push(GlobalPick.findByIdAndUpdate(pick._id, { $set: { isScored : true } })
  538.           .then(() => {console.log('updated')}))
  539.       })
  540.       yield Promise.all(prs);
  541.       yield League.findByIdAndUpdate(league._id, {$set: {'scoredStages.GROUP_STAGE' : true}})
  542.     } catch (e) {
  543.       errorHandler(null, null, e, 'DB: league group stage error');
  544.     }
  545.   });
  546. }
  547.  
  548. const scoreRoundUEFA = (league, stage, type) => {
  549.   co(function*() {
  550.     try {
  551.       let prs = []
  552.       const {matches, picks} = yield {
  553.         matches: Match.find({'season.id': league.currentSeason.id, stage: stage, status: 'FINISHED'}).lean().exec(),
  554.         picks:  GlobalPick.find({stage: 'KNOCKOUT', leagueId: league._id, knockoutStage: stage})
  555.           .populate({path: 'poolId', select: 'winPoints tiebreaker'}).lean().exec()
  556.       }
  557.  
  558.       let games = {};
  559.       matches.forEach(match => {
  560.         const id = 'g'+match.homeTeam.id+match.awayTeam.id;
  561.         if (!games[id]){
  562.           games[match._id.toString()] = {
  563.             homeTeam: {
  564.               score: match.score.fullTime.homeTeam,
  565.               id: match.homeTeam.id,
  566.               wins: match.score.winner === 'HOME_TEAM' ? 1 : 0
  567.             },
  568.             awayTeam: {
  569.               score: match.score.fullTime.awayTeam,
  570.               id: match.awayTeam.id,
  571.               wins: match.score.winner === 'AWAY_TEAM' ? 1 : 0
  572.             }
  573.           };
  574.           games.homeTeamId = match.homeTeam.id;
  575.           games.awayTeamId = match.awayTeam.id;
  576.         } else {
  577.           games[id].homeTeam.score += match.score.fullTime.homeTeam;
  578.           games[id].homeTeam.wins += (match.score.winner === 'HOME_TEAM' ? 1 : 0)
  579.           games[id].awayTeam.score += match.score.fullTime.awayTeam;
  580.           games[id].awayTeam.wins += (match.score.winner === 'AWAY_TEAM' ? 1 : 0)
  581.         }
  582.       });
  583.       let winners = [];
  584.       for (let i in games) {
  585.         const game = games[i];
  586.         if (game.homeTeam.wins === 2) {
  587.           winners.push('t' + game.homeTeam.id)
  588.         } else if (game.awayTeam.wins === 2) {
  589.           winners.push('t' + game.awayTeam.id)
  590.         } else {
  591.           winners.push('t' + (game.homeTeam.score > game.awayTeam.score ? game.homeTeam.id : game.awayTeam.id))
  592.         }
  593.       }
  594.       console.log(winners)
  595.  
  596.       picks.forEach(pick => {
  597.         let points = 0;
  598.         pick[type].forEach(bet => {
  599.           if (winners['t' + bet]) {
  600.             points = points + pick.poolId.winPoints;
  601.           }
  602.         })
  603.         if (stage === 'FINAL' && pick.tiebreaker === (matches[0].score.fullTime.homeTeam + matches[0].score.fullTime.awayTeam)) {
  604.           points = points + pick.tiebreaker;
  605.         }
  606.         prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId._id}, { $inc: { ["pools.$.score." + type] : points } })
  607.           .then(() => {console.log('updated')}))
  608.         prs.push(GlobalPick.findByIdAndUpdate(pick._id, { $set: { isScored : true } })
  609.           .then(() => {console.log('updated')}))
  610.  
  611.       })
  612.       yield Promise.all(prs);
  613.  
  614.       yield League.findByIdAndUpdate(league._id, {$set: {['scoredStages.' + stage] : true}})
  615.  
  616.     } catch (e) {
  617.       errorHandler(null, null, e, 'DB: league stage error');
  618.     }
  619.   });
  620. }
  621.  
  622. const scoreRound = (league, stage, type) => {
  623.   co(function*() {
  624.     try {
  625.       let prs = []
  626.       const {matches, picks} = yield {
  627.         matches: Match.find({'season.id': league.currentSeason.id, stage: stage, status: 'FINISHED'}).lean().exec(),
  628.         picks:  GlobalPick.find({stage: 'KNOCKOUT', leagueId: league._id})
  629.           .populate({path: 'poolId', select: 'winPoints tiebreaker'}).lean().exec()
  630.       }
  631.  
  632.       let winners = {};
  633.       matches.forEach(match => {
  634.         const winner = match.score.winner === constants.winTypes.HOME_TEAM ? match.homeTeam.id : match.awayTeam.id;
  635.         winners['t' + winner] = true;
  636.       });
  637.  
  638.       picks.forEach(pick => {
  639.         let points = 0;
  640.         pick[type].forEach(bet => {
  641.           if (winners['t' + bet]) {
  642.             points = points + pick.poolId.winPoints;
  643.           }
  644.         })
  645.         if (stage === 'FINAL' && pick.tiebreaker === (matches[0].score.fullTime.homeTeam + matches[0].score.fullTime.awayTeam)) {
  646.           points = points + pick.tiebreaker;
  647.         }
  648.         prs.push(User.findOneAndUpdate({_id: pick.userId, 'pools.poolId': pick.poolId._id}, { $inc: { ["pools.$.score." + type] : points } })
  649.           .then(() => {console.log('updated')}))
  650.         prs.push(GlobalPick.findByIdAndUpdate(pick._id, { $set: { isScored : true } })
  651.           .then(() => {console.log('updated')}))
  652.  
  653.       })
  654.       yield Promise.all(prs);
  655.  
  656.       yield League.findByIdAndUpdate(league._id, {$set: {['scoredStages.' + stage] : true}})
  657.  
  658.     } catch (e) {
  659.       errorHandler(null, null, e, 'DB: league stage error');
  660.     }
  661.   });
  662. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement