All files / web/bundles/pimui/js/product-model/form/add-child fields-container.js

98.53% Statements 67/68
92.86% Branches 13/14
100% Functions 23/23
98.46% Lines 64/65

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                    15x                                                 15x                 15x 15x 15x   15x             15x       6x 6x 6x       15x             41x   41x       41x       41x       41x 41x   41x   41x 89x       103x   41x 22x       22x 22x         19x 19x       41x 41x 130x               41x 130x   41x 41x                     41x                             41x 41x 50x     41x                                     111x   111x       111x     111x 111x 111x 111x           111x 89x       111x     111x 10x     10x                       10x       101x 10x 10x     101x 59x         101x                   19x     19x 19x   19x     19x            
'use strict';
 
/**
 * Form container for the axis fields of the product model child creation modal.
 *
 * @author    Damien Carcel <damien.carcel@akeneo.com>
 * @author    Yohan Blain <yohan.blain@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(
    [
        'pim/form',
        'jquery',
        'underscore',
        'oro/translator',
        'pim/i18n',
        'routing',
        'pim/user-context',
        'pim/fetcher-registry',
        'pim/form-builder',
        'pim/template/product-model-edit-form/add-child-form-fields-container'
    ],
    (
        BaseForm,
        $,
        _,
        __,
        i18n,
        Routing,
        UserContext,
        FetcherRegistry,
        FormBuilder,
        template
    ) => {
        return BaseForm.extend({
            template: _.template(template),
            globalErrors: [],
            errors: [],
 
            /**
             * {@inheritdoc}
             */
            initialize(meta) {
                this.config = _.defaults(meta.config, {fieldModules: {}, codeFieldModule: null});
                this.globalErrors = [];
                this.errors = [];
 
                BaseForm.prototype.initialize.apply(this, arguments);
            },
 
            /**
             * {@inheritdoc}
             */
            configure() {
                this.listenTo(
                    this.getRoot(),
                    'pim_enrich:form:entity:validation_error',
                    (errors) => {
                        this.errors = errors;
                        this.globalErrors = errors.filter((error) => undefined === error.attribute);
                        this.render();
                    }
                );
 
                return BaseForm.prototype.configure.apply(this, arguments);
            },
 
            /**
             * {@inheritdoc}
             */
            render() {
                const parentCode = this.getFormData().parent;
 
                this.$el.html(this.template({
                    errors: this.globalErrors
                }));
 
                FetcherRegistry
                    .getFetcher('product-model-by-code')
                    .fetch(parentCode)
                    .then((parent) => {
                        FetcherRegistry
                            .getFetcher('family-variant')
                            .fetch(parent.family_variant)
                            .then((familyVariant) => {
                                const currentLevel = parent.meta.level + 1;
                                const isVariantProduct = currentLevel === familyVariant.variant_attribute_sets.length;
 
                                this.getAxesAttributes(familyVariant, currentLevel)
                                    .then((axesAttributes) => {
                                        return $.when.apply($, axesAttributes.map(
                                            (attribute) => this.createAttributeField(attribute, true)
                                        ));
                                    })
                                    .then((...fields) => {
                                        fields.sort((fieldA, fieldB) => fieldA.getLabel() > fieldB.getLabel() ? 1 : -1);
 
                                        if (isVariantProduct) {
                                            return FetcherRegistry
                                                .getFetcher('attribute')
                                                .getIdentifierAttribute()
                                                .then((identifier) => {
                                                    return this.createAttributeField(identifier, false).then(
                                                        (identifierField) => fields.concat(identifierField)
                                                    );
                                                });
                                        }
 
                                        return this.createProductModelCodeField().then(
                                            (codeField) => fields.concat(codeField)
                                        );
                                    })
                                    .then((fields) => {
                                        let position = 100;
                                        fields.forEach((field) => {
                                            this.addExtension(
                                                field.code,
                                                field,
                                                'content',
                                                position++
                                            );
                                        });
 
                                        $.when.apply(this, fields.map((field) => {
                                            return field.configure();
                                        })).then(() => {
                                            this.renderExtensions();
                                            this.showErrors();
                                        });
                                    });
                            });
                    });
            },
 
            /**
             * Render validation errors for fields after field extensions are loaded
             */
            showErrors() {
                this.getRoot().trigger('pim_enrich:form:entity:bad_request',
                    { sentData: this.getFormData(), response: this.errors }
                );
            },
 
            /**
             * Looks for the attributes set corresponding to the specified level of the family variant
             * and fetches its axes attributes.
             *
             * @param {Object} familyVariant
             * @param {Number} level
             *
             * @returns {Promise}
             */
            getAxesAttributes(familyVariant, level) {
                const variantAttributeSets = familyVariant.variant_attribute_sets;
                const variantAttributeSetForLevel = variantAttributeSets.find(
                    (variantAttributeSet) => variantAttributeSet.level === level
                );
 
                return FetcherRegistry
                    .getFetcher('attribute')
                    .fetchByIdentifiers(variantAttributeSetForLevel.axes);
            },
 
            /**
             * Instantiate a field view corresponding to an attribute.
             * The "field_type" of the attribute must be mapped to a view key in the config of this module.
             * The meta under this key is then modified on-the-fly before instantiation using attribute
             * code to make the field unique.
             *
             * This logic could be extracted to a factory later.
             *
             * @param {Object}  attribute
             * @param {boolean} isAxis
             *
             * @returns {Promise}
             */
            createAttributeField(attribute, isAxis) {
                const fieldModuleName = this.config.fieldModules[attribute.field_type];
 
                Iif (undefined === fieldModuleName) {
                    throw new Error('No module set for field type "' + attribute.field_type + '"');
                }
 
                return FormBuilder
                    .getFormMeta(fieldModuleName)
                    .then((formMeta) => {
                        const newFormMeta = $.extend(true, {}, formMeta);
                        newFormMeta.code += `-${attribute.code}`;
                        newFormMeta.config.fieldName = `values.${attribute.code}`;
                        newFormMeta.config.label = i18n.getLabel(
                            attribute.labels,
                            UserContext.get('uiLocale'),
                            attribute.code
                        );
 
                        if (isAxis) {
                            newFormMeta.config.requiredLabel =
                                'pim_enrich.entity.product_model.module.variant_axis.required_label';
                        }
 
                        return FormBuilder.buildForm(newFormMeta);
                    })
                    .then((field) => {
                        if ('pim_reference_data_simpleselect' === attribute.type) {
                            return FetcherRegistry.getFetcher('reference-data-configuration')
                                .fetchAll()
                                .then((config) => {
                                    field.setChoiceUrl(
                                        Routing.generate(
                                            'pim_ui_ajaxentity_list',
                                            {
                                                'class': config[attribute.reference_data_name].class,
                                                'dataLocale': UserContext.locale,
                                                'collectionId': attribute.id,
                                                'options': {'type': 'code'}
                                            }
                                        )
                                    );
 
                                    return field;
                                });
                        }
 
                        if ('pim_catalog_metric' === attribute.type) {
                            field.setMetricFamily(attribute.metric_family);
                            field.setDefaultMetricUnit(attribute.default_metric_unit);
                        }
 
                        if ('pim_catalog_simpleselect' === attribute.type) {
                            field.setChoiceUrl(
                                Routing.generate('pim_enrich_attributeoption_get', {identifier: attribute.code})
                            );
                        }
 
                        return field;
                    });
            },
 
            /**
             * Instantiates a field view corresponding to the product model code.
             *
             * @returns {Promise}
             */
            createProductModelCodeField() {
                return FormBuilder
                    .getFormMeta(this.config.codeFieldModule)
                    .then((formMeta) => {
                        const newFormMeta = $.extend(true, {}, formMeta);
                        newFormMeta.config.fieldName = 'code';
 
                        return FormBuilder.buildForm(newFormMeta);
                    })
                    .then((field) => {
                        return field.configure().then(() => field);
                    });
            }
        });
    }
);