]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/reports/xul/template-config.js
attempt focus()ing
[Evergreen.git] / Open-ILS / web / reports / xul / template-config.js
1 function removeReportAtom (args) {
2         if (!args) args = {};
3
4         var active_tab = filterByAttribute(
5                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
6                 'selected',
7                 'true'
8         )[0];
9         var tabname = active_tab.getAttribute('id');
10
11         var tabpanel = $( tabname + 'panel' );
12         var tree = tabpanel.getElementsByTagName('tree')[0];
13         var fields = getSelectedItems(tree);
14
15
16         for (var i in fields) {
17                 var field = fields[i];
18                 var colname = field.firstChild.firstChild.nextSibling.getAttribute('label');
19                 var relation_alias = field.getAttribute('relation');
20
21                 delete rpt_rel_cache[relation_alias].fields[tabname][colname];
22                 if (tabname == 'dis_tab') {
23                         var _o_tmp = [];
24                         for each (var _o_col in rpt_rel_cache.order_by) {
25                                 if (_o_col.relation == relation_alias && _o_col.field == colname) continue;
26                                 _o_tmp.push( _o_col );
27                         }
28                         rpt_rel_cache.order_by = _o_tmp
29                 }
30
31                 with (rpt_rel_cache[relation_alias].fields) {
32                         if ( getKeys(dis_tab).length == 0 && getKeys(filter_tab).length == 0 && getKeys(aggfilter_tab).length == 0 )
33                                 delete rpt_rel_cache[relation_alias];
34                 }
35         }
36
37         renderSources();
38
39         return true;
40 }
41
42 function addReportAtoms () {
43         var nope = $( 'source-add' ).getAttribute('disabled');
44         if (nope == 'true') return false;
45
46         var class_tree = $('class-view');
47         var transform_tree = $('trans-view');
48
49         var active_tab = filterByAttribute(
50                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
51                 'selected',
52                 'true'
53         )[0];
54
55         var tabname = active_tab.getAttribute('id')
56
57         var items = getSelectedItems(class_tree);
58         var transform = getSelectedItems(transform_tree)[0];
59
60         var reltype = $('path-label').getAttribute('reltype');
61         var class_label = $('path-label').value;
62         var relation_alias = hex_md5(class_label);
63
64         for (var i in items) {
65                 var item = items[i];
66
67                 var class_path = item.getAttribute('fullpath');
68                 var field_class = item.getAttribute('idlclass');
69                 var datatype = item.getAttribute('datatype');
70                 var colname = item.getAttribute('idlfield');
71                 var field_label = item.firstChild.firstChild.getAttribute('label');
72
73                 var table_name = getIDLClass(field_class).getAttributeNS(persistNS,'tablename');
74
75                 if ( !rpt_rel_cache[relation_alias] ) {
76                         rpt_rel_cache[relation_alias] =
77                                 { label : class_label,
78                                   alias : relation_alias,
79                                   path  : class_path,
80                                   reltype  : reltype,
81                                   idlclass  : field_class,
82                                   table : table_name,
83                                   fields: { dis_tab : {}, filter_tab : {}, aggfilter_tab : {} }
84                                 };
85                 }
86
87                 if ( !rpt_rel_cache[relation_alias].fields[tabname][colname] ) {
88                         rpt_rel_cache[relation_alias].fields[tabname][colname] =
89                                 { colname   : colname,
90                                   transform : (transform && transform.getAttribute('name')) || 'Bare',
91                                   aggregate : transform && transform.getAttribute('aggregate'),
92                                   params    : transform && transform.getAttribute('params'),
93                                   transform_label: (transform && transform.getAttribute('alias')) || 'Raw Data',
94                                   alias     : field_label,
95                                   datatype  : datatype,
96                                   op        : '=',
97                                   op_label  : 'Equals',
98                                   op_value  : {},
99                                 };
100
101                         if (!rpt_rel_cache.order_by)
102                                 rpt_rel_cache.order_by = [];
103
104                         if (tabname == 'dis_tab')
105                                 rpt_rel_cache.order_by.push( { relation : relation_alias, field : colname } );
106
107                 } else if (
108                         confirm(
109                                 'You have already added the [' + field_label +
110                                 '] field\nfrom the [' + class_label + '] source. Click OK if you\nwould like ' +
111                                 'to reset this field.'
112                         )
113                 ) {
114                         rpt_rel_cache[relation_alias].fields[tabname][colname] =
115                                 { colname   : colname,
116                                   transform : (transform && transform.getAttribute('name')) || 'Bare',
117                                   aggregate : transform && transform.getAttribute('aggregate'),
118                                   params    : transform && transform.getAttribute('params'),
119                                   transform_label: (transform && transform.getAttribute('alias')) || 'Raw Data',
120                                   alias     : field_label,
121                                   datatype  : datatype,
122                                   op        : '=',
123                                   op_label  : 'Equals',
124                                   op_value  : {},
125                                 };
126                 }
127         }
128
129         renderSources();
130
131         return true;
132 }
133
134 function changeDisplayOrder (dir) {
135         var active_tab = filterByAttribute(
136                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
137                 'selected',
138                 'true'
139         )[0];
140
141         var tabname = active_tab.getAttribute('id');
142
143         var tabpanel = $( tabname + 'panel' );
144         var tree = tabpanel.getElementsByTagName('tree')[0];
145         var item = getSelectedItems(tree)[0];
146
147         var item_pos = tree.view.selection.currentIndex;
148
149         if (dir == 'u') {
150                 if ( item.previousSibling ) {
151                         item.parentNode.insertBefore( item, item.previousSibling );
152                         item_pos--;
153                 }
154         } else if (dir == 'd') {
155                 if ( item.nextSibling ) {
156                         if (item.nextSibling.nextSibling ) item.parentNode.insertBefore( item, item.nextSibling.nextSibling );
157                         else item.parentNode.appendChild( item );
158                         item_pos++;
159                 }
160         }
161         
162         rpt_rel_cache.order_by = [];
163         var ordered_list = tree.getElementsByTagName('treeitem');
164         for (var i = 0; i < ordered_list.length; i++) {
165                 rpt_rel_cache.order_by.push(
166                         { relation : ordered_list[i].getAttribute('relation'),
167                           field    : ordered_list[i].firstChild.firstChild.nextSibling.getAttribute('label')
168                         }
169                 );
170         }
171
172         tree.view.selection.select( item_pos );
173         return true;
174 }
175
176 function alterColumnLabel () {
177         var active_tab = filterByAttribute(
178                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
179                 'selected',
180                 'true'
181         )[0];
182
183         var tabname = active_tab.getAttribute('id');
184
185         var tabpanel = $( tabname + 'panel' );
186         var tree = tabpanel.getElementsByTagName('tree')[0];
187         var item_pos = tree.view.selection.currentIndex;
188
189         var item = getSelectedItems(tree)[0];
190         var relation_alias = item.getAttribute('relation');
191
192         var field = item.firstChild.firstChild;
193         var colname = field.nextSibling.getAttribute('label');
194
195         var new_label = prompt(
196                 "Change the column header to:",
197                 field.getAttribute("label")
198         );
199
200         if (new_label) {
201                 rpt_rel_cache[relation_alias].fields[tabname][colname].alias = new_label;
202                 renderSources(true);
203                 tree.view.selection.select( item_pos );
204         }
205
206         return true;
207 }
208
209 function alterColumnTransform (trans) {
210
211         var transform = OILS_RPT_TRANSFORMS[trans];
212
213         var active_tab = filterByAttribute(
214                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
215                 'selected',
216                 'true'
217         )[0];
218
219         var tabname = active_tab.getAttribute('id');
220
221         var tabpanel = $( tabname + 'panel' );
222         var tree = tabpanel.getElementsByTagName('tree')[0];
223         var item_pos = tree.view.selection.currentIndex;
224         var item =  getSelectedItems(tree)[0];
225         var relation_alias = item.getAttribute('relation');
226
227         var field = item.firstChild.firstChild;
228         var colname = field.nextSibling.getAttribute('label');
229
230         rpt_rel_cache[relation_alias].fields[tabname][colname].transform = trans;
231         rpt_rel_cache[relation_alias].fields[tabname][colname].aggregate = transform.aggregate;
232         rpt_rel_cache[relation_alias].fields[tabname][colname].params = transform.params;
233         rpt_rel_cache[relation_alias].fields[tabname][colname].transform_label = transform.label;
234
235         renderSources(true);
236         tree.view.selection.select( item_pos );
237         item.focus();
238         return true;
239 }
240
241 function changeOperator (args) {
242
243         var active_tab = filterByAttribute(
244                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
245                 'selected',
246                 'true'
247         )[0];
248
249         var tabname = active_tab.getAttribute('id');
250
251         var tabpanel = $( tabname + 'panel' );
252         var tree = tabpanel.getElementsByTagName('tree')[0];
253         var item_pos = tree.view.selection.currentIndex;
254         var item = getSelectedItems(tree)[0];
255
256         var relation_alias = item.getAttribute('relation');
257
258         var field = item.firstChild.firstChild;
259         var colname = field.nextSibling.getAttribute('label');
260
261         rpt_rel_cache[relation_alias].fields[tabname][colname].op = args.op;
262         rpt_rel_cache[relation_alias].fields[tabname][colname].op_label = args.label;
263
264         renderSources(true);
265         tree.view.selection.select( item_pos );
266         return true;
267 }
268
269 function removeTemplateFilterValue () {
270
271         var active_tab = filterByAttribute(
272                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
273                 'selected',
274                 'true'
275         )[0];
276
277         var tabname = active_tab.getAttribute('id');
278
279         var tabpanel = $( tabname + 'panel' );
280         var tree = tabpanel.getElementsByTagName('tree')[0];
281         var item_pos = tree.view.selection.currentIndex;
282         var items = getSelectedItems(tree);
283
284         for (var i in items) {
285                 var item = items[i];
286                 var relation_alias = item.getAttribute('relation');
287
288                 var field = item.firstChild.firstChild;
289                 var colname = field.nextSibling.getAttribute('label');
290
291                 rpt_rel_cache[relation_alias].fields[tabname][colname].op_value = {};
292         }
293
294         renderSources(true);
295         tree.view.selection.select( item_pos );
296         return true;
297 }
298
299 function timestampSetDate (obj, cal, date) {
300         obj.op_value.value = date;
301         obj.op_value.object = cal.date;
302         obj.op_value.label = '"' + date + '"';
303
304         renderSources(true);
305         return true;
306 }
307
308 var __handler_cache;
309
310 function changeTemplateFilterValue () {
311
312         var active_tab = filterByAttribute(
313                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
314                 'selected',
315                 'true'
316         )[0];
317
318         var tabname = active_tab.getAttribute('id');
319
320         var tabpanel = $( tabname + 'panel' );
321         var tree = tabpanel.getElementsByTagName('tree')[0];
322         var item_pos = tree.view.selection.currentIndex;
323         var items = getSelectedItems(tree);
324
325         var targetCmd = $( tabname + '_value_action' );
326
327         targetCmd.menu = null;
328         targetCmd.command = null;
329         targetCmd.oncommand = null;
330         targetCmd.removeEventListener( 'command', __handler_cache, true );
331
332         for (var i in items) {
333                 var item = items[i];
334                 var relation_alias = item.getAttribute('relation');
335
336                 var field = item.firstChild.firstChild;
337                 var colname = field.nextSibling.getAttribute('label');
338
339                 var obj = rpt_rel_cache[relation_alias].fields[tabname][colname]
340                 var operation = OILS_RPT_FILTERS[obj.op];
341
342                 switch (obj.datatype) {
343                         case 'timestamp':
344                                 var cal_popup = $('calendar-widget');
345
346                                 while (cal_popup.firstChild) cal_popup.removeChild(cal_popup.lastChild);
347                                 var calendar = new Calendar(
348                                         0,
349                                         obj.op_value.object,
350                                         function (cal,date) { return timestampSetDate(obj,cal,date) },
351                                         function (cal) { cal_popup.hidePopup(); cal.destroy(); return true; }
352                                 );
353
354                                 var format = OILS_RPT_TRANSFORMS[obj.transform].cal_format || '%Y-%m-%d';
355
356                                 calendar.setDateFormat(format);
357                                 calendar.create(cal_popup);
358
359                                 targetCmd.menu = 'calendar-widget';
360
361                                 break;
362
363                         case 'bool':
364
365                                 function __bool_value_event_handler () {
366                                         var state, answer;
367
368                                         try {
369                                                 // get a reference to the prompt service component.
370                                                 var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
371                                                                     .getService(Components.interfaces.nsIPromptService);
372
373                                                 // set the buttons that will appear on the dialog. It should be
374                                                 // a set of constants multiplied by button position constants. In this case,
375                                                 // three buttons appear, Save, Cancel and a custom button.
376                                                 var flags=promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0 +
377                                                         promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_1 +
378                                                         promptService.BUTTON_TITLE_CANCEL * promptService.BUTTON_POS_2;
379
380                                                 // display the dialog box. The flags set above are passed
381                                                 // as the fourth argument. The next three arguments are custom labels used for
382                                                 // the buttons, which are used if BUTTON_TITLE_IS_STRING is assigned to a
383                                                 // particular button. The last two arguments are for an optional check box.
384                                                 answer = promptService.select(
385                                                         window,
386                                                         "Boolean Value",
387                                                         "Select the value, or cancel:",
388                                                         2, ["True", "False"], state
389                                                 );
390                                         } catch (e) {
391                                                 answer = true;
392                                                 state = confirm("Click OK for TRUE and Cancel for FALSE.");
393                                                 state ? state = 0 : state = 1;
394                                         }
395
396                                         if (answer) {
397                                                 if (state) {
398                                                         obj.op_value.value = 'f';
399                                                         obj.op_value.label = 'False';
400                                                 } else {
401                                                         obj.op_value.value = 't';
402                                                         obj.op_value.label = 'True';
403                                                 }
404                                         }
405
406                                         targetCmd.removeEventListener( 'command', __bool_value_event_handler, true );
407                                         renderSources(true);
408                                         tree.view.selection.select( item_pos );
409                                         return true;
410                                 }
411
412                                 __handler_cache = __bool_value_event_handler;
413                                 targetCmd.addEventListener( 'command', __bool_value_event_handler, true );
414
415                                 break;
416
417                         default:
418
419
420                                 var promptstring = "Field does not match one of list (comma separated):";
421
422                                 switch (obj.op) {
423                                         case 'not between':
424                                                 promptstring = "Field value is not between (comma separated):";
425                                                 break;
426
427                                         case 'between':
428                                                 promptstring = "Field value is between (comma separated):";
429                                                 break;
430
431                                         case 'not in':
432                                                 promptstring = "Field does not match one of list (comma separated):";
433                                                 break;
434
435                                         case 'in':
436                                                 promptstring = "Field matches one of list (comma separated):";
437                                                 break;
438
439                                         default:
440                                                 promptstring = "Value " + obj.op_label + ":";
441                                                 break;
442                                 }
443
444                                 function __default_value_event_handler () {
445                                         var _v;
446                                         if (_v  = prompt( promptstring, obj.op_value.value || '' )) {
447                                                 switch (obj.op) {
448                                                         case 'between':
449                                                         case 'not between':
450                                                         case 'not in':
451                                                         case 'in':
452                                                                 obj.op_value.value = _v.split(/\s*,\s*/);
453                                                                 break;
454
455                                                         default:
456                                                                 obj.op_value.value = _v;
457                                                                 break;
458                                                 }
459
460                                                 obj.op_value.label = '"' + obj.op_value.value + '"';
461                                         }
462
463                                         targetCmd.removeEventListener( 'command', __default_value_event_handler, true );
464                                         renderSources(true);
465                                         tree.view.selection.select( item_pos );
466                                         return true;
467                                 }
468
469                                 __handler_cache = __default_value_event_handler;
470                                 targetCmd.addEventListener( 'command', __default_value_event_handler, true );
471
472                                 break;
473                 }
474         }
475
476         return true;
477 }
478
479 function populateOperatorContext () {
480
481         var active_tab = filterByAttribute(
482                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
483                 'selected',
484                 'true'
485         )[0];
486
487         var tabname = active_tab.getAttribute('id');
488
489         var tabpanel = $( tabname + 'panel' );
490         var tree = tabpanel.getElementsByTagName('tree')[0];
491         var item = getSelectedItems(tree)[0];
492
493         var dtypes = [];
494         dtypes.push( item.getAttribute('datatype') );
495
496         var menu = $(tabname + '_op_menu');
497         while (menu.firstChild) menu.removeChild(menu.lastChild);
498
499         for (var i in OILS_RPT_FILTERS) {
500                 var o = OILS_RPT_FILTERS[i];
501                 menu.appendChild(
502                         createMenuItem(
503                                 { label : o.label,
504                                   oncommand : "changeOperator({op:'"+i+"',label:'"+o.label+"'})",
505                                 }
506                         )
507                 );
508                 if (o.labels) {
509                         var keys = getKeys(o.labels);
510                         for ( var k in keys ) {
511                                 var key = keys[k];
512                                 if ( grep(function(x){return key==x},dtypes).length ) {
513                                         menu.appendChild(
514                                                 createMenuItem(
515                                                         { label : o.labels[key],
516                                                           oncommand : "changeOperator({op:'"+i+"',label:'"+o.labels[key]+"'})",
517                                                         }
518                                                 )
519                                         );
520                                 }
521                         }
522                 }
523         }
524 }
525
526 function populateTransformContext () {
527
528         var active_tab = filterByAttribute(
529                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
530                 'selected',
531                 'true'
532         )[0];
533
534         var tabname = active_tab.getAttribute('id');
535
536         var tabpanel = $( tabname + 'panel' );
537         var tree = tabpanel.getElementsByTagName('tree')[0];
538         var item_pos = tree.view.selection.currentIndex;
539         var item = getSelectedItems(tree)[0];
540
541         var transforms = {};
542         var dtype = item.getAttribute('datatype');
543         var item_transforms = getTransforms({ datatype : dtype });
544
545         for (var j in item_transforms) {
546                 transforms[item_transforms[j]] = OILS_RPT_TRANSFORMS[item_transforms[j]];
547                 transforms[item_transforms[j]].name = item_transforms[j];
548         }
549
550         var transformList = [];
551         for (var i in transforms) {
552                 transformList.push( transforms[i] );
553         }
554
555         transformList.sort( sortHashLabels );
556
557         var menu = $(tabname + '_trans_menu');
558         while (menu.firstChild) menu.removeChild(menu.lastChild);
559
560         for (var i in transformList) {
561                 var t = transformList[i];
562
563                 if (tabname.match(/filter/)) {
564                         if (tabname.match(/^agg/)) {
565                                 if (!t.aggregate) continue;
566                         } else {
567                                 if (t.aggregate) continue;
568                         }
569                 }
570
571                 menu.appendChild(
572                         createMenuItem(
573                                 { aggregate : t.aggregate,
574                                   name : t.name,
575                                   alias : t.label,
576                                   label : t.label,
577                                   params : t.params,
578                                   command : function () { return alterColumnTransform(t.name) }
579                                 }
580                         )
581                 );
582         }
583
584         menu.parentNode.setAttribute('disabled','false');
585         if (menu.childNodes.length == 0) {
586                 menu.parentNode.setAttribute('disabled','true');
587         }
588 }
589
590
591 function renderSources (selected) {
592
593         var tree = $('used-sources');
594         var sources = $('used-sources-treetop');
595         var tabs = $('used-source-fields-tabbox').getElementsByTagName('tab');
596
597         if (!selected) {
598                 while (sources.firstChild) sources.removeChild(sources.lastChild);
599         } else {
600                 selected = getSelectedItems(tree);
601                 if (!selected.length) {
602                         selected = undefined;
603                         while (sources.firstChild) sources.removeChild(sources.lastChild);
604                 }
605         }
606
607         for (var j = 0; j < tabs.length; j++) {
608                 var tab = tabs[j];
609                 var tabname = tab.getAttribute('id')
610                 var tabpanel = $( tab.getAttribute('id') + 'panel' );
611                 var fieldtree = tabpanel.getElementsByTagName('treechildren')[0];
612
613                 while (fieldtree.firstChild) fieldtree.removeChild(fieldtree.lastChild);
614         }
615
616         for (var relation_alias in rpt_rel_cache) {
617                 if (!rpt_rel_cache[relation_alias].fields) continue;
618
619                 if (selected) {
620                         if (
621                                 !grep(
622                                         function (x) {
623                                                 return x.getAttribute('relation') == relation_alias;
624                                         },
625                                         selected
626                                 ).length
627                         ) continue;
628                 } else {
629
630                         $('used-sources-treetop').appendChild(
631                                 createTreeItem(
632                                         { relation : rpt_rel_cache[relation_alias].alias,
633                                           idlclass : rpt_rel_cache[relation_alias].idlclass,
634                                           reltype  : rpt_rel_cache[relation_alias].reltype,
635                                           path     : rpt_rel_cache[relation_alias].path,
636                                         },
637                                         createTreeRow(
638                                                 {},
639                                                 createTreeCell({ label : rpt_rel_cache[relation_alias].label }),
640                                                 createTreeCell({ label : rpt_rel_cache[relation_alias].table }),
641                                                 createTreeCell({ label : rpt_rel_cache[relation_alias].alias }),
642                                                 createTreeCell({ label : rpt_rel_cache[relation_alias].reltype })
643                                         )
644                                 )
645                         );
646                 }
647
648                 for each (var tabname in ['filter_tab','aggfilter_tab']) {
649                         tabpanel = $( tabname + 'panel' );
650                         fieldtree = tabpanel.getElementsByTagName('treechildren')[0];
651
652                         for (var colname in rpt_rel_cache[relation_alias].fields[tabname]) {
653                                 with (rpt_rel_cache[relation_alias].fields[tabname][colname]) {
654                                         fieldtree.appendChild(
655                                                 createTreeItem(
656                                                         { relation : relation_alias, datatype : datatype },
657                                                         createTreeRow(
658                                                                 {},
659                                                                 createTreeCell({ label : alias }),
660                                                                 createTreeCell({ label : colname }),
661                                                                 createTreeCell({ label : datatype }),
662                                                                 createTreeCell({ label : transform_label }),
663                                                                 createTreeCell({ label : transform })
664                                                         )
665                                                 )
666                                         );
667
668                                         fieldtree.lastChild.firstChild.appendChild(
669                                                 createTreeCell({ op : op, label : op_label })
670                                         );
671
672                                         if (op_value.value != undefined) {
673                                                 fieldtree.lastChild.firstChild.appendChild(
674                                                         createTreeCell({ label : op_value.label })
675                                                 );
676                                         }
677                                 }
678                         }
679                 }
680         }
681
682         tabpanel = $( 'dis_tabpanel' );
683         fieldtree = tabpanel.getElementsByTagName('treechildren')[0];
684         for each (var order in rpt_rel_cache.order_by) {
685
686                 if (selected) {
687                         if (
688                                 !grep(
689                                         function (x) {
690                                                 return x.getAttribute('relation') == order.relation;
691                                         },
692                                         selected
693                                 ).length
694                         ) continue;
695                 }
696
697                 with (rpt_rel_cache[order.relation].fields.dis_tab[order.field]) {
698                         fieldtree.appendChild(
699                                 createTreeItem(
700                                         { relation : order.relation, datatype : datatype },
701                                         createTreeRow(
702                                                 {},
703                                                 createTreeCell({ label : alias }),
704                                                 createTreeCell({ label : colname }),
705                                                 createTreeCell({ label : datatype }),
706                                                 createTreeCell({ label : transform_label }),
707                                                 createTreeCell({ label : transform })
708                                         )
709                                 )
710                         );
711
712                         fieldtree.lastChild.firstChild.appendChild(
713                                 createTreeCell({ op : op, label : op_label })
714                         );
715
716                         if (op_value.value != undefined) {
717                                 fieldtree.lastChild.firstChild.appendChild(
718                                         createTreeCell({ label : op_value.label })
719                                 );
720                         }
721                 }
722         }
723 }
724
725 var param_count;
726 var tab_use = {
727         dis_tab       : 'select',
728         filter_tab    : 'where',
729         aggfilter_tab : 'having',
730 };
731
732
733 function save_template () {
734         param_count = 0;
735
736         var template = {
737                 version    : 1,
738                 core_class : $('sources-treetop').getElementsByTagName('treeitem')[0].getAttribute('idlclass'),
739                 select     : [],
740                 from       : {},
741                 where      : [],
742                 having     : [],
743                 order_by   : []
744         };
745
746         for (var relname in rpt_rel_cache) {
747                 var relation = rpt_rel_cache[relname];
748                 if (!relation.fields) continue;
749
750                 // first, add the where and having clauses (easier)
751                 for each (var tab_name in [ 'filter_tab', 'aggfilter_tab' ]) {
752                         var tab = relation.fields[tab_name];
753                         for (var field in tab) {
754                                 fleshTemplateField( template, relation, tab_name, field );
755                         }
756                 }
757
758                 // now the from clause
759                 fleshFromPath( template, relation );
760         }
761
762         // and now for select (based on order_by)
763         for each (var order in rpt_rel_cache.order_by)
764                 fleshTemplateField( template, rpt_rel_cache[order.relation], 'dis_tab', order.field );
765
766
767         // and the saving throw ...
768         var cgi = new CGI();
769         var session = cgi.param('ses');
770         fetchUser( session );
771
772         var tmpl = new rt();
773         tmpl.name( $('template-name').value );
774         tmpl.description( $('template-description').value );
775         tmpl.owner(USER.id());
776         tmpl.folder(cgi.param('folder'));
777         tmpl.data(js2JSON(template));
778
779         // prompt( 'template', js2JSON( tmpl ) );
780
781         if(!confirm('Name : '+tmpl.name() + '\nDescription: ' + tmpl.description()+'\nSave Template?'))
782                 return;
783
784         var req = new Request('open-ils.reporter:open-ils.reporter.template.create', session, tmpl);
785         req.request.alertEvent = false;
786         req.callback(
787                 function(r) {
788                         var res = r.getResultObject();
789                         if(checkILSEvent(res)) {
790                                 alertILSEvent(res);
791                         } else {
792                                 if( res && res != '0' ) {
793                                         confirm('Template ' + tmpl.name() + ' was successfully saved.');
794                                         _l('../oils_rpt.xhtml');
795                                 }
796                         }
797                 }
798         );
799
800         req.send();
801 }
802
803 function fleshFromPath ( template, rel ) {
804         var table_path = rel.path.split( /\./ );
805         if (table_path.length > 1 || rel.path.indexOf('-') > -1) table_path.push( rel.idlclass );
806
807         var prev_type = '';
808         var prev_link = '';
809         var current_path = '';
810         var current_obj = template.from;
811         var link;
812         while (link = table_path.shift()) {
813                 if (current_path) current_path += '-';
814                 current_path += link;
815
816                 var leaf = table_path.length == 0 ? true : false;
817
818                 current_obj.path = current_path;
819                 current_obj.table = getIDLClass( link.split(/-/)[0] ).getAttributeNS( persistNS, 'tablename' );
820
821                 if (prev_link != '') {
822                         var prev_class = getIDLClass( prev_link.split(/-/)[0] );
823                         var prev_field = prev_link.split(/-/)[1];
824
825                         var current_link = getIDLLink( prev_class, prev_field );
826                         current_obj.key = current_link.getAttribute('key');
827
828                         if (
829                                 current_link.getAttribute('reltype') != 'has_a' ||
830                                 prev_type == 'left' ||
831                                 rel.reltype != 'has_a'
832                         ) current_obj.type = 'left';
833
834                         prev_type = current_obj.type; 
835                 }
836
837                 if (leaf) {
838                         current_obj.label = rel.label;
839                         current_obj.alias = rel.alias;
840                         current_obj.idlclass = rel.idlclass;
841                         current_obj.template_path = rel.path;
842                 } else {
843                         var current_class = getIDLClass( link.split(/-/)[0] );
844                         var join_field = link.split(/-/)[1];
845                         var join_link = getIDLLink(current_class, join_field);
846
847                         if (join_link.getAttribute('reltype') != 'has_a') {
848                                 var fields_el = current_class.getElementsByTagName('fields')[0];
849                                 join_field = fields_el.getAttributeNS(persistNS, 'primary') + '-' + join_link.getAttribute('key');
850                         }
851
852                         current_obj.alias = hex_md5( current_path ) ;
853                         join_field += '-' + current_obj.alias;
854                         if (table_path.length == 1) join_field += '-' + rel.alias;
855
856                         if (!current_obj.join) current_obj.join = {};
857                         if (!current_obj.join[join_field]) current_obj.join[join_field] = {};
858
859                         if (current_obj.type == 'left') current_obj.join[join_field].type = 'left';
860
861                         current_obj = current_obj.join[join_field];
862                 }
863
864                 prev_link = link;
865         }
866
867
868 }
869
870 function fleshTemplateField ( template, rel, tab_name, field ) {
871
872         if (!rel.fields[tab_name] || !rel.fields[tab_name][field]) return;
873
874         var tab = rel.fields[tab_name];
875
876         var field_path = rel.path + '-' + field;
877         field_path = field_path.replace(/\./g, '-');
878
879         var element = {
880                 alias : tab[field].alias,
881                 column :
882                         { colname : field,
883                           transform : tab[field].transform,
884                           transform_label : tab[field].transform_label
885                         },
886                 path : field_path,
887                 relation : rel.alias
888         };
889
890         if (tab_name.match(/filter/)) {
891                 element.condition = {};
892                 element.condition[tab[field].op] =
893                         tab[field].op_value.value ?
894                                 tab[field].op_value.value :
895                                 '::P' + param_count++;
896         }
897
898         template[tab_use[tab_name]].push(element);
899 }
900