envelops.js 26.2 KB
Newer Older
1
var cash_envelops = [];
2
var archive_cash_envelops = [];
3
var ch_envelops = [];
4
var archive_ch_envelops = [];
5
var envelop_to_update = null;
6 7
var members_search_results = [];
var selected_member = null;
Administrator committed
8 9

function reset() {
10 11
    $('#cash_envelops').empty();
    $('#ch_envelops').empty();
12 13 14 15
    $('#archive_cash_envelops').empty();
    $('#archive_ch_envelops').empty();
    archive_cash_envelops = [];
    archive_ch_envelops = [];
16 17
    cash_envelops = [];
    ch_envelops = [];
Administrator committed
18 19 20
}

function toggle_error_alert() {
21
    $('#envelop_cashing_error').toggle(250);
Administrator committed
22 23
}

24
function toggle_success_alert(message) {
25 26
    $('#envelop_cashing_success').find(".success_alert_content")
        .text(message);
27
    $('#envelop_cashing_success').toggle(250);
Administrator committed
28 29
}

Damien Moulard committed
30 31 32 33
function toggle_deleted_alert() {
    $('#envelop_deletion_success').toggle(250);
}

34 35
/**
 * Get an envelop from the cash or cheque lists dependings on the params
36 37 38
 * @param {String} type
 * @param {String} index
 * @returns
39 40 41 42 43 44 45 46 47 48 49
 */
function get_envelop_from_type_index(type, index) {
    if (type === "cash") {
        return cash_envelops[index];
    } else {
        return ch_envelops[index];
    }
}

/**
 * Define a name for an envelop depending on its type, with or with its type
50
 * @param {Object} envelop
51
 * @param {String} name_type short | long
52
 * @returns
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
 */
function get_envelop_name(envelop, name_type = 'short') {
    let envelop_name = "";

    if (envelop.type === "cash") {
        let split_id = envelop._id.split('_');
        let envelop_date = split_id[3].padStart(2, '0') + "/" + split_id[2].padStart(2, '0') + "/" + split_id[1];

        envelop_name = `Enveloppe${(name_type === "short") ? "" : " de liquide"} du ${envelop_date}`;
    } else if (envelop.type == "ch") {
        envelop_name = `Enveloppe${(name_type === "short") ? "" : " de chèques"} #${envelop.display_id}`;
    }

    return envelop_name;
}

Damien Moulard committed
69 70
/**
 * Set the envelops contents on the document (could use a little cleanup someday: don't generate html in js, etc...)
71 72 73 74
 * @param {Object} envelop
 * @param {String} envelop_name
 * @param {Int} envelop_content_id
 * @param {Int} envelop_index
Damien Moulard committed
75
 */
