added a toolbar for choosing interfaces. added a queue picker interface to pick...
[Evergreen.git] / Open-ILS / web / vandelay / vandelay.js
1 /* ---------------------------------------------------------------------------
2 # Copyright (C) 2008  Georgia Public Library Service
3 # Bill Erickson <erickson@esilibrary.com>
4
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 # --------------------------------------------------------------------------- */
15 dojo.require("dojo.parser");
16 dojo.require("dojo.io.iframe"); 
17 dojo.require("dijit.ProgressBar"); 
18 dojo.require("dijit.form.Button"); 
19 dojo.require("dijit.form.FilteringSelect"); 
20 dojo.require("dijit.layout.ContentPane");
21 dojo.require("dijit.layout.TabContainer");
22 dojo.require("dojo.cookie");
23 dojo.require("dojox.grid.Grid");
24 dojo.require("dojo.data.ItemFileReadStore");
25 dojo.require('dojo.date.locale');
26 dojo.require('dojo.date.stamp');
27 dojo.require("fieldmapper.Fieldmapper");
28 dojo.require("fieldmapper.dojoData");
29 dojo.require('openils.CGI');
30 dojo.require('openils.User');
31 dojo.require('openils.Event');
32
33 var globalDivs = [
34     'vl-generic-progress',
35     'vl-generic-progress-with-total',
36     'vl-marc-upload-div',
37     'vl-queue-div',
38     'vl-match-div',
39     'vl-match-html-div',
40     'vl-queue-select-div'
41 ];
42
43 var authtoken;
44 var VANDELAY_URL = '/vandelay';
45 var bibAttrDefs = [];
46 var authAttrDefs = [];
47 var queuedRecords = [];
48 var queuedRecordsMap = {};
49 var bibAttrsFetched = false;
50 var authAttrsFetched = false;
51 var attrDefMap = {}; // maps attr def code names to attr def ids
52 var currentType;
53 var cgi = new openils.CGI();
54 var currentQueueId = null;
55 var userCache = {};
56 var currentMatchedRecords; // set of loaded matched bib records
57 var currentOverlayRecordsMap; // map of import record to overlay record
58 var currentImportRecId; // when analyzing matches, this is the current import record
59 var userBibQueues;
60 var userAuthQueues;
61 var selectableGridRecords;
62
63 /**
64   * Grab initial data
65   */
66 function vlInit() {
67     authtoken = dojo.cookie('ses') || cgi.param('ses');
68     var initNeeded = 4; // how many async responses do we need before we're init'd 
69     var initCount = 0; // how many async reponses we've received
70
71     function checkInitDone() {
72         initCount++;
73         if(initCount == initNeeded)
74             runStartupCommands();
75     }
76
77     // Fetch the bib and authority attribute definitions
78     fieldmapper.standardRequest(
79         ['open-ils.permacrud', 'open-ils.permacrud.search.vqbrad'],
80         {   async: true,
81             params: [authtoken, {id:{'!=':null}}],
82             onresponse: function(r) {
83                 var def = r.recv().content(); 
84                 if(e = openils.Event.parse(def[0])) 
85                     return alert(e);
86                 bibAttrDefs.push(def);
87             },
88             oncomplete: function() {
89                 bibAttrDefs = bibAttrDefs.sort(
90                     function(a, b) {
91                         if(a.id() > b.id()) return 1;
92                         if(a.id() < b.id()) return -1;
93                         return 0;
94                     }
95                 );
96                 checkInitDone();
97             }
98         }
99     );
100
101     fieldmapper.standardRequest(
102         ['open-ils.permacrud', 'open-ils.permacrud.search.vqarad'],
103         {   async: true,
104             params: [authtoken, {id:{'!=':null}}],
105             onresponse: function(r) {
106                 var def = r.recv().content(); 
107                 if(e = openils.Event.parse(def[0])) 
108                     return alert(e);
109                 authAttrDefs.push(def);
110             },
111             oncomplete: function() {
112                 authAttrDefs = authAttrDefs.sort(
113                     function(a, b) {
114                         if(a.id() > b.id()) return 1;
115                         if(a.id() < b.id()) return -1;
116                         return 0;
117                     }
118                 );
119                 checkInitDone();
120             }
121         }
122     );
123
124     fieldmapper.standardRequest(
125         ['open-ils.vandelay', 'open-ils.vandelay.bib_queue.owner.retrieve.atomic'],
126         {   async: true,
127             params: [authtoken],
128             oncomplete: function(r) {
129                 var list = r.recv().content();
130                 if(e = openils.Event.parse(list[0]))
131                     return alert(e);
132                 userBibQueues = list;
133                 checkInitDone();
134             }
135         }
136     );
137
138     fieldmapper.standardRequest(
139         ['open-ils.vandelay', 'open-ils.vandelay.authority_queue.owner.retrieve.atomic'],
140         {   async: true,
141             params: [authtoken],
142             oncomplete: function(r) {
143                 var list = r.recv().content();
144                 if(e = openils.Event.parse(list[0]))
145                     return alert(e);
146                 userAuthQueues = list;
147                 checkInitDone();
148             }
149         }
150     );
151 }
152
153 function displayGlobalDiv(id) {
154     for(var i = 0; i < globalDivs.length; i++) {
155         try {
156             dojo.style(dojo.byId(globalDivs[i]), 'display', 'none');
157         } catch(e) {
158             alert('please define ' + globalDivs[i]);
159         }
160     }
161     dojo.style(dojo.byId(id),'display','block');
162 }
163
164 function runStartupCommands() {
165     currentQueueId = cgi.param('qid');
166     currentType = cgi.param('qtype');
167     if(currentQueueId)
168         return retrievenueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
169     displayGlobalDiv('vl-marc-upload-div');
170 }
171
172 /**
173   * asynchronously upload a file of MARC records
174   */
175 function uploadMARC(onload){
176     dojo.byId('vl-ses-input').value = authtoken;
177     dojo.style(dojo.byId('vl-input-td'),"display","none");
178     dojo.style(dojo.byId('vl-upload-progress-span'),"display","inline"); 
179
180     dojo.style(dojo.byId('vl-file-label'), 'display', 'none');
181     dojo.style(dojo.byId('vl-file-uploading'), 'display', 'inline');
182
183     dojo.io.iframe.send({
184         url: VANDELAY_URL,
185         method: "post",
186         handleAs: "html",
187         form: dojo.byId('vl-marc-upload-form'),
188         handle: function(data,ioArgs){
189             var content = data.documentElement.textContent;
190             dojo.style(dojo.byId('vl-input-td'),"display","inline");
191             dojo.style(dojo.byId('vl-upload-progress-span'),"display","none");
192             dojo.style(dojo.byId('vl-file-label'), 'display', 'inline');
193             dojo.style(dojo.byId('vl-file-uploading'), 'display', 'none');
194             onload(content);
195         }
196     });
197 }       
198
199 /**
200   * Creates a new vandelay queue
201   */
202 function createQueue(queueName, type, onload) {
203     fieldmapper.standardRequest(
204         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.create'],
205         {   async: true,
206             params: [authtoken, queueName, null, type],
207             oncomplete : function(r) {
208                 var queue = r.recv().content();
209                 if(e = openils.Event.parse(queue)) 
210                     return alert(e);
211                 onload(queue);
212             }
213         }
214     );
215 }
216
217 /**
218   * Tells vendelay to pull a batch of records from the cache and explode them
219   * out into the vandelay tables
220   */
221 function processSpool(key, queueId, type, onload) {
222     fieldmapper.standardRequest(
223         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'.process_spool'],
224         {   async: true,
225             params: [authtoken, key, queueId],
226             oncomplete : function(r) {
227                 var resp = r.recv().content();
228                 if(e = openils.Event.parse(resp)) 
229                     return alert(e);
230                 onload();
231             }
232         }
233     );
234 }
235
236 function retrieveQueuedRecords(type, queueId, onload) {
237     queuedRecords = [];
238     queuedRecordsMap = {};
239     currentOverlayRecordsMap = {};
240     selectableGridRecords = {};
241     resetVlQueueGridLayout();
242
243     fieldmapper.standardRequest(
244         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.records.retrieve.atomic'],
245         {   async: true,
246             params: [authtoken, queueId, {clear_marc:1}],
247             /* intermittent bug in streaming, multipart requests prevents use of onreponse for now...
248             onresponse: function(r) {
249                 var rec = r.recv().content();
250                 if(e = openils.Event.parse(rec))
251                     return alert(e);
252                 queuedRecords.push(rec);
253                 queuedRecordsMap[rec.id()] = rec;
254             },
255             */
256             oncomplete: function(r){
257                 var recs = r.recv().content();
258                 if(e = openils.Event.parse(recs[0]))
259                     return alert(e);
260                 for(var i = 0; i < recs.length; i++) {
261                     var rec = recs[i];
262                     queuedRecords.push(rec);
263                     queuedRecordsMap[rec.id()] = rec;
264                 }
265                 onload();
266             }
267         }
268     );
269 }
270
271 function vlLoadMatchUI(recId, attrCode) {
272     displayGlobalDiv('vl-generic-progress');
273     var matches = getRecMatchesFromAttrCode(queuedRecordsMap[recId], attrCode);
274     var records = [];
275     currentImportRecId = recId;
276     for(var i = 0; i < matches.length; i++)
277         records.push(matches[i].eg_record());
278     fieldmapper.standardRequest(
279         ['open-ils.search', 'open-ils.search.biblio.record_entry.slim.retrieve'],
280         {   async: true,
281             params:[records],
282             oncomplete: function(r) {
283                 var recs = r.recv().content();
284                 if(e = openils.Event.parse(recs))
285                     return alert(e);
286                 displayGlobalDiv('vl-match-div');
287                 resetVlMatchGridLayout();
288                 currentMatchedRecords = recs;
289                 vlMatchGrid.setStructure(vlMatchGridLayout);
290                 var dataStore = bre.toStoreData(recs, null, {virtualFields:['field_type']});
291                 for(var i = 0; i < dataStore.items.length; i++) {
292                     var item = dataStore.items[i];
293                     for(var j = 0; j < matches.length; j++) {
294                         var match = matches[j];
295                         if(match.eg_record() == item.id)
296                             item.field_type = match.field_type();
297                     }
298                 }
299                 var store = new dojo.data.ItemFileReadStore({data:dataStore});
300                 var model = new dojox.grid.data.DojoData(
301                     null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
302                 vlMatchGrid.setModel(model);
303                 vlMatchGrid.update();
304             }
305         }
306     );
307 }
308
309
310 function vlLoadMARCHtml(recId) {
311     displayGlobalDiv('vl-generic-progress');
312     fieldmapper.standardRequest(
313         ['open-ils.search', 'open-ils.search.biblio.record.html'],
314         {   async: true,
315             params: [recId, 1],
316             oncomplete: function(r) {
317             displayGlobalDiv('vl-match-html-div');
318                 var html = r.recv().content();
319                 dojo.byId('vl-match-record-html').innerHTML = html;
320             }
321         }
322     );
323 }
324
325
326 /**
327   * Given a record, an attribute definition code, and a matching record attribute,
328   * this will determine if there are any import matches and build the UI to
329   * represent those matches.  If no matches exist, simply returns the attribute value
330   */
331 function buildAttrColumnUI(rec, attrCode, attr) {
332     var matches = getRecMatchesFromAttrCode(rec, attrCode);
333     if(matches.length > 0) { // found some matches
334         return '<div class="match_div">' +
335             '<a href="javascript:void(0);" onclick="vlLoadMatchUI('+
336             rec.id()+',\''+attrCode+'\');">'+ 
337             attr.attr_value() + '&nbsp;('+matches.length+')</a></div>';
338     }
339
340     return attr.attr_value();
341 }
342
343 function getRecMatchesFromAttrCode(rec, attrCode) {
344     var matches = [];
345     var attr = getRecAttrFromCode(rec, attrCode);
346     for(var j = 0; j < rec.matches().length; j++) {
347         var match = rec.matches()[j];
348         if(match.matched_attr() == attr.id()) 
349             matches.push(match);
350     }
351     return matches;
352 }
353
354 function getRecAttrFromCode(rec, attrCode) {
355     var defId = attrDefMap[attrCode];
356     var attrs = rec.attributes();
357     for(var i = 0; i < attrs.length; i++) {
358         var attr = attrs[i];
359         if(attr.field() == defId) 
360             return attr;
361     }
362     return null;
363 }
364
365 function getAttrValue(rowIdx) {
366     var data = this.grid.model.getRow(rowIdx);
367     if(!data) return '';
368     var attrCode = this.field.split('.')[1];
369     console.log(attrCode + " : " + data.id + ' : ' + queuedRecordsMap[data.id] + " : count = " + queuedRecords.length);
370     var rec = queuedRecordsMap[data.id];
371     var attr = getRecAttrFromCode(rec, attrCode);
372     if(attr)
373         return buildAttrColumnUI(rec, attrCode, attr);
374     return '';
375 }
376
377 function vlGetDateTimeField(rowIdx) {
378     data = this.grid.model.getRow(rowIdx);
379     if(!data) return '';
380     if(!data[this.field]) return '';
381     var date = dojo.date.stamp.fromISOString(data[this.field]);
382     return dojo.date.locale.format(date, {selector:'date'});
383 }
384
385 function vlGetCreator(rowIdx) {
386     data = this.grid.model.getRow(rowIdx);
387     if(!data) return '';
388     var id = data.creator;
389     if(userCache[id])
390         return userCache[id].usrname();
391     var user = fieldmapper.standardRequest(['open-ils.actor', 'open-ils.actor.user.retrieve'], [authtoken, id]);
392     if(e = openils.Event.parse(user))
393         return alert(e);
394     userCache[id] = user;
395     return user.usrname();
396 }
397
398 function vlGetViewMARC(rowIdx) {
399     data = this.grid.model.getRow(rowIdx);
400     if(data) 
401         return this.value.replace('RECID', data.id);
402 }
403
404 function vlGetOverlayTargetSelector(rowIdx) {
405     data = this.grid.model.getRow(rowIdx);
406     if(data) {
407         var value = this.value.replace('ID', data.id);
408         var overlay = currentOverlayRecordsMap[currentImportRecId];
409         if(overlay && overlay == data.id) 
410             value = value.replace('/>', 'checked="checked"/>');
411         return value;
412     }
413 }
414
415 /**
416   * see if the user has enabled overlays for the current match set and, 
417   * if so, map the current import record to the overlay target.
418   */
419 function vlHandleOverlayTargetSelected() {
420     if(vlOverlayTargetEnable.checked) {
421         for(var i = 0; i < currentMatchedRecords.length; i++) {
422             var matchRecId = currentMatchedRecords[i].id();
423             if(dojo.byId('vl-overlay-target-'+matchRecId).checked) {
424                 console.log("found overlay target " + matchRecId);
425                 currentOverlayRecordsMap[currentImportRecId] = matchRecId;
426                 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = true;
427                 return;
428             }
429         }
430     } else {
431         delete currentOverlayRecordsMap[currentImportRecId];
432         dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = false;
433     }
434 }
435
436 function buildRecordGrid(type) {
437     displayGlobalDiv('vl-queue-div');
438
439     currentOverlayRecordsMap = {};
440
441     if(queuedRecords.length == 0) {
442         dojo.style(dojo.byId('vl-queue-no-records'), 'display', 'block');
443         dojo.style(dojo.byId('vl-queue-div-grid'), 'display', 'none');
444         return;
445     } else {
446         dojo.style(dojo.byId('vl-queue-no-records'), 'display', 'none');
447         dojo.style(dojo.byId('vl-queue-div-grid'), 'display', 'block');
448     }
449
450     var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
451     for(var i = 0; i < defs.length; i++) {
452         var def = defs[i]
453         attrDefMap[def.code()] = def.id();
454         var col = {
455             name:def.description(), 
456             field:'attr.' + def.code(),
457             get: getAttrValue
458         };
459         //if(def.code().match(/title/i)) col.width = 'auto'; // this is hack.
460         vlQueueGridLayout[0].cells[0].push(col);
461     }
462
463     var storeData;
464     if(type == 'bib')
465         storeData = vqbr.toStoreData(queuedRecords);
466     else
467         storeData = vqar.toStoreData(queuedRecords);
468
469     var store = new dojo.data.ItemFileReadStore({data:storeData});
470     var model = new dojox.grid.data.DojoData(
471         null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
472
473     vlQueueGrid.setModel(model);
474     vlQueueGrid.setStructure(vlQueueGridLayout);
475     vlQueueGrid.update();
476 }
477
478 /*
479 function test() {
480     alert(vlQueueGridLayout.picker);
481     vlQueueGridLayout.oils = {};
482     vlQueueGridLayout[0].cells[0].pop();
483     vlQueueGridLayout[0].cells[0].pop();
484     vlQueueGridLayout[0].cells[0].pop();
485     vlQueueGridLayout[0].cells[0].pop();
486     vlQueueGridLayout[0].cells[0].pop();
487     vlQueueGrid.setStructure(vlQueueGridLayout);
488     vlQueueGrid.update();
489 }
490 */
491
492 function vlQueueGridDrawSelectBox(rowIdx) {
493     var data = this.grid.model.getRow(rowIdx);
494     if(!data) return '';
495     var domId = 'vl-record-list-selected-' +data.id;
496     selectableGridRecords[domId] = data.id;
497     return "<input type='checkbox' id='"+domId+"'/>";
498 }
499
500 function vlSelectAllGridRecords() {
501     for(var id in selectableGridRecords) 
502         dojo.byId(id).checked = true;
503 }
504 function vlSelectNoGridRecords() {
505     for(var id in selectableGridRecords) 
506         dojo.byId(id).checked = false;
507 }
508
509 var handleRetrieveRecords = function() {
510     buildRecordGrid(currentType);
511 }
512
513 function vlImportSelectedRecords() {
514     displayGlobalDiv('vl-generic-progress-with-total');
515     var records = [];
516
517     for(var id in selectableGridRecords) {
518         if(dojo.byId(id).checked) {
519             var recId = selectableGridRecords[id];
520             var rec = queuedRecordsMap[recId];
521             if(!rec.import_time()) 
522                 records.push(recId);
523         }
524     }
525
526     fieldmapper.standardRequest(
527         ['open-ils.vandelay', 'open-ils.vandelay.'+currentType+'_record.list.import'],
528         {   async: true,
529             params: [authtoken, records, {overlay_map:currentOverlayRecordsMap}],
530             onresponse: function(r) {
531                 var resp = r.recv().content();
532                 if(e = openils.Event.parse(resp))
533                     return alert(e);
534                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
535             },
536             oncomplete: function() {
537                 return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
538             }
539         }
540     );
541 }
542
543
544 /**
545   * Create queue, upload MARC, process spool, load the newly created queue 
546   */
547 function batchUpload() {
548     var queueName = dijit.byId('vl-queue-name').getValue();
549     currentType = dijit.byId('vl-record-type').getValue();
550
551     var handleProcessSpool = function() {
552         console.log('records uploaded and spooled');
553         retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
554     }
555
556     var handleUploadMARC = function(key) {
557         console.log('marc uploaded');
558         processSpool(key, currentQueueId, currentType, handleProcessSpool);
559     };
560
561     var handleCreateQueue = function(queue) {
562         console.log('queue created ' + queue.name());
563         currentQueueId = queue.id();
564         uploadMARC(handleUploadMARC);
565     };
566
567     createQueue(queueName, currentType, handleCreateQueue);
568 }
569
570
571 function vlFleshQueueSelect(selector, type) {
572     var data = (type == 'bib') ? vbq.toStoreData(userBibQueues) : vaq.toStoreData(userAuthQueues);
573     selector.store = new dojo.data.ItemFileReadStore({data:data});
574     if(data[0])
575         selector.setValue(data[0].id());
576 }
577
578 function vlShowQueueSelect() {
579     displayGlobalDiv('vl-queue-select-div');
580     vlFleshQueueSelect(vlQueueSelectQueueList, 'bib');
581 }
582
583 function vlFetchQueueFromForm() {
584     currentType = vlQueueSelectType.getValue();
585     currentQueueId = vlQueueSelectQueueList.getValue();
586     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
587 }
588     
589
590 dojo.addOnLoad(vlInit);