<commit_before>/*globals $, EJS, COMMCAREHQ */
var CaseConfig = (function () {
    "use strict";
    var action_names = ["open_case", "update_case", "close_case", "open_referral", "update_referral", "close_referral", "case_preload", "referral_preload"],
        CaseConfig = function (params) {
            var i, $form;

            this.home = params.home;
            this.actions = params.actions;
            this.questions = params.questions;
            this.save_url = params.save_url;
            this.requires = ko.utils.unwrapObservable(params.requires);
            this.save_requires_url = params.save_requires_url;
            this.template = new EJS({
                url: "/static/app_manager/ejs/casexml.ejs",
                type: "["
            });
            this.condition_ejs = new EJS({
                url: "/static/app_manager/ejs/condition.ejs",
                type: "["
            });
            this.action_ejs = new EJS({
                url: "/static/app_manager/ejs/action.ejs",
                type: "["
            });
            this.options_ejs = new EJS({
                url: "/static/app_manager/ejs/options.ejs",
                type: "["
            });
            this.propertyList_ejs = new EJS({
                url: "/static/app_manager/ejs/propertyList.ejs",
                type: "["
            });
            this.action_templates = {};
            this.reserved_words = params.reserved_words;
            for (i = 0; i < action_names.length; i += 1) {
                this.action_templates[action_names[i]] = new EJS({
                    url: "/static/app_manager/ejs/actions/" + action_names[i] + ".ejs",
                    type: "["
                });
            }
            //        $("#casexml-template").remove();
            $form = $('<form method="POST"/>').attr('action', this.save_url).append(
                $('<textarea id="casexml_json" class="hide" name="actions"/>')
            );

            this.saveButton = COMMCAREHQ.SaveButton.initForm($form, {
                unsavedMessage: "You have unchanged case and referral settings",
                success: function (data) {
                    var app_manager = hqImport('app_manager/js/app_manager.js');
                    app_manager.updateDOM(data.update);
                }
            });
            this.saveButton.ui.appendTo(this.home);
            $form.appendTo(this.home);
            this.subhome = $('<div/>').appendTo($form);
            var questionScores = {};
            _(this.questions).each(function (question, i) {
                questionScores[question.value] = i;
            });
            this.questionScores = questionScores;
        };
    CaseConfig.prototype = {
        truncateLabel: function (label, suffix) {
            suffix = suffix || "";
            var MAXLEN = 40,
                maxlen = MAXLEN - suffix.length;
            return ((label.length <= maxlen) ? (label) : (label.slice(0, maxlen) + "...")) + suffix;
        },
        escapeQuotes: function (string) {
            return string.replace(/'/g, "'").replace(/"/g, """);
        },
        action_is_active: function (action) {
            return action && action.condition && (action.condition.type === "if" || action.condition.type === "always");
        }
    };

    CaseConfig.prototype.render = function () {
        var i;
        for (i = 0; i < action_names.length; i += 1) {
            this.actions[action_names[i]] = this.actions[action_names[i]] || {
                condition: {
                    type: "never"
                }
            };
        }
        this.template.update(this.subhome.get(0), this);
        COMMCAREHQ.initBlock(this.subhome);
        $('.action-checkbox').each(function () {
            var container = $(this).parent().next('.well');
            if (!$(this).is(':checked')) {
                container.hide();
            }
        });
    };
    CaseConfig.prototype.init = function () {
        var casexml = this;
        if (this.questions.length) {
            this.home.delegate('input:not(.action-checkbox), select', 'change textchange', function () {
                // recompute casexml_json
                casexml.refreshActions();
                casexml.render();
                casexml.refreshActions();
                casexml.render();
                $("#casexml_json").text(JSON.stringify(casexml.actions));
                casexml.saveButton.fire('change');
            }).delegate('input.action-checkbox', 'change', function () {
                var container = $(this).parent().next('.well');
                if ($(this).is(':checked')) {
                    container.slideDown();
                } else {
                    container.slideUp();
                }
                casexml.refreshActions();
                $("#casexml_json").text(JSON.stringify(casexml.actions));
                casexml.saveButton.fire('change');
            });
        }
        this.render();
    };
    CaseConfig.prototype.sortByQuestions = function (map, keysOrValues) {
        var self = this, pairs = _.pairs(map);
        return _(pairs).sortBy(function (pair) {
            var path = keysOrValues === 'keys' ? pair[0] : pair[1];
            return self.questionScores[path];
        });
    };
    CaseConfig.prototype.renderCondition = function (condition) {
        return this.condition_ejs.render({
            casexml: this,
            condition: condition
        });
    };
    CaseConfig.prototype.getQuestions = function (filter, excludeHidden) {
        // filter can be "all", or any of "select1", "select", or "input" separated by spaces
        var i, options = [],
            q;
        excludeHidden = excludeHidden || false;
        filter = filter.split(" ");
        if (!excludeHidden) {
            filter.push('hidden');
        }
        for (i = 0; i < this.questions.length; i += 1) {
            q = this.questions[i];
            if (filter[0] === "all" || filter.indexOf(q.tag) !== -1) {
                options.push(q);
            }
        }
        return options;
    };
    CaseConfig.prototype.renderOptions = function (options, value, name, allowNull) {
        if (allowNull === undefined) {
            allowNull = true;
        }
        return this.options_ejs.render({
            casexml: this,
            options: options,
            value: value,
            name: name,
            allowNull: allowNull
        });
    };
    CaseConfig.prototype.renderQuestions = function (filter) {
        var options = this.getQuestions(filter),
            html = "";
        options.forEach(function (o) {
            html += "<option value='" + o.value + "' title='" + this.escapeQuotes(o.label) + "'>" + this.truncateLabel(o.label) + "</option>";
        });
        return html;
    };
    CaseConfig.prototype.getAnswers = function (condition) {
        var i, q, o, value = condition.question,
            found = false,
            options = [];
        for (i = 0; i < this.questions.length; i += 1) {
            q = this.questions[i];
            if (q.value === value) {
                found = true;
                break;
            }
        }
        if (found && q.options) {
            for (i = 0; i < q.options.length; i += 1) {
                o = q.options[i];
                options.push(o);
            }
        }
        return options;
    };
    CaseConfig.prototype.renderChecked = function (action) {
        if (this.action_is_active(action)) {
            return 'checked="true"';
        } else {
            return "";
        }
    };

    CaseConfig.prototype.refreshActions = function () {
        var actions = {},
            requires;

        function lookup(root, key) {
            return $(root).find('[name="' + key + '"]').attr('value');
        }
        requires = $('[name="requires"]', this.subhome).val();
        if (requires !== this.requires) {
            this.requires = requires;
            this.render();
        }
        $(".casexml .action").each(function () {

            var $checkbox = $(this).find('input[type="checkbox"].action-checkbox'),
                id = $checkbox.attr('id').replace('-', '_'),
                action = {
                    "condition": {
                        "type": "never"
                    }
                };

            if (!$checkbox.is(":checked")) {
                actions[id] = action;
                return;
            }

            if (id === "open_case") {
                action.name_path = lookup(this, 'name_path');
                action.external_id = lookup(this, 'external_id');
            } else if (id === "update_case") {
                action.update = {};
                $('.action-update', this).each(function () {
                    var key = lookup(this, "action-update-key"),
                        val = lookup(this, "action-update-value");
                    if (key || val) {
                        action.update[key] = val;
                    }
                });
            } else if (id === "case_preload" || id === "referral_preload") {
                action.preload = {};
                $('.action-update', this).each(function () {
                    var propertyName = lookup(this, "action-update-key"),
                        nodeset = lookup(this, "action-update-value");
                    if (propertyName || nodeset) {
                        action.preload[nodeset] = propertyName;
                    }
                });
            } else if (id === "open_referral") {
                action.name_path = lookup(this, 'name_path');
                action.followup_date = lookup(this, 'followup_date');
            } else if (id === "update_referral") {
                action.followup_date = lookup(this, 'followup_date');
            }
            action.condition = {
                'type': 'always'
            }; // default value
            $('.condition', this).each(function () { // there is only one
                // action.condition = {};
                //                if($checkbox.is(":checked")) {
                //                    action.condition.type = "never";
                //                }
                if ($('input[name="if"]', this).is(':checked')) {
                    action.condition.type = "if";
                } else {
                    action.condition.type = 'always';
                }
                if (action.condition.type === 'if') {
                    action.condition.question = lookup(this, 'condition-question');
                    action.condition.answer = lookup(this, 'condition-answer');
                }
            });
            actions[id] = action;

        });
        this.actions = actions;
    };

    CaseConfig.prototype.renderAction = function (action_type, label) {
        var html = this.action_ejs.render({
            casexml: this,
            id: action_type.replace("_", "-"),
            action_type: action_type,
            label: label,
            action_body: this.action_templates[action_type].render(this)
        });
        return html;
    };
    CaseConfig.prototype.hasActions = function () {
        var a;
        for (a in this.actions) {
            if (this.actions.hasOwnProperty(a)) {
                if (this.action_is_active(this.actions[a])) {
                    return true;
                }
            }
        }
    };

    CaseConfig.prototype.renderPropertyList = function (map, keyType, reservedWords, showSuggestion) {
        showSuggestion = showSuggestion === undefined ? false : showSuggestion;
        return this.propertyList_ejs.render({
            map: map,
            keyType: keyType,
            showSuggestion: showSuggestion,
            casexml: this,
            reservedWords: reservedWords
        });
    };

    return {CaseConfig: CaseConfig};
}());
<commit_msg>Switch delegate to on<commit_after>/*globals $, EJS, COMMCAREHQ */
var CaseConfig = (function () {
    "use strict";
    var action_names = ["open_case", "update_case", "close_case", "open_referral", "update_referral", "close_referral", "case_preload", "referral_preload"],
        CaseConfig = function (params) {
            var i, $form;

            this.home = params.home;
            this.actions = params.actions;
            this.questions = params.questions;
            this.save_url = params.save_url;
            this.requires = ko.utils.unwrapObservable(params.requires);
            this.save_requires_url = params.save_requires_url;
            this.template = new EJS({
                url: "/static/app_manager/ejs/casexml.ejs",
                type: "["
            });
            this.condition_ejs = new EJS({
                url: "/static/app_manager/ejs/condition.ejs",
                type: "["
            });
            this.action_ejs = new EJS({
                url: "/static/app_manager/ejs/action.ejs",
                type: "["
            });
            this.options_ejs = new EJS({
                url: "/static/app_manager/ejs/options.ejs",
                type: "["
            });
            this.propertyList_ejs = new EJS({
                url: "/static/app_manager/ejs/propertyList.ejs",
                type: "["
            });
            this.action_templates = {};
            this.reserved_words = params.reserved_words;
            for (i = 0; i < action_names.length; i += 1) {
                this.action_templates[action_names[i]] = new EJS({
                    url: "/static/app_manager/ejs/actions/" + action_names[i] + ".ejs",
                    type: "["
                });
            }
            //        $("#casexml-template").remove();
            $form = $('<form method="POST"/>').attr('action', this.save_url).append(
                $('<textarea id="casexml_json" class="hide" name="actions"/>')
            );

            this.saveButton = COMMCAREHQ.SaveButton.initForm($form, {
                unsavedMessage: "You have unchanged case and referral settings",
                success: function (data) {
                    var app_manager = hqImport('app_manager/js/app_manager.js');
                    app_manager.updateDOM(data.update);
                }
            });
            this.saveButton.ui.appendTo(this.home);
            $form.appendTo(this.home);
            this.subhome = $('<div/>').appendTo($form);
            var questionScores = {};
            _(this.questions).each(function (question, i) {
                questionScores[question.value] = i;
            });
            this.questionScores = questionScores;
        };
    CaseConfig.prototype = {
        truncateLabel: function (label, suffix) {
            suffix = suffix || "";
            var MAXLEN = 40,
                maxlen = MAXLEN - suffix.length;
            return ((label.length <= maxlen) ? (label) : (label.slice(0, maxlen) + "...")) + suffix;
        },
        escapeQuotes: function (string) {
            return string.replace(/'/g, "'").replace(/"/g, """);
        },
        action_is_active: function (action) {
            return action && action.condition && (action.condition.type === "if" || action.condition.type === "always");
        }
    };

    CaseConfig.prototype.render = function () {
        var i;
        for (i = 0; i < action_names.length; i += 1) {
            this.actions[action_names[i]] = this.actions[action_names[i]] || {
                condition: {
                    type: "never"
                }
            };
        }
        this.template.update(this.subhome.get(0), this);
        COMMCAREHQ.initBlock(this.subhome);
        $('.action-checkbox').each(function () {
            var container = $(this).parent().next('.well');
            if (!$(this).is(':checked')) {
                container.hide();
            }
        });
    };
    CaseConfig.prototype.init = function () {
        var casexml = this;
        if (this.questions.length) {
            this.home.on('change textchange', 'input:not(.action-checkbox), select', function () {
                // recompute casexml_json
                casexml.refreshActions();
                casexml.render();
                casexml.refreshActions();
                casexml.render();
                $("#casexml_json").text(JSON.stringify(casexml.actions));
                casexml.saveButton.fire('change');
            }).on('change', 'input.action-checkbox', function () {
                var container = $(this).parent().next('.well');
                if ($(this).is(':checked')) {
                    container.slideDown();
                } else {
                    container.slideUp();
                }
                casexml.refreshActions();
                $("#casexml_json").text(JSON.stringify(casexml.actions));
                casexml.saveButton.fire('change');
            });
        }
        this.render();
    };
    CaseConfig.prototype.sortByQuestions = function (map, keysOrValues) {
        var self = this, pairs = _.pairs(map);
        return _(pairs).sortBy(function (pair) {
            var path = keysOrValues === 'keys' ? pair[0] : pair[1];
            return self.questionScores[path];
        });
    };
    CaseConfig.prototype.renderCondition = function (condition) {
        return this.condition_ejs.render({
            casexml: this,
            condition: condition
        });
    };
    CaseConfig.prototype.getQuestions = function (filter, excludeHidden) {
        // filter can be "all", or any of "select1", "select", or "input" separated by spaces
        var i, options = [],
            q;
        excludeHidden = excludeHidden || false;
        filter = filter.split(" ");
        if (!excludeHidden) {
            filter.push('hidden');
        }
        for (i = 0; i < this.questions.length; i += 1) {
            q = this.questions[i];
            if (filter[0] === "all" || filter.indexOf(q.tag) !== -1) {
                options.push(q);
            }
        }
        return options;
    };
    CaseConfig.prototype.renderOptions = function (options, value, name, allowNull) {
        if (allowNull === undefined) {
            allowNull = true;
        }
        return this.options_ejs.render({
            casexml: this,
            options: options,
            value: value,
            name: name,
            allowNull: allowNull
        });
    };
    CaseConfig.prototype.renderQuestions = function (filter) {
        var options = this.getQuestions(filter),
            html = "";
        options.forEach(function (o) {
            html += "<option value='" + o.value + "' title='" + this.escapeQuotes(o.label) + "'>" + this.truncateLabel(o.label) + "</option>";
        });
        return html;
    };
    CaseConfig.prototype.getAnswers = function (condition) {
        var i, q, o, value = condition.question,
            found = false,
            options = [];
        for (i = 0; i < this.questions.length; i += 1) {
            q = this.questions[i];
            if (q.value === value) {
                found = true;
                break;
            }
        }
        if (found && q.options) {
            for (i = 0; i < q.options.length; i += 1) {
                o = q.options[i];
                options.push(o);
            }
        }
        return options;
    };
    CaseConfig.prototype.renderChecked = function (action) {
        if (this.action_is_active(action)) {
            return 'checked="true"';
        } else {
            return "";
        }
    };

    CaseConfig.prototype.refreshActions = function () {
        var actions = {},
            requires;

        function lookup(root, key) {
            return $(root).find('[name="' + key + '"]').attr('value');
        }
        requires = $('[name="requires"]', this.subhome).val();
        if (requires !== this.requires) {
            this.requires = requires;
            this.render();
        }
        $(".casexml .action").each(function () {

            var $checkbox = $(this).find('input[type="checkbox"].action-checkbox'),
                id = $checkbox.attr('id').replace('-', '_'),
                action = {
                    "condition": {
                        "type": "never"
                    }
                };

            if (!$checkbox.is(":checked")) {
                actions[id] = action;
                return;
            }

            if (id === "open_case") {
                action.name_path = lookup(this, 'name_path');
                action.external_id = lookup(this, 'external_id');
            } else if (id === "update_case") {
                action.update = {};
                $('.action-update', this).each(function () {
                    var key = lookup(this, "action-update-key"),
                        val = lookup(this, "action-update-value");
                    if (key || val) {
                        action.update[key] = val;
                    }
                });
            } else if (id === "case_preload" || id === "referral_preload") {
                action.preload = {};
                $('.action-update', this).each(function () {
                    var propertyName = lookup(this, "action-update-key"),
                        nodeset = lookup(this, "action-update-value");
                    if (propertyName || nodeset) {
                        action.preload[nodeset] = propertyName;
                    }
                });
            } else if (id === "open_referral") {
                action.name_path = lookup(this, 'name_path');
                action.followup_date = lookup(this, 'followup_date');
            } else if (id === "update_referral") {
                action.followup_date = lookup(this, 'followup_date');
            }
            action.condition = {
                'type': 'always'
            }; // default value
            $('.condition', this).each(function () { // there is only one
                // action.condition = {};
                //                if($checkbox.is(":checked")) {
                //                    action.condition.type = "never";
                //                }
                if ($('input[name="if"]', this).is(':checked')) {
                    action.condition.type = "if";
                } else {
                    action.condition.type = 'always';
                }
                if (action.condition.type === 'if') {
                    action.condition.question = lookup(this, 'condition-question');
                    action.condition.answer = lookup(this, 'condition-answer');
                }
            });
            actions[id] = action;

        });
        this.actions = actions;
    };

    CaseConfig.prototype.renderAction = function (action_type, label) {
        var html = this.action_ejs.render({
            casexml: this,
            id: action_type.replace("_", "-"),
            action_type: action_type,
            label: label,
            action_body: this.action_templates[action_type].render(this)
        });
        return html;
    };
    CaseConfig.prototype.hasActions = function () {
        var a;
        for (a in this.actions) {
            if (this.actions.hasOwnProperty(a)) {
                if (this.action_is_active(this.actions[a])) {
                    return true;
                }
            }
        }
    };

    CaseConfig.prototype.renderPropertyList = function (map, keyType, reservedWords, showSuggestion) {
        showSuggestion = showSuggestion === undefined ? false : showSuggestion;
        return this.propertyList_ejs.render({
            map: map,
            keyType: keyType,
            showSuggestion: showSuggestion,
            casexml: this,
            reservedWords: reservedWords
        });
    };

    return {CaseConfig: CaseConfig};
}());
<|endoftext|>


