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

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