All files / web/bundles/pimui/js/product/form categories.js

100% Statements 63/63
92.86% Branches 13/14
100% Functions 20/20
100% Lines 63/63

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 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273                  302x                                                         302x                                                     384x   384x   384x 384x     384x             383x           383x 25x 22x       383x             34x 34x   34x 24x 24x     34x                 34x         34x   34x 34x   34x 34x     34x             98x   98x             12x 12x 7x 7x                   49x                                     34x     34x 20x     34x 27x     34x                   7x 7x 7x   7x                 8x 8x   8x 8x   8x   8x 8x 8x             34x 64x 64x 64x 64x 52x     64x                       11x 8x 8x 8x           11x                 6332x          
'use strict';
/**
 * Category tab extension
 *
 * @author    Julien Sanchez <julien@akeneo.com>
 * @author    Filips Alpe <filips@akeneo.com>
 * @copyright 2015 Akeneo SAS (http://www.akeneo.com)
 * @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
define(
    [
        'jquery',
        'underscore',
        'oro/translator',
        'backbone',
        'pim/form',
        'pim/template/product/tab/categories',
        'pim/template/product/tab/catalog-switcher',
        'pim/template/product/tab/jstree-locked-item',
        'pim/user-context',
        'routing',
        'pim/tree/associate',
        'oro/mediator'
    ],
    function (
        $,
        _,
        __,
        Backbone,
        BaseForm,
        formTemplate,
        switcherTemplate,
        lockedTemplate,
        UserContext,
        Routing,
        TreeAssociate,
        mediator
    ) {
        return BaseForm.extend({
            template: _.template(formTemplate),
            switcherTemplate: _.template(switcherTemplate),
            lockedTemplate: _.template(lockedTemplate),
            className: 'tab-pane active',
            id: 'product-categories',
            treeLinkSelector: 'tree-link-',
            treeHasItemClass: 'tree-has-item',
            events: {
                'click .nav-tabs li': 'changeTree',
                'change #hidden-tree-input': 'updateModel'
            },
            treeAssociate: null,
            cache: {},
            trees: [],
            onLoadedEvent: null,
 
            /**
             * Associates the tree code to the number of selected categories
             * Example: { master: 1, sales: 12 }
             */
            categoriesCount: {},
 
            /**
             * {@inheritdoc}
             */
            initialize: function (config) {
                this.state = new Backbone.Model();
 
                this.state.set('selectedCategories', []);
 
                Eif (undefined !== config) {
                    this.config = config.config;
                }
 
                BaseForm.prototype.initialize.apply(this, arguments);
            },
 
            /**
             * {@inheritdoc}
             */
            configure: function () {
                this.trigger('tab:register', {
                    code: (undefined === this.config.tabCode) ? this.code : this.config.tabCode,
                    isVisible: this.isVisible.bind(this),
                    label: __('pim_enrich.entity.category.plural_label')
                });
 
                this.listenTo(this.getRoot(), 'pim_enrich:form:locale_switcher:change', function (localeEvent) {
                    if ('base_product' === localeEvent.context) {
                        this.render();
                    }
                }.bind(this));
 
                return BaseForm.prototype.configure.apply(this, arguments);
            },
 
            /**
             * {@inheritdoc}
             */
            render: function () {
                this.loadTrees().done(function (trees) {
                    this.trees = trees;
 
                    if (undefined === this.state.toJSON().currentTree) {
                        this.state.set('currentTree', _.first(this.trees).code);
                        this.state.set('currentTreeId', _.first(this.trees).id);
                    }
 
                    this.$el.html(
                        this.template({
                            product: this.getFormData(),
                            locale: UserContext.get('catalogLocale'),
                            state: this.state.toJSON(),
                            trees: this.trees
                        })
                    );
 
                    this.treeAssociate = new TreeAssociate('#trees', '#hidden-tree-input', {
                        list_categories: this.config.itemCategoryListRoute,
                        children:        'pim_enrich_categorytree_children'
                    });
 
                    this.delegateEvents();
 
                    this.onLoadedEvent = this.lockCategories.bind(this);
                    mediator.on('jstree:loaded', this.onLoadedEvent);
 
                    this.initCategoryCount();
                    this.renderCategorySwitcher();
                }.bind(this));
 
                return this;
            },
 
            /**
             * {@inheritdoc}
             */
            shutdown: function () {
                mediator.off('jstree:loaded', this.onLoadedEvent);
 
                BaseForm.prototype.shutdown.apply(this, arguments);
            },
 
            /**
             * Locks a set of categories
             */
            lockCategories: function() {
                const lockedCategoryIds = this.getFormData().meta.ascendant_category_ids;
                lockedCategoryIds.forEach((categoryId) => {
                    const node = $('#node_' + categoryId);
                    node.find('> a').replaceWith(this.lockedTemplate({
                        label: node.find('> a').text().trim()
                    }));
                });
            },
 
            /**
             * Renders the category switcher in the main template
             */
            renderCategorySwitcher: function () {
                this.$el.find('.catalog-switcher:first').html(this.switcherTemplate({
                    state: this.state.toJSON(),
                    trees: this.trees,
                    categoriesCount: this.categoriesCount,
                    treeLinkSelector: this.treeLinkSelector,
                    currentCategory: _.result(_.findWhere(
                        this.trees,
                        {code: this.state.toJSON().currentTree}),
                        'label'
                    )
                }));
            },
 
            /**
             * Load category trees
             *
             * @returns {promise}
             */
            loadTrees: function () {
                return $.getJSON(
                    Routing.generate(this.config.itemCategoryTreeRoute, { id: this.getFormData().meta.id })
                ).then(function (data) {
                    _.each(data.categories, function (category) {
                        this.cache[category.id] = category;
                    }.bind(this));
 
                    if (_.isEmpty(this.state.get('selectedCategories'))) {
                        this.state.set('selectedCategories', _.pluck(data.categories, 'id'));
                    }
 
                    return data.trees;
                }.bind(this));
            },
 
            /**
             * Displays the current tree when the user choose another one
             *
             * @param {Event} event
             */
            changeTree: function (event) {
                this.state.set('currentTree', event.currentTarget.dataset.tree);
                this.state.set('currentTreeId', event.currentTarget.dataset.treeId);
                this.treeAssociate.switchTree(event.currentTarget.dataset.treeId);
 
                this.renderCategorySwitcher();
            },
 
            /**
             * Change the current model when categories are checked/unchecked
             *
             * @param {Event} event
             */
            updateModel: function (event) {
                var selectedIds = _.filter(event.currentTarget.value.split(','), _.identity);
                this.state.set('selectedCategories', selectedIds);
 
                var rootTreeCode = this.state.get('currentTree');
                this.categoriesCount[rootTreeCode] =
                    this.$('li[data-code=' + rootTreeCode +  '] .jstree-checked').length;
                this.renderCategorySwitcher();
 
                var categoryCodes = _.map(selectedIds, this.getCategoryCode.bind(this));
                this.getFormModel().set('categories', categoryCodes);
                mediator.trigger('pim_enrich:form:entity:update_state');
            },
 
            /**
             * Initialize category count with hidden values
             */
            initCategoryCount: function () {
                _.each(this.trees, function (tree) {
                    var selectedCategories = [];
                    var hiddenSelection = this.$('#hidden-tree-input').val();
                    hiddenSelection = hiddenSelection.length > 0 ? hiddenSelection.split(',') : [];
                    _.each(hiddenSelection, function (categoryId) {
                        selectedCategories.push(this.cache[categoryId]);
                    }.bind(this));
 
                    this.categoriesCount[tree.code] = _.where(selectedCategories, {rootId: tree.id}).length;
                }.bind(this));
            },
 
            /**
             * Fetch category code from cache
             *
             * @param {integer} id
             *
             * @returns {string}
             */
            getCategoryCode: function (id) {
                if (!this.cache[id]) {
                    var $categoryElement = this.$('#node_' + id);
                    var $rootElement     = $categoryElement.closest('.root-unselectable');
                    this.cache[id] = {
                        code: String($categoryElement.data('code')),
                        rootId: $rootElement.data('tree-id')
                    };
                }
 
                return this.cache[id].code;
            },
 
            /**
             * Check if this extension is visible
             *
             * @returns {boolean}
             */
            isVisible: function () {
                return true;
            }
        });
    }
);