<commit_before><commit_msg>Test file for hasAnyMethod validation API<commit_after><|endoftext|>


<commit_before>/*globals $, EJS, COMMCAREHQ */
var CaseConfig = (function () {
    "use strict";
    var action_names = ["open_case", "update_case", "close_case", "open_referral", "update_referral", "close_referral", "case_preload", "referral_preload"],
        CaseConfig = function (params) {
            var i, $form;

            this.home = params.home;
            this.actions = params.actions;
            this.questions = params.questions;
            this.save_url = params.save_url;
            this.requires = ko.utils.unwrapObservable(params.requires);
            this.save_requires_url = params.save_requires_url;
            this.template = new EJS({
                url: "/static/app_manager/ejs/casexml.ejs",
                type: "["
            });
            this.condition_ejs = new EJS({
                url: "/static/app_manager/ejs/condition.ejs",
                type: "["
            });
            this.action_ejs = new EJS({
                url: "/static/app_manager/ejs/action.ejs",
                type: "["
            });
            this.options_ejs = new EJS({
                url: "/static/app_manager/ejs/options.ejs",
                type: "["
            });
            this.propertyList_ejs = new EJS({
                url: "/static/app_manager/ejs/propertyList.ejs",
                type: "["
            });
            this.action_templates = {};
            this.reserved_words = params.reserved_words;
            for (i = 0; i < action_names.length; i += 1) {
                this.action_templates[action_names[i]] = new EJS({
                    url: "/static/app_manager/ejs/actions/" + action_names[i] + ".ejs",
                    type: "["
                });
            }
            //        $("#casexml-template").remove();
            $form = $('<form method="POST"/>').attr('action', this.save_url).append(
                $('<textarea id="casexml_json" class="hide" name="actions"/>')
            );

            this.saveButton = COMMCAREHQ.SaveButton.initForm($form, {
                unsavedMessage: "You have unchanged case and referral settings",
                success: function (data) {
                    var app_manager = hqImport('app_manager/js/app_manager.js');
                    app_manager.updateDOM(data.update);
                }
            });
            this.saveButton.ui.appendTo(this.home);
            $form.appendTo(this.home);
            this.subhome = $('<div/>').appendTo($form);
            var questionScores = {};
            _(this.questions).each(function (question, i) {
                questionScores[question.value] = i;
            });
            this.questionScores = questionScores;
        };
    CaseConfig.prototype = {
        truncateLabel: function (label, suffix) {
            suffix = suffix || "";
            var MAXLEN = 40,
                maxlen = MAXLEN - suffix.length;
            return ((label.length <= maxlen) ? (label) : (label.slice(0, maxlen) + "...")) + suffix;
        },
        escapeQuotes: function (string) {
            return string.replace(/'/g, "'").replace(/"/g, """);
        },
        action_is_active: function (action) {
            return action && action.condition && (action.condition.type === "if" || action.condition.type === "always");
        }
    };

    CaseConfig.prototype.render = function () {
        var i;
        for (i = 0; i < action_names.length; i += 1) {
            this.actions[action_names[i]] = this.actions[action_names[i]] || {
                condition: {
                    type: "never"
                }
            };
        }
        this.template.update(this.subhome.get(0), this);
        COMMCAREHQ.initBlock(this.subhome);
        $('.action-checkbox').each(function () {
            var container = $(this).parent().next('.well');
            if (!$(this).is(':checked')) {
                container.hide();
            }
        });
    };
    CaseConfig.prototype.init = function () {
        var casexml = this;
        if (this.questions.length) {
            this.home.delegate('input:not(.action-checkbox), select', 'change textchange', function () {
                // recompute casexml_json
                casexml.refreshActions();
                casexml.render();
                casexml.refreshActions();
                casexml.render();
                $("#casexml_json").text(JSON.stringify(casexml.actions));
                casexml.saveButton.fire('change');
            }).delegate('input.action-checkbox', 'change', function () {
                var container = $(this).parent().next('.well');
                if ($(this).is(':checked')) {
                    container.slideDown();
                } else {
                    container.slideUp();
                }
                casexml.refreshActions();
                $("#casexml_json").text(JSON.stringify(casexml.actions));
                casexml.saveButton.fire('change');
            });
        }
        this.render();
    };
    CaseConfig.prototype.sortByQuestions = function (map, keysOrValues) {
        var self = this, pairs = _.pairs(map);
        return _(pairs).sortBy(function (pair) {
            var path = keysOrValues === 'keys' ? pair[0] : pair[1];
            return self.questionScores[path];
        });
    };
    CaseConfig.prototype.renderCondition = function (condition) {
        return this.condition_ejs.render({
            casexml: this,
            condition: condition
        });
    };
    CaseConfig.prototype.getQuestions = function (filter, excludeHidden) {
        // filter can be "all", or any of "select1", "select", or "input" separated by spaces
        var i, options = [],
            q;
        excludeHidden = excludeHidden || false;
        filter = filter.split(" ");
        if (!excludeHidden) {
            filter.push('hidden');
        }
        for (i = 0; i < this.questions.length; i += 1) {
            q = this.questions[i];
            if (filter[0] === "all" || filter.indexOf(q.tag) !== -1) {
                options.push(q);
            }
        }
        return options;
    };
    CaseConfig.prototype.renderOptions = function (options, value, name, allowNull) {
        if (allowNull === undefined) {
            allowNull = true;
        }
        return this.options_ejs.render({
            casexml: this,
            options: options,
            value: value,
            name: name,
            allowNull: allowNull
        });
    };
    CaseConfig.prototype.renderQuestions = function (filter) {
        var options = this.getQuestions(filter),
            html = "";
        options.forEach(function (o) {
            html += "<option value='" + o.value + "' title='" + this.escapeQuotes(o.label) + "'>" + this.truncateLabel(o.label) + "</option>";
        });
        return html;
    };
    CaseConfig.prototype.getAnswers = function (condition) {
        var i, q, o, value = condition.question,
            found = false,
            options = [];
        for (i = 0; i < this.questions.length; i += 1) {
            q = this.questions[i];
            if (q.value === value) {
                found = true;
                break;
            }
        }
        if (found && q.options) {
            for (i = 0; i < q.options.length; i += 1) {
                o = q.options[i];
                options.push(o);
            }
        }
        return options;
    };
    CaseConfig.prototype.renderChecked = function (action) {
        if (this.action_is_active(action)) {
            return 'checked="true"';
        } else {
            return "";
        }
    };

    CaseConfig.prototype.refreshActions = function () {
        var actions = {},
            requires;

        function lookup(root, key) {
            return $(root).find('[name="' + key + '"]').attr('value');
        }
        requires = $('[name="requires"]', this.subhome).val();
        if (requires !== this.requires) {
            this.requires = requires;
            this.render();
        }
        $(".casexml .action").each(function () {

            var $checkbox = $(this).find('input[type="checkbox"].action-checkbox'),
                id = $checkbox.attr('id').replace('-', '_'),
                action = {
                    "condition": {
                        "type": "never"
                    }
                };

            if (!$checkbox.is(":checked")) {
                actions[id] = action;
                return;
            }

            if (id === "open_case") {
                action.name_path = lookup(this, 'name_path');
                action.external_id = lookup(this, 'external_id');
            } else if (id === "update_case") {
                action.update = {};
                $('.action-update', this).each(function () {
                    var key = lookup(this, "action-update-key"),
                        val = lookup(this, "action-update-value");
                    if (key || val) {
                        action.update[key] = val;
                    }
                });
            } else if (id === "case_preload" || id === "referral_preload") {
                action.preload = {};
                $('.action-update', this).each(function () {
                    var propertyName = lookup(this, "action-update-key"),
                        nodeset = lookup(this, "action-update-value");
                    if (propertyName || nodeset) {
                        action.preload[nodeset] = propertyName;
                    }
                });
            } else if (id === "open_referral") {
                action.name_path = lookup(this, 'name_path');
                action.followup_date = lookup(this, 'followup_date');
            } else if (id === "update_referral") {
                action.followup_date = lookup(this, 'followup_date');
            }
            action.condition = {
                'type': 'always'
            }; // default value
            $('.condition', this).each(function () { // there is only one
                // action.condition = {};
                //                if($checkbox.is(":checked")) {
                //                    action.condition.type = "never";
                //                }
                if ($('input[name="if"]', this).is(':checked')) {
                    action.condition.type = "if";
                } else {
                    action.condition.type = 'always';
                }
                if (action.condition.type === 'if') {
                    action.condition.question = lookup(this, 'condition-question');
                    action.condition.answer = lookup(this, 'condition-answer');
                }
            });
            actions[id] = action;

        });
        this.actions = actions;
    };

    CaseConfig.prototype.renderAction = function (action_type, label) {
        var html = this.action_ejs.render({
            casexml: this,
            id: action_type.replace("_", "-"),
            action_type: action_type,
            label: label,
            action_body: this.action_templates[action_type].render(this)
        });
        return html;
    };
    CaseConfig.prototype.hasActions = function () {
        var a;
        for (a in this.actions) {
            if (this.actions.hasOwnProperty(a)) {
                if (this.action_is_active(this.actions[a])) {
                    return true;
                }
            }
        }
    };

    CaseConfig.prototype.renderPropertyList = function (map, keyType, reservedWords, showSuggestion) {
        showSuggestion = showSuggestion === undefined ? false : showSuggestion;
        return this.propertyList_ejs.render({
            map: map,
            keyType: keyType,
            showSuggestion: showSuggestion,
            casexml: this,
            reservedWords: reservedWords
        });
    };

    return {CaseConfig: CaseConfig};
}());
<commit_msg>delegate has been removed<commit_after>/*globals $, EJS, COMMCAREHQ */
var CaseConfig = (function () {
    "use strict";
    var action_names = ["open_case", "update_case", "close_case", "open_referral", "update_referral", "close_referral", "case_preload", "referral_preload"],
        CaseConfig = function (params) {
            var i, $form;

            this.home = params.home;
            this.actions = params.actions;
            this.questions = params.questions;
            this.save_url = params.save_url;
            this.requires = ko.utils.unwrapObservable(params.requires);
            this.save_requires_url = params.save_requires_url;
            this.template = new EJS({
                url: "/static/app_manager/ejs/casexml.ejs",
                type: "["
            });
            this.condition_ejs = new EJS({
                url: "/static/app_manager/ejs/condition.ejs",
                type: "["
            });
            this.action_ejs = new EJS({
                url: "/static/app_manager/ejs/action.ejs",
                type: "["
            });
            this.options_ejs = new EJS({
                url: "/static/app_manager/ejs/options.ejs",
                type: "["
            });
            this.propertyList_ejs = new EJS({
                url: "/static/app_manager/ejs/propertyList.ejs",
                type: "["
            });
            this.action_templates = {};
            this.reserved_words = params.reserved_words;
            for (i = 0; i < action_names.length; i += 1) {
                this.action_templates[action_names[i]] = new EJS({
                    url: "/static/app_manager/ejs/actions/" + action_names[i] + ".ejs",
                    type: "["
                });
            }
            //        $("#casexml-template").remove();
            $form = $('<form method="POST"/>').attr('action', this.save_url).append(
                $('<textarea id="casexml_json" class="hide" name="actions"/>')
            );

            this.saveButton = COMMCAREHQ.SaveButton.initForm($form, {
                unsavedMessage: "You have unchanged case and referral settings",
                success: function (data) {
                    var app_manager = hqImport('app_manager/js/app_manager.js');
                    app_manager.updateDOM(data.update);
                }
            });
            this.saveButton.ui.appendTo(this.home);
            $form.appendTo(this.home);
            this.subhome = $('<div/>').appendTo($form);
            var questionScores = {};
            _(this.questions).each(function (question, i) {
                questionScores[question.value] = i;
            });
            this.questionScores = questionScores;
        };
    CaseConfig.prototype = {
        truncateLabel: function (label, suffix) {
            suffix = suffix || "";
            var MAXLEN = 40,
                maxlen = MAXLEN - suffix.length;
            return ((label.length <= maxlen) ? (label) : (label.slice(0, maxlen) + "...")) + suffix;
        },
        escapeQuotes: function (string) {
            return string.replace(/'/g, "'").replace(/"/g, """);
        },
        action_is_active: function (action) {
            return action && action.condition && (action.condition.type === "if" || action.condition.type === "always");
        }
    };

    CaseConfig.prototype.render = function () {
        var i;
        for (i = 0; i < action_names.length; i += 1) {
            this.actions[action_names[i]] = this.actions[action_names[i]] || {
                condition: {
                    type: "never"
                }
            };
        }
        this.template.update(this.subhome.get(0), this);
        COMMCAREHQ.initBlock(this.subhome);
        $('.action-checkbox').each(function () {
            var container = $(this).parent().next('.well');
            if (!$(this).is(':checked')) {
                container.hide();
            }
        });
    };
    CaseConfig.prototype.init = function () {
        var casexml = this;
        if (this.questions.length) {
            this.home.delegate('change textchange', 'input:not(.action-checkbox), select', function () {
                // recompute casexml_json
                casexml.refreshActions();
                casexml.render();
                casexml.refreshActions();
                casexml.render();
                $("#casexml_json").text(JSON.stringify(casexml.actions));
                casexml.saveButton.fire('change');
            }).delegate('change', 'input.action-checkbox', function () {
                var container = $(this).parent().next('.well');
                if ($(this).is(':checked')) {
                    container.slideDown();
                } else {
                    container.slideUp();
                }
                casexml.refreshActions();
                $("#casexml_json").text(JSON.stringify(casexml.actions));
                casexml.saveButton.fire('change');
            });
        }
        this.render();
    };
    CaseConfig.prototype.sortByQuestions = function (map, keysOrValues) {
        var self = this, pairs = _.pairs(map);
        return _(pairs).sortBy(function (pair) {
            var path = keysOrValues === 'keys' ? pair[0] : pair[1];
            return self.questionScores[path];
        });
    };
    CaseConfig.prototype.renderCondition = function (condition) {
        return this.condition_ejs.render({
            casexml: this,
            condition: condition
        });
    };
    CaseConfig.prototype.getQuestions = function (filter, excludeHidden) {
        // filter can be "all", or any of "select1", "select", or "input" separated by spaces
        var i, options = [],
            q;
        excludeHidden = excludeHidden || false;
        filter = filter.split(" ");
        if (!excludeHidden) {
            filter.push('hidden');
        }
        for (i = 0; i < this.questions.length; i += 1) {
            q = this.questions[i];
            if (filter[0] === "all" || filter.indexOf(q.tag) !== -1) {
                options.push(q);
            }
        }
        return options;
    };
    CaseConfig.prototype.renderOptions = function (options, value, name, allowNull) {
        if (allowNull === undefined) {
            allowNull = true;
        }
        return this.options_ejs.render({
            casexml: this,
            options: options,
            value: value,
            name: name,
            allowNull: allowNull
        });
    };
    CaseConfig.prototype.renderQuestions = function (filter) {
        var options = this.getQuestions(filter),
            html = "";
        options.forEach(function (o) {
            html += "<option value='" + o.value + "' title='" + this.escapeQuotes(o.label) + "'>" + this.truncateLabel(o.label) + "</option>";
        });
        return html;
    };
    CaseConfig.prototype.getAnswers = function (condition) {
        var i, q, o, value = condition.question,
            found = false,
            options = [];
        for (i = 0; i < this.questions.length; i += 1) {
            q = this.questions[i];
            if (q.value === value) {
                found = true;
                break;
            }
        }
        if (found && q.options) {
            for (i = 0; i < q.options.length; i += 1) {
                o = q.options[i];
                options.push(o);
            }
        }
        return options;
    };
    CaseConfig.prototype.renderChecked = function (action) {
        if (this.action_is_active(action)) {
            return 'checked="true"';
        } else {
            return "";
        }
    };

    CaseConfig.prototype.refreshActions = function () {
        var actions = {},
            requires;

        function lookup(root, key) {
            return $(root).find('[name="' + key + '"]').attr('value');
        }
        requires = $('[name="requires"]', this.subhome).val();
        if (requires !== this.requires) {
            this.requires = requires;
            this.render();
        }
        $(".casexml .action").each(function () {

            var $checkbox = $(this).find('input[type="checkbox"].action-checkbox'),
                id = $checkbox.attr('id').replace('-', '_'),
                action = {
                    "condition": {
                        "type": "never"
                    }
                };

            if (!$checkbox.is(":checked")) {
                actions[id] = action;
                return;
            }

            if (id === "open_case") {
                action.name_path = lookup(this, 'name_path');
                action.external_id = lookup(this, 'external_id');
            } else if (id === "update_case") {
                action.update = {};
                $('.action-update', this).each(function () {
                    var key = lookup(this, "action-update-key"),
                        val = lookup(this, "action-update-value");
                    if (key || val) {
                        action.update[key] = val;
                    }
                });
            } else if (id === "case_preload" || id === "referral_preload") {
                action.preload = {};
                $('.action-update', this).each(function () {
                    var propertyName = lookup(this, "action-update-key"),
                        nodeset = lookup(this, "action-update-value");
                    if (propertyName || nodeset) {
                        action.preload[nodeset] = propertyName;
                    }
                });
            } else if (id === "open_referral") {
                action.name_path = lookup(this, 'name_path');
                action.followup_date = lookup(this, 'followup_date');
            } else if (id === "update_referral") {
                action.followup_date = lookup(this, 'followup_date');
            }
            action.condition = {
                'type': 'always'
            }; // default value
            $('.condition', this).each(function () { // there is only one
                // action.condition = {};
                //                if($checkbox.is(":checked")) {
                //                    action.condition.type = "never";
                //                }
                if ($('input[name="if"]', this).is(':checked')) {
                    action.condition.type = "if";
                } else {
                    action.condition.type = 'always';
                }
                if (action.condition.type === 'if') {
                    action.condition.question = lookup(this, 'condition-question');
                    action.condition.answer = lookup(this, 'condition-answer');
                }
            });
            actions[id] = action;

        });
        this.actions = actions;
    };

    CaseConfig.prototype.renderAction = function (action_type, label) {
        var html = this.action_ejs.render({
            casexml: this,
            id: action_type.replace("_", "-"),
            action_type: action_type,
            label: label,
            action_body: this.action_templates[action_type].render(this)
        });
        return html;
    };
    CaseConfig.prototype.hasActions = function () {
        var a;
        for (a in this.actions) {
            if (this.actions.hasOwnProperty(a)) {
                if (this.action_is_active(this.actions[a])) {
                    return true;
                }
            }
        }
    };

    CaseConfig.prototype.renderPropertyList = function (map, keyType, reservedWords, showSuggestion) {
        showSuggestion = showSuggestion === undefined ? false : showSuggestion;
        return this.propertyList_ejs.render({
            map: map,
            keyType: keyType,
            showSuggestion: showSuggestion,
            casexml: this,
            reservedWords: reservedWords
        });
    };

    return {CaseConfig: CaseConfig};
}());
<|endoftext|>


