]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/vandelay/vandelay.js
added import profile selector and auto-merge-1-match options to main upload page
[working/Evergreen.git] / Open-ILS / web / js / ui / default / 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.FilteringSelect"); 
19 dojo.require("dijit.layout.ContentPane");
20 dojo.require("dijit.layout.TabContainer");
21 dojo.require("dijit.layout.LayoutContainer");
22 dojo.require('dijit.form.Button');
23 dojo.require('dijit.form.CheckBox');
24 dojo.require('dijit.Toolbar');
25 dojo.require('dijit.Tooltip');
26 dojo.require('dijit.Menu');
27 dojo.require("dijit.Dialog");
28 dojo.require("dojo.cookie");
29 dojo.require('dojox.grid.DataGrid');
30 dojo.require("dojo.data.ItemFileReadStore");
31 dojo.require('dojo.date.locale');
32 dojo.require('dojo.date.stamp');
33 dojo.require("fieldmapper.Fieldmapper");
34 dojo.require("fieldmapper.dojoData");
35 dojo.require("fieldmapper.OrgUtils");
36 dojo.require('openils.CGI');
37 dojo.require('openils.User');
38 dojo.require('openils.Event');
39 dojo.require('openils.Util');
40 dojo.require('openils.MarcXPathParser');
41 dojo.require('openils.widget.GridColumnPicker');
42 dojo.require('openils.PermaCrud');
43 dojo.require('openils.widget.OrgUnitFilteringSelect');
44 dojo.require('openils.widget.AutoGrid');
45 dojo.require('openils.widget.AutoFieldWidget');
46
47
48 var globalDivs = [
49     'vl-generic-progress',
50     'vl-generic-progress-with-total',
51     'vl-marc-upload-div',
52     'vl-queue-div',
53     'vl-match-div',
54     'vl-marc-html-div',
55     'vl-queue-select-div',
56     'vl-marc-upload-status-div',
57     'vl-attr-editor-div',
58     'vl-marc-export-div',
59     'vl-profile-editor-div'
60 ];
61
62 var authtoken;
63 var VANDELAY_URL = '/vandelay-upload';
64 var bibAttrDefs = [];
65 var authAttrDefs = [];
66 var queuedRecords = [];
67 var queuedRecordsMap = {};
68 var bibAttrsFetched = false;
69 var authAttrsFetched = false;
70 var attrDefMap = {}; // maps attr def code names to attr def ids
71 var currentType;
72 var currentQueueId = null;
73 var userCache = {};
74 var currentMatchedRecords; // set of loaded matched bib records
75 var currentOverlayRecordsMap; // map of import record to overlay record
76 var currentOverlayRecordsMapGid; // map of import record to overlay record grid id
77 var currentImportRecId; // when analyzing matches, this is the current import record
78 var userBibQueues = []; // only non-complete queues
79 var userAuthQueues = []; // only non-complete queues
80 var allUserBibQueues;
81 var allUserAuthQueues;
82 var selectableGridRecords;
83 var cgi = new openils.CGI();
84 var vlQueueGridColumePicker = {};
85 var vlBibSources = [];
86 var importItemDefs = [];
87
88 /**
89   * Grab initial data
90   */
91 function vlInit() {
92     authtoken = openils.User.authtoken;
93     var initNeeded = 6; // how many async responses do we need before we're init'd 
94     var initCount = 0; // how many async reponses we've received
95
96     openils.Util.registerEnterHandler(
97         vlQueueDisplayPage.domNode, function(){retrieveQueuedRecords();});
98     openils.Util.addCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
99
100     function checkInitDone() {
101         initCount++;
102         if(initCount == initNeeded)
103             runStartupCommands();
104     }
105
106     var profiles = new openils.PermaCrud().retrieveAll('vmp');
107     vlUploadMergeProfile.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(profiles)});
108     vlUploadMergeProfile.labelAttr = 'name';
109     vlUploadMergeProfile.searchAttr = 'name';
110     vlUploadMergeProfile.startup();
111
112     // Fetch the bib and authority attribute definitions 
113     vlFetchBibAttrDefs(function () { checkInitDone(); });
114     vlFetchAuthAttrDefs(function () { checkInitDone(); });
115
116     vlRetrieveQueueList('bib', null, 
117         function(list) {
118             allUserBibQueues = list;
119             for(var i = 0; i < allUserBibQueues.length; i++) {
120                 if(allUserBibQueues[i].complete() == 'f')
121                     userBibQueues.push(allUserBibQueues[i]);
122             }
123             checkInitDone();
124         }
125     );
126
127     vlRetrieveQueueList('auth', null, 
128         function(list) {
129             allUserAuthQueues = list;
130             for(var i = 0; i < allUserAuthQueues.length; i++) {
131                 if(allUserAuthQueues[i].complete() == 'f')
132                     userAuthQueues.push(allUserAuthQueues[i]);
133             }
134             checkInitDone();
135         }
136     );
137
138     fieldmapper.standardRequest(
139         ['open-ils.permacrud', 'open-ils.permacrud.search.cbs.atomic'],
140         {   async: true,
141             params: [authtoken, {id:{"!=":null}}, {order_by:{cbs:'id'}}],
142             oncomplete : function(r) {
143                 vlBibSources = openils.Util.readResponse(r, false, true);
144                 checkInitDone();
145             }
146         }
147     );
148
149     var owner = fieldmapper.aou.orgNodeTrail(fieldmapper.aou.findOrgUnit(new openils.User().user.ws_ou()));
150     new openils.PermaCrud().search('viiad', 
151         {owner: owner.map(function(org) { return org.id(); })},
152         {   async: true,
153             oncomplete: function(r) {
154                 importItemDefs = openils.Util.readResponse(r);
155                 checkInitDone();
156             }
157         }
158     );
159
160     vlAttrEditorInit();
161 }
162
163
164 openils.Util.addOnLoad(vlInit);
165
166
167 // fetch the bib and authority attribute definitions
168
169 function vlFetchBibAttrDefs(postcomplete) {
170     bibAttrDefs = [];
171     fieldmapper.standardRequest(
172         ['open-ils.permacrud', 'open-ils.permacrud.search.vqbrad'],
173         {   async: true,
174             params: [authtoken, {id:{'!=':null}}],
175             onresponse: function(r) {
176                 var def = r.recv().content(); 
177                 if(e = openils.Event.parse(def[0])) 
178                     return alert(e);
179                 bibAttrDefs.push(def);
180             },
181             oncomplete: function() {
182                 bibAttrDefs = bibAttrDefs.sort(
183                     function(a, b) {
184                         if(a.id() > b.id()) return 1;
185                         if(a.id() < b.id()) return -1;
186                         return 0;
187                     }
188                 );
189                 postcomplete();
190             }
191         }
192     );
193 }
194
195 function vlFetchAuthAttrDefs(postcomplete) {
196     authAttrDefs = [];
197     fieldmapper.standardRequest(
198         ['open-ils.permacrud', 'open-ils.permacrud.search.vqarad'],
199         {   async: true,
200             params: [authtoken, {id:{'!=':null}}],
201             onresponse: function(r) {
202                 var def = r.recv().content(); 
203                 if(e = openils.Event.parse(def[0])) 
204                     return alert(e);
205                 authAttrDefs.push(def);
206             },
207             oncomplete: function() {
208                 authAttrDefs = authAttrDefs.sort(
209                     function(a, b) {
210                         if(a.id() > b.id()) return 1;
211                         if(a.id() < b.id()) return -1;
212                         return 0;
213                     }
214                 );
215                 postcomplete();
216             }
217         }
218     );
219 }
220
221 function vlRetrieveQueueList(type, filter, onload) {
222     type = (type == 'bib') ? type : 'authority';
223     fieldmapper.standardRequest(
224         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.owner.retrieve.atomic'],
225         {   async: true,
226             params: [authtoken, null, filter],
227             oncomplete: function(r) {
228                 var list = r.recv().content();
229                 if(e = openils.Event.parse(list[0]))
230                     return alert(e);
231                 onload(list);
232             }
233         }
234     );
235
236 }
237
238 function displayGlobalDiv(id) {
239     for(var i = 0; i < globalDivs.length; i++) {
240         try {
241             dojo.style(dojo.byId(globalDivs[i]), 'display', 'none');
242         } catch(e) {
243             alert('please define div ' + globalDivs[i]);
244         }
245     }
246     dojo.style(dojo.byId(id),'display','block');
247
248     openils.Util.removeCSSClass(dojo.byId('vl-menu-marc-export'), 'toolbar_selected');
249     openils.Util.removeCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
250     openils.Util.removeCSSClass(dojo.byId('vl-menu-queue-select'), 'toolbar_selected');
251     openils.Util.removeCSSClass(dojo.byId('vl-menu-attr-editor'), 'toolbar_selected');
252     openils.Util.removeCSSClass(dojo.byId('vl-menu-profile-editor'), 'toolbar_selected');
253
254     switch(id) {
255         case 'vl-marc-export-div':
256             openils.Util.addCSSClass(dojo.byId('vl-menu-marc-export'), 'toolbar_selected');
257             break;
258         case 'vl-marc-upload-div':
259             openils.Util.addCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
260             break;
261         case 'vl-queue-select-div':
262             openils.Util.addCSSClass(dojo.byId('vl-menu-queue-select'), 'toolbar_selected');
263             break;
264         case 'vl-attr-editor-div':
265             openils.Util.addCSSClass(dojo.byId('vl-menu-attr-editor'), 'toolbar_selected');
266             break;
267         case 'vl-profile-editor-div':
268             openils.Util.addCSSClass(dojo.byId('vl-menu-profile-editor'), 'toolbar_selected');
269             break;
270     }
271 }
272
273 function runStartupCommands() {
274     currentQueueId = cgi.param('qid');
275     currentType = cgi.param('qtype');
276     dojo.style('vl-nav-bar', 'visibility', 'visible');
277     if(currentQueueId)
278         return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
279     vlShowUploadForm();
280 }
281
282 /**
283   * asynchronously upload a file of MARC records
284   */
285 function uploadMARC(onload){
286     dojo.byId('vl-upload-status-count').innerHTML = '0';
287     dojo.byId('vl-ses-input').value = authtoken;
288     displayGlobalDiv('vl-marc-upload-status-div');
289     dojo.io.iframe.send({
290         url: VANDELAY_URL,
291         method: "post",
292         handleAs: "html",
293         form: dojo.byId('vl-marc-upload-form'),
294         handle: function(data,ioArgs){
295             var content = data.documentElement.textContent;
296             onload(content);
297         }
298     });
299 }       
300
301 /**
302   * Creates a new vandelay queue
303   */
304 function createQueue(queueName, type, onload, importDefId) {
305     var name = (type=='bib') ? 'bib' : 'authority';
306     var method = 'open-ils.vandelay.'+ name +'_queue.create'
307     fieldmapper.standardRequest(
308         ['open-ils.vandelay', method],
309         {   async: true,
310             params: [authtoken, queueName, null, name, importDefId],
311             oncomplete : function(r) {
312                 var queue = r.recv().content();
313                 if(e = openils.Event.parse(queue)) 
314                     return alert(e);
315                 onload(queue);
316             }
317         }
318     );
319 }
320
321 /**
322   * Tells vandelay to pull a batch of records from the cache and explode them
323   * out into the vandelay tables
324   */
325 function processSpool(key, queueId, type, onload) {
326     fieldmapper.standardRequest(
327         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'.process_spool'],
328         {   async: true,
329             params: [authtoken, key, queueId],
330             onresponse : function(r) {
331                 var resp = r.recv().content();
332                 if(e = openils.Event.parse(resp)) 
333                     return alert(e);
334                 dojo.byId('vl-upload-status-count').innerHTML = resp;
335             },
336             oncomplete : function(r) {onload();}
337         }
338     );
339 }
340
341 function retrieveQueuedRecords(type, queueId, onload) {
342     displayGlobalDiv('vl-generic-progress');
343     queuedRecords = [];
344     queuedRecordsMap = {};
345     currentOverlayRecordsMap = {};
346     currentOverlayRecordsMapGid = {};
347     selectableGridRecords = {};
348     //resetVlQueueGridLayout();
349
350     if(!type) type = currentType;
351     if(!queueId) queueId = currentQueueId;
352     if(!onload) onload = handleRetrieveRecords;
353
354     var method = 'open-ils.vandelay.'+type+'_queue.records.retrieve.atomic';
355     if(vlQueueGridShowMatches.checked)
356         method = method.replace('records', 'records.matches');
357
358     var sel = dojo.byId('vl-queue-display-limit-selector');
359     var limit = parseInt(sel.options[sel.selectedIndex].value);
360     var offset = limit * parseInt(vlQueueDisplayPage.attr('value')-1);
361
362     var params =  [authtoken, queueId, {clear_marc: 1, offset: offset, limit: limit}];
363     if(vlQueueGridShowNonImport.checked)
364         params[2].non_imported = 1;
365
366     fieldmapper.standardRequest(
367         ['open-ils.vandelay', method],
368         {   async: true,
369             params: params,
370             /*
371             onresponse: function(r) {
372                 console.log("ONREPONSE");
373                 var rec = r.recv().content();
374                 if(e = openils.Event.parse(rec))
375                     return alert(e);
376                 console.log("got record " + rec.id());
377                 queuedRecords.push(rec);
378                 queuedRecordsMap[rec.id()] = rec;
379             },
380             */
381             oncomplete: function(r){
382                 var recs = r.recv().content();
383                 if(e = openils.Event.parse(recs[0]))
384                     return alert(e);
385                 for(var i = 0; i < recs.length; i++) {
386                     var rec = recs[i];
387                     queuedRecords.push(rec);
388                     queuedRecordsMap[rec.id()] = rec;
389                 }
390                 onload();
391             }
392         }
393     );
394 }
395
396 function vlLoadMatchUI(recId) {
397     displayGlobalDiv('vl-generic-progress');
398     var matches = queuedRecordsMap[recId].matches();
399     var records = [];
400     currentImportRecId = recId;
401     for(var i = 0; i < matches.length; i++)
402         records.push(matches[i].eg_record());
403
404     var retrieve = ['open-ils.search', 'open-ils.search.biblio.record_entry.slim.retrieve'];
405     var params = [records];
406     if(currentType == 'auth') {
407         retrieve = ['open-ils.cat', 'open-ils.cat.authority.record.retrieve'];
408         parmas = [authtoken, records, {clear_marc:1}];
409     }
410
411     fieldmapper.standardRequest(
412         retrieve,
413         {   async: true,
414             params:params,
415             oncomplete: function(r) {
416                 var recs = r.recv().content();
417                 if(e = openils.Event.parse(recs))
418                     return alert(e);
419
420                 /* ui mangling */
421                 displayGlobalDiv('vl-match-div');
422                 resetVlMatchGridLayout();
423                 currentMatchedRecords = recs;
424                 vlMatchGrid.setStructure(vlMatchGridLayout);
425
426                 // build the data store of records with match information
427                 var dataStore = bre.toStoreData(recs, null, 
428                     {virtualFields:['dest_matchpoint', 'src_matchpoint', '_id']});
429                 dataStore.identifier = '_id';
430
431                 var matchSeenMap = {};
432
433                 for(var i = 0; i < dataStore.items.length; i++) {
434                     var item = dataStore.items[i];
435                     item._id = i; // just need something unique
436                     for(var j = 0; j < matches.length; j++) {
437                         var match = matches[j];
438                         if(match.eg_record() == item.id && !matchSeenMap[match.id()]) {
439                             item.dest_matchpoint = match.field_type();
440                             var attr = getRecAttrFromMatch(queuedRecordsMap[recId], match);
441                             item.src_matchpoint = getRecAttrDefFromAttr(attr, currentType).code();
442                             matchSeenMap[match.id()] = 1;
443                             break;
444                         }
445                     }
446                 }
447
448                 // now populate the grid
449                 vlPopulateMatchGrid(vlMatchGrid, dataStore);
450             }
451         }
452     );
453 }
454
455 function vlPopulateMatchGrid(grid, data) {
456     var store = new dojo.data.ItemFileReadStore({data:data});
457     grid.setStore(store);
458     grid.update();
459 }
460
461 function showMe(id) {
462     dojo.style(dojo.byId(id), 'display', 'block');
463 }
464 function hideMe(id) {
465     dojo.style(dojo.byId(id), 'display', 'none');
466 }
467
468
469 function vlLoadMARCHtml(recId, inCat, oncomplete) {
470     dijit.byId('vl-marc-html-done-button').onClick = oncomplete;
471     displayGlobalDiv('vl-generic-progress');
472     var api;
473     var params = [recId, 1];
474
475     if(inCat) {
476         hideMe('vl-marc-html-edit-button'); // don't show marc editor button
477         dijit.byId('vl-marc-html-edit-button').onClick = function(){}
478         api = ['open-ils.search', 'open-ils.search.biblio.record.html'];
479         if(currentType == 'auth')
480             api = ['open-ils.search', 'open-ils.search.authority.to_html'];
481     } else {
482         showMe('vl-marc-html-edit-button'); // plug in the marc editor button
483         dijit.byId('vl-marc-html-edit-button').onClick = 
484             function() {vlLoadMarcEditor(currentType, recId, oncomplete);};
485         params = [authtoken, recId];
486         api = ['open-ils.vandelay', 'open-ils.vandelay.queued_bib_record.html'];
487         if(currentType == 'auth')
488             api = ['open-ils.vandelay', 'open-ils.vandelay.queued_authority_record.html'];
489     }
490
491     fieldmapper.standardRequest(
492         api, 
493         {   async: true,
494             params: params,
495             oncomplete: function(r) {
496             displayGlobalDiv('vl-marc-html-div');
497                 var html = r.recv().content();
498                 dojo.byId('vl-marc-record-html').innerHTML = html;
499             }
500         }
501     );
502 }
503
504
505 /*
506 function getRecMatchesFromAttrCode(rec, attrCode) {
507     var matches = [];
508     var attr = getRecAttrFromCode(rec, attrCode);
509     for(var j = 0; j < rec.matches().length; j++) {
510         var match = rec.matches()[j];
511         if(match.matched_attr() == attr.id()) 
512             matches.push(match);
513     }
514     return matches;
515 }
516 */
517
518 function getRecAttrFromMatch(rec, match) {
519     for(var i = 0; i < rec.attributes().length; i++) {
520         var attr = rec.attributes()[i];
521         if(attr.id() == match.matched_attr())
522             return attr;
523     }
524 }
525
526 function getRecAttrDefFromAttr(attr, type) {
527     var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
528     for(var i = 0; i < defs.length; i++) {
529         var def = defs[i];
530         if(def.id() == attr.field())
531             return def;
532     }
533 }
534
535 function getRecAttrFromCode(rec, attrCode) {
536     var defId = attrDefMap[currentType][attrCode];
537     var attrs = rec.attributes();
538     for(var i = 0; i < attrs.length; i++) {
539         var attr = attrs[i];
540         if(attr.field() == defId) 
541             return attr;
542     }
543     return null;
544 }
545
546 function vlGetViewMatches(rowIdx, item) {
547     if(item) {
548         var id = this.grid.store.getValue(item, 'id');
549         var rec = queuedRecordsMap[id];
550         if(rec.matches().length > 0)
551             return id;
552     }
553     return -1
554 }
555
556 function vlFormatViewMatches(id) {
557     if(id == -1) return '';
558     return '<a href="javascript:void(0);" onclick="vlLoadMatchUI(' + id + ');">' + this.name + '</a>';
559 }
560
561 function vlFormatViewMatchMARC(id) {
562     return '<a href="javascript:void(0);" onclick="vlLoadMARCHtml(' + id + ', false, '+
563         'function(){displayGlobalDiv(\'vl-match-div\');});">' + this.name + '</a>';
564 }
565
566 function getAttrValue(rowIdx, item) {
567     if(!item) return '';
568     var attrCode = this.field.split('.')[1];
569     var rec = queuedRecordsMap[this.grid.store.getValue(item, 'id')];
570     var attr = getRecAttrFromCode(rec, attrCode);
571     return (attr) ? attr.attr_value() : '';
572 }
573
574 function vlGetDateTimeField(rowIdx, item) {
575     if(!item) return '';
576     var value = this.grid.store.getValue(item, this.field);
577     if(!value) return '';
578     var date = dojo.date.stamp.fromISOString(value);
579     return dojo.date.locale.format(date, {selector:'date'});
580 }
581
582 function vlGetCreator(rowIdx, item) {
583     if(!item) return '';
584     var id = this.grid.store.getValue(item, 'creator');
585     if(userCache[id])
586         return userCache[id].usrname();
587     var user = fieldmapper.standardRequest(
588         ['open-ils.actor', 'open-ils.actor.user.retrieve'], [authtoken, id]);
589     if(e = openils.Event.parse(user))
590         return alert(e);
591     userCache[id] = user;
592     return user.usrname();
593 }
594
595 function vlGetViewMARC(rowIdx, item) {
596     return item && this.grid.store.getValue(item, 'id');
597 }
598
599 function vlFormatViewMARC(id) {
600     return '<a href="javascript:void(0);" onclick="vlLoadMARCHtml(' + id + ', false, '+
601         'function(){displayGlobalDiv(\'vl-queue-div\');});">' + this.name + '</a>';
602 }
603
604 function vlGetOverlayTargetSelector(rowIdx, item) {
605     if(!item) return;
606     return this.grid.store.getValue(item, '_id') + ':' + this.grid.store.getValue(item, 'id');
607 }
608
609 function vlFormatOverlayTargetSelector(val) {
610     if(!val) return '';
611     var parts = val.split(':');
612     var _id = parts[0];
613     var id = parts[1];
614     var value = '<input type="checkbox" name="vl-overlay-target-RECID" '+
615         'onclick="vlHandleOverlayTargetSelected(ID, GRIDID);" gridid="GRIDID" match="ID"/>';
616     value = value.replace(/GRIDID/g, _id);
617     value = value.replace(/RECID/g, currentImportRecId);
618     value = value.replace(/ID/g, id);
619     if(_id == currentOverlayRecordsMapGid[currentImportRecId])
620         return value.replace('/>', 'checked="checked"/>');
621     return value;
622 }
623
624
625 /**
626   * see if the user has enabled overlays for the current match set and, 
627   * if so, map the current import record to the overlay target.
628   */
629 function vlHandleOverlayTargetSelected(recId, gridId) {
630     var noneSelected = true;
631     var checkboxes = dojo.query('[name=vl-overlay-target-'+currentImportRecId+']');
632     for(var i = 0; i < checkboxes.length; i++) {
633         var checkbox = checkboxes[i];
634         var matchRecId = checkbox.getAttribute('match');
635         var gid = checkbox.getAttribute('gridid');
636         if(checkbox.checked) {
637             if(matchRecId == recId && gid == gridId) {
638                 noneSelected = false;
639                 currentOverlayRecordsMap[currentImportRecId] = matchRecId;
640                 currentOverlayRecordsMapGid[currentImportRecId] = gid;
641                 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = true;
642                 dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = 'overlay_selected';
643             } else {
644                 checkbox.checked = false;
645             }
646         }
647     }
648
649     if(noneSelected) {
650         delete currentOverlayRecordsMap[currentImportRecId];
651         delete currentOverlayRecordsMapGid[currentImportRecId];
652         dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = false;
653         dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = '';
654     }
655 }
656
657 var valLastQueueType = null;
658 var vlQueueGridLayout = null;
659 function buildRecordGrid(type) {
660     displayGlobalDiv('vl-queue-div');
661
662     if(type == 'bib') {
663         openils.Util.show('vl-bib-queue-grid-wrapper');
664         openils.Util.hide('vl-auth-queue-grid-wrapper');
665         vlQueueGrid = vlBibQueueGrid;
666     } else {
667         openils.Util.show('vl-auth-queue-grid-wrapper');
668         openils.Util.hide('vl-bib-queue-grid-wrapper');
669         vlQueueGrid = vlAuthQueueGrid;
670     }
671
672
673     if(valLastQueueType != type) {
674         valLastQueueType = type;
675         vlQueueGridLayout = vlQueueGrid.attr('structure');
676         var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
677         attrDefMap[type] = {};
678         for(var i = 0; i < defs.length; i++) {
679             var def = defs[i]
680             attrDefMap[type][def.code()] = def.id();
681             var col = {
682                 name:def.description(), 
683                 field:'attr.' + def.code(),
684                 get: getAttrValue,
685                 selectableColumn:true
686             };
687             vlQueueGridLayout[0].cells[0].push(col);
688         }
689     }
690
691     dojo.forEach(vlQueueGridLayout[0].cells[0], 
692         function(cell) { 
693             if(cell.field.match(/^\+/)) 
694                 cell.nonSelectable=true;
695         }
696     );
697
698     var storeData;
699     if(type == 'bib')
700         storeData = vqbr.toStoreData(queuedRecords);
701     else
702         storeData = vqar.toStoreData(queuedRecords);
703
704     var store = new dojo.data.ItemFileReadStore({data:storeData});
705     vlQueueGrid.setStore(store);
706
707     if(vlQueueGridColumePicker[type]) {
708         vlQueueGrid.update();
709     } else {
710
711         vlQueueGridColumePicker[type] =
712             new openils.widget.GridColumnPicker(
713                 authtoken, 'vandelay.queue.'+type, vlQueueGrid, vlQueueGridLayout);
714         vlQueueGridColumePicker[type].load();
715     }
716 }
717
718 function vlQueueGridPrevPage() {
719     var page = parseInt(vlQueueDisplayPage.getValue());
720     if(page < 2) return;
721     vlQueueDisplayPage.setValue(page - 1);
722     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
723 }
724
725 function vlQueueGridNextPage() {
726     vlQueueDisplayPage.setValue(parseInt(vlQueueDisplayPage.getValue())+1);
727     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
728 }
729
730 function vlDeleteQueue(type, queueId, onload) {
731     fieldmapper.standardRequest(
732         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.delete'],
733         {   async: true,
734             params: [authtoken, queueId],
735             oncomplete: function(r) {
736                 var resp = r.recv().content();
737                 if(e = openils.Event.parse(resp))
738                     return alert(e);
739                 onload();
740             }
741         }
742     );
743 }
744
745
746 function vlQueueGridDrawSelectBox(rowIdx, item) {
747     return item &&  this.grid.store.getValue(item, 'id');
748 }
749
750 function vlQueueGridFormatSelectBox(id) {
751     var domId = 'vl-record-list-selected-' + id;
752     if (id) { selectableGridRecords[domId] = id; }
753     return "<div><input type='checkbox' id='"+domId+"'/></div>";
754 }
755
756 function vlSelectAllQueueGridRecords() {
757     for(var id in selectableGridRecords) 
758         dojo.byId(id).checked = true;
759 }
760 function vlSelectNoQueueGridRecords() {
761     for(var id in selectableGridRecords) 
762         dojo.byId(id).checked = false;
763 }
764 function vlToggleQueueGridSelect() {
765     if(dojo.byId('vl-queue-grid-row-selector').checked)
766         vlSelectAllQueueGridRecords();
767     else
768         vlSelectNoQueueGridRecords();
769 }
770
771 var handleRetrieveRecords = function() {
772     buildRecordGrid(currentType);
773     vlFetchQueueSummary(currentQueueId, currentType, 
774         function(summary) {
775             dojo.byId('vl-queue-summary-name').innerHTML = summary.queue.name();
776             dojo.byId('vl-queue-summary-total-count').innerHTML = summary.total +'';
777             dojo.byId('vl-queue-summary-import-count').innerHTML = summary.imported + '';
778         }
779     );
780 }
781
782 function vlFetchQueueSummary(qId, type, onload) {
783     fieldmapper.standardRequest(
784         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.summary.retrieve'],
785         {   async: true,
786             params: [authtoken, qId],
787             oncomplete : function(r) {
788                 var summary = r.recv().content();
789                 if(e = openils.Event.parse(summary))
790                     return alert(e);
791                 return onload(summary);
792             }
793         }
794     );
795 }
796     
797
798 function vlImportSelectedRecords() {
799     displayGlobalDiv('vl-generic-progress-with-total');
800     var records = [];
801
802     for(var id in selectableGridRecords) {
803         if(dojo.byId(id).checked) {
804             var recId = selectableGridRecords[id];
805             var rec = queuedRecordsMap[recId];
806             if(!rec.import_time()) 
807                 records.push(recId);
808         }
809     }
810
811     fieldmapper.standardRequest(
812         ['open-ils.vandelay', 'open-ils.vandelay.'+currentType+'_record.list.import'],
813         {   async: true,
814             params: [authtoken, records, {overlay_map:currentOverlayRecordsMap}],
815             onresponse: function(r) {
816                 var resp = r.recv().content();
817                 if(e = openils.Event.parse(resp))
818                     return alert(e);
819                 if(resp.complete) {
820                     return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
821                 } else {
822                     vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
823                 }
824             }, 
825         }
826     );
827 }
828
829 function vlImportAllRecords() {
830     vlImportRecordQueue(currentType, currentQueueId, false,
831         function(){displayGlobalDiv('vl-queue-div');});
832 }
833
834 function vlImportRecordQueue(type, queueId, noMatchOnly, onload) {
835     displayGlobalDiv('vl-generic-progress-with-total');
836     var method = 'open-ils.vandelay.bib_queue.import';
837     if(noMatchOnly)
838         method = method.replace('import', 'nomatch.import');
839     if(type == 'auth')
840         method = method.replace('bib', 'auth');
841
842     var options = {};
843     if(vlUploadQueueAutoOverlayExact.checked) {
844         options.auto_overlay_exact = true;
845         vlUploadQueueAutoOverlayExact.checked = false;
846     }
847
848     if(vlUploadQueueAutoOverlay1Match.checked) {
849         options.auto_overlay_1match = true;
850         vlUploadQueueAutoOverlay1Match.checked = false;
851     }
852
853     
854     var profile = vlUploadMergeProfile.attr('value');
855     if(profile != null && profile != '') {
856         options.merge_profile = profile;
857     }
858
859     fieldmapper.standardRequest(
860         ['open-ils.vandelay', method],
861         {   async: true,
862             params: [authtoken, queueId, options],
863             onresponse: function(r) {
864                 var resp = r.recv().content();
865                 if(e = openils.Event.parse(resp))
866                     return alert(e);
867                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
868             },
869             oncomplete: function() {onload();}
870         }
871     );
872 }
873
874
875 function vlImportHoldings(queueId, importProfile, onload) {
876     displayGlobalDiv('vl-generic-progress-with-total');
877     fieldmapper.standardRequest(
878         ['open-ils.vandelay', 'open-ils.vandelay.bib_record.queue.asset.import'],
879         {   async: true,
880             params: [authtoken, importProfile, queueId],
881             onresponse: function(r) {
882                 var resp = openils.Util.readResponse(r);
883                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
884             },
885             oncomplete: function() {onload();}
886         }
887     );
888 }
889
890 /**
891   * Create queue, upload MARC, process spool, load the newly created queue 
892   */
893 function batchUpload() {
894     var queueName = dijit.byId('vl-queue-name').getValue();
895     currentType = dijit.byId('vl-record-type').getValue();
896
897     var handleProcessSpool = function() {
898         if(vlUploadQueueAutoImport.checked || vlUploadQueueAutoOverlayExact.checked || vlUploadQueueAutoOverlay1Match.checked) {
899
900             vlImportRecordQueue(
901                 currentType, 
902                 currentQueueId, 
903                 vlUploadQueueAutoImport.checked,  
904                 function() {
905                     if(vlUploadQueueHoldingsImport.checked) {
906                         vlImportHoldings(
907                             currentQueueId, 
908                             vlUploadQueueHoldingsImportProfile.attr('value'), 
909                             function() { 
910                                 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
911                             }
912                         );
913                     } else {
914                         retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
915                     }
916                 }
917             );
918         } else {
919             retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
920         }
921     }
922
923     var handleUploadMARC = function(key) {
924         dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');
925         processSpool(key, currentQueueId, currentType, handleProcessSpool);
926     };
927
928     var handleCreateQueue = function(queue) {
929         currentQueueId = queue.id();
930         uploadMARC(handleUploadMARC);
931     };
932     
933     if(vlUploadQueueSelector.getValue() && !queueName) {
934         currentQueueId = vlUploadQueueSelector.getValue();
935         uploadMARC(handleUploadMARC);
936     } else {
937         createQueue(queueName, currentType, handleCreateQueue, vlUploadQueueHoldingsImportProfile.attr('value'));
938     }
939 }
940
941
942 function vlFleshQueueSelect(selector, type) {
943     var data = (type == 'bib') ? vbq.toStoreData(allUserBibQueues) : vaq.toStoreData(allUserAuthQueues);
944     selector.store = new dojo.data.ItemFileReadStore({data:data});
945     selector.setValue(null);
946     selector.setDisplayedValue('');
947     if(data[0])
948         selector.setValue(data[0].id());
949 }
950
951 function vlShowUploadForm() {
952     displayGlobalDiv('vl-marc-upload-div');
953     vlFleshQueueSelect(vlUploadQueueSelector, vlUploadRecordType.getValue());
954     vlUploadSourceSelector.store = 
955         new dojo.data.ItemFileReadStore({data:cbs.toStoreData(vlBibSources, 'source')});
956     vlUploadSourceSelector.setValue(vlBibSources[0].id());
957     vlUploadQueueHoldingsImportProfile.store = 
958         new dojo.data.ItemFileReadStore({data:viiad.toStoreData(importItemDefs)});
959     vlUploadQueueHoldingsImportProfile.attr('disabled', true);
960     dojo.connect(vlUploadQueueHoldingsImport, 'onChange',
961         function(val) {
962             if(val)
963                 vlUploadQueueHoldingsImportProfile.attr('disabled', false);
964             else
965                 vlUploadQueueHoldingsImportProfile.attr('disabled', true);
966         }
967     );
968 }
969
970 function vlShowQueueSelect() {
971     displayGlobalDiv('vl-queue-select-div');
972     vlFleshQueueSelect(vlQueueSelectQueueList, vlQueueSelectType.getValue());
973 }
974
975 function vlFetchQueueFromForm() {
976     currentType = vlQueueSelectType.getValue();
977     currentQueueId = vlQueueSelectQueueList.getValue();
978     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
979 }
980
981 function vlOpenMarcEditWindow(rec, postReloadHTMLHandler) {
982     /*
983         To run in Firefox directly, must set signed.applets.codebase_principal_support
984         to true in about:config
985     */
986     netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
987     win = window.open('/xul/server/cat/marcedit.xul'); // XXX version?
988
989     function onsave(r) {
990         // after the record is saved, reload the HTML display
991         var stat = r.recv().content();
992         if(e = openils.Event.parse(stat))
993             return alert(e);
994         alert(dojo.byId('vl-marc-edit-complete-label').innerHTML);
995         win.close();
996         vlLoadMARCHtml(rec.id(), false, postReloadHTMLHandler);
997     }
998
999     win.xulG = {
1000         record : {marc : rec.marc()},
1001         save : {
1002             label: dojo.byId('vl-marc-edit-save-label').innerHTML,
1003             func: function(xmlString) {
1004                 var method = 'open-ils.permacrud.update.' + rec.classname;
1005                 rec.marc(xmlString);
1006                 fieldmapper.standardRequest(
1007                     ['open-ils.permacrud', method],
1008                     {   async: true,
1009                         params: [authtoken, rec],
1010                         oncomplete: onsave
1011                     }
1012                 );
1013             },
1014         }
1015     };
1016 }
1017
1018 function vlLoadMarcEditor(type, recId, postReloadHTMLHandler) {
1019     var method = 'open-ils.permacrud.search.vqbr';
1020     if(currentType != 'bib')
1021         method = method.replace(/vqbr/,'vqar');
1022
1023     fieldmapper.standardRequest(
1024         ['open-ils.permacrud', method],
1025         {   async: true, 
1026             params: [authtoken, {id : recId}],
1027             oncomplete: function(r) {
1028                 var rec = r.recv().content();
1029                 if(e = openils.Event.parse(rec))
1030                     return alert(e);
1031                 vlOpenMarcEditWindow(rec, postReloadHTMLHandler);
1032             }
1033         }
1034     );
1035 }
1036
1037
1038
1039 //------------------------------------------------------------
1040 // attribute editors
1041
1042 // attribute-editor global variables
1043
1044 var ATTR_EDITOR_IN_UPDATE_MODE = false; // true on 'edit', false on 'create'
1045 var ATTR_EDIT_ID = null;                // id of current 'edit' attribute
1046 var ATTR_EDIT_GROUP = 'bib';            // bib-attrs or auth-attrs
1047
1048 function vlAttrEditorInit() {
1049     // set up tooltips on the edit form
1050     connectTooltip('attr-editor-tags'); 
1051     connectTooltip('attr-editor-subfields'); 
1052 }
1053
1054 function vlShowAttrEditor() {
1055     displayGlobalDiv('vl-attr-editor-div');
1056     loadAttrEditorGrid();
1057     idHide('vl-generic-progress');
1058 }
1059
1060 function setAttrEditorGroup(groupName) {
1061     // put us into 'bib'-attr or 'auth'-attr mode.
1062     if (ATTR_EDIT_GROUP != groupName) {
1063         ATTR_EDIT_GROUP = groupName;
1064         loadAttrEditorGrid();
1065     }
1066 }
1067
1068 function onAttrEditorOpen() {
1069     // the "bars" have the create/update/cancel/etc. buttons.
1070     var create_bar = document.getElementById('attr-editor-create-bar');
1071     var update_bar = document.getElementById('attr-editor-update-bar');
1072     if (ATTR_EDITOR_IN_UPDATE_MODE) {
1073         update_bar.style.display='table-row';
1074         create_bar.style.display='none';
1075         // hide the dropdown-button
1076         idStyle('vl-create-attr-editor-button', 'visibility', 'hidden');
1077     } else {
1078         dijit.byId('attr-editor-dialog').reset();
1079         create_bar.style.display='table-row';
1080         update_bar.style.display='none';
1081     }
1082 }
1083
1084 function onAttrEditorClose() {
1085     // reset the form to a "create" form. (We may have borrowed it for editing.)
1086     ATTR_EDITOR_IN_UPDATE_MODE = false;
1087     // show the dropdown-button
1088     idStyle('vl-create-attr-editor-button', 'visibility', 'visible');
1089 }
1090
1091 function loadAttrEditorGrid() {
1092     var _data = (ATTR_EDIT_GROUP == 'auth') ? 
1093         vqarad.toStoreData(authAttrDefs) : vqbrad.toStoreData(bibAttrDefs) ;
1094
1095     var store = new dojo.data.ItemFileReadStore({data:_data});
1096     attrEditorGrid.setStore(store);
1097     dojo.connect(attrEditorGrid, 'onRowDblClick', onAttrEditorClick);
1098     attrEditorGrid.update();
1099 }
1100
1101 function attrGridGetTag(n, item) {
1102     // grid helper: return the tags from the row's xpath column.
1103     return item && xpathParser.parse(this.grid.store.getValue(item, 'xpath')).tags;
1104 }
1105
1106 function attrGridGetSubfield(n, item) {
1107     // grid helper: return the subfields from the row's xpath column.
1108     return item && xpathParser.parse(this.grid.store.getValue(item, 'xpath')).subfields;
1109 }
1110
1111 function onAttrEditorClick() {
1112     var row = this.getItem(this.focus.rowIndex);
1113     ATTR_EDIT_ID = this.store.getValue(row, 'id');
1114     ATTR_EDITOR_IN_UPDATE_MODE = true;
1115
1116     // populate the popup editor.
1117     dijit.byId('attr-editor-code').attr('value', this.store.getValue(row, 'code'));
1118     dijit.byId('attr-editor-description').attr('value', this.store.getValue(row, 'description'));
1119     var parsed_xpath = xpathParser.parse(this.store.getValue(row, 'xpath'));
1120     dijit.byId('attr-editor-tags').attr('value', parsed_xpath.tags);
1121     dijit.byId('attr-editor-subfields').attr('value', parsed_xpath.subfields);
1122     dijit.byId('attr-editor-identifier').attr('value', this.store.getValue(row, 'ident'));
1123     dijit.byId('attr-editor-xpath').attr('value', this.store.getValue(row, 'xpath'));
1124     dijit.byId('attr-editor-remove').attr('value', this.store.getValue(row, 'remove'));
1125
1126     // set up UI for editing
1127     dojo.byId('vl-create-attr-editor-button').click();
1128 }
1129
1130 function vlSaveAttrDefinition(data) {
1131     idHide('vl-attr-editor-div');
1132     idShow('vl-generic-progress');
1133
1134     data.id = ATTR_EDIT_ID;
1135
1136     // this ought to honour custom xpaths, but overwrite xpaths
1137     // derived from tags/subfields.
1138     if (data.xpath == '' || looksLikeDerivedXpath(data.xpath)) {
1139         var _xpath = tagAndSubFieldsToXpath(data.tag, data.subfield);
1140         data.xpath = _xpath;
1141     }
1142
1143     // build up our permacrud params. Key variables here are
1144     // "create or update" and "bib or auth".
1145
1146     var isAuth   = (ATTR_EDIT_GROUP == 'auth');
1147     var isCreate = (ATTR_EDIT_ID == null);
1148     var rad      = isAuth ? new vqarad() : new vqbrad() ;
1149     var method   = 'open-ils.permacrud' + (isCreate ? '.create.' : '.update.') 
1150         + (isAuth ? 'vqarad' : 'vqbrad');
1151     var _data    = rad.fromStoreItem(data);
1152
1153     _data.ischanged(1);
1154
1155     fieldmapper.standardRequest(
1156         ['open-ils.permacrud', method],
1157         {   async: true,
1158             params: [authtoken, _data ],
1159             onresponse: function(r) { },
1160             oncomplete: function(r) {
1161                 attrEditorFetchAttrDefs(vlShowAttrEditor);
1162                 ATTR_EDIT_ID = null;
1163             },
1164             onerror: function(r) {
1165                 alert('vlSaveAttrDefinition comms error: ' + r);
1166             }
1167         }
1168     );
1169 }
1170
1171 function attrEditorFetchAttrDefs(callback) {
1172     var fn = (ATTR_EDIT_GROUP == 'auth') ? vlFetchAuthAttrDefs : vlFetchBibAttrDefs;
1173     return fn(callback);
1174 }
1175
1176 function vlAttrDelete() {
1177     idHide('vl-attr-editor-div');
1178     idShow('vl-generic-progress');
1179
1180     var isAuth = (ATTR_EDIT_GROUP == 'auth');
1181     var method = 'open-ils.permacrud.delete.' + (isAuth ? 'vqarad' : 'vqbrad');
1182     var rad    = isAuth ? new vqarad() : new vqbrad() ;
1183     fieldmapper.standardRequest(
1184         ['open-ils.permacrud', method],
1185         {   async: true,
1186             params: [authtoken, rad.fromHash({ id : ATTR_EDIT_ID }), ],
1187             oncomplete: function() {
1188                 dijit.byId('attr-editor-dialog').onCancel(); // close the dialog
1189                 attrEditorFetchAttrDefs(vlShowAttrEditor);
1190                 ATTR_EDIT_ID = null;
1191             },
1192             onerror: function(r) {
1193                 alert('vlAttrDelete comms error: ' + r);
1194             }
1195         }
1196     );
1197 }
1198
1199 // ------------------------------------------------------------
1200 // utilities for attribute editors
1201
1202 // dom utilities (maybe dojo does these, and these should be replaced)
1203
1204 function idStyle(obId, k, v)    { document.getElementById(obId).style[k] = v;   }
1205 function idShow(obId)           { idStyle(obId, 'display', 'block');            }
1206 function idHide(obId)           { idStyle(obId, 'display' , 'none');            }
1207
1208 function connectTooltip(fieldId) {
1209     // Given an element id, look up a tooltip element in the doc (same
1210     // id with a '-tip' suffix) and associate the two. Maybe dojo has
1211     // a better way to do this?
1212     var fld = dojo.byId(fieldId);
1213     var tip = dojo.byId(fieldId + '-tip');
1214     dojo.connect(fld, 'onfocus', function(evt) {
1215                      dijit.showTooltip(tip.innerHTML, fld, ['below', 'after']); });
1216     dojo.connect(fld, 'onblur', function(evt) { dijit.hideTooltip(fld); });
1217 }
1218
1219 // xpath utilities
1220
1221 var xpathParser = new openils.MarcXPathParser();
1222
1223 function tagAndSubFieldsToXpath(tags, subfields) {
1224     // given tags, and subfields, build up an XPath.
1225     try {
1226         var parts = {
1227             'tags':tags.match(/[\d]+/g), 
1228             'subfields':subfields.match(/[a-zA-z]/g) };
1229         return xpathParser.compile(parts);
1230     } catch (err) {
1231         return {'parts':null, 'tags':null, 'error':err};
1232     }
1233 }
1234
1235 function looksLikeDerivedXpath(path) {
1236     // Does this path look like it was derived from tags and subfields?
1237     var parsed = xpathParser.parse(path);
1238     if (parsed.tags == null) 
1239         return false;
1240     var compiled = xpathParser.compile(parsed);
1241     return (path == compiled);
1242 }
1243
1244 // amazing xpath-util unit-tests
1245 if (!looksLikeDerivedXpath('//*[@tag="901"]/*[@code="c"]'))     alert('vandelay xpath-utility error');
1246 if ( looksLikeDerivedXpath('ba-boo-ba-boo!'))                   alert('vandelay xpath-utility error');
1247
1248
1249
1250 var profileContextOrg
1251 function vlShowProfileEditor() {
1252     displayGlobalDiv('vl-profile-editor-div');
1253     buildProfileGrid();
1254
1255     var connect = function() {
1256         dojo.connect(profileContextOrgSelector, 'onChange',
1257             function() {
1258                 profileContextOrg = this.attr('value');
1259                 pGrid.resetStore();
1260                 buildGrid();
1261             }
1262         );
1263     };
1264
1265     new openils.User().buildPermOrgSelector(
1266         '"ADMIN_MERGE_PROFILE', profileContextOrgSelector, null, connect);
1267 }
1268
1269 function buildProfileGrid() {
1270
1271     if(profileContextOrg == null)
1272         profileContextOrg = openils.User.user.ws_ou();
1273
1274     pGrid.loadAll( 
1275         {order_by : {vmp : 'name'}}, 
1276         {owner : fieldmapper.aou.fullPath(profileContextOrg, true)}
1277     );
1278 }
1279
1280
1281