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