<commit_before>/**
 * Return an instance of Quarantine.
 *
 * @constructor
 * @param {Object} options - instance options
 */
var Quarantine = function(options) {
    Listing.call(this, options);
};

Quarantine.prototype = {
    constructor: Quarantine,

    defaults: {
        deflocation: "listing",
        main_table_id: "emails",
        scroll_container: "#listing",
        navigation_params: ["sort_order", "pattern", "criteria", "msgtype"],
        eor_message: gettext("No more message to show")
    },

    initialize: function(options) {
        this.options = $.extend({}, this.defaults, options);
        this.options.defcallback = $.proxy(this.listing_cb, this);
        Listing.prototype.initialize.call(this, this.options);
        this.register_navcallbacks();
        this.listen();
        this.set_msgtype();

        $(document).on('click', '#selectall', this.toggle_selection);
        this.initialize_searchfield();
    },

    /**
     * Search field initialization.
     */
    initialize_searchfield: function() {
        $("#searchfield").searchbar({
            navobj: this.navobj,
            pattern_changed: function(navobj) {
                navobj.setparam("reset_page", "true");
            }
        });
    },

    /**
     * Activate the button corresponding to the current message type
     * filter. If no message type is found, the 'All' button is
     * selected.
     */
    set_msgtype: function() {
        var msgtype = this.navobj.getparam('msgtype');

        $("input[name*=msgtype]").attr("checked", false)
            .parent().removeClass('active');

        if (msgtype !== undefined) {
            $("input[name=msgtype_" + msgtype + "]").attr("checked", true)
                .parent().addClass('active');
        } else {
            $("button[name=msgtype_all]").attr("checked", true)
                .parent().addClass('active');
        }
    },

    /**
     * Update the main page content.
     *
     * @this Quarantine
     * @param {Object} data - new content
     */
    update_page: function(data) {
        if (data.menu !== undefined) {
            $("#menubar").html(data.menu);
            this.initialize_searchfield();
        }

        if (data.listing !== undefined) {
            $("#listing").html(data.listing);
        }
        if (this.navobj.getbaseurl() == "listing") {
            this.update_listing(data);
            $(this.options.scroll_container).scrollTop(10);
        } else {
            this.update_listing(data, false);
        }
    },

    listen: function() {
        $(document).on("click", "td[class*=openable]", $.proxy(this.viewmail_loader, this));
        $(document).on("click", "a[name=selectmsgs]", $.proxy(this.selectmsgs, this));
        $(document).on("click", "a[name=release-multi]",
            $.proxy(this.release_selection, this));
        $(document).on("click", "a[name=delete-multi]",
            $.proxy(this.delete_selection, this));
        $(document).on("click", "a[name=mark-as-spam-multi]",
            $.proxy(this.mark_selection_as_spam, this));
        $(document).on("click", "a[name=mark-as-ham-multi]",
            $.proxy(this.mark_selection_as_ham, this));
        $(document).on("click", "a[name=viewrequests]",
            $.proxy(this.view_requests, this));
        $(document).on("click", "a[name=release]", $.proxy(this.release, this));
        $(document).on("click", "a[name=delete]", $.proxy(this.delete, this));
        $(document).on("click", "a[name=mark-as-spam]",
            $.proxy(this.mark_as_spam, this));
        $(document).on("click", "a[name=mark-as-ham]",
            $.proxy(this.mark_as_ham, this));
        $(document).on("click", "a[name=headers]", $.proxy(this.headers, this));
        $(document).on("click", "td[name=type] span", $.proxy(this.filter_by_type, this));
        $(document).on("click", "#filters label", $.proxy(this.filter_by_type, this));
    },

    load_page: function(e) {
        Listing.prototype.load_page.apply(this, arguments);
        this.navobj.delparam("rcpt").update();
    },

    /**
     * Return extra arguments used to fetch a page.
     *
     * @this Listing
     */
    get_load_page_args: function() {
        var args = Listing.prototype.get_load_page_args.call(this);

        args.scroll = true;
        return args;
    },

    /**
     * Calculate the bottom position of the scroll container.
     *
     * @param {Object} $element - scroll container object
     */
    calculate_bottom: function($element) {
        var emails_height = $("#emails").height();

        if (!emails_height) {
            return undefined;
        }
        return $("#emails").height() - $element.height();
    },

    view_requests: function(e) {
        e.preventDefault();
        this.navobj.setparam("viewrequests", "1").update();
    },

    viewmail_loader: function(e) {
        e.preventDefault();
        var $tr = $(e.target).parent();
        var $to = $tr.find("td[name=to]");

        this.navobj.baseurl($tr.attr("id"));
        if ($to.length) {
            this.navobj.setparam("rcpt", $to.html().trim());
        }
        this.navobj.update();
    },

    /*
     * Toggle message selection when the top checkbox's state is
     * modified.
     *
     * If it is checked, all messages are selected. Otherwise, the
     * current selection is resetted.
     */
    toggle_selection: function(e) {
        if (!$('#selectall').prop('checked')) {
            $("#emails").htmltable("clear_selection");
            return;
        }
        $("td[name*=selection]").each(function() {
            var $input = $(this).children('input');
            $input.prop('checked', true);
            $('#emails').htmltable('select_row', $(this).parent());
        });
    },

    /*
     * Select all messages of a specific type.
     */
    selectmsgs: function(e) {
        e.preventDefault();
        var type = get_target(e, 'a').attr("href");
        var counter = 0;

        $("td[name=type]").each(function() {
            var $this = $(this);
            if ($this.find('span').html().trim() == type) {
                var $input = $this.parent().children('td[name=selection]').children('input');
                $input.prop('checked', true);
                $('#emails').htmltable('select_row', $this.parent());
                counter++;
            }
        });
        if (counter) {
            $("#selectall").prop('checked', true);
        }
    },

    /**
     * Filter listing by message type (spam, virus, etc.)
     *
     * @param {Object} evt - event object
     */
    filter_by_type: function(evt) {
        var $target = $(evt.target);
        var msgtype;

        if ($target.is("span")) {
            msgtype = $target.html().trim();
        } else {
            msgtype = $target.children("input").attr("name").replace("msgtype_", "");
        }

        if (msgtype != 'all') {
            this.navobj.setparam('msgtype', msgtype);
        } else {
            this.navobj.delparam('msgtype');
        }
        this.navobj.update();
    },

    /**
     * Return the list of currently selected messages.
     *
     * @return {Array} - list of message IDs
     */
    get_current_selection: function() {
        var selection = [];

        this.htmltable.current_selection().each(function() {
            var $tr = $(this);
            var $to = $tr.find("td[name=to]");

            if ($to.length) {
                selection.push($to.html().trim() + " " + $tr.attr("id"));
            } else {
                selection.push($tr.attr("id"));
            }
        });
        return selection;
    },

    _send_selection: function(e, name, message) {
        var $link = $(e.target);

        e.preventDefault();
        if (!this.htmltable.current_selection().length ||
            !confirm(message)) {
            return;
        }
        var selection = this.get_current_selection();

        $.ajax({
            url: $link.attr("href"),
            data: "action=" + name + "&selection=" + selection.join(","),
            type: 'POST',
            dataType: 'json'
        }).done(
            $.proxy(this.action_cb, this)
        ).fail(function(jqxhr) {
            var data = $.parseJSON(jqxhr.responseText);
            $("body").notify("error", data.message);
        });
    },

    release_selection: function(e) {
        this._send_selection(e, "release", gettext("Release this selection?"));
    },

    delete_selection: function(e) {
        this._send_selection(e, "delete", gettext("Delete this selection?"));
    },

    /**
     * Show the recipient selection form inside a modal box.
     *
     * @param {Object} evt - event object
     * @param {string} ltype - learning type (spam or ham)
     */
    show_select_rcpt_form: function(evt, ltype, selection) {
        if (selection === undefined) {
            selection = this.get_current_selection();
        }
        var url = this.options.learning_recipient_url +
            "?type=" + ltype + "&selection=" +
            selection.join(",");
        var $this = this;

        modalbox(evt, null, url, function() {
            $(".submit").on("click", function(evt) {
                simple_ajax_form_post(evt, {
                    formid: "learning_recipient_form",
                    reload_on_success: false,
                    success_cb: $.proxy($this.action_cb, $this)
                });
            });
        });
    },

    /**
     * Mark the current selection as spam.
     *
     * @param {Object} e - event object
     */
    mark_selection_as_spam: function(e) {
        if (this.options.check_learning_rcpt &&
            this.htmltable.current_selection().length) {
            this.show_select_rcpt_form(e, "spam");
        } else {
            this._send_selection(
                e, "mark_as_spam", gettext("Mark this selection as spam?"));
        }
    },

    /**
     * Mark the current selection as ham.
     *
     * @param {Object} e - event object
     */
    mark_selection_as_ham: function(e) {
        if (this.options.check_learning_rcpt &&
            this.htmltable.current_selection().length) {
            this.show_select_rcpt_form(e, "ham");
        } else {
            this._send_selection(
                e, "mark_as_ham", gettext("Mark this selection as non-spam?"));
        }
    },

    _send_action: function(e, message) {
        var $link = get_target(e, "a");

        e.preventDefault();
        if (!confirm(message)) {
            return;
        }
        $.ajax({
            url: $link.attr("href"),
            dataType: 'json',
            type: 'POST',
            data: {rcpt: get_parameter_by_name($link.attr("href"), 'rcpt')}
        }).done(
            $.proxy(this.action_cb, this)
        ).fail(function(jqxhr) {
            var data = $.parseJSON(jqxhr.responseText);
            $("body").notify("error", data.message);
        });
    },

    release : function(e) {
        this._send_action(e, gettext("Release this message?"));
    },

    delete: function(e) {
        this._send_action(e, gettext("Delete this message?"));
    },

    /**
     * Mark the current message as spam.
     *
     * @param {Object} e - event object
     */
    mark_as_spam: function(e) {
        if (this.options.check_learning_rcpt) {
            var $link = get_target(e, "a");
            var selection = get_parameter_by_name($link.attr("href"), "rcpt") +
                " " + $link.attr("data-mail-id");
            this.show_select_rcpt_form(e, "spam", [selection]);
        } else {
            this._send_action(e, gettext("Mark as spam?"));
        }
    },

    /**
     * Mark the current message as ham.
     *
     * @param {Object} e - event object
     */
    mark_as_ham: function(e) {
        if (this.options.check_learning_rcpt) {
            var $link = get_target(e, "a");
            var selection = get_parameter_by_name($link.attr("href"), "rcpt") +
                " " + $link.attr("data-mail-id");
            this.show_select_rcpt_form(e, "ham", [selection]);
        } else {
            this._send_action(e, gettext("Mark as non-spam?"));
        }
    },

    show_rawheaders: function($mailcontent) {
        $mailcontent.find("#rawheaders").removeClass("hidden");
        $mailcontent.find("#emailheaders").addClass("hidden");
    },

    headers: function(e) {
        e.preventDefault();

        var $link = get_target(e, "a");
        var $mailcontent = $("#mailcontent").contents();
        var $headers = $mailcontent.find("#emailheaders");
        var $rawheaders = $mailcontent.find("#rawheaders");

        if ($headers.hasClass("hidden")) {
            $link.html(gettext("View full headers"));
            $headers.removeClass("hidden");
            $rawheaders.addClass("hidden");
            return;
        }
        $link.html(gettext("Hide full headers"));
        if (!$rawheaders.length) {
            $.ajax({
                url: $link.attr("href"),
                global: false
            }).done($.proxy(function(data) {
                $mailcontent.find("#table-container").append($(data));
                this.show_rawheaders($mailcontent);
            }, this));
            return;
        }
        this.show_rawheaders($mailcontent);
    },

    update_params: function(e) {
        var $link = $(e.target);
        e.preventDefault();
        this.navobj.updateparams($link.attr("href")).update();
    },

    register_navcallbacks: function() {
        this.navobj.register_callback("_listing",
            $.proxy(this.listing_cb, this));
        this.navobj.register_callback("viewmail",
            $.proxy(this.viewmail_cb, this));
    },

    activate_buttons: function($tr) {
        $("a[name*=-multi]").removeClass('disabled');
        $("#selectall").prop('checked', true);
    },

    deactivate_buttons: function($tr) {
        if (!this.htmltable || !this.htmltable.current_selection().length) {
            $("a[name*=-multi]").addClass('disabled');
            $("#selectall").prop('checked', false);
        }
    },

    /**
     * Navigation callback: listing.
     *
     * @this Quarantine
     * @param {Object} data - ajax call response (JSON)
     */
    listing_cb: function(data) {
        this.update_page(data);
        this.navobj.delparam("rcpt").update();
        this.set_msgtype();
        $("#emails").htmltable({
            row_selected_event: this.activate_buttons,
            row_unselected_event: $.proxy(this.deactivate_buttons, this)
        });
        this.htmltable = $("#emails").data("htmltable");
        this.deactivate_buttons();
        if (this.navobj.hasparam("reset_page")) {
            this.navobj.delparam("reset_page").update(false, true);
        }
        $("#listing").css("overflow", "auto");
    },

    viewmail_cb: function(data) {
        this.update_page(data);
        $("#listing").css("overflow", "hidden");
    },

    action_cb: function(data) {
        if (data.reload) {
            this.navobj.update(true);
        }
        if (data.url) {
            this.navobj.parse_string(data.url, true).update(true);
        }
        $("body").notify("success", data.message, 2000);
    }
};

