Passed
Push — master ( 71fe99...f3b0ea )
by
unknown
09:06
created

myems-admin/app/controllers/settings/space/spacemicrogrid.controller.js   B

Complexity

Total Complexity 46
Complexity/F 2.09

Size

Lines of Code 234
Function Count 22

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 46
eloc 164
mnd 24
bc 24
fnc 22
dl 0
loc 234
rs 8.72
bpm 1.0909
cpm 2.0909
noi 2
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like myems-admin/app/controllers/settings/space/spacemicrogrid.controller.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
'use strict';
2
3
app.controller('SpaceMicrogridController', function(
4
    $scope,
5
    $window,
6
    $timeout,
7
    $translate,
8
    SpaceService,
9
    MicrogridService,
10
    SpaceMicrogridService,
11
    toaster, SweetAlert) {
12
    
13
    $scope.spaces = [];
14
    $scope.currentSpaceID = 1;
15
    $scope.microgrids = [];
16
    $scope.spacemicrogrids = [];
17
    $scope.cur_user = JSON.parse($window.localStorage.getItem("myems_admin_ui_current_user"));
18
    $scope.isLoadingMicrogrids = false;
19
    $scope.tabInitialized = false;
20
    $scope.isSpaceSelected = false;
21
22
    $scope.getAllSpaces = function() {
23
        let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
24
        SpaceService.getAllSpaces(headers, function (response) {
25
            if (angular.isDefined(response.status) && response.status === 200) {
26
                $scope.spaces = response.data;
27
            } else {
28
                $scope.spaces = [];
29
            }
30
31
            var treedata = {'core': {'data': [], "multiple" : false }, "plugins" : [ "wholerow" ]};
32
            for (var i = 0; i < $scope.spaces.length; i++) {
33
                var node = {
34
                    "id": $scope.spaces[i].id.toString(),
35
                    "parent": $scope.spaces[i].id == 1 ? '#' : $scope.spaces[i].parent_space.id.toString(),
36
                    "text": $scope.spaces[i].name,
37
                    "state": $scope.spaces[i].id == 1 ? { 'opened': true, 'selected': false } : undefined
38
                };
39
                treedata['core']['data'].push(node);
40
            }
41
42
            angular.element(spacetreewithmicrogrid).jstree(treedata);
43
44
            angular.element(spacetreewithmicrogrid).on("changed.jstree", function (e, data) {
45
                if (data.selected && data.selected.length > 0) {
46
                    $scope.currentSpaceID = parseInt(data.selected[0]);
47
                    $scope.isSpaceSelected = true;
48
                    $scope.getMicrogridsBySpaceID($scope.currentSpaceID);
49
                } else {
50
                    $scope.isSpaceSelected = false;
51
                    $scope.spacemicrogrids = [];
52
                }
53
                if (!$scope.$$phase && !$scope.$root.$$phase) {
54
                    $scope.$apply();
55
                }
56
            });
57
        });
58
    };
59
60
    $scope.getMicrogridsBySpaceID = function(id) {
61
        if($scope.isLoadingMicrogrids) return;
62
        $scope.isLoadingMicrogrids = true;
63
        $scope.spacemicrogrids = [];
64
        let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
65
        SpaceMicrogridService.getMicrogridsBySpaceID(id, headers, function (response) {
66
            $scope.isLoadingMicrogrids = false;
67
            if (angular.isDefined(response.status) && response.status === 200) {
68
                $scope.spacemicrogrids = response.data;
69
            } else {
70
                $scope.spacemicrogrids = [];
71
            }
72
        });
73
    };
74
75
    $scope.getAllMicrogrids = function() {
76
        let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
77
        MicrogridService.getAllMicrogrids(headers, function (response) {
78
            if (angular.isDefined(response.status) && response.status === 200) {
79
                $scope.microgrids = response.data;
80
            } else {
81
                $scope.microgrids = [];
82
            }
83
        });
84
    };
85
86
    $scope.pairMicrogrid = function(dragEl, dropEl) {
87
        var microgridid = angular.element('#' + dragEl).scope().microgrid.id;
88
        var spaceid = angular.element(spacetreewithmicrogrid).jstree(true).get_top_selected();
89
        let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
90
        SpaceMicrogridService.addPair(spaceid, microgridid, headers, function (response) {
91
            if (angular.isDefined(response.status) && response.status === 201) {
92
                toaster.pop({
93
                    type: "success",
94
                    title: $translate.instant("TOASTER.SUCCESS_TITLE"),
95
                    body: $translate.instant("TOASTER.BIND_MICROGRID_SUCCESS"),
96
                    showCloseButton: true,
97
                });
98
                $scope.getMicrogridsBySpaceID(spaceid);
99
            } else {
100
                toaster.pop({
101
                    type: "error",
102
                    title: $translate.instant(response.data.title),
103
                    body: $translate.instant(response.data.description),
104
                    showCloseButton: true,
105
                });
106
            }
107
        });
108
    };
109
110
    $scope.deleteMicrogridPair = function(dragEl, dropEl) {
111
        if (angular.element('#' + dragEl).hasClass('source')) {
112
            return;
113
        }
114
        var spacemicrogridid = angular.element('#' + dragEl).scope().spacemicrogrid.id;
115
        var spaceid = angular.element(spacetreewithmicrogrid).jstree(true).get_top_selected();
116
        let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
117
        SpaceMicrogridService.deletePair(spaceid, spacemicrogridid, headers, function (response) {
118
            if (angular.isDefined(response.status) && response.status === 204) {
119
                toaster.pop({
120
                    type: "success",
121
                    title: $translate.instant("TOASTER.SUCCESS_TITLE"),
122
                    body: $translate.instant("TOASTER.UNBIND_MICROGRID_SUCCESS"),
123
                    showCloseButton: true,
124
                });
125
                $scope.getMicrogridsBySpaceID(spaceid);
126
            } else {
127
                toaster.pop({
128
                    type: "error",
129
                    title: $translate.instant(response.data.title),
130
                    body: $translate.instant(response.data.description),
131
                    showCloseButton: true,
132
                });
133
            }
134
        });
135
    };
136
137
    $scope.refreshSpaceTree = function() {
138
        let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
139
        SpaceService.getAllSpaces(headers, function (response) {
140
            if (angular.isDefined(response.status) && response.status === 200) {
141
                $scope.spaces = response.data;
142
            } else {
143
                $scope.spaces = [];
144
            }
145
146
            var treedata = {'core': {'data': [], "multiple" : false }, "plugins" : [ "wholerow" ]};
147
            for (var i = 0; i < $scope.spaces.length; i++) {
148
                var node = {
149
                    "id": $scope.spaces[i].id.toString(),
150
                    "parent": $scope.spaces[i].id == 1 ? '#' : $scope.spaces[i].parent_space.id.toString(),
151
                    "text": $scope.spaces[i].name,
152
                    "state": $scope.spaces[i].id == 1 ? { 'opened': true, 'selected': false } : undefined
153
                };
154
                treedata['core']['data'].push(node);
155
            }
156
157
            angular.element(spacetreewithmicrogrid).jstree(true).settings.core.data = treedata['core']['data'];
158
            angular.element(spacetreewithmicrogrid).jstree(true).refresh();
159
            // Reset selection state after tree refresh
160
            $scope.isSpaceSelected = false;
161
            $scope.spacemicrogrids = [];
162
            if (!$scope.$$phase && !$scope.$root.$$phase) {
163
                $scope.$apply();
164
            }
165
        });
166
    };
167
168
    $scope.$on('handleBroadcastSpaceChanged', function(event) {
169
        $scope.spacemicrogrids = [];
170
        $scope.refreshSpaceTree();
171
    });
172
173
    // Listen for disabled drop events to show warning
174
    // Only show warning if this tab is currently active
175
    $scope.$on('HJC-DROP-DISABLED', function(event) {
176
        var TAB_INDEXES = ($scope.$parent && $scope.$parent.TAB_INDEXES) || { MICROGRID: 15 };
177
        if ($scope.$parent && $scope.$parent.activeTabIndex === TAB_INDEXES.MICROGRID) {
178
            $timeout(function() {
179
                try {
180
                    toaster.pop({
181
                        type: "warning",
182
                        body: $translate.instant("SETTING.PLEASE_SELECT_SPACE_FIRST"),
183
                        showCloseButton: true,
184
                    });
185
                } catch(err) {
186
                    console.error('Error showing toaster:', err);
187
                    alert($translate.instant("SETTING.PLEASE_SELECT_SPACE_FIRST"));
0 ignored issues
show
Debugging Code Best Practice introduced by
The alert UI element is often considered obtrusive and is generally only used as a temporary measure. Consider replacing it with another UI element.
Loading history...
188
                }
189
            }, 0);
190
        }
191
    });
192
193
    // Listen for disabled drag events to show warning
194
    // Only show warning if this tab is currently active
195
    $scope.$on('HJC-DRAG-DISABLED', function(event) {
196
        var TAB_INDEXES = ($scope.$parent && $scope.$parent.TAB_INDEXES) || { MICROGRID: 15 };
197
        if ($scope.$parent && $scope.$parent.activeTabIndex === TAB_INDEXES.MICROGRID) {
198
            $timeout(function() {
199
                try {
200
                    toaster.pop({
201
                        type: "warning",
202
                        body: $translate.instant("SETTING.PLEASE_SELECT_SPACE_FIRST"),
203
                        showCloseButton: true,
204
                    });
205
                } catch(err) {
206
                    console.error('Error showing toaster:', err);
207
                    alert($translate.instant("SETTING.PLEASE_SELECT_SPACE_FIRST"));
0 ignored issues
show
Debugging Code Best Practice introduced by
The alert UI element is often considered obtrusive and is generally only used as a temporary measure. Consider replacing it with another UI element.
Loading history...
208
                }
209
            }, 0);
210
        }
211
    });
212
213
    $scope.initTab = function() {
214
        if (!$scope.tabInitialized) {
215
            $scope.tabInitialized = true;
216
            $scope.getAllSpaces();
217
            $scope.getAllMicrogrids();
218
        }
219
    };
220
221
    $scope.$on('space.tabSelected', function(event, tabIndex) {
222
        var TAB_INDEXES = ($scope.$parent && $scope.$parent.TAB_INDEXES) || { MICROGRID: 15 };
223
        if (tabIndex === TAB_INDEXES.MICROGRID && !$scope.tabInitialized) {
224
            $scope.initTab();
225
        }
226
    });
227
228
    $timeout(function() {
229
        var TAB_INDEXES = ($scope.$parent && $scope.$parent.TAB_INDEXES) || { MICROGRID: 15 };
230
        if ($scope.$parent && $scope.$parent.activeTabIndex === TAB_INDEXES.MICROGRID && !$scope.tabInitialized) {
231
            $scope.initTab();
232
        }
233
    }, 0);
234
});