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