Administrator committed
76
function set_envelop_dom(envelop, envelop_name, envelop_content_id, envelop_index) {
77 78 79 80 81 82 83
    var envelops_section ="";

    if (!envelop.archive)
        envelops_section = $('#' + envelop.type + '_envelops');

    else
        envelops_section = $('#archive_' + envelop.type + '_envelops');
84 85 86

    // Calculate envelop total amount
    var total_amount = 0;
Administrator committed
87

88 89 90
    for (partner_id in envelop.envelop_content) {
        total_amount += envelop.envelop_content[partner_id].amount;
    }
Administrator committed
91

92 93
    var new_html = '<div class="envelop_section">'
    + '<div class="flex-container">';
Administrator committed
94

95
    // Allow checking for all cash and first check envelops
96
    if ((envelop.type == 'cash' || envelop.type == 'ch' && envelop_index == 0) && !envelop.archive) {
97
        new_html += '<button class="accordion w80">' + envelop_name + ' - <i>' + total_amount + '€</i></button>'
98
    + '<button class="btn--success archive_button item-fluid" onClick="openModal(\'<h3>Êtes-vous sûr ?</h3>\', function() {archive_envelop(\'' + envelop.type + '\', ' + envelop_index + ');}, \'Encaisser\', false)">Encaisser</button>';
99 100 101 102 103 104 105 106 107 108 109 110
    } else if (envelop.archive ===true) {
        new_html += '<button class="accordion w100">' + envelop_name + ' - <i>' + total_amount + '€';

        if (envelop.cashing_date !== undefined) {
            new_html += ' - Encaissée le ' + envelop.cashing_date;
        }

        if (envelop.canceled) {
            new_html += ' - Enveloppe supprimée';
        }

        new_html += '</i></button>';
111 112
    } else {
        new_html += '<button class="accordion w100">' + envelop_name + ' - <i>' + total_amount + '€</i></button>';
Administrator committed
113 114
    }

115
    new_html += '</div>'
116 117
        + '<div class="panel panel_' + envelop_content_id + '"><ol class="envelop_content_list" id="' + envelop_content_id + '"></ol></div>'
        + '</div>';
118 119 120 121 122 123 124 125 126

    $(new_html).appendTo(envelops_section);

    for (node in envelop.envelop_content) {
        var li_node = document.createElement("LI"); // Create a <li> node

        var content = envelop.envelop_content[node].partner_name + ' : ' + envelop.envelop_content[node].amount + '€';

        if ('payment_id' in envelop.envelop_content[node]) {
127
            content += " -- paiement comptabilisé.";
128 129 130 131 132 133 134
        }

        var textnode = document.createTextNode(content); // Create a text node

        li_node.appendChild(textnode); // Append the text to <li>
        document.getElementById(envelop_content_id).appendChild(li_node);
    }
Damien Moulard committed
135 136

    let envelop_panel = $(`.panel_${envelop_content_id}`);
137

138
    if (envelop.comments) envelop_panel.append(`<p class="envelop_comment"> <b>Commentaire :</b> ${envelop.comments}</p>`);
139

140 141
    if (!envelop.archive) {
        let envelop_panel = $(`.panel_${envelop_content_id}`);
142

143
        envelop_panel.append(`<button class="btn--danger delete_envelop_button item-fluid" id="update_envelop_${envelop.type}_${envelop_index}">Supprimer l'enveloppe</button>`);
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
        envelop_panel.append(`
            <button 
                class="btn--primary update_envelop_button item-fluid" 
                id="update_envelop_${envelop.type}_${envelop_index}"
            >
                Modifier
            </button>`);
        envelop_panel.append(`
            <button 
                class="btn--primary add_to_envelop_button item-fluid" 
                id="add_to_envelop_${envelop.type}_${envelop_index}"
            >
                Ajouter un paiement ou des parts sociales
            </button>`);

159 160 161 162
        $(".update_envelop_button").off("click");
        $(".update_envelop_button").on("click", function() {
            let el_id = $(this).attr("id")
                .split("_");
163

164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
            envelop_to_update = {
                type: el_id[2],
                index: el_id[3],
                lines_to_delete: []
            };

            set_update_envelop_modal();
        });

        $(".delete_envelop_button").off("click");
        $(".delete_envelop_button").on("click", function() {
            let el_id = $(this).attr("id")
                .split("_");
            let type = el_id[2];
            let index = el_id[3];
            let envelop = get_envelop_from_type_index(type, index);

            openModal(
                "<h3>Supprimer l'enveloppe ?</h3>",
                function() {
                    archive_canceled_envelop(envelop);
                },
                'Supprimer'
            );
        });
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228

        $(".add_to_envelop_button").off("click");
        $(".add_to_envelop_button").on("click", function() {
            let el_id = $(this).attr("id")
                .split("_");

            envelop_to_update = {
                type: el_id[el_id.length-2],
                index: el_id[el_id.length-1]
            };

            let envelop = get_envelop_from_type_index(envelop_to_update.type, envelop_to_update.index);
            let envelop_name = get_envelop_name(envelop, 'long');

            let modal_add_to_envelop = $('#templates #modal_add_to_envelop');

            modal_add_to_envelop.find(".envelop_name").text(envelop_name);

            openModal(
                modal_add_to_envelop.html(),
                () => {},
                '',
                false,
                true,
                () => {
                    envelop_to_update = null;
                    selected_member = null;
                    modal.find(".btn-modal-ok").show();
                }
            );

            // No validation button
            modal.find(".btn-modal-ok").hide();
            modal.find(".add_to_envelop_lines").empty();

            // Set action to search for the member
            modal.find('.search_member_form').submit(function() {
                let search_str = modal.find('.search_member_input').val();

                $.ajax({
229
                    url: '/members/search/' + search_str + "?search_type=envelops",
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
                    dataType : 'json',
                    success: function(data) {
                        members_search_results = data.res;
                        display_possible_members();
                    },
                    error: function() {
                        err = {
                            msg: "erreur serveur lors de la recherche de membres",
                            ctx: 'add_payment_to_envelop.search_members'
                        };
                        report_JS_error(err, 'envelops');

                        alert("Erreur lors de la recherche de membre, il faut ré-essayer plus tard...");
                    }
                });
            });
        });
247
    }
Administrator committed
248 249
}

