Passed
Push — master ( 98975f...e9b166 )
by
unknown
09:13
created

myems-admin/app/controllers/settings/tenant/tenant.controller.js   F

Complexity

Total Complexity 68
Complexity/F 1.55

Size

Lines of Code 403
Function Count 44

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 68
eloc 288
dl 0
loc 403
rs 2.96
c 0
b 0
f 0
mnd 24
bc 24
fnc 44
bpm 0.5454
cpm 1.5454
noi 0

How to fix   Complexity   

Complexity

Complex classes like myems-admin/app/controllers/settings/tenant/tenant.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('TenantController', function (
4
	$scope,
5
	$rootScope,
6
	$window,
7
	$translate,
8
	$uibModal,
9
	CostCenterService,
10
	ContactService,
11
	TenantService,
12
	TenantTypeService,
13
	toaster,
14
	SweetAlert) {
15
	$scope.cur_user = JSON.parse($window.localStorage.getItem("myems_admin_ui_current_user"));
16
	$scope.exportdata = '';
17
	$scope.importdata = '';
18
	$scope.tenantTypes = [];
19
	$scope.searchTenantKeyword = '';
20
	$scope.getAllCostCenters = function () {
21
		let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
22
		CostCenterService.getAllCostCenters(headers, function (response) {
23
			if (angular.isDefined(response.status) && response.status === 200) {
24
				$scope.costcenters = response.data;
25
			} else {
26
				$scope.costcenters = [];
27
			}
28
		});
29
	};
30
31
	$scope.getAllContacts = function () {
32
		let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
33
		ContactService.getAllContacts(headers, function (response) {
34
			if (angular.isDefined(response.status) && response.status === 200) {
35
				$scope.contacts = response.data;
36
			} else {
37
				$scope.contacts = [];
38
			}
39
		});
40
	};
41
42
	$scope.getAllTenants = function () {
43
		let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
44
		TenantService.getAllTenants(headers, function (response) {
45
			if (angular.isDefined(response.status) && response.status === 200) {
46
				$scope.tenants = response.data;
47
			} else {
48
				$scope.tenants = [];
49
			}
50
		});
51
	};
52
53
	$scope.getAllTenantTypes = function () {
54
		let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
55
		TenantTypeService.getAllTenantTypes(headers, function (response) {
56
			if (angular.isDefined(response.status) && response.status === 200) {
57
				$scope.tenantTypes.length = 0;
58
				Array.prototype.push.apply($scope.tenantTypes, response.data);
59
			} else {
60
				$scope.tenantTypes.length = 0;
61
			}
62
		});
63
	};
64
	
65
	$scope.addTenant = function () {
66
		var modalInstance = $uibModal.open({
67
			templateUrl: 'views/settings/tenant/tenant.model.html',
68
			controller: 'ModalAddTenantCtrl',
69
			windowClass: "animated fadeIn",
70
			resolve: {
71
				params: function () {
72
					return {
73
						tenantTypes: $scope.tenantTypes,
74
						costcenters: angular.copy($scope.costcenters),
75
						contacts: angular.copy($scope.contacts),
76
					};
77
				}
78
			}
79
		});
80
		modalInstance.result.then(function (tenant) {
81
			tenant.tenant_type_id = tenant.tenant_type.id;
82
			tenant.cost_center_id = tenant.cost_center.id;
83
			tenant.contact_id = tenant.contact.id;
84
			if (angular.isDefined(tenant.is_input_counted) == false) {
85
				tenant.is_input_counted = false;
86
			}
87
			if (angular.isDefined(tenant.is_key_tenant) == false) {
88
				tenant.is_key_tenant = false;
89
			}
90
			if (angular.isDefined(tenant.is_in_lease) == false) {
91
				tenant.is_in_lease = false;
92
			}
93
			let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
94
			TenantService.addTenant(tenant, headers, function (response) {
95
				if (angular.isDefined(response.status) && response.status === 201) {
96
					toaster.pop({
97
						type: "success",
98
						title: $translate.instant("TOASTER.SUCCESS_TITLE"),
99
						body: $translate.instant("TOASTER.SUCCESS_ADD_BODY", { template: $translate.instant("COMMON.TENANT") }),
100
						showCloseButton: true,
101
					});
102
					$scope.$emit('handleEmitTenantChanged');
103
				} else {
104
					toaster.pop({
105
						type: "error",
106
						title: $translate.instant("TOASTER.ERROR_ADD_BODY", { template: $translate.instant("COMMON.TENANT") }),
107
						body: $translate.instant(response.data.description),
108
						showCloseButton: true,
109
					});
110
				}
111
			});
112
		}, function () {
113
114
		});
115
		$rootScope.modalInstance = modalInstance;
116
	};
117
118
	$scope.editTenant = function (tenant) {
119
		var modalInstance = $uibModal.open({
120
			windowClass: "animated fadeIn",
121
			templateUrl: 'views/settings/tenant/tenant.model.html',
122
			controller: 'ModalEditTenantCtrl',
123
			resolve: {
124
				params: function () {
125
					return {
126
						tenant: angular.copy(tenant),
127
						tenantTypes: $scope.tenantTypes,
128
						costcenters: angular.copy($scope.costcenters),
129
						contacts: angular.copy($scope.contacts)
130
					};
131
				}
132
			}
133
		});
134
135
		modalInstance.result.then(function (modifiedTenant) {
136
			modifiedTenant.tenant_type_id = modifiedTenant.tenant_type.id;
137
			modifiedTenant.cost_center_id = modifiedTenant.cost_center.id;
138
			modifiedTenant.contact_id = modifiedTenant.contact.id;
139
			if (angular.isDefined(tenant.is_input_counted) == false) {
140
				tenant.is_input_counted = false;
141
			}
142
			if (angular.isDefined(tenant.is_key_tenant) == false) {
143
				tenant.is_key_tenant = false;
144
			}
145
			if (angular.isDefined(tenant.is_in_lease) == false) {
146
				tenant.is_in_lease = false;
147
			}
148
			let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
149
			TenantService.editTenant(modifiedTenant, headers, function (response) {
150
				if (angular.isDefined(response.status) && response.status === 200) {
151
					toaster.pop({
152
						type: "success",
153
						title: $translate.instant("TOASTER.SUCCESS_TITLE"),
154
						body: $translate.instant("TOASTER.SUCCESS_UPDATE_BODY", { template: $translate.instant("COMMON.TENANT") }),
155
						showCloseButton: true,
156
					});
157
					$scope.$emit('handleEmitTenantChanged');
158
				} else {
159
					toaster.pop({
160
						type: "error",
161
						title: $translate.instant("TOASTER.ERROR_UPDATE_BODY", { template: $translate.instant("COMMON.TENANT") }),
162
						body: $translate.instant(response.data.description),
163
						showCloseButton: true,
164
					});
165
				}
166
			});
167
		}, function () {
168
		});
169
		$rootScope.modalInstance = modalInstance;
170
	};
171
172
	$scope.deleteTenant = function (tenant) {
173
		SweetAlert.swal({
174
			title: $translate.instant("SWEET.TITLE"),
175
			text: $translate.instant("SWEET.TEXT"),
176
			type: "warning",
177
			showCancelButton: true,
178
			confirmButtonColor: "#DD6B55",
179
			confirmButtonText: $translate.instant("SWEET.CONFIRM_BUTTON_TEXT"),
180
			cancelButtonText: $translate.instant("SWEET.CANCEL_BUTTON_TEXT"),
181
			closeOnConfirm: true,
182
			closeOnCancel: true
183
		},
184
			function (isConfirm) {
185
				if (isConfirm) {
186
					let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
187
					TenantService.deleteTenant(tenant, headers, function (response) {
188
						if (angular.isDefined(response.status) && response.status === 204) {
189
							toaster.pop({
190
								type: "success",
191
								title: $translate.instant("TOASTER.SUCCESS_TITLE"),
192
								body: $translate.instant("TOASTER.SUCCESS_DELETE_BODY", { template: $translate.instant("COMMON.TENANT") }),
193
								showCloseButton: true,
194
							});
195
							$scope.$emit('handleEmitTenantChanged');
196
						} else {
197
							toaster.pop({
198
								type: "error",
199
								title: $translate.instant("TOASTER.ERROR_DELETE_BODY", { template: $translate.instant("COMMON.TENANT") }),
200
								body: $translate.instant(response.data.description),
201
								showCloseButton: true,
202
							});
203
						}
204
					});
205
				}
206
			});
207
	};
208
209
	$scope.exportTenant = function(tenant) {
210
		let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
211
		TenantService.exportTenant(tenant, headers, function(response) {
212
			if (angular.isDefined(response.status) && response.status === 200) {
213
				$scope.exportdata = JSON.stringify(response.data);
214
				var modalInstance = $uibModal.open({
215
					windowClass: "animated fadeIn",
216
					templateUrl: 'views/common/export.html',
217
					controller: 'ModalExportCtrl',
218
					resolve: {
219
						params: function() {
220
							return {
221
								exportdata: angular.copy($scope.exportdata)
222
							};
223
						}
224
					}
225
				});
226
				modalInstance.result.then(function() {
227
				}, function() {
228
				});
229
				$rootScope.modalInstance = modalInstance;
230
			} else {
231
				$scope.exportdata = null;
232
			}
233
		});
234
	};
235
236
	$scope.cloneTenant = function(tenant){
237
		let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
238
		TenantService.cloneTenant(tenant, headers, function(response) {
239
			if (angular.isDefined(response.status) && response.status === 201) {
240
				toaster.pop({
241
					type: "success",
242
					title: $translate.instant("TOASTER.SUCCESS_TITLE"),
243
					body: $translate.instant("TOASTER.SUCCESS_ADD_BODY", {template: $translate.instant("COMMON.TENANT")}),
244
					showCloseButton: true,
245
				});
246
				$scope.$emit('handleEmitTenantChanged');
247
			}else {
248
				toaster.pop({
249
					type: "error",
250
					title: $translate.instant("TOASTER.ERROR_ADD_BODY", {template: $translate.instant("COMMON.TENANT")}),
251
					body: $translate.instant(response.data.description),
252
					showCloseButton: true,
253
				});
254
			}
255
		});
256
	};
257
258
	$scope.importTenant = function() {
259
		var modalInstance = $uibModal.open({
260
			templateUrl: 'views/common/import.html',
261
			controller: 'ModalImportCtrl',
262
			windowClass: "animated fadeIn",
263
			resolve: {
264
				params: function() {
265
					return {
266
					};
267
				}
268
			}
269
		});
270
		modalInstance.result.then(function(importdata) {
271
			let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
272
			TenantService.importTenant(importdata, headers, function(response) {
273
				if (angular.isDefined(response.status) && response.status === 201) {
274
					toaster.pop({
275
						type: "success",
276
						title: $translate.instant("TOASTER.SUCCESS_TITLE"),
277
						body: $translate.instant("TOASTER.SUCCESS_ADD_BODY", {template: $translate.instant("COMMON.TENANT")}),
278
						showCloseButton: true,
279
					});
280
					$scope.$emit('handleEmitTenantChanged');
281
				} else {
282
					toaster.pop({
283
						type: "error",
284
						title: $translate.instant("TOASTER.ERROR_ADD_BODY", { template: $translate.instant("COMMON.TENANT") }),
285
						body: $translate.instant(response.data.description),
286
						showCloseButton: true,
287
					});
288
				}
289
			});
290
		}, function() {
291
292
		});
293
		$rootScope.modalInstance = modalInstance;
294
	};
295
	let searchDebounceTimer = null;
296
	function safeApply(scope) {
297
		if (!scope.$$phase && !scope.$root.$$phase) {
298
			scope.$apply();
299
		}
300
	}
301
	$scope.searchTenant = function() {
302
		const headers = {
303
			"User-UUID": $scope.cur_user?.uuid,
304
			"Token": $scope.cur_user?.token
305
		};
306
307
		const rawKeyword = $scope.searchTenantKeyword || "";
308
		const trimmedKeyword = rawKeyword.trim();
309
310
		if (searchDebounceTimer) {
311
			clearTimeout(searchDebounceTimer);
312
		}
313
314
		searchDebounceTimer = setTimeout(() => {
315
			if (!trimmedKeyword) {
316
				$scope.getAllTenants();
317
				safeApply($scope);
318
				return;
319
			}
320
321
			TenantService.searchTenants(trimmedKeyword, headers, (response) => {
322
				$scope.tenants = (response.status === 200) ? response.data : [];
323
				$scope.parentmeters = [...$scope.tenants];
324
			});
325
		}, 300);
326
	};
327
	$scope.getAllTenants();
328
	$scope.getAllTenantTypes(); 
329
	$scope.getAllCostCenters();
330
	$scope.getAllContacts();
331
	
332
	$scope.$on('handleBroadcastTenantTypeChanged', function() {
333
		$scope.getAllTenantTypes();
334
	});
335
	
336
	$scope.$on('handleBroadcastTenantChanged', function (event) {
337
		$scope.getAllTenants();
338
	});
339
});
340
341
app.controller('ModalAddTenantCtrl', function ($scope, $uibModalInstance, params) {
342
	$scope.operation = "SETTING.ADD_TENANT";
343
	$scope.tenanttypes = params.tenantTypes;
344
	$scope.costcenters = params.costcenters;
345
	$scope.contacts = params.contacts;
346
	$scope.tenant = {
347
		lease_start_datetime: moment(),
348
		lease_end_datetime: moment()
349
	};
350
	$scope.dtOptions = {
351
		locale: {
352
			format: 'YYYY-MM-DD HH:mm:ss',
353
			applyLabel: "OK",
354
			cancelLabel: "Cancel",
355
		},
356
		timePicker: true,
357
		timePicker24Hour: true,
358
		timePickerIncrement: 15,
359
		singleDatePicker: true,
360
	};
361
	
362
	$scope.isLeaseDateInvalid = function () {
363
		if (!$scope.tenant.lease_start_datetime || !$scope.tenant.lease_end_datetime) {
364
			return false;
365
		}
366
		const start = moment($scope.tenant.lease_start_datetime);
367
		const end = moment($scope.tenant.lease_end_datetime);
368
		if (!start.isValid() || !end.isValid()) {
369
			return false;
370
		}
371
		return end.isSameOrBefore(start);
372
	};
373
374
	$scope.ok = function () {
375
		$scope.tenant.lease_start_datetime = moment($scope.tenant.lease_start_datetime).format().slice(0, 19);
376
		 if ($scope.tenant.lease_end_datetime) {
377
            $scope.tenant.lease_end_datetime = moment($scope.tenant.lease_end_datetime).format().slice(0, 19);
378
        } else {
379
            $scope.tenant.lease_end_datetime = null;
380
        }
381
		$uibModalInstance.close($scope.tenant);
382
	};
383
384
	$scope.cancel = function () {
385
		$uibModalInstance.dismiss('cancel');
386
	};
387
});
388
389
app.controller('ModalEditTenantCtrl', function ($scope, $uibModalInstance, params) {
390
	$scope.operation = "SETTING.EDIT_TENANT";
391
	$scope.tenant = params.tenant;
392
	$scope.tenanttypes = params.tenantTypes;
393
	$scope.costcenters = params.costcenters;
394
	$scope.contacts = params.contacts;
395
	  if (!$scope.tenant.lease_end_datetime) {
396
        $scope.tenant.lease_end_datetime = moment(); 
397
    }
398
	$scope.dtOptions = {
399
		locale: {
400
			format: 'YYYY-MM-DD HH:mm:ss',
401
			applyLabel: "OK",
402
			cancelLabel: "Cancel",
403
		},
404
		timePicker: true,
405
		timePicker24Hour: true,
406
		timePickerIncrement: 15,
407
		singleDatePicker: true,
408
	};
409
	$scope.isLeaseDateInvalid = function () {
410
		if (!$scope.tenant.lease_start_datetime || !$scope.tenant.lease_end_datetime) {
411
			return false;
412
		}
413
		const start = moment($scope.tenant.lease_start_datetime);
414
		const end = moment($scope.tenant.lease_end_datetime);
415
		if (!start.isValid() || !end.isValid()) {
416
			return false;
417
		}
418
		return end.isSameOrBefore(start);
419
	};
420
	
421
	$scope.ok = function () {
422
		$scope.tenant.lease_start_datetime = moment($scope.tenant.lease_start_datetime).format().slice(0, 19);
423
		 if ($scope.tenant.lease_end_datetime) {
424
            $scope.tenant.lease_end_datetime = moment($scope.tenant.lease_end_datetime).format().slice(0, 19);
425
        } else {
426
            $scope.tenant.lease_end_datetime = null;
427
        }
428
		$uibModalInstance.close($scope.tenant);
429
	};
430
431
	$scope.cancel = function () {
432
		$uibModalInstance.dismiss('cancel');
433
	};
434
});