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