Damien Moulard committed
250 251
/**
 * Given the raw list of envelop documents, generate the cash and cheque lists
252
 * @param {Array} envelops
Damien Moulard committed
253
 */
Administrator committed
254
function set_envelops(envelops) {
255 256
    var cash_index = 0;
    var ch_index = 0;
257 258
    var archive_cash_index = 0;
    var archive_ch_index = 0;
Administrator committed
259

260 261 262
    reset();
    for (var i= 0; i < envelops.length; i++) {
        var envelop = envelops[i].doc;
Administrator committed
263

264 265 266 267
        //If the envelop is archived and more than 1 year old we delete it
        if (envelop.archive && (new Date()-new Date(envelop.creation_date))/ (1000 * 3600 * 24 * 365)>1) {
            delete_envelop(envelop);
        } else if (envelop.type == "cash" && envelop.archive != true) {
268
            cash_envelops.push(envelop);
Administrator committed
269

270
            let envelop_name = get_envelop_name(envelop);
271
            let envelop_content_id = 'content_cash_list_' + cash_index;
Administrator committed
272

273
            set_envelop_dom(envelop, envelop_name, envelop_content_id, cash_index);
Administrator committed
274

275
            cash_index += 1;
276 277 278 279 280 281 282 283 284 285
        } else if (envelop.type == "cash" && envelop.archive == true) {
            archive_cash_envelops.push(envelop);

            let envelop_name = get_envelop_name(envelop);
            let envelop_content_id = 'content_archive_cash_list_' + archive_cash_index;

            set_envelop_dom(envelop, envelop_name, envelop_content_id, archive_cash_index);
            archive_cash_index += 1;

        } else if (envelop.type == "ch" && envelop.archive != true) {
286
            ch_envelops.push(envelop);
Administrator committed
287

288
            let envelop_name = get_envelop_name(envelop);
289
            let envelop_content_id = 'content_ch_list_' + ch_index;
Administrator committed
290

291
            set_envelop_dom(envelop, envelop_name, envelop_content_id, ch_index);
Administrator committed
292

293
            ch_index += 1;
294 295 296 297 298 299 300 301 302 303
        } else if (envelop.type == "ch" && envelop.archive == true) {
            archive_ch_envelops.push(envelop);

            let envelop_name = get_envelop_name(envelop);
            let envelop_content_id = 'content_archive_ch_list_' + archive_ch_index;

            set_envelop_dom(envelop, envelop_name, envelop_content_id, archive_ch_index);

            archive_ch_index += 1;

304
        }
Administrator committed
305
    }
306 307 308 309 310 311 312 313 314

    if (cash_index == 0)
        $('#cash_envelops').html("<p class='txtcenter'>Aucune enveloppe.</p>");
    if (ch_index == 0)
        $('#ch_envelops').html("<p class='txtcenter'>Aucune enveloppe.</p>");

    // Set accordions
    var acc = document.getElementsByClassName("accordion");

315 316
    for (var j = 0; j < acc.length; j++) {
        acc[j].addEventListener("click", function() {
317
            /* Toggle between adding and removing the "active" class,
Administrator committed
318
      to highlight the button that controls the panel */
319 320 321 322 323 324 325 326 327 328 329 330
            this.classList.toggle("active");

            /* Toggle between hiding and showing the active panel */
            var panel = this.parentNode.nextElementSibling; // depends on html structure

            if (panel.style.maxHeight) {
                panel.style.maxHeight = null;
            } else {
                panel.style.maxHeight = panel.scrollHeight + "px";
            }
        });
    }
Administrator committed
331 332
}