<commit_before>hqDefine("linked_domain/js/domain_links", [
    'jquery.rmi/jquery.rmi',
    'hqwebapp/js/initial_page_data',
    'underscore',
    'knockout',
    'hqwebapp/js/alert_user',
    'hqwebapp/js/multiselect_utils',
    'hqwebapp/js/components.ko', // for pagination
    'hqwebapp/js/select2_knockout_bindings.ko',     // selects2 for fields
], function (
    RMI,
    initialPageData,
    _,
    ko,
    alertUser
) {
    var _private = {};
    _private.RMI = function () {};

    var ModelStatus = function (data) {
        var self = {};
        self.type = data.type;
        self.name = data.name;
        self.lastUpdate = ko.observable(data.last_update);
        self.detail = data.detail;
        self.showUpdate = ko.observable(data.can_update);
        self.update_url = null;

        if (self.type === 'app' && self.detail && self.detail.app_id) {
            self.update_url = initialPageData.reverse('app_settings', self.detail.app_id);
        }
        self.error = ko.observable("");
        self.hasSuccess = ko.observable(false);
        self.showSpinner = ko.observable(false);

        self.update = function () {
            self.showSpinner(true);
            self.showUpdate(false);
            _private.RMI("update_linked_model", {"model": {
                'type': self.type,
                'detail': self.detail,
            }}).done(function (data) {
                if (data.error) {
                    self.error(data.error);
                } else {
                    self.lastUpdate(data.last_update);
                    self.hasSuccess(true);
                }
                self.showSpinner(false);
            }).fail(function () {
                self.error(gettext("Error updating."));
                self.showSpinner(false);
            });
        };

        return self;
    };

    var DomainLinksViewModel = function (data) {
        var self = {};
        self.addDownstreamDomainModal = AddDownstreamDomainModal(self, data.available_domains);
        self.domain = data.domain;
        self.master_link = data.master_link;
        if (self.master_link) {
            if (self.master_link.is_remote) {
                self.master_href = self.master_link.master_domain;
            } else {
                self.master_href = initialPageData.reverse('domain_links', self.master_link.master_domain);
            }
        }

        self.domain_links = ko.observableArray(_.map(data.linked_domains, DomainLink));

        // pull content
        self.model_status = _.map(data.model_status, ModelStatus);
        self.can_update = data.can_update;
        self.models = data.models;

        // manage downstream domains tab
        self.paginatedDomainLinks = ko.observableArray([]);
        self.itemsPerPage = ko.observable(5);
        self.totalItems = ko.computed(function () {
            return self.domain_links().length;
        });
        self.currentPage = 1;

        self.goToPage = function (page) {
            self.currentPage = page;
            self.paginatedDomainLinks.removeAll();
            var skip = (self.currentPage - 1) * self.itemsPerPage();
            self.paginatedDomainLinks(self.domain_links().slice(skip, skip + self.itemsPerPage()));
        };

        self.onPaginationLoad = function () {
            self.goToPage(1);
        };

        self.deleteLink = function (link) {
            _private.RMI("delete_domain_link", {
                "linked_domain": link.linked_domain(),
            }).done(function () {
                self.domain_links.remove(link);
                var availableDomains = self.addDownstreamDomainModal.availableDomains();
                availableDomains.push(link.linked_domain())
                self.addDownstreamDomainModal.availableDomains(availableDomains.sort());
                self.goToPage(self.currentPage);
            }).fail(function () {
                alertUser.alert_user(gettext('Something unexpected happened.\n' +
                    'Please try again, or report an issue if the problem persists.'), 'danger');
            });
        };

        // push content tab
        self.domainsToRelease = ko.observableArray();
        self.modelsToRelease = ko.observableArray();
        self.buildAppsOnRelease = ko.observable(false);
        self.releaseInProgress = ko.observable(false);
        self.enableReleaseButton = ko.computed(function () {
            return self.domainsToRelease().length && self.modelsToRelease().length && !self.releaseInProgress();
        });

        self.createRelease = function () {
            self.releaseInProgress(true);
            _private.RMI("create_release", {
                models: _.map(self.modelsToRelease(), JSON.parse),
                linked_domains: self.domainsToRelease(),
                build_apps: self.buildAppsOnRelease(),
            }).done(function (data) {
                alertUser.alert_user(data.message, data.success ? 'success' : 'danger');
                self.releaseInProgress(false);
            }).fail(function () {
                alertUser.alert_user(gettext('Something unexpected happened.\nPlease try again, or report an issue if the problem persists.'), 'danger');
                self.releaseInProgress(false);
            });
        };

        return self;
    };

    var DomainLink = function (link) {
        var self = {};
        self.linked_domain = ko.observable(link.linked_domain);
        self.is_remote = link.is_remote;
        self.master_domain = link.master_domain;
        self.remote_base_url = ko.observable(link.remote_base_url);
        self.lastUpdate = link.last_update;
        if (self.is_remote) {
            self.domain_link = self.linked_domain;
        } else {
            self.domain_link = initialPageData.reverse('domain_links', self.linked_domain());
        }
        return self;
    };

    var AddDownstreamDomainModal = function (manageDomainsViewModel, availableDomains) {
        var self = {};
        self.parent = manageDomainsViewModel;
        self.availableDomains = ko.observableArray(availableDomains.sort());
        self.value = ko.observable();

        self.addDownstreamDomain = function (viewModel) {
            // TODO: make rmi call to create domain link
            var domainLinkResponse = {"linked_domain": viewModel.value(),
                "is_remote": false,
                "master_domain": self.parent.domain,
                "remote_base_url": "",
                "last_update": ""};
            self.parent.domain_links.unshift(DomainLink(domainLinkResponse));
            self.availableDomains(_.filter(self.availableDomains(), function (item) {
                return item !== viewModel.value();
            }));
            self.value(null);
            self.parent.goToPage(1);
        };
        return self;
    };

    var setRMI = function (rmiUrl, csrfToken) {
        var _rmi = RMI(rmiUrl, csrfToken);
        _private.RMI = function (remoteMethod, data) {
            return _rmi("", data, {headers: {"DjNg-Remote-Method": remoteMethod}});
        };
    };

    $(function () {
        var view_data = initialPageData.get('view_data');
        var csrfToken = $("#csrfTokenContainer").val();
        setRMI(initialPageData.reverse('linked_domain:domain_link_rmi'), csrfToken);

        var model = DomainLinksViewModel(view_data);
        if ($("#ko-tabs-pull-content").length) {
            $("#ko-tabs-pull-content").koApplyBindings(model);
        }
        if ($("#ko-tabs-push-content").length) {
            $("#ko-tabs-push-content").koApplyBindings(model);
        }
        if ($("#ko-tabs-manage-downstream").length) {
            $("#ko-tabs-manage-downstream").koApplyBindings(model);
        }

        if ($("#new-downstream-domain-modal").length) {
            $("#new-downstream-domain-modal").koApplyBindings(model.addDownstreamDomainModal);
        }

    });
});
<commit_msg>forgot a semicolon<commit_after>hqDefine("linked_domain/js/domain_links", [
    'jquery.rmi/jquery.rmi',
    'hqwebapp/js/initial_page_data',
    'underscore',
    'knockout',
    'hqwebapp/js/alert_user',
    'hqwebapp/js/multiselect_utils',
    'hqwebapp/js/components.ko', // for pagination
    'hqwebapp/js/select2_knockout_bindings.ko',     // selects2 for fields
], function (
    RMI,
    initialPageData,
    _,
    ko,
    alertUser
) {
    var _private = {};
    _private.RMI = function () {};

    var ModelStatus = function (data) {
        var self = {};
        self.type = data.type;
        self.name = data.name;
        self.lastUpdate = ko.observable(data.last_update);
        self.detail = data.detail;
        self.showUpdate = ko.observable(data.can_update);
        self.update_url = null;

        if (self.type === 'app' && self.detail && self.detail.app_id) {
            self.update_url = initialPageData.reverse('app_settings', self.detail.app_id);
        }
        self.error = ko.observable("");
        self.hasSuccess = ko.observable(false);
        self.showSpinner = ko.observable(false);

        self.update = function () {
            self.showSpinner(true);
            self.showUpdate(false);
            _private.RMI("update_linked_model", {"model": {
                'type': self.type,
                'detail': self.detail,
            }}).done(function (data) {
                if (data.error) {
                    self.error(data.error);
                } else {
                    self.lastUpdate(data.last_update);
                    self.hasSuccess(true);
                }
                self.showSpinner(false);
            }).fail(function () {
                self.error(gettext("Error updating."));
                self.showSpinner(false);
            });
        };

        return self;
    };

    var DomainLinksViewModel = function (data) {
        var self = {};
        self.addDownstreamDomainModal = AddDownstreamDomainModal(self, data.available_domains);
        self.domain = data.domain;
        self.master_link = data.master_link;
        if (self.master_link) {
            if (self.master_link.is_remote) {
                self.master_href = self.master_link.master_domain;
            } else {
                self.master_href = initialPageData.reverse('domain_links', self.master_link.master_domain);
            }
        }

        self.domain_links = ko.observableArray(_.map(data.linked_domains, DomainLink));

        // pull content
        self.model_status = _.map(data.model_status, ModelStatus);
        self.can_update = data.can_update;
        self.models = data.models;

        // manage downstream domains tab
        self.paginatedDomainLinks = ko.observableArray([]);
        self.itemsPerPage = ko.observable(5);
        self.totalItems = ko.computed(function () {
            return self.domain_links().length;
        });
        self.currentPage = 1;

        self.goToPage = function (page) {
            self.currentPage = page;
            self.paginatedDomainLinks.removeAll();
            var skip = (self.currentPage - 1) * self.itemsPerPage();
            self.paginatedDomainLinks(self.domain_links().slice(skip, skip + self.itemsPerPage()));
        };

        self.onPaginationLoad = function () {
            self.goToPage(1);
        };

        self.deleteLink = function (link) {
            _private.RMI("delete_domain_link", {
                "linked_domain": link.linked_domain(),
            }).done(function () {
                self.domain_links.remove(link);
                var availableDomains = self.addDownstreamDomainModal.availableDomains();
                availableDomains.push(link.linked_domain());
                self.addDownstreamDomainModal.availableDomains(availableDomains.sort());
                self.goToPage(self.currentPage);
            }).fail(function () {
                alertUser.alert_user(gettext('Something unexpected happened.\n' +
                    'Please try again, or report an issue if the problem persists.'), 'danger');
            });
        };

        // push content tab
        self.domainsToRelease = ko.observableArray();
        self.modelsToRelease = ko.observableArray();
        self.buildAppsOnRelease = ko.observable(false);
        self.releaseInProgress = ko.observable(false);
        self.enableReleaseButton = ko.computed(function () {
            return self.domainsToRelease().length && self.modelsToRelease().length && !self.releaseInProgress();
        });

        self.createRelease = function () {
            self.releaseInProgress(true);
            _private.RMI("create_release", {
                models: _.map(self.modelsToRelease(), JSON.parse),
                linked_domains: self.domainsToRelease(),
                build_apps: self.buildAppsOnRelease(),
            }).done(function (data) {
                alertUser.alert_user(data.message, data.success ? 'success' : 'danger');
                self.releaseInProgress(false);
            }).fail(function () {
                alertUser.alert_user(gettext('Something unexpected happened.\nPlease try again, or report an issue if the problem persists.'), 'danger');
                self.releaseInProgress(false);
            });
        };

        return self;
    };

    var DomainLink = function (link) {
        var self = {};
        self.linked_domain = ko.observable(link.linked_domain);
        self.is_remote = link.is_remote;
        self.master_domain = link.master_domain;
        self.remote_base_url = ko.observable(link.remote_base_url);
        self.lastUpdate = link.last_update;
        if (self.is_remote) {
            self.domain_link = self.linked_domain;
        } else {
            self.domain_link = initialPageData.reverse('domain_links', self.linked_domain());
        }
        return self;
    };

    var AddDownstreamDomainModal = function (manageDomainsViewModel, availableDomains) {
        var self = {};
        self.parent = manageDomainsViewModel;
        self.availableDomains = ko.observableArray(availableDomains.sort());
        self.value = ko.observable();

        self.addDownstreamDomain = function (viewModel) {
            // TODO: make rmi call to create domain link
            var domainLinkResponse = {"linked_domain": viewModel.value(),
                "is_remote": false,
                "master_domain": self.parent.domain,
                "remote_base_url": "",
                "last_update": ""};
            self.parent.domain_links.unshift(DomainLink(domainLinkResponse));
            self.availableDomains(_.filter(self.availableDomains(), function (item) {
                return item !== viewModel.value();
            }));
            self.value(null);
            self.parent.goToPage(1);
        };
        return self;
    };

    var setRMI = function (rmiUrl, csrfToken) {
        var _rmi = RMI(rmiUrl, csrfToken);
        _private.RMI = function (remoteMethod, data) {
            return _rmi("", data, {headers: {"DjNg-Remote-Method": remoteMethod}});
        };
    };

    $(function () {
        var view_data = initialPageData.get('view_data');
        var csrfToken = $("#csrfTokenContainer").val();
        setRMI(initialPageData.reverse('linked_domain:domain_link_rmi'), csrfToken);

        var model = DomainLinksViewModel(view_data);
        if ($("#ko-tabs-pull-content").length) {
            $("#ko-tabs-pull-content").koApplyBindings(model);
        }
        if ($("#ko-tabs-push-content").length) {
            $("#ko-tabs-push-content").koApplyBindings(model);
        }
        if ($("#ko-tabs-manage-downstream").length) {
            $("#ko-tabs-manage-downstream").koApplyBindings(model);
        }

        if ($("#new-downstream-domain-modal").length) {
            $("#new-downstream-domain-modal").koApplyBindings(model.addDownstreamDomainModal);
        }

    });
});
<|endoftext|>