Quarantine.prototype = $.extend({}, Listing.prototype, Quarantine.prototype);
<commit_msg>Don't eat + characters.<commit_after>/**
 * Return an instance of Quarantine.
 *
 * @constructor
 * @param {Object} options - instance options
 */
var Quarantine = function(options) {
    Listing.call(this, options);
};

Quarantine.prototype = {
    constructor: Quarantine,

    defaults: {
        deflocation: "listing",
        main_table_id: "emails",
        scroll_container: "#listing",
        navigation_params: ["sort_order", "pattern", "criteria", "msgtype"],
        eor_message: gettext("No more message to show")
    },

    initialize: function(options) {
        this.options = $.extend({}, this.defaults, options);
        this.options.defcallback = $.proxy(this.listing_cb, this);
        Listing.prototype.initialize.call(this, this.options);
        this.register_navcallbacks();
        this.listen();
        this.set_msgtype();

        $(document).on('click', '#selectall', this.toggle_selection);
        this.initialize_searchfield();
    },

    /**
     * Search field initialization.
     */
    initialize_searchfield: function() {
        $("#searchfield").searchbar({
            navobj: this.navobj,
            pattern_changed: function(navobj) {
                navobj.setparam("reset_page", "true");
            }
        });
    },

    /**
     * Activate the button corresponding to the current message type
     * filter. If no message type is found, the 'All' button is
     * selected.
     */
    set_msgtype: function() {
        var msgtype = this.navobj.getparam('msgtype');

        $("input[name*=msgtype]").attr("checked", false)
            .parent().removeClass('active');

        if (msgtype !== undefined) {
            $("input[name=msgtype_" + msgtype + "]").attr("checked", true)
                .parent().addClass('active');
        } else {
            $("button[name=msgtype_all]").attr("checked", true)
                .parent().addClass('active');
        }
    },

    /**
     * Update the main page content.
     *
     * @this Quarantine
     * @param {Object} data - new content
     */
    update_page: function(data) {
        if (data.menu !== undefined) {
            $("#menubar").html(data.menu);
            this.initialize_searchfield();
        }

        if (data.listing !== undefined) {
            $("#listing").html(data.listing);
        }
        if (this.navobj.getbaseurl() == "listing") {
            this.update_listing(data);
            $(this.options.scroll_container).scrollTop(10);
        } else {
            this.update_listing(data, false);
        }
    },

    listen: function() {
        $(document).on("click", "td[class*=openable]", $.proxy(this.viewmail_loader, this));
        $(document).on("click", "a[name=selectmsgs]", $.proxy(this.selectmsgs, this));
        $(document).on("click", "a[name=release-multi]",
            $.proxy(this.release_selection, this));
        $(document).on("click", "a[name=delete-multi]",
            $.proxy(this.delete_selection, this));
        $(document).on("click", "a[name=mark-as-spam-multi]",
            $.proxy(this.mark_selection_as_spam, this));
        $(document).on("click", "a[name=mark-as-ham-multi]",
            $.proxy(this.mark_selection_as_ham, this));
        $(document).on("click", "a[name=viewrequests]",
            $.proxy(this.view_requests, this));
        $(document).on("click", "a[name=release]", $.proxy(this.release, this));
        $(document).on("click", "a[name=delete]", $.proxy(this.delete, this));
        $(document).on("click", "a[name=mark-as-spam]",
            $.proxy(this.mark_as_spam, this));
        $(document).on("click", "a[name=mark-as-ham]",
            $.proxy(this.mark_as_ham, this));
        $(document).on("click", "a[name=headers]", $.proxy(this.headers, this));
        $(document).on("click", "td[name=type] span", $.proxy(this.filter_by_type, this));
        $(document).on("click", "#filters label", $.proxy(this.filter_by_type, this));
    },

    load_page: function(e) {
        Listing.prototype.load_page.apply(this, arguments);
        this.navobj.delparam("rcpt").update();
    },

    /**
     * Return extra arguments used to fetch a page.
     *
     * @this Listing
     */
    get_load_page_args: function() {
        var args = Listing.prototype.get_load_page_args.call(this);

        args.scroll = true;
        return args;
    },

    /**
     * Calculate the bottom position of the scroll container.
     *
     * @param {Object} $element - scroll container object
     */
    calculate_bottom: function($element) {
        var emails_height = $("#emails").height();

        if (!emails_height) {
            return undefined;
        }
        return $("#emails").height() - $element.height();
    },

    view_requests: function(e) {
        e.preventDefault();
        this.navobj.setparam("viewrequests", "1").update();
    },

    viewmail_loader: function(e) {
        e.preventDefault();
        var $tr = $(e.target).parent();
        var $to = $tr.find("td[name=to]");

        this.navobj.baseurl($tr.attr("id"));
        if ($to.length) {
            this.navobj.setparam("rcpt", $to.html().trim());
        }
        this.navobj.update();
    },

    /*
     * Toggle message selection when the top checkbox's state is
     * modified.
     *
     * If it is checked, all messages are selected. Otherwise, the
     * current selection is resetted.
     */
    toggle_selection: function(e) {
        if (!$('#selectall').prop('checked')) {
            $("#emails").htmltable("clear_selection");
            return;
        }
        $("td[name*=selection]").each(function() {
            var $input = $(this).children('input');
            $input.prop('checked', true);
            $('#emails').htmltable('select_row', $(this).parent());
        });
    },

    /*
     * Select all messages of a specific type.
     */
    selectmsgs: function(e) {
        e.preventDefault();
        var type = get_target(e, 'a').attr("href");
        var counter = 0;

        $("td[name=type]").each(function() {
            var $this = $(this);
            if ($this.find('span').html().trim() == type) {
                var $input = $this.parent().children('td[name=selection]').children('input');
                $input.prop('checked', true);
                $('#emails').htmltable('select_row', $this.parent());
                counter++;
            }
        });
        if (counter) {
            $("#selectall").prop('checked', true);
        }
    },

    /**
     * Filter listing by message type (spam, virus, etc.)
     *
     * @param {Object} evt - event object
     */
    filter_by_type: function(evt) {
        var $target = $(evt.target);
        var msgtype;

        if ($target.is("span")) {
            msgtype = $target.html().trim();
        } else {
            msgtype = $target.children("input").attr("name").replace("msgtype_", "");
        }

        if (msgtype != 'all') {
            this.navobj.setparam('msgtype', msgtype);
        } else {
            this.navobj.delparam('msgtype');
        }
        this.navobj.update();
    },

    /**
     * Return the list of currently selected messages.
     *
     * @return {Array} - list of message IDs
     */
    get_current_selection: function() {
        var selection = [];

        this.htmltable.current_selection().each(function() {
            var $tr = $(this);
            var $to = $tr.find("td[name=to]");

            if ($to.length) {
                selection.push($to.html().trim() + " " + $tr.attr("id"));
            } else {
                selection.push($tr.attr("id"));
            }
        });
        return selection;
    },

    _send_selection: function(e, name, message) {
        var $link = $(e.target);

        e.preventDefault();
        if (!this.htmltable.current_selection().length ||
            !confirm(message)) {
            return;
        }
        var selection = this.get_current_selection();
        var data = {
            action: name,
            selection: selection.join(",")
        };

        $.ajax({
            url: $link.attr("href"),
            data: data,
            type: 'POST',
            dataType: 'json'
        }).done(
            $.proxy(this.action_cb, this)
        ).fail(function(jqxhr) {
            var data = $.parseJSON(jqxhr.responseText);
            $("body").notify("error", data.message);
        });
    },

    release_selection: function(e) {
        this._send_selection(e, "release", gettext("Release this selection?"));
    },

    delete_selection: function(e) {
        this._send_selection(e, "delete", gettext("Delete this selection?"));
    },

    /**
     * Show the recipient selection form inside a modal box.
     *
     * @param {Object} evt - event object
     * @param {string} ltype - learning type (spam or ham)
     */
    show_select_rcpt_form: function(evt, ltype, selection) {
        if (selection === undefined) {
            selection = this.get_current_selection();
        }
        var url = this.options.learning_recipient_url +
            "?type=" + ltype + "&selection=" +
            selection.join(",");
        var $this = this;

        modalbox(evt, null, url, function() {
            $(".submit").on("click", function(evt) {
                simple_ajax_form_post(evt, {
                    formid: "learning_recipient_form",
                    reload_on_success: false,
                    success_cb: $.proxy($this.action_cb, $this)
                });
            });
        });
    },

    /**
     * Mark the current selection as spam.
     *
     * @param {Object} e - event object
     */
    mark_selection_as_spam: function(e) {
        if (this.options.check_learning_rcpt &&
            this.htmltable.current_selection().length) {
            this.show_select_rcpt_form(e, "spam");
        } else {
            this._send_selection(
                e, "mark_as_spam", gettext("Mark this selection as spam?"));
        }
    },

    /**
     * Mark the current selection as ham.
     *
     * @param {Object} e - event object
     */
    mark_selection_as_ham: function(e) {
        if (this.options.check_learning_rcpt &&
            this.htmltable.current_selection().length) {
            this.show_select_rcpt_form(e, "ham");
        } else {
            this._send_selection(
                e, "mark_as_ham", gettext("Mark this selection as non-spam?"));
        }
    },

    _send_action: function(e, message) {
        var $link = get_target(e, "a");

        e.preventDefault();
        if (!confirm(message)) {
            return;
        }
        $.ajax({
            url: $link.attr("href"),
            dataType: 'json',
            type: 'POST',
            data: {rcpt: get_parameter_by_name($link.attr("href"), 'rcpt', true)}
        }).done(
            $.proxy(this.action_cb, this)
        ).fail(function(jqxhr) {
            var data = $.parseJSON(jqxhr.responseText);
            $("body").notify("error", data.message);
        });
    },

    release : function(e) {
        this._send_action(e, gettext("Release this message?"));
    },

    delete: function(e) {
        this._send_action(e, gettext("Delete this message?"));
    },

    /**
     * Mark the current message as spam.
     *
     * @param {Object} e - event object
     */
    mark_as_spam: function(e) {
        if (this.options.check_learning_rcpt) {
            var $link = get_target(e, "a");
            var selection = get_parameter_by_name($link.attr("href"), "rcpt") +
                " " + $link.attr("data-mail-id");
            this.show_select_rcpt_form(e, "spam", [selection]);
        } else {
            this._send_action(e, gettext("Mark as spam?"));
        }
    },

    /**
     * Mark the current message as ham.
     *
     * @param {Object} e - event object
     */
    mark_as_ham: function(e) {
        if (this.options.check_learning_rcpt) {
            var $link = get_target(e, "a");
            var selection = get_parameter_by_name($link.attr("href"), "rcpt") +
                " " + $link.attr("data-mail-id");
            this.show_select_rcpt_form(e, "ham", [selection]);
        } else {
            this._send_action(e, gettext("Mark as non-spam?"));
        }
    },

    show_rawheaders: function($mailcontent) {
        $mailcontent.find("#rawheaders").removeClass("hidden");
        $mailcontent.find("#emailheaders").addClass("hidden");
    },

    headers: function(e) {
        e.preventDefault();

        var $link = get_target(e, "a");
        var $mailcontent = $("#mailcontent").contents();
        var $headers = $mailcontent.find("#emailheaders");
        var $rawheaders = $mailcontent.find("#rawheaders");

        if ($headers.hasClass("hidden")) {
            $link.html(gettext("View full headers"));
            $headers.removeClass("hidden");
            $rawheaders.addClass("hidden");
            return;
        }
        $link.html(gettext("Hide full headers"));
        if (!$rawheaders.length) {
            $.ajax({
                url: $link.attr("href"),
                global: false
            }).done($.proxy(function(data) {
                $mailcontent.find("#table-container").append($(data));
                this.show_rawheaders($mailcontent);
            }, this));
            return;
        }
        this.show_rawheaders($mailcontent);
    },

    update_params: function(e) {
        var $link = $(e.target);
        e.preventDefault();
        this.navobj.updateparams($link.attr("href")).update();
    },

    register_navcallbacks: function() {
        this.navobj.register_callback("_listing",
            $.proxy(this.listing_cb, this));
        this.navobj.register_callback("viewmail",
            $.proxy(this.viewmail_cb, this));
    },

    activate_buttons: function($tr) {
        $("a[name*=-multi]").removeClass('disabled');
        $("#selectall").prop('checked', true);
    },

    deactivate_buttons: function($tr) {
        if (!this.htmltable || !this.htmltable.current_selection().length) {
            $("a[name*=-multi]").addClass('disabled');
            $("#selectall").prop('checked', false);
        }
    },

    /**
     * Navigation callback: listing.
     *
     * @this Quarantine
     * @param {Object} data - ajax call response (JSON)
     */
    listing_cb: function(data) {
        this.update_page(data);
        this.navobj.delparam("rcpt").update();
        this.set_msgtype();
        $("#emails").htmltable({
            row_selected_event: this.activate_buttons,
            row_unselected_event: $.proxy(this.deactivate_buttons, this)
        });
        this.htmltable = $("#emails").data("htmltable");
        this.deactivate_buttons();
        if (this.navobj.hasparam("reset_page")) {
            this.navobj.delparam("reset_page").update(false, true);
        }
        $("#listing").css("overflow", "auto");
    },

    viewmail_cb: function(data) {
        this.update_page(data);
        $("#listing").css("overflow", "hidden");
    },

    action_cb: function(data) {
        if (data.reload) {
            this.navobj.update(true);
        }
        if (data.url) {
            this.navobj.parse_string(data.url, true).update(true);
        }
        $("body").notify("success", data.message, 2000);
    }
};