333 334 335 336 337 338 339 340
/**
 * Generate content & set listeners for the modal to update an envelop
 */
function set_update_envelop_modal() {
    let envelop = get_envelop_from_type_index(envelop_to_update.type, envelop_to_update.index);
    let envelop_name = get_envelop_name(envelop, 'long');

    let modal_update_envelop = $('#templates #modal_update_envelop');
341

342 343 344 345 346 347
    modal_update_envelop.find(".envelop_name").text(envelop_name);
    modal_update_envelop.find(".envelop_lines").empty();

    let update_line_template = $('#templates #update_envelop_line_template');

    let cpt = 1;
348

349 350
    for (let partner_id in envelop.envelop_content) {
        let line = envelop.envelop_content[partner_id];
351

352 353 354 355 356 357 358 359 360 361 362 363
        update_line_template.find(".update_envelop_line").attr('id', `update_line_${partner_id}`);
        update_line_template.find(".line_number").html(`${cpt}.&nbsp;`);
        update_line_template.find(".line_partner_name").text(line.partner_name);

        modal_update_envelop.find(".envelop_lines").append(update_line_template.html());

        cpt += 1;
    }

    openModal(
        modal_update_envelop.html(),
        () => {
364
            update_envelop_action();
365 366 367 368 369 370 371 372 373 374 375 376
        },
        'Mettre à jour',
        true,
        true,
        () => {
            envelop_to_update = null;
        }
    );

    // Elements needs to be on the document so value & listeners can be set
    for (let partner_id in envelop.envelop_content) {
        let line = envelop.envelop_content[partner_id];
Damien Moulard committed
377

378 379
        $(`#update_line_${partner_id}`).find('.line_partner_amount')
            .val(line.amount);
380 381 382 383 384 385
    }

    modal.find('.envelop_comments').val((envelop.comments !== undefined) ? envelop.comments : '');

    $(".delete_envelop_line_icon").off("click");
    $(".delete_envelop_line_icon").on("click", function() {
386 387 388
        let line_id = $(this).closest(".update_envelop_line")
            .attr("id")
            .split("_");
389
        let partner_id = line_id[line_id.length-1];
390

391
        envelop_to_update.lines_to_delete.push(partner_id);
392

393
        $(this).hide();
394 395 396 397
        $(this).closest(".update_envelop_line")
            .find(".deleted_line_through")
            .show();
    });
398 399 400
}

/**
401
 * Update an envelop data with modal data
402
 */
403 404
function update_envelop_action() {
    if (is_time_to('update_envelop_action', 1000)) {
405 406 407 408
        let envelop = get_envelop_from_type_index(envelop_to_update.type, envelop_to_update.index);

        // Update lines amounts
        let amount_inputs = modal.find('.line_partner_amount');
409 410 411 412 413

        amount_inputs.each(function (i, e) {
            let line_id = $(e).closest(".update_envelop_line")
                .attr("id")
                .split("_");
414 415 416 417 418 419 420
            let partner_id = line_id[line_id.length-1];

            envelop.envelop_content[partner_id].amount = parseInt($(e).val());
        });

        // Delete lines
        for (let partner_id of envelop_to_update.lines_to_delete) {
421
            delete(envelop.envelop_content[partner_id]);
Damien Moulard committed
422 423
        }

424 425
        // Envelop comments
        envelop.comments = modal.find('.envelop_comments').val();
426

427 428 429 430 431 432 433 434 435 436 437
        update_envelop(envelop);
        toggle_success_alert("Enveloppe modifiée !");
    }
}

