]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/dojo/openils/widget/AutoFieldWidget.js
disabling editing of sequenced fields is better handled in the widgetLoaded function...
[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             this.onload = onload;
107             if(this.widgetValue == null)
108                 this.widgetValue = (this.fmObject) ? this.fmObject[this.idlField.name]() : null;
109
110             if(this.readOnly) {
111                 dojo.require('dijit.layout.ContentPane');
112                 this.widget = new dijit.layout.ContentPane(this.dijitArgs, this.parentNode);
113                 this._tryLinkedDisplayField();
114
115             } else if(this.widgetClass) {
116                 dojo.require(this.widgetClass);
117                 eval('this.widget = new ' + this.widgetClass + '(this.dijitArgs, this.parentNode);');
118
119             } else {
120
121                 switch(this.idlField.datatype) {
122                     
123                     case 'id':
124                         dojo.require('dijit.form.TextBox');
125                         this.widget = new dijit.form.TextBox(this.dijitArgs, this.parentNode);
126                         break;
127
128                     case 'org_unit':
129                         this._buildOrgSelector();
130                         break;
131
132                     case 'money':
133                         dojo.require('dijit.form.CurrencyTextBox');
134                         this.widget = new dijit.form.CurrencyTextBox(this.dijitArgs, this.parentNode);
135                         break;
136
137                     case 'int':
138                         dojo.require('dijit.form.NumberTextBox');
139                         this.dijitArgs = dojo.mixin(this.dijitArgs || {}, {constraints:{places:0}});
140                         this.widget = new dijit.form.NumberTextBox(this.dijitArgs, this.parentNode);
141                         break;
142
143                     case 'float':
144                         dojo.require('dijit.form.NumberTextBox');
145                         this.widget = new dijit.form.NumberTextBox(this.dijitArgs, this.parentNode);
146                         break;
147
148                     case 'timestamp':
149                         dojo.require('dijit.form.DateTextBox');
150                         dojo.require('dojo.date.stamp');
151                         this.widget = new dijit.form.DateTextBox(this.dijitArgs, this.parentNode);
152                         if(this.widgetValue != null) 
153                             this.widgetValue = dojo.date.stamp.fromISOString(this.widgetValue);
154                         break;
155
156                     case 'bool':
157                         dojo.require('dijit.form.CheckBox');
158                         this.widget = new dijit.form.CheckBox(this.dijitArgs, this.parentNode);
159                         this.widgetValue = openils.Util.isTrue(this.widgetValue);
160                         break;
161
162                     case 'link':
163                         if(this._buildLinkSelector()) break;
164
165                     default:
166                         dojo.require('dijit.form.TextBox');
167                         this.widget = new dijit.form.TextBox(this.dijitArgs, this.parentNode);
168                 }
169             }
170
171             if(!this.async) this._widgetLoaded();
172             return this.widget;
173         },
174
175         // we want to display the value for our widget.  However, instead of displaying
176         // an ID, for exmaple, display the value for the 'selector' field on the object
177         // the ID points to
178         _tryLinkedDisplayField : function() {
179
180             if(this.idlField.datatype == 'org_unit')
181                 return false; // we already handle org_units, no need to re-fetch
182
183             var linkInfo = this._getLinkSelector();
184             if(!linkInfo || !linkInfo.vfield) return false;
185             var lclass = linkInfo.linkClass;
186
187             // first try the object list cache
188             if(this.cache[lclass]) {
189                 for(var k in this.cache[lclass]) {
190                     var cc = this.cache[lclass][k];
191                     if(cc[linkInfo.vfield.name]() == this.widgetValue) {
192                         console.log("serving " + this.idlField.name + " from list cache");
193                         this.widgetValue = cc[linkInfo.vfield.selector]();
194                         return;
195                     }
196                 }
197             }
198
199             // then try the single object cache
200             if(this.cacheSingle[lclass] && this.cacheSingle[lclass][this.widgetValue]) {
201                 console.log("serving " + this.idlField.name + " from cacheSingle");
202                 this.widgetValue = this.cacheSingle[lclass][this.widgetValue];
203                 return;
204             }
205
206             // if those fail, fetch the linked object
207             dojo.require('openils.PermaCrud');
208             this.async = true;
209             var self = this;
210             new openils.PermaCrud().retrieve(lclass, this.widgetValue, {   
211                 async : true,
212                 oncomplete : function(r) {
213                     var item = openils.Util.readResponse(r);
214                     if(!self.cacheSingle[lclass])
215                         self.cacheSingle[lclass] = {};
216                     self.widgetValue = item[linkInfo.vfield.selector]();
217                     self.cacheSingle[lclass][self.widgetValue] = item;
218                     self.widget.startup();
219                     self._widgetLoaded();
220                 }
221             });
222         },
223
224         _getLinkSelector : function() {
225             var linkClass = this.idlField['class'];
226             if(this.idlField.reltype != 'has_a')  return false;
227             if(!fieldmapper.IDL.fmclasses[linkClass].permacrud) return false;
228             if(!fieldmapper.IDL.fmclasses[linkClass].permacrud.retrieve) return false;
229
230             var vfield;
231             var rclassIdl = fieldmapper.IDL.fmclasses[linkClass];
232
233             for(var f in rclassIdl.fields) {
234                 if(this.idlField.key == rclassIdl.fields[f].name) {
235                     vfield = rclassIdl.fields[f];
236                     break;
237                 }
238             }
239
240             if(!vfield) 
241                 throw new Error("'" + linkClass + "' has no '" + this.idlField.key + "' field!");
242
243             return {
244                 linkClass : linkClass,
245                 vfield : vfield
246             };
247         },
248
249         _buildLinkSelector : function() {
250             var selectorInfo = this._getLinkSelector();
251             if(!selectorInfo) return false;
252             var linkClass = selectorInfo.linkClass;
253             var vfield = selectorInfo.vfield;
254
255             this.async = true;
256
257             if(linkClass == 'pgt')
258                 return this._buildPermGrpSelector();
259
260             this.widget = new dijit.form.FilteringSelect(this.dijitArgs, this.parentNode);
261             this.widget.searchAttr = this.widget.labelAttr = vfield.selector || vfield.name;
262             this.widget.valueAttr = vfield.name;
263
264             dojo.require('openils.PermaCrud');
265             dojo.require('dojo.data.ItemFileReadStore');
266             dojo.require('dijit.form.FilteringSelect');
267
268             var self = this;
269             var oncomplete = function(list) {
270                 if(list) {
271                     self.widget.store = 
272                         new dojo.data.ItemFileReadStore({data:fieldmapper[linkClass].toStoreData(list)});
273                     self.cache[linkClass] = list;
274                 }
275                 self.widget.startup();
276                 self._widgetLoaded();
277             };
278
279             if(this.cache[linkClass]) {
280                 oncomplete(this.cache[linkClass]);
281
282             } else {
283                 new openils.PermaCrud().retrieveAll(linkClass, {   
284                     async : true,
285                     oncomplete : function(r) {
286                         var list = openils.Util.readResponse(r, false, true);
287                         oncomplete(list);
288                     }
289                 });
290             }
291
292             return true;
293         },
294
295         /**
296          * For widgets that run asynchronously, provide a callback for finishing up
297          */
298         _widgetLoaded : function(value) {
299             if(this.readOnly) {
300                 this.baseWidgetValue(this.getDisplayString());
301             } else {
302                 this.baseWidgetValue(this.widgetValue);
303                 if(this.idlField.name == this.fmIDL.pkey && this.fmIDL.pkey_sequence)
304                     this.widget.attr('disabled', true); 
305             }
306             if(this.onload)
307                 this.onload(this.widget, this);
308         },
309
310         _buildOrgSelector : function() {
311             dojo.require('fieldmapper.OrgUtils');
312             dojo.require('openils.widget.FilteringTreeSelect');
313             this.widget = new openils.widget.FilteringTreeSelect(this.dijitArgs, this.parentNode);
314             this.widget.searchAttr = 'shortname';
315             this.widget.labelAttr = 'shortname';
316             this.widget.parentField = 'parent_ou';
317             var user = new openils.User();
318             if(this.widgetValue == null) 
319                 this.widgetValue = user.user.ws_ou();
320             
321             // if we have a limit perm, find the relevent orgs (async)
322             if(this.orgLimitPerms && this.orgLimitPerms.length > 0) {
323                 this.async = true;
324                 var self = this;
325                 user.getPermOrgList(this.orgLimitPerms, 
326                     function(orgList) {
327                         self.widget.tree = orgList;
328                         self.widget.startup();
329                         self._widgetLoaded();
330                     }
331                 );
332
333             } else {
334                 this.widget.tree = fieldmapper.aou.globalOrgTree;
335                 this.widget.startup();
336             }
337         },
338
339         _buildPermGrpSelector : function() {
340             dojo.require('openils.widget.FilteringTreeSelect');
341             this.widget = new openils.widget.FilteringTreeSelect(this.dijitArgs, this.parentNode);
342             this.widget.searchAttr = 'name';
343
344             if(this.cache.permGrpTree) {
345                 this.widget.tree = this.cache.permGrpTree;
346                 this.widget.startup();
347                 return;
348             } 
349
350             var self = this;
351             this.async = true;
352             new openils.PermaCrud().retrieveAll('pgt', {
353                 async : true,
354                 oncomplete : function(r) {
355                     var list = openils.Util.readResponse(r, false, true);
356                     if(!list) return;
357                     var map = {};
358                     var root = null;
359                     for(var l in list)
360                         map[list[l].id()] = list[l];
361                     for(var l in list) {
362                         var node = list[l];
363                         var pnode = map[node.parent()];
364                         if(!pnode) {root = node; continue;}
365                         if(!pnode.children()) pnode.children([]);
366                         pnode.children().push(node);
367                     }
368                     self.widget.tree = self.cache.permGrpTree = root;
369                     self.widget.startup();
370                     self._widgetLoaded();
371                 }
372             });
373
374             return true;
375         }
376     });
377 }
378