From 66cb606368730edfc7c5a52140573364996729e3 Mon Sep 17 00:00:00 2001
From: Stephen Yeargin <stephen@yearg.in>
Date: Wed, 30 Oct 2024 23:05:16 -0500
Subject: [PATCH] Show team records in all cases

---
 src/hockey.js               | 63 ++++++++++++++++++++++++-----
 test/hockey-discord_test.js | 13 +++++-
 test/hockey-slack_test.js   | 27 ++++++++-----
 test/hockey_test.js         | 80 +++++++++++++++++++++++++++----------
 4 files changed, 140 insertions(+), 43 deletions(-)

diff --git a/src/hockey.js b/src/hockey.js
index 473751c..dcd5477 100644
--- a/src/hockey.js
+++ b/src/hockey.js
@@ -53,14 +53,44 @@ module.exports = (robot) => {
     }
   };
 
-  const postGameResults = (team, msg, cb) => msg.http(`https://api-web.nhle.com/v1/scoreboard/${team.abbreviation.toLowerCase()}/now`)
-    .get()((err, res, body) => {
+  const getScoreboard = (team) => new Promise((resolve, reject) => {
+    robot.http(`https://api-web.nhle.com/v1/scoreboard/${team.abbreviation.toLowerCase()}/now`)
+      .get()((err, res, body) => {
+        if (err) {
+          robot.logger.error(err);
+          reject(err);
+        }
+        const json = JSON.parse(body);
+        resolve(json);
+      });
+  });
+
+  const getStandings = () => new Promise((resolve, reject) => {
+    robot.http(`https://api-web.nhle.com/v1/standings/${moment().tz('America/Los_Angeles').format('YYYY-MM-DD')}`)
+      .get()((err, res, body) => {
+        if (err) {
+          robot.logger.error(err);
+          reject(err);
+        }
+        const json = JSON.parse(body);
+        resolve(json);
+      });
+  });
+
+  const getTeamRecord = (team, standings) => {
+    const teamRecord = standings.standings?.find((t) => t.teamAbbrev.default === team.abbrev);
+    return `${teamRecord.wins}-${teamRecord.losses}-${teamRecord.otLosses}`;
+  };
+
+  const postGameResults = (team, msg, cb) => Promise.all([
+    getStandings(),
+    getScoreboard(team),
+  ])
+    .then((results) => {
+      const [standings, scoreboard] = results;
+
       let gameStatus;
-      if (err) {
-        robot.logger.error(err);
-        return cb;
-      }
-      const json = JSON.parse(body);
+      const json = scoreboard;
       if (!json || (
         !json.gamesByDate
           || json.gamesByDate.length === 0)
@@ -152,8 +182,8 @@ module.exports = (robot) => {
           table.addRow(`${game.homeTeam.name.default}`);
         }
       } else {
-        table.addRow(`${game.awayTeam.name.default}`, `${game.awayTeam.score}`);
-        table.addRow(`${game.homeTeam.name.default}`, `${game.homeTeam.score}`);
+        table.addRow(`${game.awayTeam.name.default} (${getTeamRecord(game.awayTeam, standings)})`, `${game.awayTeam.score}`);
+        table.addRow(`${game.homeTeam.name.default} (${getTeamRecord(game.homeTeam, standings)})`, `${game.homeTeam.score}`);
       }
       table.removeBorder();
 
@@ -170,13 +200,19 @@ module.exports = (robot) => {
 
       const output = [];
 
+      const formatFallback = () => {
+        const date = moment(game.startTimeUTC).tz(team.time_zone).format('l');
+        const tableRows = table.getRows();
+        return `${date} - ${tableRows[0].join(' ')}, ${tableRows[1].join(' ')} (${gameStatus})`;
+      };
+
       // Say it
       switch (true) {
         case /slack/.test(robot.adapterName):
           msg.send({
             attachments: [
               {
-                fallback: `${moment(game.startTimeUTC).tz(team.time_zone).format('l')} - ${table.getRows()[0].join(' ')}, ${table.getRows()[1].join(' ')} (${gameStatus})`,
+                fallback: formatFallback(),
                 title_link: `https://www.nhl.com/gamecenter/${game.id}`,
                 author_name: 'NHL.com',
                 author_link: 'https://nhl.com',
@@ -201,6 +237,13 @@ module.exports = (robot) => {
           msg.send(table.toString());
           msg.send(`${gameStatus} - https://www.nhl.com/gamecenter/${game.id}`);
       }
+      return cb;
+    })
+    .catch((err) => {
+      robot.logger.error(err);
+      return cb;
+    })
+    .finally(() => {
       if (typeof cb === 'function') {
         return cb();
       }
diff --git a/test/hockey-discord_test.js b/test/hockey-discord_test.js
index 2de94fb..2a58ccc 100644
--- a/test/hockey-discord_test.js
+++ b/test/hockey-discord_test.js
@@ -23,6 +23,15 @@ describe('hubot-hockey for discord', () => {
     process.env.HUBOT_LOG_LEVEL = 'error';
     nock.disableNetConnect();
     room = helper.createRoom();
+
+    // Re-used in every call
+    nock('https://api-web.nhle.com')
+      .get(/\/v1\/standings\/\d{4}-\d{2}-\d{2}/)
+      .delay({
+        head: 100,
+        body: 200,
+      })
+      .replyWithFile(200, `${__dirname}/fixtures/api-web-nhle-standings.json`);
   });
 
   afterEach(() => {
@@ -71,8 +80,8 @@ describe('hubot-hockey for discord', () => {
               'hubot',
               '11/7/2023 - Scotiabank Saddledome; TV: BSSO (A) | SNW (H)\n'
               + '```\n'
-              + '  Nashville Predators   2  \n'
-              + '  Calgary Flames        3  \n'
+              + '  Nashville Predators (5-6-0)   2  \n'
+              + '  Calgary Flames (3-7-1)        3  \n'
               + '```\n'
               + '09:04 3rd - https://www.nhl.com/gamecenter/2023020186',
             ],
diff --git a/test/hockey-slack_test.js b/test/hockey-slack_test.js
index 931c6d8..8b55fbf 100644
--- a/test/hockey-slack_test.js
+++ b/test/hockey-slack_test.js
@@ -23,6 +23,15 @@ describe('hubot-hockey for slack', () => {
     process.env.HUBOT_LOG_LEVEL = 'error';
     nock.disableNetConnect();
     room = helper.createRoom();
+
+    // Re-used in every call
+    nock('https://api-web.nhle.com')
+      .get(/\/v1\/standings\/\d{4}-\d{2}-\d{2}/)
+      .delay({
+        head: 100,
+        body: 200,
+      })
+      .replyWithFile(200, `${__dirname}/fixtures/api-web-nhle-standings.json`);
   });
 
   afterEach(() => {
@@ -76,7 +85,7 @@ describe('hubot-hockey for slack', () => {
                     author_link: 'https://nhl.com',
                     author_name: 'NHL.com',
                     color: '#FFB81C',
-                    fallback: '11/7/2023 - Nashville Predators 2, Calgary Flames 3 (09:04 3rd)',
+                    fallback: '11/7/2023 - Nashville Predators (5-6-0) 2, Calgary Flames (3-7-1) 3 (09:04 3rd)',
                     footer: 'Scotiabank Saddledome; TV: BSSO (A) | SNW (H)',
                     mrkdwn_in: [
                       'text',
@@ -84,8 +93,8 @@ describe('hubot-hockey for slack', () => {
                     ],
                     text:
                     '```\n'
-                     + '  Nashville Predators   2  \n'
-                     + '  Calgary Flames        3  \n'
+                     + '  Nashville Predators (5-6-0)   2  \n'
+                     + '  Calgary Flames (3-7-1)        3  \n'
                      + '```',
                     title: '11/7/2023 - 09:04 3rd',
                     title_link: 'https://www.nhl.com/gamecenter/2023020186',
@@ -195,7 +204,7 @@ describe('hubot-hockey for slack', () => {
                   author_link: 'https://nhl.com',
                   author_name: 'NHL.com',
                   color: '#FFB81C',
-                  fallback: '12/16/2023 - Washington Capitals 0, Nashville Predators 1 (07:21 1st Intermission)',
+                  fallback: '12/16/2023 - Washington Capitals (5-4-1) 0, Nashville Predators (5-6-0) 1 (07:21 1st Intermission)',
                   footer: 'Bridgestone Arena; TV: NHLN (N) | BSSO (H) | MNMT (A)',
                   mrkdwn_in: [
                     'text',
@@ -203,8 +212,8 @@ describe('hubot-hockey for slack', () => {
                   ],
                   text:
                     '```\n'
-                    + '  Washington Capitals   0  \n'
-                    + '  Nashville Predators   1  \n'
+                    + '  Washington Capitals (5-4-1)   0  \n'
+                    + '  Nashville Predators (5-6-0)   1  \n'
                     + '```',
                   title: '12/16/2023 - 07:21 1st Intermission',
                   title_link: 'https://www.nhl.com/gamecenter/2023020468',
@@ -436,7 +445,7 @@ describe('hubot-hockey for slack', () => {
                     author_link: 'https://nhl.com',
                     author_name: 'NHL.com',
                     color: '#FFB81C',
-                    fallback: '11/7/2023 - Nashville Predators 2, Calgary Flames 4 (Final)',
+                    fallback: '11/7/2023 - Nashville Predators (5-6-0) 2, Calgary Flames (3-7-1) 4 (Final)',
                     footer: 'Scotiabank Saddledome',
                     mrkdwn_in: [
                       'text',
@@ -444,8 +453,8 @@ describe('hubot-hockey for slack', () => {
                     ],
                     text:
                     '```\n'
-                     + '  Nashville Predators   2  \n'
-                     + '  Calgary Flames        4  \n'
+                     + '  Nashville Predators (5-6-0)   2  \n'
+                     + '  Calgary Flames (3-7-1)        4  \n'
                      + '```',
                     title: '11/7/2023 - Final',
                     title_link: 'https://www.nhl.com/gamecenter/2023020186',
diff --git a/test/hockey_test.js b/test/hockey_test.js
index 9873a0b..91c1638 100644
--- a/test/hockey_test.js
+++ b/test/hockey_test.js
@@ -21,6 +21,15 @@ describe('hubot-hockey', () => {
     nock.disableNetConnect();
     room = helper.createRoom();
     nock.disableNetConnect();
+
+    // Re-used in every call
+    nock('https://api-web.nhle.com')
+      .get(/\/v1\/standings\/\d{4}-\d{2}-\d{2}/)
+      .delay({
+        head: 100,
+        body: 200,
+      })
+      .replyWithFile(200, `${__dirname}/fixtures/api-web-nhle-standings.json`);
   });
 
   afterEach(() => {
@@ -68,8 +77,8 @@ describe('hubot-hockey', () => {
             ['hubot', '11/7/2023 - Scotiabank Saddledome; TV: BSSO (A) | SNW (H)'],
             [
               'hubot',
-              '  Nashville Predators   2  \n'
-            + '  Calgary Flames        3  ',
+              '  Nashville Predators (5-6-0)   2  \n'
+            + '  Calgary Flames (3-7-1)        3  ',
             ],
             ['hubot', '09:04 3rd - https://www.nhl.com/gamecenter/2023020186'],
             ['hubot', 'Sports Club Stats: 77.7% to Make Playoffs'],
@@ -122,8 +131,8 @@ describe('hubot-hockey', () => {
             ['hubot', '12/16/2023 - Bridgestone Arena; TV: NHLN (N) | BSSO (H) | MNMT (A)'],
             [
               'hubot',
-              '  Washington Capitals   0  \n'
-            + '  Nashville Predators   1  ',
+              '  Washington Capitals (5-4-1)   0  \n'
+            + '  Nashville Predators (5-6-0)   1  ',
             ],
             ['hubot', '07:21 1st Intermission - https://www.nhl.com/gamecenter/2023020468'],
             ['hubot', 'Sports Club Stats: 77.7% to Make Playoffs'],
@@ -230,8 +239,8 @@ describe('hubot-hockey', () => {
             ['hubot', '11/7/2023 - Scotiabank Saddledome'],
             [
               'hubot',
-              '  Nashville Predators   2  \n'
-            + '  Calgary Flames        4  ',
+              '  Nashville Predators (5-6-0)   2  \n'
+            + '  Calgary Flames (3-7-1)        4  ',
             ],
             ['hubot', 'Final - https://www.nhl.com/gamecenter/2023020186'],
             ['hubot', 'Sports Club Stats: 77.7% to Make Playoffs'],
@@ -338,8 +347,8 @@ describe('hubot-hockey', () => {
             ['hubot', '12/15/2023 - PNC Arena; TV: ESPN+ (N) | HULU (N)'],
             [
               'hubot',
-              '  Nashville Predators   6  \n'
-            + '  Carolina Hurricanes   5  ',
+              '  Nashville Predators (5-6-0)   6  \n'
+            + '  Carolina Hurricanes (8-5-0)   5  ',
             ],
             ['hubot', '04:25 OT - https://www.nhl.com/gamecenter/2023020455'],
             ['hubot', 'Sports Club Stats: 77.7% to Make Playoffs'],
@@ -447,8 +456,8 @@ describe('hubot-hockey', () => {
             ['hubot', '6/15/2024 - Rogers Place; TV: ABC (N) | ESPN+ (N) | SN (N) | CBC (N) | TVAS (N)'],
             [
               'hubot',
-              '  Florida Panthers   1  \n'
-            + '  Edmonton Oilers    6  ',
+              '  Florida Panthers (6-4-1)   1  \n'
+            + '  Edmonton Oilers (2-8-1)    6  ',
             ],
             [
               'hubot',
@@ -502,8 +511,8 @@ describe('hubot-hockey', () => {
             ['hubot', '4/23/2024 - Rogers Arena'],
             [
               'hubot',
-              '  Nashville Predators   4  \n'
-            + '  Vancouver Canucks     1  ',
+              '  Nashville Predators (5-6-0)   4  \n'
+            + '  Vancouver Canucks (9-2-1)     1  ',
             ],
             [
               'hubot',
@@ -557,8 +566,8 @@ describe('hubot-hockey', () => {
             ['hubot', '5/3/2024 - Bridgestone Arena'],
             [
               'hubot',
-              '  Vancouver Canucks     1  \n'
-            + '  Nashville Predators   0  ',
+              '  Vancouver Canucks (9-2-1)     1  \n'
+            + '  Nashville Predators (5-6-0)   0  ',
             ],
             [
               'hubot',
@@ -612,8 +621,8 @@ describe('hubot-hockey', () => {
             ['hubot', '11/22/2023 - Bridgestone Arena'],
             [
               'hubot',
-              '  Calgary Flames        2  \n'
-              + '  Nashville Predators   4  ',
+              '  Calgary Flames (3-7-1)        2  \n'
+            + '  Nashville Predators (5-6-0)   4  ',
             ],
             ['hubot', 'Final - https://www.nhl.com/gamecenter/2023020288'],
             ['hubot', 'Sports Club Stats: 77.7% to Make Playoffs'],
@@ -666,8 +675,8 @@ describe('hubot-hockey', () => {
             ['hubot', '12/15/2023 - UBS Arena'],
             [
               'hubot',
-              '  Boston Bruins        5  \n'
-              + '  New York Islanders   4  ',
+              '  Boston Bruins (10-1-1)       5  \n'
+            + '  New York Islanders (5-3-3)   4  ',
             ],
             ['hubot', 'Final/SO - https://www.nhl.com/gamecenter/2023020457'],
             ['hubot', 'Sports Club Stats: 100.0% to Make Playoffs'],
@@ -772,8 +781,8 @@ describe('hubot-hockey', () => {
             ['hubot', '12/15/2023 - UBS Arena'],
             [
               'hubot',
-              '  Boston Bruins        5  \n'
-              + '  New York Islanders   4  ',
+              '  Boston Bruins (10-1-1)       5  \n'
+            + '  New York Islanders (5-3-3)   4  ',
             ],
             ['hubot', 'Final/SO - https://www.nhl.com/gamecenter/2023020457'],
           ]);
@@ -785,6 +794,24 @@ describe('hubot-hockey', () => {
       500,
     );
   });
+});
+
+describe('hubot-hockey league standings', () => {
+  let room = null;
+
+  beforeEach(() => {
+    process.env.HUBOT_LOG_LEVEL = 'error';
+    nock.disableNetConnect();
+    room = helper.createRoom();
+    nock.disableNetConnect();
+  });
+
+  afterEach(() => {
+    delete process.env.HUBOT_LOG_LEVEL;
+    Date.now = originalDateNow;
+    nock.cleanAll();
+    room.destroy();
+  });
 
   it('responds with division leader standings', (done) => {
     Date.now = () => Date.parse('Tues Nov 7 22:36:00 CST 2023');
@@ -1127,6 +1154,15 @@ describe('hubot-hockey HUBOT_HOCKEY_HIDE_ODDS=true', () => {
     nock.disableNetConnect();
     room = helper.createRoom();
     nock.disableNetConnect();
+
+    // Re-used in every call
+    nock('https://api-web.nhle.com')
+      .get(/\/v1\/standings\/\d{4}-\d{2}-\d{2}/)
+      .delay({
+        head: 100,
+        body: 200,
+      })
+      .replyWithFile(200, `${__dirname}/fixtures/api-web-nhle-standings.json`);
   });
 
   afterEach(() => {
@@ -1157,8 +1193,8 @@ describe('hubot-hockey HUBOT_HOCKEY_HIDE_ODDS=true', () => {
             ['hubot', '11/7/2023 - Scotiabank Saddledome; TV: BSSO (A) | SNW (H)'],
             [
               'hubot',
-              '  Nashville Predators   2  \n'
-            + '  Calgary Flames        3  ',
+              '  Nashville Predators (5-6-0)   2  \n'
+            + '  Calgary Flames (3-7-1)        3  ',
             ],
             ['hubot', '09:04 3rd - https://www.nhl.com/gamecenter/2023020186'],
           ]);