<commit_before>/* This file is part of Indico.
 * Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

ndRegForm.controller('FieldCtrl', function($scope, regFormFactory) {
    $scope.fieldApi = {};
    $scope.getDefaultFieldSetting = regFormFactory.getDefaultFieldSetting;

    var getRequestParams = function(field) {
        return {
            confId: $scope.confId,
            sectionId: $scope.section.id,
            fieldId: field.id,
            confFormId: $scope.confFormId
        };
    };

    $scope.fieldApi.disableField = function(field) {
        regFormFactory.Fields.disable(getRequestParams(field), function(updatedField) {
            regFormFactory.processResponse(updatedField, {
                success: function(updatedField) {
                    var index = -1;
                    _.find($scope.section.items, function(item) {
                        index++;
                        return item.id == $scope.field.id;
                    });

                    $scope.field.isEnabled = updatedField.isEnabled;
                    $scope.section.items.splice(index, 1);
                    $scope.section.items.push($scope.field);
                }
            });
        }, handleAjaxError);
    };

    $scope.fieldApi.enableField = function(field) {
        regFormFactory.Fields.enable(getRequestParams(field), function(updatedField) {
            regFormFactory.processResponse(updatedField, {
                success: function(updatedField) {
                    $scope.field.isEnabled = updatedField.isEnabled;
                    $scope.section.items.sort(function(a, b) {
                        return a.position - b.position;
                    });
                }
            });
        }, handleAjaxError);
    };

    $scope.fieldApi.removeField = function(field) {
        $scope.sectionApi.removeField($scope.section, field);
    };

    $scope.fieldApi.updateField = function(field, data) {
        var postData = angular.extend(getRequestParams(field), {fieldData: data});

        if ($scope.isNew()) {
            delete postData['fieldId'];
        }

        regFormFactory.Fields[$scope.isNew() ? 'save' : 'modify'](postData, function(response) {
            regFormFactory.processResponse(response, {
                success: function(response) {
                    if ($scope.isNew()) {
                        $scope.field = angular.extend($scope.field, response);
                    } else {
                        $scope.field = angular.extend($scope.field, postData.fieldData);
                    }
                }
            });
        }, handleAjaxError);
    };

    $scope.openFieldSettings = function() {
        $scope.dialog.open = true;
    };

    $scope.canBeDeleted = function(field) {
        return !field.fieldIsPersonalData;
    };

    $scope.canBeDisabled = function(field) {
        return !field.fieldIsRequired;
    };

    $scope.isNew = function() {
        return $scope.field.id == -1;
    };

    $scope.settings = {
        isBillable: false,
        date: false,
        defaultValue: false,
        singleColumn: false,
        itemtable: false,
        isRequired: true,
        number: false,
        placesLimit: false,
        rowsAndColumns: false,
        size: false,
        formData: [
            'title',
            'description',
            'isRequired'
        ]
    };

    $scope.dialog = {
        open: false,
        title: function() {
            return $scope.isNew()? $T('New Field') : $T('Edit Field');
        },
        okButton: function() {
            return $scope.isNew()? $T('Add') : $T('Update');
        },
        onOk: function(dialogScope) {
            if (dialogScope.optionsForm.$invalid === true) {
                dialogScope.$apply(dialogScope.setSelectedTab('tab-options'));
                return false;
            }

            if ($scope.settings.itemtable && !dialogScope.hasRadioItems()) {
                dialogScope.$apply(dialogScope.setSelectedTab('tab-editItems'));
                return false;
            }

            if ($scope.settings.itemtable) {
                var validCaptions = _.all(dialogScope.formData.radioitems, function(item) {
                    return item.remove || !!item.caption;
                });

                if (!validCaptions) {
                    dialogScope.$apply(dialogScope.setSelectedTab('tab-editItems'));
                    return false;
                }
            }

            $scope.fieldApi.updateField($scope.field, dialogScope.formData);
            return true;
        },
        onCancel: function() {
            if ($scope.isNew()) {
                $scope.sectionApi.removeNewField();
            }
        }
    };

    function checkEmail(email) {
        $scope.emailInfoMessage = '';
        email = email.trim();
        if (!email) {
            return;
        }
        $.ajax({
            url: $scope.checkEmailUrl,
            data: {email: email},
            error: handleAjaxError,
            success: function(data) {
                var msg;
                if (data.conflict == 'email') {
                    msg = $T.gettext('There is already a registration with this email address.');
                } else if (data.conflict == 'user') {
                    msg = $T.gettext('The user associated with this email address is already registered.');
                } else if (!data.user) {
                    msg = $T.gettext('The registration will not be associated with any indico account.');
                } else if (data.self) {
                    msg = $T.gettext('The registration will be associated with your Indico account.');
                } else {
                    var name = $('<span>', {text: data.user}).html();
                    msg = $T.gettext('The registration will be associated with the Indico account <strong>{0}</strong>.').format(name);
                }
                $('#regformSubmit').prop('disabled', !!data.conflict);
                $scope.emailInfoError = !!data.conflict;
                $scope.emailInfoMessage = msg;
                $scope.$apply();
            }
        });
    }

    $scope.fieldName = $scope.field.htmlName;
    $scope.emailInfoMessage = '';
    $scope.emailInfoError = false;
    if ($scope.field.htmlName == 'email') {
        $('#registrationForm').on('change input', 'input[name=email]', _.debounce(function() {
            checkEmail($(this).val());
        }, 250));
        checkEmail($scope.userdata.email);
    }
});

ndRegForm.controller('BillableCtrl', function($scope, $filter) {
    $scope.getBillableStr = function(item, uservalue) {
        var str = '';

        if ($scope.isBillable(item)) {
            str += ' {0} {1}'.format(item.price, $scope.currency);
        }

        if ($scope.hasPlacesLimit(item)) {
            if ($scope.hasPlacesLeft(item, uservalue)) {
                str += ' [{0} {1}]'.format($scope.getPlacesLeft(item, uservalue), $filter('i18n')('place(s) left'));
            } else {
                str += ' [{0}]'.format($filter('i18n')('no places left'));
            }
        }

        return str;
    };

    /*
     * Returns the places left for a field. Optionally corrected with the value
     * the user selected initially, and the current selection on the page.
     *<commit_msg>Fix js error with undefined email<commit_after>/* This file is part of Indico.
 * Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

ndRegForm.controller('FieldCtrl', function($scope, regFormFactory) {
    $scope.fieldApi = {};
    $scope.getDefaultFieldSetting = regFormFactory.getDefaultFieldSetting;

    var getRequestParams = function(field) {
        return {
            confId: $scope.confId,
            sectionId: $scope.section.id,
            fieldId: field.id,
            confFormId: $scope.confFormId
        };
    };

    $scope.fieldApi.disableField = function(field) {
        regFormFactory.Fields.disable(getRequestParams(field), function(updatedField) {
            regFormFactory.processResponse(updatedField, {
                success: function(updatedField) {
                    var index = -1;
                    _.find($scope.section.items, function(item) {
                        index++;
                        return item.id == $scope.field.id;
                    });

                    $scope.field.isEnabled = updatedField.isEnabled;
                    $scope.section.items.splice(index, 1);
                    $scope.section.items.push($scope.field);
                }
            });
        }, handleAjaxError);
    };

    $scope.fieldApi.enableField = function(field) {
        regFormFactory.Fields.enable(getRequestParams(field), function(updatedField) {
            regFormFactory.processResponse(updatedField, {
                success: function(updatedField) {
                    $scope.field.isEnabled = updatedField.isEnabled;
                    $scope.section.items.sort(function(a, b) {
                        return a.position - b.position;
                    });
                }
            });
        }, handleAjaxError);
    };

    $scope.fieldApi.removeField = function(field) {
        $scope.sectionApi.removeField($scope.section, field);
    };

    $scope.fieldApi.updateField = function(field, data) {
        var postData = angular.extend(getRequestParams(field), {fieldData: data});

        if ($scope.isNew()) {
            delete postData['fieldId'];
        }

        regFormFactory.Fields[$scope.isNew() ? 'save' : 'modify'](postData, function(response) {
            regFormFactory.processResponse(response, {
                success: function(response) {
                    if ($scope.isNew()) {
                        $scope.field = angular.extend($scope.field, response);
                    } else {
                        $scope.field = angular.extend($scope.field, postData.fieldData);
                    }
                }
            });
        }, handleAjaxError);
    };

    $scope.openFieldSettings = function() {
        $scope.dialog.open = true;
    };

    $scope.canBeDeleted = function(field) {
        return !field.fieldIsPersonalData;
    };

    $scope.canBeDisabled = function(field) {
        return !field.fieldIsRequired;
    };

    $scope.isNew = function() {
        return $scope.field.id == -1;
    };

    $scope.settings = {
        isBillable: false,
        date: false,
        defaultValue: false,
        singleColumn: false,
        itemtable: false,
        isRequired: true,
        number: false,
        placesLimit: false,
        rowsAndColumns: false,
        size: false,
        formData: [
            'title',
            'description',
            'isRequired'
        ]
    };

    $scope.dialog = {
        open: false,
        title: function() {
            return $scope.isNew()? $T('New Field') : $T('Edit Field');
        },
        okButton: function() {
            return $scope.isNew()? $T('Add') : $T('Update');
        },
        onOk: function(dialogScope) {
            if (dialogScope.optionsForm.$invalid === true) {
                dialogScope.$apply(dialogScope.setSelectedTab('tab-options'));
                return false;
            }

            if ($scope.settings.itemtable && !dialogScope.hasRadioItems()) {
                dialogScope.$apply(dialogScope.setSelectedTab('tab-editItems'));
                return false;
            }

            if ($scope.settings.itemtable) {
                var validCaptions = _.all(dialogScope.formData.radioitems, function(item) {
                    return item.remove || !!item.caption;
                });

                if (!validCaptions) {
                    dialogScope.$apply(dialogScope.setSelectedTab('tab-editItems'));
                    return false;
                }
            }

            $scope.fieldApi.updateField($scope.field, dialogScope.formData);
            return true;
        },
        onCancel: function() {
            if ($scope.isNew()) {
                $scope.sectionApi.removeNewField();
            }
        }
    };

    function checkEmail(email) {
        $scope.emailInfoMessage = '';
        email = email.trim();
        if (!email) {
            return;
        }
        $.ajax({
            url: $scope.checkEmailUrl,
            data: {email: email},
            error: handleAjaxError,
            success: function(data) {
                var msg;
                if (data.conflict == 'email') {
                    msg = $T.gettext('There is already a registration with this email address.');
                } else if (data.conflict == 'user') {
                    msg = $T.gettext('The user associated with this email address is already registered.');
                } else if (!data.user) {
                    msg = $T.gettext('The registration will not be associated with any indico account.');
                } else if (data.self) {
                    msg = $T.gettext('The registration will be associated with your Indico account.');
                } else {
                    var name = $('<span>', {text: data.user}).html();
                    msg = $T.gettext('The registration will be associated with the Indico account <strong>{0}</strong>.').format(name);
                }
                $('#regformSubmit').prop('disabled', !!data.conflict);
                $scope.emailInfoError = !!data.conflict;
                $scope.emailInfoMessage = msg;
                $scope.$apply();
            }
        });
    }

    $scope.fieldName = $scope.field.htmlName;
    $scope.emailInfoMessage = '';
    $scope.emailInfoError = false;
    if ($scope.field.htmlName == 'email') {
        $('#registrationForm').on('change input', 'input[name=email]', _.debounce(function() {
            checkEmail($(this).val());
        }, 250));
        checkEmail($scope.userdata.email || '');
    }
});

ndRegForm.controller('BillableCtrl', function($scope, $filter) {
    $scope.getBillableStr = function(item, uservalue) {
        var str = '';

        if ($scope.isBillable(item)) {
            str += ' {0} {1}'.format(item.price, $scope.currency);
        }

        if ($scope.hasPlacesLimit(item)) {
            if ($scope.hasPlacesLeft(item, uservalue)) {
                str += ' [{0} {1}]'.format($scope.getPlacesLeft(item, uservalue), $filter('i18n')('place(s) left'));
            } else {
                str += ' [{0}]'.format($filter('i18n')('no places left'));
            }
        }

        return str;
    };

    /*
     * Returns the places left for a field. Optionally corrected with the value
     * the user selected initially, and the current selection on the page.
     *
{'fraction_non_alphanumeric': 0.12506240639041438, 'fraction_numerical': 0.0031203195207189214, 'mean_word_length': 1.7869565217391303, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4667418', 'n_tokens_mistral': 4310, 'n_tokens_neox': 4145, 'n_words': 937}