Advertisement
SouldrinK

Waiver Wire

Feb 20th, 2020
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. const HIGHNOON = require('./lib/highnoon')
  3. const FIRESTORE = admin.firestore()
  4. let PLAYERS = {}
  5.  
  6. async function run () {
  7.   const promises = []
  8.   const waivers = await FIRESTORE.collection('waivers').get().then(wwdocs => wwdocs.docs.map(d => d.data()))
  9.   PLAYERS = await FIRESTORE.collection('players').get().then(playerDocs => {
  10.     const tmp = playerDocs.docs.map(pd => ({ id: pd.id, ...pd.data() }))
  11.     return _.keyBy(tmp, 'id')
  12.   })
  13.   console.log(`We have ${waivers.length} waivers!`)
  14.   const byLeague = _.groupBy(waivers, 'leagueId')
  15.   _.forEach(byLeague, (wires, leagueId) => {
  16.     console.log(`${wires.length} waivers found for ${leagueId}`)
  17.     // process the waivers for this league
  18.     promises.push(processLeagueWaivers(wires, leagueId))
  19.   })
  20.   // console.log(`Across ${totalLeagues} leagues!`)
  21.   return Promise.all(promises)
  22. }
  23.  
  24. run().then(() => console.log('Completed.'))
  25.  
  26. async function processLeagueWaivers(wires, leagueId) {
  27.   console.log(chalk.blue(`Processing ${wires.length} wires...`))
  28.   const claimed = {}
  29.   const owlConfig = await HIGHNOON.getOwlConfig()
  30.   // get the league
  31.   const league = await FIRESTORE.collection('standardLeagues').doc(leagueId).get().then(ld => ld.data())
  32.   // get the league users
  33.   const leagueUsers = await FIRESTORE.collection('userLeagues').where('leagueId', '==', leagueId).get().then(lud => lud.docs.map(lu => lu.data()))
  34.   const keyedLeagueUsers = _.keyBy(leagueUsers, 'userId')
  35.   // get the league rosters
  36.   const leagueRosters = await FIRESTORE.collection('standardLeagueRosters').where('leagueId', '==', leagueId).get().then(rosterDocs => {
  37.     const theRosters = rosterDocs.docs.map(rd => rd.data())
  38.     return _.keyBy(theRosters, 'userId')
  39.   })
  40.   // sort them by losses, then by leagueScore
  41.   let priority = _.orderBy(leagueUsers, ['losses', 'leagueScore'], ['desc', 'asc'])
  42.   // console.log(priority)
  43.   let sortedWaiver = _.orderBy(wires, ['priority'], ['asc'])
  44.  
  45.   // go through the priority order.  If they get a waiver, move them to the bottom.  If not, remove them.
  46.   do {
  47.     let user = priority[0].userId
  48.     let waiverIndex = sortedWaiver.findIndex(sw => sw.userId === user)
  49.     if (waiverIndex > -1 && sortedWaiver.length) {
  50.       console.log(chalk.blue(`Getting ${waiverIndex} from sortedWaiver with a length of: ${sortedWaiver.length}`))
  51.       let waiver = sortedWaiver[waiverIndex]
  52.       if (!claimed[waiver.wants]) {
  53.         if (waiver.for === 'empty') {
  54.           if (Object.keys(leagueRosters[user].players).length >= league.numRoster) {
  55.             // this claim is invalid
  56.             console.log(chalk.magenta(`Roster already full, moving on...`))
  57.             sortedWaiver.splice(waiverIndex, 1)
  58.           } else {
  59.             let { id, name, role, teamShortName } = PLAYERS[waiver.wants]
  60.             leagueRosters[user].players[waiver.wants] = {
  61.               id,
  62.               name,
  63.               points: 0,
  64.               role,
  65.               status: 'bench',
  66.               teamShortName
  67.             }
  68.             console.log(`Added ${name} to ${user} in exchange for: ${waiver.for}`)
  69.             claimed[waiver.wants] = true
  70.             priority.push(priority.shift)
  71.             sortedWaiver.splice(waiverIndex, 1)
  72.             await FIRESTORE.collection('standardLeagueRosters').doc(`${leagueId}-${user}-${owlConfig.currentWeek}`).update(leagueRosters[user])
  73.             await HIGHNOON.saveLeagueHistory({ userId: user, leagueId, type: 'Waiver', who: keyedLeagueUsers[user].displayName, message: `Obtained ${PLAYERS[waiver.wants].name} through waiver wire.` })
  74.             await HIGHNOON.sendNotification({ userId: user, icon: 'exchange-alt', link: `/leagueStandard/${leagueId}`, message: `You obtained ${PLAYERS[waiver.wants].name} through waiver wire!`, leagueId })
  75.           }
  76.         } else {
  77.           // now the fun part
  78.           if (leagueRosters[user].players[waiver.for]) {
  79.             // they have who they want to trade for, awesome!
  80.             let { id, name, role, teamShortName } = PLAYERS[waiver.wants]
  81.             delete leagueRosters[user].players[waiver.for]
  82.             leagueRosters[user].players[waiver.wants] = {
  83.               id,
  84.               name,
  85.               points: 0,
  86.               role,
  87.               status: 'bench',
  88.               teamShortName
  89.             }
  90.             // console.log(leagueRosters[user].players)
  91.             console.log(`Added ${name} to ${user} in exchanged for: ${waiver.for}`)
  92.             await FIRESTORE.collection('standardLeagueRosters').doc(`${leagueId}-${user}-${owlConfig.currentWeek}`).update(leagueRosters[user])
  93.             await HIGHNOON.saveLeagueHistory({ userId: user, leagueId, type: 'Waiver', who: keyedLeagueUsers[user].displayName, message: `Obtained ${PLAYERS[waiver.wants].name} through waiver wire.` })
  94.             await HIGHNOON.sendNotification({ userId: user, icon: 'exchange-alt', link: `/leagueStandard/${leagueId}`, message: `You obtained ${PLAYERS[waiver.wants].name} through waiver wire!`, leagueId })
  95.             claimed[waiver.wants] = true
  96.             priority.push(priority.shift)
  97.             sortedWaiver.splice(waiverIndex, 1)
  98.           } else {
  99.             // they don't have that player. Invalid waiver.
  100.             console.log(`You don't have ${PLAYERS[waiver.for].name}, so this waiver is invalid.`)
  101.            sortedWaiver.splice(waiverIndex, 1)
  102.          }
  103.        }
  104.      } else {
  105.        // remove it
  106.        console.log(chalk.red(`${waiver ? waiver.wants : '???'} was already taken.  Deleting this waiver.`))
  107.        sortedWaiver.splice(waiverIndex, 1)
  108.      }
  109.    } else {
  110.      console.log(chalk.grey('No waivers for this user, removing them.'))
  111.      priority.splice(0, 1)
  112.    }
  113.  } while (sortedWaiver.length)
  114.  console.log(chalk.yellow('--------------'))
  115.  return Promise.resolve(true)
  116. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement