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

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

Complexity

Total Complexity 49
Complexity/F 1.96

Size

Lines of Code 268
Function Count 25

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 49
eloc 189
mnd 24
bc 24
fnc 25
dl 0
loc 268
rs 8.48
bpm 0.96
cpm 1.96
noi 2
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like myems-admin/app/controllers/settings/space/spacepoint.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('SpacePointController', function (
4
    $scope, 
5
    $window,
6
    $timeout,
7
    $translate, 
8
    SpaceService,
9
    DataSourceService, 
10
    PointService, 
11
    SpacePointService,  
12
    toaster, 
13
    SweetAlert) {
14
    $scope.cur_user = JSON.parse($window.localStorage.getItem("myems_admin_ui_current_user"));
15
    $scope.spaces = [];
16
    $scope.currentSpaceID = 1;
17
    $scope.spacepoints = [];
18
    $scope.datasources = [];
19
    $scope.points = [];
20
    $scope.isLoadingPoints = false;
21
    $scope.tabInitialized = false;
22
    $scope.isSpaceSelected = false;
23
24
    $scope.getAllSpaces = function() {
25
      let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
26
      SpaceService.getAllSpaces(headers, function (response) {
27
        if (angular.isDefined(response.status) && response.status === 200) {
28
          $scope.spaces = response.data;
29
        } else {
30
          $scope.spaces = [];
31
        }
32
        //create space tree
33
        var treedata = {'core': {'data': [], "multiple" : false,}, "plugins" : [ "wholerow" ]};
34
        for(var i=0; i < $scope.spaces.length; i++) {
35
            if ($scope.spaces[i].id == 1) {
36
              var node = {"id": $scope.spaces[i].id.toString(),
37
                                  "parent": '#',
38
                                  "text": $scope.spaces[i].name,
39
                                  "state": {  'opened' : true,  'selected' : false },
40
                                 };
41
            } else {
42
                var node = {"id": $scope.spaces[i].id.toString(),
43
                                    "parent": $scope.spaces[i].parent_space.id.toString(),
44
                                    "text": $scope.spaces[i].name,
45
                                   };
46
            };
47
            treedata['core']['data'].push(node);
48
        }
49
50
        angular.element(spacetreewithpoint).jstree(treedata);
51
        //space tree selected changed event handler
52
        angular.element(spacetreewithpoint).on("changed.jstree", function (e, data) {
53
            if (data.selected && data.selected.length > 0) {
54
                $scope.currentSpaceID = parseInt(data.selected[0]);
55
                $scope.isSpaceSelected = true;
56
                $scope.getPointsBySpaceID($scope.currentSpaceID);
57
            } else {
58
                $scope.isSpaceSelected = false;
59
                $scope.spacepoints = [];
60
            }
61
            if (!$scope.$$phase && !$scope.$root.$$phase) {
62
                $scope.$apply();
63
            }
64
        });
65
      });
66
    };
67
68
    $scope.getAllDataSources = function () {
69
		let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
70
        DataSourceService.getAllDataSources(headers, function (response) {
71
            if (angular.isDefined(response.status) && response.status === 200) {
72
                $scope.datasources = response.data;
73
                if ($scope.datasources.length > 0) {
74
                    $scope.currentDataSource = $scope.datasources[0].id;
75
                    $scope.getPointsByDataSourceID($scope.currentDataSource);
76
                }
77
            } else {
78
                $scope.datasources = [];
79
            }
80
        });
81
    };
82
83
    $scope.getPointsByDataSourceID = function (id) {
84
		let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
85
        PointService.getPointsByDataSourceID(id, headers, function (response) {
86
            if (angular.isDefined(response.status) && response.status === 200) {
87
                $scope.points = response.data;
88
            } else {
89
                $scope.points = [];
90
            }
91
        });
92
    };
93
94
    $scope.getPointsBySpaceID = function (id) {
95
        if ($scope.isLoadingPoints) return;
96
        $scope.isLoadingPoints = true;
97
        let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
98
        SpacePointService.getPointsBySpaceID(id, headers, function (response) {
99
             $scope.isLoadingPoints = false;
100
            if (angular.isDefined(response.status) && response.status === 200) {
101
                $scope.spacepoints = response.data;
102
            } else {
103
                $scope.spacepoints = [];
104
            }
105
        });
106
107
    };
108
109
    $scope.changeDataSource = function (item, model) {
110
        $scope.currentDataSource = model;
111
        $scope.getPointsByDataSourceID($scope.currentDataSource);
112
    };
113
114
    $scope.pairPoint = function (dragEl, dropEl) {
115
        var pointid = angular.element('#' + dragEl).scope().point.id;
116
        var spaceid = $scope.currentSpaceID;
117
        let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
118
        SpacePointService.addPair(spaceid, pointid, headers, function (response) {
119
            if (angular.isDefined(response.status) && response.status === 201) {
120
                toaster.pop({
121
                    type: "success",
122
                    title: $translate.instant("TOASTER.SUCCESS_TITLE"),
123
                    body: $translate.instant("TOASTER.BIND_POINT_SUCCESS"),
124
                    showCloseButton: true,
125
                });
126
                $scope.getPointsBySpaceID($scope.currentSpaceID);
127
            } else {
128
                toaster.pop({
129
                    type: "error",
130
                    title: $translate.instant(response.data.title),
131
                    body: $translate.instant(response.data.description),
132
                    showCloseButton: true,
133
                });
134
            }
135
        });
136
    };
137
138
    $scope.deletePointPair = function (dragEl, dropEl) {
139
        if (angular.element('#' + dragEl).hasClass('source')) {
140
            return;
141
        }
142
        var spacepointid = angular.element('#' + dragEl).scope().spacepoint.id;
143
        var spaceid = $scope.currentSpaceID;
144
        let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
145
        SpacePointService.deletePair(spaceid, spacepointid, headers, function (response) {
146
            if (angular.isDefined(response.status) && response.status === 204) {
147
                toaster.pop({
148
                    type: "success",
149
                    title: $translate.instant("TOASTER.SUCCESS_TITLE"),
150
                    body: $translate.instant("TOASTER.UNBIND_POINT_SUCCESS"),
151
                    showCloseButton: true,
152
                });
153
                $scope.getPointsBySpaceID($scope.currentSpaceID);
154
            } else {
155
                toaster.pop({
156
                    type: "error",
157
                    title: $translate.instant(response.data.title),
158
                    body: $translate.instant(response.data.description),
159
                    showCloseButton: true,
160
                });
161
            }
162
        });
163
    };
164
165
    $scope.initTab = function() {
166
        if (!$scope.tabInitialized) {
167
            $scope.tabInitialized = true;
168
            $scope.getAllDataSources();
169
            $scope.getAllSpaces();
170
        }
171
    };
172
173
    $scope.$on('space.tabSelected', function(event, tabIndex) {
174
        var TAB_INDEXES = ($scope.$parent && $scope.$parent.TAB_INDEXES) || { POINT: 4 };
175
        if (tabIndex === TAB_INDEXES.POINT && !$scope.tabInitialized) {
176
            $scope.initTab();
177
        }
178
    });
179
180
    $timeout(function() {
181
        var TAB_INDEXES = ($scope.$parent && $scope.$parent.TAB_INDEXES) || { POINT: 4 };
182
        if ($scope.$parent && $scope.$parent.activeTabIndex === TAB_INDEXES.POINT && !$scope.tabInitialized) {
183
            $scope.initTab();
184
        }
185
    }, 0);
186
187
    $scope.refreshSpaceTree = function() {
188
      let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
189
      SpaceService.getAllSpaces(headers, function (response) {
190
        if (angular.isDefined(response.status) && response.status === 200) {
191
          $scope.spaces = response.data;
192
        } else {
193
          $scope.spaces = [];
194
        }
195
        //create space tree
196
        var treedata = {'core': {'data': [], "multiple" : false,}, "plugins" : [ "wholerow" ]};
197
        for(var i=0; i < $scope.spaces.length; i++) {
198
            if ($scope.spaces[i].id == 1) {
199
              var node = {"id": $scope.spaces[i].id.toString(),
200
                                  "parent": '#',
201
                                  "text": $scope.spaces[i].name,
202
                                  "state": {  'opened' : true,  'selected' : false },
203
                                 };
204
            } else {
205
                var node = {"id": $scope.spaces[i].id.toString(),
206
                                    "parent": $scope.spaces[i].parent_space.id.toString(),
207
                                    "text": $scope.spaces[i].name,
208
                                   };
209
            };
210
            treedata['core']['data'].push(node);
211
        }
212
213
        angular.element(spacetreewithpoint).jstree(true).settings.core.data = treedata['core']['data'];
214
        angular.element(spacetreewithpoint).jstree(true).refresh();
215
        // Reset selection state after tree refresh
216
        $scope.isSpaceSelected = false;
217
        $scope.spacepoints = [];
218
        if (!$scope.$$phase && !$scope.$root.$$phase) {
219
            $scope.$apply();
220
        }
221
      });
222
    };
223
224
  	$scope.$on('handleBroadcastSpaceChanged', function(event) {
225
      $scope.spacepoints = [];
226
      $scope.refreshSpaceTree();
227
  	});
228
229
    // Listen for disabled drop events to show warning
230
    // Only show warning if this tab is currently active
231
    $scope.$on('HJC-DROP-DISABLED', function(event) {
232
        var TAB_INDEXES = ($scope.$parent && $scope.$parent.TAB_INDEXES) || { POINT: 4 };
233
        if ($scope.$parent && $scope.$parent.activeTabIndex === TAB_INDEXES.POINT) {
234
            $timeout(function() {
235
                try {
236
                    toaster.pop({
237
                        type: "warning",
238
                        body: $translate.instant("SETTING.PLEASE_SELECT_SPACE_FIRST"),
239
                        showCloseButton: true,
240
                    });
241
                } catch(err) {
242
                    console.error('Error showing toaster:', err);
243
                    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...
244
                }
245
            }, 0);
246
        }
247
    });
248
249
    // Listen for disabled drag events to show warning
250
    // Only show warning if this tab is currently active
251
    $scope.$on('HJC-DRAG-DISABLED', function(event) {
252
        var TAB_INDEXES = ($scope.$parent && $scope.$parent.TAB_INDEXES) || { POINT: 4 };
253
        if ($scope.$parent && $scope.$parent.activeTabIndex === TAB_INDEXES.POINT) {
254
            $timeout(function() {
255
                try {
256
                    toaster.pop({
257
                        type: "warning",
258
                        body: $translate.instant("SETTING.PLEASE_SELECT_SPACE_FIRST"),
259
                        showCloseButton: true,
260
                    });
261
                } catch(err) {
262
                    console.error('Error showing toaster:', err);
263
                    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...
264
                }
265
            }, 0);
266
        }
267
    });
268
});
269