]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/dojo/openils/widget/AutoFieldWidget.js
import PermaCrud globally within this module
[working/Evergreen.git] / Open-ILS / web / js / dojo / openils / widget / AutoFieldWidget.js
1 if(!dojo._hasResource['openils.widget.AutoFieldWidget']) {
2     dojo.provide('openils.widget.AutoFieldWidget');
3     dojo.require('openils.Util');
4     dojo.require('openils.User');
5     dojo.require('fieldmapper.IDL');
6     dojo.require('openils.PermaCrud');
7
8     dojo.declare('openils.widget.AutoFieldWidget', null, {
9
10         async : false,
11         cache : {},
12         cacheSingle : {},
13
14         /**
15          * args:
16          *  idlField -- Field description object from fieldmapper.IDL.fmclasses
17          *  fmObject -- If available, the object being edited.  This will be used 
18          *      to set the value of the widget.
19          *  fmClass -- Class name (not required if idlField or fmObject is set)
20          *  fmField -- Field name (not required if idlField)
21          *  parentNode -- If defined, the widget will be appended to this DOM node
22          *  dijitArgs -- Optional parameters object, passed directly to the dojo widget
23          *  orgLimitPerms -- If this field defines a set of org units and an orgLimitPerms 
24          *      is defined, the code will limit the org units in the set to those
25          *      allowed by the permission
26          */
27         constructor : function(args) {
28             for(var k in args)
29                 this[k] = args[k];
30
31             // find the field description in the IDL if not provided
32             if(this.fmObject) 
33                 this.fmClass = this.fmObject.classname;
34             this.fmIDL = fieldmapper.IDL.fmclasses[this.fmClass];
35
36             if(!this.idlField) {
37                 this.fmIDL = fieldmapper.IDL.fmclasses[this.fmClass];
38                 var fields = this.fmIDL.fields;
39                 for(var f in fields) 
40                     if(fields[f].name == this.fmField)
41                         this.idlField = fields[f];
42             }
43
44             if(!this.idlField) 
45                 throw new Error("AutoFieldWidget could not determine which field to render.  We need more information. fmClass=" + 
46                     this.fmClass + ' fmField=' + this.fmField + ' fmObject=' + js2JSON(this.fmObject));
47
48             this.auth = openils.User.authtoken;
49             if(!this.cache[this.auth]) {
50                 this.cache[this.auth] = {};
51             }
52         },
53
54         /**
55          * Turn the widget-stored value into a value oils understands
56          */
57         getFormattedValue : function() {
58             var value = this.baseWidgetValue();
59             switch(this.idlField.datatype) {
60                 case 'bool':
61                     return (value) ? 't' : 'f'
62                 case 'timestamp':
63                     return dojo.date.stamp.toISOString(value);
64                 case 'int':
65                 case 'float':
66                     if(isNaN(value)) value = 0;
67                 default:
68                     return (value === '') ? null : value;
69             }
70         },
71
72         baseWidgetValue : function(value) {
73             var attr = (this.readOnly) ? 'content' : 'value';
74             if(arguments.length) this.widget.attr(attr, value);
75             return this.widget.attr(attr);
76         },
77         
78         /**
79          * Turn the widget-stored value into something visually suitable
80          */
81         getDisplayString : function() {
82             var value = this.widgetValue;
83             switch(this.idlField.datatype) {
84                 case 'bool':
85                     return (value) ? 'True' : 'False'; // XXX i18n!
86                 case 'timestamp':
87                     dojo.require('dojo.date.locale');
88                     dojo.require('dojo.date.stamp');
89                     var date = dojo.date.stamp.fromISOString(value);
90                     return dojo.date.locale.format(date, {formatLength:'short'});
91                 case 'org_unit':
92                     if(value === null || value === undefined) return '';
93                     return fieldmapper.aou.findOrgUnit(value).shortname();
94                 case 'int':
95                 case 'float':
96                     if(isNaN(value)) value = 0;
97                 default:
98                     if(value === undefined || value === null)
99                         value = '';
100                     return value+'';
101             }
102         },
103
104         build : function(onload) {
105
106             if(this.widget) {
107                 // core widget provided for us, attach and move on
108                 if(this.parentNode) // may already be in the "right" place
109                     this.parentNode.appendChild(this.widget.domNode);
110                 return;
111             }
112             
113             if(!this.parentNode) // give it somewhere to live so that dojo won't complain
114                 this.parentNode = document.createElement('div');
115
116             this.onload = onload;
117             if(this.widgetValue == null)
118                 this.widgetValue = (this.fmObject) ? this.fmObject[this.idlField.name]() : null;
119
120             if(this.readOnly) {
121                 dojo.require('dijit.layout.ContentPane');
122                 this.widget = new dijit.layout.ContentPane(this.dijitArgs, this.parentNode);
123                 if(this.widgetValue !== null)
124                     this._tryLinkedDisplayField();
125
126             } else if(this.widgetClass) {
127                 dojo.require(this.widgetClass);
128                 eval('this.widget = new ' + this.widgetClass + '(this.dijitArgs, this.parentNode);');
129
130             } else {
131
132                 switch(this.idlField.datatype) {
133                     
134                     case 'id':
135                         dojo.require('dijit.form.TextBox');
136                         this.widget = new dijit.form.TextBox(this.dijitArgs, this.parentNode);
137                         break;
138
139                     case 'org_unit':
140                         this._buildOrgSelector();
141                         break;
142
143                     case 'money':
144                         dojo.require('dijit.form.CurrencyTextBox');
145                         this.widget = new dijit.form.CurrencyTextBox(this.dijitArgs, this.parentNode);
146                         break;
147
148                     case 'int':
149                         dojo.require('dijit.form.NumberTextBox');
150                         this.dijitArgs = dojo.mixin(this.dijitArgs || {}, {constraints:{places:0}});
151                         this.widget = new dijit.form.NumberTextBox(this.dijitArgs, this.parentNode);
152                         break;
153
154                     case 'float':
155                         dojo.require('dijit.form.NumberTextBox');
156                         this.widget = new dijit.form.NumberTextBox(this.dijitArgs, this.parentNode);
157                         break;
158
159                     case 'timestamp':
160                         dojo.require('dijit.form.DateTextBox');
161                         dojo.require('dojo.date.stamp');
162                         this.widget = new dijit.form.DateTextBox(this.dijitArgs, this.parentNode);
163                         if(this.widgetValue != null) 
164                             this.widgetValue = dojo.date.stamp.fromISOString(this.widgetValue);
165                         break;
166
167                     case 'bool':
168                         dojo.require('dijit.form.CheckBox');
169                         this.widget = new dijit.form.CheckBox(this.dijitArgs, this.parentNode);
170                         this.widgetValue = openils.Util.isTrue(this.widgetValue);
171                         break;
172
173                     case 'link':
174                         if(this._buildLinkSelector()) break;
175
176                     default:
177                         dojo.require('dijit.form.TextBox');
178                         this.widget = new dijit.form.TextBox(this.dijitArgs, this.parentNode);
179                 }
180             }
181
182             if(!this.async) this._widgetLoaded();
183             return this.widget;
184         },
185
186         // we want to display the value for our widget.  However, instead of displaying
187         // an ID, for exmaple, display the value for the 'selector' field on the object
188         // the ID points to
189         _tryLinkedDisplayField : function(noAsync) {
190
191             if(this.idlField.datatype == 'org_unit')
192                 return false; // we already handle org_units, no need to re-fetch
193
194             var linkInfo = this._getLinkSelector();
195             if(!(linkInfo && linkInfo.vfield && linkInfo.vfield.selector)) 
196                 return false;
197             var lclass = linkInfo.linkClass;
198
199             if(lclass == 'aou') {
200                 this.widgetValue = fieldmapper.aou.findOrgUnit(this.widgetValue).shortname();
201                 return;
202             }
203
204             // first try the store cache
205             var self = this;
206             if(this.cache[this.auth][lclass]) {
207                 var store = this.cache[this.auth][lclass];
208                 var query = {};
209                 query[linkInfo.vfield.name] = ''+this.widgetValue;
210                 store.fetch({query:query, onComplete:
211                     function(list) {
212                         self.widgetValue = store.getValue(list[0], linkInfo.vfield.selector);
213                     }
214                 });
215                 return;
216             }
217
218             // then try the single object cache
219             if(this.cacheSingle[lclass] && this.cacheSingle[lclass][this.widgetValue]) {
220                 this.widgetValue = this.cacheSingle[lclass][this.widgetValue];
221                 return;
222             }
223
224             // if those fail, fetch the linked object
225             this.async = true;
226             var self = this;
227             new openils.PermaCrud().retrieve(lclass, this.widgetValue, {   
228                 async : !this.forceSync,
229                 oncomplete : function(r) {
230                     var item = openils.Util.readResponse(r);
231                     if(!self.cacheSingle[lclass])
232                         self.cacheSingle[lclass] = {};
233                     self.widgetValue = item[linkInfo.vfield.selector]();
234                     self.cacheSingle[lclass][self.widgetValue] = item;
235                     self.widget.startup();
236                     self._widgetLoaded();
237                 }
238             });
239         },
240
241         _getLinkSelector : function() {
242             var linkClass = this.idlField['class'];
243             if(this.idlField.reltype != 'has_a')  return false;
244             if(!fieldmapper.IDL.fmclasses[linkClass].permacrud) return false;
245             if(!fieldmapper.IDL.fmclasses[linkClass].permacrud.retrieve) return false;
246
247             var vfield;
248             var rclassIdl = fieldmapper.IDL.fmclasses[linkClass];
249
250             for(var f in rclassIdl.fields) {
251                 if(this.idlField.key == rclassIdl.fields[f].name) {
252                     vfield = rclassIdl.fields[f];
253                     break;
254                 }
255             }
256
257             if(!vfield) 
258                 throw new Error("'" + linkClass + "' has no '" + this.idlField.key + "' field!");
259
260             return {
261                 linkClass : linkClass,
262                 vfield : vfield
263             };
264         },
265
266         _buildLinkSelector : function() {
267             var selectorInfo = this._getLinkSelector();
268             if(!selectorInfo) return false;
269
270             var linkClass = selectorInfo.linkClass;
271             var vfield = selectorInfo.vfield;
272
273             this.async = true;
274
275             if(linkClass == 'pgt')
276                 return this._buildPermGrpSelector();
277             if(linkClass == 'aou')
278                 return this._buildOrgSelector();
279             if(linkClass == 'acpl')
280                 return this._buildCopyLocSelector();
281
282
283             dojo.require('dojo.data.ItemFileReadStore');
284             dojo.require('dijit.form.FilteringSelect');
285
286             this.widget = new dijit.form.FilteringSelect(this.dijitArgs, this.parentNode);
287             this.widget.searchAttr = this.widget.labelAttr = vfield.selector || vfield.name;
288             this.widget.valueAttr = vfield.name;
289
290             var self = this;
291             var oncomplete = function(list) {
292                 if(list) {
293                     self.widget.store = 
294                         new dojo.data.ItemFileReadStore({data:fieldmapper[linkClass].toStoreData(list)});
295                     self.cache[self.auth][linkClass] = self.widget.store;
296                 } else {
297                     self.widget.store = self.cache[self.auth][linkClass];
298                 }
299                 self.widget.startup();
300                 self._widgetLoaded();
301             };
302
303             if(this.cache[self.auth][linkClass]) {
304                 oncomplete();
305
306             } else {
307                 new openils.PermaCrud().retrieveAll(linkClass, {   
308                     async : !this.forceSync,
309                     oncomplete : function(r) {
310                         var list = openils.Util.readResponse(r, false, true);
311                         oncomplete(list);
312                     }
313                 });
314             }
315
316             return true;
317         },
318
319         /**
320          * For widgets that run asynchronously, provide a callback for finishing up
321          */
322         _widgetLoaded : function(value) {
323             if(this.readOnly) {
324                 this.baseWidgetValue(this.getDisplayString());
325             } else {
326                 this.baseWidgetValue(this.widgetValue);
327                 if(this.idlField.name == this.fmIDL.pkey && this.fmIDL.pkey_sequence)
328                     this.widget.attr('disabled', true); 
329                 if(this.disableWidgetTest && this.disableWidgetTest(this.idlField.name, this.fmObject))
330                     this.widget.attr('disabled', true); 
331             }
332             if(this.onload)
333                 this.onload(this.widget, this);
334         },
335
336         _buildOrgSelector : function() {
337             dojo.require('fieldmapper.OrgUtils');
338             dojo.require('openils.widget.FilteringTreeSelect');
339             this.widget = new openils.widget.FilteringTreeSelect(this.dijitArgs, this.parentNode);
340             this.widget.searchAttr = 'shortname';
341             this.widget.labelAttr = 'shortname';
342             this.widget.parentField = 'parent_ou';
343             var user = new openils.User();
344
345             if(this.widgetValue == null) 
346                 this.widgetValue = user.user.ws_ou();
347             
348             // if we have a limit perm, find the relevent orgs (async)
349             if(this.orgLimitPerms && this.orgLimitPerms.length > 0) {
350                 this.async = true;
351                 var self = this;
352                 user.getPermOrgList(this.orgLimitPerms, 
353                     function(orgList) {
354                         self.widget.tree = orgList;
355                         self.widget.startup();
356                         self._widgetLoaded();
357                     }
358                 );
359
360             } else {
361                 this.widget.tree = fieldmapper.aou.globalOrgTree;
362                 this.widget.startup();
363             }
364         },
365
366         _buildPermGrpSelector : function() {
367             dojo.require('openils.widget.FilteringTreeSelect');
368             this.widget = new openils.widget.FilteringTreeSelect(this.dijitArgs, this.parentNode);
369             this.widget.searchAttr = 'name';
370
371             if(this.cache.permGrpTree) {
372                 this.widget.tree = this.cache.permGrpTree;
373                 this.widget.startup();
374                 return true;
375             } 
376
377             var self = this;
378             this.async = true;
379             new openils.PermaCrud().retrieveAll('pgt', {
380                 async : !this.forceSync,
381                 oncomplete : function(r) {
382                     var list = openils.Util.readResponse(r, false, true);
383                     if(!list) return;
384                     var map = {};
385                     var root = null;
386                     for(var l in list)
387                         map[list[l].id()] = list[l];
388                     for(var l in list) {
389                         var node = list[l];
390                         var pnode = map[node.parent()];
391                         if(!pnode) {root = node; continue;}
392                         if(!pnode.children()) pnode.children([]);
393                         pnode.children().push(node);
394                     }
395                     self.widget.tree = self.cache.permGrpTree = root;
396                     self.widget.startup();
397                     self._widgetLoaded();
398                 }
399             });
400
401             return true;
402         },
403
404         _buildCopyLocSelector : function() {
405             dojo.require('dijit.form.FilteringSelect');
406             this.widget = new dijit.form.FilteringSelect(this.dijitArgs, this.parentNode);
407             this.widget.searchAttr = this.widget.labalAttr = 'name';
408             this.widget.valueAttr = 'id';
409
410             if(this.cache.copyLocStore) {
411                 this.widget.store = this.cache.copyLocStore;
412                 this.widget.startup();
413                 this.async = false;
414                 return true;
415             } 
416
417             // my orgs
418             var ws_ou = openils.User.user.ws_ou();
419             var orgs = fieldmapper.aou.findOrgUnit(ws_ou).orgNodeTrail().map(function (i) { return i.id() });
420             orgs = orgs.concat(fieldmapper.aou.descendantNodeList(ws_ou).map(function (i) { return i.id() }));
421
422             var self = this;
423             new openils.PermaCrud().search('acpl', {owning_lib : orgs}, {
424                 async : !this.forceSync,
425                 oncomplete : function(r) {
426                     var list = openils.Util.readResponse(r, false, true);
427                     if(!list) return;
428                     self.widget.store = 
429                         new dojo.data.ItemFileReadStore({data:fieldmapper.acpl.toStoreData(list)});
430                     self.cache.copyLocStore = self.widget.store;
431                     self.widget.startup();
432                     self._widgetLoaded();
433                 }
434             });
435
436             return true;
437         }
438     });
439 }
440