ajaxDisplay.html.twig 19.8 KB
Newer Older
Mat's avatar
Mat committed
1 2 3
{% extends '@Potage/layout.html.twig' %}

{% block title %}
4
    Collection de légumes
Mat's avatar
Mat committed
5 6
{% endblock %}

7
{% block searchbar %}
8
    <nav class="navbar navbar-expand-lg navbar-light navbar-search">
9
        <form class="form-inline my-2 my-lg-0" style="margin: auto;">
Mat's avatar
Mat committed
10
            <div class="input-group input-group-lg">
11 12 13
                <div class="input-group-prepend">
                    <span class="input-group-text" id="inputGroup-sizing-lg"><i class="fas fa-search"></i></span>
                </div>
14 15
                <input id="search" type="search" class="form-control" placeholder="Rechercher"
                       aria-label="LargeSearch" aria-describedby="inputGroup-sizing-sm">
16
            </div>
Mat's avatar
Mat committed
17
            <span id="rebours"></span>
18
        </form>
19 20 21
        <b>
            <a href="{{ path('potage_offre_ajax_display') }}" class="nav-laterale right text-secondary">Les offres<i class="fas fa-long-arrow-alt-right  fa-fw"></i></a>
        </b>
22
    </nav>
23
{% endblock %}
24

25 26
{% block headerContent %}
    <div class="row">
27
        <div class="col left hd-1">
28

