]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/reports/xul/template-config.js
debugging
[working/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         return true;
238 }
239
240 function changeOperator (args) {
241
242         var active_tab = filterByAttribute(
243                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
244                 'selected',
245                 'true'
246         )[0];
247
248         var tabname = active_tab.getAttribute('id');
249
250         var tabpanel = $( tabname + 'panel' );
251         var tree = tabpanel.getElementsByTagName('tree')[0];
252         var item_pos = tree.view.selection.currentIndex;
253         var item = getSelectedItems(tree)[0];
254
255         var relation_alias = item.getAttribute('relation');
256
257         var field = item.firstChild.firstChild;
258         var colname = field.nextSibling.getAttribute('label');
259
260         rpt_rel_cache[relation_alias].fields[tabname][colname].op = args.op;
261         rpt_rel_cache[relation_alias].fields[tabname][colname].op_label = args.label;
262
263         renderSources(true);
264         tree.view.selection.select( item_pos );
265         return true;
266 }
267
268 function removeTemplateFilterValue () {
269
270         var active_tab = filterByAttribute(
271                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
272                 'selected',
273                 'true'
274         )[0];
275
276         var tabname = active_tab.getAttribute('id');
277
278         var tabpanel = $( tabname + 'panel' );
279         var tree = tabpanel.getElementsByTagName('tree')[0];
280         var item_pos = tree.view.selection.currentIndex;
281         var items = getSelectedItems(tree);
282
283         for (var i in items) {
284                 var item = items[i];
285                 var relation_alias = item.getAttribute('relation');
286
287                 var field = item.firstChild.firstChild;
288                 var colname = field.nextSibling.getAttribute('label');
289
290                 rpt_rel_cache[relation_alias].fields[tabname][colname].op_value = {};
291         }
292
293         renderSources(true);
294         tree.view.selection.select( item_pos );
295         return true;
296 }
297
298 function timestampSetDate (obj, cal, date) {
299         obj.op_value.value = date;
300         obj.op_value.object = cal.date;
301         obj.op_value.label = '"' + date + '"';
302
303         renderSources(true);
304         return true;
305 }
306
307 var __handler_cache;
308
309 function changeTemplateFilterValue () {
310
311         var active_tab = filterByAttribute(
312                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
313                 'selected',
314                 'true'
315         )[0];
316
317         var tabname = active_tab.getAttribute('id');
318
319         var tabpanel = $( tabname + 'panel' );
320         var tree = tabpanel.getElementsByTagName('tree')[0];
321         var items = getSelectedItems(tree);
322
323         var targetCmd = $( tabname + '_value_action' );
324
325         targetCmd.menu = null;
326         targetCmd.command = null;
327         targetCmd.oncommand = null;
328         targetCmd.removeEventListener( 'command', __handler_cache, true );
329
330         for (var i in items) {
331                 var item = items[i];
332                 var relation_alias = item.getAttribute('relation');
333
334                 var field = item.firstChild.firstChild;
335                 var colname = field.nextSibling.getAttribute('label');
336
337                 var obj = rpt_rel_cache[relation_alias].fields[tabname][colname]
338                 var operation = OILS_RPT_FILTERS[obj.op];
339
340                 switch (obj.datatype) {
341                         case 'timestamp':
342                                 var cal_popup = $('calendar-widget');
343
344                                 while (cal_popup.firstChild) cal_popup.removeChild(cal_popup.lastChild);
345                                 var calendar = new Calendar(
346                                         0,
347                                         obj.op_value.object,
348                                         function (cal,date) { return timestampSetDate(obj,cal,date) },
349                                         function (cal) { cal_popup.hidePopup(); cal.destroy(); return true; }
350                                 );
351
352                                 var format = OILS_RPT_TRANSFORMS[obj.transform].cal_format || '%Y-%m-%d';
353
354                                 calendar.setDateFormat(format);
355                                 calendar.create(cal_popup);
356
357                                 targetCmd.menu = 'calendar-widget';
358
359                                 break;
360
361                         case 'bool':
362
363                                 function __bool_value_event_handler () {
364                                         var state, answer;
365
366                                         try {
367                                                 // get a reference to the prompt service component.
368                                                 var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
369                                                                     .getService(Components.interfaces.nsIPromptService);
370
371                                                 // set the buttons that will appear on the dialog. It should be
372                                                 // a set of constants multiplied by button position constants. In this case,
373                                                 // three buttons appear, Save, Cancel and a custom button.
374                                                 var flags=promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0 +
375                                                         promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_1 +
376                                                         promptService.BUTTON_TITLE_CANCEL * promptService.BUTTON_POS_2;
377
378                                                 // display the dialog box. The flags set above are passed
379                                                 // as the fourth argument. The next three arguments are custom labels used for
380                                                 // the buttons, which are used if BUTTON_TITLE_IS_STRING is assigned to a
381                                                 // particular button. The last two arguments are for an optional check box.
382                                                 answer = promptService.select(
383                                                         window,
384                                                         "Boolean Value",
385                                                         "Select the value, or cancel:",
386                                                         2, ["True", "False"], state
387                                                 );
388                                         } catch (e) {
389                                                 answer = true;
390                                                 state = confirm("Click OK for TRUE and Cancel for FALSE.");
391                                                 state ? state = 0 : state = 1;
392                                         }
393
394                                         if (answer) {
395                                                 if (state) {
396                                                         obj.op_value.value = 'f';
397                                                         obj.op_value.label = 'False';
398                                                 } else {
399                                                         obj.op_value.value = 't';
400                                                         obj.op_value.label = 'True';
401                                                 }
402                                         }
403
404                                         targetCmd.removeEventListener( 'command', __bool_value_event_handler, true );
405                                         renderSources(true);
406                                         tree.view.selection.select( item_pos );
407                                         return true;
408                                 }
409
410                                 __handler_cache = __bool_value_event_handler;
411                                 targetCmd.addEventListener( 'command', __bool_value_event_handler, true );
412
413                                 break;
414
415                         default:
416
417
418                                 var promptstring = "Field does not match one of list (comma separated):";
419
420                                 switch (obj.op) {
421                                         case 'not between':
422                                                 promptstring = "Field value is not between (comma separated):";
423                                                 break;
424
425                                         case 'between':
426                                                 promptstring = "Field value is between (comma separated):";
427                                                 break;
428
429                                         case 'not in':
430                                                 promptstring = "Field does not match one of list (comma separated):";
431                                                 break;
432
433                                         case 'in':
434                                                 promptstring = "Field matches one of list (comma separated):";
435                                                 break;
436
437                                         default:
438                                                 promptstring = "Value " + obj.op_label + ":";
439                                                 break;
440                                 }
441
442                                 function __default_value_event_handler () {
443                                         var _v;
444                                         if (_v  = prompt( promptstring, obj.op_value.value || '' )) {
445                                                 switch (obj.op) {
446                                                         case 'between':
447                                                         case 'not between':
448                                                         case 'not in':
449                                                         case 'in':
450                                                                 obj.op_value.value = _v.split(/\s*,\s*/);
451                                                                 break;
452
453                                                         default:
454                                                                 obj.op_value.value = _v;
455                                                                 break;
456                                                 }
457
458                                                 obj.op_value.label = '"' + obj.op_value.value + '"';
459                                         }
460
461                                         targetCmd.removeEventListener( 'command', __default_value_event_handler, true );
462                                         renderSources(true);
463                                         tree.view.selection.select( item_pos );
464                                         return true;
465                                 }
466
467                                 __handler_cache = __default_value_event_handler;
468                                 targetCmd.addEventListener( 'command', __default_value_event_handler, true );
469
470                                 break;
471                 }
472         }
473
474         return true;
475 }
476
477 function populateOperatorContext () {
478
479         var active_tab = filterByAttribute(
480                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
481                 'selected',
482                 'true'
483         )[0];
484
485         var tabname = active_tab.getAttribute('id');
486
487         var tabpanel = $( tabname + 'panel' );
488         var tree = tabpanel.getElementsByTagName('tree')[0];
489         var items = getSelectedItems(tree);
490
491         var dtypes = [];
492         for (var i in items) {
493                 var item = items[i];
494                 dtypes.push( item.getAttribute('datatype') );
495         }
496
497         var menu = $(tabname + '_op_menu');
498         while (menu.firstChild) menu.removeChild(menu.lastChild);
499
500         for (var i in OILS_RPT_FILTERS) {
501                 var o = OILS_RPT_FILTERS[i];
502                 menu.appendChild(
503                         createMenuItem(
504                                 { label : o.label,
505                                   command : function () { return changeOperator({op:i,label:o.label}) },
506                                 }
507                         )
508                 );
509                 if (o.labels) {
510                         var keys = getKeys(o.labels);
511                         for ( var k in keys ) {
512                                 var key = keys[k];
513                                 if ( grep(function(x){return key==x},dtypes).length ) {
514                                         menu.appendChild(
515                                                 createMenuItem(
516                                                         { label : o.labels[key],
517                                                           command : function () { return changeOperator({op:i,label:o.labels[key]}); },
518                                                         }
519                                                 )
520                                         );
521                                 }
522                         }
523                 }
524         }
525 }
526
527 function populateTransformContext () {
528
529         var active_tab = filterByAttribute(
530                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
531                 'selected',
532                 'true'
533         )[0];
534
535         var tabname = active_tab.getAttribute('id');
536
537         var tabpanel = $( tabname + 'panel' );
538         var tree = tabpanel.getElementsByTagName('tree')[0];
539         var items = getSelectedItems(tree);
540
541         var transforms = {};
542         for (var i in items) {
543                 var item = items[i];
544                 var dtype = item.getAttribute('datatype');
545                 var item_transforms = getTransforms({ datatype : dtype });
546
547                 for (var j in item_transforms) {
548                         transforms[item_transforms[j]] = OILS_RPT_TRANSFORMS[item_transforms[j]];
549                         transforms[item_transforms[j]].name = item_transforms[j];
550                 }
551         }
552
553         var transformList = [];
554         for (var i in transforms) {
555                 transformList.push( transforms[i] );
556         }
557
558         transformList.sort( sortHashLabels );
559
560         var menu = $(tabname + '_trans_menu');
561         while (menu.firstChild) menu.removeChild(menu.lastChild);
562
563         for (var i in transformList) {
564                 var t = transformList[i];
565
566                 if (tabname.match(/filter/)) {
567                         if (tabname.match(/^agg/)) {
568                                 if (!t.aggregate) continue;
569                         } else {
570                                 if (t.aggregate) continue;
571                         }
572                 }
573
574                 menu.appendChild(
575                         createMenuItem(
576                                 { aggregate : t.aggregate,
577                                   name : t.name,
578                                   alias : t.label,
579                                   label : t.label,
580                                   params : t.params,
581                                   command : function () { return alterColumnTransform(t.name) }
582                                 }
583                         )
584                 );
585         }
586
587         menu.parentNode.setAttribute('disabled','false');
588         if (menu.childNodes.length == 0) {
589                 menu.parentNode.setAttribute('disabled','true');
590         }
591 }
592
593
594 function renderSources (selected) {
595
596         var tree = $('used-sources');
597         var sources = $('used-sources-treetop');
598         var tabs = $('used-source-fields-tabbox').getElementsByTagName('tab');
599
600         if (!selected) {
601                 while (sources.firstChild) sources.removeChild(sources.lastChild);
602         } else {
603                 selected = getSelectedItems(tree);
604                 if (!selected.length) {
605                         selected = undefined;
606                         while (sources.firstChild) sources.removeChild(sources.lastChild);
607                 }
608         }
609
610         for (var j = 0; j < tabs.length; j++) {
611                 var tab = tabs[j];
612                 var tabname = tab.getAttribute('id')
613                 var tabpanel = $( tab.getAttribute('id') + 'panel' );
614                 var fieldtree = tabpanel.getElementsByTagName('treechildren')[0];
615
616                 while (fieldtree.firstChild) fieldtree.removeChild(fieldtree.lastChild);
617         }
618
619         for (var relation_alias in rpt_rel_cache) {
620                 if (!rpt_rel_cache[relation_alias].fields) continue;
621
622                 if (selected) {
623                         if (
624                                 !grep(
625                                         function (x) {
626                                                 return x.getAttribute('relation') == relation_alias;
627                                         },
628                                         selected
629                                 ).length
630                         ) continue;
631                 } else {
632
633                         $('used-sources-treetop').appendChild(
634                                 createTreeItem(
635                                         { relation : rpt_rel_cache[relation_alias].alias,
636                                           idlclass : rpt_rel_cache[relation_alias].idlclass,
637                                           reltype  : rpt_rel_cache[relation_alias].reltype,
638                                           path     : rpt_rel_cache[relation_alias].path,
639                                         },
640                                         createTreeRow(
641                                                 {},
642                                                 createTreeCell({ label : rpt_rel_cache[relation_alias].label }),
643                                                 createTreeCell({ label : rpt_rel_cache[relation_alias].table }),
644                                                 createTreeCell({ label : rpt_rel_cache[relation_alias].alias }),
645                                                 createTreeCell({ label : rpt_rel_cache[relation_alias].reltype })
646                                         )
647                                 )
648                         );
649                 }
650
651                 for each (var tabname in ['filter_tab','aggfilter_tab']) {
652                         tabpanel = $( tabname + 'panel' );
653                         fieldtree = tabpanel.getElementsByTagName('treechildren')[0];
654
655                         for (var colname in rpt_rel_cache[relation_alias].fields[tabname]) {
656                                 with (rpt_rel_cache[relation_alias].fields[tabname][colname]) {
657                                         fieldtree.appendChild(
658                                                 createTreeItem(
659                                                         { relation : relation_alias, datatype : datatype },
660                                                         createTreeRow(
661                                                                 {},
662                                                                 createTreeCell({ label : alias }),
663                                                                 createTreeCell({ label : colname }),
664                                                                 createTreeCell({ label : datatype }),
665                                                                 createTreeCell({ label : transform_label }),
666                                                                 createTreeCell({ label : transform })
667                                                         )
668                                                 )
669                                         );
670
671                                         fieldtree.lastChild.firstChild.appendChild(
672                                                 createTreeCell({ op : op, label : op_label })
673                                         );
674
675                                         if (op_value.value != undefined) {
676                                                 fieldtree.lastChild.firstChild.appendChild(
677                                                         createTreeCell({ label : op_value.label })
678                                                 );
679                                         }
680                                 }
681                         }
682                 }
683         }
684
685         tabpanel = $( 'dis_tabpanel' );
686         fieldtree = tabpanel.getElementsByTagName('treechildren')[0];
687         for each (var order in rpt_rel_cache.order_by) {
688
689                 if (selected) {
690                         if (
691                                 !grep(
692                                         function (x) {
693                                                 return x.getAttribute('relation') == order.relation;
694                                         },
695                                         selected
696                                 ).length
697                         ) continue;
698                 }
699
700                 with (rpt_rel_cache[order.relation].fields.dis_tab[order.field]) {
701                         fieldtree.appendChild(
702                                 createTreeItem(
703                                         { relation : order.relation, datatype : datatype },
704                                         createTreeRow(
705                                                 {},
706                                                 createTreeCell({ label : alias }),
707                                                 createTreeCell({ label : colname }),
708                                                 createTreeCell({ label : datatype }),
709                                                 createTreeCell({ label : transform_label }),
710                                                 createTreeCell({ label : transform })
711                                         )
712                                 )
713                         );
714
715                         fieldtree.lastChild.firstChild.appendChild(
716                                 createTreeCell({ op : op, label : op_label })
717                         );
718
719                         if (op_value.value != undefined) {
720                                 fieldtree.lastChild.firstChild.appendChild(
721                                         createTreeCell({ label : op_value.label })
722                                 );
723                         }
724                 }
725         }
726 }
727
728 var param_count;
729 var tab_use = {
730         dis_tab       : 'select',
731         filter_tab    : 'where',
732         aggfilter_tab : 'having',
733 };
734
735
736 function save_template () {
737         param_count = 0;
738
739         var template = {
740                 version    : 1,
741                 core_class : $('sources-treetop').getElementsByTagName('treeitem')[0].getAttribute('idlclass'),
742                 select     : [],
743                 from       : {},
744                 where      : [],
745                 having     : [],
746                 order_by   : []
747         };
748
749         for (var relname in rpt_rel_cache) {
750                 var relation = rpt_rel_cache[relname];
751                 if (!relation.fields) continue;
752
753                 // first, add the where and having clauses (easier)
754                 for each (var tab_name in [ 'filter_tab', 'aggfilter_tab' ]) {
755                         var tab = relation.fields[tab_name];
756                         for (var field in tab) {
757                                 fleshTemplateField( template, relation, tab_name, field );
758                         }
759                 }
760
761                 // now the from clause
762                 fleshFromPath( template, relation );
763         }
764
765         // and now for select (based on order_by)
766         for each (var order in rpt_rel_cache.order_by)
767                 fleshTemplateField( template, rpt_rel_cache[order.relation], 'dis_tab', order.field );
768
769         prompt( 'template', js2JSON( template ) );
770
771         // and the saving throw ...
772         var cgi = new CGI();
773         var session = cgi.param('ses');
774         fetchUser( session );
775
776         var tmpl = new rt();
777         tmpl.name( $('template-name').value );
778         tmpl.description( $('template-description').value );
779         tmpl.owner(USER.id());
780         tmpl.folder(cgi.param('folder'));
781         tmpl.data(js2JSON(template));
782
783         if(!confirm('Name : '+tmpl.name() + '\nDescription: ' + tmpl.description()+'\nSave Template?'))
784                 return;
785
786         var req = new Request('open-ils.reporter:open-ils.reporter.template.create', session, tmpl);
787         req.request.alertEvent = false;
788         req.callback(
789                 function(r) {
790                         var res = r.getResultObject();
791                         if(checkILSEvent(res)) {
792                                 alertILSEvent(res);
793                         } else {
794                                 if( res && res != '0' ) {
795                                         confirm('Template ' + tmpl.name() + ' was successfully saved.');
796                                         _l('../oils_rpt.xhtml');
797                                 }
798                         }
799                 }
800         );
801
802         req.send();
803 }
804
805 function fleshFromPath ( template, rel ) {
806         var table_path = rel.path.split( /\./ );
807         if (table_path.length > 1 || rel.path.indexOf('-') > -1) table_path.push( rel.idlclass );
808
809         var prev_type = '';
810         var prev_link = '';
811         var current_path = '';
812         var current_obj = template.from;
813         var link;
814         while (link = table_path.shift()) {
815                 if (current_path) current_path += '-';
816                 current_path += link;
817
818                 var leaf = table_path.length == 0 ? true : false;
819
820                 current_obj.path = current_path;
821                 current_obj.table = getIDLClass( link.split(/-/)[0] ).getAttributeNS( persistNS, 'tablename' );
822
823                 if (prev_link != '') {
824                         var prev_class = getIDLClass( prev_link.split(/-/)[0] );
825                         var prev_field = prev_link.split(/-/)[1];
826
827                         var current_link = getIDLLink( prev_class, prev_field );
828                         current_obj.key = current_link.getAttribute('key');
829
830                         if (
831                                 current_link.getAttribute('reltype') != 'has_a' ||
832                                 prev_type == 'left' ||
833                                 rel.reltype != 'has_a'
834                         ) current_obj.type = 'left';
835
836                         prev_type = current_obj.type; 
837                 }
838
839                 if (leaf) {
840                         current_obj.label = rel.label;
841                         current_obj.alias = rel.alias;
842                         current_obj.idlclass = rel.idlclass;
843                         current_obj.template_path = rel.path;
844                 } else {
845                         var current_class = getIDLClass( link.split(/-/)[0] );
846                         var join_field = link.split(/-/)[1];
847                         var join_link = getIDLLink(current_class, join_field);
848
849                         if (join_link.getAttribute('reltype') != 'has_a') {
850                                 var fields_el = current_class.getElementsByTagName('fields')[0];
851                                 join_field = fields_el.getAttributeNS(persistNS, 'primary') + '-' + join_link.getAttribute('key');
852                         }
853
854                         current_obj.alias = hex_md5( current_path ) ;
855                         join_field += '-' + current_obj.alias;
856                         if (table_path.length == 1) join_field += '-' + rel.alias;
857
858                         if (!current_obj.join) current_obj.join = {};
859                         if (!current_obj.join[join_field]) current_obj.join[join_field] = {};
860
861                         if (current_obj.type == 'left') current_obj.join[join_field].type = 'left';
862
863                         current_obj = current_obj.join[join_field];
864                 }
865
866                 prev_link = link;
867         }
868
869
870 }
871
872 function fleshTemplateField ( template, rel, tab_name, field ) {
873
874         if (!rel.fields[tab_name] || !rel.fields[tab_name][field]) return;
875
876         prompt('eh',js2JSON(rel));
877
878         var tab = rel.fields[tab_name];
879
880         var field_path = rel.path + '-' + rel.idlclass + '-' + field;
881         field_path = field_path.replace(/\./g, '-');
882
883         var element = {
884                 alias : tab[field].alias,
885                 column :
886                         { colname : field,
887                           transform : tab[field].transform,
888                           transform_label : tab[field].transform_label
889                         },
890                 path : field_path,
891                 relation : rel.alias
892         };
893
894         if (tab_name.match(/filter/)) {
895                 element.condition = {};
896                 element.condition[tab[field].op] =
897                         tab[field].op_value.value ?
898                                 tab[field].op_value.value :
899                                 '::P' + param_count++;
900         }
901
902         template[tab_use[tab_name]].push(element);
903 }
904