All files / web/bundles/pimdatagrid/js/datagrid/action abstract-action.js

77.01% Statements 67/87
60.34% Branches 35/58
83.33% Functions 20/24
77.01% Lines 67/87

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  781x                               781x                                                                                                       53740x   53740x     53740x   53740x 309638x     53740x   53740x       53740x       53740x                   53718x 53718x 7682x   53718x 4157x   53718x   53718x             202x     202x 202x 202x 202x               136x 136x 136x   136x             136x       136x 16x 120x 2x 118x 118x             136x     136x         16x       16x   16x 16x                                 118x     118x 118x       2x     2x 2x                                 2x       2x 2x   2x 2x 2x 2x                     134x     134x                                     134x                 2x                                             64x 64x   64x 27x     37x             43x 43x                         27x 3x     24x        
 /* global define */
define(['jquery', 'underscore', 'backbone', 'routing', 'pim/router', 'oro/translator', 'oro/mediator',
    'oro/messenger', 'oro/error', 'pim/dialog', 'oro/datagrid/action-launcher', 'require-context'],
function($, _, Backbone, routing, router, __, mediator, messenger, error, Dialog, ActionLauncher, requireContext) {
    'use strict';
 
    /**
     * Abstract action class. Subclasses should override execute method which is invoked when action is running.
     *
     * Triggers events:
     *  - "preExecute" before action is executed
     *  - "postExecute" after action is executed
     *
     * @export  oro/datagrid/abstract-action
     * @class   oro.datagrid.AbstractAction
     * @extends Backbone.View
     */
    return Backbone.View.extend({
        /** @property {Function} */
        launcherPrototype: ActionLauncher,
 
        /** @property {Object} */
        launcherOptions: undefined,
 
        /** @property {String} */
        name: null,
 
        /** @property {oro.datagrid.Grid} */
        datagrid: null,
 
        /** @property {string} */
        route: null,
 
        /** @property {Object} */
        route_parameters: null,
 
        /** @property {Boolean} */
        confirmation: false,
 
        /** @property {String} */
        frontend_type: null,
 
        /** @property {Object} */
        frontend_options: null,
 
        /** @property {string} */
        identifierFieldName: 'id',
 
        messages: {},
 
        dispatched: false,
 
        /** @property {Object} */
        defaultMessages: {
            confirm_title: __('pim_datagrid.action.default.confirmation.title'),
            confirm_content: __('pim_datagrid.action.default.confirmation.content'),
            confirm_ok: __('pim_common.yes'),
            success: __('pim_datagrid.action.default.success'),
            error: __('pim_datagrid.action.default.error'),
            empty_selection: __('pim_datagrid.action.default.no_items')
        },
 
        /**
         * Initialize view
         *
         * @param {Object} options
         * @param {Object} [options.launcherOptions] Options for new instance of launcher object
         */
        initialize: function(options) {
            options = options || {};
 
            Iif (!options.datagrid) {
                throw new TypeError("'datagrid' is required");
            }
            this.datagrid = options.datagrid;
 
            _.each(this.messages, _.bind(function (message, key) {
                this.messages[key] = message;
            }, this));
 
            _.defaults(this.messages, this.defaultMessages);
 
            Iif (options.launcherOptions) {
                this.launcherOptions = _.extend({}, this.launcherOptions, options.launcherOptions);
            }
 
            this.launcherOptions = _.extend({
                action: this
            }, this.launcherOptions);
 
            Backbone.View.prototype.initialize.apply(this, arguments);
        },
 
        /**
         * Creates launcher
         *
         * @param {Object} options Launcher options
         * @return {oro.datagrid.ActionLauncher}
         */
        createLauncher: function(options) {
            options = options || {};
            if (_.isUndefined(options.icon) && !_.isUndefined(this.icon)) {
                options.icon = this.icon;
            }
            if (_.isUndefined(options.className) && !_.isUndefined(this.className)) {
                options.className = this.className;
            }
            _.defaults(options, this.launcherOptions);
 
            return new (this.launcherPrototype)(options);
        },
 
        /**
         * Run action
         */
        run: function() {
            var options = {
                doExecute: true
            };
            this.trigger('preExecute', this, options);
            Eif (options.doExecute) {
                this.execute();
                this.trigger('postExecute', this, options);
            }
        },
 
        /**
         * Execute action
         */
        execute: function() {
            var eventName = this.getEventName();
            mediator.once(eventName, this.executeConfiguredAction, this);
            this._confirmationExecutor(
                _.bind(
                    function() {mediator.trigger(eventName, this);},
                    this
                )
            );
        },
 
        getEventName: function() {
            return 'grid_action_execute:' + this.datagrid.name + ':' + this.name;
        },
 
        executeConfiguredAction: function(action) {
            if (action.frontend_type == 'export') {
                this._handleExport(action);
            } else if (action.frontend_type == 'ajax') {
                this._handleAjax(action);
            } else Eif (action.frontend_type == 'redirect') {
                this._handleRedirect(action);
            } else {
                this._handleWidget(action);
            }
        },
 
        _confirmationExecutor: function(callback) {
            Iif (this.confirmation) {
                this.getConfirmDialog(callback);
            } else {
                callback();
            }
        },
 
        _handleExport: function(action) {
            Iif (action.dispatched) {
                return;
            }
 
            var ExportAction = requireContext('oro/' + action.frontend_type + '-widget')
 
            var exportAction = new ExportAction(action)
            exportAction.run();
        },
 
        _handleWidget: function(action) {
            if (action.dispatched) {
                return;
            }
            action.frontend_options.url = action.frontend_options.url || this.getLinkWithParameters();
            action.frontend_options.title = action.frontend_options.title || this.label;
 
            var WidgetType = requireContext('oro/' + action.frontend_type + '-widget')
 
            var widget = new WidgetType(action.frontend_options);
            widget.render();
        },
 
        _handleRedirect: function(action) {
            Iif (action.dispatched) {
                return;
            }
            var url = action.getLinkWithParameters();
            router.redirect(url);
        },
 
        _handleAjax: function(action) {
            Iif (action.dispatched) {
                return;
            }
            action.datagrid.showLoading();
            $.ajax({
                url: action.getLink(),
                method: action.getMethod(),
                data: action.getActionParameters(),
                context: action,
                dataType: 'json',
                error: action._onAjaxError,
                success: action._onAjaxSuccess
            });
        },
 
        _onAjaxError: function(jqXHR, textStatus, errorThrown) {
            error.dispatch(null, jqXHR);
            this.datagrid.hideLoading();
        },
 
        _onAjaxSuccess: function(data, textStatus, jqXHR) {
            Iif (data.count) {
                this.datagrid.collection.state.totalRecords -= data.count;
            }
 
            this.datagrid.hideLoading();
            this.datagrid.collection.fetch();
 
            var defaultMessage = data.successful ? this.messages.success : this.messages.error,
                message = __(data.message) || defaultMessage;
            Eif (message) {
                messenger.notify(data.successful ? 'success' : 'error', message);
            }
        },
 
        /**
         * Get action url
         *
         * @return {String}
         * @private
         */
        getLink: function(parameters) {
            Iif (_.isUndefined(parameters)) {
                parameters = {};
            }
            return routing.generate(
                this.route,
                _.extend(
                    this.route_parameters,
                    parameters
                )
            );
        },
 
        getMethod: function () {
            return 'GET';
        },
 
        /**
         * Get action url with parameters added.
         *
         * @returns {String}
         */
        getLinkWithParameters: function() {
            return this.getLink(this.getActionParameters());
        },
 
        /**
         * Get action parameters
         *
         * @returns {Object}
         */
        getActionParameters: function() {
            return {};
        },
 
        /**
         * Get view for confirm modal
         *
         * @return {oro.Modal}
         */
        getConfirmDialog: function(callback) {
            return Dialog.confirm(
              this.messages.confirm_content,
              this.messages.confirm_title,
              callback,
              this.getEntityHint(true)
            );
        },
 
        /**
         * Get the entity type from datagrid metadata
         *
         * @param {Boolean} plural Pluralize the entity code
         */
        getEntityHint: function(plural) {
            const datagrid = this.datagrid || {};
            const entityHint = datagrid.entityHint || 'item';
 
            if (plural) {
                return this.getEntityPlural(entityHint);
            }
 
            return entityHint;
        },
 
        /**
         * Get the entity hint separated by dashes
         */
        getEntityCode: function() {
            const entityHint = this.getEntityHint();
            return entityHint.toLowerCase().split(' ').join('_');
        },
 
        /**
         * Very basic pluralize method for entity types
         *
         * Example:
         *      Product -> products
         *      Family -> families
         *
         * @return {String}
         */
        getEntityPlural: function(entityHint) {
            if (entityHint.endsWith('y')) {
                return entityHint.replace(/y$/, 'ies');
            }
 
            return `${entityHint.replace('_', ' ')}s`;
        }
    });
});