]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/dojo/openils/widget/AutoGrid.js
Vandelay-based record matching and import for Acquisitions
[working/Evergreen.git] / Open-ILS / web / js / dojo / openils / widget / AutoGrid.js
1 if(!dojo._hasResource['openils.widget.AutoGrid']) {
2     dojo.provide('openils.widget.AutoGrid');
3     dojo.require('dojox.grid.DataGrid');
4     dojo.require('dijit.layout.ContentPane');
5     dojo.require('openils.widget.AutoWidget');
6     dojo.require('openils.widget.AutoFieldWidget');
7     dojo.require('openils.widget.EditPane');
8     dojo.require('openils.widget.EditDialog');
9     dojo.require('openils.widget.GridColumnPicker');
10     dojo.require('openils.Util');
11
12     dojo.declare(
13         'openils.widget.AutoGrid',
14         [dojox.grid.DataGrid, openils.widget.AutoWidget],
15         {
16
17             /* if true, pop up an edit dialog when user hits Enter on a give row */
18             editPaneOnSubmit : null,
19             createPaneOnSubmit : null,
20             editOnEnter : false, 
21             defaultCellWidth : null,
22             editStyle : 'dialog',
23             editReadOnly : false,
24             suppressFields : null,
25             suppressEditFields : null,
26             suppressFilterFields : null,
27             hideSelector : false,
28             hideLineNumber : false,
29             selectorWidth : '1.5',
30             lineNumberWidth : '1.5',
31             showColumnPicker : false,
32             columnPickerPrefix : null,
33             displayLimit : 15,
34             displayOffset : 0,
35             requiredFields : null,
36             hidePaginator : false,
37             showLoadFilter : false,
38             suppressLinkedFields : null, // list of fields whose linked display data should not be fetched from the server
39
40             /* by default, don't show auto-generated (sequence) fields */
41             showSequenceFields : false, 
42
43             // style the cells in the line number column
44             onStyleRow : function(row) {
45                 if (!this.hideLineNumber) {
46                     var cellIdx = this.hideSelector ? 0 : 1;
47                     dojo.addClass(this.views.views[0].getCellNode(row.index, cellIdx), 'autoGridLineNumber');
48                 }
49             },
50
51             startup : function() {
52                 this.selectionMode = 'single';
53                 this.sequence = openils.widget.AutoGrid.sequence++;
54                 openils.widget.AutoGrid.gridCache[this.sequence] = this;
55                 this.inherited(arguments);
56                 this.initAutoEnv();
57                 this.attr('structure', this._compileStructure());
58                 this.setStore(this.buildAutoStore());
59                 this.cachedQueryOpts = {};
60                 this._showing_create_pane = false;
61
62                 if(this.showColumnPicker) {
63                     if(!this.columnPickerPrefix) {
64                         console.error("No columnPickerPrefix defined");
65                     } else {
66                         var picker = new openils.widget.GridColumnPicker(
67                             openils.User.authtoken, this.columnPickerPrefix, this);
68                         if(openils.User.authtoken) {
69                             picker.load();
70                         } else {
71                             openils.Util.addOnLoad(function() { picker.load() });
72                         }
73                     }
74                 }
75
76                 this.overrideEditWidgets = {};
77                 this.overrideEditWidgetClass = {};
78                 this.overrideWidgetArgs = {};
79
80                 if(this.editOnEnter) 
81                     this._applyEditOnEnter();
82                 else if(this.singleEditStyle) 
83                     this._applySingleEditStyle();
84
85                 if(!this.hideSelector) {
86                     dojo.connect(this, 'onHeaderCellClick', 
87                         function(e) {
88                             if(e.cell.index == 0)
89                                 this.toggleSelectAll();
90                         }
91                     );
92                 }
93
94                 if(!this.hidePaginator) {
95                     var self = this;
96                     this.paginator = new dijit.layout.ContentPane();
97
98
99                     var back = dojo.create('a', {
100                         innerHTML : 'Back',  // TODO i18n
101                         style : 'padding-right:6px;',
102                         href : 'javascript:void(0);', 
103                         onclick : function() { 
104                             self.cachedQueryOpts.offset = self.displayOffset -= self.displayLimit;
105                             if(self.displayOffset < 0)
106                                 self.cachedQueryOpts.offset = self.displayOffset = 0;
107                             self.refresh();
108                         }
109                     });
110
111                     var forw = dojo.create('a', {
112                         innerHTML : 'Next',  // TODO i18n
113                         style : 'padding-right:6px;',
114                         href : 'javascript:void(0);', 
115                         onclick : function() { 
116                             self.cachedQueryOpts.offset = self.displayOffset += self.displayLimit;
117                             self.refresh();
118                         }
119                     });
120
121                     dojo.place(this.paginator.domNode, this.domNode, 'before');
122                     dojo.place(back, this.paginator.domNode);
123                     dojo.place(forw, this.paginator.domNode);
124
125                     if(this.showLoadFilter) {
126                         dojo.require('openils.widget.PCrudFilterDialog');
127                         dojo.place(
128                             dojo.create('a', {
129                                 innerHTML : 'Filter', // TODO i18n
130                                 style : 'padding-right:6px;',
131                                 href : 'javascript:void(0);', 
132                                 onclick : function() { 
133                                     if (!self.filterDialog) {
134                                         self.filterDialog = new openils.widget.PCrudFilterDialog({fmClass:self.fmClass, suppressFilterFields:self.suppressFilterFields})
135                                         self.filterDialog.onApply = function(filter) {
136                                             self.resetStore();
137                                             self.loadAll(self.cachedQueryOpts, filter);
138                                         };
139                                         self.filterDialog.startup();
140                                     }
141                                     self.filterDialog.show();
142                                 }
143                             }),
144                             this.paginator.domNode
145                         );
146                     }
147
148                     // progress image
149                     this.loadProgressIndicator = dojo.create('img', {
150                         src:'/opac/images/progressbar_green.gif', // TODO configured path
151                         style:'height:16px;width:16px;'
152                     });
153                     dojo.place(this.loadProgressIndicator, this.paginator.domNode);
154                 }
155             },
156
157             hideLoadProgressIndicator : function() {
158                 dojo.style(this.loadProgressIndicator, 'visibility', 'hidden');
159             },
160
161             showLoadProgressIndicator : function() {
162                 dojo.style(this.loadProgressIndicator, 'visibility', 'visible');
163             },
164
165             /* Don't allow sorting on the selector column */
166             canSort : function(rowIdx) {
167                 if(rowIdx == 1 && !this.hideSelector)
168                     return false;
169                 if(this.hideSelector && rowIdx == 1 && !this.hideLineNumber)
170                     return false;
171                 if(!this.hideSelector && rowIdx == 2 && !this.hideLineNumber)
172                     return false;
173                 return true;
174             },
175
176             _compileStructure : function() {
177                 var existing = (this.structure && this.structure[0].cells[0]) ? 
178                     this.structure[0].cells[0] : [];
179                 var fields = [];
180
181                 var self = this;
182                 function pushEntry(entry) {
183                     if(self.suppressFields) {
184                         if(dojo.indexOf(self.suppressFields, entry.field) != -1)
185                             return;
186                     }
187                     if(!entry.get) 
188                         entry.get = openils.widget.AutoGrid.defaultGetter
189                     if(!entry.width && self.defaultCellWidth)
190                         entry.width = self.defaultCellWidth;
191                     fields.push(entry);
192                 }
193
194                 if(!this.hideSelector) {
195                     // insert the selector column
196                     pushEntry({
197                         field : '+selector',
198                         formatter : function(rowIdx) { return self._formatRowSelectInput(rowIdx); },
199                         get : function(rowIdx, item) { if(item) return rowIdx; },
200                         width : this.selectorWidth,
201                         name : '&#x2713',
202                         nonSelectable : true
203                     });
204                 }
205
206                 if(!this.hideLineNumber) {
207                     // insert the line number column
208                     pushEntry({
209                         field : '+lineno',
210                         get : function(rowIdx, item) { if(item) return 1 + rowIdx; },
211                         width : this.lineNumberWidth,
212                         name : '#',
213                         nonSelectable : false
214                     });
215                 }
216
217                 if(!this.fieldOrder) {
218                     /* no order defined, start with any explicit grid fields */
219                     for(var e in existing) {
220                         var entry = existing[e];
221                         var field = this.fmIDL.fields.filter(
222                             function(i){return (i.name == entry.field)})[0];
223                         if(field) entry.name = entry.name || field.label;
224                         pushEntry(entry);
225                     }
226                 }
227
228                 for(var f in this.sortedFieldList) {
229                     var field = this.sortedFieldList[f];
230                     if(!field || field.virtual) continue;
231                     
232                     // field was already added above
233                     if(fields.filter(function(i){return (i.field == field.name)})[0]) 
234                         continue;
235
236                     var entry = existing.filter(function(i){return (i.field == field.name)})[0];
237                     if(entry) {
238                         entry.name = entry.name || field.label;
239                     } else {
240                         // unless specifically requested, hide sequence fields
241                         if(!this.showSequenceFields && field.name == this.fmIDL.pkey && this.fmIDL.pkey_sequence)
242                             continue; 
243
244                         entry = {field:field.name, name:field.label};
245                     }
246                     pushEntry(entry);
247                 }
248
249                 if(this.fieldOrder) {
250                     /* append any explicit non-IDL grid fields to the end */
251                     for(var e in existing) {
252                         var entry = existing[e];
253                         var field = fields.filter(
254                             function(i){return (i.field == entry.field)})[0];
255                         if(field) continue; // don't duplicate
256                         pushEntry(entry);
257                     }
258                 }
259
260                 return [{cells: [fields]}];
261             },
262
263             toggleSelectAll : function() {
264                 var selected = this.getSelectedRows();
265                 for(var i = 0; i < this.rowCount; i++) {
266                     if(selected[0])
267                         this.deSelectRow(i);
268                     else
269                         this.selectRow(i);
270                 }
271             },
272
273             getSelectedRows : function() {
274                 var rows = []; 
275                 dojo.forEach(
276                     dojo.query('[name=autogrid.selector]', this.domNode),
277                     function(input) {
278                         if(input.checked)
279                             rows.push(input.getAttribute('row'));
280                     }
281                 );
282                 return rows;
283             },
284
285             getFirstSelectedRow : function() {
286                 return this.getSelectedRows()[0];
287             },
288
289             getSelectedItems : function() {
290                 var items = [];
291                 var self = this;
292                 dojo.forEach(this.getSelectedRows(), function(idx) { items.push(self.getItem(idx)); });
293                 return items;
294             },
295
296             selectRow : function(rowIdx) {
297                 var inputs = dojo.query('[name=autogrid.selector]', this.domNode);
298                 for(var i = 0; i < inputs.length; i++) {
299                     if(inputs[i].getAttribute('row') == rowIdx) {
300                         if(!inputs[i].disabled)
301                             inputs[i].checked = true;
302                         break;
303                     }
304                 }
305             },
306
307             deSelectRow : function(rowIdx) {
308                 var inputs = dojo.query('[name=autogrid.selector]', this.domNode);
309                 for(var i = 0; i < inputs.length; i++) {
310                     if(inputs[i].getAttribute('row') == rowIdx) {
311                         inputs[i].checked = false;
312                         break;
313                     }
314                 }
315             },
316
317             /**
318              * @return {Array} List of every fieldmapper object in the data store
319              */
320             getAllObjects : function() {
321                 var objs = [];
322                 var self = this;
323                 this.store.fetch({
324                     onComplete : function(list) {
325                         dojo.forEach(list, 
326                             function(item) {
327                                 objs.push(new fieldmapper[self.fmClass]().fromStoreItem(item));
328                             }
329                         )
330                     }
331                 });
332                 return objs;
333             },
334
335             /**
336              * Deletes the underlying object for all selected rows
337              */
338             deleteSelected : function() {
339                 var items = this.getSelectedItems();
340                 var total = items.length;
341                 var self = this;
342                 dojo.require('openils.PermaCrud');
343                 dojo.forEach(items,
344                     function(item) {
345                         var fmObject = new fieldmapper[self.fmClass]().fromStoreItem(item);
346                         new openils.PermaCrud()['eliminate'](fmObject, {oncomplete : function(r) { self.store.deleteItem(item) }});
347                     }
348                 );
349             },
350
351             _formatRowSelectInput : function(rowIdx) {
352                 if(rowIdx === null || rowIdx === undefined) return '';
353                 var s = "<input type='checkbox' name='autogrid.selector' row='" + rowIdx + "'";
354                 if(this.disableSelectorForRow && this.disableSelectorForRow(rowIdx)) 
355                     s += " disabled='disabled'";
356                 return s + "/>";
357             },
358
359             _applySingleEditStyle : function() {
360                 this.onMouseOverRow = function(e) {};
361                 this.onMouseOutRow = function(e) {};
362                 this.onCellFocus = function(cell, rowIndex) { 
363                     this.selection.deselectAll();
364                     this.selection.select(this.focus.rowIndex);
365                 };
366             },
367
368             /* capture keydown and launch edit dialog on enter */
369             _applyEditOnEnter : function() {
370                 this._applySingleEditStyle();
371
372                 dojo.connect(this, 'onRowDblClick',
373                     function(e) {
374                         if(this.editStyle == 'pane')
375                             this._drawEditPane(this.selection.getFirstSelected(), this.focus.rowIndex);
376                         else
377                             this._drawEditDialog(this.selection.getFirstSelected(), this.focus.rowIndex);
378                     }
379                 );
380
381                 dojo.connect(this, 'onKeyDown',
382                     function(e) {
383                         if(e.keyCode == dojo.keys.ENTER) {
384                             this.selection.deselectAll();
385                             this.selection.select(this.focus.rowIndex);
386                             if(this.editStyle == 'pane')
387                                 this._drawEditPane(this.selection.getFirstSelected(), this.focus.rowIndex);
388                             else
389                                 this._drawEditDialog(this.selection.getFirstSelected(), this.focus.rowIndex);
390                         }
391                     }
392                 );
393             },
394
395             _makeEditPane : function(storeItem, rowIndex, onPostSubmit, onCancel) {
396                 var grid = this;
397                 var fmObject = new fieldmapper[this.fmClass]().fromStoreItem(storeItem);
398                 var idents = grid.store.getIdentityAttributes();
399                 var self = this;
400
401                 var pane = new openils.widget.EditPane({
402                     fmObject:fmObject,
403                     hideSaveButton : this.editReadOnly,
404                     readOnly : this.editReadOnly,
405                     overrideWidgets : this.overrideEditWidgets,
406                     overrideWidgetClass : this.overrideEditWidgetClass,
407                     overrideWidgetArgs : this.overrideWidgetArgs,
408                     disableWidgetTest : this.disableWidgetTest,
409                     requiredFields : this.requiredFields,
410                     suppressFields : this.suppressEditFields,
411                     onPostSubmit : function() {
412                         for(var i in fmObject._fields) {
413                             var field = fmObject._fields[i];
414                             if(idents.filter(function(j){return (j == field)})[0])
415                                 continue; // don't try to edit an identifier field
416                             grid.store.setValue(storeItem, field, fmObject[field]());
417                         }
418                         if(self.onPostUpdate)
419                             self.onPostUpdate(storeItem, rowIndex);
420                         setTimeout(
421                             function(){
422                                 try { 
423                                     grid.views.views[0].getCellNode(rowIndex, 0).focus(); 
424                                 } catch (E) {}
425                             },200
426                         );
427                         if(onPostSubmit) 
428                             onPostSubmit();
429                     },
430                     onCancel : function() {
431                         setTimeout(function(){
432                             grid.views.views[0].getCellNode(rowIndex, 0).focus();},200);
433                         if(onCancel) onCancel();
434                     }
435                 });
436
437                 if (typeof this.editPaneOnSubmit == "function")
438                     pane.onSubmit = this.editPaneOnSubmit;
439                 pane.fieldOrder = this.fieldOrder;
440                 pane.mode = 'update';
441                 return pane;
442             },
443
444             _makeCreatePane : function(onPostSubmit, onCancel) {
445                 var grid = this;
446                 var pane = new openils.widget.EditPane({
447                     fmClass : this.fmClass,
448                     overrideWidgets : this.overrideEditWidgets,
449                     overrideWidgetClass : this.overrideEditWidgetClass,
450                     overrideWidgetArgs : this.overrideWidgetArgs,
451                     disableWidgetTest : this.disableWidgetTest,
452                     requiredFields : this.requiredFields,
453                     suppressFields : this.suppressEditFields,
454                     onPostSubmit : function(req, cudResults) {
455                         var fmObject = cudResults[0];
456                         if(grid.onPostCreate)
457                             grid.onPostCreate(fmObject);
458                         if(fmObject) 
459                             grid.store.newItem(fmObject.toStoreItem());
460                         setTimeout(function(){
461                             try {
462                                 grid.selection.select(grid.rowCount-1);
463                                 grid.views.views[0].getCellNode(grid.rowCount-1, 1).focus();
464                             } catch (E) {}
465                         },200);
466                         if(onPostSubmit)
467                             onPostSubmit(fmObject);
468                     },
469                     onCancel : function() {
470                         if(onCancel) onCancel();
471                     }
472                 });
473                 if (typeof this.createPaneOnSubmit == "function")
474                     pane.onSubmit = this.createPaneOnSubmit;
475                 pane.fieldOrder = this.fieldOrder;
476                 pane.mode = 'create';
477                 return pane;
478             },
479
480             /**
481              * Creates an EditPane with a copy of the data from the provided store
482              * item for cloning said item
483              * @param {Object} storeItem Dojo data item
484              * @param {Number} rowIndex The Grid row index of the item to be cloned
485              * @param {Function} onPostSubmit Optional callback for post-submit behavior
486              * @param {Function} onCancel Optional callback for clone cancelation
487              * @return {Object} The clone EditPane
488              */
489             _makeClonePane : function(storeItem, rowIndex, onPostSubmit, onCancel) {
490                 var clonePane = this._makeCreatePane(onPostSubmit, onCancel);
491                 var origPane = this._makeEditPane(storeItem, rowIndex);
492                 clonePane.startup();
493                 origPane.startup();
494                 dojo.forEach(origPane.fieldList,
495                     function(field) {
496                         if(field.widget.widget.attr('disabled')) return;
497                         var w = clonePane.fieldList.filter(
498                             function(i) { return (i.name == field.name) })[0];
499                         w.widget.baseWidgetValue(field.widget.widget.attr('value')); // sync widgets
500                         w.widget.onload = function(){w.widget.baseWidgetValue(field.widget.widget.attr('value'))}; // async widgets
501                     }
502                 );
503                 origPane.destroy();
504                 return clonePane;
505             },
506
507
508             _drawEditDialog : function(storeItem, rowIndex) {
509                 var self = this;
510                 var done = function() { self.hideDialog(); };
511                 var pane = this._makeEditPane(storeItem, rowIndex, done, done);
512                 this.editDialog = new openils.widget.EditDialog({editPane:pane});
513                 this.editDialog.startup();
514                 this.editDialog.show();
515             },
516
517             /**
518              * Generates an EditDialog for object creation and displays it to the user
519              */
520             showCreateDialog : function() {
521                 var self = this;
522                 var done = function() { self.hideDialog(); };
523                 var pane = this._makeCreatePane(done, done);
524                 this.editDialog = new openils.widget.EditDialog({editPane:pane});
525                 this.editDialog.startup();
526                 this.editDialog.show();
527             },
528
529             _drawEditPane : function(storeItem, rowIndex) {
530                 var self = this;
531                 var done = function() { self.hidePane(); };
532                 dojo.style(this.domNode, 'display', 'none');
533                 this.editPane = this._makeEditPane(storeItem, rowIndex, done, done);
534                 this.editPane.startup();
535                 this.domNode.parentNode.insertBefore(this.editPane.domNode, this.domNode);
536                 if(this.onEditPane) this.onEditPane(this.editPane);
537             },
538
539             showClonePane : function(onPostSubmit) {
540                 var self = this;
541                 var done = function() { self.hidePane(); };
542
543                                     
544                 var row = this.getFirstSelectedRow();
545                 if(!row) return;
546
547                 var postSubmit = (onPostSubmit) ? 
548                     function(result) { onPostSubmit(self.getItem(row), result); self.hidePane(); } :
549                     done;
550
551                 dojo.style(this.domNode, 'display', 'none');
552                 this.editPane = this._makeClonePane(this.getItem(row), row, postSubmit, done);
553                 this.domNode.parentNode.insertBefore(this.editPane.domNode, this.domNode);
554                 if(this.onEditPane) this.onEditPane(this.editPane);
555             },
556
557             showCreatePane : function() {
558                 if (this._showing_create_pane)
559                     return;
560                 this._showing_create_pane = true;
561
562                 var self = this;
563                 var done = function() {
564                     self._showing_create_pane = false;
565                     self.hidePane();
566                 };
567                 dojo.style(this.domNode, 'display', 'none');
568                 this.editPane = this._makeCreatePane(done, done);
569                 this.editPane.startup();
570                 this.domNode.parentNode.insertBefore(this.editPane.domNode, this.domNode);
571                 if(this.onEditPane) this.onEditPane(this.editPane);
572             },
573
574             hideDialog : function() {
575                 this.editDialog.hide(); 
576                 this.editDialog.destroy(); 
577                 delete this.editDialog;
578                 this.update();
579             },
580
581             hidePane : function() {
582                 this.domNode.parentNode.removeChild(this.editPane.domNode);
583                 this.editPane.destroy();
584                 delete this.editPane;
585                 dojo.style(this.domNode, 'display', 'block');
586                 this.update();
587             },
588             
589             resetStore : function() {
590                 this.setStore(this.buildAutoStore());
591             },
592
593             refresh : function() {
594                 this.resetStore();
595                 if (this.dataLoader)
596                     this.dataLoader()
597                 else
598                     this.loadAll(this.cachedQueryOpts, this.cachedQuerySearch);
599             },
600
601             loadAll : function(opts, search) {
602                 dojo.require('openils.PermaCrud');
603                 if(this.loadProgressIndicator)
604                     dojo.style(this.loadProgressIndicator, 'visibility', 'visible');
605                 var self = this;
606                 opts = dojo.mixin(
607                     {limit : this.displayLimit, offset : this.displayOffset}, 
608                     opts || {}
609                 );
610                 opts = dojo.mixin(opts, {
611                     async : true,
612                     streaming : true,
613                     onresponse : function(r) {
614                         var item = openils.Util.readResponse(r);
615                         self.store.newItem(item.toStoreItem());
616                     },
617                     oncomplete : function() {
618                         if(self.loadProgressIndicator) 
619                             dojo.style(self.loadProgressIndicator, 'visibility', 'hidden');
620                     }
621                 });
622
623                 this.cachedQuerySearch = search;
624                 this.cachedQueryOpts = opts;
625                 if(search)
626                     new openils.PermaCrud().search(this.fmClass, search, opts);
627                 else
628                     new openils.PermaCrud().retrieveAll(this.fmClass, opts);
629             }
630         } 
631     );
632
633     // static ID generater seed
634     openils.widget.AutoGrid.sequence = 0;
635     openils.widget.AutoGrid.gridCache = {};
636
637     openils.widget.AutoGrid.markupFactory = dojox.grid.DataGrid.markupFactory;
638
639     openils.widget.AutoGrid.defaultGetter = function(rowIndex, item) {
640         if(!item) return '';
641         if(!this.grid.overrideWidgetArgs[this.field])
642             this.grid.overrideWidgetArgs[this.field] = {};
643         var val = this.grid.store.getValue(item, this.field);
644         var autoWidget = new openils.widget.AutoFieldWidget(dojo.mixin({
645             fmClass: this.grid.fmClass,
646             fmField: this.field,
647             widgetValue : val,
648             readOnly : true,
649             forceSync : true, // prevents many simultaneous requests for the same data
650             suppressLinkedFields : this.grid.suppressLinkedFields
651         },this.grid.overrideWidgetArgs[this.field]));
652
653         autoWidget.build();
654
655         /*
656         // With proper caching, this should not be necessary to prevent grid render flickering
657         var _this = this;
658         autoWidget.build(
659             function(w, ww) {
660                 try {
661                     var node = _this.grid.getCell(_this.index).view.getCellNode(rowIndex, _this.index);
662                     if(node) 
663                         node.innerHTML = ww.getDisplayString();
664                 } catch(E) {}
665             }
666         );
667         */
668
669         return autoWidget.getDisplayString();
670     };
671
672     openils.widget.AutoGrid.orgUnitGetter = function(rowIndex, item) {
673         if (!item) return "";
674         return fieldmapper.aou.findOrgUnit(
675             this.grid.store.getValue(item, this.field)
676         ).shortname();
677     };
678 }
679