]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/idl.js
3e4171543d476168753495962849d1934c13efb4
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / services / idl.js
1 /**
2  * Core Service - egIDL
3  *
4  * IDL parser
5  * usage:
6  *  var aou = new egIDL.aou();
7  *  var fullIDL = egIDL.classes;
8  *
9  *  IDL TODO:
10  *
11  * 1. selector field only appears once per class.  We could save
12  *    a lot of IDL (network) space storing it only once at the 
13  *    class level.
14  * 2. we don't need to store array_position in /IDL2js since it
15  *    can be derived at parse time.  Ditto saving space.
16  */
17 angular.module('egCoreMod')
18
19 .factory('egIDL', ['$window', function($window) {
20
21     var service = {};
22
23     // Clones data structures containing fieldmapper objects
24     service.Clone = function(old) {
25         var obj;
26         if (typeof old == 'undefined') {
27             return old;
28         } else if (old._isfieldmapper) {
29             obj = new service[old.classname]()
30
31             for( var i in old.a ) {
32                 var thing = old.a[i];
33                 if(thing === null) continue;
34
35                 if (typeof thing == 'undefined') {
36                     obj.a[i] = thing;
37                 } else if (thing._isfieldmapper) {
38                     obj.a[i] = service.Clone(thing);
39                 } else {
40
41                     if(angular.isArray(thing)) {
42                         obj.a[i] = [];
43
44                         for( var j in thing ) {
45
46                             if (typeof thing[j] == 'undefined')
47                                 obj.a[i][j] = thing[j];
48                             else if( thing[j]._isfieldmapper )
49                                 obj.a[i][j] = service.Clone(thing[j]);
50                             else
51                                 obj.a[i][j] = angular.copy(thing[j]);
52                         }
53                     } else {
54                         obj.a[i] = angular.copy(thing);
55                     }
56                 }
57             }
58         } else {
59             if(angular.isArray(old)) {
60                 obj = [];
61                 for( var j in old ) {
62                     if (typeof old[j] == 'undefined')
63                         obj[j] = old[j];
64                     else if( old[j]._isfieldmapper )
65                         obj[j] = service.Clone(old[j]);
66                     else
67                         obj[j] = angular.copy(old[j]);
68                 }
69             } else if(angular.isObject(old)) {
70                 obj = {};
71                 for( var j in old ) {
72                     if (typeof old[j] == 'undefined')
73                         obj[j] = old[j];
74                     else if( old[j]._isfieldmapper )
75                         obj[j] = service.Clone(old[j]);
76                     else
77                         obj[j] = angular.copy(old[j]);
78                 }
79             } else {
80                 obj = angular.copy(old);
81             }
82         }
83         return obj;
84     };
85
86     service.parseIDL = function() {
87         //console.debug('egIDL.parseIDL()');
88
89         // retain a copy of the full IDL within the service
90         service.classes = $window._preload_fieldmapper_IDL;
91
92         // keep this reference around (note: not a clone, just a ref)
93         // so that unit tests, which repeatedly instantiate the
94         // service will work.
95         //$window._preload_fieldmapper_IDL = null;
96
97         /**
98          * Creates the class constructor and getter/setter
99          * methods for each IDL class.
100          */
101         function mkclass(cls, fields) {
102
103             service.classes[cls].core_label = service.classes[cls].core ? 'Core sources' : 'Non-core sources';
104             service.classes[cls].classname = cls;
105
106             service[cls] = function(seed) {
107                 this.a = seed || [];
108                 this.classname = cls;
109                 this._isfieldmapper = true;
110             }
111
112             /** creates the getter/setter methods for each field */
113             angular.forEach(fields, function(field, idx) {
114                 service[cls].prototype[fields[idx].name] = function(n) {
115                     if (arguments.length==1) this.a[idx] = n;
116                     return this.a[idx];
117                 }
118             });
119
120             // global class constructors required for JSON_v1.js
121             $window[cls] = service[cls]; 
122         }
123
124         for (var cls in service.classes) 
125             mkclass(cls, service.classes[cls].fields);
126     };
127
128     /**
129      * Generate a hash version of an IDL object.
130      *
131      * Flatten determines if nested objects should be squashed into
132      * the top-level hash.
133      *
134      * If 'flatten' is false, e.g.:
135      *
136      * {"call_number" : {"label" :  "foo"}}
137      *
138      * If 'flatten' is true, e.g.:
139      *
140      * e.g.  {"call_number.label" : "foo"}
141      */
142     service.toHash = function(obj, flatten) {
143         if (!angular.isObject(obj)) return obj; // arrays are objects
144
145         if (angular.isArray(obj)) { // NOTE: flatten arrays not supported
146             return obj.map(function(item) {return service.toHash(item)});
147         }
148
149         var field_names = obj.classname ? 
150             Object.keys(service.classes[obj.classname].field_map) :
151             Object.keys(obj);
152
153         var hash = {};
154         angular.forEach(
155             field_names,
156             function(field) { 
157
158                 var val = service.toHash(
159                     angular.isFunction(obj[field]) ? 
160                         obj[field]() : obj[field], 
161                     flatten
162                 );
163
164                 if (flatten && angular.isObject(val)) {
165                     angular.forEach(val, function(sub_val, key) {
166                         var fname = field + '.' + key;
167                         hash[fname] = sub_val;
168                     });
169
170                 } else if (val !== undefined) {
171                     hash[field] = val;
172                 }
173             }
174         );
175
176         return hash;
177     }
178
179     // returns a simple string key=value string of an IDL object.
180     service.toString = function(obj) {
181         var s = '';
182         angular.forEach(
183             service.classes[obj.classname].fields.sort(
184                 function(a,b) {return a.name < b.name ? -1 : 1}),
185             function(field) {
186                 s += field.name + '=' + obj[field.name]() + '\n';
187             }
188         );
189         return s;
190     }
191
192     // hash-to-IDL object translater.  Does not support nested values.
193     service.fromHash = function(cls, hash) {
194         if (!service.classes[cls]) {
195             console.error('No such IDL class ' + cls);
196             return null;
197         }
198
199         var new_obj = new service[cls]();
200         angular.forEach(hash, function(val, key) {
201             if (!angular.isFunction(new_obj[key])) return;
202             new_obj[key](hash[key]);
203         });
204
205         return new_obj;
206     }
207
208     // Transforms a flattened hash (see toHash() or egGridFlatDataProvider)
209     // to a nested hash.
210     //
211     // e.g. {"call_number.label" : "foo"} => {"call_number":{"label":"foo"}}
212     service.flatToNestedHash = function(obj) {
213         var hash = {};
214         angular.forEach(obj, function(val, key) {
215             var parts = key.split('.');
216             var sub_hash = hash;
217             var last_key;
218             for (var i = 0; i < parts.length; i++) {
219                 var part = parts[i];
220                 if (i == parts.length - 1) {
221                     sub_hash[part] = val;
222                     break;
223                 } else {
224                     if (!sub_hash[part])
225                         sub_hash[part] = {};
226                     sub_hash = sub_hash[part];
227                 }
228             }
229         });
230
231         return hash;
232     }
233
234     // Using IDL links, allow construction of a tree-ish data structure from
235     // the IDL2js web service output.  This structure will be directly usable
236     // by the <treecontrol> directive
237     service.classTree = {
238         top : null
239     };
240
241     function _sort_class_fields (a,b) {
242         var aname = a.label || a.name;
243         var bname = b.label || b.name;
244         return aname > bname ? 1 : -1;
245     }
246
247     service.classTree.buildNode = function (cls, args) {
248         if (!cls) return null;
249
250         var n = service.classes[cls];
251         if (!n) return null;
252
253         if (!args)
254             args = { label : n.label };
255
256         args.id = cls;
257         if (args.from)
258             args.id = args.from + '.' + args.id;
259
260         return angular.extend( args, {
261             idl     : service[cls],
262             jtype   : 'inner',
263             uplink  : args.link,
264             classname: cls,
265             struct  : n,
266             table   : n.table,
267             fields  : n.fields.sort( _sort_class_fields ),
268             links   : n.fields
269                 .filter( function(x) { return x.type == 'link'; } )
270                 .sort( _sort_class_fields ),
271             children: []
272         });
273     }
274
275     service.classTree.fleshNode = function ( node ) {
276         if (node.children.length > 0)
277             return node; // already done already
278
279         angular.forEach(
280             node.links.sort( _sort_class_fields ),
281             function (n) {
282                 var nlabel = n.label ? n.label : n.name;
283                 node.children.push(
284                     service.classTree.buildNode(
285                         n["class"],
286                         {   label : nlabel,
287                             from  : node.id,
288                             link  : n
289                         }
290                     )
291                 );
292             }
293         );
294
295         return node;
296     }
297
298     service.classTree.setTop = function (cls) {
299         console.debug('setTop: '+cls);
300         return service.classTree.top = service.classTree.fleshNode(
301             service.classTree.buildNode(cls)
302         );
303     }
304
305     service.classTree.getTop = function () {
306         return service.classTree.top;
307     }
308
309     return service;
310 }])
311 ;