Quarantine.prototype = $.extend({}, Listing.prototype, Quarantine.prototype);
<|endoftext|>


<commit_before>/*
 * Constant strings used in the activity model
 */

export default {
  ACTIVITY_ALL: 'all',
  CONNECTED_ACCOUNT_CREATED: 'connected_account.created',
  COLLECTIVE_APPLY: 'collective.apply',
  COLLECTIVE_APPROVED: 'collective.approved',
  COLLECTIVE_CREATED: 'collective.created',
  COLLECTIVE_COMMENT_CREATED: 'collective.comment.created',
  COLLECTIVE_EXPENSE_CREATED: 'collective.expense.created',
  COLLECTIVE_EXPENSE_DELETED: 'collective.expense.deleted',
  COLLECTIVE_EXPENSE_UPDATED: 'collective.expense.updated',
  COLLECTIVE_EXPENSE_REJECTED: 'collective.expense.rejected',
  COLLECTIVE_EXPENSE_APPROVED: 'collective.expense.approved',
  COLLECTIVE_EXPENSE_PAID: 'collective.expense.paid',
  COLLECTIVE_MEMBER_CREATED: 'collective.member.created',
  COLLECTIVE_TRANSACTION_CREATED: 'collective.transaction.created',
  COLLECTIVE_UPDATE_CREATED: 'collective.update.created',
  COLLECTIVE_UPDATE_PUBLISHED: 'collective.update.published',
  COLLECTIVE_USER_ADDED: 'collective.user.added',
  ORGANIZATION_COLLECTIVE_CREATED: 'organization.collective.created',
  SUBSCRIPTION_CONFIRMED: 'subscription.confirmed',
  SUBSCRIPTION_CANCELED: 'subscription.canceled',
  TICKET_CONFIRMED: 'ticket.confirmed',
  USER_CREATED: 'user.created',
  WEBHOOK_STRIPE_RECEIVED: 'webhook.stripe.received',
  WEBHOOK_PAYPAL_RECEIVED: 'webhook.paypal.received',
  COLLECTIVE_MONTHLY: 'collective.monthly',
  ORDERS_SUSPICIOUS: 'orders.suspicious',

  // Not used anymore, leaving for historical reference
  COLLECTIVE_TRANSACTION_PAID: 'collective.transaction.paid', // replaced with COLLECTIVE_EXPENSE_PAID
};
<commit_msg>fix(notification): add GITHUB_COLLECTIVE_CREATED to activities<commit_after>/*
 * Constant strings used in the activity model
 */

