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