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