/**
 * Update an envelop in couchdb
 * @param {Object} envelop
 */
function update_envelop(envelop) {
    if (is_time_to('update_envelop', 1000)) {
438 439 440 441 442 443 444 445 446 447 448 449 450
        dbc.put(envelop, function callback(err, result) {
            envelop_to_update = null;

            if (!err && result !== undefined) {
                get_envelops();
            } else {
                alert("Erreur lors de la mise à jour de l'enveloppe. Si l'erreur persiste contactez un administrateur svp.");
                console.log(err);
            }
        });
    }
}

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
/**
 * archive and canceled an envelop from couchdb.
 * @param {Object} envelop
 */
function archive_canceled_envelop(envelop) {
    if (is_time_to('archive_canceled_envelop', 1000)) {
        envelop.archive = true;
        envelop.canceled = true;

        dbc.put(envelop, function callback(err, result) {
            if (!err && result !== undefined) {
                toggle_deleted_alert();
                get_envelops();
            } else {
                alert("Erreur lors de la suppression de l'enveloppe... Essaye de recharger la page et réessaye.");
                console.log(err);
            }
        });

    }
}

473 474
/**
 * Delete an envelop from couchdb.
475
 * @param {Object} envelop
476 477 478
 */
function delete_envelop(envelop) {
    if (is_time_to('delete_envelop', 1000)) {
Damien Moulard committed
479
        envelop._deleted = true;
480

Damien Moulard committed
481 482 483 484 485 486 487 488
        dbc.put(envelop, function callback(err, result) {
            if (!err && result !== undefined) {
                get_envelops();
            } else {
                alert("Erreur lors de la suppression de l'enveloppe... Essaye de recharger la page et réessaye.");
                console.log(err);
            }
        });
489

Administrator committed
490
    }
Damien Moulard committed
491
}
492

493 494
/**
 * Send the request to save an envelop payments in Odoo. The envelop will be deleted from couchdb.
495 496
 * @param {String} type
 * @param {String} index
497
 */
Damien Moulard committed
498
function archive_envelop(type, index) {
Damien Moulard committed
499
    if (is_time_to('archive_envelop', 5000)) {
Damien Moulard committed
500 501 502 503 504
        $('#envelop_cashing_error').hide();
        $('#envelop_cashing_success').hide();
        // Loading on
        openModal();

505
        let envelop = get_envelop_from_type_index(type, index);
Damien Moulard committed
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527

        // Proceed to envelop cashing
        $.ajax({
            type: "POST",
            url: "/envelops/archive_envelop",
            headers: { "X-CSRFToken": getCookie("csrftoken") },
            dataType: "json",
            traditional: true,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(envelop),
            success: function(response) {
                closeModal();

                var display_success_alert = true;
                // Handle errors when saving payments
                var error_payments = response.error_payments;
                var error_message = "";

                for (var i = 0; i < error_payments.length; i++) {
                    if (error_payments[i].done == false) {
                        error_message += "<p>Erreur lors de l'enregistrement du paiement de <b>" + error_payments[i]['partner_name']
                + "</b> (id odoo : " + error_payments[i]['partner_id'] + ", valeur à encaisser : " + error_payments[i]['amount'] + "€).";
528 529 530 531 532 533 534
                        error_message += "<br/><b>L'opération est à reprendre manuellement dans Odoo pour ce paiement.</b>";

                        if ('error' in error_payments[i]) {
                            error_message += `<br/>(error: ${error_payments[i]['error']})`;
                        }

                        error_message += "</p>";
Damien Moulard committed
535
                    }
536 537
                }

Damien Moulard committed
538 539
                // If error during envelop deletion
                var response_envelop = response.envelop;
540

Damien Moulard committed
541 542 543 544 545 546
                if (response_envelop == "error") {
                    error_message += "<p>Erreur lors de la suppression de l'enveloppe.<br/>";
                    error_message += "<b>Sauf contre-indication explicite, les paiements ont bien été enregistrés.</b><br/>";
                    error_message += "Les paiements déjà comptabilisés ne le seront pas à nouveau, vous pouvez ré-essayer. Si l'erreur persiste, l'enveloppe devra être supprimée manuellement.</p>";
                    display_success_alert = false;
                }
547

Damien Moulard committed
548 549 550 551
                if (error_message !== "") {
                    $('#error_alert_txt').html(error_message);
                    toggle_error_alert();
                }
552

Damien Moulard committed
553
                if (display_success_alert) {
554
                    toggle_success_alert("Enveloppe encaissée !");
Damien Moulard committed
555 556 557 558 559
                }
            },
            error: function() {
                closeModal();
                alert('Erreur serveur. Merci de ne pas ré-encaisser l\'enveloppe qui a causé l\'erreur.');
560
            }
Damien Moulard committed
561
        });
Damien Moulard committed
562
    } else {
Damien Moulard committed
563
        alert("Par sécurité, il faut attendre 5s entre l'encaissement de deux enveloppes.");
Damien Moulard committed
564
    }
Administrator committed
565 566
}

