All files / web/bundles/pimui/js/form/common attributes.js

93.21% Statements 151/162
84% Branches 42/50
93.48% Functions 43/46
93.13% Lines 149/160

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 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556                  354x                                                                                                         1039x 5940x   5940x 2053x             5940x 5940x 1435x     5940x                       354x 2053x 2053x 2053x           2053x 5534x   5940x 5940x   5940x     2053x   2053x     354x                             459x   459x             458x         458x 458x 458x 458x 458x 458x 458x 458x 34x 34x 34x     458x 458x 25x 22x       458x   458x 458x 458x 458x 458x 458x   458x             1649x 592x     1057x 1057x   1057x 1057x   1054x     1054x   1054x 1054x   1044x 1044x     1039x 1039x 1039x   1039x     1539x   1039x   1039x 2053x                     1039x 1039x 78x                 961x   1039x 1039x   1039x       1057x         1057x                         6036x 6036x           6035x 6035x   6035x                   6035x 6035x   6035x                       4x     4x 4x 4x   4x       4x 4x         4x   4x 4x   4x   4x   4x                                                                     479x 439x     439x                       99x             878x                     470x 427x     427x                       27x             854x                                 93x   93x 93x 31x 31x   93x 5x 5x     93x 32x     93x   93x 93x   93x                   735x 735x                         1054x 147x 147x 147x 917x 579x     147x     1054x 298x     756x                               1054x     1047x 11883x       11883x       11883x     1047x 6036x     1045x               4x             2076x 3091x 3091x     1038x 1038x   1038x 1038x          
'use strict';
/**
 * Attribute 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',
        'oro/mediator',
        'routing',
        'pim/form',
        'pim/field-manager',
        'pim/fetcher-registry',
        'pim/attribute-manager',
        'pim/attribute-group-manager',
        'pim/user-context',
        'pim/security-context',
        'pim/template/form/tab/attributes',
        'pim/template/form/tab/attribute/attribute-group',
        'pim/template/common/no-data',
        'pim/provider/to-fill-field-provider',
        'pim/dialog',
        'oro/messenger',
        'pim/i18n'
    ],
    function (
        $,
        _,
        __,
        Backbone,
        mediator,
        Routing,
        BaseForm,
        FieldManager,
        FetcherRegistry,
        AttributeManager,
        AttributeGroupManager,
        UserContext,
        SecurityContext,
        formTemplate,
        attributeGroupTemplate,
        noDataTemplate,
        toFillFieldProvider,
        Dialog,
        messenger,
        i18n
    ) {
        /**
         * Group field views by sections (attribute groups)
         *
         * @param {Array} attributeGroups
         * @param {Array} fieldsToFill
         *
         * @return {Object}
         */
        const groupFieldsBySection = (attributeGroups, fieldsToFill) => (fieldCollection, field) => {
            const newFieldCollection = Object.assign({}, fieldCollection);
 
            if (undefined === newFieldCollection[field.attribute.group]) {
                newFieldCollection[field.attribute.group] = {
                    attributeGroup: attributeGroups[field.attribute.group],
                    fields: [],
                    toFill: 0
                };
            }
 
            newFieldCollection[field.attribute.group].fields.push(field);
            if (-1 !== fieldsToFill.indexOf(field.attribute.code)) {
                newFieldCollection[field.attribute.group].toFill++;
            }
 
            return newFieldCollection;
        };
 
        /**
         * Generate a section view for the given fields
         *
         * @param {Object}   fieldCollection
         * @param {function} template
         * @param {String}   label
         *
         * @return {view}
         */
        const createSectionView = (fieldCollection, template, label) => {
            const view = document.createElement('div');
            view.className = 'AknSubsection';
            view.innerHTML = template({
                label,
                fieldCollection,
                __
            });
 
            const container = fieldCollection.fields.sort(
                (firstField, secondField) => firstField.attribute.sort_order - secondField.attribute.sort_order
            ).reduce((container, field) => {
                _.defer(field.render.bind(field));
                container.appendChild(field.el);
 
                return container;
            }, document.createElement('div'));
 
            view.appendChild(container);
 
            return view;
        };
 
        return BaseForm.extend({
            template: _.template(formTemplate),
            attributeGroupTemplate: _.template(attributeGroupTemplate),
            noDataTemplate: _.template(noDataTemplate),
            className: 'tabbable object-attributes',
            events: {
                'click .remove-attribute': 'removeAttribute',
                'click .required-attribute-indicator': 'filterRequiredAttributes'
            },
            rendering: false,
 
            /**
             * {@inheritdoc}
             */
            initialize: function (meta) {
                this.config = meta.config;
 
                BaseForm.prototype.initialize.apply(this, arguments);
            },
 
            /**
             * {@inheritdoc}
             */
            configure: function () {
                this.trigger('tab:register', {
                    code: this.code,
                    label: __(this.config.tabTitle)
                });
 
                UserContext.off('change:catalogLocale change:catalogScope', this.render);
                this.listenTo(UserContext, 'change:catalogLocale change:catalogScope', this.render);
                this.listenTo(this.getRoot(), 'pim_enrich:form:entity:validation_error', this.render);
                this.listenTo(this.getRoot(), 'pim_enrich:form:entity:post_fetch', this.render);
                this.listenTo(this.getRoot(), 'pim_enrich:form:add-attribute:after', this.render);
                this.listenTo(this.getRoot(), 'pim_enrich:form:show_attribute', this.showAttribute);
                this.listenTo(this.getRoot(), 'pim_enrich:form:scope_switcher:pre_render', this.initScope.bind(this));
                this.listenTo(this.getRoot(), 'pim_enrich:form:scope_switcher:change', (scopeEvent) => {
                    Eif ('base_product' === scopeEvent.context) {
                        this.setScope(scopeEvent.scopeCode, {silent: true});
                        this.setScope(scopeEvent.scopeCode);
                    }
                });
                this.listenTo(this.getRoot(), 'pim_enrich:form:locale_switcher:pre_render', this.initLocale.bind(this));
                this.listenTo(this.getRoot(), 'pim_enrich:form:locale_switcher:change', (localeEvent) => {
                    if ('base_product' === localeEvent.context) {
                        this.setLocale(localeEvent.localeCode, {silent: true});
                    }
                });
 
                FieldManager.clearFields();
 
                this.onExtensions('comparison:change', this.comparisonChange.bind(this));
                this.onExtensions('copy:copy-fields:after', this.render.bind(this));
                this.onExtensions('copy:select:after', this.render.bind(this));
                this.onExtensions('copy:context:change', this.render.bind(this));
                this.onExtensions('group:change', this.render.bind(this));
                this.onExtensions('attribute_filter:change', this.render.bind(this));
 
                return BaseForm.prototype.configure.apply(this, arguments);
            },
 
            /**
             * {@inheritdoc}
             */
            render: function () {
                if (!this.configured || this.rendering) {
                    return this;
                }
 
                this.rendering = true;
                this.$el.html(this.template({}));
 
                var data = this.getFormData();
                AttributeGroupManager.getAttributeGroupsForObject(data)
                    .then((attributeGroups) => {
                        this.getExtension('attribute-group-selector').setElements(
                            _.indexBy(attributeGroups, 'code')
                        );
                        FieldManager.clearVisibleFields();
                    })
                    .then(() => this.filterValues(data.values))
                    .then((values) => this.createFields(data, values))
                    .then((fields) => {
                        this.rendering = false;
                        $.when(
                            AttributeGroupManager.getAttributeGroupsForObject(data)
                        ).then((attributeGroups) => {
                            const scope = UserContext.get('catalogScope');
                            const locale = UserContext.get('catalogLocale');
                            const fieldsToFill = toFillFieldProvider.getMissingRequiredFields(data, scope, locale);
 
                            const sections = _.values(
                                fields.reduce(groupFieldsBySection(attributeGroups, fieldsToFill), {})
                            ).sort((firstSection, secondSection) =>
                                firstSection.attributeGroup.sort_order - secondSection.attributeGroup.sort_order
                            );
                            const fieldsView = document.createElement('div');
 
                            for (const section of sections) {
                                fieldsView.appendChild(createSectionView(
                                    section,
                                    this.attributeGroupTemplate,
                                    i18n.getLabel(
                                        section.attributeGroup.labels,
                                        UserContext.get('catalogLocale'),
                                        section.attributeGroup.code
                                    )
                                ));
                            }
 
                            const objectValuesDom = this.$('.object-values').empty();
                            if (_.isEmpty(fields)) {
                                objectValuesDom.append(this.noDataTemplate({
                                    hint: __('pim_datagrid.no_results', {
                                        entityHint: __('pim_enrich.entity.attribute.label')
                                    }),
                                    subHint: 'pim_datagrid.no_results_subtitle',
                                    imageClass: '',
                                    __
                                }));
                            } else {
                                objectValuesDom.append(fieldsView);
                            }
                            this.renderExtensions();
                            this.delegateEvents();
 
                            _.defer(this.sticky.bind(this));
                        });
                    });
 
                Iif (null !== sessionStorage.getItem('filter_missing_required_attributes')) {
                    sessionStorage.removeItem('filter_missing_required_attributes');
                    this.filterRequiredAttributes();
                }
 
                return this;
            },
 
            /**
             * Render a single field
             *
             * @param {Object} object
             * @param {String} attributeCode
             * @param {Array} values
             *
             * @return {Promise}
             */
            createAttributeField: function (object, attributeCode, values) {
                return FieldManager.getField(attributeCode).then(function (field) {
                    return $.when(
                        (new $.Deferred().resolve(field)),
                        FetcherRegistry.getFetcher('channel').fetchAll(),
                        AttributeManager.isOptional(field.attribute, object)
                    );
                }).then(function (field, channels, isOptional) {
                    const scope = _.findWhere(channels, { code: UserContext.get('catalogScope') });
                    const locale = UserContext.get('catalogLocale');
 
                    field.setContext({
                        entity: this.getFormData(),
                        locale,
                        scope: scope.code,
                        scopeLabel: i18n.getLabel(scope.labels, locale, scope.code),
                        uiLocale: UserContext.get('catalogLocale'),
                        optional: isOptional,
                        removable: SecurityContext.isGranted(this.config.removeAttributeACL)
                    });
 
                    field.setValues(values);
                    FieldManager.addVisibleField(field.attribute.code);
 
                    return field;
                }.bind(this));
            },
 
            /**
             * Remove an attribute from the collection
             *
             * @param {Event} event
             *
             * // TODO: Move this to product/form/mass-edit/attributes when the variant groups will be dropped.
             */
            removeAttribute: function (event) {
                Iif (!SecurityContext.isGranted(this.config.removeAttributeACL)) {
                    return;
                }
                var attributeCode = event.currentTarget.dataset.attribute;
                var formData = this.getFormData();
                var fields = FieldManager.getFields();
 
                Dialog.confirm(
                    __('pim_enrich.entity.attribute.module.delete.confirm_from_product'),
                    __('pim_common.confirm_deletion'),
                    function () {
                        FetcherRegistry.getFetcher('attribute').fetch(attributeCode).then(function (attribute) {
                            $.ajax({
                                type: 'DELETE',
                                url: this.generateRemoveAttributeUrl(attribute),
                                contentType: 'application/json'
                            }).then(function () {
                                this.triggerExtensions('add-attribute:update:available-attributes');
 
                                delete formData.values[attributeCode];
                                delete fields[attributeCode];
 
                                this.setData(formData);
 
                                this.getRoot().trigger('pim_enrich:form:remove-attribute:after');
 
                                this.render();
                            }.bind(this)).fail(function () {
                                messenger.notify(
                                    'error',
                                    __(this.config.deletionFailed)
                                );
                            });
                        }.bind(this));
                    }.bind(this)
                );
            },
 
            /**
             * Generate the remove attribute url
             *
             * @return {String}
             */
            generateRemoveAttributeUrl: function (attribute) {
                return Routing.generate(
                    this.config.removeAttributeRoute,
                    {
                        code: this.getFormData().code,
                        attributeId: attribute.meta.id
                    }
                );
            },
 
            /**
             * Initialize  the scope if there is none, or modify it by reference if there is already one
             *
             * @param {Object} scopeEvent
             * @param {String} scopeEvent.context
             * @param {String} scopeEvent.scopeCode
             */
            initScope: function (scopeEvent) {
                if ('base_product' === scopeEvent.context) {
                    Iif (undefined === this.getScope()) {
                        this.setScope(scopeEvent.scopeCode, {silent: true});
                    } else {
                        scopeEvent.scopeCode = this.getScope();
                    }
                }
            },
 
            /**
             * Set the current scope
             *
             * @param {String} scope
             * @param {Object} options
             */
            setScope: function (scope, options) {
                UserContext.set('catalogScope', scope, options);
            },
 
            /**
             * Get the current scope
             */
            getScope: function () {
                return UserContext.get('catalogScope');
            },
 
            /**
             * Initialize  the locale if there is none, or modify it by reference if there is already one
             *
             * @param {Object} eventLocale
             * @param {String} eventLocale.context
             * @param {String} eventLocale.localeCode
             */
            initLocale: function (eventLocale) {
                if ('base_product' === eventLocale.context) {
                    Iif (undefined === this.getLocale()) {
                        this.setLocale(eventLocale.localeCode, {silent: true});
                    } else {
                        eventLocale.localeCode = this.getLocale();
                    }
                }
            },
 
            /**
             * Set the current locale
             *
             * @param {String} locale
             * @param {Object} options
             */
            setLocale: function (locale, options) {
                UserContext.set('catalogLocale', locale, options);
            },
 
            /**
             * Get the current locale
             */
            getLocale: function () {
                return UserContext.get('catalogLocale');
            },
 
            /**
             * Post save actions
             */
            postSave: function () {
                FieldManager.clearFields();
                this.render();
            },
 
            /**
             * Switch to the given attribute
             *
             * @param {Event} event
             */
            showAttribute: function (event) {
                this.getRoot().trigger('pim_enrich:form:form-tabs:change', this.code);
 
                var needRendering = false;
                if (event.scope) {
                    this.setScope(event.scope, {silent: true});
                    needRendering = true;
                }
                if (event.locale) {
                    this.setLocale(event.locale, {silent: true});
                    needRendering = true;
                }
 
                if (needRendering) {
                    this.render();
                }
 
                var displayedAttributes = FieldManager.getFields();
 
                Eif (_.has(displayedAttributes, event.attribute)) {
                    const field = displayedAttributes[event.attribute];
                    // TODO: the manager shouldn't be stateful, access the field by another way
                    _.defer(field.setFocus.bind(field));
                }
            },
 
            /**
             * Toggle the comparison mode
             *
             * @param {Boolean} open
             */
            comparisonChange: function (open) {
                this.$el[open ? 'addClass' : 'removeClass']('comparison-mode');
                this.$el.find('.AknAttributeActions')[open ? 'addClass' : 'removeClass'](
                    'AknAttributeActions--comparisonMode'
                );
            },
 
            /**
             * Filter values
             *
             * @param {Object} values
             *
             * @return {Promise}
             */
            filterValues: function (values) {
                if (!this.getExtension('attribute-group-selector').isAll()) {
                    const filteredValues = {};
                    const attributeGroup = this.getExtension('attribute-group-selector').getCurrentElement();
                    attributeGroup.attributes.forEach((attributeCode) => {
                        if (undefined !== values[attributeCode]) {
                            filteredValues[attributeCode] = values[attributeCode];
                        }
                    });
                    values = filteredValues;
                }
 
                if (undefined === this.getExtension('attribute-filter')) {
                    return $.Deferred().resolve(values);
                }
 
                return this.getExtension('attribute-filter').filterValues(values);
            },
 
            /**
             * Render all fields and return a collection of promises
             *
             * This method is pretty optimization oriented: We fetch the attributes as a collection
             * to avoid individual fetching afterward. We also don't use fat arrow functions because
             * we cannot get the 'arguments' object out of it
             *
             * @param {Object} data
             * @param {Object} values
             *
             * @return {Promise}
             */
            createFields: function (data, values) {
                return FetcherRegistry.getFetcher('attribute')
                    .fetchByIdentifiers(Object.keys(values))
                    .then((attributes) => {
                        attributes.sort((a, b) => {
                            Iif (a.sortOrder < b.sortOrder) {
                                return -1;
                            }
 
                            Iif (a.sortOrder > b.sortOder) {
                                return 1;
                            }
 
                            return (a.meta.id < b.meta.id ? -1 : 1);
                        });
 
                        return $.when.apply($, attributes.map((attribute) => {
                            return this.createAttributeField(data, attribute.code, values[attribute.code]);
                        }));
                    }).then(function () {
                        return _.values(arguments);
                    });
            },
 
            /**
             * Filter the required attributes and attribute group
             */
            filterRequiredAttributes: function () {
                this.getRoot().trigger('pim_enrich:form:switch_values_filter', 'missing_required');
            },
 
            /**
             * Make the header and section header sticky
             */
            sticky: function () {
                const makeItSticky = (position) => (element) => {
                    element.style.position = 'sticky';
                    element.style.top = `${position}px`;
                };
 
                const header = this.getZone('header');
                makeItSticky(this.getRoot().headerSize())(header);
 
                const sectionTitles = this.el.querySelectorAll('.AknSubsection-title');
                _.each(sectionTitles, makeItSticky(header.offsetHeight + this.getRoot().headerSize()));
            }
        });
    }
);