]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/reporter/template/app.js
LP#1721807: fix webstaff report templates that have might_have and has_many joins
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / reporter / template / app.js
1 /*
2  * Report template builder
3  */
4
5 angular.module('egReporter',
6     ['ngRoute', 'ui.bootstrap', 'egCoreMod', 'egUiMod', 'egGridMod', 'egReportMod', 'treeControl', 'ngToast'])
7
8 .config(['ngToastProvider', function(ngToastProvider) {
9   ngToastProvider.configure({
10     verticalPosition: 'bottom',
11     animation: 'fade'
12   });
13 }])
14
15 .config(function($routeProvider, $locationProvider, $compileProvider) {
16     $locationProvider.html5Mode(true);
17     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|mailto|blob):/); // grid export
18         
19     var resolver = {delay : function(egStartup) {return egStartup.go()}};
20
21     $routeProvider.when('/reporter/template/clone/:folder/:id', {
22         templateUrl: './reporter/t_edit_template',
23         controller: 'ReporterTemplateEdit',
24         resolve : resolver
25     });
26
27     $routeProvider.when('/reporter/legacy/template/clone/:folder/:id', {
28         templateUrl: './reporter/t_legacy',
29         controller: 'ReporterTemplateLegacy',
30         resolve : resolver
31     });
32
33     $routeProvider.when('/reporter/template/new/:folder', {
34         templateUrl: './reporter/t_edit_template',
35         controller: 'ReporterTemplateEdit',
36         resolve : resolver
37     });
38
39     $routeProvider.when('/reporter/legacy/main', {
40         templateUrl: './reporter/t_legacy',
41         controller: 'ReporterTemplateLegacy',
42         resolve : resolver
43     });
44
45     // default page
46     $routeProvider.otherwise({redirectTo : '/reporter/legacy/main'});
47 })
48
49 /**
50  * controller for legacy template stuff
51  */
52 .controller('ReporterTemplateLegacy',
53        ['$scope','$routeParams','$location','egCore',
54 function($scope , $routeParams , $location , egCore) {
55
56     var template_id = $routeParams.id;
57     var folder_id = $routeParams.folder;
58
59     $scope.rurl = '/reports/oils_rpt.xhtml?ses=' + egCore.auth.token();
60
61     if (folder_id) {
62         $scope.rurl = '/reports/oils_rpt_builder.xhtml?ses=' +
63                         egCore.auth.token() + '&folder=' + folder_id;
64
65         if (template_id) $scope.rurl += '&ct=' + template_id;
66     }
67
68 }])
69
70 /**
71  * Uber-controller for template editing
72  */
73 .controller('ReporterTemplateEdit',
74        ['$scope','$q','$routeParams','$location','$timeout','$window','egCore','$uibModal','egPromptDialog',
75         'egGridDataProvider','egReportTemplateSvc','$uibModal','egConfirmDialog','egSelectDialog','ngToast',
76 function($scope , $q , $routeParams , $location , $timeout , $window,  egCore , $uibModal , egPromptDialog ,
77          egGridDataProvider , egReportTemplateSvc , $uibModal , egConfirmDialog , egSelectDialog , ngToast) {
78
79     function values(o) { return Object.keys(o).map(function(k){return o[k]}) };
80
81     var template_id = $routeParams.id;
82     var folder_id = $routeParams.folder;
83
84     $scope.grid_display_fields_provider = egGridDataProvider.instance({
85         get : function (offset, count) {
86             return this.arrayNotifier(egReportTemplateSvc.display_fields, offset, count);
87         }
88     });
89     $scope.grid_filter_fields_provider = egGridDataProvider.instance({
90         get : function (offset, count) {
91             return this.arrayNotifier(egReportTemplateSvc.filter_fields, offset, count);
92         }
93     });
94
95     var dgrid = $scope.display_grid_controls = {};
96     var fgrid = $scope.filter_grid_controls = {};
97
98     var default_filter_obj = {
99         op : '=',
100         label     : egReportTemplateSvc.Filters['='].label
101     };
102
103     var default_transform_obj = {
104         transform : 'Bare',
105         label     : egReportTemplateSvc.Transforms.Bare.label,
106         aggregate : false
107     };
108
109     function mergePaths (items) {
110         var tree = {};
111
112         items.forEach(function (item) {
113             var t = tree;
114             var join_path = '';
115
116             item.path.forEach(function (p, i, a) {
117                 var alias; // unpredictable hashes are fine for intermediate tables
118
119                 if (i) { // not at the top of the tree
120                     if (i == 1) join_path = join_path.split('-')[0];
121
122                     // SQLBuilder relies on the first dash-separated component
123                     // of the join key to specify the column of left-hand relation
124                     // to join on; for has_many and might_have link types, we have to grab the
125                     // primary key of the left-hand table; otherwise, we can
126                     // just use the field/column name found in p.uplink.name.
127                     var uplink = (p.uplink.reltype == 'has_many' || p.uplink.reltype == 'might_have') ?
128                         egCore.idl.classes[p.from.split('.').slice(-1)[0]].pkey + '-' + p.uplink.name :
129                         p.uplink.name;
130                     join_path += '-' + uplink;
131                     alias = hex_md5(join_path);
132
133                     var uplink_alias = uplink + '-' + alias;
134
135                     if (!t.join) t.join = {};
136                     if (!t.join[uplink_alias]) t.join[uplink_alias] = {};
137
138                     t = t.join[uplink_alias];
139
140                     var djtype = 'inner';
141                     if (p.uplink.reltype != 'has_a') djtype = 'left';
142
143                     t.type = p.jtype || djtype;
144                     t.key = p.uplink.key;
145                 } else {
146                     join_path = p.classname + '-' + p.classname;
147                     alias = hex_md5(join_path);
148                 }
149
150                 if (!t.alias) t.alias = alias;
151                 t.path = join_path;
152
153                 t.table = p.struct.source ? p.struct.source : p.table;
154                 t.idlclass = p.classname;
155
156                 if (a.length == i + 1) { // end of the path array, need a predictable hash
157                     t.label = item.path_label;
158                     t.alias = hex_md5(item.path_label);
159                 }
160
161             });
162         });
163
164         return tree;
165     };
166     // expose for testing
167     $scope._mergePaths = mergePaths;
168
169     $scope.constructTemplate = function () {
170         var param_counter = 0;
171         return {
172             version     : 5,
173             doc_url     : $scope.templateDocURL,
174             core_class  : egCore.idl.classTree.top.classname,
175             select      : dgrid.allItems().map(function (i) {
176                             return {
177                                 alias     : i.label,
178                                 path      : i.path[i.path.length - 1].classname + '-' + i.name,
179                                 field_doc : i.doc_text,
180                                 relation  : hex_md5(i.path_label),
181                                 column    : {
182                                     colname         : i.name,
183                                     transform       : i.transform ? i.transform.transform : '',
184                                     transform_label : i.transform ? i.transform.label : '',
185                                     aggregate       : !!i.transform.aggregate
186                                 }
187                             }
188                           }),
189             from        : mergePaths( dgrid.allItems().concat(fgrid.allItems()) ),
190             where       : fgrid.allItems().filter(function(i) {
191                             return !i.transform.aggregate;
192                           }).map(function (i) {
193                             var cond = {};
194                             if (
195                                 i.operator.op == 'is' ||
196                                 i.operator.op == 'is not' ||
197                                 i.operator.op == 'is blank' ||
198                                 i.operator.op == 'is not blank'
199                             ) {
200                                 cond[i.operator.op] = null;
201                             } else {
202                                 if (i.value === undefined) {
203                                     cond[i.operator.op] = '::P' + param_counter++;
204                                 }else {
205                                     cond[i.operator.op] = i.value;
206                                 }
207                             }
208                             return {
209                                 alias     : i.label,
210                                 path      : i.path[i.path.length - 1].classname + '-' + i.name,
211                                 field_doc : i.doc_text,
212                                 relation  : hex_md5(i.path_label),
213                                 column    : {
214                                     colname         : i.name,
215                                     transform       : i.transform.transform,
216                                     transform_label : i.transform.label,
217                                     aggregate       : 0
218                                 },
219                                 condition : cond // constructed above
220                             }
221                           }),
222             having      : fgrid.allItems().filter(function(i) {
223                             return !!i.transform.aggregate;
224                           }).map(function (i) {
225                             var cond = {};
226                             cond[i.operator.op] = '::P' + param_counter++;
227                             return {
228                                 alias     : i.label,
229                                 path      : i.path[i.path.length - 1].classname + '-' + i.name,
230                                 field_doc : i.doc_text,
231                                 relation  : hex_md5(i.path_label),
232                                 column    : {
233                                     colname         : i.name,
234                                     transform       : i.transform.transform,
235                                     transform_label : i.transform.label,
236                                     aggregate       : 1
237                                 },
238                                 condition : cond // constructed above
239                             }
240                           }),
241             display_cols: angular.copy( dgrid.allItems() ).map(strip_item),
242             filter_cols : angular.copy( fgrid.allItems() ).map(strip_item)
243         };
244
245         function strip_item (i) {
246             delete i.children;
247             i.path.forEach(function(p){
248                 delete p.children;
249                 delete p.fields;
250                 delete p.links;
251                 delete p.struct.permacrud;
252                 delete p.struct.field_map;
253                 delete p.struct.fields;
254             });
255             return i;
256         }
257
258     }
259
260     function loadTemplate () {
261         if (!template_id) return;
262         egCore.pcrud.retrieve( 'rt', template_id)
263         .then( function(template) {
264             template.data = angular.fromJson(template.data());
265             if (template.data.version < 5) { // redirect to old editor...
266                 $window.location.href = egCore.env.basePath + 'reporter/legacy/template/clone/'+folder_id + '/' + template_id;
267             // } else if (template.data.version < 5) { // redirect to old editor...
268             } else {
269                 $scope.templateName = template.name() + ' (clone)';
270                 $scope.templateDescription = template.description();
271                 $scope.templateDocURL = template.data.doc_url;
272
273                 $scope.changeCoreSource( template.data.core_class );
274
275                 egReportTemplateSvc.display_fields = template.data.display_cols;
276                 egReportTemplateSvc.filter_fields = template.data.filter_cols;
277
278                 $timeout(function(){
279                     dgrid.refresh();
280                     fgrid.refresh();
281                 });
282             }
283         });
284
285     }
286
287     $scope.saveTemplate = function () {
288         var tmpl = new egCore.idl.rt();
289         tmpl.name( $scope.templateName );
290         tmpl.description( $scope.templateDescription );
291         tmpl.owner(egCore.auth.user().id());
292         tmpl.folder(folder_id);
293         tmpl.data(angular.toJson($scope.constructTemplate()));
294
295         egConfirmDialog.open(tmpl.name(), egCore.strings.TEMPLATE_CONF_CONFIRM_SAVE,
296             {ok : function() {
297                 return egCore.pcrud.create( tmpl )
298                 .then(
299                     function() {
300                         ngToast.create(egCore.strings.TEMPLATE_CONF_SUCCESS_SAVE);
301                         return $timeout(
302                             function(){
303                                 $window.location.href = egCore.env.basePath + 'reporter/legacy/main';
304                             },
305                             1000
306                         );
307                     },
308                     function() {
309                         ngToast.warning(egCore.strings.TEMPLATE_CONF_FAIL_SAVE);
310                     }
311                 );
312             }}
313         );
314     }
315
316     $scope.addDisplayFields = function () {
317         var t = $scope.selected_transform;
318         if (!t) t = default_transform_obj;
319
320         egReportTemplateSvc.addFields(
321             'display_fields',
322             $scope.selected_source_field_list, 
323             t,
324             $scope.currentPathLabel,
325             $scope.currentPath
326         );
327         dgrid.refresh();
328     }
329
330     $scope.addFilterFields = function () {
331         var t = $scope.selected_transform;
332         if (!t) t = default_transform_obj;
333         f = default_filter_obj;
334
335         egReportTemplateSvc.addFields(
336             'filter_fields',
337             $scope.selected_source_field_list, 
338             t,
339             $scope.currentPathLabel,
340             $scope.currentPath,
341             f
342         );
343         fgrid.refresh();
344     }
345
346     $scope.moveDisplayFieldUp = function (items) {
347         items.reverse().forEach(function(item) {
348             egReportTemplateSvc.moveFieldUp('display_fields', item);
349         });
350         dgrid.refresh();
351     }
352
353     $scope.moveDisplayFieldDown = function (items) {
354         items.forEach(function(item) {
355             egReportTemplateSvc.moveFieldDown('display_fields', item);
356         });
357         dgrid.refresh();
358     }
359
360     $scope.removeDisplayField = function (items) {
361         items.forEach(function(item) {egReportTemplateSvc.removeField('display_fields', item)});
362         dgrid.refresh();
363     }
364
365     $scope.changeDisplayLabel = function (items) {
366         items.forEach(function(item) {
367             egPromptDialog.open(egCore.strings.TEMPLATE_CONF_PROMPT_CHANGE, item.label || '',
368                 {ok : function(value) {
369                     if (value) egReportTemplateSvc.display_fields[item.index].label = value;
370                 }}
371             );
372         });
373         dgrid.refresh();
374     }
375
376     $scope.changeDisplayFieldDoc = function (items) {
377         items.forEach(function(item) {
378             egPromptDialog.open(egCore.strings.TEMPLATE_FIELD_DOC_PROMPT_CHANGE, item.doc_text || '',
379                 {ok : function(value) {
380                     if (value) egReportTemplateSvc.display_fields[item.index].doc_text = value;
381                 }}
382             );
383         });
384         dgrid.refresh();
385     }
386
387     $scope.changeFilterFieldDoc = function (items) {
388         items.forEach(function(item) {
389             egPromptDialog.open(egCore.strings.TEMPLATE_FIELD_DOC_PROMPT_CHANGE, item.doc_text || '',
390                 {ok : function(value) {
391                     if (value) egReportTemplateSvc.filter_fields[item.index].doc_text = value;
392                 }}
393             );
394         });
395         fgrid.refresh();
396     }
397
398     $scope.changeFilterValue = function (items) {
399         items.forEach(function(item) {
400             var l = null;
401             egPromptDialog.open(egCore.strings.TEMPLATE_CONF_DEFAULT, item.value || '',
402                 {ok : function(value) {
403                     if (value) egReportTemplateSvc.filter_fields[item.index].value = value;
404                 }}
405             );
406         });
407         fgrid.refresh();
408     }
409
410     $scope.changeTransform = function (items) {
411
412         var f = items[0];
413
414         var tlist = [];
415         angular.forEach(egReportTemplateSvc.Transforms, function (o,n) {
416             if ( o.datatype.indexOf(f.datatype) > -1) {
417                 if (tlist.indexOf(o.label) == -1) tlist.push( o.label );
418             }
419         });
420         
421         items.forEach(function(item) {
422             egSelectDialog.open(
423                 egCore.strings.SELECT_TFORM, tlist, item.transform.label,
424                 {ok : function(value) {
425                     if (value) {
426                         var t = egReportTemplateSvc.getTransformByLabel(value);
427                         item.transform = {
428                             label     : value,
429                             transform : t,
430                             aggregate : egReportTemplateSvc.Transforms[t].aggregate ? true : false
431                         };
432                     }
433                 }}
434             );
435         });
436
437         fgrid.refresh();
438     }
439
440     $scope.changeOperator = function (items) {
441
442         var flist = [];
443         Object.keys(egReportTemplateSvc.Filters).forEach(function(k){
444             var v = egReportTemplateSvc.Filters[k];
445             if (flist.indexOf(v.label) == -1) flist.push(v.label);
446             if (v.labels && v.labels.length > 0) {
447                 v.labels.forEach(function(l) {
448                     if (flist.indexOf(l) == -1) flist.push(l);
449                 })
450             }
451         });
452
453         items.forEach(function(item) {
454             var l = item.operator ? item.operator.label : '';
455             egSelectDialog.open(
456                 egCore.strings.SELECT_OP, flist, l,
457                 {ok : function(value) {
458                     if (value) {
459                         var t = egReportTemplateSvc.getFilterByLabel(value);
460                         item.operator = { label: value, op : t };
461                     }
462                 }}
463             );
464         });
465
466         fgrid.refresh();
467     }
468
469     $scope.removeFilterValue = function (items) {
470         items.forEach(function(item) {delete egReportTemplateSvc.filter_fields[item.index].value});
471         fgrid.refresh();
472     }
473
474     $scope.removeFilterField = function (items) {
475         items.forEach(function(item) {egReportTemplateSvc.removeField('filter_fields', item)});
476         fgrid.refresh();
477     }
478
479     $scope.allSources = values(egCore.idl.classes).sort( function(a,b) {
480         if (a.core && !b.core) return -1;
481         if (b.core && !a.core) return 1;
482         aname = a.label ? a.label : a.name;
483         bname = b.label ? b.label : b.name;
484         if (aname > bname) return 1;
485         return -1;
486     });
487
488     $scope.class_tree = [];
489     $scope.selected_source = null;
490     $scope.selected_source_fields = [];
491     $scope.selected_source_field_list = [];
492     $scope.available_field_transforms = [];
493     $scope.coreSource = null;
494     $scope.coreSourceChosen = false;
495     $scope.currentPathLabel = '';
496
497     $scope.treeExpand = function (node, expanding) {
498         if (expanding) node.children.map(egCore.idl.classTree.fleshNode);
499     }
500
501     $scope.filterFields = function (n) {
502         return n.virtual ? false : true;
503         // should we hide links?
504         return n.datatype && n.datatype != 'link'
505     }
506
507     $scope.field_tree_opts = {
508         multiSelection: true,
509         equality      : function(node1, node2) {
510             return node1.name == node2.name;
511         }
512     }
513
514     $scope.field_transforms_tree_opts = {
515         equality : function(node1, node2) {
516             if (!node2) return false;
517             return node1.transform == node2.transform;
518         }
519     }
520
521     $scope.selectFields = function () {
522         while ($scope.available_field_transforms.length) {
523             $scope.available_field_transforms.pop();
524         }
525
526         angular.forEach( $scope.selected_source_field_list, function (f) {
527             angular.forEach(egReportTemplateSvc.Transforms, function (o,n) {
528                 if ( o.datatype.indexOf(f.datatype) > -1) {
529                     var include = true;
530
531                     angular.forEach($scope.available_field_transforms, function (t) {
532                         if (t.transform == n) include = false;
533                     });
534
535                     if (include) $scope.available_field_transforms.push({
536                         transform : n,
537                         label     : o.label,
538                         aggregate : o.aggregate ? true : false
539                     });
540                 }
541             });
542         });
543
544     }
545
546     $scope.selectSource = function (node, selected, $path) {
547
548         while ($scope.selected_source_field_list.length) {
549             $scope.selected_source_field_list.pop();
550         }
551         while ($scope.selected_source_fields.length) {
552             $scope.selected_source_fields.pop();
553         }
554
555         if (selected) {
556             $scope.currentPath = angular.copy( $path().reverse() );
557             $scope.selected_source = node;
558             $scope.currentPathLabel = $scope.currentPath.map(function(n,i){
559                 var l = n.label
560                 if (i) l += ' (' + n.jtype + ')';
561                 return l;
562             }).join( ' -> ' );
563             angular.forEach( node.fields, function (f) {
564                 $scope.selected_source_fields.push( f );
565             });
566         } else {
567             $scope.currentPathLabel = '';
568         }
569
570         // console.log($scope.selected_source);
571     }
572
573     $scope.changeCoreSource = function (new_core) {
574         console.log('changeCoreSource: '+new_core);
575         function change_core () {
576             if (new_core) $scope.coreSource = new_core;
577             $scope.coreSourceChosen = true;
578
579             $scope.class_tree.pop();
580             $scope.class_tree.push(
581                 egCore.idl.classTree.setTop($scope.coreSource)
582             );
583
584             while ($scope.selected_source_fields.length) {
585                 $scope.selected_source_fields.pop();
586             }
587
588             while ($scope.available_field_transforms.length) {
589                 $scope.available_field_transforms.pop();
590             }
591
592             $scope.currentPathLabel = '';
593         }
594
595         if ($scope.coreSourceChosen) {
596             egConfirmDialog.open(
597                 egCore.strings.FOLDERS_TEMPLATE,
598                 egCore.strings.SOURCE_SETUP_CONFIRM_EXIT,
599                 {ok : change_core}
600             );
601         } else {
602             change_core();
603         }
604     }
605
606     loadTemplate();
607 }])
608
609 ;