export default {
  ACTIVITY_ALL: 'all',
  CONNECTED_ACCOUNT_CREATED: 'connected_account.created',
  GITHUB_COLLECTIVE_CREATED: 'github.collective.created',
  COLLECTIVE_APPLY: 'collective.apply',
  COLLECTIVE_APPROVED: 'collective.approved',
  COLLECTIVE_CREATED: 'collective.created',
  COLLECTIVE_COMMENT_CREATED: 'collective.comment.created',
  COLLECTIVE_EXPENSE_CREATED: 'collective.expense.created',
  COLLECTIVE_EXPENSE_DELETED: 'collective.expense.deleted',
  COLLECTIVE_EXPENSE_UPDATED: 'collective.expense.updated',
  COLLECTIVE_EXPENSE_REJECTED: 'collective.expense.rejected',
  COLLECTIVE_EXPENSE_APPROVED: 'collective.expense.approved',
  COLLECTIVE_EXPENSE_PAID: 'collective.expense.paid',
  COLLECTIVE_MEMBER_CREATED: 'collective.member.created',
  COLLECTIVE_TRANSACTION_CREATED: 'collective.transaction.created',
  COLLECTIVE_UPDATE_CREATED: 'collective.update.created',
  COLLECTIVE_UPDATE_PUBLISHED: 'collective.update.published',
  COLLECTIVE_USER_ADDED: 'collective.user.added',
  ORGANIZATION_COLLECTIVE_CREATED: 'organization.collective.created',
  SUBSCRIPTION_CONFIRMED: 'subscription.confirmed',
  SUBSCRIPTION_CANCELED: 'subscription.canceled',
  TICKET_CONFIRMED: 'ticket.confirmed',
  USER_CREATED: 'user.created',
  WEBHOOK_STRIPE_RECEIVED: 'webhook.stripe.received',
  WEBHOOK_PAYPAL_RECEIVED: 'webhook.paypal.received',
  COLLECTIVE_MONTHLY: 'collective.monthly',
  ORDERS_SUSPICIOUS: 'orders.suspicious',

  // Not used anymore, leaving for historical reference
  COLLECTIVE_TRANSACTION_PAID: 'collective.transaction.paid', // replaced with COLLECTIVE_EXPENSE_PAID
};
<|endoftext|>


<commit_before>var Project 		= require('mongoose').model('Project'),
    Country 		= require('mongoose').model('Country'),
    Source	 		= require('mongoose').model('Source'),
    Link 	        = require('mongoose').model('Link'),
    Transfer 	    = require('mongoose').model('Transfer'),
    Production 	    = require('mongoose').model('Production'),
    async           = require('async'),
    _               = require("underscore"),
    request         = require('request'),
    encrypt 		= require('../utilities/encryption');

exports.getProjects = function(req, res) {
    var project_len, link_len, project_counter, link_counter,
        limit = Number(req.params.limit),
        skip = Number(req.params.skip);

    async.waterfall([
        projectCount,
        getProjectSet,
        getProjectLinks
    ], function (err, result) {
        if (err) {
            res.send(err);
        }
    });

    function projectCount(callback) {
        Project.find({}).count().exec(function(err, project_count) {
            if(project_count) {
                callback(null, project_count);
            } else {
                callback(err);
            }
        });
    }

    function getProjectSet(project_count, callback) {
        Project.find(req.query)
            .sort({
                proj_name: 'asc'
            })
            .skip(skip)
            .limit(limit)
            .populate('proj_country.country', '_id iso2 name')
            //.populate('proj_aliases', ' _id alias')
            .lean()
            .exec(function(err, projects) {
                if(projects.length>0) {
                    callback(null, project_count, projects);
                } else {
                    //callback(err);
                    res.send({data: projects, count: project_count});
                }
            });
    }

    function getProjectLinks(project_count, projects, callback) {
        project_len = projects.length;
        project_counter = 0;
        if(project_len>0) {
            projects.forEach(function (c) {
                Link.find({project: c._id})
                    .populate('commodity', '_id commodity_name')
                    .populate('company')
                    .exec(function (err, links) {
                        ++project_counter;
                        link_len = links.length;
                        link_counter = 0;
                        c.proj_commodity = [];
                        c.companies = 0;
                        links.forEach(function (link) {
                            ++link_counter;
                            var entity = _.without(link.entities, 'project')[0];
                            switch (entity) {
                                case 'commodity':
                                    c.proj_commodity.push({
                                        _id: link.commodity._id,
                                        commodity_name: link.commodity.commodity_name
                                    });
                                    break;
                                //
                                case 'company':
                                    c.companies += 1;
                                    break;
                                //
                                default:
                                //console.log('error');
                            }
                        });
                        if (project_counter == project_len && link_counter == link_len) {
                            res.send({data: projects, count: project_count});
                        }
                    });
            });
        } else{
            res.send({data: projects, count: project_count});
        }
    }
};

