for now, show the matched attr value and number of matches. will link to a page of...
[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 function vlLoadMatchUI(recId, attrCode) {
223     alert(recId + ' : ' + attrCode);
224 }
225
226
227 /**
228   * Given a record, an attribute definition code, and a matching record attribute,
229   * this will determine if there are any import matches and build the UI to
230   * represent those matches.  If no matches exist, simply returns the attribute value
231   */
232 function buildAttrColumnUI(rec, attrCode, attr) {
233     var matches = [];
234     for(var j = 0; j < rec.matches().length; j++) {
235         var match = rec.matches()[j];
236         if(match.field_type() == attrCode)
237             matches.push(match);
238     }
239
240     if(matches.length > 0) { // found some matches
241         return '<div class="match_div">' +
242             '<a href="javascript:void(0);" onclick="vlLoadMatchUI('+
243             rec.id()+',\''+match.field_type()+'\');">'+ 
244             attr.attr_value() + '&nbsp;('+matches.length+')</a></div>';
245     }
246
247     return attr.attr_value();
248 }
249
250 function getAttrValue(rowIdx) {
251     var data = this.grid.model.getRow(rowIdx);
252     if(!data) return '';
253     var attrCode = this.field.split('.')[1];
254     var defId = attrMap[attrCode];
255     var rec = queuedRecordsMap[data.id];
256     var attrs = rec.attributes();
257     for(var i = 0; i < attrs.length; i++) {
258         var attr = attrs[i];
259         if(attr.field() == defId) 
260             return buildAttrColumnUI(rec, attrCode, attr);
261     }
262     return '';
263 }
264
265 function getDateTimeField(rowIdx) {
266     data = this.grid.model.getRow(rowIdx);
267     if(!data) return '';
268     var date = dojo.date.stamp.fromISOString(data[this.field]);
269     return dojo.date.locale.format(date, {formatLength:'medium'});
270 }
271
272 function buildRecordGrid(type) {
273     displayGlobalDiv('vl-queue-div');
274
275     var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
276     for(var i = 0; i < defs.length; i++) {
277         var attr = defs[i]
278         attrMap[attr.code()] = attr.id();
279         var col = {
280             name:attr.description(), 
281             field:'attr.' + attr.code(),
282             get: getAttrValue
283         };
284         //if(attr.code().match(/title/i)) col.width = 'auto'; // this is hack.
285         vlQueueGridLayout[0].cells[0].push(col);
286     }
287
288     vlQueueGrid.setStructure(vlQueueGridLayout);
289
290     var storeData;
291     if(type == 'bib')
292         storeData = vqbr.toStoreData(queuedRecords);
293     else
294         storeData = vqar.toStoreData(queuedRecords);
295
296     var store = new dojo.data.ItemFileReadStore({data:storeData});
297     var model = new dojox.grid.data.DojoData(
298         null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
299
300     vlQueueGrid.setModel(model);
301     vlQueueGrid.update();
302 }
303
304 var selectableGridRecords = {};
305 function vlQueueGridDrawSelectBox(rowIdx) {
306     var data = this.grid.model.getRow(rowIdx);
307     if(!data) return '';
308     var domId = 'vl-record-list-selected-' +data.id;
309     selectableGridRecords[domId] = data.id;
310     return "<input type='checkbox' id='"+domId+"'/>";
311 }
312
313 function vlSelectAllGridRecords() {
314     for(var id in selectableGridRecords) 
315         dojo.byId(id).checked = true;
316 }
317 function vlSelectNoGridRecords() {
318     for(var id in selectableGridRecords) 
319         dojo.byId(id).checked = false;
320 }
321
322 var handleRetrieveRecords = function() {
323     buildRecordGrid(currentType);
324 }
325
326 function vlImportSelectedRecords() {
327     displayGlobalDiv('vl-generic-progress-with-total');
328     var records = [];
329     for(var id in selectableGridRecords) {
330         if(dojo.byId(id).checked) {
331             var recId = selectableGridRecords[id];
332             var rec = queuedRecordsMap[recId];
333             if(!rec.import_time()) 
334                 records.push(recId);
335         }
336     }
337     fieldmapper.standardRequest(
338         ['open-ils.vandelay', 'open-ils.vandelay.'+currentType+'_record.list.import'],
339         {   async: true,
340             params: [authtoken, records],
341             onresponse: function(r) {
342                 var resp = r.recv().content();
343                 if(e = openils.Event.parse(resp))
344                     return alert(e);
345                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
346             },
347             oncomplete: function() {
348                 return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
349             }
350         }
351     );
352 }
353
354
355 /**
356   * Create queue, upload MARC, process spool, load the newly created queue 
357   */
358 function batchUpload() {
359     var queueName = dijit.byId('vl-queue-name').getValue();
360     currentType = dijit.byId('vl-record-type').getValue();
361
362     var handleProcessSpool = function() {
363         console.log('records uploaded and spooled');
364         retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
365     }
366
367     var handleUploadMARC = function(key) {
368         console.log('marc uploaded');
369         processSpool(key, currentQueueId, currentType, handleProcessSpool);
370     };
371
372     var handleCreateQueue = function(queue) {
373         console.log('queue created ' + queue.name());
374         currentQueueId = queue.id();
375         uploadMARC(handleUploadMARC);
376     };
377
378     createQueue(queueName, currentType, handleCreateQueue);
379 }
380
381 dojo.addOnLoad(vlInit);