make sure record is selected for import if overlay has been selected. pre-select...
[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 ];
41
42 var authtoken;
43 var VANDELAY_URL = '/vandelay';
44 var bibAttrDefs = [];
45 var authAttrDefs = [];
46 var queuedRecords = [];
47 var queuedRecordsMap = {};
48 var bibAttrsFetched = false;
49 var authAttrsFetched = false;
50 var attrDefMap = {}; // maps attr def code names to attr def ids
51 var currentType;
52 var cgi = new openils.CGI();
53 var currentQueueId = null;
54 var userCache = {};
55 var currentMatchedRecords; // set of loaded matched bib records
56 var currentOverlayRecordsMap; // map of import record to overlay record
57 var currentImportRecId; // when analyzing matches, this is the current import record
58
59 /**
60   * Grab initial data
61   */
62 function vlInit() {
63     authtoken = dojo.cookie('ses') || cgi.param('ses');
64     bibAttrsFetched = false;
65     authAttrsFetched = false;
66
67     // Fetch the bib and authority attribute definitions
68     fieldmapper.standardRequest(
69         ['open-ils.permacrud', 'open-ils.permacrud.search.vqbrad'],
70         {   async: true,
71             params: [authtoken, {id:{'!=':null}}],
72             onresponse: function(r) {
73                 var def = r.recv().content(); 
74                 if(e = openils.Event.parse(def[0])) 
75                     return alert(e);
76                 bibAttrDefs.push(def);
77             },
78             oncomplete: function() {
79                 bibAttrsFetched = true;
80                 bibAttrDefs = bibAttrDefs.sort(
81                     function(a, b) {
82                         if(a.id() > b.id()) return 1;
83                         if(a.id() < b.id()) return -1;
84                         return 0;
85                     }
86                 );
87                 if(authAttrsFetched) 
88                     runStartupCommands();
89             }
90         }
91     );
92
93     fieldmapper.standardRequest(
94         ['open-ils.permacrud', 'open-ils.permacrud.search.vqarad'],
95         {   async: true,
96             params: [authtoken, {id:{'!=':null}}],
97             onresponse: function(r) {
98                 var def = r.recv().content(); 
99                 if(e = openils.Event.parse(def[0])) 
100                     return alert(e);
101                 authAttrDefs.push(def);
102             },
103             oncomplete: function() {
104                 authAttrsFetched = true;
105                 authAttrDefs = authAttrDefs.sort(
106                     function(a, b) {
107                         if(a.id() > b.id()) return 1;
108                         if(a.id() < b.id()) return -1;
109                         return 0;
110                     }
111                 );
112                 if(bibAttrsFetched) 
113                     runStartupCommands();
114             }
115         }
116     );
117 }
118
119 function displayGlobalDiv(id) {
120     for(var i = 0; i < globalDivs.length; i++) 
121         dojo.style(dojo.byId(globalDivs[i]), 'display', 'none');
122     dojo.style(dojo.byId(id),'display','block');
123 }
124
125 function runStartupCommands() {
126     currentQueueId = cgi.param('qid');
127     currentType = cgi.param('qtype');
128     if(currentQueueId)
129         return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
130     displayGlobalDiv('vl-marc-upload-div');
131 }
132
133 /**
134   * asynchronously upload a file of MARC records
135   */
136 function uploadMARC(onload){
137     dojo.byId('vl-ses-input').value = authtoken;
138     dojo.style(dojo.byId('vl-input-td'),"display","none");
139     dojo.style(dojo.byId('vl-upload-progress-span'),"display","inline"); 
140
141     dojo.style(dojo.byId('vl-file-label'), 'display', 'none');
142     dojo.style(dojo.byId('vl-file-uploading'), 'display', 'inline');
143
144     dojo.io.iframe.send({
145         url: VANDELAY_URL,
146         method: "post",
147         handleAs: "html",
148         form: dojo.byId('vl-marc-upload-form'),
149         handle: function(data,ioArgs){
150             var content = data.documentElement.textContent;
151             dojo.style(dojo.byId('vl-input-td'),"display","inline");
152             dojo.style(dojo.byId('vl-upload-progress-span'),"display","none");
153             dojo.style(dojo.byId('vl-file-label'), 'display', 'inline');
154             dojo.style(dojo.byId('vl-file-uploading'), 'display', 'none');
155             onload(content);
156         }
157     });
158 }       
159
160 /**
161   * Creates a new vandelay queue
162   */
163 function createQueue(queueName, type, onload) {
164     fieldmapper.standardRequest(
165         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.create'],
166         {   async: true,
167             params: [authtoken, queueName, null, type],
168             oncomplete : function(r) {
169                 var queue = r.recv().content();
170                 if(e = openils.Event.parse(queue)) 
171                     return alert(e);
172                 onload(queue);
173             }
174         }
175     );
176 }
177
178 /**
179   * Tells vendelay to pull a batch of records from the cache and explode them
180   * out into the vandelay tables
181   */
182 function processSpool(key, queueId, type, onload) {
183     fieldmapper.standardRequest(
184         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'.process_spool'],
185         {   async: true,
186             params: [authtoken, key, queueId],
187             oncomplete : function(r) {
188                 var resp = r.recv().content();
189                 if(e = openils.Event.parse(resp)) 
190                     return alert(e);
191                 onload();
192             }
193         }
194     );
195 }
196
197 function retrieveQueuedRecords(type, queueId, onload) {
198     queuedRecords = [];
199     queuedRecordsMap = {};
200     currentOverlayRecordsMap = {};
201     resetVlQueueGridLayout();
202
203     fieldmapper.standardRequest(
204         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.records.retrieve.atomic'],
205         {   async: true,
206             params: [authtoken, queueId, {clear_marc:1}],
207             /* intermittent bug in streaming, multipart requests prevents use of onreponse for now...
208             onresponse: function(r) {
209                 var rec = r.recv().content();
210                 if(e = openils.Event.parse(rec))
211                     return alert(e);
212                 queuedRecords.push(rec);
213                 queuedRecordsMap[rec.id()] = rec;
214             },
215             */
216             oncomplete: function(r){
217                 var recs = r.recv().content();
218                 if(e = openils.Event.parse(recs[0]))
219                     return alert(e);
220                 for(var i = 0; i < recs.length; i++) {
221                     var rec = recs[i];
222                     queuedRecords.push(rec);
223                     queuedRecordsMap[rec.id()] = rec;
224                 }
225                 onload();
226             }
227         }
228     );
229 }
230
231 function vlLoadMatchUI(recId, attrCode) {
232     displayGlobalDiv('vl-generic-progress');
233     var matches = getRecMatchesFromAttrCode(queuedRecordsMap[recId], attrCode);
234     var records = [];
235     currentImportRecId = recId;
236     for(var i = 0; i < matches.length; i++)
237         records.push(matches[i].eg_record());
238     fieldmapper.standardRequest(
239         ['open-ils.search', 'open-ils.search.biblio.record_entry.slim.retrieve'],
240         {   async: true,
241             params:[records],
242             oncomplete: function(r) {
243                 var recs = r.recv().content();
244                 if(e = openils.Event.parse(recs))
245                     return alert(e);
246                 displayGlobalDiv('vl-match-div');
247                 resetVlMatchGridLayout();
248                 currentMatchedRecords = recs;
249                 vlMatchGrid.setStructure(vlMatchGridLayout);
250                 var dataStore = bre.toStoreData(recs, null, {virtualFields:['field_type']});
251                 for(var i = 0; i < dataStore.items.length; i++) {
252                     var item = dataStore.items[i];
253                     for(var j = 0; j < matches.length; j++) {
254                         var match = matches[j];
255                         if(match.eg_record() == item.id)
256                             item.field_type = match.field_type();
257                     }
258                 }
259                 var store = new dojo.data.ItemFileReadStore({data:dataStore});
260                 var model = new dojox.grid.data.DojoData(
261                     null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
262                 vlMatchGrid.setModel(model);
263                 vlMatchGrid.update();
264             }
265         }
266     );
267 }
268
269
270 function vlLoadMARCHtml(recId) {
271     displayGlobalDiv('vl-generic-progress');
272     fieldmapper.standardRequest(
273         ['open-ils.search', 'open-ils.search.biblio.record.html'],
274         {   async: true,
275             params: [recId, 1],
276             oncomplete: function(r) {
277             displayGlobalDiv('vl-match-html-div');
278                 var html = r.recv().content();
279                 dojo.byId('vl-match-record-html').innerHTML = html;
280             }
281         }
282     );
283 }
284
285
286 /**
287   * Given a record, an attribute definition code, and a matching record attribute,
288   * this will determine if there are any import matches and build the UI to
289   * represent those matches.  If no matches exist, simply returns the attribute value
290   */
291 function buildAttrColumnUI(rec, attrCode, attr) {
292     var matches = getRecMatchesFromAttrCode(rec, attrCode);
293     if(matches.length > 0) { // found some matches
294         return '<div class="match_div">' +
295             '<a href="javascript:void(0);" onclick="vlLoadMatchUI('+
296             rec.id()+',\''+attrCode+'\');">'+ 
297             attr.attr_value() + '&nbsp;('+matches.length+')</a></div>';
298     }
299
300     return attr.attr_value();
301 }
302
303 function getRecMatchesFromAttrCode(rec, attrCode) {
304     var matches = [];
305     var attr = getRecAttrFromCode(rec, attrCode);
306     for(var j = 0; j < rec.matches().length; j++) {
307         var match = rec.matches()[j];
308         if(match.matched_attr() == attr.id()) 
309             matches.push(match);
310     }
311     return matches;
312 }
313
314 function getRecAttrFromCode(rec, attrCode) {
315     var defId = attrDefMap[attrCode];
316     var attrs = rec.attributes();
317     for(var i = 0; i < attrs.length; i++) {
318         var attr = attrs[i];
319         if(attr.field() == defId) 
320             return attr;
321     }
322     return null;
323 }
324
325 function getAttrValue(rowIdx) {
326     var data = this.grid.model.getRow(rowIdx);
327     if(!data) return '';
328     var attrCode = this.field.split('.')[1];
329     var rec = queuedRecordsMap[data.id];
330     var attr = getRecAttrFromCode(rec, attrCode);
331     if(attr)
332         return buildAttrColumnUI(rec, attrCode, attr);
333     return '';
334 }
335
336 function vlGetDateTimeField(rowIdx) {
337     data = this.grid.model.getRow(rowIdx);
338     if(!data) return '';
339     if(!data[this.field]) return '';
340     var date = dojo.date.stamp.fromISOString(data[this.field]);
341     return dojo.date.locale.format(date, {selector:'date'});
342 }
343
344 function vlGetCreator(rowIdx) {
345     data = this.grid.model.getRow(rowIdx);
346     if(!data) return '';
347     var id = data.creator;
348     if(userCache[id])
349         return userCache[id].usrname();
350     var user = fieldmapper.standardRequest(['open-ils.actor', 'open-ils.actor.user.retrieve'], [authtoken, id]);
351     if(e = openils.Event.parse(user))
352         return alert(e);
353     userCache[id] = user;
354     return user.usrname();
355 }
356
357 function vlGetViewMARC(rowIdx) {
358     data = this.grid.model.getRow(rowIdx);
359     if(data) 
360         return this.value.replace('RECID', data.id);
361 }
362
363 function vlGetOverlayTargetSelector(rowIdx) {
364     data = this.grid.model.getRow(rowIdx);
365     if(data) {
366         var value = this.value.replace('ID', data.id);
367         var overlay = currentOverlayRecordsMap[currentImportRecId];
368         if(overlay && overlay == data.id) 
369             value = value.replace('/>', 'checked="checked"/>');
370         return value;
371     }
372 }
373
374 /**
375   * see if the user has enabled overlays for the current match set and, 
376   * if so, map the current import record to the overlay target.
377   */
378 function vlHandleOverlayTargetSelected() {
379     if(vlOverlayTargetEnable.checked) {
380         for(var i = 0; i < currentMatchedRecords.length; i++) {
381             var matchRecId = currentMatchedRecords[i].id();
382             if(dojo.byId('vl-overlay-target-'+matchRecId).checked) {
383                 console.log("found overlay target " + matchRecId);
384                 currentOverlayRecordsMap[currentImportRecId] = matchRecId;
385                 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = true;
386                 return;
387             }
388         }
389     } else {
390         delete currentOverlayRecordsMap[currentImportRecId];
391         dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = false;
392     }
393 }
394
395 function buildRecordGrid(type) {
396     displayGlobalDiv('vl-queue-div');
397
398     currentOverlayRecordsMap = {};
399
400     var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
401     for(var i = 0; i < defs.length; i++) {
402         var def = defs[i]
403         attrDefMap[def.code()] = def.id();
404         var col = {
405             name:def.description(), 
406             field:'attr.' + def.code(),
407             get: getAttrValue
408         };
409         //if(def.code().match(/title/i)) col.width = 'auto'; // this is hack.
410         vlQueueGridLayout[0].cells[0].push(col);
411     }
412
413     vlQueueGrid.setStructure(vlQueueGridLayout);
414
415     var storeData;
416     if(type == 'bib')
417         storeData = vqbr.toStoreData(queuedRecords);
418     else
419         storeData = vqar.toStoreData(queuedRecords);
420
421     var store = new dojo.data.ItemFileReadStore({data:storeData});
422     var model = new dojox.grid.data.DojoData(
423         null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
424
425     vlQueueGrid.setModel(model);
426     vlQueueGrid.update();
427 }
428
429 /*
430 function test() {
431     alert(vlQueueGridLayout.picker);
432     vlQueueGridLayout.oils = {};
433     vlQueueGridLayout[0].cells[0].pop();
434     vlQueueGridLayout[0].cells[0].pop();
435     vlQueueGridLayout[0].cells[0].pop();
436     vlQueueGridLayout[0].cells[0].pop();
437     vlQueueGridLayout[0].cells[0].pop();
438     vlQueueGrid.setStructure(vlQueueGridLayout);
439     vlQueueGrid.update();
440 }
441 */
442
443 var selectableGridRecords = {};
444 function vlQueueGridDrawSelectBox(rowIdx) {
445     var data = this.grid.model.getRow(rowIdx);
446     if(!data) return '';
447     var domId = 'vl-record-list-selected-' +data.id;
448     selectableGridRecords[domId] = data.id;
449     return "<input type='checkbox' id='"+domId+"'/>";
450 }
451
452 function vlSelectAllGridRecords() {
453     for(var id in selectableGridRecords) 
454         dojo.byId(id).checked = true;
455 }
456 function vlSelectNoGridRecords() {
457     for(var id in selectableGridRecords) 
458         dojo.byId(id).checked = false;
459 }
460
461 var handleRetrieveRecords = function() {
462     buildRecordGrid(currentType);
463 }
464
465 function vlImportSelectedRecords() {
466     displayGlobalDiv('vl-generic-progress-with-total');
467     var records = [];
468
469     for(var id in selectableGridRecords) {
470         if(dojo.byId(id).checked) {
471             var recId = selectableGridRecords[id];
472             var rec = queuedRecordsMap[recId];
473             if(!rec.import_time()) 
474                 records.push(recId);
475         }
476     }
477
478     fieldmapper.standardRequest(
479         ['open-ils.vandelay', 'open-ils.vandelay.'+currentType+'_record.list.import'],
480         {   async: true,
481             params: [authtoken, records, {overlay_map:currentOverlayRecordsMap}],
482             onresponse: function(r) {
483                 var resp = r.recv().content();
484                 if(e = openils.Event.parse(resp))
485                     return alert(e);
486                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
487             },
488             oncomplete: function() {
489                 return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
490             }
491         }
492     );
493 }
494
495
496 /**
497   * Create queue, upload MARC, process spool, load the newly created queue 
498   */
499 function batchUpload() {
500     var queueName = dijit.byId('vl-queue-name').getValue();
501     currentType = dijit.byId('vl-record-type').getValue();
502
503     var handleProcessSpool = function() {
504         console.log('records uploaded and spooled');
505         retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
506     }
507
508     var handleUploadMARC = function(key) {
509         console.log('marc uploaded');
510         processSpool(key, currentQueueId, currentType, handleProcessSpool);
511     };
512
513     var handleCreateQueue = function(queue) {
514         console.log('queue created ' + queue.name());
515         currentQueueId = queue.id();
516         uploadMARC(handleUploadMARC);
517     };
518
519     createQueue(queueName, currentType, handleCreateQueue);
520 }
521
522 dojo.addOnLoad(vlInit);