exports.getProjectByID = function(req, res) {
    var link_counter, link_len,project_counter, project_len;

    async.waterfall([
        getProject,
        //getTransfers,
        //getProductions,
        getProjectLinks,
        getProjectCoordinate,
        getCompanyGroup
    ], function (err, result) {
        if (err) {
            res.send(err);
        }

    });

    function getProject(callback) {
        Project.findOne({_id:req.params.id})
            .populate('proj_country.country')
            .populate('proj_aliases', '_id alias')
            .populate('proj_commodity.commodity')
            .lean()
            .exec(function(err, project) {
                if(project) {
                    callback(null, project);
                } else {
                    callback(err);
                }
            });
    }
    //function getTransfers(project, callback) {
    //    project.transfers = [];
    //    Transfer.find({transfer_project: project._id})
    //        .populate('transfer_country')
    //        .populate('transfer_company', '_id company_name')
    //        .exec(function(err, transfers) {
    //            console.log(transfers);
    //            _.each(transfers, function(transfer) {
    //                project.transfers.push(transfer);
    //            });
    //            if(project) {
    //                callback(null, project);
    //            } else {
    //                callback(err);
    //            }
    //        });
    //}
    //function getProductions(project, callback) {
    //    project.productions = [];
    //    Production.find({production_project: project._id})
    //        .populate('production_commodity')
    //        .exec(function(err, productions) {
    //            _.each(productions, function(productions) {
    //                project.productions.push(productions);
    //            });
    //            if(project) {
    //                callback(null, project);
    //            } else {
    //                callback(err);
    //            }
    //        });
    //}
    function getProjectLinks(project, callback) {
        project.companies = [];
        project.commodities = [];
        project.transfers = [];
        project.projects = [];
        project.production = [];
        project.concessions = [];
        project.contracts = [];
        project.sources = {};
        Link.find({project: project._id})
            .populate('commodity')
            .populate('company')
            .populate('contract')
            .populate('concession')
            //.populate('source')
            //.populate('transfer')
            //.populate('production')
            .deepPopulate('company_group transfer.transfer_company transfer.transfer_country production.production_commodity source.source_type_id')
            //.deepPopulate('company company.company_group')
            .exec(function(err, links) {
                if(links.length>0) {
                    link_len = links.length;
                    link_counter = 0;
                    links.forEach(function (link) {
                        ++link_counter;
                        var entity = _.without(link.entities, 'project')[0];
                        console.log(link);
                        console.log(link.source);
                        //console.log(link.source._id);
                        if (!project.sources[link.source._id]) {
                            project.sources[link.source._id] = link.source;
                        }
                        switch (entity) {
                            case 'commodity':
                                if (!project.commodities.hasOwnProperty(link.commodity_code)) {
                                    project.commodities.push({
                                        _id: link.commodity._id,
                                        commodity_name:link.commodity.commodity_name});
                                }
                                break;
                            case 'company':
                                if (!project.companies.hasOwnProperty(link.company._id)) {
                                    project.companies.push({
                                        _id: link.company._id,
                                        company_name: link.company.company_name
                                    });
                                }
                                break;
                            case 'concession':
                                project.concessions.push({
                                    _id: link.concession._id,
                                    concession_name: link.concession.concession_name
                                });
                                break;
                            case 'concession':
                                project.concessions.push({
                                    _id: link.concession._id,
                                    concession_name: link.concession.concession_name
                                });
                                break;
                            case 'contract':
                                project.contracts.push(link);
                                break;
                            case 'transfer':
                                project.transfers.push(link);
                                break;
                            case 'production':
                                //console.log(link);
                                project.production.push(link);
                                break;
                            default:
                                //console.log(link);
                                console.log('error');
                        }
                        if(link_counter == link_len) {
                            callback(null, project);
                        }
                    });
                }
            });
    }

    function getProjectCoordinate(project, callback) {
        project.coordinates = [];
        project_counter = 0;
        project_len = project.proj_coordinates.length;
        if(project_len>0) {
            project.proj_coordinates.forEach(function (loc) {
                ++project_counter;
                project.coordinates.push({
                    'lat': loc.loc[0],
                    'lng': loc.loc[1],
                    'message': project.proj_name,
                    'timestamp': loc.timestamp
                });
                if (project_counter == project_len) {
                    callback(null, project);
                }
            });
        } else {
            callback(null, project);

        }
    }
    function getCompanyGroup(project, callback) {
        project_len = project.companies.length;
        project_counter = 0;
        project.companies.forEach(function(company) {
            Link.find({company: company._id})
                .populate('company_group', '_id company_group_name')
                .exec(function (err, links) {
                    ++project_counter;
                    link_len = links.length;
                    link_counter = 0;
                    company.company_groups = [];
                    links.forEach(function (link) {
                        ++link_counter;
                        var entity = _.without(link.entities, 'company')[0];
                        switch (entity) {
                            case 'company_group':
                                if (!company.company_groups.hasOwnProperty(link.company_group._id)) {
                                    company.company_groups.push({
                                        _id: link.company_group._id,
                                        company_group_name: link.company_group.company_group_name
                                    });
                                }
                                break;
                            default:
                                //console.log('error');
                        }
                        if(project_counter == project_len && link_counter == link_len) {
                            res.send(project);
                        }
                    });
                });
        });
    }

};

exports.getProjectsMap = function(req, res) {
    var project_len, project_counter;
    async.waterfall([
        getProject
    ], function (err, result) {
        if (err) {
            res.send(err);
        }

    });

    function getProject(callback) {
        Project.find(req.query)
            .lean()
            .exec(function(err, projects) {
                project_len = projects.length;
                project_counter = 0;
                var data = [];
                if(projects) {
                    projects.forEach(function (project) {
                        ++project_counter;
                        project.proj_coordinates.forEach(function (loc) {
                            data.push({
                                'lat':loc.loc[0],
                                'lng':loc.loc[1],
                                'message':""+project.proj_name+"
"+project.proj_name
                            })
                        })
                    });
                    if(project_counter == project_len) {
                        res.send({data:data});}
                } else {
                    callback(err);
                }
            });
    }
};

exports.createProject = function(req, res, next) {
    var projectData = req.body;
	Project.create(projectData, function(err, project) {
		if(err){
			err = new Error('Error');
			res.status(400);
			return res.send({reason:err.toString()})
		} else{
			res.send();
		}
	});
};

exports.updateProject = function(req, res) {
    var projectUpdates = req.body;
    console.log(projectUpdates);
    Project.findOne({_id:req.body._id}).exec(function(err, project) {
        if(err) {
            err = new Error('Error');
            res.status(400);
            return res.send({ reason: err.toString() });
        }
        project.proj_name= projectUpdates.proj_name;
        //project.proj_aliases= projectUpdates.proj_aliases;
        //project.proj_established_source= projectUpdates.proj_established_source;
        //project.proj_country= projectUpdates.proj_country;
        //project.proj_type= projectUpdates.proj_type;
        ////project.proj_commodity= projectUpdates.proj_commodity;
        //project.proj_site_name= projectUpdates.proj_site_name;
        //project.proj_address= projectUpdates.proj_address;
        //project.proj_coordinates= projectUpdates.proj_coordinates;
        //project.proj_status= projectUpdates.proj_status;
        //project.description= projectUpdates.description;
        project.save(function(err) {
            if(err) {
                err = new Error('Error');
                return res.send({reason: err.toString()});
            } else{
                res.send();
            }
        })
    });
};

exports.deleteProject = function(req, res) {
    Project.remove({_id: req.params.id}, function(err) {
        if(!err) {
            res.send();
        }else{
            return res.send({ reason: err.toString() });
        }
    });
};<commit_msg>SAVEPOINT<commit_after>var Project 		= require('mongoose').model('Project'),
    Country 		= require('mongoose').model('Country'),
    Source	 		= require('mongoose').model('Source'),
    Link 	        = require('mongoose').model('Link'),
    Transfer 	    = require('mongoose').model('Transfer'),
    Production 	    = require('mongoose').model('Production'),
    async           = require('async'),
    _               = require("underscore"),
    request         = require('request'),
    encrypt 		= require('../utilities/encryption');

exports.getProjects = function(req, res) {
    var project_len, link_len, project_counter, link_counter,
        limit = Number(req.params.limit),
        skip = Number(req.params.skip);

    async.waterfall([
        projectCount,
        getProjectSet,
        getProjectLinks
    ], function (err, result) {
        if (err) {
            res.send(err);
        }
    });

    function projectCount(callback) {
        Project.find({}).count().exec(function(err, project_count) {
            if(project_count) {
                callback(null, project_count);
            } else {
                callback(err);
            }
        });
    }

    function getProjectSet(project_count, callback) {
        Project.find(req.query)
            .sort({
                proj_name: 'asc'
            })
            .skip(skip)
            .limit(limit)
            .populate('proj_country.country', '_id iso2 name')
            //.populate('proj_aliases', ' _id alias')
            .lean()
            .exec(function(err, projects) {
                if(projects.length>0) {
                    callback(null, project_count, projects);
                } else {
                    //callback(err);
                    res.send({data: projects, count: project_count});
                }
            });
    }

    function getProjectLinks(project_count, projects, callback) {
        project_len = projects.length;
        project_counter = 0;
        if(project_len>0) {
            projects.forEach(function (c) {
                Link.find({project: c._id})
                    .populate('commodity', '_id commodity_name')
                    .populate('company')
                    .exec(function (err, links) {
                        ++project_counter;
                        link_len = links.length;
                        link_counter = 0;
                        c.proj_commodity = [];
                        c.companies = 0;
                        links.forEach(function (link) {
                            ++link_counter;
                            var entity = _.without(link.entities, 'project')[0];
                            switch (entity) {
                                case 'commodity':
                                    c.proj_commodity.push({
                                        _id: link.commodity._id,
                                        commodity_name: link.commodity.commodity_name
                                    });
                                    break;
                                //
                                case 'company':
                                    c.companies += 1;
                                    break;
                                //
                                default:
                                //console.log('error');
                            }
                        });
                        if (project_counter == project_len && link_counter == link_len) {
                            res.send({data: projects, count: project_count});
                        }
                    });
            });
        } else{
            res.send({data: projects, count: project_count});
        }
    }
};

