rsanchez
2014-10-16 4d18a46ee3ada751517f9bf767d5057a3bf5eb9e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
(function() {
   'use strict';
   
   var LIC_STATUS = {
           CREATED: 1,
            REQUESTED: 2,
            PREACTIVE: 3,
            ACTIVE: 4,
            CANCELED: 5
   }
   
   var ACTIONS_BY_STATUS = {
            activate: [LIC_STATUS.REQUESTED, LIC_STATUS.PREACTIVE],
            send: [LIC_STATUS.ACTIVE, LIC_STATUS.PREACTIVE],
            download: [LIC_STATUS.ACTIVE, LIC_STATUS.PREACTIVE],
            request: [LIC_STATUS.CREATED, LIC_STATUS.REQUESTED],
            cancel: [LIC_STATUS.REQUESTED, LIC_STATUS.PREACTIVE, LIC_STATUS.ACTIVE],
            'delete': [LIC_STATUS.CREATED, LIC_STATUS.CANCELED],
    }
      var HTTP_ERRORS = {
               401: "Unathorized action",
               403: "Forbidden action",
               500: "Server error",
               404: "Element not found"
       }
   var app = angular.module('securis');
   
   app.directive('fileLoader',
               function($timeout, $parse) {
                   return {
                       restrict : 'A', // only activate on element attribute
                       require : '',
                       link : function(scope, element, attrs) {
                            console.log('scope.license: ' + scope.$parent.license);
                            var setter = $parse(attrs.fileLoader).assign;
                           element.bind('change', function(evt) {
                               if (!window.FileReader) { // Browser is not compatible
                                   BootstrapDialog.alert($L.get("Open your .req file with a text editor and copy&paste the content in the form text field?"));
                                   return;
                               }
                               //console.log('scope.license: ' + scope.$parent.license);
                               var field = $parse(attrs.fileLoader);
                               //console.log('field: ' + field);
                               var fileList = evt.target.files;
                               if (fileList != null && fileList[0]) {
                                   var reader = new FileReader();
                                    reader.onerror = function(data) {
                                        setter(scope.$parent, 'ERROR');
                                        //scope.$apply();
                                    }
                                    reader.onload = function(data) {
                                        setter(scope.$parent, reader.result);
                                        //scope.$apply();
                                    }
                                    
                                    reader.readAsText(fileList[0]);       
                               } else {
                                   setter(scope.$parent, '');
                                    //scope.$apply();
                               }
                           });
                           
                       }
                   };
               });
   app.controller('PackAndLicensesCtrl', [
                                   '$scope',
                                   '$http',
                                   'toaster',
                                   '$store',
                                   '$L',
                  function($scope, $http, toaster, $store, $L) {
                       $store.set('location', '/licenses');
                                       
                        $scope.maxLengthErrorMsg = function(displayname, fieldMaxlength) {
                            return $L.get("{0} length is too long (max: {1}).", $L.get(displayname), fieldMaxlength);
                        }
                        $scope.mandatoryFieldErrorMsg = function(displayname) {
                            return $L.get("'{0}' is required.", $L.get(displayname));
                        }
                        $scope.ellipsis = function(txt, len) {
                            if (!txt || txt.length <= len) return txt;
                            return txt.substring(0, len) + '...';
                        }
                        $scope.currentPack = $store.get('currentPack');
                  }]);
   
   app.controller('PacksCtrl', [
           '$scope',
           '$http',
           '$resource',
           'toaster',
           'Catalogs',
           '$store',
           '$L',
           function($scope, $http, $resource, toaster, Catalogs, $store, $L) {
               var packResource = $resource('/pack/:packId', {
                   packId : '@id'
               });
               var PACK_STATUS = [
                                  {id: 'PE', label: $L.get('Pending')},
                                  {id: 'AC', label: $L.get('Active')},
                                  {id: 'OH', label: $L.get('On Hold')},
                                  {id: 'EX', label: $L.get('Expired')},
                                  {id: 'CA', label: $L.get('Cancelled')}
                                  ];
               $scope.mandatory = {
                       code: true,
                       num_licenses: true,
                       organization_id: true,
                       license_type_id: true
               }
               $scope.maxlength = {
                       code: 50,
                       comments: 1024
               }
               $scope.refs = {};
                Catalogs.init().then(function() {
                    var refFields = [{resource: 'organization', name: 'organization_id'},{resource: 'licensetype', name: 'license_type_id'}]; 
                    Catalogs.loadRefs(function(refs) {
                           $scope.refs = refs;
                           $scope.refs['pack_status'] = PACK_STATUS;
                       }, refFields);
                }); 
               // Used to create the form with the appropriate data
               $scope.isNew = undefined;
               // Selected pack from listing
               // pack is the edited pack, in creation contains the data for the new pack
               $scope.pack = null;
               $scope.packs = packResource.query();
               
               var _savePackData = function() {
                   var _success = function() {
                       if (!$scope.isNew) $scope.showForm = false;
                       $scope.packs = packResource.query();
                       toaster.pop('success', Catalogs.getName(), $L.get("Pack '{0}' {1} successfully", $scope.pack.code, $scope.isNew ? $L.get("created") : $L.get("updated")));
                   }
                   var _error =  function(error) {
                        console.log(error);
                       toaster.pop('error', Catalogs.getName(), $L.get("Error {0} pack '{1}'. Reason: {2}", $scope.isNew ? $L.get("creating") : $L.get("updating"), $scope.pack.code, $L.get(error.headers('X-SECURIS-ERROR'))));
                   }
                   packResource.save($scope.pack, _success, _error);
               } 
               $scope.save = function() {
                   if ($scope.pack.num_activations > 0) {
                       BootstrapDialog.confirm($L.get("The pack '{0}' has active licenses, Do you want to modify it ?", $scope.pack.code), function(answer){
                           if (answer) {
                               _savePackData();
                           }
                       });
                   } else {
                       _savePackData();
                   }
               }
               
               $scope.newPack = function() {
                   $scope.isNew = true;
                   $scope.showForm = true;
                   $scope.pack = {
                            license_preactivation: true,
                            status: 'PE',
                            num_licenses: 1,
                            license_type_id: null,
                            organization_id: null  //!$scope.refs.organization_id || !$scope.refs.organization_id.length ? null : $scope.refs.organization_id[0].id
                   }
                   setTimeout(function() {
                        $('#code').focus();
                    }, 0);
               }
                $scope.editPack = function(selectedPack) {
                    $scope.isNew = false;
                    $scope.showForm = true;
                    $scope.pack = selectedPack;
                   setTimeout(function() {
                        $('#code').focus();
                    }, 0);
                }
                $scope.deletePack = function(selectedPack) {
                    $scope.showForm = false;
                    BootstrapDialog.confirm($L.get("The pack '{0}' will be deleted, are you sure?", selectedPack.code), function(result){
                        if(result) {
                            var promise = packResource.remove({}, {id: selectedPack.id}).$promise;
                            promise.then(function(data) {
                                $scope.selectPack(null);
                                $scope.packs = packResource.query();
                                toaster.pop('success', Catalogs.getName(), $L.get("Pack '{0}' deleted successfully", selectedPack.code));
                            },function(error) {
                                console.log(error);
                                toaster.pop('error', Catalogs.getName(), $L.get("Error deleting pack, reason: {0}. Details: {1}", $L.get(HTTP_ERRORS[error.status]), error.headers('X-SECURIS-ERROR')), 10000);
                            });
                        }
                    });
                    $scope.isNew = false;
                }
                $scope.cancel = function() {
                    $scope.showForm = false;
                }
               $scope.selectPack = function(pack) {
                   $scope.$parent.currentPack = pack;
                   $store.put('currentPack', pack);
                   $scope.$parent.$broadcast('pack_changed', pack);
               }
               
               $scope.createMetadataRow = function() {
                   if (!$scope.formu.metadata) {
                       $scope.formu.metadata = [];
                   }
                   $scope.formu.metadata.push({key: '', value: '', mandatory: true});
               }
               $scope.removeMetadataKey = function(row_md) {
                   $scope.formu.metadata.splice( $scope.formu.metadata.indexOf(row_md), 1 );
               }
               $scope.updateMetadata = function() {
                   // Called when Application ID change in current field
                   var newLTId = $scope.pack['license_type_id'];
                   if (newLTId) {
                       // Only if there is a "valid" value selected we should update the metadata
                       Catalogs.getResource('licensetype').get({licenseTypeId: newLTId}).$promise.then(function(lt) {
                           $scope.pack.metadata = [];
                           lt.metadata.forEach(function(md) {
                               $scope.pack.metadata.push({
                                   key: md.key,
                                   value: md.value,
                                   readonly: !!md.value,
                                   mandatory: md.mandatory
                               });
                           });
                       });
                   }
               }
           } ]);
      app.controller('LicensesCtrl', [
                                      '$scope',
                                      '$http',
                                      '$resource',
                                      'toaster',
                                      '$store',
                                      '$L',
                                      function($scope, $http, $resource, toaster, $store, $L) {
                                          $scope.$on('pack_changed', function(evt, message) {
                                               $scope.licenses = licenseResource.query({packId: $scope.currentPack.id});
                                              if ($scope.showForm) {
                                                  if ($scope.isNew) {
                                                      $scope.license.pack_id = $scope.currentPack.id
                                                  } else {
                                                      $scope.showForm = false;    
                                                  }
                                              }
                                          })
                                              
                                          var licenseResource = $resource('/license/:licenseId', {
                                              licenseId : '@id'
                                          }, {
                                              save_w_upload: {
                                                  method: "POST",
                                                  transformRequest: function(data, headersGetter) {
                                                      // To use an object without FormData, follow: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest?redirectlocale=en-US&redirectslug=DOM%2FXMLHttpRequest%2FUsing_XMLHttpRequest#Submitting_forms_and_uploading_files
                                                      var formData = new FormData();
                                                      angular.forEach(data, function(value, key) {
                                                          if (key !== 'request_data')
                                                              formData.append(key, value)
                                                           else
                                                               formData.append(key, $('input#request_data_file').get(0).files[0]);
                                                      })
                                                      
                                                      return formData;
                                                  },
                                                  headers: {
                                                      'Content-Type': undefined
                                                  }
                                              }
                                          });
                                          $scope.mandatory = {
                                                  code: true
                                          }
                                          $scope.maxlength = {
                                                  code: 50,
                                                  comments: 1024
                                          }
                                          $scope.refs = {};
                                          // Used to create the form with the appropriate data
                                          $scope.isNew = undefined;
                                          // Selected license from listing
                                          // license is the edited license, in creation contains the data for the new license
                                          $scope.license = null;
                                          if ($scope.currentPack)
                                              $scope.licenses = licenseResource.query({packId: $scope.currentPack.id});
                                          
//                                           $(document).on('change', '#request_data_file', function(newValue, oldValue) {
//                                              console.log('File changed!!!!'); 
//                                               var reader = new FileReader();
//                                               reader.onload = function(data) {
//                                                   console.log('LOAD complete: ' + data);
//                                                   console.log('LOAD reader.result: ' + reader.result);
//                                                   $('input#request_data').val(reader.result)
//                                               }
//                                               console.log('file: ' + $('input#request_data_file').get(0).files[0]);
//                                               console.log('file2: ' + $scope.request_data_file);
//                                               reader.readAsText($('input#request_data_file').get(0).files[0]);                                                
//                                           });
                                          
                                          $scope.save = function() {
                                              $( "form#licenseForm" )
                                              .attr( "enctype", "multipart/form-data" )
                                              .attr( "encoding", "multipart/form-data" );
                                              var _success = function() {
                                                  if (!$scope.isNew) $scope.showForm = false;
                                                  $scope.licenses = licenseResource.query({packId: $scope.currentPack.id});
                                              }
                                              licenseResource.save_w_upload($scope.license, _success)
                                          }
                                          
                                          $scope.newLicense = function() {
                                              if (!$scope.currentPack) {
                                                  BootstrapDialog.show({
                                                      title: $L.get('New license'),
                                                      type: BootstrapDialog.TYPE_WARNING,
                                                      message: $L.get('Please, select a pack before to create a new license'),
                                                      buttons: [{
                                                          label: 'OK',
                                                          action: function(dialog) {
                                                              dialog.close();
                                                          }
                                                      }]
                                                  });
                                                  return;
                                              }
                                                  
                                              $scope.isNew = true;
                                              $scope.showForm = true;
                                              $scope.license = {
                                                      pack_id: $scope.currentPack.id
                                              }
                                             setTimeout(function() {
                                                  $('#licenseForm * #code').focus();
                                              }, 0);
                                          }
                                          $scope.editLicense = function(selectedlicense) {
                                              $scope.isNew = false;
                                              $scope.showForm = true;
                                              $scope.license = selectedlicense;
                                             setTimeout(function() {
                                                  $('#licenseForm * #code').focus();
                                              }, 0);
                                          }
                                          $scope.deletelicense = function(selectedlicense) {
                                              $scope.showForm = false;
                                              BootstrapDialog.confirm($L.get("The license '{0}' will be deleted, are you sure?", selectedlicense.code), function(result){
                                                  if(result) {
                                                      var promise = licenseResource.remove({}, {id: selectedlicense.id}).$promise;
                                                      promise.then(function(data) {
                                                          $scope.selectlicense(null);
                                                          $scope.licenses = licenseResource.query({packId: $scope.currentPack.id});
                                                          toaster.pop('success', Catalogs.getName(), $L.get("License '{0}' deleted successfully", selectedlicense.code));
                                                      },function(error) {
                                                          console.log(error);
                                                          toaster.pop('error', Catalogs.getName(), $L.get("Error deleting license, reason: {0}. Details: {1}", $L.get(HTTP_ERRORS[error.status]), error.headers('X-SECURIS-ERROR')), 10000);
                                                      });
                                                  }
                                              });
                                              $scope.isNew = false;
                                          }
                                          $scope.cancel = function() {
                                              $scope.showForm = false;
                                          }
                                          
                                           $scope.showStatus = function(lic) {
                                               
                                           }
                                           $scope.showStatusLong = function(license) {
                                               
                                           }
                                           $scope.isActionVisible = function(action, lic) {
                                               var validStatuses = ACTIONS_BY_STATUS[action];
                                               return lic && validStatuses.indexOf(lic.status) !== -1;
                                           }
                                          
                                      } ]);
})();