<commit_before><commit_msg>Use update 'broken' test fixture name<commit_after><|endoftext|>


<commit_before><commit_msg>* add initService tests<commit_after><|endoftext|>


<commit_before><commit_msg>Updating tests to ensure passwordConfirm data is not supplied.<commit_after><|endoftext|>


<commit_before><commit_msg>test(unit/scaling.js): remove IE11 hack after working around img onload browser bug #1061<commit_after><|endoftext|>


<commit_before><commit_msg>[TEST] Cover remaning URLs<commit_after><|endoftext|>


<commit_before>'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/math/base/random/randu' );
var pow = require( '@stdlib/math/base/special/pow' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var pkg = require( './../package.json' ).name;
var wasm = require( './../lib/wasm.js' )();

// FUNCTIONS //

/**
* Creates a benchmark function for measuring vanilla JavaScript.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark1( len ) {
	var x;
	var i;

	x = new Float64Array( len );
	for ( i = 0; i < x.length; i++ ) {
		x[ i ] = ( randu()*10000.0 ) - 20000.0;
	}
	return benchmark;

	/**
	* Benchmark function.
	*
	* @private
	* @param {Benchmark} b - benchmark instance
	*/
	function benchmark( b ) {
		var v;
		var i;
		var j;

		b.tic();
		for ( i = 0; i < b.iterations; i++ ) {
			for ( j = 0; j < len; j++ ) {
				v = ( randu()*10000.0 ) - 20000.0;
				x[ j ] = v;
			}
			if ( isnan( v ) ) {
				b.fail( 'should not return NaN' );
			}
		}
		b.toc();
		if ( isnan( v ) ) {
			b.fail( 'should not return NaN' );
		}
		b.pass( 'benchmark finished' );
		b.end();
	} // end FUNCTION benchmark()
} // end FUNCTION createBenchmark1()

