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