Passed
Push — master ( 157b3f...4f79df )
by Vasyl
01:47
created

resources/js/dashboard.js   F

Complexity

Total Complexity 70
Complexity/F 1.59

Size

Lines of Code 459
Function Count 44

Duplication

Duplicated Lines 459
Ratio 100 %

Importance

Changes 0
Metric Value
wmc 70
eloc 318
mnd 26
bc 26
fnc 44
dl 459
loc 459
rs 2.8
bpm 0.5909
cpm 1.5909
noi 25
c 0
b 0
f 0

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complexity

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like resources/js/dashboard.js often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1 View Code Duplication
$(function () {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2
3
    'use strict';
4
5
    const LANGUAGE = $('html').attr('lang') || 'ru'
6
7
    $(document).ajaxStart(function () {
8
        Pace.restart()
0 ignored issues
show
Bug introduced by
The variable Pace seems to be never declared. If this is a global, consider adding a /** global: Pace */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
9
    })
10
11
    $(document).ready(function () {
12
        $.ajaxSetup({
13
            headers: {
14
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
15
            }
16
        });
17
18
        $('.field-select2-change-status-ajax').each(function () {
19
            var $base = $(this),
20
                $select = $base.find('.select2-change-status-ajax'),
21
                url = $base.data('url') || $base.data('route'),
22
                fieldName = $base.find('select').attr('name'),
23
                method = $base.data('method') || 'GET',
24
                $select2 = $select.select2({
25
                    language: LANGUAGE,
26
                    tags: false
27
                });
28
29
            $select2.on("select2:select", function (e) {
30
                $base.find('.overlay').removeClass('hidden');
31
32
                $.ajax({
33
                    method: method,
34
                    url: url,
35
                    dataType: 'json',
36
                    data: {name: fieldName, value: e.params.data.id},
37
                    success: function (data) {
38
                        if (data.message) {
39
                            $base.append('<div class="text-success">' + data.message + '</div>')
40
                            $base.find('.text-success').delay(2000).fadeOut(500, 'linear', function () {
41
                                $(this).remove()
42
                            })
43
                        }
44
                    },
45
                    error: function () {
46
                        console.log('Error Ajax!')
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
47
                        $base.append('<div class="text-danger">Error Ajax</div>')
48
                        $base.find('.text-danger').delay(2000).fadeOut(500, 'linear', function () {
49
                            $(this).remove()
50
                        })
51
                    },
52
                    complete: function () {
53
                        $base.find('.overlay').addClass('hidden')
54
                    }
55
                })
56
            })
57
        })
58
59
        $('.field-select2-tree-ajax').each(function () {
60
            var $base = $(this),
61
                $select = $base.find('.select2-tree'),
62
                url = $base.data('url') || $base.data('route'),
63
                valFld = $base.data('valFld') ? $base.data('valFld') : 'id',
64
                labelFld = $base.data('labelFld') ? $base.data('labelFld') : 'name',
65
                incFld = $base.data('incFld') ? $base.data('incFld') : 'children'
66
67
            $.ajax({
68
                method: 'GET',
69
                url: url,
70
                dataType: 'json',
71
                data: {data: ''},
72
                success: function (data) {
73
                    $select.select2ToTree({
74
                        treeData: {
75
                            dataArr: data.data,
76
                            dftVal: data.default,
77
                            valFld: valFld,
78
                            labelFld: labelFld,
79
                            'incFld': incFld
80
                        }
81
                    })
82
                },
83
                error: function () {
84
                    console.log('Error Ajax!')
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
85
                },
86
                complete: function () {
87
                    $base.find('.overlay').fadeOut(200)
88
                }
89
            })
90
        })
91
92
        $('.field-tree').each(function () {
93
            var $base = $(this),
94
                $tree = $base.find('.field-tree-data'),
95
                url = $base.data('url') || $base.data('route'),
96
                showCheckbox = $base.data('showCheckbox') === undefined ? true : $base.data('showCheckbox'),
97
                showIcon = $base.data('showIcon') === undefined ? false : $base.data('showIcon'),
98
                fieldName = $base.data('field-name'),
99
                $inputs = $base.find('.field-tree-inputs'),
100
                getCheckedIds = function (obj) {
101
                    $inputs.html('')
102
                    var array = []
103
                    obj.forEach(element => {
104
                        $inputs.append('<input type="hidden" name="' + fieldName + '[]" value="' + element.id + '" />')
105
                    })
106
                    return array
107
                }
108
109
            $.ajax({
110
                method: 'GET',
111
                url: url,
112
                dataType: 'json',
113
                data: {data: ''},
114
                success: function (data) {
115
                    $tree.treeview({
116
                        data: data,
117
                        showIcon: showIcon,
118
                        showCheckbox: showCheckbox,
119
                    })
120
121
                    getCheckedIds($tree.treeview('getChecked'))
122
123
                    $tree.on('nodeChecked', function (event, data) {
0 ignored issues
show
Unused Code introduced by
The parameter event is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter data is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
124
                        // console.log($(this).treeview('getChecked'))
125
                        getCheckedIds($(this).treeview('getChecked'))
126
                    })
127
                    $tree.on('nodeUnchecked', function (event, data) {
0 ignored issues
show
Unused Code introduced by
The parameter data is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter event is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
128
                        // console.log($(this).treeview('getChecked'))
129
                        getCheckedIds($(this).treeview('getChecked'))
130
                    })
131
                },
132
                error: function () {
133
                    console.log('Error Ajax!')
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
134
                },
135
                complete: function () {
136
                    $base.find('.overlay').fadeOut(200)
137
                }
138
            })
139
140
        })
141
142
        if ($('textarea.ck-editor.ck-mini').length) {
143
            $('textarea.ck-editor.ck-mini').ckeditor(ckMini || {})
0 ignored issues
show
Best Practice introduced by
If you intend to check if the variable ckMini is declared in the current environment, consider using typeof ckMini === "undefined" instead. This is safe if the variable is not actually declared.
Loading history...
144
        }
145
146
        if ($('textarea.ck-editor.ck-small').length) {
147
            $('textarea.ck-editor.ck-small').ckeditor(ckSmall || {})
0 ignored issues
show
Best Practice introduced by
If you intend to check if the variable ckSmall is declared in the current environment, consider using typeof ckSmall === "undefined" instead. This is safe if the variable is not actually declared.
Loading history...
148
        }
149
150
        if ($('textarea.ck-editor.ck-full').length) {
151
            $('textarea.ck-editor.ck-full').ckeditor(ckFull || {})
0 ignored issues
show
Best Practice introduced by
If you intend to check if the variable ckFull is declared in the current environment, consider using typeof ckFull === "undefined" instead. This is safe if the variable is not actually declared.
Loading history...
152
        }
153
154
        if ($('.field-x-editable').length) {
155
            $('.field-x-editable').editable(xEditable || {});
0 ignored issues
show
Best Practice introduced by
If you intend to check if the variable xEditable is declared in the current environment, consider using typeof xEditable === "undefined" instead. This is safe if the variable is not actually declared.
Loading history...
156
        }
157
158
        if ($('.field-colorpicker').length) {
159
            $('.field-colorpicker').colorpicker(colorpickerOptions || {});
0 ignored issues
show
Best Practice introduced by
If you intend to check if the variable colorpickerOptions is declared in the current environment, consider using typeof colorpickerOptions === "undefined" instead. This is safe if the variable is not actually declared.
Loading history...
160
        }
161
162
        if ($('.field-datetimepicker').length) {
163
            $('.field-datetimepicker').datetimepicker(datetimepickerOptions || {
0 ignored issues
show
Best Practice introduced by
If you intend to check if the variable datetimepickerOptions is declared in the current environment, consider using typeof datetimepickerOptions === "undefined" instead. This is safe if the variable is not actually declared.
Loading history...
164
                format: 'Y/m/d H:i:s'
165
            });
166
        }
167
168
        if ($('.field-datepicker').length) {
169
            $('.field-datepicker').datetimepicker(datepickerOptions || {
0 ignored issues
show
Best Practice introduced by
If you intend to check if the variable datepickerOptions is declared in the current environment, consider using typeof datepickerOptions === "undefined" instead. This is safe if the variable is not actually declared.
Loading history...
170
                timepicker:false,
171
                format:'d/m/Y'
172
            });
173
        }
174
175
        if ($('.field-timepicker').length) {
176
            $('.field-timepicker').datetimepicker(timepickerOptions || {
0 ignored issues
show
Best Practice introduced by
If you intend to check if the variable timepickerOptions is declared in the current environment, consider using typeof timepickerOptions === "undefined" instead. This is safe if the variable is not actually declared.
Loading history...
177
                datepicker:false,
178
                format: 'H:i'
179
            });
180
        }
181
182
        $(document).on('click', '.js-action-form', function (e) {
183
            e.preventDefault()
184
            var $form = $('#js-action-form'),
185
                $this = $(this),
186
                method = $this.data('method') || 'POST',
187
                strConfirm = $this.data('confirm') || translates.notifications.confirmAction || 'Confirm action?',
0 ignored issues
show
Bug introduced by
The variable translates seems to be never declared. If this is a global, consider adding a /** global: translates */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
188
                destination = $(this).data('destination'),
189
                url = $(this).data('url');
190
            if (url && $form && confirm(strConfirm)) {
0 ignored issues
show
Debugging Code Best Practice introduced by
The confirm UI element is often considered obtrusive and is generally only used as a temporary measure. Consider replacing it with another UI element.
Loading history...
191
                $form.find('input[name="_method"]').val(method)
192
                if (destination) {
193
                    $form.find('input[name="destination"]').val(destination)
194
                }
195
                $form.attr('action', url).submit()
196
            }
197
            return false
198
        })
199
200
        if ($('.select2:not(.field-select-ajax):not(.sortable)').length) {
201
            $('.select2:not(.field-select-ajax):not(.sortable)').select2({
202
                language: 'ru',
203
                tags: false
204
            })
205
        }
206
207
        if ($('.select2.sortable').length) {
208
            $('.select2.sortable').select2({
209
                language: 'ru',
210
                tags: true
211
            })
212
213
            $('.select2.sortable').on("select2:select", function (evt) {
214
                var element = evt.params.data.element
215
                var $element = $(element)
216
217
                $element.detach()
218
                $(this).append($element)
219
                $(this).trigger("change")
220
            })
221
        }
222
223
        if ($('.select2.field-select-ajax').length) {
224
            $('.select2.field-select-ajax').each(function (index) {
0 ignored issues
show
Unused Code introduced by
The parameter index is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
225
                var url = $(this).data('url') || $(this).data('route')
226
227
                $(this).select2({
228
                    language: LANGUAGE,
229
                    tags: false,
230
                    ajax: {
231
                        delay: 250,
232
                        url: url,
233
                        dataType: 'json'
234
                    }
235
                })
236
            })
237
238
        }
239
240
        $('.lte-daterangepicker').each(function () {
241
            $(this).on('apply.daterangepicker', function (ev, picker) {
242
                var $inputNameStart = $(this).data('input-name-start'),
243
                    $inputNameEnd = $(this).data('input-name-end'),
244
                    $format = $(this).data('format') || 'MM/DD/YYYY'
245
                $(this).val(picker.startDate.format($format) + ' - ' + picker.endDate.format($format))
246
                $(this).siblings('input[name="' + $inputNameStart + '"]').val(picker.startDate.format($format))
247
                $(this).siblings('input[name="' + $inputNameEnd + '"]').val(picker.endDate.format($format))
248
            })
249
250
            $(this).on('cancel.daterangepicker', function (ev, picker) {
0 ignored issues
show
Unused Code introduced by
The parameter ev is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter picker is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
251
                $(this).val('')
252
            })
253
254
            $(this).daterangepicker({
255
                autoUpdateInput: false,
256
                "locale": translates.localeDateRangePicker || {
0 ignored issues
show
Bug introduced by
The variable translates seems to be never declared. If this is a global, consider adding a /** global: translates */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
257
                    "format": "MM/DD/YYYY",
258
                    "separator": " - ",
259
                    "applyLabel": "Apply",
260
                    "cancelLabel": "Cancel",
261
                    "fromLabel": "From",
262
                    "toLabel": "To",
263
                    "customRangeLabel": "Custom",
264
                    "weekLabel": "W",
265
                    "daysOfWeek": [
266
                        "Su",
267
                        "Mo",
268
                        "Tu",
269
                        "We",
270
                        "Th",
271
                        "Fr",
272
                        "Sa"
273
                    ],
274
                    "monthNames": [
275
                        "January",
276
                        "February",
277
                        "March",
278
                        "April",
279
                        "May",
280
                        "June",
281
                        "July",
282
                        "August",
283
                        "September",
284
                        "October",
285
                        "November",
286
                        "December"
287
                    ],
288
                    "firstDay": 1
289
                }
290
            })
291
        })
292
293
        $('[data-toggle="tooltip"]').tooltip()
294
295
        $(document).on('click', '.js-fill-fields-modal', function (e) {
296
            e.preventDefault()
297
            var $this = $(this),
298
                url = $this.data('url'),
299
                dataFields = $this.data('fields'),
300
                modal = $($this.data('target'))
301
302
            if (url) {
303
                modal.find('form').attr('action', url)
304
            }
305
            for (var field in dataFields) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
306
                modal.find('[name="' + field + '"]').val(dataFields[field]);
307
            }
308
309
            modal.modal() // Bootstrap!
310
        })
311
312
        var treeSortable = {}
313
314
        if ($('.tree-sortable').length) {
315
            $('.tree-sortable').each(function () {
316
                treeSortable[$(this).data('entity-name')] = $(this).sortable({
317
                    group: 'serialization',
318
                    delay: 500,
319
                    handle: '.handle',
320
                    onDrop: function ($item, container, _super) {
321
                        _super($item, container);
322
                    }
323
                })
324
            })
325
        }
326
327
        $(document).on('click', '.post-tree-sortaple', function (e) {
328
            e.preventDefault()
329
            e.stopPropagation()
330
            var $base = $(this),
331
                data = treeSortable[$(this).data('entity-name')].sortable("serialize").get(),
332
                url = $base.data('url') || $(this).data('route')
333
334
            $.ajax({
335
                method: 'POST',
336
                url: url,
337
                dataType: 'json',
338
                data: {'data': data},
339
                beforeSend: function () {
340
                    $base.attr('disabled', true)
341
                        .find('.fa')
342
                        .toggleClass('fa-spin')
343
                        .toggleClass('fa-refresh')
344
                },
345
                success: function (data) {
346
                    console.log(data)
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
347
                },
348
                error: function () {
349
                    console.log('Error Ajax!')
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
350
                },
351
                complete: function () {
352
                    $base.attr('disabled', false)
353
                        .find('.fa')
354
                        .toggleClass('fa-spin')
355
                        .toggleClass('fa-refresh')
356
                }
357
            })
358
        })
359
360
        if ($('.field-links').length) {
361
            $('.field-links').on('click', '.btn-info', function (e) {
362
                e.preventDefault()
363
                var n = $(this).parents('.field-links').find('.btn-info').index(this),
364
                    length = $(this).parents('.field-links').find('.btn-info').length,
365
                    fieldName = $(this).parents('.field-links').data('field-name'),
366
                    keyKey = $(this).parents('.field-links').data('key'),
367
                    keyValue = $(this).parents('.field-links').data('value'),
368
                    placeholderKey = $(this).parents('.field-links').data('placeholder-key'),
369
                    placeholderValue = $(this).parents('.field-links').data('placeholder-value'),
370
                    item = '<tr class="item">'
371
                        + '<td>'
372
                        + '<div class="input-group input-group-md">'
373
                        + '<input type="text" name="' + fieldName + '[' + (length) + '][' + keyKey + ']" class="form-control" placeholder="' + placeholderKey + '">'
374
                        + '<span class="input-group-btn" style="width: 40%">'
375
                        + '<input type="text" name="' + fieldName + '[' + (length) + '][' + keyValue + ']" class="form-control" placeholder="' + placeholderValue + '">'
376
                        + '</span>'
377
                        + '<span class="input-group-btn">'
378
                        + '<button type="button" class="btn btn-info btn-flat">'
379
                        + '<i class="fa fa-plus"></i>'
380
                        + '</button>'
381
                        + '<button type="button" class="btn btn-danger btn-flat">'
382
                        + '<i class="fa fa-remove"></i>'
383
                        + '</button>'
384
                        + '</span>'
385
                        + '</div>'
386
                        + '</td>'
387
                        + '</tr>"'
388
389
                $(this).parents('.field-links').find('.item').eq(n).after(item)
390
            })
391
392
            $('.field-links').on('click', '.btn-danger', function (e) {
393
                e.preventDefault()
394
                var n = $(this).parents('.field-links').find('.btn-danger:not(.first)').index(this)
395
396
                $(this).parents('.field-links').find('.item').eq(n).remove()
397
            })
398
        }
399
400
        if ($('.field-linear-list').length) {
401
            $('.field-linear-list').on('click', '.btn-info', function (e) {
402
                e.preventDefault()
403
                var n = $(this).parents('.field-linear-list').find('.btn-info').index(this),
404
                    length = $(this).parents('.field-linear-list').find('.btn-info').length,
405
                    fieldName = $(this).parents('.field-linear-list').data('field-name'),
406
                    placeholderValue = $(this).parents('.field-linear-list').data('placeholder-value'),
407
                    item = '<tr class="item">'
408
                        + '<td>'
409
                        + '<div class="input-group input-group-md">'
410
                        + '<span class="input-group-btn" style="width: 100%">'
411
                        + '<input type="text" name="' + fieldName + '[' + (length) + ']" class="form-control" placeholder="' + placeholderValue + ' ' + (parseInt(length) + 1) + '">'
412
                        + '</span>'
413
                        + '<span class="input-group-btn">'
414
                        + '<button type="button" class="btn btn-info btn-flat">'
415
                        + '<i class="fa fa-plus"></i>'
416
                        + '</button>'
417
                        + '<button type="button" class="btn btn-danger btn-flat">'
418
                        + '<i class="fa fa-remove"></i>'
419
                        + '</button>'
420
                        + '</span>'
421
                        + '</div>'
422
                        + '</td>'
423
                        + '</tr>"'
424
                $(this).parents('.field-linear-list').find('.item').eq(n).after(item)
425
            })
426
427
            $('.field-linear-list').on('click', '.btn-danger', function (e) {
428
                e.preventDefault()
429
                var n = $(this).parents('.field-linear-list').find('.btn-danger:not(.first)').index(this)
430
431
                $(this).parents('.field-linear-list').find('.item').eq(n).remove()
432
            })
433
        }
434
435
        if ($('.field-more-items-sortable').length) {
436
            $('.field-more-items-sortable .todo-list').sortable({
437
                handle: '.handle',
438
                onDrop: function ($item, container, _super) {
439
                    _super($item, container);
440
                    $(container.target[0]).find('li').each(function (index) {
441
                        $(this).find('.field-weight-item').val(index)
442
                    })
443
                }
444
            });
445
446
            $('.field-more-items-sortable').on('click', '.filed-remove', function (e) {
447
                e.preventDefault()
448
                $(this).parents('li').hide().find('.field-delete-item').val($(this).data('id'))
449
            })
450
        }
451
452
        if ($('.field-more-items').length) {
453
            $('.field-more-items').on('click', '.filed-remove', function (e) {
454
                e.preventDefault()
455
                $(this).parents('tr').hide().find('.field-delete-item').val($(this).data('id'))
456
            })
457
        }
458
    })
459
});
460