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

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

Complexity

Total Complexity 44
Complexity/F 2

Size

Lines of Code 245
Function Count 22

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 44
eloc 174
mnd 22
bc 22
fnc 22
dl 0
loc 245
rs 8.8798
bpm 1
cpm 2
noi 2
c 0
b 0
f 0

How to fix   Complexity   

Complexity

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