Damien Moulard committed
567 568 569
/**
 * Get all the envelops from couchdb
 */
Administrator committed
570
function get_envelops() {
571 572 573 574 575 576
    dbc.allDocs({
        include_docs: true,
        attachments: true
    }).then(function (result) {
        set_envelops(result.rows);
    })
577 578 579 580
        .catch(function (err) {
            alert('Erreur lors de la récupération des enveloppes.');
            console.log(err);
        });
Administrator committed
581 582
}

583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
/**
 * Display the members from the search result in the "add payments to envelop" modal
 */
function display_possible_members() {
    modal.find('.search_member_results_area').show();
    modal.find('.search_member_results').empty();

    if (members_search_results.length > 0) {
        $(".search_results_text").show();

        for (member of members_search_results) {
            // Display results (possible members) as buttons
            var member_button = '<button class="btn--success btn_possible_member" member_id="'
                + member.id + '">'
                + member.barcode_base + ' - ' + member.name
                + '</button>';

            $('.search_member_results').append(member_button);
        }

        // Set action on member button click
        $('.btn_possible_member').on('click', function() {
            const mid = $(this).attr('member_id');

            selected_member = members_search_results.find(m => m.id == mid);
            members_search_results = [];

            modal.find('.search_member_input').val('');
            modal.find('.search_member_results').empty();
            modal.find('.search_member_results_area').hide();

            // Adding line for this member in modal...
            display_line_add_payment();
        });
    } else {
        $(".search_results_text").hide();
        $('.search_member_results').html(`<p>
            <i>Aucun résultat ! Vérifiez votre recherche...</i>
        </p>`);
    }
}

/**
 * Display a line for adding a member's payment in the "add payments to envelop" modal
 */
