ManagerZone most valuable u18 teams

Check most valuable U18 teams for current season

// ==UserScript==
// @name         ManagerZone most valuable u18 teams
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Check most valuable U18 teams for current season
// @author       You
// @match        *://www.managerzone.com/?p=league&type=*
// @grant        GM_xmlhttpRequest
// @connect      restcountries.com
// @license      MIT
// ==/UserScript==

(function () {
  "use strict";

  const sport = new URL(
    document.querySelector("#shortcut_link_thezone").href
  ).searchParams.get("sport");
  const sportId = sport === "soccer" ? 1 : 2;

  const conversionRatesToUSD = {
    USD: 1,
    R$: 2.827003,
    SEK: 7.4234,
    EUR: 0.80887,
    GBP: 0.555957,
    DKK: 6.00978,
    NOK: 6.921908,
    CHF: 1.265201,
    CAD: 1.3003,
    AUD: 1.309244,
    ILS: 4.378812,
    MXN: 10.82507,
    ARS: 2.807162,
    BOB: 7.905644,
    PYG: 5671.047,
    UYU: 28.88898,
    RUB: 28.21191,
    PLN: 3.801452,
    ISK: 71.15307,
    BGN: 1.576971,
    ZAR: 5.999531,
    THB: 43.46507,
    SIT: 190.539,
    SKK: 29.75788,
    JPY: 123.7233,
    INR: 43.66706,
    MZ: 7.4234,
    MM: 7.4234,
    点: 7.4234,
  };

  const currentFormattedDate = () => {
    return (
      (new Date().getMonth() + 1).toString().padStart(2, "0") +
      "-" +
      new Date().getDate().toString().padStart(2, "0") +
      "-" +
      new Date().getFullYear() +
      " " +
      new Date().getHours().toString().padStart(2, "0") +
      ":" +
      new Date().getMinutes().toString().padStart(2, "0") +
      ":" +
      new Date().getSeconds().toString().padStart(2, "0")
    );
  };

  const button = document.createElement("button");
  button.textContent = "Most valuable U18 teams (console)";
  button.style.margin = "0 8px";
  button.onclick = function () {
    console.log("Button clicked. Process has been started. Data is being fetched. Please wait…");
    console.log(`Start time: ${currentFormattedDate()}`);
    collectTeamIds();
  };

  const linksCopy = document.getElementById("links_copy");
  linksCopy.appendChild(button);

  const lim = 40; // 1 for top series, 4 for div 1; 13 for div 2; 40 for div 3; 121 for div 4; div 5 may vary, somewhere around 290

  function collectTeamIds() {
    const allAvgValuesXI = [];

    for (let sid = 1; sid <= lim; sid++) {
      GM_xmlhttpRequest({
        method: "GET",
        url: `https://www.managerzone.com/ajax.php?p=league&type=u18_world&sid=${sid}&tid=837021&sport=${sport}&sub=table`,
        onload: function (resp) {
          const parser = new DOMParser();
          const doc = parser.parseFromString(resp.responseText, "text/html");

          const rows = doc.querySelectorAll(".nice_table tr");
          const teamIds = [];

          for (const row of rows) {
            const link = row.querySelector("a[href*='tid=']");
            if (link) {
              const url = new URL(link.href);
              const tid = url.searchParams.get("tid");
              teamIds.push(tid);
            }
          }

          calculateAverageValues(teamIds, sid, allAvgValuesXI);
        },
      });
    }
  }

  function calculateAverageValues(teamIds, sid, allAvgValuesXI) {
    const avgValuesXI = [];

    for (const tid of teamIds) {
      GM_xmlhttpRequest({
        method: "GET",
        url: `https://www.managerzone.com/xml/team_playerlist.php?sport_id=${sportId}&team_id=${tid}`,
        onload: function (resp) {
          const parser = new DOMParser();
          const xmlDoc = parser.parseFromString(resp.responseText, "text/xml");

          const players = Array.from(xmlDoc.getElementsByTagName("Player"));

          const currency = xmlDoc
            .getElementsByTagName("TeamPlayers")[0]
            .getAttribute("teamCurrency");
          const conversionRate = conversionRatesToUSD[currency];

          let country = xmlDoc.getElementsByTagName("TeamPlayers")[0].getAttribute("countryShortname");
          if (country === "en") country = "gb";

          const playerValuesXI = players
            .filter((player) =>
              [16, 17, 18].includes(parseInt(player.getAttribute("age")))
            )
            .map(
              (player) =>
                parseInt(player.getAttribute("value")) / conversionRate
            )
            .sort((a, b) => b - a)
            .slice(0, 11);

          const totalValueXI = playerValuesXI.reduce((a, b) => a + b, 0);

          const avgValue =
            playerValuesXI.length > 0
              ? totalValueXI / playerValuesXI.length
              : 0;

          const players18 = players.filter(
            (player) => parseInt(player.getAttribute("age")) === 18
          ).length;

          const fullU18 = players.every(
            (player) => parseInt(player.getAttribute("age")) <= 18
          )
            ? "yes"
            : "no";

          GM_xmlhttpRequest({
            method: "GET",
            url: `http://www.managerzone.com/xml/manager_data.php?sport_id=${sportId}&team_id=${tid}`,
            onload: function (resp) {
              const parser = new DOMParser();
              const xmlDoc = parser.parseFromString(
                resp.responseText,
                "text/xml"
              );

              const username = xmlDoc
                .getElementsByTagName("UserData")[0]
                .getAttribute("username");

              const teamName = Array.from(xmlDoc.getElementsByTagName("Team"))
                .find((team) => team.getAttribute("sport") === sport)
                .getAttribute("teamName");

              let wlDiv = getDivisionFromSid(sid);

              avgValuesXI.push({
                team: teamName,
                user: username,
                val: avgValue.toFixed(0),
                _18anos: players18,
                div: getDivisionFromSid(sid),
                fullU18: fullU18,
                country: country,
              });
              console.log(`pushed ${teamName}, ${username}, ${wlDiv}`) // debug

              if (avgValuesXI.length === teamIds.length) {
                allAvgValuesXI.push(...avgValuesXI);

                const teamsPerDivision = 12;

                if (allAvgValuesXI.length === lim * teamsPerDivision) {
                  console.log('Done.')
                  allAvgValuesXI.sort((a, b) => b.val - a.val);

                  const atLeastThreePlayersAged18AvgValuesXI =
                    allAvgValuesXI.filter((team) => team._18anos >= 3);

                  console.log(
                    atLeastThreePlayersAged18AvgValuesXI.map(
                      ({ fullU18, ...rest }) => ({
                        ...rest,
                        val: rest.val + " USD",
                      })
                    )
                  );

                  const teamsWithFullU18 = allAvgValuesXI.filter(
                    (team) => team.fullU18 === "yes"
                  );
                  console.warn(teamsWithFullU18);

                  console.log('end');
                  console.log(new Date());
                }
              }
            },
          });
        },
      });
    }
  }

  function getDivisionFromSid(sid) {
    let group;
    if (sid == 1) {
      return "Top Series";
    } else if (sid <= 4) {
      group = sid - 1;
      return "1." + group;
    } else if (sid <= 13) {
      group = sid - 4;
      return "2." + group;
    } else if (sid <= 40) {
      group = sid - 13;
      return "3." + group;
    } else if (sid <= 121) {
      group = sid - 40;
      return "4." + group;
    } else {
      return "Undefined";
    }
  }
})();