/**
* Creates a benchmark function for measuring WASM heap `setValue` method.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark2( len ) {
	var x;
	var i;

	x = new Float64Array( len );
	for ( i = 0; i < x.length; i++ ) {
		x[ i ] = ( randu()*10000.0 ) - 20000.0;
	}
	return benchmark;

	/**
	* Benchmark function.
	*
	* @private
	* @param {Benchmark} b - benchmark instance
	*/
	function benchmark( b ) {
		var nbytes;
		var heap;
		var v;
		var i;
		var j;

		nbytes = x.length * x.BYTES_PER_ELEMENT;
		heap = wasm.malloc( nbytes );
		heap.set( new Uint8Array( x.buffer ) );

		b.tic();
		for ( i = 0; i < b.iterations; i++ ) {
			for ( j = 0; j < len; j++ ) {
				v = ( randu()*10000.0 ) - 20000.0;
				heap.setValue( j * x.BYTES_PER_ELEMENT, v );
			}
			if ( isnan( v ) ) {
				b.fail( 'should not return NaN' );
			}
		}
		b.toc();
		if ( isnan( v ) ) {
			b.fail( 'should not return NaN' );
		}
		b.pass( 'benchmark finished' );

		wasm.free( heap );
		b.end();
	} // end FUNCTION benchmark()
} // end FUNCTION createBenchmark2()

