97be36bf03256aab9e3592186461e0e4c52366e1
[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     'vl-item-attr-editor-div',
61     'vl-import-error-div'
62 ];
63
64 var authtoken;
65 var VANDELAY_URL = '/vandelay-upload';
66 var bibAttrDefs = [];
67 var authAttrDefs = [];
68 var queuedRecords = [];
69 var queuedRecordsMap = {};
70 var bibAttrsFetched = false;
71 var authAttrsFetched = false;
72 var attrDefMap = {}; // maps attr def code names to attr def ids
73 var currentType;
74 var currentQueueId = null;
75 var userCache = {};
76 var currentMatchedRecords; // set of loaded matched bib records
77 var currentOverlayRecordsMap; // map of import record to overlay record
78 var currentOverlayRecordsMapGid; // map of import record to overlay record grid id
79 var currentImportRecId; // when analyzing matches, this is the current import record
80 var userBibQueues = []; // only non-complete queues
81 var userAuthQueues = []; // only non-complete queues
82 var allUserBibQueues;
83 var allUserAuthQueues;
84 var selectableGridRecords;
85 var cgi = new openils.CGI();
86 var vlQueueGridColumePicker = {};
87 var vlBibSources = [];
88 var importItemDefs = [];
89 var matchSets = {};
90 var mergeProfiles = [];
91
92 /**
93   * Grab initial data
94   */
95 function vlInit() {
96     authtoken = openils.User.authtoken;
97     var initNeeded = 7; // how many async responses do we need before we're init'd 
98     var initCount = 0; // how many async reponses we've received
99
100     openils.Util.registerEnterHandler(
101         vlQueueDisplayPage.domNode, function(){retrieveQueuedRecords();});
102     openils.Util.addCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
103
104     function checkInitDone() {
105         initCount++;
106         if(initCount == initNeeded)
107             runStartupCommands();
108     }
109
110     mergeProfiles = new openils.PermaCrud().retrieveAll('vmp');
111     vlUploadMergeProfile.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(mergeProfiles)});
112     vlUploadMergeProfile.labelAttr = 'name';
113     vlUploadMergeProfile.searchAttr = 'name';
114     vlUploadMergeProfile.startup();
115
116     vlUploadMergeProfile2.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(mergeProfiles)});
117     vlUploadMergeProfile2.labelAttr = 'name';
118     vlUploadMergeProfile2.searchAttr = 'name';
119     vlUploadMergeProfile2.startup();
120
121
122     // Fetch the bib and authority attribute definitions 
123     vlFetchBibAttrDefs(function () { checkInitDone(); });
124     vlFetchAuthAttrDefs(function () { checkInitDone(); });
125
126     vlRetrieveQueueList('bib', null, 
127         function(list) {
128             allUserBibQueues = list;
129             for(var i = 0; i < allUserBibQueues.length; i++) {
130                 if(allUserBibQueues[i].complete() == 'f')
131                     userBibQueues.push(allUserBibQueues[i]);
132             }
133             checkInitDone();
134         }
135     );
136
137     vlRetrieveQueueList('auth', null, 
138         function(list) {
139             allUserAuthQueues = list;
140             for(var i = 0; i < allUserAuthQueues.length; i++) {
141                 if(allUserAuthQueues[i].complete() == 'f')
142                     userAuthQueues.push(allUserAuthQueues[i]);
143             }
144             checkInitDone();
145         }
146     );
147
148     fieldmapper.standardRequest(
149         ['open-ils.permacrud', 'open-ils.permacrud.search.cbs.atomic'],
150         {   async: true,
151             params: [authtoken, {id:{"!=":null}}, {order_by:{cbs:'id'}}],
152             oncomplete : function(r) {
153                 vlBibSources = openils.Util.readResponse(r, false, true);
154                 checkInitDone();
155             }
156         }
157     );
158
159     var owner = fieldmapper.aou.orgNodeTrail(fieldmapper.aou.findOrgUnit(new openils.User().user.ws_ou()));
160     new openils.PermaCrud().search('viiad', 
161         {owner: owner.map(function(org) { return org.id(); })},
162         {   async: true,
163             oncomplete: function(r) {
164                 importItemDefs = openils.Util.readResponse(r);
165                 checkInitDone();
166             }
167         }
168     );
169
170     new openils.PermaCrud().search('vms',
171         {owner: owner.map(function(org) { return org.id(); })},
172         {   async: true,
173             oncomplete: function(r) {
174                 var sets = openils.Util.readResponse(r);
175                 dojo.forEach(sets, 
176                     function(set) {
177                         if(!matchSets[set.mtype()])
178                             matchSets[set.mtype()] = [];
179                         matchSets[set.mtype()].push(set);
180                     }
181                 );
182                 checkInitDone();
183             }
184         }
185     );
186
187     vlAttrEditorInit();
188     vlExportInit();
189 }
190
191
192 openils.Util.addOnLoad(vlInit);
193
194
195 // fetch the bib and authority attribute definitions
196
197 function vlFetchBibAttrDefs(postcomplete) {
198     bibAttrDefs = [];
199     fieldmapper.standardRequest(
200         ['open-ils.permacrud', 'open-ils.permacrud.search.vqbrad'],
201         {   async: true,
202             params: [authtoken, {id:{'!=':null}}],
203             onresponse: function(r) {
204                 var def = r.recv().content(); 
205                 if(e = openils.Event.parse(def[0])) 
206                     return alert(e);
207                 bibAttrDefs.push(def);
208             },
209             oncomplete: function() {
210                 bibAttrDefs = bibAttrDefs.sort(
211                     function(a, b) {
212                         if(a.id() > b.id()) return 1;
213                         if(a.id() < b.id()) return -1;
214                         return 0;
215                     }
216                 );
217                 postcomplete();
218             }
219         }
220     );
221 }
222
223 function vlFetchAuthAttrDefs(postcomplete) {
224     authAttrDefs = [];
225     fieldmapper.standardRequest(
226         ['open-ils.permacrud', 'open-ils.permacrud.search.vqarad'],
227         {   async: true,
228             params: [authtoken, {id:{'!=':null}}],
229             onresponse: function(r) {
230                 var def = r.recv().content(); 
231                 if(e = openils.Event.parse(def[0])) 
232                     return alert(e);
233                 authAttrDefs.push(def);
234             },
235             oncomplete: function() {
236                 authAttrDefs = authAttrDefs.sort(
237                     function(a, b) {
238                         if(a.id() > b.id()) return 1;
239                         if(a.id() < b.id()) return -1;
240                         return 0;
241                     }
242                 );
243                 postcomplete();
244             }
245         }
246     );
247 }
248
249 function vlRetrieveQueueList(type, filter, onload) {
250     type = (type == 'bib') ? type : 'authority';
251     fieldmapper.standardRequest(
252         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.owner.retrieve.atomic'],
253         {   async: true,
254             params: [authtoken, null, filter],
255             oncomplete: function(r) {
256                 var list = r.recv().content();
257                 if(e = openils.Event.parse(list[0]))
258                     return alert(e);
259                 onload(list);
260             }
261         }
262     );
263
264 }
265
266 function displayGlobalDiv(id) {
267     for(var i = 0; i < globalDivs.length; i++) {
268         try {
269             dojo.style(dojo.byId(globalDivs[i]), 'display', 'none');
270         } catch(e) {
271             alert('please define div ' + globalDivs[i]);
272         }
273     }
274     dojo.style(dojo.byId(id),'display','block');
275
276     openils.Util.removeCSSClass(dojo.byId('vl-menu-marc-export'), 'toolbar_selected');
277     openils.Util.removeCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
278     openils.Util.removeCSSClass(dojo.byId('vl-menu-queue-select'), 'toolbar_selected');
279     openils.Util.removeCSSClass(dojo.byId('vl-menu-attr-editor'), 'toolbar_selected');
280     openils.Util.removeCSSClass(dojo.byId('vl-menu-profile-editor'), 'toolbar_selected');
281     openils.Util.removeCSSClass(dojo.byId('vl-menu-match-set-editor'), 'toolbar_selected');
282
283     if(dojo.byId('vl-match-set-iframe'))
284         dojo.byId('vl-match-set-editor-div').removeChild(dojo.byId('vl-match-set-iframe'));
285
286     switch(id) {
287         case 'vl-marc-export-div':
288             openils.Util.addCSSClass(dojo.byId('vl-menu-marc-export'), 'toolbar_selected');
289             break;
290         case 'vl-marc-upload-div':
291             openils.Util.addCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
292             break;
293         case 'vl-queue-select-div':
294             openils.Util.addCSSClass(dojo.byId('vl-menu-queue-select'), 'toolbar_selected');
295             break;
296         case 'vl-attr-editor-div':
297             openils.Util.addCSSClass(dojo.byId('vl-menu-attr-editor'), 'toolbar_selected');
298             break;
299         case 'vl-profile-editor-div':
300             openils.Util.addCSSClass(dojo.byId('vl-menu-profile-editor'), 'toolbar_selected');
301             break;
302         case 'vl-item-attr-editor-div':
303             openils.Util.addCSSClass(dojo.byId('vl-menu-import-item-attr-editor'), 'toolbar_selected');
304             break;
305         case 'vl-match-set-editor-div':
306             openils.Util.addCSSClass(dojo.byId('vl-menu-match-set-editor'), 'toolbar_selected');
307             break;
308     }
309 }
310
311 function runStartupCommands() {
312     currentQueueId = cgi.param('qid');
313     currentType = cgi.param('qtype');
314     dojo.style('vl-nav-bar', 'visibility', 'visible');
315     if(currentQueueId)
316         return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
317     vlShowUploadForm();
318 }
319
320 /**
321   * asynchronously upload a file of MARC records
322   */
323 function uploadMARC(onload){
324     dojo.byId('vl-upload-status-count').innerHTML = '0';
325     dojo.byId('vl-ses-input').value = authtoken;
326     displayGlobalDiv('vl-marc-upload-status-div');
327     dojo.io.iframe.send({
328         url: VANDELAY_URL,
329         method: "post",
330         handleAs: "html",
331         form: dojo.byId('vl-marc-upload-form'),
332         handle: function(data,ioArgs){
333             var content = data.documentElement.textContent;
334             onload(content);
335         }
336     });
337 }       
338
339 /**
340   * Creates a new vandelay queue
341   */
342 function createQueue(queueName, type, onload, importDefId, matchSet) {
343     var name = (type=='bib') ? 'bib' : 'authority';
344     var method = 'open-ils.vandelay.'+ name +'_queue.create'
345     fieldmapper.standardRequest(
346         ['open-ils.vandelay', method],
347         {   async: true,
348             params: [authtoken, queueName, null, name, matchSet, importDefId],
349             oncomplete : function(r) {
350                 var queue = r.recv().content();
351                 if(e = openils.Event.parse(queue)) 
352                     return alert(e);
353                 onload(queue);
354             }
355         }
356     );
357 }
358
359 /**
360   * Tells vandelay to pull a batch of records from the cache and explode them
361   * out into the vandelay tables
362   */
363 function processSpool(key, queueId, type, onload) {
364     fieldmapper.standardRequest(
365         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'.process_spool'],
366         {   async: true,
367             params: [authtoken, key, queueId],
368             onresponse : function(r) {
369                 var resp = r.recv().content();
370                 if(e = openils.Event.parse(resp)) 
371                     return alert(e);
372                 dojo.byId('vl-upload-status-count').innerHTML = resp;
373             },
374             oncomplete : function(r) {onload();}
375         }
376     );
377 }
378
379 function vlExportInit() {
380
381     // queue export
382     var qsel = dojo.byId('vl-queue-export-options');
383     qsel.onchange = function(newVal) {
384         var value = qsel.options[qsel.selectedIndex].value;
385         qsel.selectedIndex = 0;
386         if(!value) return;
387         if(!confirm('Export as "' + value + '"?')) return; // TODO: i18n
388         retrieveQueuedRecords(
389             currentType, 
390             currentQueueId, 
391             function(r) { 
392                 exportHandler(value, r);
393                 displayGlobalDiv('vl-queue-div');
394             },
395             value
396         );
397     }
398
399     // item export
400     var isel = dojo.byId('vl-item-export-options');
401     isel.onchange = function(newVal) {
402         var value = isel.options[isel.selectedIndex].value;
403         isel.selectedIndex = 0;
404         if(!value) return;
405         if(!confirm('Export as "' + value + '"?')) return; // TODO: i18n
406
407         displayGlobalDiv('vl-generic-progress');
408         var method = 'open-ils.vandelay.import_item.queue.export.' + value + '.atomic';
409
410         fieldmapper.standardRequest(
411             ['open-ils.vandelay', method],
412             {
413                 params : [
414                     authtoken, 
415                     currentQueueId, 
416                     {with_import_error: (vlImportItemsShowErrors.checked) ? 1 : null}
417                 ],
418                 async : true,
419                 oncomplete : function(r) {exportHandler(value, r)}
420             }
421         );
422     }
423 }
424
425 function exportHandler(type, response) {
426     displayGlobalDiv('vl-import-error-div');
427     try {
428         var content = openils.Util.readResponse(response);
429         if (type=='email') {
430             if (content==1) { alert('Email sent.'); return; }
431             throw(content);
432         }
433         /* handle .atomic versus non-atomic method calls */
434         content = content.constructor == Array
435             ? content[0].template_output().data()
436             : content.template_output().data();
437         switch(type) {
438             case 'print':
439                 openils.Util.printHtmlString(content);
440             break;
441             case 'csv':
442                 //content = content.replace(/\\t/g,'\t'); // if we really wanted to do .tsv instead
443                 openils.XUL.contentToFileSaveDialog(content);
444             break;
445             default:
446                 alert('response = ' + response + '\tcontent:\n' + content);
447         }
448     } catch(E) {
449         alert('Error exporting data: ' + E);
450     }
451 }
452
453 function retrieveQueuedRecords(type, queueId, onload, doExport) {
454     displayGlobalDiv('vl-generic-progress');
455     queuedRecords = [];
456     queuedRecordsMap = {};
457     currentOverlayRecordsMap = {};
458     currentOverlayRecordsMapGid = {};
459     selectableGridRecords = {};
460
461     if(!type) type = currentType;
462     if(!queueId) queueId = currentQueueId;
463     if(!onload) onload = handleRetrieveRecords;
464
465     var method = 'open-ils.vandelay.'+type+'_queue.records.retrieve';
466
467     if(doExport) method += '.export.' + doExport;
468     if(vlQueueGridShowMatches.checked)
469         method = method.replace('records', 'records.matches');
470
471     method += '.atomic';
472
473     var sel = dojo.byId('vl-queue-display-limit-selector');
474     var limit = parseInt(sel.options[sel.selectedIndex].value);
475     var offset = limit * parseInt(vlQueueDisplayPage.attr('value')-1);
476
477     var params =  [authtoken, queueId, {clear_marc: 1, offset: offset, limit: limit, flesh_import_items:1}];
478     if(vlQueueGridShowNonImport.checked)
479         params[2].non_imported = 1;
480
481     if(vlQueueGridShowImportErrors.checked)
482         params[2].with_import_error = 1;
483
484     fieldmapper.standardRequest(
485         ['open-ils.vandelay', method],
486         {   async: true,
487             params: params,
488             oncomplete: function(r){
489                 if(doExport) return onload(r);
490                 var recs = r.recv().content();
491                 if(e = openils.Event.parse(recs[0]))
492                     return alert(e);
493                 for(var i = 0; i < recs.length; i++) {
494                     var rec = recs[i];
495                     queuedRecords.push(rec);
496                     queuedRecordsMap[rec.id()] = rec;
497                 }
498                 onload();
499             }
500         }
501     );
502 }
503
504 function vlLoadMatchUI(recId) {
505     displayGlobalDiv('vl-generic-progress');
506     var queuedRec = queuedRecordsMap[recId];
507     var matches = queuedRec.matches();
508     var records = [];
509     currentImportRecId = recId;
510     for(var i = 0; i < matches.length; i++)
511         records.push(matches[i].eg_record());
512
513     var retrieve = ['open-ils.search', 'open-ils.search.biblio.record_entry.slim.retrieve'];
514     var params = [records];
515     if(currentType == 'auth') {
516         retrieve = ['open-ils.cat', 'open-ils.cat.authority.record.retrieve'];
517         params = [authtoken, records, {clear_marc:1}];
518     }
519
520     fieldmapper.standardRequest(
521         retrieve,
522         {   async: true,
523             params:params,
524             oncomplete: function(r) {
525                 var recs = r.recv().content();
526                 if(e = openils.Event.parse(recs))
527                     return alert(e);
528
529                 /* ui mangling */
530                 displayGlobalDiv('vl-match-div');
531                 resetVlMatchGridLayout();
532                 currentMatchedRecords = recs;
533                 vlMatchGrid.setStructure(vlMatchGridLayout);
534
535                 // build the data store of records with match information
536                 var dataStore = bre.toStoreData(recs, null, 
537                     {virtualFields:['_id', 'match_score', 'match_quality', 'rec_quality']});
538                 dataStore.identifier = '_id';
539
540                 var matchSeenMap = {};
541
542                 for(var i = 0; i < dataStore.items.length; i++) {
543                     var item = dataStore.items[i];
544                     item._id = i; // just need something unique
545                     for(var j = 0; j < matches.length; j++) {
546                         var match = matches[j];
547                         if(match.eg_record() == item.id && !matchSeenMap[match.id()]) {
548                             if(match.match_score)
549                                 item.match_score = match.match_score();
550                             item.match_quality = match.quality();
551                             item.rec_quality = queuedRec.quality();
552                             matchSeenMap[match.id()] = 1;
553                             break;
554                         }
555                     }
556                 }
557
558                 // now populate the grid
559                 vlPopulateMatchGrid(vlMatchGrid, dataStore);
560             }
561         }
562     );
563 }
564
565 function vlPopulateMatchGrid(grid, data) {
566     var store = new dojo.data.ItemFileReadStore({data:data});
567     grid.setStore(store);
568     grid.update();
569 }
570
571 function showMe(id) {
572     dojo.style(dojo.byId(id), 'display', 'block');
573 }
574 function hideMe(id) {
575     dojo.style(dojo.byId(id), 'display', 'none');
576 }
577
578
579 function vlLoadMARCHtml(recId, inCat, oncomplete) {
580     dijit.byId('vl-marc-html-done-button').onClick = oncomplete;
581     displayGlobalDiv('vl-generic-progress');
582     var api;
583     var params = [recId, 1];
584
585     if(inCat) {
586         hideMe('vl-marc-html-edit-button'); // don't show marc editor button
587         dijit.byId('vl-marc-html-edit-button').onClick = function(){}
588         api = ['open-ils.search', 'open-ils.search.biblio.record.html'];
589         if(currentType == 'auth')
590             api = ['open-ils.search', 'open-ils.search.authority.to_html'];
591     } else {
592         showMe('vl-marc-html-edit-button'); // plug in the marc editor button
593         dijit.byId('vl-marc-html-edit-button').onClick = 
594             function() {vlLoadMarcEditor(currentType, recId, oncomplete);};
595         params = [authtoken, recId];
596         api = ['open-ils.vandelay', 'open-ils.vandelay.queued_bib_record.html'];
597         if(currentType == 'auth')
598             api = ['open-ils.vandelay', 'open-ils.vandelay.queued_authority_record.html'];
599     }
600
601     fieldmapper.standardRequest(
602         api, 
603         {   async: true,
604             params: params,
605             oncomplete: function(r) {
606             displayGlobalDiv('vl-marc-html-div');
607                 var html = r.recv().content();
608                 dojo.byId('vl-marc-record-html').innerHTML = html;
609             }
610         }
611     );
612 }
613
614
615 /*
616 function getRecMatchesFromAttrCode(rec, attrCode) {
617     var matches = [];
618     var attr = getRecAttrFromCode(rec, attrCode);
619     for(var j = 0; j < rec.matches().length; j++) {
620         var match = rec.matches()[j];
621         if(match.matched_attr() == attr.id()) 
622             matches.push(match);
623     }
624     return matches;
625 }
626 */
627
628 /*
629 function getRecAttrFromMatch(rec, match) {
630     for(var i = 0; i < rec.attributes().length; i++) {
631         var attr = rec.attributes()[i];
632         if(attr.id() == match.matched_attr())
633             return attr;
634     }
635 }
636 */
637
638 function getRecAttrDefFromAttr(attr, type) {
639     var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
640     for(var i = 0; i < defs.length; i++) {
641         var def = defs[i];
642         if(def.id() == attr.field())
643             return def;
644     }
645 }
646
647 function getRecAttrFromCode(rec, attrCode) {
648     var defId = attrDefMap[currentType][attrCode];
649     var attrs = rec.attributes();
650     for(var i = 0; i < attrs.length; i++) {
651         var attr = attrs[i];
652         if(attr.field() == defId) 
653             return attr;
654     }
655     return null;
656 }
657
658 function vlGetViewMatches(rowIdx, item) {
659     if(item) {
660         var id = this.grid.store.getValue(item, 'id');
661         var rec = queuedRecordsMap[id];
662         if(rec.matches().length > 0)
663             return id;
664     }
665     return -1
666 }
667
668 function vlFormatViewMatches(id) {
669     if(id == -1) return '';
670     return '<a href="javascript:void(0);" onclick="vlLoadMatchUI(' + id + ');">' + this.name + '</a>';
671 }
672
673 function vlGetViewErrors(rowIdx, item) {
674     if(item) {
675         var id = this.grid.store.getValue(item, 'id');
676         var rec = queuedRecordsMap[id];
677         // id:rec_error:item_import_error_count
678         return id + ':' + 
679             (rec.import_error() ? 1 : '') + ':' + 
680             (typeof rec.import_items == 'function'
681                 ? rec.import_items().filter(function(i) {return i.import_error()}).length
682                 :''
683             );
684     }
685     return -1
686 }
687
688 function vlFormatViewErrors(chunk) {
689     if(chunk == -1) return '';
690     var id = chunk.split(':')[0];
691     var rec = chunk.split(':')[1];
692     var count = chunk.split(':')[2];
693     var links = '';
694     if(rec) 
695         links += '<a href="javascript:void(0);" onclick="vlLoadErrorUI(' + id + ');">Record</a><br/>'; // TODO I18N
696     if(Number(count))
697         links += '<a href="javascript:void(0);" onclick="vlLoadErrorUI(' + id + ');">Items ('+count+')</a>'; // TODO I18N
698     return links;
699 }
700
701 //var vlItemErrorColumnPicker;
702 function vlLoadErrorUI(id) {
703
704     displayGlobalDiv('vl-import-error-div');
705     openils.Util.hide('vl-import-error-grid-all');
706     openils.Util.show('vl-import-error-record');
707
708     var rec = queuedRecordsMap[id];
709
710     dojo.byId('vl-error-id').innerHTML = rec.id();
711     dojo.forEach( // TODO sane authority rec. fields
712         ['title', 'author', 'isbn', 'issn', 'upc'],
713         function(field) {
714             var attr =  getRecAttrFromCode(rec, field);
715             var eid = 'vl-error-' + field;
716             if(attr) {
717                 openils.Util.show(dojo.byId(eid).parentNode, 'table-row');
718                 dojo.byId(eid).innerHTML = attr.attr_value();
719             } else {
720                 openils.Util.hide(dojo.byId(eid).parentNode);
721             }
722         }
723     );
724     var iediv = dojo.byId('vl-error-import-error');
725     var eddiv = dojo.byId('vl-error-error-detail');
726     if(rec.import_error()) {
727         openils.Util.show(iediv.parentNode, 'table-row');
728         openils.Util.show(eddiv.parentNode, 'table-row');
729         iediv.innerHTML = rec.import_error();
730         eddiv.innerHTML = rec.error_detail();
731     } else {
732         openils.Util.hide(iediv.parentNode);
733         openils.Util.hide(eddiv.parentNode);
734     }
735
736     var errorItems = rec.import_items().filter(function(i) {return i.import_error()});
737     if(errorItems.length) {
738         openils.Util.show('vl-import-error-grid-some');
739         storeData = vqbr.toStoreData(errorItems);
740         var store = new dojo.data.ItemFileReadStore({data:storeData});
741         vlImportErrorGrid.setStore(store);
742         vlImportErrorGrid.update();
743     } else {
744         openils.Util.hide('vl-import-error-grid-some');
745     }
746 }
747
748 function vlLoadErrorUIAll() {
749
750     displayGlobalDiv('vl-import-error-div');
751     openils.Util.hide('vl-import-error-grid-some');
752     openils.Util.hide('vl-import-error-record');
753     openils.Util.show('vl-import-error-grid-all');
754     vlAllImportErrorGrid.resetStore();
755
756     vlImportErrorGrid.displayOffset = 0;
757
758     vlAllImportErrorGrid.dataLoader = function() {
759
760         vlAllImportErrorGrid.showLoadProgressIndicator();
761
762         fieldmapper.standardRequest(
763             ['open-ils.vandelay', 'open-ils.vandelay.import_item.queue.retrieve'],
764             {
765                 async : true,
766                 params : [
767                     authtoken, currentQueueId, {   
768                         with_import_error: (vlImportItemsShowErrors.checked) ? 1 : null,
769                         offset : vlAllImportErrorGrid.displayOffset,
770                         limit : vlAllImportErrorGrid.displayLimit
771                     }
772                 ],
773                 onresponse : function(r) {
774                     var item = openils.Util.readResponse(r);
775                     if(!item) return;
776                     vlAllImportErrorGrid.store.newItem(vii.toStoreItem(item));
777                 },
778                 oncomplete : function() {
779                     vlAllImportErrorGrid.hideLoadProgressIndicator();
780                 }
781             }
782         );
783     };
784
785     vlAllImportErrorGrid.dataLoader();
786 }
787
788 function vlGetOrg(rowIdx, item) {
789     if(!item) return '';
790     var value = this.grid.store.getValue(item, this.field);
791     if(value) return fieldmapper.aou.findOrgUnit(value).shortname();
792     return '';
793 }
794
795 function vlFormatViewMatchMARC(id) {
796     return '<a href="javascript:void(0);" onclick="vlLoadMARCHtml(' + id + ', true, '+
797         'function(){displayGlobalDiv(\'vl-match-div\');});">' + this.name + '</a>';
798 }
799
800 function getAttrValue(rowIdx, item) {
801     if(!item) return '';
802     var attrCode = this.field.split('.')[1];
803     var rec = queuedRecordsMap[this.grid.store.getValue(item, 'id')];
804     var attr = getRecAttrFromCode(rec, attrCode);
805     return (attr) ? attr.attr_value() : '';
806 }
807
808 function vlGetDateTimeField(rowIdx, item) {
809     if(!item) return '';
810     var value = this.grid.store.getValue(item, this.field);
811     if(!value) return '';
812     var date = dojo.date.stamp.fromISOString(value);
813     return dojo.date.locale.format(date, {selector:'date'});
814 }
815
816 function vlGetCreator(rowIdx, item) {
817     if(!item) return '';
818     var id = this.grid.store.getValue(item, 'creator');
819     if(userCache[id])
820         return userCache[id].usrname();
821     var user = fieldmapper.standardRequest(
822         ['open-ils.actor', 'open-ils.actor.user.retrieve'], [authtoken, id]);
823     if(e = openils.Event.parse(user))
824         return alert(e);
825     userCache[id] = user;
826     return user.usrname();
827 }
828
829 function vlGetViewMARC(rowIdx, item) {
830     return item && this.grid.store.getValue(item, 'id');
831 }
832
833 function vlFormatViewMARC(id) {
834     return '<a href="javascript:void(0);" onclick="vlLoadMARCHtml(' + id + ', false, '+
835         'function(){displayGlobalDiv(\'vl-queue-div\');});">' + this.name + '</a>';
836 }
837
838 function vlGetOverlayTargetSelector(rowIdx, item) {
839     if(!item) return;
840     return this.grid.store.getValue(item, '_id') + ':' + this.grid.store.getValue(item, 'id');
841 }
842
843 function vlFormatOverlayTargetSelector(val) {
844     if(!val) return '';
845     var parts = val.split(':');
846     var _id = parts[0];
847     var id = parts[1];
848     var value = '<input type="checkbox" name="vl-overlay-target-RECID" '+
849         'onclick="vlHandleOverlayTargetSelected(ID, GRIDID);" gridid="GRIDID" match="ID"/>';
850     value = value.replace(/GRIDID/g, _id);
851     value = value.replace(/RECID/g, currentImportRecId);
852     value = value.replace(/ID/g, id);
853     if(_id == currentOverlayRecordsMapGid[currentImportRecId])
854         return value.replace('/>', 'checked="checked"/>');
855     return value;
856 }
857
858
859 /**
860   * see if the user has enabled overlays for the current match set and, 
861   * if so, map the current import record to the overlay target.
862   */
863 function vlHandleOverlayTargetSelected(recId, gridId) {
864     var noneSelected = true;
865     var checkboxes = dojo.query('[name=vl-overlay-target-'+currentImportRecId+']');
866     for(var i = 0; i < checkboxes.length; i++) {
867         var checkbox = checkboxes[i];
868         var matchRecId = checkbox.getAttribute('match');
869         var gid = checkbox.getAttribute('gridid');
870         if(checkbox.checked) {
871             if(matchRecId == recId && gid == gridId) {
872                 noneSelected = false;
873                 currentOverlayRecordsMap[currentImportRecId] = matchRecId;
874                 currentOverlayRecordsMapGid[currentImportRecId] = gid;
875                 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = true;
876                 dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = 'overlay_selected';
877             } else {
878                 checkbox.checked = false;
879             }
880         }
881     }
882
883     if(noneSelected) {
884         delete currentOverlayRecordsMap[currentImportRecId];
885         delete currentOverlayRecordsMapGid[currentImportRecId];
886         dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = false;
887         dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = '';
888     }
889 }
890
891 var valLastQueueType = null;
892 var vlQueueGridLayout = null;
893 function buildRecordGrid(type) {
894     displayGlobalDiv('vl-queue-div');
895
896     vlBibQueueGrid.canSort = function(col){ if(Math.abs(col) == 1) { return false; } else { return true; } }; 
897     vlAuthQueueGrid.canSort = function(col){ if(Math.abs(col) == 1) { return false; } else { return true; } }; 
898
899     if(type == 'bib') {
900         openils.Util.show('vl-bib-queue-grid-wrapper');
901         openils.Util.hide('vl-auth-queue-grid-wrapper');
902         vlQueueGrid = vlBibQueueGrid;
903     } else {
904         openils.Util.show('vl-auth-queue-grid-wrapper');
905         openils.Util.hide('vl-bib-queue-grid-wrapper');
906         vlQueueGrid = vlAuthQueueGrid;
907     }
908
909
910     if(valLastQueueType != type) {
911         valLastQueueType = type;
912         vlQueueGridLayout = vlQueueGrid.attr('structure');
913         var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
914         attrDefMap[type] = {};
915         for(var i = 0; i < defs.length; i++) {
916             var def = defs[i]
917             attrDefMap[type][def.code()] = def.id();
918             var col = {
919                 name:def.description(), 
920                 field:'attr.' + def.code(),
921                 get: getAttrValue,
922                 selectableColumn:true
923             };
924             vlQueueGridLayout[0].cells[0].push(col);
925         }
926     }
927
928     dojo.forEach(vlQueueGridLayout[0].cells[0], 
929         function(cell) { 
930             if(cell.field.match(/^\+/)) 
931                 cell.nonSelectable=true;
932         }
933     );
934
935     var storeData;
936     if(type == 'bib')
937         storeData = vqbr.toStoreData(queuedRecords);
938     else
939         storeData = vqar.toStoreData(queuedRecords);
940
941     var store = new dojo.data.ItemFileReadStore({data:storeData});
942     vlQueueGrid.setStore(store);
943
944     if(vlQueueGridColumePicker[type]) {
945         vlQueueGrid.update();
946     } else {
947
948         vlQueueGridColumePicker[type] =
949             new openils.widget.GridColumnPicker(
950                 authtoken, 'vandelay.queue.'+type, vlQueueGrid, vlQueueGridLayout);
951         vlQueueGridColumePicker[type].load();
952     }
953 }
954
955 function vlQueueGridPrevPage() {
956     var page = parseInt(vlQueueDisplayPage.getValue());
957     if(page < 2) return;
958     vlQueueDisplayPage.setValue(page - 1);
959     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
960 }
961
962 function vlQueueGridNextPage() {
963     vlQueueDisplayPage.setValue(parseInt(vlQueueDisplayPage.getValue())+1);
964     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
965 }
966
967 function vlDeleteQueue(type, queueId, onload) {
968     fieldmapper.standardRequest(
969         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.delete'],
970         {   async: true,
971             params: [authtoken, queueId],
972             oncomplete: function(r) {
973                 var resp = r.recv().content();
974                 if(e = openils.Event.parse(resp))
975                     return alert(e);
976                 onload();
977             }
978         }
979     );
980 }
981
982
983 function vlQueueGridDrawSelectBox(rowIdx, item) {
984     return item &&  this.grid.store.getValue(item, 'id');
985 }
986
987 function vlQueueGridFormatSelectBox(id) {
988     var domId = 'vl-record-list-selected-' + id;
989     if (id) { selectableGridRecords[domId] = id; }
990     return "<div><input type='checkbox' id='"+domId+"'/></div>";
991 }
992
993 function vlSelectAllQueueGridRecords() {
994     for(var id in selectableGridRecords) 
995         dojo.byId(id).checked = true;
996 }
997 function vlSelectNoQueueGridRecords() {
998     for(var id in selectableGridRecords) 
999         dojo.byId(id).checked = false;
1000 }
1001 function vlToggleQueueGridSelect() {
1002     if(dojo.byId('vl-queue-grid-row-selector').checked)
1003         vlSelectAllQueueGridRecords();
1004     else
1005         vlSelectNoQueueGridRecords();
1006 }
1007
1008 var handleRetrieveRecords = function() {
1009     buildRecordGrid(currentType);
1010     vlFetchQueueSummary(currentQueueId, currentType, 
1011         function(summary) {
1012             dojo.byId('vl-queue-summary-name').innerHTML = summary.queue.name();
1013             dojo.byId('vl-queue-summary-total-count').innerHTML = summary.total +'';
1014             dojo.byId('vl-queue-summary-import-count').innerHTML = summary.imported + '';
1015             dojo.byId('vl-queue-summary-import-item-count').innerHTML = summary.total_items + '';
1016             dojo.byId('vl-queue-summary-import-item-imported-count').innerHTML = summary.total_items_imported + '';
1017             dojo.byId('vl-queue-summary-rec-error-count').innerHTML = summary.rec_import_errors + '';
1018             dojo.byId('vl-queue-summary-item-error-count').innerHTML = summary.item_import_errors + '';
1019         }
1020     );
1021 }
1022
1023 function vlFetchQueueSummary(qId, type, onload) {
1024     fieldmapper.standardRequest(
1025         ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.summary.retrieve'],
1026         {   async: true,
1027             params: [authtoken, qId],
1028             oncomplete : function(r) {
1029                 var summary = r.recv().content();
1030                 if(e = openils.Event.parse(summary))
1031                     return alert(e);
1032                 return onload(summary);
1033             }
1034         }
1035     );
1036 }
1037
1038 var _importCancelHandler;
1039 var _importGoHandler;
1040 function vlHandleQueueItemsAction(action) {
1041
1042     if(_importCancelHandler) dojo.disconnect(_importCancelHandler);
1043
1044     _importCancelHandler = dojo.connect(
1045         queueItemsImportCancelButton, 
1046         'onClick', 
1047         function() {
1048             queueItemsImportDialog.hide();
1049         }
1050     );
1051
1052     if(_importGoHandler)
1053         dojo.disconnect(_importGoHandler);
1054
1055     _importGoHandler = dojo.connect(
1056         queueItemsImportGoButton,
1057         'onClick', 
1058         function() {
1059             queueItemsImportDialog.hide();
1060
1061             // hack to set the widgets the import funcs will be looking at.  Reset them below.
1062             vlUploadQueueImportNoMatch.attr('value',  vlUploadQueueImportNoMatch2.attr('value'));
1063             vlUploadQueueAutoOverlayExact.attr('value',  vlUploadQueueAutoOverlayExact2.attr('value'));
1064             vlUploadQueueAutoOverlay1Match.attr('value',  vlUploadQueueAutoOverlay1Match2.attr('value'));
1065             vlUploadMergeProfile.attr('value',  vlUploadMergeProfile2.attr('value'));
1066             vlUploadQueueAutoOverlayBestMatch.attr('value',  vlUploadQueueAutoOverlayBestMatch2.attr('value'));
1067             vlUploadQueueAutoOverlayBestMatchRatio.attr('value',  vlUploadQueueAutoOverlayBestMatchRatio2.attr('value'));
1068
1069             if(action == 'import') {
1070                 vlImportSelectedRecords();
1071             } else if(action == 'import_all') {
1072                 vlImportAllRecords();
1073             }
1074             
1075             // reset the widgets to prevent accidental future actions
1076             vlUploadQueueImportNoMatch.attr('value',  false);
1077             vlUploadQueueImportNoMatch2.attr('value', false);
1078             vlUploadQueueAutoOverlayExact.attr('value', false);
1079             vlUploadQueueAutoOverlayExact2.attr('value', false);
1080             vlUploadQueueAutoOverlay1Match.attr('value', false);
1081             vlUploadQueueAutoOverlay1Match2.attr('value', false);
1082             vlUploadMergeProfile.attr('value', '');
1083             vlUploadMergeProfile2.attr('value', '');
1084             vlUploadQueueAutoOverlayBestMatch.attr('value', false);
1085             vlUploadQueueAutoOverlayBestMatch2.attr('value', false);
1086             vlUploadQueueAutoOverlayBestMatchRatio.attr('value', '0.0');
1087             vlUploadQueueAutoOverlayBestMatchRatio2.attr('value', '0.0');
1088         }
1089     );
1090
1091     queueItemsImportDialog.show();
1092 }
1093     
1094
1095 /* import user-selected records */
1096 function vlImportSelectedRecords() {
1097     var records = [];
1098
1099     for(var id in selectableGridRecords) {
1100         if(dojo.byId(id).checked) {
1101             var recId = selectableGridRecords[id];
1102             var rec = queuedRecordsMap[recId];
1103             if(!rec.import_time()) 
1104                 records.push(recId);
1105         }
1106     }
1107
1108     vlImportRecordQueue(
1109         currentType, 
1110         currentQueueId, 
1111         records,
1112         function(){
1113             retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1114         }
1115     );
1116 }
1117
1118 /* import all (non-imported) queue records */
1119 function vlImportAllRecords() {
1120     vlImportRecordQueue(
1121         currentType, 
1122         currentQueueId, 
1123         null,
1124         function(){
1125             retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1126         }
1127     );
1128 }
1129
1130 /* if recList has values, import only those records */
1131 function vlImportRecordQueue(type, queueId, recList, onload) {
1132     displayGlobalDiv('vl-generic-progress-with-total');
1133
1134     /* set up options */
1135     var options = {overlay_map : currentOverlayRecordsMap};
1136
1137     if(vlUploadQueueImportNoMatch.checked) {
1138         options.import_no_match = true;
1139         vlUploadQueueImportNoMatch.checked = false;
1140     }
1141
1142     if(vlUploadQueueAutoOverlayExact.checked) {
1143         options.auto_overlay_exact = true;
1144         vlUploadQueueAutoOverlayExact.checked = false;
1145     }
1146
1147     if(vlUploadQueueAutoOverlayBestMatch.checked) {
1148         options.auto_overlay_best_match = true;
1149         vlUploadQueueAutoOverlayBestMatch.checked = false;
1150         options.match_quality_ratio = vlUploadQueueAutoOverlayBestMatchRatio.attr('value');
1151     }
1152
1153     if(vlUploadQueueAutoOverlay1Match.checked) {
1154         options.auto_overlay_1match = true;
1155         vlUploadQueueAutoOverlay1Match.checked = false;
1156         options.match_quality_ratio = vlUploadQueueAutoOverlayBestMatchRatio.attr('value');
1157     }
1158
1159     var profile = vlUploadMergeProfile.attr('value');
1160     if(profile != null && profile != '') {
1161         options.merge_profile = profile;
1162     }
1163
1164     /* determine which method we're calling */
1165
1166     var method = 'open-ils.vandelay.bib_queue.import';
1167     if(type == 'auth')
1168         method = method.replace('bib', 'auth');
1169
1170     var params = [authtoken, queueId, options];
1171     if(recList) {
1172         method = 'open-ils.vandelay.'+currentType+'_record.list.import';
1173         params[1] = recList;
1174     }
1175
1176     fieldmapper.standardRequest(
1177         ['open-ils.vandelay', method],
1178         {   async: true,
1179             params: params,
1180             onresponse: function(r) {
1181                 var resp = r.recv().content();
1182                 if(e = openils.Event.parse(resp))
1183                     return alert(e);
1184                 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
1185             },
1186             oncomplete: function() {onload();}
1187         }
1188     );
1189 }
1190
1191
1192 /**
1193   * Create queue, upload MARC, process spool, load the newly created queue 
1194   */
1195 function batchUpload() {
1196     var queueName = dijit.byId('vl-queue-name').getValue();
1197     currentType = dijit.byId('vl-record-type').getValue();
1198
1199     var handleProcessSpool = function() {
1200         if( 
1201             vlUploadQueueImportNoMatch.checked || 
1202             vlUploadQueueAutoOverlayExact.checked || 
1203             vlUploadQueueAutoOverlay1Match.checked ||
1204             vlUploadQueueAutoOverlayBestMatch.checked ) {
1205
1206                 vlImportRecordQueue(
1207                     currentType, 
1208                     currentQueueId, 
1209                     null,
1210                     function() {
1211                         retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1212                     }
1213                 );
1214         } else {
1215             retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1216         }
1217     }
1218
1219     var handleUploadMARC = function(key) {
1220         dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');
1221         processSpool(key, currentQueueId, currentType, handleProcessSpool);
1222     };
1223
1224     var handleCreateQueue = function(queue) {
1225         currentQueueId = queue.id();
1226         uploadMARC(handleUploadMARC);
1227     };
1228     
1229     if(vlUploadQueueSelector.getValue() && !queueName) {
1230         currentQueueId = vlUploadQueueSelector.getValue();
1231         uploadMARC(handleUploadMARC);
1232     } else {
1233         createQueue(queueName, currentType, handleCreateQueue, 
1234             vlUploadQueueHoldingsImportProfile.attr('value'),
1235             vlUploadQueueMatchSet.attr('value')
1236         );
1237     }
1238 }
1239
1240
1241 function vlFleshQueueSelect(selector, type) {
1242     var data = (type == 'bib') ? vbq.toStoreData(allUserBibQueues) : vaq.toStoreData(allUserAuthQueues);
1243     selector.store = new dojo.data.ItemFileReadStore({data:data});
1244     selector.setValue(null);
1245     selector.setDisplayedValue('');
1246     if(data[0])
1247         selector.setValue(data[0].id());
1248
1249     var qInput = dijit.byId('vl-queue-name');
1250
1251     var selChange = function(val) {
1252         console.log('selector onchange');
1253         // user selected a queue from the selector;  clear the input and 
1254         // set the item import profile already defined for the queue
1255         var queue = allUserBibQueues.filter(function(q) { return (q.id() == val) })[0];
1256         if(val) {
1257             vlUploadQueueHoldingsImportProfile.attr('value', queue.item_attr_def() || '');
1258             vlUploadQueueHoldingsImportProfile.attr('disabled', true);
1259             vlUploadQueueMatchSet.attr('value', queue.match_set() || '');
1260             vlUploadQueueMatchSet.attr('disabled', true);
1261         } else {
1262             vlUploadQueueHoldingsImportProfile.attr('value', '');
1263             vlUploadQueueHoldingsImportProfile.attr('disabled', false);
1264             vlUploadQueueMatchSet.attr('value', '');
1265             vlUploadQueueMatchSet.attr('disabled', false);
1266         }
1267         dojo.disconnect(qInput._onchange);
1268         qInput.attr('value', '');
1269         qInput._onchange = dojo.connect(qInput, 'onChange', inputChange);
1270     }
1271     
1272     var inputChange = function(val) {
1273         console.log('qinput onchange');
1274         // user entered a new queue name. clear the selector 
1275         vlUploadQueueHoldingsImportProfile.attr('value', '');
1276         vlUploadQueueHoldingsImportProfile.attr('disabled', false);
1277         vlUploadQueueMatchSet.attr('value', '');
1278         vlUploadQueueMatchSet.attr('disabled', false);
1279         dojo.disconnect(selector._onchange);
1280         selector.attr('value', '');
1281         selector._onchange = dojo.connect(selector, 'onChange', selChange);
1282     }
1283
1284     selector._onchange = dojo.connect(selector, 'onChange', selChange);
1285     qInput._onchange = dojo.connect(qInput, 'onChange', inputChange);
1286 }
1287
1288 function vlUpdateMatchSetSelector(type) {
1289     type = (type.match(/bib/)) ? 'biblio' : 'authority';
1290     vlUploadQueueMatchSet.store = 
1291         new dojo.data.ItemFileReadStore({data:vms.toStoreData(matchSets[type])});
1292 }
1293
1294 function vlShowUploadForm() {
1295     displayGlobalDiv('vl-marc-upload-div');
1296     vlFleshQueueSelect(vlUploadQueueSelector, vlUploadRecordType.getValue());
1297     vlUploadSourceSelector.store = 
1298         new dojo.data.ItemFileReadStore({data:cbs.toStoreData(vlBibSources, 'source')});
1299     vlUploadSourceSelector.setValue(vlBibSources[0].id());
1300     vlUploadQueueHoldingsImportProfile.store = 
1301         new dojo.data.ItemFileReadStore({data:viiad.toStoreData(importItemDefs)});
1302     vlUpdateMatchSetSelector(vlUploadRecordType.getValue());
1303
1304     // use ratio from the merge profile if it's set
1305     dojo.connect(
1306         vlUploadMergeProfile, 
1307         'onChange',
1308         function(val) {
1309             if(!val) return;
1310             var profile = mergeProfiles.filter(function(p) { return (p.id() == val); })[0];
1311             if(profile.lwm_ratio() != null)
1312                vlUploadQueueAutoOverlayBestMatchRatio.attr('value', profile.lwm_ratio()+''); 
1313         }
1314     );
1315     dojo.connect(
1316         vlUploadMergeProfile2, 
1317         'onChange',
1318         function(val) {
1319             if(!val) return;
1320             var profile = mergeProfiles.filter(function(p) { return (p.id() == val); })[0];
1321             if(profile.lwm_ratio() != null)
1322                vlUploadQueueAutoOverlayBestMatchRatio2.attr('value', profile.lwm_ratio()+''); 
1323         }
1324     );
1325
1326 }
1327
1328 function vlShowQueueSelect() {
1329     displayGlobalDiv('vl-queue-select-div');
1330     vlFleshQueueSelect(vlQueueSelectQueueList, vlQueueSelectType.getValue());
1331 }
1332
1333 function vlShowMatchSetEditor() {
1334     displayGlobalDiv('vl-match-set-editor-div');
1335     dojo.byId('vl-match-set-editor-div').appendChild(
1336         dojo.create('iframe', {
1337             id : 'vl-match-set-iframe',
1338             src : oilsBasePath + '/eg/conify/global/vandelay/match_set',
1339             style : 'width:100%; height:500px; border:none; margin:0px;'
1340         })
1341     );
1342 }
1343
1344 function vlFetchQueueFromForm() {
1345     currentType = vlQueueSelectType.getValue();
1346     currentQueueId = vlQueueSelectQueueList.getValue();
1347     retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1348 }
1349
1350 function vlOpenMarcEditWindow(rec, postReloadHTMLHandler) {
1351     /*
1352         To run in Firefox directly, must set signed.applets.codebase_principal_support
1353         to true in about:config
1354     */
1355     netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1356     win = window.open('/xul/server/cat/marcedit.xul'); // XXX version?
1357
1358     var type;
1359     if (currentType == 'bib') {
1360         type = 'bre';
1361     } else {
1362         type = 'are';
1363     }
1364
1365     function onsave(r) {
1366         // after the record is saved, reload the HTML display
1367         var stat = r.recv().content();
1368         if(e = openils.Event.parse(stat))
1369             return alert(e);
1370         alert(dojo.byId('vl-marc-edit-complete-label').innerHTML);
1371         win.close();
1372         vlLoadMARCHtml(rec.id(), false, postReloadHTMLHandler);
1373     }
1374
1375     win.xulG = {
1376         record : {marc : rec.marc(), "rtype": type},
1377         save : {
1378             label: dojo.byId('vl-marc-edit-save-label').innerHTML,
1379             func: function(xmlString) {
1380                 var method = 'open-ils.permacrud.update.' + rec.classname;
1381                 rec.marc(xmlString);
1382                 fieldmapper.standardRequest(
1383                     ['open-ils.permacrud', method],
1384                     {   async: true,
1385                         params: [authtoken, rec],
1386                         oncomplete: onsave
1387                     }
1388                 );
1389             },
1390         },
1391         'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
1392         'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
1393     };
1394 }
1395
1396 function vlLoadMarcEditor(type, recId, postReloadHTMLHandler) {
1397     var method = 'open-ils.permacrud.search.vqbr';
1398     if(currentType != 'bib')
1399         method = method.replace(/vqbr/,'vqar');
1400
1401     fieldmapper.standardRequest(
1402         ['open-ils.permacrud', method],
1403         {   async: true, 
1404             params: [authtoken, {id : recId}],
1405             oncomplete: function(r) {
1406                 var rec = r.recv().content();
1407                 if(e = openils.Event.parse(rec))
1408                     return alert(e);
1409                 vlOpenMarcEditWindow(rec, postReloadHTMLHandler);
1410             }
1411         }
1412     );
1413 }
1414
1415
1416
1417 //------------------------------------------------------------
1418 // attribute editors
1419
1420 // attribute-editor global variables
1421
1422 var ATTR_EDITOR_IN_UPDATE_MODE = false; // true on 'edit', false on 'create'
1423 var ATTR_EDIT_ID = null;                // id of current 'edit' attribute
1424 var ATTR_EDIT_GROUP = 'bib';            // bib-attrs or auth-attrs
1425
1426 function vlAttrEditorInit() {
1427     // set up tooltips on the edit form
1428     connectTooltip('attr-editor-tags'); 
1429     connectTooltip('attr-editor-subfields'); 
1430 }
1431
1432 function vlShowAttrEditor() {
1433     displayGlobalDiv('vl-attr-editor-div');
1434     loadAttrEditorGrid();
1435     idHide('vl-generic-progress');
1436 }
1437
1438 function setAttrEditorGroup(groupName) {
1439     // put us into 'bib'-attr or 'auth'-attr mode.
1440     if (ATTR_EDIT_GROUP != groupName) {
1441         ATTR_EDIT_GROUP = groupName;
1442         loadAttrEditorGrid();
1443     }
1444 }
1445
1446 function onAttrEditorOpen() {
1447     // the "bars" have the create/update/cancel/etc. buttons.
1448     var create_bar = document.getElementById('attr-editor-create-bar');
1449     var update_bar = document.getElementById('attr-editor-update-bar');
1450     if (ATTR_EDITOR_IN_UPDATE_MODE) {
1451         update_bar.style.display='table-row';
1452         create_bar.style.display='none';
1453         // hide the dropdown-button
1454         idStyle('vl-create-attr-editor-button', 'visibility', 'hidden');
1455     } else {
1456         dijit.byId('attr-editor-dialog').reset();
1457         create_bar.style.display='table-row';
1458         update_bar.style.display='none';
1459     }
1460 }
1461
1462 function onAttrEditorClose() {
1463     // reset the form to a "create" form. (We may have borrowed it for editing.)
1464     ATTR_EDITOR_IN_UPDATE_MODE = false;
1465     // show the dropdown-button
1466     idStyle('vl-create-attr-editor-button', 'visibility', 'visible');
1467 }
1468
1469 function loadAttrEditorGrid() {
1470     var _data = (ATTR_EDIT_GROUP == 'auth') ? 
1471         vqarad.toStoreData(authAttrDefs) : vqbrad.toStoreData(bibAttrDefs) ;
1472
1473     var store = new dojo.data.ItemFileReadStore({data:_data});
1474     attrEditorGrid.setStore(store);
1475     attrEditorGrid.onRowDblClick = onAttrEditorClick;
1476     attrEditorGrid.update();
1477 }
1478
1479 function attrGridGetTag(n, item) {
1480     // grid helper: return the tags from the row's xpath column.
1481     return item && xpathParser.parse(this.grid.store.getValue(item, 'xpath')).tags;
1482 }
1483
1484 function attrGridGetSubfield(n, item) {
1485     // grid helper: return the subfields from the row's xpath column.
1486     return item && xpathParser.parse(this.grid.store.getValue(item, 'xpath')).subfields;
1487 }
1488
1489 function onAttrEditorClick() {
1490     var row = this.getItem(this.focus.rowIndex);
1491     ATTR_EDIT_ID = this.store.getValue(row, 'id');
1492     ATTR_EDITOR_IN_UPDATE_MODE = true;
1493
1494     // populate the popup editor.
1495     dijit.byId('attr-editor-code').attr('value', this.store.getValue(row, 'code'));
1496     dijit.byId('attr-editor-description').attr('value', this.store.getValue(row, 'description'));
1497     var parsed_xpath = xpathParser.parse(this.store.getValue(row, 'xpath'));
1498     dijit.byId('attr-editor-tags').attr('value', parsed_xpath.tags);
1499     dijit.byId('attr-editor-subfields').attr('value', parsed_xpath.subfields);
1500     dijit.byId('attr-editor-xpath').attr('value', this.store.getValue(row, 'xpath'));
1501     dijit.byId('attr-editor-remove').attr('value', this.store.getValue(row, 'remove'));
1502
1503     // set up UI for editing
1504     dojo.byId('vl-create-attr-editor-button').click();
1505 }
1506
1507 function vlSaveAttrDefinition(data) {
1508     idHide('vl-attr-editor-div');
1509     idShow('vl-generic-progress');
1510
1511     data.id = ATTR_EDIT_ID;
1512
1513     // this ought to honour custom xpaths, but overwrite xpaths
1514     // derived from tags/subfields.
1515     if (data.xpath == '' || looksLikeDerivedXpath(data.xpath)) {
1516         var _xpath = tagAndSubFieldsToXpath(data.tag, data.subfield);
1517         data.xpath = _xpath;
1518     }
1519
1520     // build up our permacrud params. Key variables here are
1521     // "create or update" and "bib or auth".
1522
1523     var isAuth   = (ATTR_EDIT_GROUP == 'auth');
1524     var isCreate = (ATTR_EDIT_ID == null);
1525     var rad      = isAuth ? new vqarad() : new vqbrad() ;
1526     var method   = 'open-ils.permacrud' + (isCreate ? '.create.' : '.update.') 
1527         + (isAuth ? 'vqarad' : 'vqbrad');
1528     var _data    = rad.fromStoreItem(data);
1529
1530     _data.ischanged(1);
1531
1532     fieldmapper.standardRequest(
1533         ['open-ils.permacrud', method],
1534         {   async: true,
1535             params: [authtoken, _data ],
1536             onresponse: function(r) { },
1537             oncomplete: function(r) {
1538                 attrEditorFetchAttrDefs(vlShowAttrEditor);
1539                 ATTR_EDIT_ID = null;
1540             },
1541             onerror: function(r) {
1542                 alert('vlSaveAttrDefinition comms error: ' + r);
1543             }
1544         }
1545     );
1546 }
1547
1548 function attrEditorFetchAttrDefs(callback) {
1549     var fn = (ATTR_EDIT_GROUP == 'auth') ? vlFetchAuthAttrDefs : vlFetchBibAttrDefs;
1550     return fn(callback);
1551 }
1552
1553 function vlAttrDelete() {
1554     idHide('vl-attr-editor-div');
1555     idShow('vl-generic-progress');
1556
1557     var isAuth = (ATTR_EDIT_GROUP == 'auth');
1558     var method = 'open-ils.permacrud.delete.' + (isAuth ? 'vqarad' : 'vqbrad');
1559     var rad    = isAuth ? new vqarad() : new vqbrad() ;
1560     fieldmapper.standardRequest(
1561         ['open-ils.permacrud', method],
1562         {   async: true,
1563             params: [authtoken, rad.fromHash({ id : ATTR_EDIT_ID }), ],
1564             oncomplete: function() {
1565                 dijit.byId('attr-editor-dialog').onCancel(); // close the dialog
1566                 attrEditorFetchAttrDefs(vlShowAttrEditor);
1567                 ATTR_EDIT_ID = null;
1568             },
1569             onerror: function(r) {
1570                 alert('vlAttrDelete comms error: ' + r);
1571             }
1572         }
1573     );
1574 }
1575
1576 // ------------------------------------------------------------
1577 // utilities for attribute editors
1578
1579 // dom utilities (maybe dojo does these, and these should be replaced)
1580
1581 function idStyle(obId, k, v)    { document.getElementById(obId).style[k] = v;   }
1582 function idShow(obId)           { idStyle(obId, 'display', 'block');            }
1583 function idHide(obId)           { idStyle(obId, 'display' , 'none');            }
1584
1585 function connectTooltip(fieldId) {
1586     // Given an element id, look up a tooltip element in the doc (same
1587     // id with a '-tip' suffix) and associate the two. Maybe dojo has
1588     // a better way to do this?
1589     var fld = dojo.byId(fieldId);
1590     var tip = dojo.byId(fieldId + '-tip');
1591     dojo.connect(fld, 'onfocus', function(evt) {
1592                      dijit.showTooltip(tip.innerHTML, fld, ['below', 'after']); });
1593     dojo.connect(fld, 'onblur', function(evt) { dijit.hideTooltip(fld); });
1594 }
1595
1596 // xpath utilities
1597
1598 var xpathParser = new openils.MarcXPathParser();
1599
1600 function tagAndSubFieldsToXpath(tags, subfields) {
1601     // given tags, and subfields, build up an XPath.
1602     try {
1603         var parts = {
1604             'tags':tags.match(/[\d]+/g), 
1605             'subfields':subfields.match(/[a-zA-z]/g) };
1606         return xpathParser.compile(parts);
1607     } catch (err) {
1608         return {'parts':null, 'tags':null, 'error':err};
1609     }
1610 }
1611
1612 function looksLikeDerivedXpath(path) {
1613     // Does this path look like it was derived from tags and subfields?
1614     var parsed = xpathParser.parse(path);
1615     if (parsed.tags == null) 
1616         return false;
1617     var compiled = xpathParser.compile(parsed);
1618     return (path == compiled);
1619 }
1620
1621 // amazing xpath-util unit-tests
1622 if (!looksLikeDerivedXpath('//*[@tag="901"]/*[@code="c"]'))     alert('vandelay xpath-utility error');
1623 if ( looksLikeDerivedXpath('ba-boo-ba-boo!'))                   alert('vandelay xpath-utility error');
1624
1625
1626
1627 var profileContextOrg
1628 function vlShowProfileEditor() {
1629     displayGlobalDiv('vl-profile-editor-div');
1630     buildProfileGrid();
1631
1632     var connect = function() {
1633         dojo.connect(profileContextOrgSelector, 'onChange',
1634             function() {
1635                 profileContextOrg = this.attr('value');
1636                 pGrid.resetStore();
1637                 buildProfileGrid();
1638             }
1639         );
1640     };
1641
1642     new openils.User().buildPermOrgSelector(
1643         'ADMIN_MERGE_PROFILE', profileContextOrgSelector, null, connect);
1644 }
1645
1646 function buildProfileGrid() {
1647
1648     if(profileContextOrg == null)
1649         profileContextOrg = openils.User.user.ws_ou();
1650
1651     pGrid.loadAll( 
1652         {order_by : {vmp : 'name'}}, 
1653         {owner : fieldmapper.aou.fullPath(profileContextOrg, true)}
1654     );
1655 }
1656
1657 /* --- Import Item Attr Grid --------------- */
1658
1659 var itemAttrContextOrg;
1660 function vlShowImportItemAttrEditor() {
1661     displayGlobalDiv('vl-item-attr-editor-div');
1662     buildImportItemAttrGrid();
1663
1664     var connect = function() {
1665         dojo.connect(itemAttrContextOrgSelector, 'onChange',
1666             function() {
1667                 itemAttrContextOrg = this.attr('value');
1668                 itemAttrGrid.resetStore();
1669                 vlShowImportItemAttrEditor();
1670             }
1671         );
1672     };
1673
1674     new openils.User().buildPermOrgSelector(
1675         'ADMIN_IMPORT_ITEM_ATTR_DEF', 
1676             itemAttrContextOrgSelector, null, connect);
1677 }
1678
1679 function buildImportItemAttrGrid() {
1680
1681     if(itemAttrContextOrg == null)
1682         itemAttrContextOrg = openils.User.user.ws_ou();
1683
1684     itemAttrGrid.loadAll( 
1685         {order_by : {viiad : 'name'}}, 
1686         {owner : fieldmapper.aou.fullPath(itemAttrContextOrg, true)}
1687     );
1688 }
1689