exports.getProjectByID = function(req, res) {
    var link_counter, link_len,project_counter, project_len;

    async.waterfall([
        getProject,
        //getTransfers,
        //getProductions,
        getProjectLinks,
        getProjectCoordinate,
        getCompanyGroup
    ], function (err, result) {
        if (err) {
            res.send(err);
        }

    });

    function getProject(callback) {
        Project.findOne({_id:req.params.id})
            .populate('proj_country.country')
            .populate('proj_aliases', '_id alias')
            .populate('proj_commodity.commodity')
            .lean()
            .exec(function(err, project) {
                if(project) {
                    callback(null, project);
                } else {
                    callback(err);
                }
            });
    }
    //function getTransfers(project, callback) {
    //    project.transfers = [];
    //    Transfer.find({transfer_project: project._id})
    //        .populate('transfer_country')
    //        .populate('transfer_company', '_id company_name')
    //        .exec(function(err, transfers) {
    //            console.log(transfers);
    //            _.each(transfers, function(transfer) {
    //                project.transfers.push(transfer);
    //            });
    //            if(project) {
    //                callback(null, project);
    //            } else {
    //                callback(err);
    //            }
    //        });
    //}
    //function getProductions(project, callback) {
    //    project.productions = [];
    //    Production.find({production_project: project._id})
    //        .populate('production_commodity')
    //        .exec(function(err, productions) {
    //            _.each(productions, function(productions) {
    //                project.productions.push(productions);
    //            });
    //            if(project) {
    //                callback(null, project);
    //            } else {
    //                callback(err);
    //            }
    //        });
    //}
    function getProjectLinks(project, callback) {
        project.companies = [];
        project.commodities = [];
        project.transfers = [];
        project.projects = [];
        project.production = [];
        project.concessions = [];
        project.contracts = [];
        project.sources = {};
        Link.find({project: project._id})
            .populate('commodity')
            .populate('company')
            .populate('contract')
            .populate('concession')
            //.populate('source')
            //.populate('transfer')
            //.populate('production')
            .deepPopulate('company_group transfer.transfer_company transfer.transfer_country production.production_commodity source.source_type_id')
            //.deepPopulate('company company.company_group')
            .exec(function(err, links) {
                if(links.length>0) {
                    link_len = links.length;
                    link_counter = 0;
                    links.forEach(function (link) {
                        ++link_counter;
                        var entity = _.without(link.entities, 'project')[0];
                        //console.log(link);
                        //console.log(link.source);
                        //console.log(link.source._id);
                        if (!project.sources[link.source._id]) {
                            project.sources[link.source._id] = link.source;
                        }
                        switch (entity) {
                            case 'commodity':
                                if (!project.commodities.hasOwnProperty(link.commodity_code)) {
                                    project.commodities.push({
                                        _id: link.commodity._id,
                                        commodity_name:link.commodity.commodity_name});
                                }
                                break;
                            case 'company':
                                if (!project.companies.hasOwnProperty(link.company._id)) {
                                    project.companies.push({
                                        _id: link.company._id,
                                        company_name: link.company.company_name
                                    });
                                }
                                break;
                            case 'concession':
                                project.concessions.push({
                                    _id: link.concession._id,
                                    concession_name: link.concession.concession_name
                                });
                                break;
                            case 'concession':
                                project.concessions.push({
                                    _id: link.concession._id,
                                    concession_name: link.concession.concession_name
                                });
                                break;
                            case 'contract':
                                project.contracts.push(link);
                                break;
                            case 'transfer':
                                project.transfers.push(link);
                                break;
                            case 'production':
                                //console.log(link);
                                project.production.push(link);
                                break;
                            default:
                                //console.log(link);
                                console.log('error');
                        }
                        if(link_counter == link_len) {
                            callback(null, project);
                        }
                    });
                }
            });
    }

    function getProjectCoordinate(project, callback) {
        project.coordinates = [];
        project_counter = 0;
        project_len = project.proj_coordinates.length;
        if(project_len>0) {
            project.proj_coordinates.forEach(function (loc) {
                ++project_counter;
                project.coordinates.push({
                    'lat': loc.loc[0],
                    'lng': loc.loc[1],
                    'message': project.proj_name,
                    'timestamp': loc.timestamp
                });
                if (project_counter == project_len) {
                    callback(null, project);
                }
            });
        } else {
            callback(null, project);

        }
    }
    function getCompanyGroup(project, callback) {
        project_len = project.companies.length;
        project_counter = 0;
        project.companies.forEach(function(company) {
            Link.find({company: company._id})
                .populate('company_group', '_id company_group_name')
                .exec(function (err, links) {
                    ++project_counter;
                    link_len = links.length;
                    link_counter = 0;
                    company.company_groups = [];
                    links.forEach(function (link) {
                        ++link_counter;
                        var entity = _.without(link.entities, 'company')[0];
                        switch (entity) {
                            case 'company_group':
                                if (!company.company_groups.hasOwnProperty(link.company_group._id)) {
                                    company.company_groups.push({
                                        _id: link.company_group._id,
                                        company_group_name: link.company_group.company_group_name
                                    });
                                }
                                break;
                            default:
                                //console.log('error');
                        }
                        if(project_counter == project_len && link_counter == link_len) {
                            res.send(project);
                        }
                    });
                });
        });
    }

};

exports.getProjectsMap = function(req, res) {
    var project_len, project_counter;
    async.waterfall([
        getProject
    ], function (err, result) {
        if (err) {
            res.send(err);
        }

    });

    function getProject(callback) {
        Project.find(req.query)
            .lean()
            .exec(function(err, projects) {
                project_len = projects.length;
                project_counter = 0;
                var data = [];
                if(projects) {
                    projects.forEach(function (project) {
                        ++project_counter;
                        project.proj_coordinates.forEach(function (loc) {
                            data.push({
                                'lat':loc.loc[0],
                                'lng':loc.loc[1],
                                'message':""+project.proj_name+"
"+project.proj_name
                            })
                        })
                    });
                    if(project_counter == project_len) {
                        res.send({data:data});}
                } else {
                    callback(err);
                }
            });
    }
};

exports.createProject = function(req, res, next) {
    var projectData = req.body;
	Project.create(projectData, function(err, project) {
		if(err){
			err = new Error('Error');
			res.status(400);
			return res.send({reason:err.toString()})
		} else{
			res.send();
		}
	});
};

exports.updateProject = function(req, res) {
    var projectUpdates = req.body;
    console.log(projectUpdates);
    Project.findOne({_id:req.body._id}).exec(function(err, project) {
        if(err) {
            err = new Error('Error');
            res.status(400);
            return res.send({ reason: err.toString() });
        }
        project.proj_name= projectUpdates.proj_name;
        //project.proj_aliases= projectUpdates.proj_aliases;
        //project.proj_established_source= projectUpdates.proj_established_source;
        //project.proj_country= projectUpdates.proj_country;
        //project.proj_type= projectUpdates.proj_type;
        ////project.proj_commodity= projectUpdates.proj_commodity;
        //project.proj_site_name= projectUpdates.proj_site_name;
        //project.proj_address= projectUpdates.proj_address;
        //project.proj_coordinates= projectUpdates.proj_coordinates;
        //project.proj_status= projectUpdates.proj_status;
        //project.description= projectUpdates.description;
        project.save(function(err) {
            if(err) {
                err = new Error('Error');
                return res.send({reason: err.toString()});
            } else{
                res.send();
            }
        })
    });
};

exports.deleteProject = function(req, res) {
    Project.remove({_id: req.params.id}, function(err) {
        if(!err) {
            res.send();
        }else{
            return res.send({ reason: err.toString() });
        }
    });
};<|endoftext|>


<commit_before>var Project 		= require('mongoose').model('Project'),
    Country 		= require('mongoose').model('Country'),
    Source	 		= require('mongoose').model('Source'),
    Link 	        = require('mongoose').model('Link'),
    Transfer 	    = require('mongoose').model('Transfer'),
    Production 	    = require('mongoose').model('Production'),
    async           = require('async'),
    _               = require("underscore"),
    request         = require('request'),
    encrypt 		= require('../utilities/encryption');

exports.getProjects = function(req, res) {
    var project_len, link_len, project_counter, link_counter,
        limit = Number(req.params.limit),
        skip = Number(req.params.skip);

    async.waterfall([
        projectCount,
        getProjectSet,
        getProjectLinks
    ], function (err, result) {
        if (err) {
            res.send(err);
        }
    });

    function projectCount(callback) {
        Project.find({}).count().exec(function(err, project_count) {
            if(project_count) {
                callback(null, project_count);
            } else {
                callback(err);
            }
        });
    }

    function getProjectSet(project_count, callback) {
        Project.find(req.query)
            .sort({
                proj_name: 'asc'
            })
            .skip(skip)
            .limit(limit)
            .populate('proj_country.country', '_id iso2 name')
            //.populate('proj_aliases', ' _id alias')
            .lean()
            .exec(function(err, projects) {
                if(projects.length>0) {
                    callback(null, project_count, projects);
                } else {
                    //callback(err);
                    res.send({data: projects, count: project_count});
                }
            });
    }

    function getProjectLinks(project_count, projects, callback) {
        project_len = projects.length;
        project_counter = 0;
        if(project_len>0) {
            projects.forEach(function (c) {
                Link.find({project: c._id})
                    .populate('commodity', '_id commodity_name')
                    .populate('company')
                    .exec(function (err, links) {
                        ++project_counter;
                        link_len = links.length;
                        link_counter = 0;
                        c.proj_commodity = [];
                        c.companies = 0;
                        links.forEach(function (link) {
                            ++link_counter;
                            var entity = _.without(link.entities, 'project')[0];
                            switch (entity) {
                                case 'commodity':
                                    c.proj_commodity.push({
                                        _id: link.commodity._id,
                                        commodity_name: link.commodity.commodity_name
                                    });
                                    break;
                                //
                                case 'company':
                                    c.companies += 1;
                                    break;
                                //
                                default:
                                //console.log('error');
                            }
                        });
                        if (project_counter == project_len && link_counter == link_len) {
                            res.send({data: projects, count: project_count});
                        }
                    });
            });
        } else{
            res.send({data: projects, count: project_count});
        }
    }
};

