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