/**
* Creates a benchmark function for measuring WASM view.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark3( len ) {
	var x;
	var i;

	x = new Float64Array( len );
	for ( i = 0; i < x.length; i++ ) {
		x[ i ] = ( randu()*10000.0 ) - 20000.0;
	}
	return benchmark;

	/**
	* Benchmark function.
	*
	* @private
	* @param {Benchmark} b - benchmark instance
	*/
	function benchmark( b ) {
		var nbytes;
		var heap;
		var view;
		var v;
		var i;
		var j;

		nbytes = x.length * x.BYTES_PER_ELEMENT;
		heap = wasm.malloc( nbytes );
		heap.set( new Uint8Array( x.buffer ) );

		view = new Float64Array( heap.buffer, heap.byteOffset, x.length );

		b.tic();
		for ( i = 0; i < b.iterations; i++ ) {
			for ( j = 0; j < len; j++ ) {
				v = ( randu()*10000.0 ) - 20000.0;
				view[ j ] = v;
			}
			if ( isnan( v ) ) {
				b.fail( 'should not return NaN' );
			}
		}
		b.toc();
		if ( isnan( v ) ) {
			b.fail( 'should not return NaN' );
		}
		b.pass( 'benchmark finished' );

		wasm.free( heap );
		b.end();
	} // end FUNCTION benchmark()
} // end FUNCTION createBenchmark3()

