1 /* ---------------------------------------------------------------------------
2 # Copyright (C) 2008 Georgia Public Library Service
3 # Bill Erickson <erickson@esilibrary.com>
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.
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 dojo.require('openils.widget.ProgressDialog');
47 dojo.require('dojox.form.CheckedMultiSelect');
51 'vl-generic-progress',
52 'vl-generic-progress-with-total',
57 'vl-queue-select-div',
58 'vl-marc-upload-status-div',
61 'vl-profile-editor-div',
62 'vl-item-attr-editor-div',
67 var VANDELAY_URL = '/vandelay-upload';
69 var authAttrDefs = [];
70 var queuedRecords = [];
71 var queuedRecordsMap = {};
72 var bibAttrsFetched = false;
73 var authAttrsFetched = false;
74 var attrDefMap = {}; // maps attr def code names to attr def ids
76 var currentQueueId = null;
78 var currentMatchedRecords; // set of loaded matched bib records
79 var currentOverlayRecordsMap; // map of import record to overlay record
80 var currentOverlayRecordsMapGid; // map of import record to overlay record grid id
81 var currentImportRecId; // when analyzing matches, this is the current import record
82 var userBibQueues = []; // only non-complete queues
83 var userAuthQueues = []; // only non-complete queues
85 var allUserAuthQueues;
86 var selectableGridRecords;
87 var cgi = new openils.CGI();
88 var vlQueueGridColumePicker = {};
89 var vlBibSources = [];
90 var importItemDefs = [];
91 var matchSets = {biblio : [], authority : []};
92 var matchBuckets = {};
93 var mergeProfiles = [];
94 var copyStatusCache = {};
95 var copyLocationCache = {};
100 var orgSettings = {};
101 const DEFAULT_MATCH_SET = 'vandelay.default_match_set';
108 dojo.requireLocalization("openils.vandelay", "vandelay");
109 localeStrings = dojo.i18n.getLocalization("openils.vandelay", "vandelay");
111 authtoken = openils.User.authtoken;
112 var initNeeded = 10; // how many async responses do we need before we're init'd
113 var initCount = 0; // how many async reponses we've received
115 openils.Util.registerEnterHandler(
116 vlQueueDisplayPage.domNode, function(){retrieveQueuedRecords();});
117 openils.Util.addCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
119 function checkInitDone() {
121 if(initCount == initNeeded)
122 runStartupCommands();
125 mergeProfiles = new openils.PermaCrud().retrieveAll('vmp');
126 vlUploadMergeProfile.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(mergeProfiles)});
127 vlUploadMergeProfile.labelAttr = 'name';
128 vlUploadMergeProfile.searchAttr = 'name';
129 vlUploadMergeProfile.startup();
131 vlUploadMergeProfile2.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(mergeProfiles)});
132 vlUploadMergeProfile2.labelAttr = 'name';
133 vlUploadMergeProfile2.searchAttr = 'name';
134 vlUploadMergeProfile2.startup();
136 vlUploadFtMergeProfile.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(mergeProfiles)});
137 vlUploadFtMergeProfile.labelAttr = 'name';
138 vlUploadFtMergeProfile.searchAttr = 'name';
139 vlUploadFtMergeProfile.startup();
141 vlUploadFtMergeProfile2.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(mergeProfiles)});
142 vlUploadFtMergeProfile2.labelAttr = 'name';
143 vlUploadFtMergeProfile2.searchAttr = 'name';
144 vlUploadFtMergeProfile2.startup();
147 // Fetch the bib and authority attribute definitions
148 vlFetchBibAttrDefs(function () { checkInitDone(); });
149 vlFetchAuthAttrDefs(function () { checkInitDone(); });
151 vlRetrieveQueueList('bib', null,
153 allUserBibQueues = list;
154 for(var i = 0; i < allUserBibQueues.length; i++) {
155 if(allUserBibQueues[i].complete() == 'f')
156 userBibQueues.push(allUserBibQueues[i]);
162 vlRetrieveQueueList('auth', null,
164 allUserAuthQueues = list;
165 for(var i = 0; i < allUserAuthQueues.length; i++) {
166 if(allUserAuthQueues[i].complete() == 'f')
167 userAuthQueues.push(allUserAuthQueues[i]);
173 fieldmapper.standardRequest(
174 ['open-ils.permacrud', 'open-ils.permacrud.search.cbs.atomic'],
176 params: [authtoken, {id:{"!=":null}}, {order_by:{cbs:'id'}}],
177 oncomplete : function(r) {
178 vlBibSources = openils.Util.readResponse(r, false, true);
184 var owner = fieldmapper.aou.orgNodeTrail(fieldmapper.aou.findOrgUnit(new openils.User().user.ws_ou()));
185 new openils.PermaCrud().search('viiad',
186 {owner: owner.map(function(org) { return org.id(); })},
188 oncomplete: function(r) {
189 importItemDefs = openils.Util.readResponse(r);
195 new openils.PermaCrud().search('vms',
196 {owner: owner.map(function(org) { return org.id(); })},
198 oncomplete: function(r) {
199 var sets = openils.Util.readResponse(r);
202 if(!matchSets[set.mtype()])
203 matchSets[set.mtype()] = [];
204 matchSets[set.mtype()].push(set);
212 fieldmapper.standardRequest(
213 ['open-ils.actor', 'open-ils.actor.container.retrieve_by_class'],
215 params : [authtoken, new openils.User().user.id(), 'biblio'],
216 oncomplete : function(r) {
217 var buckets = openils.Util.readResponse(r);
218 // only bib buckets are supported
219 matchBuckets.biblio = buckets;
225 new openils.PermaCrud().retrieveAll('ccs',
227 oncomplete: function(r) {
228 var stats = openils.Util.readResponse(r);
230 function(stat){copyStatusCache[stat.id()] = stat});
236 new openils.PermaCrud().search('vibtg',
237 { always_apply : 'f',
238 owner: owner.map(function(org) { return org.id(); })
240 { order_by : {vibtg : ['label']},
242 oncomplete: function(r) {
243 trashGroups = openils.Util.readResponse(r);
245 if (trashGroups.length == 0) {
246 openils.Util.hide('vl-trash-groups-row');
247 openils.Util.hide('vl-trash-groups-row2');
252 dojo.forEach(trashGroups, function(grp) {
253 var sn = fieldmapper.aou.findOrgUnit(grp.owner()).shortname();
255 label : grp.label() + ' (' + sn + ')',
258 vlUploadTrashGroups.addOption(opt);
259 vlUploadTrashGroups2.addOption(opt);
267 orgSettings = fieldmapper.aou.fetchOrgSettingBatch(openils.User.user.ws_ou(), [
270 for(k in orgSettings)
272 orgSettings[k] = orgSettings[k].value;
279 openils.Util.addOnLoad(vlInit);
282 // fetch the bib and authority attribute definitions
284 function vlFetchBibAttrDefs(postcomplete) {
286 fieldmapper.standardRequest(
287 ['open-ils.permacrud', 'open-ils.permacrud.search.vqbrad'],
289 params: [authtoken, {id:{'!=':null}}],
290 onresponse: function(r) {
291 var def = r.recv().content();
292 if(e = openils.Event.parse(def[0]))
294 bibAttrDefs.push(def);
296 oncomplete: function() {
297 bibAttrDefs = bibAttrDefs.sort(
299 if(a.id() > b.id()) return 1;
300 if(a.id() < b.id()) return -1;
310 function vlFetchAuthAttrDefs(postcomplete) {
312 fieldmapper.standardRequest(
313 ['open-ils.permacrud', 'open-ils.permacrud.search.vqarad'],
315 params: [authtoken, {id:{'!=':null}}],
316 onresponse: function(r) {
317 var def = r.recv().content();
318 if(e = openils.Event.parse(def[0]))
320 authAttrDefs.push(def);
322 oncomplete: function() {
323 authAttrDefs = authAttrDefs.sort(
325 if(a.id() > b.id()) return 1;
326 if(a.id() < b.id()) return -1;
336 function vlRetrieveQueueList(type, filter, onload) {
337 type = (type == 'bib') ? type : 'authority';
338 fieldmapper.standardRequest(
339 ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.owner.retrieve.atomic'],
341 params: [authtoken, null, filter],
342 oncomplete: function(r) {
343 var list = r.recv().content();
344 if(e = openils.Event.parse(list[0]))
353 function displayGlobalDiv(id) {
354 for(var i = 0; i < globalDivs.length; i++) {
356 dojo.style(dojo.byId(globalDivs[i]), 'display', 'none');
358 alert('please define div ' + globalDivs[i]);
361 dojo.style(dojo.byId(id),'display','block');
363 openils.Util.removeCSSClass(dojo.byId('vl-menu-marc-export'), 'toolbar_selected');
364 openils.Util.removeCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
365 openils.Util.removeCSSClass(dojo.byId('vl-menu-queue-select'), 'toolbar_selected');
366 openils.Util.removeCSSClass(dojo.byId('vl-menu-attr-editor'), 'toolbar_selected');
367 openils.Util.removeCSSClass(dojo.byId('vl-menu-profile-editor'), 'toolbar_selected');
368 openils.Util.removeCSSClass(dojo.byId('vl-menu-match-set-editor'), 'toolbar_selected');
370 if(dojo.byId('vl-match-set-iframe'))
371 dojo.byId('vl-match-set-editor-div').removeChild(dojo.byId('vl-match-set-iframe'));
374 case 'vl-marc-export-div':
375 openils.Util.addCSSClass(dojo.byId('vl-menu-marc-export'), 'toolbar_selected');
377 case 'vl-marc-upload-div':
378 openils.Util.addCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
380 case 'vl-queue-select-div':
381 openils.Util.addCSSClass(dojo.byId('vl-menu-queue-select'), 'toolbar_selected');
383 case 'vl-attr-editor-div':
384 openils.Util.addCSSClass(dojo.byId('vl-menu-attr-editor'), 'toolbar_selected');
386 case 'vl-profile-editor-div':
387 openils.Util.addCSSClass(dojo.byId('vl-menu-profile-editor'), 'toolbar_selected');
389 case 'vl-item-attr-editor-div':
390 openils.Util.addCSSClass(dojo.byId('vl-menu-import-item-attr-editor'), 'toolbar_selected');
392 case 'vl-match-set-editor-div':
393 openils.Util.addCSSClass(dojo.byId('vl-menu-match-set-editor'), 'toolbar_selected');
398 function runStartupCommands() {
399 openils.Util.hide(dojo.byId('vl-page-loading'));
400 openils.Util.show(dojo.byId('vl-body-wrapper'));
401 currentQueueId = cgi.param('qid');
402 currentType = cgi.param('qtype');
403 dojo.style('vl-nav-bar', 'visibility', 'visible');
405 return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
406 if (cgi.param('page') == 'inspectq')
407 return vlShowQueueSelect();
413 * asynchronously upload a file of MARC records
415 function uploadMARC(onload){
416 dojo.byId('vl-upload-status-count').innerHTML = '0';
417 dojo.byId('vl-ses-input').value = authtoken;
418 displayGlobalDiv('vl-marc-upload-status-div');
419 dojo.io.iframe.send({
423 form: dojo.byId('vl-marc-upload-form'),
424 handle: function(data,ioArgs){
425 var content = data.documentElement.textContent;
432 * Creates a new vandelay queue
434 function createQueue(
435 queueName, type, onload, importDefId, matchSet, matchBucket) {
437 var name = (type=='bib') ? 'bib' : 'authority';
438 var method = 'open-ils.vandelay.'+ name +'_queue.create'
441 if (vlUploadRecordType.getValue().match(/acq/))
444 console.log('record type ' + vlUploadRecordType.getValue());
445 console.log('record type ' + vlUploadRecordType.getValue());
447 fieldmapper.standardRequest(
448 ['open-ils.vandelay', method],
451 authtoken, queueName, null,
452 qType, matchSet, importDefId, matchBucket
454 oncomplete : function(r) {
455 var queue = r.recv().content();
456 if(e = openils.Event.parse(queue))
465 * Tells vandelay to pull a batch of records from the cache and explode them
466 * out into the vandelay tables
468 function processSpool(key, queueId, type, onload) {
469 fieldmapper.standardRequest(
470 ['open-ils.vandelay', 'open-ils.vandelay.'+type+'.process_spool'],
472 params: [authtoken, key, queueId],
473 onresponse : function(r) {
474 var resp = r.recv().content();
475 if(e = openils.Event.parse(resp))
477 dojo.byId('vl-upload-status-count').innerHTML = resp;
479 oncomplete : function(r) {onload();}
484 function vlExportInit() {
487 var qsel = dojo.byId('vl-queue-export-options');
488 qsel.onchange = function(newVal) {
489 var value = qsel.options[qsel.selectedIndex].value;
490 qsel.selectedIndex = 0;
492 if(!confirm('Export as "' + value + '"?')) return; // TODO: i18n
493 retrieveQueuedRecords(
497 exportHandler(value, r);
498 displayGlobalDiv('vl-queue-div');
505 var isel = dojo.byId('vl-item-export-options');
506 isel.onchange = function(newVal) {
507 var value = isel.options[isel.selectedIndex].value;
508 isel.selectedIndex = 0;
510 if(!confirm('Export as "' + value + '"?')) return; // TODO: i18n
512 displayGlobalDiv('vl-generic-progress');
513 var method = 'open-ils.vandelay.import_item.queue.export.' + value + '.atomic';
515 fieldmapper.standardRequest(
516 ['open-ils.vandelay', method],
521 {with_import_error: (vlImportItemsShowErrors.checked) ? 1 : null}
524 oncomplete : function(r) {exportHandler(value, r)}
530 function exportHandler(type, response) {
531 displayGlobalDiv('vl-import-error-div');
533 var content = openils.Util.readResponse(response);
535 if (content==1) { alert('Email sent.'); return; }
538 /* handle .atomic versus non-atomic method calls */
539 content = content.constructor == Array
540 ? content[0].template_output().data()
541 : content.template_output().data();
544 openils.Util.printHtmlString(content);
547 //content = content.replace(/\\t/g,'\t'); // if we really wanted to do .tsv instead
548 openils.XUL.contentToFileSaveDialog(content, null, {
549 defaultString : 'VandelayExport.csv',
550 defaultExtension : '.csv',
552 filterExtension : '*.csv',
557 alert('response = ' + response + '\tcontent:\n' + content);
560 alert('Error exporting data: ' + E);
564 function retrieveQueuedRecords(type, queueId, onload, doExport) {
565 displayGlobalDiv('vl-generic-progress');
567 queuedRecordsMap = {};
568 currentOverlayRecordsMap = {};
569 currentOverlayRecordsMapGid = {};
570 selectableGridRecords = {};
572 if(!type) type = currentType;
573 else currentType = type;
574 if(!queueId) queueId = currentQueueId;
575 else currentQueueId = queueId;
576 if(!onload) onload = handleRetrieveRecords;
578 var method = 'open-ils.vandelay.'+type+'_queue.records.retrieve';
580 if(doExport) method += '.export.' + doExport;
581 if(vlQueueGridShowMatches.checked)
582 method = method.replace('records', 'records.matches');
586 var sel = dojo.byId('vl-queue-display-limit-selector');
587 var limit = parseInt(sel.options[sel.selectedIndex].value);
588 var offset = limit * parseInt(vlQueueDisplayPage.attr('value')-1);
590 var params = [authtoken, queueId, {clear_marc: 1, offset: offset, limit: limit, flesh_import_items:1}];
591 if(vlQueueGridShowNonImport.checked)
592 params[2].non_imported = 1;
594 if(vlQueueGridShowImportErrors.checked)
595 params[2].with_import_error = 1;
597 fieldmapper.standardRequest(
598 ['open-ils.vandelay', method],
601 oncomplete: function(r){
602 if(doExport) return onload(r);
603 var recs = r.recv().content();
604 if(e = openils.Event.parse(recs[0]))
606 for(var i = 0; i < recs.length; i++) {
608 queuedRecords.push(rec);
609 queuedRecordsMap[rec.id()] = rec;
617 function vlLoadMatchUI(recId) {
618 displayGlobalDiv('vl-generic-progress');
619 var queuedRec = queuedRecordsMap[recId];
620 var matches = queuedRec.matches();
622 currentImportRecId = recId;
623 for(var i = 0; i < matches.length; i++)
624 records.push(matches[i].eg_record());
626 var retrieve = ['open-ils.search', 'open-ils.search.biblio.record_entry.slim.retrieve'];
627 var params = [records];
628 if(currentType == 'auth') {
629 retrieve = ['open-ils.pcrud', 'open-ils.pcrud.search.are.atomic'];
630 // retrieve all authority record fields except 'marc' for lightness
631 var fields = fieldmapper.IDL.fmclasses.are.fields
632 .filter(function(f) {return (!f.virtual && f.name != 'marc')})
633 .map(function(f) {return f.name});
634 params = [authtoken, {id : records}, {select : {are : fields}}]
637 fieldmapper.standardRequest(
641 oncomplete: function(r) {
642 var recs = r.recv().content();
643 if(e = openils.Event.parse(recs))
647 displayGlobalDiv('vl-match-div');
648 resetVlMatchGridLayout(currentType);
649 currentMatchedRecords = recs;
650 vlMatchGrid.setStructure(vlMatchGridLayout);
652 // build the data store of records with match information
653 var dataStore = bre.toStoreData(recs, null,
654 {virtualFields:['_id', 'match_score', 'match_quality', 'rec_quality']});
655 dataStore.identifier = '_id';
657 var matchSeenMap = {};
659 for(var i = 0; i < dataStore.items.length; i++) {
660 var item = dataStore.items[i];
661 item._id = i; // just need something unique
662 for(var j = 0; j < matches.length; j++) {
663 var match = matches[j];
664 if(match.eg_record() == item.id && !matchSeenMap[match.id()]) {
665 if(match.match_score)
666 item.match_score = match.match_score();
667 item.match_quality = match.quality();
668 item.rec_quality = queuedRec.quality();
669 matchSeenMap[match.id()] = 1;
675 // now populate the grid
676 vlPopulateMatchGrid(vlMatchGrid, dataStore);
682 function vlPopulateMatchGrid(grid, data) {
683 var store = new dojo.data.ItemFileReadStore({data:data});
684 grid.setStore(store);
688 function showMe(id) {
689 dojo.style(dojo.byId(id), 'display', 'block');
691 function hideMe(id) {
692 dojo.style(dojo.byId(id), 'display', 'none');
696 function vlLoadMARCHtml(recId, inCat, oncomplete) {
697 dijit.byId('vl-marc-html-done-button').onClick = oncomplete;
698 displayGlobalDiv('vl-generic-progress');
700 var params = [recId, 1];
703 hideMe('vl-marc-html-edit-button'); // don't show marc editor button
704 dijit.byId('vl-marc-html-edit-button').onClick = function(){}
705 api = ['open-ils.search', 'open-ils.search.biblio.record.html'];
706 if(currentType == 'auth')
707 api = ['open-ils.search', 'open-ils.search.authority.to_html'];
709 showMe('vl-marc-html-edit-button'); // plug in the marc editor button
710 dijit.byId('vl-marc-html-edit-button').onClick =
711 function() {vlLoadMarcEditor(currentType, recId, oncomplete);};
712 params = [authtoken, recId];
713 api = ['open-ils.vandelay', 'open-ils.vandelay.queued_bib_record.html'];
714 if(currentType == 'auth')
715 api = ['open-ils.vandelay', 'open-ils.vandelay.queued_authority_record.html'];
718 fieldmapper.standardRequest(
722 oncomplete: function(r) {
723 displayGlobalDiv('vl-marc-html-div');
724 var html = r.recv().content();
725 dojo.byId('vl-marc-record-html').innerHTML = html;
733 function getRecMatchesFromAttrCode(rec, attrCode) {
735 var attr = getRecAttrFromCode(rec, attrCode);
736 for(var j = 0; j < rec.matches().length; j++) {
737 var match = rec.matches()[j];
738 if(match.matched_attr() == attr.id())
746 function getRecAttrFromMatch(rec, match) {
747 for(var i = 0; i < rec.attributes().length; i++) {
748 var attr = rec.attributes()[i];
749 if(attr.id() == match.matched_attr())
755 function getRecAttrDefFromAttr(attr, type) {
756 var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
757 for(var i = 0; i < defs.length; i++) {
759 if(def.id() == attr.field())
764 function getRecAttrFromCode(rec, attrCode) {
765 var defId = attrDefMap[currentType][attrCode];
766 var attrs = rec.attributes();
767 for(var i = 0; i < attrs.length; i++) {
769 if(attr.field() == defId)
775 function vlGetViewMatches(rowIdx, item) {
777 var id = this.grid.store.getValue(item, 'id');
778 var rec = queuedRecordsMap[id];
779 if(rec.matches().length > 0)
780 return id + ':' + rec.matches().length;
785 function vlFormatViewMatches(id) {
786 if(id == -1) return '';
787 var chunks = id.split(':');
790 return '<a href="javascript:void(0);" onclick="vlLoadMatchUI(' + id + ');">' + this.name + ' (' + count + ')</a>';
793 function vlGetViewErrors(rowIdx, item) {
795 var id = this.grid.store.getValue(item, 'id');
796 var rec = queuedRecordsMap[id];
797 // id:rec_error:item_import_error_count
799 (rec.import_error() ? 1 : '') + ':' +
800 (typeof rec.import_items == 'function'
801 ? rec.import_items().filter(function(i) {return i.import_error()}).length
808 function vlFormatViewErrors(chunk) {
809 if(chunk == -1) return '';
810 var id = chunk.split(':')[0];
811 var rec = chunk.split(':')[1];
812 var count = chunk.split(':')[2];
815 links += '<a href="javascript:void(0);" onclick="vlLoadErrorUI(' + id + ');">Record</a><br/>'; // TODO I18N
817 links += '<a href="javascript:void(0);" onclick="vlLoadErrorUI(' + id + ');">Items ('+count+')</a>'; // TODO I18N
821 //var vlItemErrorColumnPicker;
822 function vlLoadErrorUI(id) {
824 displayGlobalDiv('vl-import-error-div');
825 openils.Util.hide('vl-import-error-grid-all');
826 openils.Util.show('vl-import-error-record');
828 var rec = queuedRecordsMap[id];
830 dojo.byId('vl-error-id').innerHTML = rec.id();
831 dojo.forEach( // TODO sane authority rec. fields
832 ['title', 'author', 'isbn', 'issn', 'upc'],
834 var attr = getRecAttrFromCode(rec, field);
835 var eid = 'vl-error-' + field;
837 openils.Util.show(dojo.byId(eid).parentNode, 'table-row');
838 dojo.byId(eid).innerHTML = attr.attr_value();
840 openils.Util.hide(dojo.byId(eid).parentNode);
844 var iediv = dojo.byId('vl-error-import-error');
845 var eddiv = dojo.byId('vl-error-error-detail');
846 if(rec.import_error()) {
847 openils.Util.show(iediv.parentNode, 'table-row');
848 openils.Util.show(eddiv.parentNode, 'table-row');
849 iediv.innerHTML = rec.import_error();
850 eddiv.innerHTML = rec.error_detail();
852 openils.Util.hide(iediv.parentNode);
853 openils.Util.hide(eddiv.parentNode);
856 var errorItems = rec.import_items().filter(function(i) {return i.import_error()});
857 if(errorItems.length) {
858 openils.Util.show('vl-import-error-grid-some');
859 storeData = vqbr.toStoreData(errorItems);
860 var store = new dojo.data.ItemFileReadStore({data:storeData});
861 vlImportErrorGrid.setStore(store);
862 vlImportErrorGrid.update();
864 openils.Util.hide('vl-import-error-grid-some');
868 function vlLoadErrorUIAll() {
870 displayGlobalDiv('vl-import-error-div');
871 openils.Util.hide('vl-import-error-grid-some');
872 openils.Util.hide('vl-import-error-record');
873 openils.Util.show('vl-import-error-grid-all');
874 vlAllImportErrorGrid.resetStore();
876 vlImportErrorGrid.displayOffset = 0;
878 vlAllImportErrorGrid.dataLoader = function() {
880 vlAllImportErrorGrid.showLoadProgressIndicator();
882 fieldmapper.standardRequest(
883 ['open-ils.vandelay', 'open-ils.vandelay.import_item.queue.retrieve'],
887 authtoken, currentQueueId, {
888 with_import_error: (vlImportItemsShowErrors.checked) ? 1 : null,
889 offset : vlAllImportErrorGrid.displayOffset,
890 limit : vlAllImportErrorGrid.displayLimit
893 onresponse : function(r) {
894 var item = openils.Util.readResponse(r);
896 vlAllImportErrorGrid.store.newItem(vii.toStoreItem(item));
898 oncomplete : function() {
899 vlAllImportErrorGrid.hideLoadProgressIndicator();
905 vlAllImportErrorGrid.dataLoader();
908 function vlGetOrg(rowIdx, item) {
910 var value = this.grid.store.getValue(item, this.field);
911 if(value) return fieldmapper.aou.findOrgUnit(value).shortname();
915 function vlCopyStatus(rowIdx, item) {
917 var value = this.grid.store.getValue(item, this.field);
918 if(value) return copyStatusCache[value].name();
922 // Note, we don't pre-fetch all copy locations because there could be
923 // a lot of them. Instead, fetch-and-cache on demand.
924 function vlCopyLocation(rowIdx, item) {
926 var value = this.grid.store.getValue(item, this.field);
928 if(!copyLocationCache[value]) {
929 copyLocationCache[value] =
930 new openils.PermaCrud().retrieve('acpl', value);
932 return copyLocationCache[value].name();
938 function vlFormatViewMatchMARC(id) {
939 return '<a href="javascript:void(0);" onclick="vlLoadMARCHtml(' + id + ', true, '+
940 'function(){displayGlobalDiv(\'vl-match-div\');});">' + this.name + '</a>';
943 function getAttrValue(rowIdx, item) {
945 var attrCode = this.field.split('.')[1];
946 var rec = queuedRecordsMap[this.grid.store.getValue(item, 'id')];
947 var attr = getRecAttrFromCode(rec, attrCode);
948 return (attr) ? attr.attr_value() : '';
951 function vlGetDateTimeField(rowIdx, item) {
953 var value = this.grid.store.getValue(item, this.field);
954 if(!value) return '';
955 var date = dojo.date.stamp.fromISOString(value);
956 return dojo.date.locale.format(date, {selector:'date'});
959 function vlGetCreator(rowIdx, item) {
961 var id = this.grid.store.getValue(item, 'creator');
963 return userCache[id].usrname();
964 var user = fieldmapper.standardRequest(
965 ['open-ils.actor', 'open-ils.actor.user.retrieve'], [authtoken, id]);
966 if(e = openils.Event.parse(user))
968 userCache[id] = user;
969 return user.usrname();
972 function vlGetViewMARC(rowIdx, item) {
973 return item && this.grid.store.getValue(item, 'id');
976 function vlFormatViewMARC(id) {
977 return '<a href="javascript:void(0);" onclick="vlLoadMARCHtml(' + id + ', false, '+
978 'function(){displayGlobalDiv(\'vl-queue-div\');});">' + this.name + '</a>';
981 function vlGetOverlayTargetSelector(rowIdx, item) {
983 return this.grid.store.getValue(item, '_id') + ':' + this.grid.store.getValue(item, 'id');
986 function vlFormatOverlayTargetSelector(val) {
988 var parts = val.split(':');
991 var value = '<input type="checkbox" name="vl-overlay-target-RECID" '+
992 'onclick="vlHandleOverlayTargetSelected(ID, GRIDID);" gridid="GRIDID" match="ID"/>';
993 value = value.replace(/GRIDID/g, _id);
994 value = value.replace(/RECID/g, currentImportRecId);
995 value = value.replace(/ID/g, id);
996 if(_id == currentOverlayRecordsMapGid[currentImportRecId])
997 return value.replace('/>', 'checked="checked"/>');
1003 * see if the user has enabled overlays for the current match set and,
1004 * if so, map the current import record to the overlay target.
1006 function vlHandleOverlayTargetSelected(recId, gridId) {
1007 var noneSelected = true;
1008 var checkboxes = dojo.query('[name=vl-overlay-target-'+currentImportRecId+']');
1009 for(var i = 0; i < checkboxes.length; i++) {
1010 var checkbox = checkboxes[i];
1011 var matchRecId = checkbox.getAttribute('match');
1012 var gid = checkbox.getAttribute('gridid');
1013 if(checkbox.checked) {
1014 if(matchRecId == recId && gid == gridId) {
1015 noneSelected = false;
1016 currentOverlayRecordsMap[currentImportRecId] = matchRecId;
1017 currentOverlayRecordsMapGid[currentImportRecId] = gid;
1018 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = true;
1019 dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = 'overlay_selected';
1021 checkbox.checked = false;
1027 delete currentOverlayRecordsMap[currentImportRecId];
1028 delete currentOverlayRecordsMapGid[currentImportRecId];
1029 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = false;
1030 dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = '';
1034 var valLastQueueType = null;
1035 var vlQueueGridLayout = null;
1036 function buildRecordGrid(type) {
1037 displayGlobalDiv('vl-queue-div');
1039 vlBibQueueGrid.canSort = function(col){ if(Math.abs(col) == 1) { return false; } else { return true; } };
1040 vlAuthQueueGrid.canSort = function(col){ if(Math.abs(col) == 1) { return false; } else { return true; } };
1043 openils.Util.show('vl-bib-queue-grid-wrapper');
1044 openils.Util.hide('vl-auth-queue-grid-wrapper');
1045 vlQueueGrid = vlBibQueueGrid;
1046 openils.Util.show('add-to-bucket-action', 'table-row');
1048 openils.Util.show('vl-auth-queue-grid-wrapper');
1049 openils.Util.hide('vl-bib-queue-grid-wrapper');
1050 vlQueueGrid = vlAuthQueueGrid;
1051 openils.Util.hide('add-to-bucket-action');
1055 if(valLastQueueType != type) {
1056 valLastQueueType = type;
1057 vlQueueGridLayout = vlQueueGrid.attr('structure');
1058 var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
1059 attrDefMap[type] = {};
1060 for(var i = 0; i < defs.length; i++) {
1062 attrDefMap[type][def.code()] = def.id();
1064 name:def.description(),
1065 field:'attr.' + def.code(),
1067 selectableColumn:true
1069 vlQueueGridLayout[0].cells[0].push(col);
1073 dojo.forEach(vlQueueGridLayout[0].cells[0],
1075 if(cell.field.match(/^\+/))
1076 cell.nonSelectable=true;
1082 storeData = vqbr.toStoreData(queuedRecords);
1084 storeData = vqar.toStoreData(queuedRecords);
1086 var store = new dojo.data.ItemFileReadStore({data:storeData});
1087 vlQueueGrid.setStore(store);
1089 if(vlQueueGridColumePicker[type]) {
1090 vlQueueGrid.update();
1093 vlQueueGridColumePicker[type] =
1094 new openils.widget.GridColumnPicker(
1095 authtoken, 'vandelay.queue.'+type, vlQueueGrid, vlQueueGridLayout);
1096 vlQueueGridColumePicker[type].load();
1100 function vlQueueGridPrevPage() {
1101 var page = parseInt(vlQueueDisplayPage.getValue());
1102 if(page < 2) return;
1103 vlQueueDisplayPage.setValue(page - 1);
1104 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1107 function vlQueueGridNextPage() {
1108 vlQueueDisplayPage.setValue(parseInt(vlQueueDisplayPage.getValue())+1);
1109 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1112 function vlDeleteQueue(type, queueId, onload) {
1113 fieldmapper.standardRequest(
1114 ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.delete'],
1116 params: [authtoken, queueId],
1117 oncomplete: function(r) {
1118 var resp = r.recv().content();
1119 if(e = openils.Event.parse(resp))
1128 function vlQueueGridDrawSelectBox(rowIdx, item) {
1129 return item && this.grid.store.getValue(item, 'id');
1132 function vlQueueGridFormatSelectBox(id) {
1133 var domId = 'vl-record-list-selected-' + id;
1134 if (id) { selectableGridRecords[domId] = id; }
1135 return "<div><input type='checkbox' id='"+domId+"'/></div>";
1138 function vlSelectAllQueueGridRecords() {
1139 for(var id in selectableGridRecords)
1140 dojo.byId(id).checked = true;
1142 function vlSelectNoQueueGridRecords() {
1143 for(var id in selectableGridRecords)
1144 dojo.byId(id).checked = false;
1146 function vlToggleQueueGridSelect() {
1147 if(dojo.byId('vl-queue-grid-row-selector').checked)
1148 vlSelectAllQueueGridRecords();
1150 vlSelectNoQueueGridRecords();
1153 var handleRetrieveRecords = function() {
1154 buildRecordGrid(currentType);
1156 if (currentType.match(/auth/)) {
1157 openils.Util.hide('vl-queue-summary-import-item-summary');
1159 openils.Util.show('vl-queue-summary-import-item-summary', 'table-body');
1161 vlFetchQueueSummary(currentQueueId, currentType,
1163 dojo.byId('vl-queue-summary-name').innerHTML = summary.queue.name();
1164 dojo.byId('vl-queue-summary-total-count').innerHTML = summary.total +'';
1165 dojo.byId('vl-queue-summary-import-count').innerHTML = summary.imported + '';
1166 dojo.byId('vl-queue-summary-import-item-count').innerHTML = summary.total_items + '';
1167 dojo.byId('vl-queue-summary-import-item-imported-count').innerHTML = summary.total_items_imported + '';
1168 dojo.byId('vl-queue-summary-rec-error-count').innerHTML = summary.rec_import_errors + '';
1169 dojo.byId('vl-queue-summary-item-error-count').innerHTML = summary.item_import_errors + '';
1171 if (dojo.byId('create-bucket-dialog-name')) {
1172 dojo.byId('create-bucket-dialog-name').value = summary.queue.name();
1178 function vlFetchQueueSummary(qId, type, onload) {
1179 fieldmapper.standardRequest(
1180 ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.summary.retrieve'],
1182 params: [authtoken, qId],
1183 oncomplete : function(r) {
1184 var summary = r.recv().content();
1185 if(e = openils.Event.parse(summary))
1187 return onload(summary);
1193 function handleCreateBucket(args) {
1194 var bname = dojo.byId('create-bucket-dialog-name').value;
1197 progressDialog.show(true);
1198 fieldmapper.standardRequest(
1199 ['open-ils.vandelay', 'open-ils.vandelay.bib_queue.to_bucket'],
1201 params : [authtoken, currentQueueId, bname],
1202 oncomplete : function(r) {
1203 progressDialog.hide();
1204 setTimeout(function() {
1205 var resp = openils.Util.readResponse(r);
1206 if (resp.add_count == 0) {
1207 alert(localeStrings.NO_BUCKET_ITEMS);
1210 dojo.string.substitute(
1211 localeStrings.BUCKET_CREATE_SUCCESS,
1212 [resp.add_count, bname, resp.item_count]
1216 }, 200); // give the dialog a chance to hide
1223 var _importCancelHandler;
1224 var _importGoHandler;
1225 function vlHandleQueueItemsAction(action) {
1227 if(_importCancelHandler) dojo.disconnect(_importCancelHandler);
1229 _importCancelHandler = dojo.connect(
1230 queueItemsImportCancelButton,
1233 queueItemsImportDialog.hide();
1237 if(_importGoHandler)
1238 dojo.disconnect(_importGoHandler);
1240 _importGoHandler = dojo.connect(
1241 queueItemsImportGoButton,
1244 queueItemsImportDialog.hide();
1246 // hack to set the widgets the import funcs will be looking at. Reset them below.
1247 vlUploadQueueImportNoMatch.attr('value', vlUploadQueueImportNoMatch2.attr('value'));
1248 vlUploadQueueAutoOverlayExact.attr('value', vlUploadQueueAutoOverlayExact2.attr('value'));
1249 vlUploadQueueAutoOverlay1Match.attr('value', vlUploadQueueAutoOverlay1Match2.attr('value'));
1250 vlUploadMergeProfile.attr('value', vlUploadMergeProfile2.attr('value'));
1251 vlUploadFtMergeProfile.attr('value', vlUploadFtMergeProfile2.attr('value'));
1252 vlUploadQueueAutoOverlayBestMatch.attr('value', vlUploadQueueAutoOverlayBestMatch2.attr('value'));
1253 vlUploadQueueAutoOverlayBestMatchRatio.attr('value', vlUploadQueueAutoOverlayBestMatchRatio2.attr('value'));
1254 vlUploadQueueAutoOverlayInprocessAcqCopies.attr('value', vlUploadQueueAutoOverlayInprocessAcqCopies2.attr('value'));
1256 // attr('value') and various other incantations won't let me set
1257 // the value on the checkedmultiselect, so we temporarily swap
1258 // the dijits instead.
1259 var tmpTrashGroup = vlUploadTrashGroups;
1260 vlUploadTrashGroups = vlUploadTrashGroups2;
1262 if(action == 'import') {
1263 vlImportSelectedRecords();
1264 } else if(action == 'import_all') {
1265 vlImportAllRecords();
1268 // reset the widgets to prevent accidental future actions
1269 vlUploadQueueImportNoMatch.attr('value', false);
1270 vlUploadQueueImportNoMatch2.attr('value', false);
1271 vlUploadQueueAutoOverlayExact.attr('value', false);
1272 vlUploadQueueAutoOverlayExact2.attr('value', false);
1273 vlUploadQueueAutoOverlay1Match.attr('value', false);
1274 vlUploadQueueAutoOverlay1Match2.attr('value', false);
1275 vlUploadMergeProfile.attr('value', '');
1276 vlUploadMergeProfile2.attr('value', '');
1277 vlUploadFtMergeProfile.attr('value', '');
1278 vlUploadFtMergeProfile2.attr('value', '');
1279 vlUploadTrashGroups.attr('value', '');
1280 vlUploadTrashGroups2.attr('value', '');
1281 vlUploadQueueAutoOverlayBestMatch.attr('value', false);
1282 vlUploadQueueAutoOverlayBestMatch2.attr('value', false);
1283 vlUploadQueueAutoOverlayBestMatchRatio.attr('value', '0.0');
1284 vlUploadQueueAutoOverlayBestMatchRatio2.attr('value', '0.0');
1285 vlUploadQueueAutoOverlayInprocessAcqCopies.attr('value', false);
1286 vlUploadQueueAutoOverlayInprocessAcqCopies2.attr('value', false);
1288 // and... swap them back
1289 vlUploadTrashGroups2 = vlUploadTrashGroups;
1290 vlUploadTrashGroups = tmpTrashGroup;
1294 if (currentType.match(/auth/) || trashGroups.length == 0) {
1295 openils.Util.hide('vl-trash-groups-row2');
1297 openils.Util.show('vl-trash-groups-row2', 'table-row');
1300 queueItemsImportDialog.show();
1303 /* import user-selected records */
1304 function vlImportSelectedRecords() {
1307 for(var id in selectableGridRecords) {
1308 if(dojo.byId(id).checked) {
1309 var recId = selectableGridRecords[id];
1310 var rec = queuedRecordsMap[recId];
1311 if(!rec.import_time())
1312 records.push(recId);
1316 vlImportRecordQueue(
1321 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1326 /* import all (non-imported) queue records */
1327 function vlImportAllRecords() {
1328 vlImportRecordQueue(
1333 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1338 /* if recList has values, import only those records */
1339 function vlImportRecordQueue(type, queueId, recList, onload) {
1340 displayGlobalDiv('vl-generic-progress-with-total');
1342 /* set up options */
1343 var options = {overlay_map : currentOverlayRecordsMap};
1345 if(vlUploadQueueImportNoMatch.checked) {
1346 options.import_no_match = true;
1347 vlUploadQueueImportNoMatch.checked = false;
1350 if(vlUploadQueueAutoOverlayExact.checked) {
1351 options.auto_overlay_exact = true;
1352 vlUploadQueueAutoOverlayExact.checked = false;
1355 if(vlUploadQueueAutoOverlayBestMatch.checked) {
1356 options.auto_overlay_best_match = true;
1357 vlUploadQueueAutoOverlayBestMatch.checked = false;
1358 options.match_quality_ratio = vlUploadQueueAutoOverlayBestMatchRatio.attr('value');
1361 if(vlUploadQueueAutoOverlay1Match.checked) {
1362 options.auto_overlay_1match = true;
1363 vlUploadQueueAutoOverlay1Match.checked = false;
1364 options.match_quality_ratio = vlUploadQueueAutoOverlayBestMatchRatio.attr('value');
1367 if(vlUploadQueueAutoOverlayInprocessAcqCopies.checked) {
1368 options.opp_acq_copy_overlay = true; //"opp" for opportunistic
1369 vlUploadQueueAutoOverlayInprocessAcqCopies.checked = false;
1372 var profile = vlUploadMergeProfile.attr('value');
1373 if(profile != null && profile != '') {
1374 options.merge_profile = profile;
1377 var ftprofile = vlUploadFtMergeProfile.attr('value');
1378 if(ftprofile != null && ftprofile != '') {
1379 options.fall_through_merge_profile = ftprofile;
1382 var strip_grps = vlUploadTrashGroups.attr('value');
1383 if (strip_grps != null && strip_grps.length) {
1384 options.strip_field_groups = strip_grps;
1387 /* determine which method we're calling */
1389 var method = 'open-ils.vandelay.bib_queue.import';
1391 method = method.replace('bib', 'auth');
1393 var params = [authtoken, queueId, options];
1395 method = 'open-ils.vandelay.'+currentType+'_record.list.import';
1396 params[1] = recList;
1399 fieldmapper.standardRequest(
1400 ['open-ils.vandelay', method],
1403 onresponse: function(r) {
1404 var resp = r.recv().content();
1405 if(e = openils.Event.parse(resp))
1407 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
1409 oncomplete: function() {onload();}
1416 * Create queue, upload MARC, process spool, load the newly created queue
1418 function batchUpload() {
1419 var queueName = dijit.byId('vl-queue-name').getValue();
1420 currentType = dijit.byId('vl-record-type').getValue();
1422 // could be bib-acq, which makes no sense in most places
1423 if (currentType.match(/bib/)) currentType = 'bib';
1425 var handleProcessSpool = function() {
1427 vlUploadQueueImportNoMatch.checked ||
1428 vlUploadQueueAutoOverlayExact.checked ||
1429 vlUploadQueueAutoOverlay1Match.checked ||
1430 vlUploadQueueAutoOverlayBestMatch.checked ) {
1432 vlImportRecordQueue(
1437 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1441 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1445 var handleUploadMARC = function(key) {
1446 dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');
1447 processSpool(key, currentQueueId, currentType, handleProcessSpool);
1450 var handleCreateQueue = function(queue) {
1451 currentQueueId = queue.id();
1452 uploadMARC(handleUploadMARC);
1455 if(vlUploadQueueSelector.getValue() && !queueName) {
1456 currentQueueId = vlUploadQueueSelector.getValue();
1457 uploadMARC(handleUploadMARC);
1459 createQueue(queueName, currentType, handleCreateQueue,
1460 vlUploadQueueHoldingsImportProfile.attr('value'),
1461 vlUploadQueueMatchSet.attr('value'),
1462 vlUploadQueueMatchBucket.attr('value')
1467 // Inspect Queue no longer uses stores, so put type matching here instead
1468 function vlGetQueueData(type, asStore) {
1474 if(!filter) filter = 'bib';
1475 var bibList = allUserBibQueues.filter(
1477 return (q.queue_type() == filter);
1480 if (!asStore) return bibList;
1481 return vbq.toStoreData(bibList);
1483 if (!asStore) return allUserAuthQueues;
1484 return vaq.toStoreData(allUserAuthQueues);
1488 function vlFleshQueueSelect(selector, type) {
1489 var data = vlGetQueueData(type, true);
1490 selector.store = new dojo.data.ItemFileReadStore({data:data});
1491 selector.setValue(null);
1492 selector.setDisplayedValue('');
1494 selector.setValue(data[0].id());
1496 var qInput = dijit.byId('vl-queue-name');
1498 var selChange = function(val) {
1499 console.log('selector onchange');
1500 // user selected a queue from the selector; clear the input and
1501 // set the item import profile already defined for the queue
1502 var queue = allUserBibQueues.filter(function(q) { return (q.id() == val) })[0];
1504 vlUploadQueueHoldingsImportProfile.attr('value', queue.item_attr_def() || '');
1505 vlUploadQueueHoldingsImportProfile.attr('disabled', true);
1506 vlUploadQueueMatchSet.attr('value', queue.match_set() || '');
1507 vlUploadQueueMatchSet.attr('disabled', true);
1508 vlUploadQueueMatchBucket.attr('value', queue.match_bucket() || '');
1509 vlUploadQueueMatchBucket.attr('disabled', true);
1511 vlUploadQueueHoldingsImportProfile.attr('value', '');
1512 vlUploadQueueHoldingsImportProfile.attr('disabled', false);
1513 vlUploadQueueMatchBucket.attr('value', '');
1514 vlUploadQueueMatchBucket.attr('disabled', false);
1516 dojo.disconnect(qInput._onchange);
1517 qInput.attr('value', '');
1518 qInput._onchange = dojo.connect(qInput, 'onChange', inputChange);
1521 var inputChange = function(val) {
1522 console.log('qinput onchange');
1523 // user entered a new queue name. clear the selector
1524 vlUploadQueueHoldingsImportProfile.attr('disabled', false);
1525 vlUploadQueueMatchSet.attr('disabled', false);
1526 vlUploadQueueMatchBucket.attr('disabled', false);
1527 dojo.disconnect(selector._onchange);
1528 selector.attr('value', '');
1529 selector._onchange = dojo.connect(selector, 'onChange', selChange);
1532 selector._onchange = dojo.connect(selector, 'onChange', selChange);
1533 qInput._onchange = dojo.connect(qInput, 'onChange', inputChange);
1536 function vlUpdateMatchSetSelector(type) {
1537 type = (type.match(/bib/)) ? 'biblio' : 'authority';
1538 vlUploadQueueMatchSet.store =
1539 new dojo.data.ItemFileReadStore({data:vms.toStoreData(matchSets[type])});
1540 // apply default match set
1541 for (var i = 0; i < matchSets[type].length; i++) {
1542 if (matchSets[type][i].id() == orgSettings[DEFAULT_MATCH_SET]) {
1543 vlUploadQueueMatchSet.setValue(matchSets[type][i].id());
1549 function vlUpdateMatchBucketSelector(type) {
1550 type = (type.match(/bib/)) ? 'biblio' : 'authority';
1551 if (type == 'authority') {
1552 vlUploadQueueMatchBucket.attr('value', '');
1553 vlUploadQueueMatchBucket.attr('disabled', true);
1555 vlUploadQueueMatchBucket.attr('disabled', false);
1556 vlUploadQueueMatchBucket.store =
1557 new dojo.data.ItemFileReadStore(
1558 {data:cbreb.toStoreData(matchBuckets[type])});
1562 function vlShowUploadForm() {
1563 displayGlobalDiv('vl-marc-upload-div');
1564 vlFleshQueueSelect(vlUploadQueueSelector, vlUploadRecordType.getValue());
1565 vlUploadSourceSelector.store =
1566 new dojo.data.ItemFileReadStore({data:cbs.toStoreData(vlBibSources, 'source')});
1567 vlUploadSourceSelector.setValue(vlBibSources[0].id());
1568 vlUploadQueueHoldingsImportProfile.store =
1569 new dojo.data.ItemFileReadStore({data:viiad.toStoreData(importItemDefs)});
1570 vlUpdateMatchSetSelector(vlUploadRecordType.getValue());
1571 vlUpdateMatchBucketSelector(vlUploadRecordType.getValue());
1573 if (vlUploadRecordType.attr('value').match(/auth/) || trashGroups.length == 0) {
1574 openils.Util.hide('vl-trash-groups-row');
1576 openils.Util.show('vl-trash-groups-row', 'table-row');
1579 // use ratio from the merge profile if it's set
1581 vlUploadMergeProfile,
1585 var profile = mergeProfiles.filter(function(p) { return (p.id() == val); })[0];
1586 if(profile.lwm_ratio() != null)
1587 vlUploadQueueAutoOverlayBestMatchRatio.attr('value', profile.lwm_ratio()+'');
1591 vlUploadMergeProfile2,
1595 var profile = mergeProfiles.filter(function(p) { return (p.id() == val); })[0];
1596 if(profile.lwm_ratio() != null)
1597 vlUploadQueueAutoOverlayBestMatchRatio2.attr('value', profile.lwm_ratio()+'');
1602 function vlDeleteSelectedQueues() {
1603 var checkboxes = document.getElementById('vlQueueSelectList').getElementsByTagName('input');
1604 var type = vlQueueSelectType.attr('value').replace(/-.*/, '');
1605 for(var i = 0; i < checkboxes.length; i++) {
1606 if(checkboxes[i].getAttribute('name') == 'delete' && checkboxes[i].checked) {
1607 vlDeleteQueue(type, checkboxes[i].getAttribute('value'), function () {});
1610 window.location.reload();
1613 function vlShowQueueSelect() {
1614 displayGlobalDiv('vl-queue-select-div');
1615 var type = vlQueueSelectType.attr('value');
1616 var data = vlGetQueueData(type, false);
1617 type = type.replace(/-.*/, ''); // To remove any sub-typeish info.
1618 var tbody = document.getElementById('vlQueueSelectList');
1622 function vlDeleteSelectedQueues() {
1623 var checkboxes = document.getElementById('vlQueueSelectList').getElementsByTagName('input');
1624 var type = vlQueueSelectType.attr('value').replace(/-.*/, '');
1625 for(var i = 0; i < checkboxes.length; i++) {
1626 if(checkboxes[i].getAttribute('name') == 'delete' && checkboxes[i].checked) {
1627 vlDeleteQueue(type, checkboxes[i].getAttribute('value'), function () {});
1630 window.location.reload();
1633 function vlShowQueueSelect() {
1634 displayGlobalDiv('vl-queue-select-div');
1635 var type = vlQueueSelectType.attr('value');
1636 var data = vlGetQueueData(type, false);
1637 type = type.replace(/-.*/, ''); // To remove any sub-typeish info.
1638 var tbody = document.getElementById('vlQueueSelectList');
1640 while(tbody.firstChild) {
1641 tbody.removeChild(tbody.firstChild);
1644 for(var entry in data) {
1645 var name = data[entry].name();
1646 if(!name.match(/\S/))
1648 var tr = document.createElement('tr');
1649 var td = document.createElement('td');
1650 var checkbox = document.createElement('input');
1651 checkbox.setAttribute('type', 'checkbox');
1652 checkbox.setAttribute('name', 'delete');
1653 checkbox.setAttribute('value', data[entry].id());
1654 td.appendChild(checkbox);
1656 td = document.createElement('td');
1657 var a = document.createElement('a');
1658 a.textContent = name;
1659 a.setAttribute('href', "javascript:retrieveQueuedRecords('" + type + "', " + data[entry].id() + ");");
1662 tbody.appendChild(tr);
1666 function vlShowMatchSetEditor() {
1667 displayGlobalDiv('vl-match-set-editor-div');
1668 dojo.byId('vl-match-set-editor-div').appendChild(
1669 dojo.create('iframe', {
1670 id : 'vl-match-set-iframe',
1671 src : oilsBasePath + '/conify/global/vandelay/match_set',
1672 style : 'width:100%; height:500px; border:none; margin:0px;'
1677 function vlOpenMarcEditWindow(rec, postReloadHTMLHandler) {
1679 To run in Firefox directly, must set signed.applets.codebase_principal_support
1680 to true in about:config
1682 win = window.open('/xul/server/cat/marcedit.xul','','chrome'); // XXX version?
1685 if (currentType == 'bib') {
1691 function onsave(r) {
1692 // after the record is saved, reload the HTML display
1693 var stat = r.recv().content();
1694 if(e = openils.Event.parse(stat))
1696 alert(dojo.byId('vl-marc-edit-complete-label').innerHTML);
1698 vlLoadMARCHtml(rec.id(), false, postReloadHTMLHandler);
1702 record : {marc : rec.marc(), "rtype": type},
1704 label: dojo.byId('vl-marc-edit-save-label').innerHTML,
1705 func: function(xmlString) {
1706 var method = 'open-ils.permacrud.update.' + rec.classname;
1707 rec.marc(xmlString);
1708 fieldmapper.standardRequest(
1709 ['open-ils.permacrud', method],
1711 params: [authtoken, rec],
1717 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
1718 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
1722 function vlLoadMarcEditor(type, recId, postReloadHTMLHandler) {
1723 var method = 'open-ils.permacrud.search.vqbr';
1724 if(currentType != 'bib')
1725 method = method.replace(/vqbr/,'vqar');
1727 fieldmapper.standardRequest(
1728 ['open-ils.permacrud', method],
1730 params: [authtoken, {id : recId}],
1731 oncomplete: function(r) {
1732 var rec = r.recv().content();
1733 if(e = openils.Event.parse(rec))
1735 vlOpenMarcEditWindow(rec, postReloadHTMLHandler);
1743 //------------------------------------------------------------
1744 // attribute editors
1746 // attribute-editor global variables
1748 var ATTR_EDITOR_IN_UPDATE_MODE = false; // true on 'edit', false on 'create'
1749 var ATTR_EDIT_ID = null; // id of current 'edit' attribute
1750 var ATTR_EDIT_GROUP = 'bib'; // bib-attrs or auth-attrs
1752 function vlAttrEditorInit() {
1753 // set up tooltips on the edit form
1754 connectTooltip('attr-editor-tags');
1755 connectTooltip('attr-editor-subfields');
1758 function vlShowAttrEditor() {
1759 displayGlobalDiv('vl-attr-editor-div');
1760 loadAttrEditorGrid();
1761 idHide('vl-generic-progress');
1764 function setAttrEditorGroup(groupName) {
1765 // put us into 'bib'-attr or 'auth'-attr mode.
1766 if (ATTR_EDIT_GROUP != groupName) {
1767 ATTR_EDIT_GROUP = groupName;
1768 loadAttrEditorGrid();
1772 function onAttrEditorOpen() {
1773 // the "bars" have the create/update/cancel/etc. buttons.
1774 var create_bar = document.getElementById('attr-editor-create-bar');
1775 var update_bar = document.getElementById('attr-editor-update-bar');
1776 if (ATTR_EDITOR_IN_UPDATE_MODE) {
1777 update_bar.style.display='table-row';
1778 create_bar.style.display='none';
1779 // hide the dropdown-button
1780 idStyle('vl-create-attr-editor-button', 'visibility', 'hidden');
1782 dijit.byId('attr-editor-dialog').reset();
1783 create_bar.style.display='table-row';
1784 update_bar.style.display='none';
1788 function onAttrEditorClose() {
1789 // reset the form to a "create" form. (We may have borrowed it for editing.)
1790 ATTR_EDITOR_IN_UPDATE_MODE = false;
1791 // show the dropdown-button
1792 idStyle('vl-create-attr-editor-button', 'visibility', 'visible');
1795 function loadAttrEditorGrid() {
1796 var _data = (ATTR_EDIT_GROUP == 'auth') ?
1797 vqarad.toStoreData(authAttrDefs) : vqbrad.toStoreData(bibAttrDefs) ;
1799 var store = new dojo.data.ItemFileReadStore({data:_data});
1800 attrEditorGrid.setStore(store);
1801 attrEditorGrid.onRowDblClick = onAttrEditorClick;
1802 attrEditorGrid.update();
1805 function attrGridGetTag(n, item) {
1806 // grid helper: return the tags from the row's xpath column.
1807 return item && xpathParser.parse(this.grid.store.getValue(item, 'xpath')).tags;
1810 function attrGridGetSubfield(n, item) {
1811 // grid helper: return the subfields from the row's xpath column.
1812 return item && xpathParser.parse(this.grid.store.getValue(item, 'xpath')).subfields;
1815 function onAttrEditorClick() {
1816 var row = this.getItem(this.focus.rowIndex);
1817 ATTR_EDIT_ID = this.store.getValue(row, 'id');
1818 ATTR_EDITOR_IN_UPDATE_MODE = true;
1820 // populate the popup editor.
1821 dijit.byId('attr-editor-code').attr('value', this.store.getValue(row, 'code'));
1822 dijit.byId('attr-editor-description').attr('value', this.store.getValue(row, 'description'));
1823 var parsed_xpath = xpathParser.parse(this.store.getValue(row, 'xpath'));
1824 dijit.byId('attr-editor-tags').attr('value', parsed_xpath.tags);
1825 dijit.byId('attr-editor-subfields').attr('value', parsed_xpath.subfields);
1826 dijit.byId('attr-editor-xpath').attr('value', this.store.getValue(row, 'xpath'));
1827 dijit.byId('attr-editor-remove').attr('value', this.store.getValue(row, 'remove'));
1829 // set up UI for editing
1830 dojo.byId('vl-create-attr-editor-button').click();
1833 function vlSaveAttrDefinition(data) {
1834 idHide('vl-attr-editor-div');
1835 idShow('vl-generic-progress');
1837 data.id = ATTR_EDIT_ID;
1839 // this ought to honour custom xpaths, but overwrite xpaths
1840 // derived from tags/subfields.
1841 if (data.xpath == '' || looksLikeDerivedXpath(data.xpath)) {
1842 var _xpath = tagAndSubFieldsToXpath(data.tag, data.subfield);
1843 data.xpath = _xpath;
1846 // build up our permacrud params. Key variables here are
1847 // "create or update" and "bib or auth".
1849 var isAuth = (ATTR_EDIT_GROUP == 'auth');
1850 var isCreate = (ATTR_EDIT_ID == null);
1851 var rad = isAuth ? new vqarad() : new vqbrad() ;
1852 var method = 'open-ils.permacrud' + (isCreate ? '.create.' : '.update.')
1853 + (isAuth ? 'vqarad' : 'vqbrad');
1854 var _data = rad.fromStoreItem(data);
1858 fieldmapper.standardRequest(
1859 ['open-ils.permacrud', method],
1861 params: [authtoken, _data ],
1862 onresponse: function(r) { },
1863 oncomplete: function(r) {
1864 attrEditorFetchAttrDefs(vlShowAttrEditor);
1865 ATTR_EDIT_ID = null;
1867 onerror: function(r) {
1868 alert('vlSaveAttrDefinition comms error: ' + r);
1874 function attrEditorFetchAttrDefs(callback) {
1875 var fn = (ATTR_EDIT_GROUP == 'auth') ? vlFetchAuthAttrDefs : vlFetchBibAttrDefs;
1876 return fn(callback);
1879 function vlAttrDelete() {
1880 idHide('vl-attr-editor-div');
1881 idShow('vl-generic-progress');
1883 var isAuth = (ATTR_EDIT_GROUP == 'auth');
1884 var method = 'open-ils.permacrud.delete.' + (isAuth ? 'vqarad' : 'vqbrad');
1885 var rad = isAuth ? new vqarad() : new vqbrad() ;
1886 fieldmapper.standardRequest(
1887 ['open-ils.permacrud', method],
1889 params: [authtoken, rad.fromHash({ id : ATTR_EDIT_ID }), ],
1890 oncomplete: function() {
1891 dijit.byId('attr-editor-dialog').onCancel(); // close the dialog
1892 attrEditorFetchAttrDefs(vlShowAttrEditor);
1893 ATTR_EDIT_ID = null;
1895 onerror: function(r) {
1896 alert('vlAttrDelete comms error: ' + r);
1902 // ------------------------------------------------------------
1903 // utilities for attribute editors
1905 // dom utilities (maybe dojo does these, and these should be replaced)
1907 function idStyle(obId, k, v) { document.getElementById(obId).style[k] = v; }
1908 function idShow(obId) { idStyle(obId, 'display', 'block'); }
1909 function idHide(obId) { idStyle(obId, 'display' , 'none'); }
1911 function connectTooltip(fieldId) {
1912 // Given an element id, look up a tooltip element in the doc (same
1913 // id with a '-tip' suffix) and associate the two. Maybe dojo has
1914 // a better way to do this?
1915 var fld = dojo.byId(fieldId);
1916 var tip = dojo.byId(fieldId + '-tip');
1917 dojo.connect(fld, 'onfocus', function(evt) {
1918 dijit.showTooltip(tip.innerHTML, fld, ['below', 'after']); });
1919 dojo.connect(fld, 'onblur', function(evt) { dijit.hideTooltip(fld); });
1924 var xpathParser = new openils.MarcXPathParser();
1926 function tagAndSubFieldsToXpath(tags, subfields) {
1927 // given tags, and subfields, build up an XPath.
1930 'tags':tags.match(/[\d]+/g),
1931 'subfields':subfields.match(/[a-zA-z]/g) };
1932 return xpathParser.compile(parts);
1934 return {'parts':null, 'tags':null, 'error':err};
1938 function looksLikeDerivedXpath(path) {
1939 // Does this path look like it was derived from tags and subfields?
1940 var parsed = xpathParser.parse(path);
1941 if (parsed.tags == null)
1943 var compiled = xpathParser.compile(parsed);
1944 return (path == compiled);
1947 // amazing xpath-util unit-tests
1948 if (!looksLikeDerivedXpath('//*[@tag="901"]/*[@code="c"]')) alert('vandelay xpath-utility error');
1949 if ( looksLikeDerivedXpath('ba-boo-ba-boo!')) alert('vandelay xpath-utility error');
1953 var profileContextOrg
1954 function vlShowProfileEditor() {
1955 displayGlobalDiv('vl-profile-editor-div');
1958 var connect = function() {
1959 dojo.connect(profileContextOrgSelector, 'onChange',
1961 profileContextOrg = this.attr('value');
1968 new openils.User().buildPermOrgSelector(
1969 'ADMIN_MERGE_PROFILE', profileContextOrgSelector, null, connect);
1972 function buildProfileGrid() {
1974 if(profileContextOrg == null)
1975 profileContextOrg = openils.User.user.ws_ou();
1978 {order_by : {vmp : 'name'}},
1979 {owner : fieldmapper.aou.fullPath(profileContextOrg, true)}
1983 /* --- Import Item Attr Grid --------------- */
1985 var itemAttrContextOrg;
1986 var itemAttrGridFirstTime = true;
1987 function vlShowImportItemAttrEditor() {
1988 displayGlobalDiv('vl-item-attr-editor-div');
1990 if (itemAttrGridFirstTime) {
1992 buildImportItemAttrGrid();
1994 var connect = function() {
1995 dojo.connect(itemAttrContextOrgSelector, 'onChange',
1997 itemAttrContextOrg = this.attr('value');
1998 itemAttrGrid.resetStore();
1999 buildImportItemAttrGrid();
2004 new openils.User().buildPermOrgSelector(
2005 'ADMIN_IMPORT_ITEM_ATTR_DEF',
2006 itemAttrContextOrgSelector, null, connect);
2008 itemAttrGridFirstTime = false;
2012 function buildImportItemAttrGrid() {
2014 if(itemAttrContextOrg == null)
2015 itemAttrContextOrg = openils.User.user.ws_ou();
2017 itemAttrGrid.loadAll(
2018 {order_by : {viiad : 'name'}},
2019 {owner : fieldmapper.aou.fullPath(itemAttrContextOrg, true)}