Merge "Yangman - clear indetifiers, fix boolean type, fix history req sent data"
[dlux.git] / modules / yangman-resources / src / main / resources / yangman / controllers / requests-list.controller.js
1 define([
2     'app/yangman/controllers/save-req-dialog.controller',
3     'app/yangman/controllers/edit-collection-dialog.controller',
4     'app/yangman/services/handle-file.services',
5 ], function (SaveReqDialogCtrl, EditCollectionDialogCtrl) {
6     'use strict';
7
8     angular.module('app.yangman').controller('RequestsListCtrl', RequestsListCtrl);
9
10     RequestsListCtrl.$inject = [
11         '$filter', '$mdDialog', '$scope', 'HandleFileService', 'PathUtilsService', 'RequestsService', 'YangmanService',
12         'YangmanDesignService',
13     ];
14
15     function RequestsListCtrl($filter, $mdDialog, $scope, HandleFileService, PathUtilsService, RequestsService,
16                               YangmanService, YangmanDesignService) {
17         var vm = this;
18
19         vm.collectionList = RequestsService.createEmptyCollectionList('yangman_collectionsList');
20         vm.collectionsSortAsc = true;
21         vm.mainList = null;
22         vm.requestList = RequestsService.createEmptyHistoryList('yangman_requestsList');
23         vm.search = '';
24
25         // methods
26         vm.clearFilter = clearFilter;
27         vm.clearHistoryList = clearHistoryList;
28         vm.clearCollectionList = clearCollectionList;
29         vm.colMatchingReqsCount = colMatchingReqsCount;
30         vm.deselectAllRequests = deselectAllRequests;
31         vm.downloadCollection = downloadCollection;
32         vm.executeRequest = executeRequest;
33         vm.fakeFilter = fakeFilter;
34         vm.filterCol = filterCol;
35         vm.filterColName = filterColName;
36         vm.filterReq = filterReq;
37         vm.init = init;
38         vm.loadRequests = loadRequests;
39         vm.readCollectionFromFile = readCollectionFromFile;
40         vm.refreshCollections = refreshCollections;
41         vm.selectAllRequests = selectAllRequests;
42         vm.selectRequest = selectRequest;
43         vm.showData = showData;
44         vm.showDgDeleteCollection = showDgDeleteCollection;
45         vm.showDgDeleteRequests = showDgDeleteRequests;
46         vm.showDgEditCollection = showDgEditCollection;
47         vm.showDgSaveReq = showDgSaveReq;
48         vm.toggleCollectionsSort = toggleCollectionsSort;
49         vm.showForm = showForm;
50
51         $scope.$on('YANGMAN_REFRESH_COLLECTIONS', loadCollectionRequest);
52         $scope.$on('YANGMAN_REFRESH_HISTORY', loadHistoryRequests);
53
54         loadRequests();
55
56         /**
57          * Save request obje to collection from other controller
58          * @param reqObj
59          */
60         function saveRequestFromExt(event, args) {
61             vm.showDgSaveReq(args.params.event, args.params.reqObj, false);
62         }
63
64
65         /**
66          * Clear history requests list and save to storage
67          */
68         function clearHistoryList(ev) {
69             var confirm = $mdDialog.confirm()
70                 .title($filter('translate')('YANGMAN_DELETE_HISTORY_CONFIRM_TITLE'))
71                 .textContent($filter('translate')('YANGMAN_DELETE_HISTORY_CONFIRM_TEXT'))
72                 .ariaLabel($filter('translate')('YANGMAN_DELETE_HISTORY_CONFIRM_TITLE'))
73                 .targetEvent(ev)
74                 .ok($filter('translate')('YANGMAN_OK'))
75                 .cancel($filter('translate')('YANGMAN_CANCEL'));
76
77             $mdDialog.show(confirm).then(function (){
78                 vm.requestList.clear();
79                 vm.requestList.saveToStorage();
80                 $scope.rootBroadcast('YANGMAN_REFRESH_HISTORY');
81             });
82         }
83
84         /**
85          * Clear collections requests list and save to storage
86          */
87         function clearCollectionList(ev) {
88             var confirm = $mdDialog.confirm()
89                 .title($filter('translate')('YANGMAN_DELETE_COLLECTION_CONFIRM_TITLE'))
90                 .textContent($filter('translate')('YANGMAN_DELETE_COLLECTION_CONFIRM_TEXT'))
91                 .ariaLabel($filter('translate')('YANGMAN_DELETE_COLLECTION_CONFIRM_TITLE'))
92                 .targetEvent(ev)
93                 .ok($filter('translate')('YANGMAN_OK'))
94                 .cancel($filter('translate')('YANGMAN_CANCEL'));
95
96             $mdDialog.show(confirm).then(function (){
97                 vm.collectionList.clear();
98                 vm.collectionList.saveToStorage();
99                 $scope.rootBroadcast('YANGMAN_REFRESH_COLLECTIONS');
100             });
101         }
102
103         /**
104          * Create history request from other ctrl
105          * @param broadcastEvent
106          * @param params
107          */
108         function saveBcstedHistoryRequest(broadcastEvent, params) {
109             vm.requestList.addRequestToList(params.params);
110             vm.requestList.groupListByDate();
111             vm.requestList.saveToStorage();
112             loadHistoryRequests();
113
114             (params.cbk || angular.noop)();
115         }
116
117         /**
118          * Clear value of input file used to import collection
119          */
120         function clearFileInputValue(){
121             angular.element(document).find('#importCollection').val('');
122         }
123
124         /**
125          * Importing collection from a file
126          * todo: error handling - msgs for user
127          * @param $fileContent
128          */
129         function readCollectionFromFile($fileContent) {
130             var data = $fileContent,
131                 checkArray = [
132                     'sentData',
133                     'receivedData',
134                     'path',
135                     'collection',
136                     'method',
137                     'status',
138                     'name',
139                 ];
140
141             if (data && YangmanService.validateFile(data, checkArray)){
142                 try {
143                     vm.collectionList.loadListFromFile(data);
144                     vm.collectionList.saveToStorage();
145                     clearFileInputValue();
146                 }
147                 catch (e) {
148                     clearFileInputValue();
149                     console.error('DataStorage error:', e);
150                 }
151             }
152             else {
153                 clearFileInputValue();
154             }
155         }
156
157         function toggleCollectionsSort() {
158             vm.collectionsSortAsc = !vm.collectionsSortAsc;
159         }
160
161         /**
162          * Export collection to json file
163          * @param {Collection} collection
164          */
165         function downloadCollection(collection) {
166
167             var cListJSON = vm.collectionList.getCollectionInJSON(collection.name);
168
169             HandleFileService.downloadFile(collection.name + '.json', cListJSON, 'json', 'charset=utf-8',
170                 function (){},
171                 function (e){
172                     console.error('ExportCollection error:', e);
173                 }
174             );
175         }
176
177         /**
178          * Fill request form in right panel with request data
179          * @param reqObj
180          */
181         function showForm(reqObj) {
182             var data = reqObj.method === 'GET' ? reqObj.receivedData : reqObj.sentData;
183
184             $scope.rootBroadcast('YANGMAN_SET_ERROR_DATA', reqObj.receivedData.hasOwnProperty('errors') ? reqObj.receivedData : {});
185
186             $scope.rootBroadcast('YANGMAN_FILL_NODE_FROM_REQ', { requestUrl: reqObj.path, requestData: data },
187                 function (){
188                     $scope.setRightPanelSection('form');
189                     $scope.rootBroadcast('YANGMAN_HEADER_INIT', {
190                         path: reqObj.path,
191                         method: reqObj.method,
192                         statusObj: {
193                             status: reqObj.responseStatus,
194                             statusText: reqObj.responseStatusText,
195                             time: reqObj.responseTime,
196                         },
197                     });
198
199                     if ( $scope.node ) {
200                         // try to fill node
201                         YangmanService.fillNodeFromResponse($scope.node, data);
202                         $scope.node.expanded = true;
203                     }
204
205                 }
206             );
207
208         }
209
210         /**
211          * Force request header to execute request with data from reqObj
212          * @param reqObj
213          */
214         function executeRequest(reqObj) {
215             $scope.setRightPanelSection('req-data');
216             $scope.rootBroadcast(
217                 'YANGMAN_HEADER_INIT',
218                 { path: reqObj.path, method: reqObj.method },
219                 function (){
220                     $scope.rootBroadcast(
221                         'YANGMAN_EXECUTE_WITH_DATA',
222                         { data: reqObj.sentData },
223                         function (historyReq){
224                             showData(historyReq);
225                         }
226                     );
227                 }
228             );
229
230         }
231
232
233         /**
234          * Show current reqObj json data in right panel section
235          * @param reqObj
236          * @param dataType
237          */
238         function showData(reqObj) {
239
240             $scope.setRightPanelSection('req-data');
241             $scope.setJsonView(true, reqObj.method !== 'GET');
242
243             $scope.rootBroadcast('YANGMAN_HEADER_INIT', {
244                 path: reqObj.path,
245                 method: reqObj.method,
246                 statusObj: {
247                     status: reqObj.responseStatus,
248                     statusText: reqObj.responseStatusText,
249                     time: reqObj.responseTime,
250                 },
251             });
252
253             $scope.rootBroadcast(
254                 'YANGMAN_SET_ERROR_DATA',
255                 reqObj.receivedData && reqObj.receivedData.hasOwnProperty('errors') ? reqObj.receivedData : {}
256             );
257
258             $scope.rootBroadcast(
259                 'YANGMAN_SET_CODEMIRROR_DATA_SENT',
260                 { data: reqObj.setDataForView(reqObj.sentData) }
261             );
262             $scope.rootBroadcast(
263                 'YANGMAN_SET_CODEMIRROR_DATA_RECEIVED',
264                 { data: reqObj.setDataForView(reqObj.receivedData) }
265             );
266
267             var data = reqObj.method === 'GET' ? reqObj.receivedData : reqObj.sentData;
268
269             $scope.rootBroadcast('YANGMAN_FILL_NODE_FROM_REQ', { requestUrl: reqObj.path, leftpanel: 0},
270                 function (){
271                     if ( $scope.node ) {
272                         // try to fill node
273                         YangmanService.fillNodeFromResponse($scope.node, data);
274                         $scope.node.expanded = true;
275                     }
276
277                 }
278             );
279         }
280
281         /**
282          * Clear current ctrl search value
283          */
284         function clearFilter(){
285             vm.search = '';
286         }
287
288         /**
289          * Dialog for deleting either selected requests or reqObj
290          *
291          * @param ev
292          * @param reqObj
293          */
294         function showDgDeleteRequests(ev, reqObj){
295
296             var confirm = $mdDialog.confirm()
297                 .title($filter('translate')('YANGMAN_DELETE_REQ_CONFIRM_TITLE'))
298                 .textContent($filter('translate')('YANGMAN_DELETE_REQ_CONFIRM_TEXT'))
299                 .ariaLabel($filter('translate')('YANGMAN_DELETE_REQ_CONFIRM_TITLE'))
300                 .targetEvent(ev)
301                 .ok($filter('translate')('YANGMAN_OK'))
302                 .cancel($filter('translate')('YANGMAN_CANCEL'));
303
304             YangmanDesignService.disableMdMenuItem(ev);
305
306             $mdDialog.show(confirm).then(function (){
307                 if (reqObj){
308                     vm.mainList.deleteRequestItem(reqObj);
309                 }
310                 else {
311                     vm.mainList.selectedRequests.forEach(function (elem){
312                         vm.mainList.deleteRequestItem(elem);
313                     });
314                 }
315                 vm.mainList.saveToStorage();
316                 $scope.rootBroadcast('YANGMAN_REFRESH_HISTORY');
317             }, function (){
318                 YangmanDesignService.enableMdMenuItem(ev);
319             });
320         }
321
322
323         /**
324          * Dialog for deleting collection and refreshing collections
325          * @param ev
326          * @param collObj
327          */
328         function showDgDeleteCollection(ev, collObj){
329             var confirm = $mdDialog.confirm()
330                 .title($filter('translate')('YANGMAN_DELETE_COL_CONFIRM_TITLE') + ' ' + collObj.name + '?')
331                 .textContent($filter('translate')('YANGMAN_DELETE_COL_CONFIRM_TEXT'))
332                 .ariaLabel($filter('translate')('YANGMAN_DELETE_COL_CONFIRM_TITLE'))
333                 .targetEvent(ev)
334                 .ok($filter('translate')('YANGMAN_OK'))
335                 .cancel($filter('translate')('YANGMAN_CANCEL'));
336
337             YangmanDesignService.disableMdMenuItem(ev);
338
339             $mdDialog.show(confirm).then(function (){
340                 vm.collectionList.deleteCollection(collObj);
341                 vm.collectionList.saveToStorage();
342                 refreshCollections();
343             }, function (){
344                 YangmanDesignService.enableMdMenuItem(ev);
345             });
346         }
347
348         /**
349          * Check if reqObj matches current search value
350          * @param reqObj
351          * @returns {boolean}
352          */
353         function filterReq(reqObj){
354             return reqObj.path.indexOf(vm.search) !== -1;
355         }
356
357         /**
358          * Check if collection name matches current search value or any collection req matches
359          * @param colObj
360          */
361         function filterCol(colObj){
362             return filterColName(colObj) || colObj.data.some(filterReq);
363         }
364
365         /**
366          * Get count of requests matching filter in collection colObj
367          * @param colObj
368          * @returns {*}
369          */
370         function colMatchingReqsCount(colObj){
371             return colObj.data.filter(vm.filterReq).length;
372         }
373
374         /**
375          * Check if collection name matches current filter
376          * @param colObj
377          * @returns {boolean}
378          */
379         function filterColName(colObj){
380             return colObj.name.indexOf(vm.search) !== -1;
381         }
382
383         /**
384          * Returns true
385          * @returns {boolean}
386          */
387         function fakeFilter(){
388             return true;
389         }
390
391         /**
392          * Show dialog for saving reqObj to collection (used for duplicate req too)
393          * @param ev
394          * @param reqObj
395          * @param duplicate
396          */
397         function showDgSaveReq(ev, reqObj, duplicate){
398
399             $mdDialog.show({
400                 controller: SaveReqDialogCtrl,
401                 controllerAs: 'dialog',
402                 templateUrl: $scope.globalViewPath + 'leftpanel/save-req-dialog.tpl.html',
403                 parent: angular.element('#yangmanModule'),
404                 targetEvent: ev,
405                 clickOutsideToClose: true,
406                 locals: {
407                     requests: reqObj ? [reqObj] : vm.requestList.selectedRequests,
408                     collectionNames: vm.collectionList.getCollectionNames(),
409                     duplicate: duplicate || false,
410                 },
411             }).then(saveRequests);
412         }
413
414         /**
415          * Add each request from requests array to collectionList and save
416          * @param requests
417          */
418         function saveRequests(requests){
419             requests.forEach(function (reqObj){
420                 vm.collectionList.addRequestToList(reqObj);
421                 vm.collectionList.saveToStorage();
422                 refreshCollections();
423             });
424         }
425
426
427         /**
428          * Dialog for editing collection name (used for duplicating collection too)
429          * @param ev
430          * @param collection
431          * @param {boolean} duplicate
432          */
433         function showDgEditCollection(ev, collection, duplicate){
434             $mdDialog.show({
435                 controller: EditCollectionDialogCtrl,
436                 controllerAs: 'dialog',
437                 templateUrl: $scope.globalViewPath + 'leftpanel/edit-collection-dialog.tpl.html',
438                 parent: angular.element('#yangmanModule'),
439                 targetEvent: ev,
440                 clickOutsideToClose: true,
441                 locals: {
442                     collection: collection,
443                     allCollections: vm.collectionList.collections,
444                     duplicate: duplicate,
445                 },
446             }).then(duplicate ? duplicateCollection : changeCollectionName);
447         }
448
449         /**
450          * Rename collection
451          * @param {array} names 0. element is old name, 1. element is new name
452          */
453         function changeCollectionName(names){
454             vm.collectionList.renameCollection(names[0], names[1]);
455             vm.collectionList.saveToStorage();
456             refreshCollections();
457         }
458
459         /**
460          * Create collection duplicate, save and refresh collections
461          * @param {array} names 0. element is old name, 1. element is new name
462          */
463         function duplicateCollection(names){
464             vm.collectionList.duplicateCollection(names[0], names[1]);
465             vm.collectionList.saveToStorage();
466             refreshCollections();
467         }
468
469
470         function selectNewestRequest() {
471             vm.mainList.toggleReqSelection(true, vm.mainList.getNewestRequest());
472         }
473
474         /**
475          *
476          * @param list collectionList or requestList object
477          */
478         function init(list){
479             vm.mainList = list;
480
481             if (list === vm.requestList){
482                 // saving from request header after execution
483                 $scope.$on('YANGMAN_SAVE_EXECUTED_REQUEST', saveBcstedHistoryRequest);
484                 // saving from request header
485                 $scope.$on('YANGMAN_SAVE_REQUEST_TO_COLLECTION', saveRequestFromExt);
486                 // select newest request
487                 $scope.$on('YANGMAN_SELECT_THE_NEWEST_REQUEST', selectNewestRequest);
488
489             } else {
490                 // saving collections expanded status on refresh
491                 $scope.$on('YANGMAN_REFRESH_AND_EXPAND_COLLECTIONS', function(event, params){
492                     $scope.rootBroadcast('YANGMAN_REFRESH_COLLECTIONS');
493                     (params.cbk || angular.noop)();
494                 });
495             }
496
497         }
498
499         /**
500          * Loading history request and grouping by date
501          */
502         function loadHistoryRequests(){
503             vm.requestList.loadListFromStorage();
504             vm.requestList.groupListByDate();
505         }
506
507         /**
508          * Loading collections
509          */
510         function loadCollectionRequest(){
511             vm.collectionList.loadListFromStorage();
512         }
513
514         /**
515          * Loading both history and collections reqs
516          */
517         function loadRequests(){
518             loadHistoryRequests();
519             loadCollectionRequest();
520         }
521
522         /**
523          * Request in list selection
524          * For history reqs it is possible multiselect, thats why event.ctrlKey is used
525          * @param event
526          * @param requestObj
527          */
528         function selectRequest(event, requestObj){
529             vm.mainList.toggleReqSelection(!event.ctrlKey, requestObj);
530             $scope.setHistoryReqsSelected(vm.requestList.selectedRequests.length > 0);
531             if (!event.ctrlKey){
532                 vm.showData(requestObj);
533             }
534         }
535
536         /**
537          * Deselect history requests
538          */
539         function deselectAllRequests(){
540             vm.mainList.deselectReqs();
541         }
542
543         /**
544          * Select history requests
545          */
546         function selectAllRequests(){
547             deselectAllRequests();
548             vm.mainList.dateGroups.forEach(function(group){
549                 vm.mainList.selectReqs(group.requests);
550             });
551         }
552
553         /**
554          * Refresh and expand collections
555          */
556         function refreshCollections(){
557             var collectionNames = vm.collectionList.getExpandedCollectionNames();
558             $scope.rootBroadcast('YANGMAN_REFRESH_AND_EXPAND_COLLECTIONS', null, function(){
559                 vm.collectionList.expandCollectionByNames(collectionNames);
560             });
561         }
562
563     }
564
565 });