plugged in bib import with progress bar. in a perfect world (with no collisions...
[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("dojo.cookie");
21 dojo.require("dojox.grid.Grid");
22 dojo.require("dojo.data.ItemFileReadStore");
23 dojo.require("fieldmapper.Fieldmapper");
24 dojo.require("fieldmapper.dojoData");
25 dojo.require('openils.CGI');
26 dojo.require('openils.User');
27 dojo.require('openils.Event');
28
29 var globalDivs = [
30     'vl-generic-progress',
31     'vl-generic-progress-with-total',
32     'vl-marc-upload-div',
33     'vl-queue-div'
34 ];
35
36 var authtoken;
37 var VANDELAY_URL = '/vandelay';
38 var bibAttrDefs = [];
39 var authAttrDefs = [];
40 var queuedRecords = [];
41 var queuedRecordsMap = {};
42 var bibAttrsFetched = false;
43 var authAttrsFetched = false;
44 var attrMap = {};
45 var currentType;
46 var cgi = new openils.CGI();
47 var currentQueueId = null;
48
49 /**
50   * Grab initial data
51   */
52 function vlInit() {
53     authtoken = dojo.cookie('ses') || cgi.param('ses');
54     bibAttrsFetched = false;
55     authAttrsFetched = false;
56
57     // Fetch the bib and authority attribute definitions
58     fieldmapper.standardRequest(
59         ['open-ils.permacrud', 'open-ils.permacrud.search.vqbrad'],
60         {   async: true,
61             params: [authtoken, {id:{'!=':null}}],
62             onresponse: function(r) {
63                 var def = r.recv().content(); 
64                 if(openils.Event.parse(def)) 
65                     return alert(def);
66                 bibAttrDefs.push(def);
67             },
68             oncomplete: function() {
69                 bibAttrsFetched = true;
70                 if(authAttrsFetched) 
71                     runStartupCommands();
72             }
73         }
74     );
75
76     fieldmapper.standardRequest(
77         ['open-ils.permacrud', 'open-ils.permacrud.search.vqarad'],
78         {   async: true,
79             params: [authtoken, {id:{'!=':null}}],
80             onresponse: function(r) {
81                 var def = r.recv().content(); 
82                 if(openils.Event.parse(def)) 
83                     return alert(def);
84                 authAttrDefs.push(def);
85             },
86             oncomplete: function() {
87                 authAttrsFetched = true;
88                 if(bibAttrsFetched) 
89                     runStartupCommands();
90             }
91         }
92     );
93 }
94
95 function displayGlobalDiv(id) {
96     for(var i = 0; i < globalDivs.length; i++) 
97         dojo.style(dojo.byId(globalDivs[i]), 'display', 'none');
98     dojo.style(dojo.byId(id),'display','block');
99 }
100
101 function runStartupCommands() {
102     currentQueueId = cgi.param('qid');
103     currentType = cgi.param('qtype');
104     if(currentQueueId)
105         return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
106     displayGlobalDiv('vl-marc-upload-div');
107 }
108
109 /**
110   * asynchronously upload a file of MARC records
111   */
112 function uploadMARC(onload){
113     dojo.byId('vl-ses-input').value = authtoken;
114     dojo.style(dojo.byId('vl-input-td'),"display","none");
115     dojo.style(dojo.byId('vl-upload-progress-span'),"display","inline"); 
116
117     dojo.style(dojo.byId('vl-file-label'), 'display', 'none');
118     dojo.style(dojo.byId('vl-file-uploading'), 'display', 'inline');
119
120     dojo.io.iframe.send({
121         url: VANDELAY_URL,
122         method: "post",
123         handleAs: "html",
124         form: dojo.byId('vl-marc-upload-form'),
125         handle: function(data,ioArgs){
126             var content = data.documentElement.textContent;
127             var key = content.split(/\n/)[2]; /* XXX have to strip the headers.. (why?) */
128             dojo.style(dojo.byId('vl-input-td'),"display","inline");
129             dojo.style(dojo.byId('vl-upload-progress-span'),"display","none");
130             dojo.style(dojo.byId('vl-file-label'), 'display', 'inline');
131             dojo.style(dojo.byId('vl-file-uploading'), 'display', 'none');
132             onload(key);
133         }
134     });
135 }       
136
137 /**
138   * Creates a new vandelay queue
139   */
140 function createQueue(queueName, type, onload) {
141     fieldmapper.standardRequest(
142         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.create'],
143         {   async: true,
144             params: [authtoken, queueName, null, type],
145             oncomplete : function(r) {
146                 var queue = r.recv().content();
147                 if(e = openils.Event.parse(queue)) 
148                     return alert(e);
149                 onload(queue);
150             }
151         }
152     );
153 }
154
155 /**
156   * Tells vendelay to pull a batch of records from the cache and explode them
157   * out into the vandelay tables
158   */
159 function processSpool(key, queueId, type, onload) {
160     fieldmapper.standardRequest(
161         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'.process_spool'],
162         {   async: true,
163             params: [authtoken, key, queueId],
164             oncomplete : function(r) {
165                 var resp = r.recv().content();
166                 if(e = openils.Event.parse(resp)) 
167                     return alert(e);
168                 onload();
169             }
170         }
171     );
172 }
173
174 function retrieveQueuedRecords(type, queueId, onload) {
175     queuedRecords = [];
176     queuedRecordsMap = {};
177     resetVlQueueGridLayout();
178     fieldmapper.standardRequest(
179         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.records.retrieve.atomic'],
180         {   async: true,
181             params: [authtoken, queueId, {clear_marc:1}],
182             /* intermittent bug in streaming, multipart requests prevents use of onreponse for now...
183             onresponse: function(r) {
184                 var rec = r.recv().content();
185                 if(e = openils.Event.parse(rec))
186                     return alert(e);
187                 queuedRecords.push(rec);
188                 queuedRecordsMap[rec.id()] = rec;
189             },
190             */
191             oncomplete: function(r){
192                 var recs = r.recv().content();
193                 if(e = openils.Event.parse(recs[0]))
194                     return alert(e);
195                 for(var i = 0; i < recs.length; i++) {
196                     var rec = recs[i];
197                     queuedRecords.push(rec);
198                     queuedRecordsMap[rec.id()] = rec;
199                 }
200                 onload();
201             }
202         }
203     );
204 }
205
206 function getAttrValue(rowIdx) {
207     var data = this.grid.model.getRow(rowIdx);
208     if(!data) return '';
209     var attrName = this.field.split('.')[1];
210     var defId = attrMap[attrName];
211     var rec = queuedRecordsMap[data.id];
212     var attrs = rec.attributes();
213     for(var i = 0; i < attrs.length; i++) {
214         var attr = attrs[i];
215         if(attr.field() == defId) 
216             return attr.attr_value();
217     }
218     return '';
219 }
220
221 function buildRecordGrid(type) {
222     displayGlobalDiv('vl-queue-div');
223
224     var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
225     for(var i = 0; i < defs.length; i++) {
226         var attr = defs[i]
227         attrMap[attr.code()] = attr.id();
228         var col = {
229             name:attr.description(), 
230             field:'attr.' + attr.code(),
231             get: getAttrValue
232         };
233         //if(attr.code().match(/title/i)) col.width = 'auto'; // this is hack.
234         vlQueueGridLayout[0].cells[0].push(col);
235     }
236
237     vlQueueGrid.setStructure(vlQueueGridLayout);
238
239     var storeData;
240     if(type == 'bib')
241         storeData = vqbr.toStoreData(queuedRecords);
242     else
243         storeData = vqar.toStoreData(queuedRecords);
244
245     var store = new dojo.data.ItemFileReadStore({data:storeData});
246     var model = new dojox.grid.data.DojoData(
247         null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
248
249     vlQueueGrid.setModel(model);
250     vlQueueGrid.update();
251 }
252
253 var selectableGridRecords = {};
254 function vlQueueGridDrawSelectBox(rowIdx) {
255     var data = this.grid.model.getRow(rowIdx);
256     if(!data) return '';
257     var domId = 'vl-record-list-selected-' +data.id;
258     selectableGridRecords[domId] = data.id;
259     return "<input type='checkbox' id='"+domId+"'/>";
260 }
261
262 function vlSelectAllGridRecords() {
263     for(var id in selectableGridRecords) 
264         dojo.byId(id).checked = true;
265 }
266 function vlSelectNoGridRecords() {
267     for(var id in selectableGridRecords) 
268         dojo.byId(id).checked = false;
269 }
270
271 var handleRetrieveRecords = function() {
272     buildRecordGrid(currentType);
273 }
274
275 function vlImportSelectedRecords() {
276     displayGlobalDiv('vl-generic-progress-with-total');
277     var records = [];
278     for(var id in selectableGridRecords) {
279         if(dojo.byId(id).checked) 
280             records.push(selectableGridRecords[id]);
281     }
282     fieldmapper.standardRequest(
283         ['open-ils.vandelay', 'open-ils.vandelay.'+currentType+'_record.list.import'],
284         {   async: true,
285             params: [authtoken, records],
286             onresponse: function(r) {
287                 var resp = r.recv().content();
288                 if(e = openils.Event.parse(resp))
289                     return alert(e);
290                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
291             },
292             oncomplete: function() {
293                 return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
294             }
295         }
296     );
297 }
298
299
300 /**
301   * Create queue, upload MARC, process spool, load the newly created queue 
302   */
303 function batchUpload() {
304     var queueName = dijit.byId('vl-queue-name').getValue();
305     currentType = dijit.byId('vl-record-type').getValue();
306
307     var handleProcessSpool = function() {
308         console.log('records uploaded and spooled');
309         retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
310     }
311
312     var handleUploadMARC = function(key) {
313         console.log('marc uploaded');
314         processSpool(key, currentQueueId, currentType, handleProcessSpool);
315     };
316
317     var handleCreateQueue = function(queue) {
318         console.log('queue created ' + queue.name());
319         currentQueueId = queue.id();
320         uploadMARC(handleUploadMARC);
321     };
322
323     createQueue(queueName, currentType, handleCreateQueue);
324 }
325
326 dojo.addOnLoad(vlInit);