// MAIN //

/**
* Main execution sequence.
*
* @private
*/
function main() {
	var len;
	var min;
	var max;
	var f;
	var i;

	min = 1; // 10^min
	max = 6; // 10^max

	for ( i = min; i <= max; i++ ) {
		len = pow( 10, i );

		f = createBenchmark1( len );
		bench( pkg+'::set-value,main:len='+len, f );

		f = createBenchmark2( len );
		bench( pkg+'::set-value,wasm,set-value:len='+len, f );

		f = createBenchmark3( len );
		bench( pkg+'::set-value,wasm,view:len='+len, f );
	}
} // end FUNCTION main()

main();
<commit_msg>Rename variables<commit_after>'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/math/base/random/randu' );
var pow = require( '@stdlib/math/base/special/pow' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var pkg = require( './../package.json' ).name;
var wasm = require( './../lib/wasm.js' )();

// FUNCTIONS //

/**
* Creates a benchmark function for measuring vanilla JavaScript.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark1( len ) {
	var x;
	var i;

	x = new Float64Array( len );
	for ( i = 0; i < x.length; i++ ) {
		x[ i ] = ( randu()*10000.0 ) - 20000.0;
	}
	return benchmark;

	/**
	* Benchmark function.
	*
	* @private
	* @param {Benchmark} b - benchmark instance
	*/
	function benchmark( b ) {
		var v;
		var i;
		var j;

		b.tic();
		for ( i = 0; i < b.iterations; i++ ) {
			for ( j = 0; j < len; j++ ) {
				v = ( randu()*10000.0 ) - 20000.0;
				x[ j ] = v;
			}
			if ( isnan( v ) ) {
				b.fail( 'should not return NaN' );
			}
		}
		b.toc();
		if ( isnan( v ) ) {
			b.fail( 'should not return NaN' );
		}
		b.pass( 'benchmark finished' );
		b.end();
	} // end FUNCTION benchmark()
} // end FUNCTION createBenchmark1()

/**
* Creates a benchmark function for measuring WASM heap `setValue` method.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark2( len ) {
	var x;
	var i;

	x = new Float64Array( len );
	for ( i = 0; i < x.length; i++ ) {
		x[ i ] = ( randu()*10000.0 ) - 20000.0;
	}
	return benchmark;

	/**
	* Benchmark function.
	*
	* @private
	* @param {Benchmark} b - benchmark instance
	*/
	function benchmark( b ) {
		var nbytes;
		var bytes;
		var v;
		var i;
		var j;

		nbytes = x.length * x.BYTES_PER_ELEMENT;
		bytes = wasm.malloc( nbytes );
		bytes.set( new Uint8Array( x.buffer ) );

		b.tic();
		for ( i = 0; i < b.iterations; i++ ) {
			for ( j = 0; j < len; j++ ) {
				v = ( randu()*10000.0 ) - 20000.0;
				bytes.setValue( j * x.BYTES_PER_ELEMENT, v );
			}
			if ( isnan( v ) ) {
				b.fail( 'should not return NaN' );
			}
		}
		b.toc();
		if ( isnan( v ) ) {
			b.fail( 'should not return NaN' );
		}
		b.pass( 'benchmark finished' );

		wasm.free( bytes );
		b.end();
	} // end FUNCTION benchmark()
} // end FUNCTION createBenchmark2()

/**
* Creates a benchmark function for measuring WASM view.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark3( len ) {
	var x;
	var i;

	x = new Float64Array( len );
	for ( i = 0; i < x.length; i++ ) {
		x[ i ] = ( randu()*10000.0 ) - 20000.0;
	}
	return benchmark;

	/**
	* Benchmark function.
	*
	* @private
	* @param {Benchmark} b - benchmark instance
	*/
	function benchmark( b ) {
		var nbytes;
		var bytes;
		var view;
		var v;
		var i;
		var j;

		nbytes = x.length * x.BYTES_PER_ELEMENT;
		bytes = wasm.malloc( nbytes );
		bytes.set( new Uint8Array( x.buffer ) );

		view = new Float64Array( bytes.buffer, bytes.byteOffset, x.length );

		b.tic();
		for ( i = 0; i < b.iterations; i++ ) {
			for ( j = 0; j < len; j++ ) {
				v = ( randu()*10000.0 ) - 20000.0;
				view[ j ] = v;
			}
			if ( isnan( v ) ) {
				b.fail( 'should not return NaN' );
			}
		}
		b.toc();
		if ( isnan( v ) ) {
			b.fail( 'should not return NaN' );
		}
		b.pass( 'benchmark finished' );

		wasm.free( bytes );
		b.end();
	} // end FUNCTION benchmark()
} // end FUNCTION createBenchmark3()

// MAIN //

/**
* Main execution sequence.
*
* @private
*/
function main() {
	var len;
	var min;
	var max;
	var f;
	var i;

	min = 1; // 10^min
	max = 6; // 10^max

	for ( i = min; i <= max; i++ ) {
		len = pow( 10, i );

		f = createBenchmark1( len );
		bench( pkg+'::set-value,main:len='+len, f );

		f = createBenchmark2( len );
		bench( pkg+'::set-value,wasm,set-value:len='+len, f );

		f = createBenchmark3( len );
		bench( pkg+'::set-value,wasm,view:len='+len, f );
	}
} // end FUNCTION main()

main();
<|endoftext|>


<commit_before><commit_msg>open strict mode<commit_after><|endoftext|>


<commit_before><commit_msg>Box and object tests<commit_after><|endoftext|>


<commit_before><commit_msg>comments<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed bug with sound<commit_after><|endoftext|>


<commit_before>var request = require('request');
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var createdby = "job-timer";

String.prototype.hashCode = function(){
    var hash = 0;
    if (this.length == 0) return hash;
    for (i = 0; i < this.length; i++) {
        char = this.charCodeAt(i);
        hash = ((hash<<5)-hash)+char;
        hash = hash & hash;
    }
    return hash;
}

var client_data = {
  endpoint: process.env.KUBE_ENDPOINT || "https://kubernetes.default",
  token: process.env.KUBE_TOKEN || fs.readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/token", "utf8")
};
var client_auth = {"Authorization": "Bearer " + client_data.token};
var r = request.defaults({'headers': client_auth, "strictSSL": false});
var namespace = process.env.KUBE_NAMESPACE;
if (!namespace) {
  console.log("Error, must specify KUBE_NAMESPACE.");
  process.exit(1);
}

var ndp = client_data.endpoint;
var extp = "/apis/extensions/v1beta1/";
var jobs_url = ndp + extp + "namespaces/" + namespace + "/" + "jobs";

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

var token = process.env.SCHEDULER_TOKEN || null;
var port = process.env.PORT || 8080;

// Endpoint to schedule a job with an ID
// POST /job/create
// body:
//   {
//      token: If required, SCHEDULER_TOKEN
//      id: ID the system should use for this. If duplicate will reject the call.
//      endpoint: Endpoint the system should GET to get current status
//      subkey: Subkey to check for end time, e.g. "payload.voting.expiry_vote_time"
//      callback: Callback URL to call when the timer is complete
//      callback_method: Callback method to use, default GET
//      callback_data: Callback data to use, default none, valid only for POST,
//      callback_content_type: Callback content type to use, default none, valid only for POST
//      initial_expire_time: Initial expire time.
//   }
// returns: 201 created or 503 error, or 208 already exists
app.post("/job/create", function(req, res) {
  // Check token
  if (!req.body) return res.status(503).json({"error": "No body given."});
  if (token && (!req.body.token || req.body.token != token))
    return res.status(503).json({"error": "No token given."});

  // Check ID
  if (!req.body.id || req.body.id.length < 3)
    return res.status(503).json({"error": "No ID given."});
  if (!req.body.endpoint || !req.body.subkey || !req.body.callback || !req.body.callback_method)
    return res.status(503).json({"error": "Missing required parameter."})

  // Check if it exists already
  r.get(jobs_url, function(err, resp, body) {
    if (err) return res.status(resp.statusCode).json(err);
    var items = JSON.parse(body)["items"];
    for (var itemx in items) {
      var item = items[itemx];
      if (item["metadata"]["labels"]["created-by"] !== createdby) continue;
      if (item["metadata"]["annotations"]["job-timer/id"] === req.body.id)
        return res.status(208).json({"error": "ID " + req.body.id + " already exists."});
    }
    // It doesn't, create it
    var jname = "job-timer-" + req.body.id.hashCode();
    var njob = {
      metadata: {
        "name": jname,
        "namespace": namespace,
        "labels": {
          "app": jname,
          "tier": "job",
          "created-by": createdby
        },
        "annotations": {
          "job-timer/id": req.body.id
        }
      },
      spec: {
        "completions": 1,
        "template": {
          "metadata": {
            "name": jname,
            "labels": {
              "app": jname,
              "tier": "job",
              "created-by": createdby
            },
            "annotations": {
              "job-timer/id": req.body.id
            }
          },
          spec: {
            "containers": [{
              "name": "job-timer",
              "image": "paralin/job-timer:latest",
              "env": [
                {
                  "name": "JOBTIMER_JOB_ID",
                  "value": "" + req.body.id
                },
                {
                  "name": "JOBTIMER_ENDPOINT",
                  "value": "" + req.body.endpoint
                },
                {
                  "name": "JOBTIMER_SUBKEY",
                  "value": "" + req.body.subkey
                },
                {
                  "name": "JOBTIMER_CALLBACK",
                  "value": "" + req.body.callback
                },
                {
                  "name": "JOBTIMER_CALLBACK_METHOD",
                  "value": "" + req.body.callback_method
                },
                {
                  "name": "JOBTIMER_CALLBACK_DATA",
                  "value": JSON.stringify(req.body.callback_data)
                },
                {
                  "name": "JOBTIMER_CALLBACK_DATA_CONTENT_TYPE",
                  "value": req.body.callback_content_type || "application/json"
                },
                {
                  "name": "JOBTIMER_INITIAL_EXPIRE_TIME",
                  "value": req.body.initial_expire_time || 0
                }
              ],
              "imagePullPolicy": "Always"
            }],
            // "restartPolicy": "Always" consider never
            "restartPolicy": "OnFailure"
          }
        }
      }
    };
    console.log("POST -> " + jobs_url + " body: " + JSON.stringify(njob));
    r({uri: jobs_url, method: "POST", json: njob}, function(err, resp, body) {
      if (err) return res.status(resp.statusCode).json(err);
      console.log("created job " + req.body.id);
      res.status(201).json({});
    });
  });
});