29 30 31 32 33
            <h1>{{ block('title') }}</h1>
            <div>
                <span id="t_rows">{{ nbRows }}</span> légumes
                <span id="t_pages"></span>
                {# TODO nbRows doit être rafraichit si on crée ou si on efface #}
34
            </div>
35 36 37 38 39 40 41 42 43 44 45
            <form id="pagination">
                <select class="custom-select custom-select-sm" title="Pagination">
                    <option value="-1" selected>Pagination</option>
                    <option value="5">5</option>
                    <option value="10">10</option>
                    <option value="20">20</option>
                    <option value="50">50</option>
                    <option value="100">100</option>
                </select>
            </form>
        </div>
46
        <div class="col right hd-1">
47
            <div style="margin-top: 0.65em; margin-bottom: 1em;">
Mat's avatar
Mat committed
48
                <a href="javascript: void(0);" class="btn btn-outline-dark mb-2 btn-reload">
49 50 51
                    <i class="fas fa-sync-alt"></i>
                    Rafraîchir la liste
                </a>
Mat's avatar
Mat committed
52
                <a href="javascript: void(0);" class="btn btn-dark mb-2 btn-create" data-toggle="modal" data-target=".form-legume-modal">
53 54 55
                    <i class="fas fa-plus"></i>
                    Ajouter un nouveau légume
                </a>
56 57
            </div>
        </div>
58 59 60 61 62
    </div>
{% endblock %}

{% block sectionContent %}
    <section>
63

64 65 66 67 68
        <nav id="pagenav" aria-label="page navigation legume">
            <ul class="pagination justify-content-center">
            </ul>
        </nav>

69
        {% include '@Potage/Legume/ajaxForm.html.twig' %}
70
        {% include '@Potage/OffreLegumes/ajaxInsertForm.html.twig' %}
71

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
        <table id="maintab" class="table legumes table-striped">
            <thead>
                <tr>
                    <th scope="col">
                        <a href="javascript: void(0);" id="id" class="btn-sort">#</a>
                    </th>
                    <th scope="col">
                        <a href="javascript: void(0);" id="fruit" class="btn-sort" title="Fruit ou Légume">F/L</a>
                    </th>
                    <th scope="col">
                        <a href="javascript: void(0);" id="revente" class="btn-sort" title="Revente">R</a>
                    </th>
                    <th scope="col">
                        <a href="javascript: void(0);" id="nom" class="btn-sort">Nom</a>
                    </th>
                    <th scope="col">
                        <a href="javascript: void(0);" id="image" class="btn-sort">Vignette</a>
                    </th>
                    <th scope="col">
                        <a href="javascript: void(0);" id="description" class="btn-sort">Description</a>
                    </th>
                    <th scope="col">
                        <a href="javascript: void(0);" id="prixUnitaire" class="btn-sort">Prix</a>
                    </th>
                    <th scope="col">
                        <a href="javascript: void(0);" id="unite" class="btn-sort">Unité</a>
                    </th>
                    <th scope="col">
                        <a>Action</a>
                    </th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
107 108

    </section>
Mat's avatar
Mat committed
109 110 111
{% endblock %}

{% block customJS %}
112
<script type="text/javascript" src="{{ asset('js/functions.js') }}"></script>
113
<script type="text/javascript" src="{{ asset('js/ajax_functions.js') }}"></script>
Mat's avatar
Mat committed
114 115
<script type="text/javascript">

116 117 118 119 120 121

    /*
    *   Recharge la table
    */
    function reloadTableLegume(paginate)
    {
122 123
        tbody.innerHTML = null;

124
        //console.log(paginate);
125
        let legumeURL = Routing.generate('api_legume_read', paginate);
126 127

        displayPagination(paginate);
128
        getTableBodyLegume(legumeURL);
129 130 131 132
    }


    /*
133
     *   Affiche le bloc de pagination
134 135 136 137 138 139 140 141 142 143
     */
    function displayPagination(paginate)
    {
        let pageNav = document.querySelector('nav#pagenav ul.pagination');
        AJAX('GET', Routing.generate('api_legume_read', paginate), function()
        {
            tpage.innerHTML = null;
            pageNav.innerHTML = null;
            let perPage = paginate.step;
            if (total > perPage)
144
            {
145 146 147
                let nbPages = Math.ceil(total / perPage);
                let currentPage = paginate.page;
                for (let i = 1; i <= nbPages; i++)
148
                {
149 150 151 152
                    let pageItem = document.createElement('li');
                    pageItem.classList.add('page-item', (i === currentPage) ? 'active' : null);
                    let pageItemChild = document.createElement((i === currentPage) ? 'span' : 'a');
                    pageItemChild.classList.add('page-link');
Mat's avatar
Mat committed
153
                    pageItemChild.textContent = i.toString();
154
                    if (i !== currentPage)
155
                    {
156
                        pageItemChild.addEventListener('click', function()
157
                        {
158 159 160
                            paginate.page = i;
                            reloadTableLegume(paginate);
                        });
161
                    }
162 163
                    pageItem.appendChild(pageItemChild);
                    pageNav.appendChild(pageItem);
164
                }
165 166
                tpage.innerHTML = '— page '+ currentPage + ' sur '+ nbPages;
            }
167 168
        });
    }
169 170 171 172 173 174 175 176 177 178 179


    /*
    *   Recharge la table avec la fonction de recherche
    */
    function reloadTableSearchLegume(qString)
    {
        let searchURL = Routing.generate('api_legume_search', qString);

        removePagination();
        refreshSearchStats(searchURL);
180 181 182 183 184 185

        tbody.innerHTML = null;
        sleep(1000).then(() => {
            //  TODO le sleep est encore buggé
            getTableBodyLegume(searchURL);
        });
186 187 188 189 190 191
    }


    /*
    *   Enlève le bloc de pagination
    */
192 193 194 195 196 197
    function removePagination()
    {
        let pageNav = document.querySelector('nav#pagenav ul.pagination');
        tpage.innerHTML = null;
        pageNav.innerHTML = null;
    }
198 199 200 201 202


    /*
    *   Rafraîchit les stats de la page
    */
Mat's avatar
hop  
Mat committed
203 204 205 206 207 208 209
    function refreshSearchStats(searchURL)
    {
        AJAX('GET', searchURL, function(request) {
            let json = JSON.parse(request.responseText);
            tpage.innerHTML = ''+ json.length +' résultats';
        });
    }
210

211 212 213 214

    /*
    *   Rafraîchit l'affichage de la table légume
    */
215
    function getTableBodyLegume(URL)
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    {
        AJAX('GET', URL, function(request)
        {
            let json = JSON.parse(request.responseText);

            for (let i = 0; i < json.length; i++)
            {
                let tr = buildRowLegume(json[i]);
                tbody.appendChild(tr);
            }
        });
    }


    /*
    *   Construit une rangée du tableau des Légumes
    *   @param json object jsonRow
    */
    function buildRowLegume(jsonRow)
    {
        //console.log(jsonRow);

        let tr = document.createElement('tr');

        let td1 = document.createElement('td');
        td1.textContent = formatNumber(jsonRow.id, 3);
        tr.appendChild(td1);

        let td8 = document.createElement('td');
        td8.innerHTML = (jsonRow.fruit === true) ? '<span class="badge badge-pill badge-info">F</span>' : 'L';
        tr.appendChild(td8);

        let td9 = document.createElement('td');
        td9.innerHTML = (jsonRow.revente === true) ? '<span class="badge badge-pill badge-dark">R</span>' : null;
        tr.appendChild(td9);

        let td2 = document.createElement('td');
        td2.textContent = jsonRow.nom;
        tr.appendChild(td2);

        let td3 = document.createElement('td');
        td3.innerHTML = jsonRow.image ?
            '<div class="logo-sm"><div class="crop"><img src="/web/uploads/images/legumes/'
            + jsonRow.image + '" /></div></div>': null;
        tr.appendChild(td3);

        let td4 = document.createElement('td');
        td4.innerHTML =
            (jsonRow.description ? jsonRow.description + '<br>' : '')
            + (jsonRow.origine ? '<span class="details">Origine: ' + jsonRow.origine + '</span><br>' : '')
            + '<span class="details">'
            + (jsonRow.quantite_min ? ' Min:' + jsonRow.quantite_min  : '')
            + (jsonRow.quantite_max ? ' | Max:' + jsonRow.quantite_max  : '')
            + (jsonRow.quantite_step ? ' | Step:' + jsonRow.quantite_step  : '')
            + '</span>';
        tr.appendChild(td4);

        let td5 = document.createElement('td');
        td5.textContent = jsonRow.prix_unitaire + '';
        tr.appendChild(td5);

        let td6 = document.createElement('td');
        td6.textContent = jsonRow.unite;
        tr.appendChild(td6);

        let td7 = document.createElement('td');
        td7.appendChild(displayEditLegume(jsonRow));
        td7.appendChild(displayDuplicateLegume(jsonRow));
        td7.appendChild(displayDeleteLegume(jsonRow));
285
        td7.appendChild(displayInsertLegume(jsonRow));
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
        tr.appendChild(td7);

        return tr;
    }


    /*
    *   Affiche un bouton pour éditer une rangée
    *   @param json object jsonRow
    */
    function displayEditLegume(jsonRow)
    {
        let editBtn = document.createElement('button');
        editBtn.innerHTML = '<i class="fas fa-edit fa-fw"></i> Editer';
        editBtn.classList.add('btn', 'btn-dark', 'btn-sm', 'mb-1', 'mr-1');
        editBtn.dataset.legumeId = jsonRow.id;
        editBtn.dataset.toggle = "modal";
        editBtn.dataset.target = ".form-legume-modal";
        editBtn.addEventListener('click', function()
        {
            let legumeId = this.dataset.legumeId;
            submitURL = Routing.generate('api_legume_update', {'id': legumeId});
            AJAX('GET', submitURL, function(request)
            {
                let json = JSON.parse(request.responseText);
                titleForm.textContent = 'Légume # ' + json.id;

                form.querySelector('#legume_nom').value = json.nom;
314

315
                let legumeFruit = form.querySelector('#legume_fruit');
316 317 318 319 320
                for (let i = 0; i < legumeFruit.options.length; i++)
                {
                    if (legumeFruit.options[i].value == json.fruit)
                    {
                        legumeFruit.selectedIndex = legumeFruit[i].index;
321 322
                    }
                }
323

324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
                form.querySelector('#legume_revente').value = json.revente;
                form.querySelector('#legume_revente').checked = json.revente;
                form.querySelector('#legume_description').value = json.description;
                form.querySelector('#legume_origine').value = json.origine ? json.origine : null;
                form.querySelector('#legume_quantiteMin').value = json.quantite_min ? json.quantite_min : null;
                form.querySelector('#legume_quantiteMax').value = json.quantite_max ? json.quantite_max : null;
                form.querySelector('#legume_quantiteStep').value = json.quantite_step ? json.quantite_step : null;
                form.querySelector('#legume_unite').value = json.unite;
                form.querySelector('#legume_prixUnitaire').value = json.prix_unitaire;
            });
        });
        return editBtn;
    }


    /*
    *   Affiche un bouton pour dupliquer une rangée
    *   @param json object jsonRow
    */
    function displayDuplicateLegume(jsonRow)
    {
        let copyBtn = document.createElement('button');
        copyBtn.setAttribute('title', 'Dupliquer');
        copyBtn.innerHTML = '<i class="fas fa-clone fa-fw"></i>';
        copyBtn.classList.add('btn', 'btn-secondary', 'btn-sm', 'mb-1', 'mr-1');
        copyBtn.dataset.legumeId = jsonRow.id;
        copyBtn.addEventListener('click', function()
        {
            let legumeId = this.dataset.legumeId;
            let r = confirm('Dupliquer la rangée n°' + legumeId
                + '\nSouhaitez-vous continuer ?\n');
            if (r === true) {
                submitURL = Routing.generate('api_legume_duplicate', {'id': legumeId });
                AJAX('GET', submitURL, function()
                {
                    reloadTableLegume();
                });
            }
        });
        return copyBtn;
    }


367
    /*
368 369 370 371 372 373 374 375 376 377
    *   Affiche un bouton pour supprimer une rangée
    *   @param json object jsonRow
    */
    function displayDeleteLegume(jsonRow)
    {
        let deleteBtn = document.createElement('button');
        deleteBtn.setAttribute('title', 'Supprimer');
        deleteBtn.innerHTML = '<i class="fas fa-trash fa-fw"></i>';
        deleteBtn.classList.add('btn', 'btn-danger', 'btn-sm', 'mb-1', 'mr-1');
        deleteBtn.dataset.legumeId = jsonRow.id;
378 379
        deleteBtn.addEventListener('click', function()
        {
380 381 382 383 384 385 386 387 388 389 390 391 392 393
            let legumeId = this.dataset.legumeId;
            let r = confirm('Effacer le légume n°' + legumeId
                + '\nCette action n\'est pas réversible. Souhaitez-vous continuer ?\n');
            if (r === true) {
                submitURL = Routing.generate('api_legume_delete', {'id': legumeId});
                AJAX('DELETE', submitURL, function () {
                    reloadTableLegume();
                });
            }
        });
        return deleteBtn;
    }


394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    /*
    *   Affiche un bouton pour insérer le légume dans une offre
    *   @param json object jsonRow
    */
    function displayInsertLegume(jsonRow)
    {
        let insertBtn = document.createElement('button');
        insertBtn.setAttribute('title', 'Insérer dans une offre');
        insertBtn.innerHTML = '<i class="fas fa-clipboard-check fa-fw"></i> Insérer';
        insertBtn.classList.add('btn', 'btn-info', 'btn-sm', 'mb-1', 'mr-1');
        insertBtn.dataset.legumeId = jsonRow.id;
        insertBtn.dataset.toggle = "modal";
        insertBtn.dataset.target = ".form-offre-legume-insert-modal";
        insertBtn.addEventListener('click', function()
        {
            let legumeId = this.dataset.legumeId;
            submitURL = Routing.generate('api_legume_insert', {'id': legumeId});

            let titleInsertForm = document.querySelector('#form-offre-legume-insert');
            titleInsertForm.textContent = 'Insérer le légume # ' + jsonRow.id;

            AJAX('GET', submitURL, function(request)
            {
                console.log('getget');

                let json = JSON.parse(request.responseText);

                reloadTableLegume();
            });
        });
        return insertBtn;

    }


429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
    /*
    *
    *   Initialise l'affichage de la page
    */

    let submitURL = null;

    let table = document.querySelector('table#maintab.legumes');
    let tbody = table.querySelector('tbody');

    let total = parseInt(document.querySelector('#t_rows').textContent);
    let tpage = document.querySelector('#t_pages');

    let form = document.querySelector('form[name=legume]');
    let titleForm = document.querySelector('#form-legume');

    let paginate = { 'step': 10, 'page': 1, 'column': 'id', 'order': 'ASC' };

    reloadTableLegume(paginate);


    /*
    *   Bouton pour recharger la page
452 453 454
    */
    let reloadBtns = document.querySelectorAll('.btn-reload');
    reloadBtns.forEach(function(reloadBtn) {
455
        reloadBtn.addEventListener('click', function()
456 457
        {
            reloadTableLegume(paginate);
Mat's avatar
hop  
Mat committed
458
            searchField.value = null;
459 460 461
        });
    });

462

463
    /*
464
    *   Bouton pour ajouter une nouveau légume
465 466 467
    */
    let createBtns = document.querySelectorAll('.btn-create');
    createBtns.forEach(function(createBtn) {
468
        createBtn.addEventListener('click', function()
469
        {
470
            titleForm.textContent = 'Nouveau légume';
471
            form.querySelector('#legume_nom').value = null;
472
            form.querySelector('#legume_fruit').selectedIndex = true;
473 474
            form.querySelector('#legume_revente').value = false;
            form.querySelector('#legume_revente').checked = false;
475
            form.querySelector('#legume_description').value = null;
Mat's avatar
Mat committed
476 477 478 479
            form.querySelector('#legume_origine').value = null;
            form.querySelector('#legume_quantiteMin').value = null;
            form.querySelector('#legume_quantiteMax').value = null;
            form.querySelector('#legume_quantiteStep').value = null;
Mat's avatar
Mat committed
480
            form.querySelector('#legume_unite').value = 'kg';
481
            form.querySelector('#legume_prixUnitaire').value = null;
482 483 484 485 486 487 488 489 490 491 492 493
            submitURL = Routing.generate('api_legume_create');
        });
    });

    /*
    *   Soumission du formulaire
    */
    form.addEventListener('submit', function(e)
    {
        let form = this;
        e.preventDefault();
        AJAX('POST', submitURL, function()
494 495
        {
            reloadTableLegume(paginate);
496
            $('.form-legume-modal').modal('hide'); // en jquery
497 498
        },
        form);
499 500
    });

501

502 503 504 505
    /*
    *   Définir le pas de la pagination
    */
    let stepform = document.querySelector('form#pagination select');
506
    stepform.addEventListener('change', function()
507
    {
508
        let step = (this.value === '-1') ? 10 : this.value;
509 510
        paginate.step = parseInt(step);
        paginate.page = 1;
511 512

        searchField.value = null;
513 514 515
        reloadTableLegume(paginate);
    });

516

517 518 519 520 521 522 523
    /*
    *   Tri par colonne, toggle
    */
    let columns = document.querySelectorAll('th[scope="col"] a.btn-sort');
    columns.forEach(function(column)
    {
        let col = column.getAttribute('id');
524
        column.addEventListener('click', function()
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
        {
            columns.forEach(function(column) {
                let oldCaret  = column.parentNode.querySelector('i.fas');
                if (oldCaret !== null) {
                    oldCaret.remove();
                }
            });
            paginate.column = col;
            paginate.order = (paginate.order === 'ASC') ? 'DESC' : 'ASC';
            reloadTableLegume(paginate);
            let th = this.parentNode;
            let newCaret = document.createElement('i');
            newCaret.classList.add('fas', (paginate.order === 'DESC') ? 'fa-caret-down' : 'fa-caret-up');
            th.appendChild(newCaret);
        });
    });

542

543 544 545 546 547 548 549 550
    /*
    *   Recherche Live Ajax
    */
    let searchField = document.querySelector('input#search');
    let qString = null;
    searchField.addEventListener('input', function()
    {
        qString = this.value;
Mat's avatar
Mat committed
551 552
        if (qString.length === 0) {
            reloadTableLegume(paginate);
553 554 555 556 557 558
        } else {
            if (qString.length >= 3)
            {
                stepform.value = -1;
                reloadTableSearchLegume({'q': qString });
            }
Mat's avatar
Mat committed
559
        }
560
    });
Mat's avatar
Mat committed
561

562

Mat's avatar
Mat committed
563 564
</script>
{% endblock %}
565 566
{#
    TODO méthode pour actualiser en ajax le nombre total de rangées
Mat's avatar
Mat committed
567
    TODO formulaire ajax spécial pour ajouter/éditer/effacer l'image, la renommer de manière unique
568
    TODO !! BUG champs de recherche ajax, temporiser si on entre plusieurs lettres trop rapidement
Mat's avatar
Mat committed
569
    TODO pagination, calcul la largeur et raccourcit avec des next/previous
Mat's avatar
todo  
Mat committed
570 571
    TODO contraintes assert et vérif html
    TODO copie de la rangée dans le menu en cours
572
#}