All files / web/bundles/pimui/js/mass-edit/form/product associate.js

90.54% Statements 67/74
75% Branches 12/16
96.15% Functions 25/26
90.54% Lines 67/74

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                89x                                                                         89x                               6x             9x 6x 6x       6x   3x     3x     6x     6x               6x   6x     3x 3x 3x               3x 3x                     3x     3x                 6x 6x       6x             6x                 9x 9x         9x                 9x   9x                                       3x             27x                 6x             3x 3x 3x 3x 6x 6x 2x   4x 4x       3x   3x 3x         3x   3x                   3x   3x 3x       3x                                 3x 3x 3x 3x 3x   3x   3x     3x       3x                 3x   3x               3x     3x                 6x 6x 6x 6x          
'use strict';
/**
 * Mass associate
 *
 * @author    Julien Sanchez <julien@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',
        'backbone',
        'oro/translator',
        'routing',
        'pim/mass-edit-form/product/operation',
        'pim/user-context',
        'pim/form-builder',
        'pim/fetcher-registry',
        'pim/i18n',
        'pim/media-url-generator',
        'oro/loading-mask',
        'oro/messenger',
        'pim/template/mass-edit/product/associate/pick',
        'pim/template/mass-edit/product/associate/confirm',
        'pim/template/common/modal-centered'
    ],
    function (
        $,
        _,
        Backbone,
        __,
        Routing,
        BaseOperation,
        UserContext,
        FormBuilder,
        FetcherRegistry,
        i18n,
        MediaUrlGenerator,
        LoadingMask,
        messenger,
        pickTemplate,
        confirmTemplate,
        modalTemplate
    ) {
        return BaseOperation.extend({
            className: 'AknGridToolbar',
            pickTemplate: _.template(pickTemplate),
            confirmTemplate: _.template(confirmTemplate),
            modalTemplate: _.template(modalTemplate),
            errors: null,
            formPromise: null,
            events: {
                'click .associations-list li': 'changeAssociationType',
                'click .add-associations': 'addAssociations'
            },
 
            /**
             * {@inheritdoc}
             */
            reset: function () {
                this.setValue([]);
            },
 
            /**
             * {@inheritdoc}
             */
            render: function () {
                if (!this.readOnly) {
                    this.loadAssociationTypes().then((associationTypes) => {
                        const currentAssociationTypeCode = associationTypes.length ?
                            _.first(associationTypes).code :
                            null;
 
                        if (null === this.getCurrentAssociationTypeCode() ||
                            undefined === associationTypes.find(
                                associationType => associationType.code === this.getCurrentAssociationTypeCode()
                            )
                        ) {
                            this.setCurrentAssociationType(currentAssociationTypeCode);
                        }
 
                        this.$el.html(this.pickTemplate({
                            associationTypes,
                            associationType: associationTypes.find(
                                associationType => associationType.code === this.getCurrentAssociationTypeCode()
                            ),
                            locale: UserContext.get('uiLocale'),
                            i18n,
                            label: __('pim_enrich.entity.product.module.associations.association_type_selector'),
                            addAssociationsLabel: __('pim_enrich.entity.product.module.associations.add_associations')
                        }));
 
                        this.resizeContent(associationTypes.length);
 
                        this.delegateEvents();
                    });
                } else {
                    var loadingMask = new LoadingMask();
                    this.$el.empty().append(loadingMask.render().$el.show());
                    $.when(
                        FetcherRegistry.getFetcher('product-model').fetchByIdentifiers(
                            this.getValue()[this.getCurrentAssociationTypeCode()].product_models
                        ),
                        FetcherRegistry.getFetcher('product').fetchByIdentifiers(
                            this.getValue()[this.getCurrentAssociationTypeCode()].products
                        )
                    ).then((productModels, products) => {
                        const items = products.concat(productModels);
                        this.$el.html(this.confirmTemplate({
                            items: items,
                            title: __('pim_enrich.entity.product.module.basket.title'),
                            emptyLabel: __('pim_enrich.entity.product.module.basket.empty_basket'),
                            confirmLabel: __(
                                'pim_enrich.mass_edit.product.operation.associate_to_product_and_product_model.confirm'
                            ),
                            imagePathMethod: this.imagePathMethod.bind(this),
                            labelMethod: this.labelMethod.bind(this),
                            readOnly: this.readOnly
                        }));
                        this.delegateEvents();
                    })
                    .always(() => {
                        loadingMask.remove();
                    });
                }
            },
 
            /**
             * {@inheritdoc}
             */
            imagePathMethod: function (item) {
                let filePath = null;
                Iif (item.meta.image !== null) {
                    filePath = item.meta.image.filePath;
                }
 
                return MediaUrlGenerator.getMediaShowUrl(filePath, 'thumbnail_small');
            },
 
            /**
             * {@inheritdoc}
             */
            labelMethod: function (item) {
                return item.meta.label[UserContext.get('catalogLocale')];
            },
 
            /**
             * Update the model after dom event triggered
             *
             * @param {string} group
             */
            setValue: function (values) {
                const data = this.getFormData();
                data.actions = [{
                    field: 'associations',
                    value: values
                }];
 
                this.setData(data);
            },
 
            /**
             * Get current value from mass edit model
             *
             * @return {string}
             */
            getValue: function () {
                var action = _.first(this.getFormData().actions);
 
                return action ? action.value : null;
            },
 
            /**
             * Switch the current association type
             *
             * @param {Event} event
             */
            changeAssociationType: function (event) {
                event.preventDefault();
                const associationType = event.currentTarget.dataset.associationType;
                this.setCurrentAssociationType(associationType);
 
                this.render();
            },
 
            /**
             * @param {string} associationType
             */
            setCurrentAssociationType: function (associationType) {
                sessionStorage.setItem('current_association_type', associationType);
            },
 
            /**
             * @returns {string}
             */
            getCurrentAssociationTypeCode: function () {
                return sessionStorage.getItem('current_association_type');
            },
 
            /**
             * Fetch all the association types
             *
             * @returns {Promise}
             */
            loadAssociationTypes: function () {
                return FetcherRegistry.getFetcher('association-type').fetchAll();
            },
 
            /**
             * Opens the panel to select new products to associate
             */
            addAssociations: function () {
                this.manageProducts().then((productAndProductModelIdentifiers) => {
                    let productIds = [];
                    let productModelIds = [];
                    productAndProductModelIdentifiers.forEach((item) => {
                        const matchProductModel = item.match(/^product_model_(.*)$/);
                        if (matchProductModel) {
                            productModelIds.push(matchProductModel[1]);
                        } else {
                            const matchProduct = item.match(/^product_(.*)$/);
                            productIds.push(matchProduct[1]);
                        }
                    });
 
                    const assocType = this.getCurrentAssociationTypeCode();
 
                    const associations = {};
                    associations[assocType] = {
                        'products': productIds,
                        'product_models': productModelIds,
                        'groups': []
                    };
                    this.setValue(associations);
 
                    this.getRoot().trigger('mass-edit:navigate:action', 'confirm');
                });
            },
 
            /**
             * Launch the association product picker
             *
             * @return {Promise}
             */
            manageProducts: function () {
                const deferred = $.Deferred();
 
                FormBuilder.build('pim-associations-product-picker-form').then((form) => {
                    FetcherRegistry
                        .getFetcher('association-type')
                        .fetch(this.getCurrentAssociationTypeCode())
                        .then((associationType) => {
                            let modal = new Backbone.BootstrapModal({
                                modalOptions: {
                                    backdrop: 'static',
                                    keyboard: false
                                },
                                innerDescription:
                                __('pim_enrich.entity.product.module.associations.manage_description'),
                                okCloses: false,
                                title: __('pim_enrich.entity.product.module.associations.manage', {
                                    associationType: associationType.labels[UserContext.get('catalogLocale')]
                                }),
                                content: '',
                                cancelText: ' ',
                                okText: __('pim_common.confirm'),
                                template: this.modalTemplate,
                                innerClassName: 'AknFullPage--full',
                            });
                            modal.open();
                            modal.on('cancel', deferred.reject);
                            modal.on('ok', () => {
                                const products = form.getItems().sort((a, b) => {
                                    return a.code < b.code;
                                });
                                modal.close();
 
                                deferred.resolve(products);
                            });
 
                            form.setElement(modal.$('.modal-body')).render();
                        });
                });
 
                return deferred.promise();
            },
 
            /**
             * Validate the model before confirmation
             *
             * @return {Promise}
             */
            validate: function () {
                const deferred = $.Deferred();
 
                Iif (_.isEmpty(this.getValue())) {
                    messenger.notify(
                        'error',
                        __('pim_enrich.mass_edit.product.operation.associate_to_product_and_product_model.validate')
                    );
 
                    deferred.resolve(false);
                } else {
                    deferred.resolve(true);
                }
 
                return deferred;
            },
 
            /**
             * The dropdown and the mass edit layout have incompatible CSS displays.
             * We need to trick the height of the content box to avoid a too small zone to click.
             * The height is estimated from the count of association types.
             */
            resizeContent: function (associationTypesLength) {
                const contentDom = $('.AknFullPage-content.AknFullPage-content--withIllustration');
                const headerHeight = $('.AknFullPage-titleContainer').outerHeight();
                const newHeight = (headerHeight + associationTypesLength * 26 + 150);
                contentDom.css('min-height', Math.min(newHeight, $('body').outerHeight()) + 'px');
            }
        });
    }
);