exports.getProjectByID = function(req, res) {
    var link_counter, link_len,project_counter, project_len;

    async.waterfall([
        getProject,
        //getTransfers,
        //getProductions,
        getProjectLinks,
        getProjectCoordinate,
        getCompanyGroup
    ], function (err, result) {
        if (err) {
            res.send(err);
        }
    });

    function getProject(callback) {
        Project.findOne({_id:req.params.id})
            .populate('proj_country.country')
            .populate('proj_aliases', '_id alias')
            .populate('proj_commodity.commodity')
            .lean()
            .exec(function(err, project) {
                if(project) {
                    callback(null, project);
                } else {
                    callback(err);
                }
            });
    }
    //function getTransfers(project, callback) {
    //    project.transfers = [];
    //    Transfer.find({transfer_project: project._id})
    //        .populate('transfer_country')
    //        .populate('transfer_company', '_id company_name')
    //        .exec(function(err, transfers) {
    //            console.log(transfers);
    //            _.each(transfers, function(transfer) {
    //                project.transfers.push(transfer);
    //            });
    //            if(project) {
    //                callback(null, project);
    //            } else {
    //                callback(err);
    //            }
    //        });
    //}
    //function getProductions(project, callback) {
    //    project.productions = [];
    //    Production.find({production_project: project._id})
    //        .populate('production_commodity')
    //        .exec(function(err, productions) {
    //            _.each(productions, function(productions) {
    //                project.productions.push(productions);
    //            });
    //            if(project) {
    //                callback(null, project);
    //            } else {
    //                callback(err);
    //            }
    //        });
    //}
    function getProjectLinks(project, callback) {
        project.companies = [];
        project.commodities = [];
        project.transfers = [];
        project.projects = [];
        project.production = [];
        project.concessions = [];
        project.contracts = [];
        project.sources = {};
        Link.find({project: project._id})
            .populate('commodity')
            .populate('company')
            .populate('contract')
            .populate('concession')
            //.populate('source')
            //.populate('transfer')
            //.populate('production')
            .deepPopulate('company_group transfer.transfer_company transfer.transfer_country production.production_commodity source.source_type_id')
            //.deepPopulate('company company.company_group')
            .exec(function(err, links) {
                if(links.length>0) {
                    link_len = links.length;
                    link_counter = 0;
                    links.forEach(function (link) {
                        ++link_counter;
                        var entity = _.without(link.entities, 'project')[0];
                        //console.log(link);
                        //console.log(link.source);
                        //console.log(link.source._id);
                        if (!project.sources[link.source._id]) {
                            project.sources[link.source._id] = link.source;
                        }
                        switch (entity) {
                            case 'commodity':
                                if (!project.commodities.hasOwnProperty(link.commodity_code)) {
                                    project.commodities.push({
                                        _id: link.commodity._id,
                                        commodity_name:link.commodity.commodity_name});
                                }
                                break;
                            case 'company':
                                if (!project.companies.hasOwnProperty(link.company._id)) {
                                    project.companies.push({
                                        _id: link.company._id,
                                        company_name: link.company.company_name
                                    });
                                }
                                break;
                            case 'concession':
                                project.concessions.push({
                                    _id: link.concession._id,
                                    concession_name: link.concession.concession_name
                                });
                                break;
                            case 'concession':
                                project.concessions.push({
                                    _id: link.concession._id,
                                    concession_name: link.concession.concession_name
                                });
                                break;
                            case 'contract':
                                project.contracts.push(link);
                                break;
                            case 'transfer':
                                project.transfers.push(link);
                                break;
                            case 'production':
                                //console.log(link);
                                project.production.push(link);
                                break;
                            default:
                                //console.log(link);
                                console.log('error');
                        }
                        if(link_counter == link_len) {
                            callback(null, project);
                        }
                    });
                }
            });
    }

    function getProjectCoordinate(project, callback) {
        project.coordinates = [];
        project_counter = 0;
        project_len = project.proj_coordinates.length;
        if(project_len>0) {
            project.proj_coordinates.forEach(function (loc) {
                ++project_counter;
                project.coordinates.push({
                    'lat': loc.loc[0],
                    'lng': loc.loc[1],
                    'message': project.proj_name,
                    'timestamp': loc.timestamp
                });
                if (project_counter == project_len) {
                    callback(null, project);
                }
            });
        } else {
            callback(null, project);
        }
    }
    function getCompanyGroup(project, callback) {
        project_len = project.companies.length;
        project_counter = 0;
        project.companies.forEach(function(company) {
            Link.find({company: company._id})
                .populate('company_group', '_id company_group_name')
                .exec(function (err, links) {
                    ++project_counter;
                    link_len = links.length;
                    link_counter = 0;
                    company.company_groups = [];
                    links.forEach(function (link) {
                        ++link_counter;
                        var entity = _.without(link.entities, 'company')[0];
                        switch (entity) {
                            case 'company_group':
                                if (!company.company_groups.hasOwnProperty(link.company_group._id)) {
                                    company.company_groups.push({
                                        _id: link.company_group._id,
                                        company_group_name: link.company_group.company_group_name
                                    });
                                }
                                break;
                            default:
                                //console.log('error');
                        }
                        if(project_counter == project_len && link_counter == link_len) {
                            res.send(project);
                        }
                    });
                });
        });
    }
};

exports.getProjectsMap = function(req, res) {
    var project_len, project_counter;
    async.waterfall([
        getProject
    ], function (err, result) {
        if (err) {
            res.send(err);
        }
    });

    function getProject(callback) {
        Project.find(req.query)
            .lean()
            .exec(function(err, projects) {
                project_len = projects.length;
                project_counter = 0;
                var data = [];
                if(projects) {
                    projects.forEach(function (project) {
                        ++project_counter;
                        project.proj_coordinates.forEach(function (loc) {
                            data.push({
                                'lat':loc.loc[0],
                                'lng':loc.loc[1],
                                'message':""+project.proj_name+"
"+project.proj_name
                            })
                        })
                    });
                    if(project_counter == project_len) {
                        res.send({data:data});}
                } else {
                    callback(err);
                }
            });
    }
};

exports.createProject = function(req, res, next) {
    var projectData = req.body;
	Project.create(projectData, function(err, project) {
		if(err){
			err = new Error('Error');
			res.status(400);
			return res.send({reason:err.toString()})
		} else{
			res.send();
		}
	});
};

exports.updateProject = function(req, res) {
    var projectUpdates = req.body;
    console.log(projectUpdates);
    Project.findOne({_id:req.body._id}).exec(function(err, project) {
        if(err) {
            err = new Error('Error');
            res.status(400);
            return res.send({ reason: err.toString() });
        }
        project.proj_name= projectUpdates.proj_name;
        //project.proj_aliases= projectUpdates.proj_aliases;
        //project.proj_established_source= projectUpdates.proj_established_source;
        //project.proj_country= projectUpdates.proj_country;
        //project.proj_type= projectUpdates.proj_type;
        ////project.proj_commodity= projectUpdates.proj_commodity;
        //project.proj_site_name= projectUpdates.proj_site_name;
        //project.proj_address= projectUpdates.proj_address;
        //project.proj_coordinates= projectUpdates.proj_coordinates;
        //project.proj_status= projectUpdates.proj_status;
        //project.description= projectUpdates.description;
        project.save(function(err) {
            if(err) {
                err = new Error('Error');
                return res.send({reason: err.toString()});
            } else{
                res.send();
            }
        })
    });
};

exports.deleteProject = function(req, res) {
    Project.remove({_id: req.params.id}, function(err) {
        if(!err) {
            res.send();
        }else{
            return res.send({ reason: err.toString() });
        }
    });
};<commit_msg>brought transfer links back to link model<commit_after>var Project 		= require('mongoose').model('Project'),
    Country 		= require('mongoose').model('Country'),
    Source	 		= require('mongoose').model('Source'),
    Link 	        = require('mongoose').model('Link'),
    Transfer 	    = require('mongoose').model('Transfer'),
    Production 	    = require('mongoose').model('Production'),
    async           = require('async'),
    _               = require("underscore"),
    request         = require('request'),
    encrypt 		= require('../utilities/encryption');

