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