last requirements implemented; still a 'restore' bug to fix
[westcastle.git] / js / index.js
index 944a51b..a4a0dc7 100644 (file)
@@ -9,7 +9,7 @@ new Vue({
                        props: ['players'],
                        template: `
                                <div id="players">
-                                       <div id="active">
+                                       <div class="left">
                                                <p>Présents</p>
                                                <table class="list">
                                                        <tr v-for="p in sortedPlayers" v-if="p.available" @click="toggleAvailability(p.index)">
@@ -18,10 +18,10 @@ new Vue({
                                                        </tr>
                                                </table>
                                        </div>
-                                       <div id="inactive">
+                                       <div id="inactive" class="right">
                                                <p>Absents</p>
                                                <table class="list">
-                                                       <tr v-for="p in sortedPlayers" v-if="!p.available" @click="toggleAvailability(p.index)">
+                                                       <tr v-for="p in sortedPlayers" v-if="!p.available && p.nom!=''" @click="toggleAvailability(p.index)">
                                                                <td>{{ p.prenom }}</td>
                                                                <td>{{ p.nom }}</td>
                                                        </tr>
@@ -46,75 +46,109 @@ new Vue({
                        },
                },
                'my-ranking': {
-                       props: ['players'],
-                       data: function() {
-                               return {
-                                       sortMethod: "score",
-                               };
-                       },
+                       props: ['players','sortByScore','writeScoreToDb'],
                        template: `
                                <div id="ranking">
                                        <table class="ranking">
                                                <tr class="title">
                                                        <th>Rang</th>
                                                        <th>Joueur</th>
-                                                       <th @click="sortMethod='score'" class="scoring" :class="{active: sortMethod=='score'}">Score</th>
-                                                       <th @click="sortMethod='pdt'" class="scoring" :class="{active: sortMethod=='pdt'}">PdT</th>
+                                                       <th>Points</th>
+                                                       <th>Mini-pts</th>
                                                </tr>
-                                               <tr v-for="(p,i) in sortedPlayers">
-                                                       <td>{{ i+1 }}</td>
+                                               <tr v-for="p in sortedPlayers">
+                                                       <td>{{ p.rank }}</td>
                                                        <td>{{ p.prenom }} {{ p.nom }}</td>
-                                                       <td>{{ p.score }}</td>
                                                        <td>{{ p.pdt }}</td>
+                                                       <td>{{ p.session }}</td>
                                                </tr>
                                        </table>
+                                       <div class="button-container-vertical" style="width:200px">
+                                               <button class="btn cancel" @click="resetPlayers()">Réinitialiser</button>
+                                               <button id="restoreBtn" class="btn" @click="restoreLast()">Restaurer</button>
+                                       </div>
                                </div>
                        `,
                        computed: {
                                sortedPlayers: function() {
-                                       let sortFunc = this.sortMethod == "score"
-                                               ? this.sortByScore
-                                               : this.sortByPdt;
-                                       return this.players
-                                               .map( p => { return p; }) //to not alter original array
-                                               .sort(sortFunc);
+                                       let res = this.rankPeople();
+                                       // Add rank information (taking care of ex-aequos)
+                                       let rank = 1;
+                                       for (let i=0; i<res.length; i++)
+                                       {
+                                               if (i==0 || this.sortByScore(res[i],res[i-1]) == 0)
+                                                       res[i].rank = rank;
+                                               else //strictly lower scoring
+                                                       res[i].rank = ++rank;
+                                       }
+                                       return res;
                                },
                        },
                        methods: {
-                               sortByScore: function(a,b) {
-                                       return b.score - a.score;
+                               rankPeople: function() {
+                                       return this.players
+                                               .slice(1) //discard Toto
+                                               .map( p => { return Object.assign({}, p); }) //to not alter original array
+                                               .sort(this.sortByScore);
                                },
-                               sortByPdt: function(a,b) {
-                                       return b.pdt - a.pdt;
+                               resetPlayers: function() {
+                                       this.players
+                                               .slice(1) //discard Toto
+                                               .forEach( p => {
+                                                       p.pdt = 0;
+                                                       p.session = 0;
+                                                       p.available = 1;
+                                               });
+                                       this.writeScoreToDb();
+                                       document.getElementById("runPairing").click(); //TODO: hack...
+                               },
+                               restoreLast: function() {
+                                       let xhr = new XMLHttpRequest();
+                                       let self = this;
+                                       xhr.onreadystatechange = function() {
+                                               if (this.readyState == 4 && this.status == 200)
+                                               {
+                                                       let players = JSON.parse(xhr.responseText);
+                                                       if (players.length > 0)
+                                                       {
+                                                               players.unshift({ //add ghost 4th player for 3-players tables
+                                                                       prenom: "Toto",
+                                                                       nom: "",
+                                                                       pdt: 0,
+                                                                       session: 0,
+                                                                       available: 0,
+                                                               });
+                                                               self.players = players;
+                                                       }
+                                               }
+                                       };
+                                       xhr.open("GET", "scripts/rw_players.php?restore=1", true);
+                                       xhr.send(null);
                                },
                        },
                },
                'my-pairings': {
-                       props: ['players'],
+                       props: ['players','writeScoreToDb'],
                        data: function() {
                                return {
                                        unpaired: [],
                                        tables: [], //array of arrays of players indices
-                                       scores: [], //scores for each table (3 or 4 players)
-                                       pdts: [], //"points de table" for each table (3 or 4 players)
+                                       sessions: [], //"mini-points" for each table
                                        currentIndex: -1, //table index for scoring
+                                       scored: [], //boolean for each table index
                                };
                        },
                        template: `
                                <div id="pairings">
                                        <div v-show="currentIndex < 0">
-                                               <button class="block btn" @click="shuffle()">Appariement</button>
-                                               <div class="pairing" v-for="(table,index) in tables" :class="{scored: scores[index].length > 0}"
+                                               <button id="runPairing" class="block btn" @click="doPairings()">Nouvelle ronde</button>
+                                               <div class="pairing" v-for="(table,index) in tables" :class="{scored: scored[index]}"
                                                                @click="showScoreForm(table,index)">
                                                        <p>Table {{ index+1 }}</p>
                                                        <table>
                                                                <tr v-for="(i,j) in table">
-                                                                       <td>{{ players[i].prenom }} {{ players[i].nom }}</td>
-                                                                       <td class="score"><span v-show="pdts[index].length > 0">{{ pdts[index][j] }}</span></td>
-                                                               </tr>
-                                                               <tr v-if="table.length < 4">
-                                                                       <td>&nbsp;</td>
-                                                                       <td>&nbsp;</td>
+                                                                       <td :class="{toto: players[i].prenom=='Toto'}">{{ players[i].prenom }} {{ players[i].nom }}</td>
+                                                                       <td class="score"><span v-show="sessions[index].length > 0">{{ sessions[index][j] }}</span></td>
                                                                </tr>
                                                        </table>
                                                </div>
@@ -128,13 +162,21 @@ new Vue({
                                        <div id="scoreInput" v-if="currentIndex >= 0">
                                                <table>
                                                        <tr v-for="(index,i) in tables[currentIndex]">
-                                                               <td>{{ players[tables[currentIndex][i]].prenom }} {{ players[tables[currentIndex][i]].nom }}</td>
-                                                               <td><input type="text" v-model="pdts[currentIndex][i]" value="0"/></td>
+                                                               <td :class="{toto: players[tables[currentIndex][i]].prenom=='Toto'}">
+                                                                       {{ players[tables[currentIndex][i]].prenom }} {{ players[tables[currentIndex][i]].nom }}
+                                                               </td>
+                                                               <td><input type="text" v-model="sessions[currentIndex][i]" value="0"/></td>
                                                        </tr>
                                                </table>
-                                               <div class="button-container">
-                                                       <button class="btn" @click="setScore()">Enregistrer</button>
-                                                       <button class="btn cancel" @click="resetScore()">Annuler</button>
+                                               <div class="button-container-horizontal">
+                                                       <button class="btn validate" @click="setScore()">Enregistrer</button>
+                                                       <button class="btn" @click="currentIndex = -1">Fermer</button>
+                                               </div>
+                                               <div v-if="scored[currentIndex]" class="warning">
+                                                       Attention: un score a déjà été enregistré.
+                                                       Les points indiqués ici s'ajouteront : il faut d'abord
+                                                       <span class="link" @click="document.getElementById('restoreBtn').click()">restaurer l'état précédent.</span>
+                                                       Si c'est déjà fait, ignorer ce message :)
                                                </div>
                                        </div>
                                </div>
@@ -144,7 +186,7 @@ new Vue({
                                        // Simple case first: 4 by 4
                                        let tables = [];
                                        let currentTable = [];
-                                       let ordering = _.shuffle(_.range(this.players.length)); //TODO: take scores into account?
+                                       let ordering = _.shuffle(_.range(this.players.length));
                                        for (let i=0; i<ordering.length; i++)
                                        {
                                                if ( ! this.players[ordering[i]].available )
@@ -177,48 +219,49 @@ new Vue({
                                                else
                                                        this.unpaired = currentTable;
                                        }
+                                       // Ensure that all tables have 4 players
+                                       tables.forEach( t => {
+                                               if (t.length < 4)
+                                                       t.push(0); //index of "Toto", ghost player
+                                       });
                                        this.tables = tables;
-                                       this.scores = tables.map( t => { return []; }); //empty scores
-                                       this.pdts = tables.map( t => { return []; }); //empty pdts
-                               },
-                               shuffle: function() {
-                                       this.doPairings();
+                                       this.sessions = tables.map( t => { return []; }); //empty sessions
+                                       this.scored = tables.map( t => { return false; }); //nothing scored yet
+                                       this.currentIndex = -1; //required if reset while scoring
                                },
                                showScoreForm: function(table,index) {
-                                       if (this.scores[index].length > 0)
-                                               return; //already scored
-                                       this.scores[index] = _.times(table.length, _.constant(0));
-                                       this.pdts[index] = _.times(table.length, _.constant(0));
+                                       if (this.sessions[index].length == 0)
+                                               this.sessions[index] = _.times(table.length, _.constant(0));
                                        this.currentIndex = index;
                                },
                                setScore: function() {
-                                       let sortedPdts = this.pdts[this.currentIndex]
+                                       let sortedSessions = this.sessions[this.currentIndex]
                                                .map( (s,i) => { return {value:s, index:i}; })
                                                .sort( (a,b) => { return parseInt(b.value) - parseInt(a.value); });
-                                       let scores = [4, 2, 1, 0]; //TODO: biased for 3-players tables. TODO: ex-aequos ?!
-                                       for (let i=0; i<this.tables[this.currentIndex].length; i++)
+                                       let pdts = [4, 2, 1, 0];
+                                       // NOTE: take care of ex-aequos (spread points subtotal)
+                                       let curSum = 0, curCount = 0, start = 0;
+                                       for (let i=0; i<4; i++)
                                        {
-                                               this.players[this.tables[this.currentIndex][sortedPdts[i].index]].score += scores[i];
-                                               this.players[this.tables[this.currentIndex][i]].pdt += parseInt(this.pdts[this.currentIndex][i]);
+                                               // Update pdts:
+                                               curSum += pdts[i];
+                                               curCount++;
+                                               if (i==3 || sortedSessions[i].value > sortedSessions[i+1].value)
+                                               {
+                                                       let pdt = curSum / curCount;
+                                                       for (let j=start; j<=i; j++)
+                                                               this.players[this.tables[this.currentIndex][sortedSessions[j].index]].pdt += pdt;
+                                                       curSum = 0;
+                                                       curCount = 0;
+                                                       start = i+1;
+                                               }
+                                               // Update sessions:
+                                               this.players[this.tables[this.currentIndex][i]].session += parseInt(this.sessions[this.currentIndex][i]);
                                        }
+                                       this.scored[this.currentIndex] = true;
                                        this.currentIndex = -1;
                                        this.writeScoreToDb();
                                },
-                               resetScore: function() {
-                                       this.scores[this.currentIndex] = [];
-                                       this.pdts[this.currentIndex] = [];
-                                       this.currentIndex = -1;
-                               },
-                               writeScoreToDb: function()
-                               {
-                                       let xhr = new XMLHttpRequest();
-                                       xhr.open("POST", "scripts/rw_players.php");
-                                       xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
-                                       let orderedPlayers = this.players
-                                               .map( p => { return Object.assign({}, p); }) //deep (enough) copy
-                                               .sort( (a,b) => { return b.score - a.score; });
-                                       xhr.send("players="+encodeURIComponent(JSON.stringify(orderedPlayers)));
-                               },
                        },
                },
        },
@@ -230,14 +273,37 @@ new Vue({
                        {
                                let players = JSON.parse(xhr.responseText);
                                players.forEach( p => {
-                                       p.score = !!p.score ? parseInt(p.score) : 0;
-                                       p.pdt = !!p.pdt ? parseInt(p.pdt) : 0;
+                                       p.pdt = !!p.pdt ? parseFloat(p.pdt) : 0;
+                                       p.session = !!p.session ? parseInt(p.session) : 0;
                                        p.available = !!p.available ? p.available : 1; //use integer for fputcsv PHP func
                                });
+                               players.unshift({ //add ghost 4th player for 3-players tables
+                                       prenom: "Toto",
+                                       nom: "",
+                                       pdt: 0,
+                                       session: 0,
+                                       available: 0,
+                               });
                                self.players = players;
                        }
                };
                xhr.open("GET", "scripts/rw_players.php", true);
                xhr.send(null);
        },
+       methods: {
+               // Used both in ranking and pairings:
+               sortByScore: function(a,b) {
+                       return b.pdt - a.pdt + (Math.atan(b.session - a.session) / (Math.PI/2)) / 2;
+               },
+               writeScoreToDb: function() {
+                       let xhr = new XMLHttpRequest();
+                       xhr.open("POST", "scripts/rw_players.php");
+                       xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
+                       let orderedPlayers = this.players
+                               .slice(1) //discard Toto
+                               .map( p => { return Object.assign({}, p); }) //deep (enough) copy
+                               .sort(this.sortByScore);
+                       xhr.send("players="+encodeURIComponent(JSON.stringify(orderedPlayers)));
+               },
+       },
 });