exports.getProjects = function(req, res) {
    var project_len, link_len, project_counter, link_counter,
        limit = Number(req.params.limit),
        skip = Number(req.params.skip);

    async.waterfall([
        projectCount,
        getProjectSet,
        getProjectLinks
    ], function (err, result) {
        if (err) {
            res.send(err);
        }
    });

    function projectCount(callback) {
        Project.find({}).count().exec(function(err, project_count) {
            if(project_count) {
                callback(null, project_count);
            } else {
                callback(err);
            }
        });
    }

    function getProjectSet(project_count, callback) {
        Project.find(req.query)
            .sort({
                proj_name: 'asc'
            })
            .skip(skip)
            .limit(limit)
            .populate('proj_country.country', '_id iso2 name')
            //.populate('proj_aliases', ' _id alias')
            .lean()
            .exec(function(err, projects) {
                if(projects.length>0) {
                    callback(null, project_count, projects);
                } else {
                    //callback(err);
                    res.send({data: projects, count: project_count});
                }
            });
    }

    function getProjectLinks(project_count, projects, callback) {
        project_len = projects.length;
        project_counter = 0;
        if(project_len>0) {
            projects.forEach(function (c) {
                Link.find({project: c._id})
                    .populate('commodity', '_id commodity_name')
                    .populate('company')
                    .exec(function (err, links) {
                        ++project_counter;
                        link_len = links.length;
                        link_counter = 0;
                        c.proj_commodity = [];
                        c.companies = 0;
                        links.forEach(function (link) {
                            ++link_counter;
                            var entity = _.without(link.entities, 'project')[0];
                            switch (entity) {
                                case 'commodity':
                                    c.proj_commodity.push({
                                        _id: link.commodity._id,
                                        commodity_name: link.commodity.commodity_name
                                    });
                                    break;
                                //
                                case 'company':
                                    c.companies += 1;
                                    break;
                                //
                                default:
                                //console.log('error');
                            }
                        });
                        if (project_counter == project_len && link_counter == link_len) {
                            res.send({data: projects, count: project_count});
                        }
                    });
            });
        } else{
            res.send({data: projects, count: project_count});
        }
    }
};

exports.getProjectByID = function(req, res) {
    var link_counter, link_len,project_counter, project_len;
    async.waterfall([
        getProject,
        //getTransfers,
        getProductions,
        getProjectLinks,
        getProjectCoordinate,
        getCompanyGroup
    ], function (err, result) {
        if (err) {
            res.send(err);
        }
    });

    function getProject(callback) {
        Project.findOne({_id:req.params.id})
            .populate('proj_country.country')
            .populate('proj_aliases', '_id alias')
            .populate('proj_commodity.commodity')
            .lean()
            .exec(function(err, project) {
                if(project) {
                    callback(null, project);
                } else {
                    callback(err);
                }
            });
    }
    //function getTransfers(project, callback) {
    //    project.transfers = [];
    //    Transfer.find({transfer_project: project._id})
    //        .populate('transfer_country')
    //        .populate('transfer_company', '_id company_name')
    //        .exec(function(err, transfers) {
    //            console.log(transfers);
    //            _.each(transfers, function(transfer) {
    //                project.transfers.push(transfer);
    //            });
    //            if(project) {
    //                callback(null, project);
    //            } else {
    //                callback(err);
    //            }
    //        });
    //}
    //function getProductions(project, callback) {
    //    project.productions = [];
    //    Production.find({production_project: project._id})
    //        .populate('production_commodity')
    //        .exec(function(err, productions) {
    //            _.each(productions, function(productions) {
    //                project.productions.push(productions);
    //            });
    //            if(project) {
    //                callback(null, project);
    //            } else {
    //                callback(err);
    //            }
    //        });
    //}
    function getProjectLinks(project, callback) {
        project.companies = [];
        project.commodities = [];
        project.transfers = [];
        project.projects = [];
        project.production = [];
        project.concessions = [];
        project.contracts = [];
        project.sources = {};
        Link.find({project: project._id})
            .populate('commodity')
            .populate('company')
            .populate('contract')
            .populate('concession')
            //.populate('source')
            //.populate('transfer')
            //.populate('production')
            .deepPopulate('company_group transfer.transfer_company transfer.transfer_country production.production_commodity source.source_type_id')
            //.deepPopulate('company company.company_group')
            .exec(function(err, links) {
                if(links.length>0) {
                    link_len = links.length;
                    link_counter = 0;
                    links.forEach(function (link) {
                        ++link_counter;
                        var entity = _.without(link.entities, 'project')[0];
                        //console.log(link);
                        //console.log(link.source);
                        //console.log(link.source._id);
                        if (!project.sources[link.source._id]) {
                            project.sources[link.source._id] = link.source;
                        }
                        switch (entity) {
                            case 'commodity':
                                if (!project.commodities.hasOwnProperty(link.commodity_code)) {
                                    project.commodities.push({
                                        _id: link.commodity._id,
                                        commodity_name:link.commodity.commodity_name});
                                }
                                break;
                            case 'company':
                                if (!project.companies.hasOwnProperty(link.company._id)) {
                                    project.companies.push({
                                        _id: link.company._id,
                                        company_name: link.company.company_name
                                    });
                                }
                                break;
                            case 'concession':
                                project.concessions.push({
                                    _id: link.concession._id,
                                    concession_name: link.concession.concession_name
                                });
                                break;
                            case 'concession':
                                project.concessions.push({
                                    _id: link.concession._id,
                                    concession_name: link.concession.concession_name
                                });
                                break;
                            case 'contract':
                                project.contracts.push(link);
                                break;
                            case 'transfer':
                                project.transfers.push(link);
                                break;
                            case 'production':
                                //console.log(link);
                                project.production.push(link);
                                break;
                            default:
                                //console.log(link);
                                console.log('error');
                        }
                        if(link_counter == link_len) {
                            callback(null, project);
                        }
                    });
                }
            });
    }

    function getProjectCoordinate(project, callback) {
        project.coordinates = [];
        project_counter = 0;
        project_len = project.proj_coordinates.length;
        if(project_len>0) {
            project.proj_coordinates.forEach(function (loc) {
                ++project_counter;
                project.coordinates.push({
                    'lat': loc.loc[0],
                    'lng': loc.loc[1],
                    'message': project.proj_name,
                    'timestamp': loc.timestamp
                });
                if (project_counter == project_len) {
                    callback(null, project);
                }
            });
        } else {
            callback(null, project);
        }
    }
    function getCompanyGroup(project, callback) {
        project_len = project.companies.length;
        project_counter = 0;
        project.companies.forEach(function(company) {
            Link.find({company: company._id})
                .populate('company_group', '_id company_group_name')
                .exec(function (err, links) {
                    ++project_counter;
                    link_len = links.length;
                    link_counter = 0;
                    company.company_groups = [];
                    links.forEach(function (link) {
                        ++link_counter;
                        var entity = _.without(link.entities, 'company')[0];
                        switch (entity) {
                            case 'company_group':
                                if (!company.company_groups.hasOwnProperty(link.company_group._id)) {
                                    company.company_groups.push({
                                        _id: link.company_group._id,
                                        company_group_name: link.company_group.company_group_name
                                    });
                                }
                                break;
                            default:
                                //console.log('error');
                        }
                        if(project_counter == project_len && link_counter == link_len) {
                            res.send(project);
                        }
                    });
                });
        });
    }
};

exports.getProjectsMap = function(req, res) {
    var project_len, project_counter;
    async.waterfall([
        getProject
    ], function (err, result) {
        if (err) {
            res.send(err);
        }
    });

    function getProject(callback) {
        Project.find(req.query)
            .lean()
            .exec(function(err, projects) {
                project_len = projects.length;
                project_counter = 0;
                var data = [];
                if(projects) {
                    projects.forEach(function (project) {
                        ++project_counter;
                        project.proj_coordinates.forEach(function (loc) {
                            data.push({
                                'lat':loc.loc[0],
                                'lng':loc.loc[1],
                                'message':""+project.proj_name+"
"+project.proj_name
                            })
                        })
                    });
                    if(project_counter == project_len) {
                        res.send({data:data});}
                } else {
                    callback(err);
                }
            });
    }
};

exports.createProject = function(req, res, next) {
    var projectData = req.body;
	Project.create(projectData, function(err, project) {
		if(err){
			err = new Error('Error');
			res.status(400);
			return res.send({reason:err.toString()})
		} else{
			res.send();
		}
	});
};

exports.updateProject = function(req, res) {
    var projectUpdates = req.body;
    console.log(projectUpdates);
    Project.findOne({_id:req.body._id}).exec(function(err, project) {
        if(err) {
            err = new Error('Error');
            res.status(400);
            return res.send({ reason: err.toString() });
        }
        project.proj_name= projectUpdates.proj_name;
        //project.proj_aliases= projectUpdates.proj_aliases;
        //project.proj_established_source= projectUpdates.proj_established_source;
        //project.proj_country= projectUpdates.proj_country;
        //project.proj_type= projectUpdates.proj_type;
        ////project.proj_commodity= projectUpdates.proj_commodity;
        //project.proj_site_name= projectUpdates.proj_site_name;
        //project.proj_address= projectUpdates.proj_address;
        //project.proj_coordinates= projectUpdates.proj_coordinates;
        //project.proj_status= projectUpdates.proj_status;
        //project.description= projectUpdates.description;
        project.save(function(err) {
            if(err) {
                err = new Error('Error');
                return res.send({reason: err.toString()});
            } else{
                res.send();
            }
        })
    });
};

exports.deleteProject = function(req, res) {
    Project.remove({_id: req.params.id}, function(err) {
        if(!err) {
            res.send();
        }else{
            return res.send({ reason: err.toString() });
        }
    });
};<|endoftext|>