]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/reports/xul/template-config.js
focus on name element
[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         $('template-name').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         $('template-name').focus();
267         return true;
268 }
269
270 function removeTemplateFilterValue () {
271
272         var active_tab = filterByAttribute(
273                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
274                 'selected',
275                 'true'
276         )[0];
277
278         var tabname = active_tab.getAttribute('id');
279
280         var tabpanel = $( tabname + 'panel' );
281         var tree = tabpanel.getElementsByTagName('tree')[0];
282         var item_pos = tree.view.selection.currentIndex;
283         var items = getSelectedItems(tree);
284
285         for (var i in items) {
286                 var item = items[i];
287                 var relation_alias = item.getAttribute('relation');
288
289                 var field = item.firstChild.firstChild;
290                 var colname = field.nextSibling.getAttribute('label');
291
292                 rpt_rel_cache[relation_alias].fields[tabname][colname].op_value = {};
293         }
294
295         renderSources(true);
296         tree.view.selection.select( item_pos );
297         return true;
298 }
299
300 function timestampSetDate (obj, cal, date) {
301         obj.op_value.value = date;
302         obj.op_value.object = cal.date;
303         obj.op_value.label = '"' + date + '"';
304
305         renderSources(true);
306         return true;
307 }
308
309 var __handler_cache;
310
311 function changeTemplateFilterValue () {
312
313         var active_tab = filterByAttribute(
314                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
315                 'selected',
316                 'true'
317         )[0];
318
319         var tabname = active_tab.getAttribute('id');
320
321         var tabpanel = $( tabname + 'panel' );
322         var tree = tabpanel.getElementsByTagName('tree')[0];
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 items = getSelectedItems(tree);
492
493         var dtypes = [];
494         for (var i in items) {
495                 var item = items[i];
496                 dtypes.push( item.getAttribute('datatype') );
497         }
498
499         var menu = $(tabname + '_op_menu');
500         while (menu.firstChild) menu.removeChild(menu.lastChild);
501
502         for (var i in OILS_RPT_FILTERS) {
503                 var o = OILS_RPT_FILTERS[i];
504                 menu.appendChild(
505                         createMenuItem(
506                                 { label : o.label,
507                                   oncommand : "changeOperator({op:'"+i+"',label:'"+o.label+"'})",
508                                 }
509                         )
510                 );
511                 if (o.labels) {
512                         var keys = getKeys(o.labels);
513                         for ( var k in keys ) {
514                                 var key = keys[k];
515                                 if ( grep(function(x){return key==x},dtypes).length ) {
516                                         menu.appendChild(
517                                                 createMenuItem(
518                                                         { label : o.labels[key],
519                                                           command : function () { return changeOperator({op:i,label:o.labels[key]}) },
520                                                         }
521                                                 )
522                                         );
523                                 }
524                         }
525                 }
526         }
527 }
528
529 function populateTransformContext () {
530
531         var active_tab = filterByAttribute(
532                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
533                 'selected',
534                 'true'
535         )[0];
536
537         var tabname = active_tab.getAttribute('id');
538
539         var tabpanel = $( tabname + 'panel' );
540         var tree = tabpanel.getElementsByTagName('tree')[0];
541         var items = getSelectedItems(tree);
542
543         var transforms = {};
544         for (var i in items) {
545                 var item = items[i];
546                 var dtype = item.getAttribute('datatype');
547                 var item_transforms = getTransforms({ datatype : dtype });
548
549                 for (var j in item_transforms) {
550                         transforms[item_transforms[j]] = OILS_RPT_TRANSFORMS[item_transforms[j]];
551                         transforms[item_transforms[j]].name = item_transforms[j];
552                 }
553         }
554
555         var transformList = [];
556         for (var i in transforms) {
557                 transformList.push( transforms[i] );
558         }
559
560         transformList.sort( sortHashLabels );
561
562         var menu = $(tabname + '_trans_menu');
563         while (menu.firstChild) menu.removeChild(menu.lastChild);
564
565         for (var i in transformList) {
566                 var t = transformList[i];
567
568                 if (tabname.match(/filter/)) {
569                         if (tabname.match(/^agg/)) {
570                                 if (!t.aggregate) continue;
571                         } else {
572                                 if (t.aggregate) continue;
573                         }
574                 }
575
576                 menu.appendChild(
577                         createMenuItem(
578                                 { aggregate : t.aggregate,
579                                   name : t.name,
580                                   alias : t.label,
581                                   label : t.label,
582                                   params : t.params,
583                                   command : function () { return alterColumnTransform(t.name) }
584                                 }
585                         )
586                 );
587         }
588
589         menu.parentNode.setAttribute('disabled','false');
590         if (menu.childNodes.length == 0) {
591                 menu.parentNode.setAttribute('disabled','true');
592         }
593 }
594
595
596 function renderSources (selected) {
597
598         var tree = $('used-sources');
599         var sources = $('used-sources-treetop');
600         var tabs = $('used-source-fields-tabbox').getElementsByTagName('tab');
601
602         if (!selected) {
603                 while (sources.firstChild) sources.removeChild(sources.lastChild);
604         } else {
605                 selected = getSelectedItems(tree);
606                 if (!selected.length) {
607                         selected = undefined;
608                         while (sources.firstChild) sources.removeChild(sources.lastChild);
609                 }
610         }
611
612         for (var j = 0; j < tabs.length; j++) {
613                 var tab = tabs[j];
614                 var tabname = tab.getAttribute('id')
615                 var tabpanel = $( tab.getAttribute('id') + 'panel' );
616                 var fieldtree = tabpanel.getElementsByTagName('treechildren')[0];
617
618                 while (fieldtree.firstChild) fieldtree.removeChild(fieldtree.lastChild);
619         }
620
621         for (var relation_alias in rpt_rel_cache) {
622                 if (!rpt_rel_cache[relation_alias].fields) continue;
623
624                 if (selected) {
625                         if (
626                                 !grep(
627                                         function (x) {
628                                                 return x.getAttribute('relation') == relation_alias;
629                                         },
630                                         selected
631                                 ).length
632                         ) continue;
633                 } else {
634
635                         $('used-sources-treetop').appendChild(
636                                 createTreeItem(
637                                         { relation : rpt_rel_cache[relation_alias].alias,
638                                           idlclass : rpt_rel_cache[relation_alias].idlclass,
639                                           reltype  : rpt_rel_cache[relation_alias].reltype,
640                                           path     : rpt_rel_cache[relation_alias].path,
641                                         },
642                                         createTreeRow(
643                                                 {},
644                                                 createTreeCell({ label : rpt_rel_cache[relation_alias].label }),
645                                                 createTreeCell({ label : rpt_rel_cache[relation_alias].table }),
646                                                 createTreeCell({ label : rpt_rel_cache[relation_alias].alias }),
647                                                 createTreeCell({ label : rpt_rel_cache[relation_alias].reltype })
648                                         )
649                                 )
650                         );
651                 }
652
653                 for each (var tabname in ['filter_tab','aggfilter_tab']) {
654                         tabpanel = $( tabname + 'panel' );
655                         fieldtree = tabpanel.getElementsByTagName('treechildren')[0];
656
657                         for (var colname in rpt_rel_cache[relation_alias].fields[tabname]) {
658                                 with (rpt_rel_cache[relation_alias].fields[tabname][colname]) {
659                                         fieldtree.appendChild(
660                                                 createTreeItem(
661                                                         { relation : relation_alias, datatype : datatype },
662                                                         createTreeRow(
663                                                                 {},
664                                                                 createTreeCell({ label : alias }),
665                                                                 createTreeCell({ label : colname }),
666                                                                 createTreeCell({ label : datatype }),
667                                                                 createTreeCell({ label : transform_label }),
668                                                                 createTreeCell({ label : transform })
669                                                         )
670                                                 )
671                                         );
672
673                                         fieldtree.lastChild.firstChild.appendChild(
674                                                 createTreeCell({ op : op, label : op_label })
675                                         );
676
677                                         if (op_value.value != undefined) {
678                                                 fieldtree.lastChild.firstChild.appendChild(
679                                                         createTreeCell({ label : op_value.label })
680                                                 );
681                                         }
682                                 }
683                         }
684                 }
685         }
686
687         tabpanel = $( 'dis_tabpanel' );
688         fieldtree = tabpanel.getElementsByTagName('treechildren')[0];
689         for each (var order in rpt_rel_cache.order_by) {
690
691                 if (selected) {
692                         if (
693                                 !grep(
694                                         function (x) {
695                                                 return x.getAttribute('relation') == order.relation;
696                                         },
697                                         selected
698                                 ).length
699                         ) continue;
700                 }
701
702                 with (rpt_rel_cache[order.relation].fields.dis_tab[order.field]) {
703                         fieldtree.appendChild(
704                                 createTreeItem(
705                                         { relation : order.relation, datatype : datatype },
706                                         createTreeRow(
707                                                 {},
708                                                 createTreeCell({ label : alias }),
709                                                 createTreeCell({ label : colname }),
710                                                 createTreeCell({ label : datatype }),
711                                                 createTreeCell({ label : transform_label }),
712                                                 createTreeCell({ label : transform })
713                                         )
714                                 )
715                         );
716
717                         fieldtree.lastChild.firstChild.appendChild(
718                                 createTreeCell({ op : op, label : op_label })
719                         );
720
721                         if (op_value.value != undefined) {
722                                 fieldtree.lastChild.firstChild.appendChild(
723                                         createTreeCell({ label : op_value.label })
724                                 );
725                         }
726                 }
727         }
728 }
729
730 var param_count;
731 var tab_use = {
732         dis_tab       : 'select',
733         filter_tab    : 'where',
734         aggfilter_tab : 'having',
735 };
736
737
738 function save_template () {
739         param_count = 0;
740
741         var template = {
742                 version    : 1,
743                 core_class : $('sources-treetop').getElementsByTagName('treeitem')[0].getAttribute('idlclass'),
744                 select     : [],
745                 from       : {},
746                 where      : [],
747                 having     : [],
748                 order_by   : []
749         };
750
751         for (var relname in rpt_rel_cache) {
752                 var relation = rpt_rel_cache[relname];
753                 if (!relation.fields) continue;
754
755                 // first, add the where and having clauses (easier)
756                 for each (var tab_name in [ 'filter_tab', 'aggfilter_tab' ]) {
757                         var tab = relation.fields[tab_name];
758                         for (var field in tab) {
759                                 fleshTemplateField( template, relation, tab_name, field );
760                         }
761                 }
762
763                 // now the from clause
764                 fleshFromPath( template, relation );
765         }
766
767         // and now for select (based on order_by)
768         for each (var order in rpt_rel_cache.order_by)
769                 fleshTemplateField( template, rpt_rel_cache[order.relation], 'dis_tab', order.field );
770
771
772         // and the saving throw ...
773         var cgi = new CGI();
774         var session = cgi.param('ses');
775         fetchUser( session );
776
777         var tmpl = new rt();
778         tmpl.name( $('template-name').value );
779         tmpl.description( $('template-description').value );
780         tmpl.owner(USER.id());
781         tmpl.folder(cgi.param('folder'));
782         tmpl.data(js2JSON(template));
783
784         // prompt( 'template', js2JSON( tmpl ) );
785
786         if(!confirm('Name : '+tmpl.name() + '\nDescription: ' + tmpl.description()+'\nSave Template?'))
787                 return;
788
789         var req = new Request('open-ils.reporter:open-ils.reporter.template.create', session, tmpl);
790         req.request.alertEvent = false;
791         req.callback(
792                 function(r) {
793                         var res = r.getResultObject();
794                         if(checkILSEvent(res)) {
795                                 alertILSEvent(res);
796                         } else {
797                                 if( res && res != '0' ) {
798                                         confirm('Template ' + tmpl.name() + ' was successfully saved.');
799                                         _l('../oils_rpt.xhtml');
800                                 }
801                         }
802                 }
803         );
804
805         req.send();
806 }
807
808 function fleshFromPath ( template, rel ) {
809         var table_path = rel.path.split( /\./ );
810         if (table_path.length > 1 || rel.path.indexOf('-') > -1) table_path.push( rel.idlclass );
811
812         var prev_type = '';
813         var prev_link = '';
814         var current_path = '';
815         var current_obj = template.from;
816         var link;
817         while (link = table_path.shift()) {
818                 if (current_path) current_path += '-';
819                 current_path += link;
820
821                 var leaf = table_path.length == 0 ? true : false;
822
823                 current_obj.path = current_path;
824                 current_obj.table = getIDLClass( link.split(/-/)[0] ).getAttributeNS( persistNS, 'tablename' );
825
826                 if (prev_link != '') {
827                         var prev_class = getIDLClass( prev_link.split(/-/)[0] );
828                         var prev_field = prev_link.split(/-/)[1];
829
830                         var current_link = getIDLLink( prev_class, prev_field );
831                         current_obj.key = current_link.getAttribute('key');
832
833                         if (
834                                 current_link.getAttribute('reltype') != 'has_a' ||
835                                 prev_type == 'left' ||
836                                 rel.reltype != 'has_a'
837                         ) current_obj.type = 'left';
838
839                         prev_type = current_obj.type; 
840                 }
841
842                 if (leaf) {
843                         current_obj.label = rel.label;
844                         current_obj.alias = rel.alias;
845                         current_obj.idlclass = rel.idlclass;
846                         current_obj.template_path = rel.path;
847                 } else {
848                         var current_class = getIDLClass( link.split(/-/)[0] );
849                         var join_field = link.split(/-/)[1];
850                         var join_link = getIDLLink(current_class, join_field);
851
852                         if (join_link.getAttribute('reltype') != 'has_a') {
853                                 var fields_el = current_class.getElementsByTagName('fields')[0];
854                                 join_field = fields_el.getAttributeNS(persistNS, 'primary') + '-' + join_link.getAttribute('key');
855                         }
856
857                         current_obj.alias = hex_md5( current_path ) ;
858                         join_field += '-' + current_obj.alias;
859                         if (table_path.length == 1) join_field += '-' + rel.alias;
860
861                         if (!current_obj.join) current_obj.join = {};
862                         if (!current_obj.join[join_field]) current_obj.join[join_field] = {};
863
864                         if (current_obj.type == 'left') current_obj.join[join_field].type = 'left';
865
866                         current_obj = current_obj.join[join_field];
867                 }
868
869                 prev_link = link;
870         }
871
872
873 }
874
875 function fleshTemplateField ( template, rel, tab_name, field ) {
876
877         if (!rel.fields[tab_name] || !rel.fields[tab_name][field]) return;
878
879         var tab = rel.fields[tab_name];
880
881         var field_path = rel.path + '-' + field;
882         field_path = field_path.replace(/\./g, '-');
883
884         var element = {
885                 alias : tab[field].alias,
886                 column :
887                         { colname : field,
888                           transform : tab[field].transform,
889                           transform_label : tab[field].transform_label
890                         },
891                 path : field_path,
892                 relation : rel.alias
893         };
894
895         if (tab_name.match(/filter/)) {
896                 element.condition = {};
897                 element.condition[tab[field].op] =
898                         tab[field].op_value.value ?
899                                 tab[field].op_value.value :
900                                 '::P' + param_count++;
901         }
902
903         template[tab_use[tab_name]].push(element);
904 }
905