// Endpoint to cancel a job with an ID
// POST /job/cancel
// body:
//   {
//      token: If required, SCHEDULER_TOKEN
//      id: ID the system should use for this.
//   }
// returns: 200 or 404
app.post("/job/cancel", function(req, res) {
  // Check token
  if (!req.body) return res.status(503).json({"error": "No body given."});
  if (token && (!req.body.token || req.body.token != token))
    return res.status(503).json({"error": "No token given."});

  // Check ID
  if (!req.body.id || req.body.id.length < 3)
    return res.status(503).json({"error": "No ID given."});

  // Check if it exists already
  r.get(jobs_url, function(err, resp, body) {
    if (err) return res.status(resp.statusCode).json(err);
    var items = JSON.parse(body)["items"];
    for (var itemx in items) {
      var item = items[itemx];
      console.log(item);
      if (item["metadata"]["labels"]["created-by"] !== createdby) continue;
      if (item["metadata"]["annotations"]["job-timer/id"] === req.body.id) {
        console.log("canceling job " + req.body.id);
        r.del(jobs_url + "/" + item["metadata"]["name"], function(err, resp, body) {
          if (err) return res.status(resp.statusCode).json(err);
          console.log("canceled job " + req.body.id);
          res.status(200).json({});
        });
        return;
      }
    }
    console.log("cancel request for not-found job " + req.body.id);
    res.status(404).json({"error": "not found"});
    return;
  });
});

app.listen(port, function() {
  console.log("listening on port " + port);
});
<commit_msg>Fix env var string conversion<commit_after>var request = require('request');
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var createdby = "job-timer";

String.prototype.hashCode = function(){
    var hash = 0;
    if (this.length == 0) return hash;
    for (i = 0; i < this.length; i++) {
        char = this.charCodeAt(i);
        hash = ((hash<<5)-hash)+char;
        hash = hash & hash;
    }
    return hash;
}

var client_data = {
  endpoint: process.env.KUBE_ENDPOINT || "https://kubernetes.default",
  token: process.env.KUBE_TOKEN || fs.readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/token", "utf8")
};
var client_auth = {"Authorization": "Bearer " + client_data.token};
var r = request.defaults({'headers': client_auth, "strictSSL": false});
var namespace = process.env.KUBE_NAMESPACE;
if (!namespace) {
  console.log("Error, must specify KUBE_NAMESPACE.");
  process.exit(1);
}

var ndp = client_data.endpoint;
var extp = "/apis/extensions/v1beta1/";
var jobs_url = ndp + extp + "namespaces/" + namespace + "/" + "jobs";

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

var token = process.env.SCHEDULER_TOKEN || null;
var port = process.env.PORT || 8080;

// Endpoint to schedule a job with an ID
// POST /job/create
// body:
//   {
//      token: If required, SCHEDULER_TOKEN
//      id: ID the system should use for this. If duplicate will reject the call.
//      endpoint: Endpoint the system should GET to get current status
//      subkey: Subkey to check for end time, e.g. "payload.voting.expiry_vote_time"
//      callback: Callback URL to call when the timer is complete
//      callback_method: Callback method to use, default GET
//      callback_data: Callback data to use, default none, valid only for POST,
//      callback_content_type: Callback content type to use, default none, valid only for POST
//      initial_expire_time: Initial expire time.
//   }
// returns: 201 created or 503 error, or 208 already exists
app.post("/job/create", function(req, res) {
  // Check token
  if (!req.body) return res.status(503).json({"error": "No body given."});
  if (token && (!req.body.token || req.body.token != token))
    return res.status(503).json({"error": "No token given."});

  // Check ID
  if (!req.body.id || req.body.id.length < 3)
    return res.status(503).json({"error": "No ID given."});
  if (!req.body.endpoint || !req.body.subkey || !req.body.callback || !req.body.callback_method)
    return res.status(503).json({"error": "Missing required parameter."})

  // Check if it exists already
  r.get(jobs_url, function(err, resp, body) {
    if (err) return res.status(resp.statusCode).json(err);
    var items = JSON.parse(body)["items"];
    for (var itemx in items) {
      var item = items[itemx];
      if (item["metadata"]["labels"]["created-by"] !== createdby) continue;
      if (item["metadata"]["annotations"]["job-timer/id"] === req.body.id)
        return res.status(208).json({"error": "ID " + req.body.id + " already exists."});
    }
    // It doesn't, create it
    var jname = "job-timer-" + req.body.id.hashCode();
    var njob = {
      metadata: {
        "name": jname,
        "namespace": namespace,
        "labels": {
          "app": jname,
          "tier": "job",
          "created-by": createdby
        },
        "annotations": {
          "job-timer/id": req.body.id
        }
      },
      spec: {
        "completions": 1,
        "template": {
          "metadata": {
            "name": jname,
            "labels": {
              "app": jname,
              "tier": "job",
              "created-by": createdby
            },
            "annotations": {
              "job-timer/id": req.body.id
            }
          },
          spec: {
            "containers": [{
              "name": "job-timer",
              "image": "paralin/job-timer:latest",
              "env": [
                {
                  "name": "JOBTIMER_JOB_ID",
                  "value": "" + req.body.id
                },
                {
                  "name": "JOBTIMER_ENDPOINT",
                  "value": "" + req.body.endpoint
                },
                {
                  "name": "JOBTIMER_SUBKEY",
                  "value": "" + req.body.subkey
                },
                {
                  "name": "JOBTIMER_CALLBACK",
                  "value": "" + req.body.callback
                },
                {
                  "name": "JOBTIMER_CALLBACK_METHOD",
                  "value": "" + req.body.callback_method
                },
                {
                  "name": "JOBTIMER_CALLBACK_DATA",
                  "value": JSON.stringify(req.body.callback_data)
                },
                {
                  "name": "JOBTIMER_CALLBACK_DATA_CONTENT_TYPE",
                  "value": req.body.callback_content_type || "application/json"
                },
                {
                  "name": "JOBTIMER_INITIAL_EXPIRE_TIME",
                  "value": (req.body.initial_expire_time || 0) + ""
                }
              ],
              "imagePullPolicy": "Always"
            }],
            // "restartPolicy": "Always" consider never
            "restartPolicy": "OnFailure"
          }
        }
      }
    };
    console.log("POST -> " + jobs_url + " body: " + JSON.stringify(njob));
    r({uri: jobs_url, method: "POST", json: njob}, function(err, resp, body) {
      if (err) return res.status(resp.statusCode).json(err);
      console.log("created job " + req.body.id);
      res.status(201).json({});
    });
  });
});

// Endpoint to cancel a job with an ID
// POST /job/cancel
// body:
//   {
//      token: If required, SCHEDULER_TOKEN
//      id: ID the system should use for this.
//   }
// returns: 200 or 404
app.post("/job/cancel", function(req, res) {
  // Check token
  if (!req.body) return res.status(503).json({"error": "No body given."});
  if (token && (!req.body.token || req.body.token != token))
    return res.status(503).json({"error": "No token given."});

  // Check ID
  if (!req.body.id || req.body.id.length < 3)
    return res.status(503).json({"error": "No ID given."});

  // Check if it exists already
  r.get(jobs_url, function(err, resp, body) {
    if (err) return res.status(resp.statusCode).json(err);
    var items = JSON.parse(body)["items"];
    for (var itemx in items) {
      var item = items[itemx];
      console.log(item);
      if (item["metadata"]["labels"]["created-by"] !== createdby) continue;
      if (item["metadata"]["annotations"]["job-timer/id"] === req.body.id) {
        console.log("canceling job " + req.body.id);
        r.del(jobs_url + "/" + item["metadata"]["name"], function(err, resp, body) {
          if (err) return res.status(resp.statusCode).json(err);
          console.log("canceled job " + req.body.id);
          res.status(200).json({});
        });
        return;
      }
    }
    console.log("cancel request for not-found job " + req.body.id);
    res.status(404).json({"error": "not found"});
    return;
  });
});

app.listen(port, function() {
  console.log("listening on port " + port);
});
<|endoftext|>


<commit_before><commit_msg>missing require<commit_after><|endoftext|>


<commit_before><commit_msg>DPRO-2709 - remove console.log<commit_after><|endoftext|>