All files / web/bundles/pimui/js/filter/attribute select.js

100% Statements 44/44
100% Branches 15/15
100% Functions 22/22
100% Lines 44/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234    11x                                           11x                       14x   14x             14x 68x     14x             93x               14x 11x     14x                           14x       14x 12x               14x       14x 14x 12x     14x                                   17x 17x   17x 15x 15x 25x       17x                         14x   14x         20x               20x       6x 6x 6x 11x   6x                               20x   20x 14x     20x                     34x                                           14x 14x 14x   14x          
'use strict';
 
define([
    'jquery',
    'underscore',
    'oro/translator',
    'routing',
    'pim/filter/attribute/attribute',
    'pim/fetcher-registry',
    'pim/user-context',
    'pim/i18n',
    'pim/template/filter/attribute/select',
    'jquery.select2'
], function (
    $,
    _,
    __,
    Routing,
    BaseFilter,
    FetcherRegistry,
    UserContext,
    i18n,
    template
) {
    return BaseFilter.extend({
        shortname: 'select',
        template: _.template(template),
        choicePromise: null,
        events: {
            'change [name="filter-value"], [name="filter-operator"]': 'updateState'
        },
 
        /**
         * {@inheritdoc}
         */
        initialize: function () {
            this.choicePromise = null;
 
            return BaseFilter.prototype.initialize.apply(this, arguments);
        },
 
        /**
         * {@inheritdoc}
         */
        configure: function () {
            this.listenTo(this.getRoot(), 'pim_enrich:form:entity:pre_update', function (data) {
                _.defaults(data, {field: this.getCode() + '.code'});
            }.bind(this));
 
            return BaseFilter.prototype.configure.apply(this, arguments);
        },
 
        /**
         * {@inheritdoc}
         */
        isEmpty: function () {
            return !_.contains(['EMPTY', 'NOT EMPTY'], this.getOperator()) &&
                (undefined === this.getValue() || _.isEmpty(this.getValue()));
        },
 
        /**
         * {@inheritdoc}
         */
        renderInput: function () {
            if (undefined === this.getOperator()) {
                this.setOperator(_.first(_.values(this.config.operators)));
            }
 
            return this.template({
                __: __,
                value: this.getValue(),
                field: this.getField(),
                operator: this.getOperator(),
                editable: this.isEditable(),
                operators: this.getLabelledOperatorChoices(this.shortname)
            });
        },
 
        /**
         * {@inheritdoc}
         */
        postRender: function (templateContext) {
            this.$('.operator').select2({
                minimumResultsForSearch: -1
            });
 
            if (!_.contains(['EMPTY', 'NOT EMPTY'], this.getOperator())) {
                this.$('.value').select2(templateContext.select2Options);
            }
        },
 
        /**
         * {@inheritdoc}
         */
        getTemplateContext: function () {
            return FetcherRegistry
                .getFetcher('attribute')
                .fetch(this.getCode())
                .then(function (attribute) {
                    return this.cleanInvalidValues(attribute, this.getValue()).then(function (cleanedValues) {
                        if (!_.isEqual(this.getValue(), cleanedValues)) {
                            this.setValue(cleanedValues, {silent: false});
                        }
 
                        return {
                            label: i18n.getLabel(
                                attribute.labels,
                                UserContext.get('uiLocale'),
                                attribute.code
                            ),
                            select2Options: this.getSelect2Options(attribute),
                            removable: this.isRemovable(),
                            editable: this.isEditable()
                        };
                    }.bind(this));
                }.bind(this));
        },
 
        /**
         * {@inheritdoc}
         */
        updateState: function () {
            var cleanedValues = [];
            var operator = this.$('[name="filter-operator"]').val();
 
            if (!_.contains(['EMPTY', 'NOT EMPTY'], operator)) {
                var value = this.$('[name="filter-value"]').val().split(/[\s,]+/);
                cleanedValues = _.reject(value, function (val) {
                    return '' === val;
                });
            }
 
            this.setData({
                field: this.getField(),
                operator: operator,
                value: cleanedValues
            });
        },
 
        /**
         * Return the choice options or reference data to populate the select2.
         *
         * @returns {Object}
         */
        getSelect2Options: function (attribute) {
            var choiceUrl = this.getChoiceUrl(attribute);
 
            return {
                ajax: {
                    url: choiceUrl,
                    cache: true,
                    data: function (term) {
                        return {
                            search: term,
                            options: {
                                locale: UserContext.get('uiLocale')
                            }
                        };
                    },
                    results: function (data) {
                        return data;
                    }
                },
                initSelection: function (element, callback) {
                    this.getChoices(attribute).then(function (response) {
                        var results = response.results;
                        var choices = _.map($(element).val().split(','), function (choice) {
                            return _.findWhere(results, {id: choice});
                        });
                        callback(choices);
                    }.bind(this));
                }.bind(this),
                multiple: true
            };
        },
 
        /**
         * Return the select choice promise which, once resolved, return all possible choices
         * for the given select attribute.
         *
         * @param {string} attribute
         *
         * @returns {Promise}
         */
        getChoices: function (attribute) {
            var choiceUrl = this.getChoiceUrl(attribute);
 
            if (null === this.choicePromise) {
                this.choicePromise = $.get(choiceUrl);
            }
 
            return this.choicePromise;
        },
 
        /**
         * Get the string Url to access all select choices related to the given attribute.
         *
         * @param {string} attribute
         *
         * @returns {string}
         */
        getChoiceUrl: function (attribute) {
            return Routing.generate(
                this.config.url,
                {
                    class: this.config.entityClass,
                    dataLocale: UserContext.get('uiLocale'),
                    collectionId: attribute.meta.id,
                    options: {type: 'code'},
                    referenceDataName: attribute.reference_data_name
                }
            );
        },
 
        /**
         * Clean invalid values by removing possibly non-existent options coming from database.
         * This method returns a promise which, once resolved, should return the attribute.
         *
         * @param {string} attribute
         * @param {array} currentValues
         *
         * @returns {Promise}
         */
        cleanInvalidValues: function (attribute, currentValues) {
            return this.getChoices(attribute).then(function (response) {
                var possibleValues = _.pluck(response.results, 'id');
                currentValues  = undefined !== currentValues ? currentValues : [];
 
                return _.intersection(currentValues, possibleValues);
            }.bind(this));
        }
    });
});