All files / web/bundles/pimui/js/product/form variant-navigation.js

96.19% Statements 101/105
88.64% Branches 39/44
100% Functions 33/33
96.19% Lines 101/105

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 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445                  302x                                                                             302x                             383x   383x             461x 461x   461x 365x   365x     96x                 96x             96x 96x   96x 136x 136x                 93x 93x 93x           93x         93x       39x             136x   136x   3x     35x     136x                   35x   35x 35x   35x   35x       35x       35x     15x 15x                           35x                       35x 35x   35x 1x       1x         34x 26x     8x                 15x               15x   15x         15x 8x   7x     15x             15x                     14x       14x       14x     8x 8x                         50x       50x       50x   50x                         93x 93x   93x 39x 39x   39x       54x 54x 54x   54x     54x     54x                             93x 54x     39x       39x                       39x 39x   39x 123x   123x                       39x 39x 39x       39x 39x 85x 188x 22x 166x 63x             39x                     3x 3x   3x                 14x       14x 14x         14x          
'use strict';
 
/**
 * Extension to display the variant navigation to browse variant product structure (parents and children)
 *
 * @author    Adrien Pétremann <adrien.petremann@akeneo.com>
 * @copyright 2017 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',
        'pim/router',
        'pim/i18n',
        'pim/user-context',
        'pim/form',
        'pim/security-context',
        'pim/initselect2',
        'pim/fetcher-registry',
        'pim/media-url-generator',
        'oro/messenger',
        'pim/form-modal',
        'pim/template/product/form/variant-navigation/navigation',
        'pim/template/product/form/variant-navigation/product-item',
        'pim/template/product/form/variant-navigation/product-model-item',
        'pim/template/product/form/variant-navigation/add-child-button'
    ],
    function (
        $,
        _,
        __,
        router,
        i18n,
        UserContext,
        BaseForm,
        SecurityContext,
        initSelect2,
        FetcherRegistry,
        MediaUrlGenerator,
        messenger,
        FormModal,
        template,
        templateProduct,
        templateProductModel,
        templateAddChild
    ) {
        return BaseForm.extend({
            template: _.template(template),
            templateProduct: _.template(templateProduct),
            templateProductModel: _.template(templateProductModel),
            templateAddChild: _.template(templateAddChild),
            dropdowns: {},
            queryTimer: null,
            events: {
                'click [data-action="navigateToLevel"]': 'navigateToLevel'
            },
 
            /**
             * {@inheritdoc}
             */
            configure: function () {
                this.listenTo(UserContext, 'change:catalogLocale change:catalogScope', this.render);
 
                return BaseForm.prototype.configure.apply(this, arguments);
            },
 
            /**
             * {@inheritdoc}
             */
            render: function () {
                const entity = this.getFormData();
                const catalogLocale = UserContext.get('catalogLocale');
 
                if ('product' === entity.meta.model_type && null === entity.parent) {
                    this.$el.html('');
 
                    return;
                }
 
                this.$el.html(
                    this.template({
                        commonLabel: __('pim_enrich.entity.product.module.variant_navigation.common'),
                        currentLocale: catalogLocale,
                        entity: entity,
                        navigation: entity.meta.variant_navigation
                    })
                );
 
                this.initializeSelectWidgets();
            },
 
            /**
             * Initialize the Select2 component and format elements.
             */
            initializeSelectWidgets: function () {
                const entity = this.getFormData();
                const $selects = this.$('.select-field');
 
                _.each($selects, (select, index) => {
                    const $select = $(select);
                    const options = {
                        dropdownCssClass: 'variant-navigation',
                        closeOnSelect: false,
 
                        /**
                         * Format result (product or product model variations) method of select2.
                         * This way we can display entities and their info beside them (completeness, image..).
                         */
                        formatResult: (item, $container) => {
                            const catalogLocale = UserContext.get('catalogLocale');
                            const filePath = (null !== item.image) ? item.image.filePath : null;
                            const entity = {
                                label: item.axes_values_labels[catalogLocale],
                                image: MediaUrlGenerator.getMediaShowUrl(filePath, 'thumbnail_small'),
                                completeness: this.parseCompleteness(item)
                            };
 
                            const html = ('product' === item.model_type)
                                ? this.templateProduct({entity: entity, getClass: this.getCompletenessBadgeClass})
                                : this.templateProductModel({entity: entity, getClass: this.getCompletenessBadgeClass})
                            ;
 
                            $container.append(html);
                        },
 
                        query: (options) => {
                            this.queryChildrenEntities(
                                options,
                                entity.meta.variant_navigation[index].selected.id
                            );
                        }
                    };
 
                    const dropDown = initSelect2.init($select, options);
 
                    dropDown
                        .on('select2-selecting', (event) => {
                            this.redirectToEntity(event.object);
                        })
                        .on('select2-open', () => {
                            this.addSelect2Footer(dropDown)
                        });
 
                    this.dropdowns[index] = dropDown;
                });
            },
 
            /**
             * Adds the footer containing the creation button to the select2 dropdown.
             *
             * @param {Element} dropDown
             */
            addSelect2Footer: function(dropDown) {
                $('#select2-drop .select2-drop-footer').remove();
 
                const targetLevel = dropDown[0].dataset.level;
                this.getEntityParentCode(targetLevel)
                    .then((parentCode) => {
                        this.isVariantProduct(parentCode)
                            .then((isVariantProduct) => {
                                Iif (!this.isCreationGranted(isVariantProduct)) {
                                    return;
                                }
 
                                const footer = this.templateAddChild({
                                    label: __('pim_enrich.entity.product_model.module.variant_axis.create')
                                });
 
                                $('#select2-drop')
                                    .append(footer)
                                    .find('.select2-drop-footer').on('click', '.add-child', () => {
                                        dropDown.select2('close');
                                        this.openModal(parentCode);
                                    });
                            });
                    })
            },
 
            /**
             * Tests the creation ACL depending on the entity type the user wants to create.
             *
             * @param {boolean} isVariantProduct
             *
             * @returns {boolean}
             */
            isCreationGranted: function(isVariantProduct) {
                return (isVariantProduct && SecurityContext.isGranted('pim_enrich_product_create'))
                    || (!isVariantProduct && SecurityContext.isGranted('pim_enrich_product_model_create'));
            },
 
            /**
             * Get the parent code for the new product model / variant product child.
             *
             * @param {Number} targetLevel
             *
             * @return {Promise}
             */
            getEntityParentCode: function (targetLevel) {
                const entity = this.getFormData();
                const entityLevel = entity.meta.level;
 
                if (targetLevel < entityLevel) {
                    return FetcherRegistry
                        .getFetcher('product-model-by-code')
                        .fetch(entity.parent)
                        .then((parent) => {
                            return parent.parent;
                        })
                    ;
                }
 
                if (targetLevel > entityLevel) {
                    return $.Deferred().resolve(entity.code).promise();
                }
 
                return $.Deferred().resolve(entity.parent).promise();
            },
 
            /**
             * Opens the modal containing the form to create a new family variant.
             *
             * @param {String} parentCode
             */
            openModal: function (parentCode) {
                const modalParameters = {
                    className: 'modal modal--fullPage add-product-model-child',
                    content: '',
                    cancelText: __('pim_common.cancel'),
                    okText: __('pim_common.confirm'),
                    okCloses: false
                };
 
                this.isVariantProduct(parentCode)
                    .then((isVariantProduct) => {
                        const initialModalState = {
                            parent: parentCode,
                            values: {}
                        };
 
                        if (isVariantProduct) {
                            initialModalState.family = this.getFormData().family;
                        } else {
                            initialModalState.family_variant = this.getFormData().family_variant;
                        }
 
                        const formModal = new FormModal(
                            'pim-product-model-add-child-form',
                            this.submitForm.bind(this, isVariantProduct),
                            modalParameters,
                            initialModalState
                        );
 
                        formModal.open();
                    });
            },
 
            /**
             * Action made when user submit the modal.
             *
             * @param {boolean} isVariantProduct
             * @param {Object} formModal
             */
            submitForm: function (isVariantProduct, formModal) {
                const message = isVariantProduct
                    ? __('pim_enrich.entity.product_model.flash.create.variant_product_added')
                    : __('pim_enrich.entity.product_model.flash.create.product_model_added');
 
                const route = isVariantProduct
                    ? 'pim_enrich_product_rest_create'
                    : 'pim_enrich_product_model_rest_create';
 
                return formModal
                    .saveProductModelChild(route)
                    .done((entity) => {
                        this.redirectToEntity(entity.meta);
                        messenger.notify('success', message);
                    });
            },
 
            /**
             * Returns whether the new entity will be a variant product or a product model
             * using the parent code.
             *
             * @param {string} parentCode
             *
             * @returns {Promise}
             */
            isVariantProduct: function(parentCode) {
                return FetcherRegistry
                    .getFetcher('product-model-by-code')
                    .fetch(parentCode)
                    .then((parent) => {
                        return FetcherRegistry
                            .getFetcher('family-variant')
                            .fetch(parent.family_variant)
                            .then((familyVariant) => {
                                const currentLevel = parent.meta.level + 1;
 
                                return currentLevel === familyVariant.variant_attribute_sets.length;
                            })
                    });
            },
 
            /**
             * Return a string of the completeness for the given entity to be displayed.
             *
             * @param {Object} entity
             *
             * @returns {string}
             */
            parseCompleteness: function (entity) {
                const catalogLocale = UserContext.get('catalogLocale');
                const catalogScope = UserContext.get('catalogScope');
 
                if ('product' === entity.model_type) {
                    const channelCompletenesses = _.findWhere(entity.completeness, {channel: catalogScope});
                    const localeCompleteness = channelCompletenesses.locales[catalogLocale].completeness;
 
                    return {
                        ratio: localeCompleteness.ratio
                    };
                } else {
                    const completenesses = entity.completeness.completenesses;
                    const totalProducts  = entity.completeness.total;
                    let completeProducts = 0;
 
                    Eif (_.has(completenesses, catalogScope) &&
                        _.has(completenesses[catalogScope], catalogLocale)
                    ) {
                        completeProducts = completenesses[catalogScope][catalogLocale];
                    }
 
                    return {
                        ratio: (completeProducts > 0) ? Math.floor(totalProducts / completeProducts * 100) : 0,
                        display: completeProducts + ' / ' + totalProducts
                    };
                }
            },
 
            /**
             * Get the CSS class for the completeness badge of the template, depending on the given ratio.
             *
             * @param {int} ratio
             *
             * @returns {string}
             */
            getCompletenessBadgeClass: function (ratio) {
                if (0 === ratio) {
                    return 'empty';
                }
 
                Iif (100 === ratio) {
                    return 'complete';
                }
 
                return 'incomplete';
            },
 
            /**
             * Return all entities that have a label (axes values) that match the given term.
             *
             * @param {string} term
             * @param {array} entities
             *
             * @returns {array}
             */
            searchOnResults: function (term, entities) {
                const catalogLocale = UserContext.get('catalogLocale');
                term = term.toLowerCase();
 
                return entities.filter((entity) => {
                    const label = entity.axes_values_labels[catalogLocale].toLowerCase();
 
                    return -1 !== label.search(term);
                });
            },
 
            /**
             * Fetch all children of the given parentId and calls the callback of Select2 to
             * display them in the dropdown.
             *
             * @param {Object} options
             * @param {int} parentId
             */
            queryChildrenEntities: function (options, parentId) {
                clearTimeout(this.queryTimer);
                this.queryTimer = setTimeout(() => {
                    FetcherRegistry
                        .getFetcher('product-model')
                        .fetchChildren(parentId)
                        .then((children) => {
                            const childrenResults = this.searchOnResults(options.term, children);
                            const sortedChildrenResults = childrenResults.sort((item1, item2) => {
                                for (let i = 0; i < item1.order.length; i++) {
                                    if (item1.order[i] > item2.order[i]) {
                                        return 1;
                                    } else if (item1.order[i] < item2.order[i]) {
                                        return -1;
                                    }
                                }
 
                                return 0;
                            });
 
                            options.callback({
                                results: sortedChildrenResults
                            });
                        });
                }, 400);
            },
 
            /**
             * Redirect to the entity of the given level
             */
            navigateToLevel: function (event) {
                const entity = this.getFormData();
                const level = $(event.target).data('level');
 
                this.redirectToEntity(entity.meta.variant_navigation[level].selected);
            },
 
            /**
             * Redirect the user to the given entity edit page
             *
             * @param {Object} entity
             */
            redirectToEntity: function (entity) {
                Iif (!entity) {
                    return;
                }
 
                const params = {id: entity.id};
                const route = ('product_model' === entity.model_type)
                    ? 'pim_enrich_product_model_edit'
                    : 'pim_enrich_product_edit'
                ;
 
                router.redirectToRoute(route, params);
            }
        });
    }
);