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