]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/vandelay/vandelay.js
e27b0a8a5791ff5c5f24e8dd8cc37ee1e1e5ad7b
[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.description() > b.description()) return 1;
80                         if(a.description() < b.description()) 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.description() > b.description()) return 1;
105                         if(a.description() < b.description()) 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             var key = content.split(/\n/)[2]; /* XXX have to strip the headers.. (why?) */
149             dojo.style(dojo.byId('vl-input-td'),"display","inline");
150             dojo.style(dojo.byId('vl-upload-progress-span'),"display","none");
151             dojo.style(dojo.byId('vl-file-label'), 'display', 'inline');
152             dojo.style(dojo.byId('vl-file-uploading'), 'display', 'none');
153             onload(key);
154         }
155     });
156 }       
157
158 /**
159   * Creates a new vandelay queue
160   */
161 function createQueue(queueName, type, onload) {
162     fieldmapper.standardRequest(
163         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.create'],
164         {   async: true,
165             params: [authtoken, queueName, null, type],
166             oncomplete : function(r) {
167                 var queue = r.recv().content();
168                 if(e = openils.Event.parse(queue)) 
169                     return alert(e);
170                 onload(queue);
171             }
172         }
173     );
174 }
175
176 /**
177   * Tells vendelay to pull a batch of records from the cache and explode them
178   * out into the vandelay tables
179   */
180 function processSpool(key, queueId, type, onload) {
181     fieldmapper.standardRequest(
182         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'.process_spool'],
183         {   async: true,
184             params: [authtoken, key, queueId],
185             oncomplete : function(r) {
186                 var resp = r.recv().content();
187                 if(e = openils.Event.parse(resp)) 
188                     return alert(e);
189                 onload();
190             }
191         }
192     );
193 }
194
195 function retrieveQueuedRecords(type, queueId, onload) {
196     queuedRecords = [];
197     queuedRecordsMap = {};
198     resetVlQueueGridLayout();
199     fieldmapper.standardRequest(
200         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.records.retrieve.atomic'],
201         {   async: true,
202             params: [authtoken, queueId, {clear_marc:1}],
203             /* intermittent bug in streaming, multipart requests prevents use of onreponse for now...
204             onresponse: function(r) {
205                 var rec = r.recv().content();
206                 if(e = openils.Event.parse(rec))
207                     return alert(e);
208                 queuedRecords.push(rec);
209                 queuedRecordsMap[rec.id()] = rec;
210             },
211             */
212             oncomplete: function(r){
213                 var recs = r.recv().content();
214                 if(e = openils.Event.parse(recs[0]))
215                     return alert(e);
216                 for(var i = 0; i < recs.length; i++) {
217                     var rec = recs[i];
218                     queuedRecords.push(rec);
219                     queuedRecordsMap[rec.id()] = rec;
220                 }
221                 onload();
222             }
223         }
224     );
225 }
226
227 function vlLoadMatchUI(recId, attrCode) {
228     displayGlobalDiv('vl-generic-progress');
229     var matches = getRecMatchesFromAttrCode(queuedRecordsMap[recId], attrCode);
230     var records = [];
231     for(var i = 0; i < matches.length; i++)
232         records.push(matches[i].eg_record());
233     fieldmapper.standardRequest(
234         ['open-ils.search', 'open-ils.search.biblio.record_entry.slim.retrieve'],
235         {   async: true,
236             params:[records],
237             oncomplete: function(r) {
238                 var recs = r.recv().content();
239                 if(e = openils.Event.parse(recs))
240                     return alert(e);
241                 displayGlobalDiv('vl-match-div');
242                 resetVlMatchGridLayout();
243                 vlMatchGrid.setStructure(vlMatchGridLayout);
244                 var store = new dojo.data.ItemFileReadStore({data:bre.toStoreData(recs)});
245                 var model = new dojox.grid.data.DojoData(
246                     null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
247                 vlMatchGrid.setModel(model);
248                 vlMatchGrid.update();
249             }
250         }
251     );
252 }
253
254 function vlLoadMARCHtml(recId) {
255     displayGlobalDiv('vl-generic-progress');
256     fieldmapper.standardRequest(
257         ['open-ils.search', 'open-ils.search.biblio.record.html'],
258         {   async: true,
259             params: [recId, 1],
260             oncomplete: function(r) {
261             displayGlobalDiv('vl-match-html-div');
262                 var html = r.recv().content();
263                 dojo.byId('vl-match-record-html').innerHTML = html;
264             }
265         }
266     );
267 }
268
269
270 /**
271   * Given a record, an attribute definition code, and a matching record attribute,
272   * this will determine if there are any import matches and build the UI to
273   * represent those matches.  If no matches exist, simply returns the attribute value
274   */
275 function buildAttrColumnUI(rec, attrCode, attr) {
276     var matches = getRecMatchesFromAttrCode(rec, attrCode);
277     if(matches.length > 0) { // found some matches
278         return '<div class="match_div">' +
279             '<a href="javascript:void(0);" onclick="vlLoadMatchUI('+
280             rec.id()+',\''+matches[0].field_type()+'\');">'+ 
281             attr.attr_value() + ' ('+matches.length+')</a></div>';
282     }
283
284     return attr.attr_value();
285 }
286
287 function getRecMatchesFromAttrCode(rec, attrCode) {
288     var matches = [];
289     for(var j = 0; j < rec.matches().length; j++) {
290         var match = rec.matches()[j];
291         if(match.field_type() == attrCode)
292             matches.push(match);
293     }
294     return matches;
295 }
296
297 function getRecAttrFromCode(rec, attrCode) {
298     var defId = attrMap[attrCode];
299     var attrs = rec.attributes();
300     for(var i = 0; i < attrs.length; i++) {
301         var attr = attrs[i];
302         if(attr.field() == defId) 
303             return attr;
304     }
305     return null;
306 }
307
308 function getAttrValue(rowIdx) {
309     var data = this.grid.model.getRow(rowIdx);
310     if(!data) return '';
311     var attrCode = this.field.split('.')[1];
312     var rec = queuedRecordsMap[data.id];
313     var attr = getRecAttrFromCode(rec, attrCode);
314     console.log('attr = ' + attr);
315     if(attr)
316         return buildAttrColumnUI(rec, attrCode, attr);
317     return '';
318 }
319
320 function vlGetDateTimeField(rowIdx) {
321     data = this.grid.model.getRow(rowIdx);
322     if(!data) return '';
323     if(!data[this.field]) return '';
324     var date = dojo.date.stamp.fromISOString(data[this.field]);
325     return dojo.date.locale.format(date, {selector:'date'});
326 }
327
328 function vlGetCreator(rowIdx) {
329     data = this.grid.model.getRow(rowIdx);
330     if(!data) return '';
331     var id = data.creator;
332     if(userCache[id])
333         return userCache[id].usrname();
334     var user = fieldmapper.standardRequest(['open-ils.actor', 'open-ils.actor.user.retrieve'], [authtoken, id]);
335     if(e = openils.Event.parse(user))
336         return alert(e);
337     userCache[id] = user;
338     return user.usrname();
339 }
340
341 function vlGetViewMARC(rowIdx) {
342     data = this.grid.model.getRow(rowIdx);
343     if(data) 
344         return this.value.replace('RECID', data.id);
345 }
346
347 function buildRecordGrid(type) {
348     displayGlobalDiv('vl-queue-div');
349
350     var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
351     for(var i = 0; i < defs.length; i++) {
352         var attr = defs[i]
353         attrMap[attr.code()] = attr.id();
354         var col = {
355             name:attr.description(), 
356             field:'attr.' + attr.code(),
357             get: getAttrValue
358         };
359         //if(attr.code().match(/title/i)) col.width = 'auto'; // this is hack.
360         vlQueueGridLayout[0].cells[0].push(col);
361     }
362
363     vlQueueGrid.setStructure(vlQueueGridLayout);
364
365     var storeData;
366     if(type == 'bib')
367         storeData = vqbr.toStoreData(queuedRecords);
368     else
369         storeData = vqar.toStoreData(queuedRecords);
370
371     var store = new dojo.data.ItemFileReadStore({data:storeData});
372     var model = new dojox.grid.data.DojoData(
373         null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
374
375     vlQueueGrid.setModel(model);
376     vlQueueGrid.update();
377 }
378
379 var selectableGridRecords = {};
380 function vlQueueGridDrawSelectBox(rowIdx) {
381     var data = this.grid.model.getRow(rowIdx);
382     if(!data) return '';
383     var domId = 'vl-record-list-selected-' +data.id;
384     selectableGridRecords[domId] = data.id;
385     return "<input type='checkbox' id='"+domId+"'/>";
386 }
387
388 function vlSelectAllGridRecords() {
389     for(var id in selectableGridRecords) 
390         dojo.byId(id).checked = true;
391 }
392 function vlSelectNoGridRecords() {
393     for(var id in selectableGridRecords) 
394         dojo.byId(id).checked = false;
395 }
396
397 var handleRetrieveRecords = function() {
398     buildRecordGrid(currentType);
399 }
400
401 function vlImportSelectedRecords() {
402     displayGlobalDiv('vl-generic-progress-with-total');
403     var records = [];
404     for(var id in selectableGridRecords) {
405         if(dojo.byId(id).checked) {
406             var recId = selectableGridRecords[id];
407             var rec = queuedRecordsMap[recId];
408             if(!rec.import_time()) 
409                 records.push(recId);
410         }
411     }
412     fieldmapper.standardRequest(
413         ['open-ils.vandelay', 'open-ils.vandelay.'+currentType+'_record.list.import'],
414         {   async: true,
415             params: [authtoken, records],
416             onresponse: function(r) {
417                 var resp = r.recv().content();
418                 if(e = openils.Event.parse(resp))
419                     return alert(e);
420                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
421             },
422             oncomplete: function() {
423                 return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
424             }
425         }
426     );
427 }
428
429
430 /**
431   * Create queue, upload MARC, process spool, load the newly created queue 
432   */
433 function batchUpload() {
434     var queueName = dijit.byId('vl-queue-name').getValue();
435     currentType = dijit.byId('vl-record-type').getValue();
436
437     var handleProcessSpool = function() {
438         console.log('records uploaded and spooled');
439         retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
440     }
441
442     var handleUploadMARC = function(key) {
443         console.log('marc uploaded');
444         processSpool(key, currentQueueId, currentType, handleProcessSpool);
445     };
446
447     var handleCreateQueue = function(queue) {
448         console.log('queue created ' + queue.name());
449         currentQueueId = queue.id();
450         uploadMARC(handleUploadMARC);
451     };
452
453     createQueue(queueName, currentType, handleCreateQueue);
454 }
455
456 dojo.addOnLoad(vlInit);