function display_line_add_payment() {
    let envelop = get_envelop_from_type_index(envelop_to_update.type, envelop_to_update.index);

    // Block adding payment if member is already in the envelop
    for (let env_partner_id in envelop.envelop_content) {
        if (env_partner_id == selected_member.id) {
            alert("Ce membre est déjà dans l'enveloppe, impossible de lui rajouter un paiement.\nVous pouvez modifier le montant de son paiement dans la fenêtre de modification de l'enveloppe.");

            return -1;
        }
    }

    modal.find('.search_member_area').hide();

    let modal_line = $('#templates #add_to_envelop_line_template');

    modal_line.find(".line_partner_name").text(selected_member.name);

    modal.find(".add_to_envelop_lines").append(modal_line.html());
    modal.find(".add_to_envelop_lines_area").show();

    // Add payment button
    $('.add_payment_button').off('click');
    $('.add_payment_button').on('click', function() {
        let amount = parseInt(modal.find(".line_partner_amount").val(), 10);

        if (isNaN(amount)) {
            modal.find(".line_partner_amount_error").show();
        } else {
            modal.find(".line_partner_amount_error").hide();

            let modal_confirm_add_payment = $('#templates #modal_confirm_add_payment');

            modal_confirm_add_payment.find(".amount").text(amount);
            modal_confirm_add_payment.find(".member").text(selected_member.name);
            modal_confirm_add_payment.find(".envelop").text(get_envelop_name(envelop, 'long'));

            openModal(
                modal_confirm_add_payment.html(),
                () => {
                    add_payment_to_envelop(amount, envelop);
                },
                "Confirmer"
            );

            modal.find(".btn-modal-ok").show();
        }
    });

    // Add shares button
    $('.add_shares_button').off('click');
    $('.add_shares_button').on('click', function() {
        let amount = parseInt(modal.find(".line_partner_amount").val(), 10);

        if (isNaN(amount)) {
            modal.find(".line_partner_amount_error").show();
        } else {
            modal.find(".line_partner_amount_error").hide();

            let modal_confirm_add_shares = $('#templates #modal_confirm_add_shares');

            modal_confirm_add_shares.find(".amount").text(amount);
            modal_confirm_add_shares.find(".member").text(selected_member.name);
            modal_confirm_add_shares.find(".envelop").text(get_envelop_name(envelop, 'long'));

            openModal(
                modal_confirm_add_shares.html(),
                () => {
                    add_shares_to_member(amount, envelop);
                },
                "Confirmer",
                false
            );

            modal.find(".btn-modal-ok").show();
        }
    });

    return null;
}

/**
 * Add a payment in an envelop & save in couchdb
 * @param {Int} amount
 * @param {Object} envelop
 * @param {Int} invoice_id
 * @param {String} message
 */
function add_payment_to_envelop(amount, envelop, invoice_id=null, message="Paiement ajouté !") {
    if (is_time_to('add_payment_to_envelop', 1000)) {
        envelop.envelop_content[selected_member.id] = {
            partner_name: selected_member.name,
            amount: amount
        };
        if (invoice_id != null) {
            envelop.envelop_content[selected_member.id].invoice_id = invoice_id;
        }
        update_envelop(envelop);
        toggle_success_alert(message);

        envelop_to_update = null;
        selected_member = null;

        get_envelops();
    }
}

/**
 * Send request to add shares & then add payment
 * @param {Int} amount
 * @param {Object} envelop
 */
function add_shares_to_member(amount, envelop) {
    if (is_time_to('add_shares_to_member', 1000)) {
        openModal();

        data = {
            partner_id: selected_member.id,
            amount: amount
        };

        $.ajax({
            type: "POST",
            url: "/members/add_shares_to_member",
            headers: { "X-CSRFToken": getCookie("csrftoken") },
            dataType: "json",
            traditional: true,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(data),
            success: function(response) {
                closeModal();

                invoice_id = response[0];
                add_payment_to_envelop(amount, envelop, invoice_id, "Parts sociales ajoutées !");
            },
            error: function() {
                closeModal();
                alert('Un erreur est survenue lors de l\'ajout de parts sociales.');
            }
        });
    }
}

Administrator committed
771
$(document).ready(function() {
772 773
    if (typeof must_identify == "undefined" || coop_is_connected()) {
        get_envelops();
Damien Moulard committed
774 775 776 777 778 779 780 781 782 783 784 785

        // Hande change in couc db
        sync.on('change', function (info) {
            // handle change
            if (info.direction == 'pull') {
                get_envelops();
            }
        }).on('error', function (err) {
            // handle error
            console.log('erreur sync');
            console.log(err);
        });
786
    }
Administrator committed
787
});