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');
50 'vl-generic-progress',
51 'vl-generic-progress-with-total',
56 'vl-queue-select-div',
57 'vl-marc-upload-status-div',
60 'vl-profile-editor-div',
61 'vl-item-attr-editor-div',
66 var VANDELAY_URL = '/vandelay-upload';
68 var authAttrDefs = [];
69 var queuedRecords = [];
70 var queuedRecordsMap = {};
71 var bibAttrsFetched = false;
72 var authAttrsFetched = false;
73 var attrDefMap = {}; // maps attr def code names to attr def ids
75 var currentQueueId = null;
77 var currentMatchedRecords; // set of loaded matched bib records
78 var currentOverlayRecordsMap; // map of import record to overlay record
79 var currentOverlayRecordsMapGid; // map of import record to overlay record grid id
80 var currentImportRecId; // when analyzing matches, this is the current import record
81 var userBibQueues = []; // only non-complete queues
82 var userAuthQueues = []; // only non-complete queues
84 var allUserAuthQueues;
85 var selectableGridRecords;
86 var cgi = new openils.CGI();
87 var vlQueueGridColumePicker = {};
88 var vlBibSources = [];
89 var importItemDefs = [];
91 var mergeProfiles = [];
92 var copyStatusCache = {};
93 var copyLocationCache = {};
101 dojo.requireLocalization("openils.vandelay", "vandelay");
102 localeStrings = dojo.i18n.getLocalization("openils.vandelay", "vandelay");
104 authtoken = openils.User.authtoken;
105 var initNeeded = 8; // how many async responses do we need before we're init'd
106 var initCount = 0; // how many async reponses we've received
108 openils.Util.registerEnterHandler(
109 vlQueueDisplayPage.domNode, function(){retrieveQueuedRecords();});
110 openils.Util.addCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
112 function checkInitDone() {
114 if(initCount == initNeeded)
115 runStartupCommands();
118 mergeProfiles = new openils.PermaCrud().retrieveAll('vmp');
119 vlUploadMergeProfile.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(mergeProfiles)});
120 vlUploadMergeProfile.labelAttr = 'name';
121 vlUploadMergeProfile.searchAttr = 'name';
122 vlUploadMergeProfile.startup();
124 vlUploadMergeProfile2.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(mergeProfiles)});
125 vlUploadMergeProfile2.labelAttr = 'name';
126 vlUploadMergeProfile2.searchAttr = 'name';
127 vlUploadMergeProfile2.startup();
129 vlUploadFtMergeProfile.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(mergeProfiles)});
130 vlUploadFtMergeProfile.labelAttr = 'name';
131 vlUploadFtMergeProfile.searchAttr = 'name';
132 vlUploadFtMergeProfile.startup();
134 vlUploadFtMergeProfile2.store = new dojo.data.ItemFileReadStore({data:fieldmapper.vmp.toStoreData(mergeProfiles)});
135 vlUploadFtMergeProfile2.labelAttr = 'name';
136 vlUploadFtMergeProfile2.searchAttr = 'name';
137 vlUploadFtMergeProfile2.startup();
140 // Fetch the bib and authority attribute definitions
141 vlFetchBibAttrDefs(function () { checkInitDone(); });
142 vlFetchAuthAttrDefs(function () { checkInitDone(); });
144 vlRetrieveQueueList('bib', null,
146 allUserBibQueues = list;
147 for(var i = 0; i < allUserBibQueues.length; i++) {
148 if(allUserBibQueues[i].complete() == 'f')
149 userBibQueues.push(allUserBibQueues[i]);
155 vlRetrieveQueueList('auth', null,
157 allUserAuthQueues = list;
158 for(var i = 0; i < allUserAuthQueues.length; i++) {
159 if(allUserAuthQueues[i].complete() == 'f')
160 userAuthQueues.push(allUserAuthQueues[i]);
166 fieldmapper.standardRequest(
167 ['open-ils.permacrud', 'open-ils.permacrud.search.cbs.atomic'],
169 params: [authtoken, {id:{"!=":null}}, {order_by:{cbs:'id'}}],
170 oncomplete : function(r) {
171 vlBibSources = openils.Util.readResponse(r, false, true);
177 var owner = fieldmapper.aou.orgNodeTrail(fieldmapper.aou.findOrgUnit(new openils.User().user.ws_ou()));
178 new openils.PermaCrud().search('viiad',
179 {owner: owner.map(function(org) { return org.id(); })},
181 oncomplete: function(r) {
182 importItemDefs = openils.Util.readResponse(r);
188 new openils.PermaCrud().search('vms',
189 {owner: owner.map(function(org) { return org.id(); })},
191 oncomplete: function(r) {
192 var sets = openils.Util.readResponse(r);
195 if(!matchSets[set.mtype()])
196 matchSets[set.mtype()] = [];
197 matchSets[set.mtype()].push(set);
205 new openils.PermaCrud().retrieveAll('ccs',
207 oncomplete: function(r) {
208 var stats = openils.Util.readResponse(r);
209 dojo.forEach(stats, function(stat){copyStatusCache[stat.id()] = stat});
220 openils.Util.addOnLoad(vlInit);
223 // fetch the bib and authority attribute definitions
225 function vlFetchBibAttrDefs(postcomplete) {
227 fieldmapper.standardRequest(
228 ['open-ils.permacrud', 'open-ils.permacrud.search.vqbrad'],
230 params: [authtoken, {id:{'!=':null}}],
231 onresponse: function(r) {
232 var def = r.recv().content();
233 if(e = openils.Event.parse(def[0]))
235 bibAttrDefs.push(def);
237 oncomplete: function() {
238 bibAttrDefs = bibAttrDefs.sort(
240 if(a.id() > b.id()) return 1;
241 if(a.id() < b.id()) return -1;
251 function vlFetchAuthAttrDefs(postcomplete) {
253 fieldmapper.standardRequest(
254 ['open-ils.permacrud', 'open-ils.permacrud.search.vqarad'],
256 params: [authtoken, {id:{'!=':null}}],
257 onresponse: function(r) {
258 var def = r.recv().content();
259 if(e = openils.Event.parse(def[0]))
261 authAttrDefs.push(def);
263 oncomplete: function() {
264 authAttrDefs = authAttrDefs.sort(
266 if(a.id() > b.id()) return 1;
267 if(a.id() < b.id()) return -1;
277 function vlRetrieveQueueList(type, filter, onload) {
278 type = (type == 'bib') ? type : 'authority';
279 fieldmapper.standardRequest(
280 ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.owner.retrieve.atomic'],
282 params: [authtoken, null, filter],
283 oncomplete: function(r) {
284 var list = r.recv().content();
285 if(e = openils.Event.parse(list[0]))
294 function displayGlobalDiv(id) {
295 for(var i = 0; i < globalDivs.length; i++) {
297 dojo.style(dojo.byId(globalDivs[i]), 'display', 'none');
299 alert('please define div ' + globalDivs[i]);
302 dojo.style(dojo.byId(id),'display','block');
304 openils.Util.removeCSSClass(dojo.byId('vl-menu-marc-export'), 'toolbar_selected');
305 openils.Util.removeCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
306 openils.Util.removeCSSClass(dojo.byId('vl-menu-queue-select'), 'toolbar_selected');
307 openils.Util.removeCSSClass(dojo.byId('vl-menu-attr-editor'), 'toolbar_selected');
308 openils.Util.removeCSSClass(dojo.byId('vl-menu-profile-editor'), 'toolbar_selected');
309 openils.Util.removeCSSClass(dojo.byId('vl-menu-match-set-editor'), 'toolbar_selected');
311 if(dojo.byId('vl-match-set-iframe'))
312 dojo.byId('vl-match-set-editor-div').removeChild(dojo.byId('vl-match-set-iframe'));
315 case 'vl-marc-export-div':
316 openils.Util.addCSSClass(dojo.byId('vl-menu-marc-export'), 'toolbar_selected');
318 case 'vl-marc-upload-div':
319 openils.Util.addCSSClass(dojo.byId('vl-menu-marc-upload'), 'toolbar_selected');
321 case 'vl-queue-select-div':
322 openils.Util.addCSSClass(dojo.byId('vl-menu-queue-select'), 'toolbar_selected');
324 case 'vl-attr-editor-div':
325 openils.Util.addCSSClass(dojo.byId('vl-menu-attr-editor'), 'toolbar_selected');
327 case 'vl-profile-editor-div':
328 openils.Util.addCSSClass(dojo.byId('vl-menu-profile-editor'), 'toolbar_selected');
330 case 'vl-item-attr-editor-div':
331 openils.Util.addCSSClass(dojo.byId('vl-menu-import-item-attr-editor'), 'toolbar_selected');
333 case 'vl-match-set-editor-div':
334 openils.Util.addCSSClass(dojo.byId('vl-menu-match-set-editor'), 'toolbar_selected');
339 function runStartupCommands() {
340 openils.Util.hide(dojo.byId('vl-page-loading'));
341 openils.Util.show(dojo.byId('vl-body-wrapper'));
342 currentQueueId = cgi.param('qid');
343 currentType = cgi.param('qtype');
344 dojo.style('vl-nav-bar', 'visibility', 'visible');
346 return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
347 if (cgi.param('page') == 'inspectq')
348 return vlShowQueueSelect();
354 * asynchronously upload a file of MARC records
356 function uploadMARC(onload){
357 dojo.byId('vl-upload-status-count').innerHTML = '0';
358 dojo.byId('vl-ses-input').value = authtoken;
359 displayGlobalDiv('vl-marc-upload-status-div');
360 dojo.io.iframe.send({
364 form: dojo.byId('vl-marc-upload-form'),
365 handle: function(data,ioArgs){
366 var content = data.documentElement.textContent;
373 * Creates a new vandelay queue
375 function createQueue(queueName, type, onload, importDefId, matchSet) {
376 var name = (type=='bib') ? 'bib' : 'authority';
377 var method = 'open-ils.vandelay.'+ name +'_queue.create'
380 if (vlUploadRecordType.getValue().match(/acq/))
383 console.log('record type ' + vlUploadRecordType.getValue());
384 console.log('record type ' + vlUploadRecordType.getValue());
386 fieldmapper.standardRequest(
387 ['open-ils.vandelay', method],
389 params: [authtoken, queueName, null, qType, matchSet, importDefId],
390 oncomplete : function(r) {
391 var queue = r.recv().content();
392 if(e = openils.Event.parse(queue))
401 * Tells vandelay to pull a batch of records from the cache and explode them
402 * out into the vandelay tables
404 function processSpool(key, queueId, type, onload) {
405 fieldmapper.standardRequest(
406 ['open-ils.vandelay', 'open-ils.vandelay.'+type+'.process_spool'],
408 params: [authtoken, key, queueId],
409 onresponse : function(r) {
410 var resp = r.recv().content();
411 if(e = openils.Event.parse(resp))
413 dojo.byId('vl-upload-status-count').innerHTML = resp;
415 oncomplete : function(r) {onload();}
420 function vlExportInit() {
423 var qsel = dojo.byId('vl-queue-export-options');
424 qsel.onchange = function(newVal) {
425 var value = qsel.options[qsel.selectedIndex].value;
426 qsel.selectedIndex = 0;
428 if(!confirm('Export as "' + value + '"?')) return; // TODO: i18n
429 retrieveQueuedRecords(
433 exportHandler(value, r);
434 displayGlobalDiv('vl-queue-div');
441 var isel = dojo.byId('vl-item-export-options');
442 isel.onchange = function(newVal) {
443 var value = isel.options[isel.selectedIndex].value;
444 isel.selectedIndex = 0;
446 if(!confirm('Export as "' + value + '"?')) return; // TODO: i18n
448 displayGlobalDiv('vl-generic-progress');
449 var method = 'open-ils.vandelay.import_item.queue.export.' + value + '.atomic';
451 fieldmapper.standardRequest(
452 ['open-ils.vandelay', method],
457 {with_import_error: (vlImportItemsShowErrors.checked) ? 1 : null}
460 oncomplete : function(r) {exportHandler(value, r)}
466 function exportHandler(type, response) {
467 displayGlobalDiv('vl-import-error-div');
469 var content = openils.Util.readResponse(response);
471 if (content==1) { alert('Email sent.'); return; }
474 /* handle .atomic versus non-atomic method calls */
475 content = content.constructor == Array
476 ? content[0].template_output().data()
477 : content.template_output().data();
480 openils.Util.printHtmlString(content);
483 //content = content.replace(/\\t/g,'\t'); // if we really wanted to do .tsv instead
484 openils.XUL.contentToFileSaveDialog(content, null, {
485 defaultString : 'VandelayExport.csv',
486 defaultExtension : '.csv',
488 filterExtension : '*.csv',
493 alert('response = ' + response + '\tcontent:\n' + content);
496 alert('Error exporting data: ' + E);
500 function retrieveQueuedRecords(type, queueId, onload, doExport) {
501 displayGlobalDiv('vl-generic-progress');
503 queuedRecordsMap = {};
504 currentOverlayRecordsMap = {};
505 currentOverlayRecordsMapGid = {};
506 selectableGridRecords = {};
508 if(!type) type = currentType;
509 else currentType = type;
510 if(!queueId) queueId = currentQueueId;
511 else currentQueueId = queueId;
512 if(!onload) onload = handleRetrieveRecords;
514 var method = 'open-ils.vandelay.'+type+'_queue.records.retrieve';
516 if(doExport) method += '.export.' + doExport;
517 if(vlQueueGridShowMatches.checked)
518 method = method.replace('records', 'records.matches');
522 var sel = dojo.byId('vl-queue-display-limit-selector');
523 var limit = parseInt(sel.options[sel.selectedIndex].value);
524 var offset = limit * parseInt(vlQueueDisplayPage.attr('value')-1);
526 var params = [authtoken, queueId, {clear_marc: 1, offset: offset, limit: limit, flesh_import_items:1}];
527 if(vlQueueGridShowNonImport.checked)
528 params[2].non_imported = 1;
530 if(vlQueueGridShowImportErrors.checked)
531 params[2].with_import_error = 1;
533 fieldmapper.standardRequest(
534 ['open-ils.vandelay', method],
537 oncomplete: function(r){
538 if(doExport) return onload(r);
539 var recs = r.recv().content();
540 if(e = openils.Event.parse(recs[0]))
542 for(var i = 0; i < recs.length; i++) {
544 queuedRecords.push(rec);
545 queuedRecordsMap[rec.id()] = rec;
553 function vlLoadMatchUI(recId) {
554 displayGlobalDiv('vl-generic-progress');
555 var queuedRec = queuedRecordsMap[recId];
556 var matches = queuedRec.matches();
558 currentImportRecId = recId;
559 for(var i = 0; i < matches.length; i++)
560 records.push(matches[i].eg_record());
562 var retrieve = ['open-ils.search', 'open-ils.search.biblio.record_entry.slim.retrieve'];
563 var params = [records];
564 if(currentType == 'auth') {
565 retrieve = ['open-ils.cat', 'open-ils.cat.authority.record.retrieve'];
566 params = [authtoken, records, {clear_marc:1}];
569 fieldmapper.standardRequest(
573 oncomplete: function(r) {
574 var recs = r.recv().content();
575 if(e = openils.Event.parse(recs))
579 displayGlobalDiv('vl-match-div');
580 resetVlMatchGridLayout();
581 currentMatchedRecords = recs;
582 vlMatchGrid.setStructure(vlMatchGridLayout);
584 // build the data store of records with match information
585 var dataStore = bre.toStoreData(recs, null,
586 {virtualFields:['_id', 'match_score', 'match_quality', 'rec_quality']});
587 dataStore.identifier = '_id';
589 var matchSeenMap = {};
591 for(var i = 0; i < dataStore.items.length; i++) {
592 var item = dataStore.items[i];
593 item._id = i; // just need something unique
594 for(var j = 0; j < matches.length; j++) {
595 var match = matches[j];
596 if(match.eg_record() == item.id && !matchSeenMap[match.id()]) {
597 if(match.match_score)
598 item.match_score = match.match_score();
599 item.match_quality = match.quality();
600 item.rec_quality = queuedRec.quality();
601 matchSeenMap[match.id()] = 1;
607 // now populate the grid
608 vlPopulateMatchGrid(vlMatchGrid, dataStore);
614 function vlPopulateMatchGrid(grid, data) {
615 var store = new dojo.data.ItemFileReadStore({data:data});
616 grid.setStore(store);
620 function showMe(id) {
621 dojo.style(dojo.byId(id), 'display', 'block');
623 function hideMe(id) {
624 dojo.style(dojo.byId(id), 'display', 'none');
628 function vlLoadMARCHtml(recId, inCat, oncomplete) {
629 dijit.byId('vl-marc-html-done-button').onClick = oncomplete;
630 displayGlobalDiv('vl-generic-progress');
632 var params = [recId, 1];
635 hideMe('vl-marc-html-edit-button'); // don't show marc editor button
636 dijit.byId('vl-marc-html-edit-button').onClick = function(){}
637 api = ['open-ils.search', 'open-ils.search.biblio.record.html'];
638 if(currentType == 'auth')
639 api = ['open-ils.search', 'open-ils.search.authority.to_html'];
641 showMe('vl-marc-html-edit-button'); // plug in the marc editor button
642 dijit.byId('vl-marc-html-edit-button').onClick =
643 function() {vlLoadMarcEditor(currentType, recId, oncomplete);};
644 params = [authtoken, recId];
645 api = ['open-ils.vandelay', 'open-ils.vandelay.queued_bib_record.html'];
646 if(currentType == 'auth')
647 api = ['open-ils.vandelay', 'open-ils.vandelay.queued_authority_record.html'];
650 fieldmapper.standardRequest(
654 oncomplete: function(r) {
655 displayGlobalDiv('vl-marc-html-div');
656 var html = r.recv().content();
657 dojo.byId('vl-marc-record-html').innerHTML = html;
665 function getRecMatchesFromAttrCode(rec, attrCode) {
667 var attr = getRecAttrFromCode(rec, attrCode);
668 for(var j = 0; j < rec.matches().length; j++) {
669 var match = rec.matches()[j];
670 if(match.matched_attr() == attr.id())
678 function getRecAttrFromMatch(rec, match) {
679 for(var i = 0; i < rec.attributes().length; i++) {
680 var attr = rec.attributes()[i];
681 if(attr.id() == match.matched_attr())
687 function getRecAttrDefFromAttr(attr, type) {
688 var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
689 for(var i = 0; i < defs.length; i++) {
691 if(def.id() == attr.field())
696 function getRecAttrFromCode(rec, attrCode) {
697 var defId = attrDefMap[currentType][attrCode];
698 var attrs = rec.attributes();
699 for(var i = 0; i < attrs.length; i++) {
701 if(attr.field() == defId)
707 function vlGetViewMatches(rowIdx, item) {
709 var id = this.grid.store.getValue(item, 'id');
710 var rec = queuedRecordsMap[id];
711 if(rec.matches().length > 0)
712 return id + ':' + rec.matches().length;
717 function vlFormatViewMatches(id) {
718 if(id == -1) return '';
719 var chunks = id.split(':');
722 return '<a href="javascript:void(0);" onclick="vlLoadMatchUI(' + id + ');">' + this.name + ' (' + count + ')</a>';
725 function vlGetViewErrors(rowIdx, item) {
727 var id = this.grid.store.getValue(item, 'id');
728 var rec = queuedRecordsMap[id];
729 // id:rec_error:item_import_error_count
731 (rec.import_error() ? 1 : '') + ':' +
732 (typeof rec.import_items == 'function'
733 ? rec.import_items().filter(function(i) {return i.import_error()}).length
740 function vlFormatViewErrors(chunk) {
741 if(chunk == -1) return '';
742 var id = chunk.split(':')[0];
743 var rec = chunk.split(':')[1];
744 var count = chunk.split(':')[2];
747 links += '<a href="javascript:void(0);" onclick="vlLoadErrorUI(' + id + ');">Record</a><br/>'; // TODO I18N
749 links += '<a href="javascript:void(0);" onclick="vlLoadErrorUI(' + id + ');">Items ('+count+')</a>'; // TODO I18N
753 //var vlItemErrorColumnPicker;
754 function vlLoadErrorUI(id) {
756 displayGlobalDiv('vl-import-error-div');
757 openils.Util.hide('vl-import-error-grid-all');
758 openils.Util.show('vl-import-error-record');
760 var rec = queuedRecordsMap[id];
762 dojo.byId('vl-error-id').innerHTML = rec.id();
763 dojo.forEach( // TODO sane authority rec. fields
764 ['title', 'author', 'isbn', 'issn', 'upc'],
766 var attr = getRecAttrFromCode(rec, field);
767 var eid = 'vl-error-' + field;
769 openils.Util.show(dojo.byId(eid).parentNode, 'table-row');
770 dojo.byId(eid).innerHTML = attr.attr_value();
772 openils.Util.hide(dojo.byId(eid).parentNode);
776 var iediv = dojo.byId('vl-error-import-error');
777 var eddiv = dojo.byId('vl-error-error-detail');
778 if(rec.import_error()) {
779 openils.Util.show(iediv.parentNode, 'table-row');
780 openils.Util.show(eddiv.parentNode, 'table-row');
781 iediv.innerHTML = rec.import_error();
782 eddiv.innerHTML = rec.error_detail();
784 openils.Util.hide(iediv.parentNode);
785 openils.Util.hide(eddiv.parentNode);
788 var errorItems = rec.import_items().filter(function(i) {return i.import_error()});
789 if(errorItems.length) {
790 openils.Util.show('vl-import-error-grid-some');
791 storeData = vqbr.toStoreData(errorItems);
792 var store = new dojo.data.ItemFileReadStore({data:storeData});
793 vlImportErrorGrid.setStore(store);
794 vlImportErrorGrid.update();
796 openils.Util.hide('vl-import-error-grid-some');
800 function vlLoadErrorUIAll() {
802 displayGlobalDiv('vl-import-error-div');
803 openils.Util.hide('vl-import-error-grid-some');
804 openils.Util.hide('vl-import-error-record');
805 openils.Util.show('vl-import-error-grid-all');
806 vlAllImportErrorGrid.resetStore();
808 vlImportErrorGrid.displayOffset = 0;
810 vlAllImportErrorGrid.dataLoader = function() {
812 vlAllImportErrorGrid.showLoadProgressIndicator();
814 fieldmapper.standardRequest(
815 ['open-ils.vandelay', 'open-ils.vandelay.import_item.queue.retrieve'],
819 authtoken, currentQueueId, {
820 with_import_error: (vlImportItemsShowErrors.checked) ? 1 : null,
821 offset : vlAllImportErrorGrid.displayOffset,
822 limit : vlAllImportErrorGrid.displayLimit
825 onresponse : function(r) {
826 var item = openils.Util.readResponse(r);
828 vlAllImportErrorGrid.store.newItem(vii.toStoreItem(item));
830 oncomplete : function() {
831 vlAllImportErrorGrid.hideLoadProgressIndicator();
837 vlAllImportErrorGrid.dataLoader();
840 function vlGetOrg(rowIdx, item) {
842 var value = this.grid.store.getValue(item, this.field);
843 if(value) return fieldmapper.aou.findOrgUnit(value).shortname();
847 function vlCopyStatus(rowIdx, item) {
849 var value = this.grid.store.getValue(item, this.field);
850 if(value) return copyStatusCache[value].name();
854 // Note, we don't pre-fetch all copy locations because there could be
855 // a lot of them. Instead, fetch-and-cache on demand.
856 function vlCopyLocation(rowIdx, item) {
858 var value = this.grid.store.getValue(item, this.field);
860 if(!copyLocationCache[value]) {
861 copyLocationCache[value] =
862 new openils.PermaCrud().retrieve('acpl', value);
864 return copyLocationCache[value].name();
870 function vlFormatViewMatchMARC(id) {
871 return '<a href="javascript:void(0);" onclick="vlLoadMARCHtml(' + id + ', true, '+
872 'function(){displayGlobalDiv(\'vl-match-div\');});">' + this.name + '</a>';
875 function getAttrValue(rowIdx, item) {
877 var attrCode = this.field.split('.')[1];
878 var rec = queuedRecordsMap[this.grid.store.getValue(item, 'id')];
879 var attr = getRecAttrFromCode(rec, attrCode);
880 return (attr) ? attr.attr_value() : '';
883 function vlGetDateTimeField(rowIdx, item) {
885 var value = this.grid.store.getValue(item, this.field);
886 if(!value) return '';
887 var date = dojo.date.stamp.fromISOString(value);
888 return dojo.date.locale.format(date, {selector:'date'});
891 function vlGetCreator(rowIdx, item) {
893 var id = this.grid.store.getValue(item, 'creator');
895 return userCache[id].usrname();
896 var user = fieldmapper.standardRequest(
897 ['open-ils.actor', 'open-ils.actor.user.retrieve'], [authtoken, id]);
898 if(e = openils.Event.parse(user))
900 userCache[id] = user;
901 return user.usrname();
904 function vlGetViewMARC(rowIdx, item) {
905 return item && this.grid.store.getValue(item, 'id');
908 function vlFormatViewMARC(id) {
909 return '<a href="javascript:void(0);" onclick="vlLoadMARCHtml(' + id + ', false, '+
910 'function(){displayGlobalDiv(\'vl-queue-div\');});">' + this.name + '</a>';
913 function vlGetOverlayTargetSelector(rowIdx, item) {
915 return this.grid.store.getValue(item, '_id') + ':' + this.grid.store.getValue(item, 'id');
918 function vlFormatOverlayTargetSelector(val) {
920 var parts = val.split(':');
923 var value = '<input type="checkbox" name="vl-overlay-target-RECID" '+
924 'onclick="vlHandleOverlayTargetSelected(ID, GRIDID);" gridid="GRIDID" match="ID"/>';
925 value = value.replace(/GRIDID/g, _id);
926 value = value.replace(/RECID/g, currentImportRecId);
927 value = value.replace(/ID/g, id);
928 if(_id == currentOverlayRecordsMapGid[currentImportRecId])
929 return value.replace('/>', 'checked="checked"/>');
935 * see if the user has enabled overlays for the current match set and,
936 * if so, map the current import record to the overlay target.
938 function vlHandleOverlayTargetSelected(recId, gridId) {
939 var noneSelected = true;
940 var checkboxes = dojo.query('[name=vl-overlay-target-'+currentImportRecId+']');
941 for(var i = 0; i < checkboxes.length; i++) {
942 var checkbox = checkboxes[i];
943 var matchRecId = checkbox.getAttribute('match');
944 var gid = checkbox.getAttribute('gridid');
945 if(checkbox.checked) {
946 if(matchRecId == recId && gid == gridId) {
947 noneSelected = false;
948 currentOverlayRecordsMap[currentImportRecId] = matchRecId;
949 currentOverlayRecordsMapGid[currentImportRecId] = gid;
950 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = true;
951 dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = 'overlay_selected';
953 checkbox.checked = false;
959 delete currentOverlayRecordsMap[currentImportRecId];
960 delete currentOverlayRecordsMapGid[currentImportRecId];
961 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = false;
962 dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = '';
966 var valLastQueueType = null;
967 var vlQueueGridLayout = null;
968 function buildRecordGrid(type) {
969 displayGlobalDiv('vl-queue-div');
971 vlBibQueueGrid.canSort = function(col){ if(Math.abs(col) == 1) { return false; } else { return true; } };
972 vlAuthQueueGrid.canSort = function(col){ if(Math.abs(col) == 1) { return false; } else { return true; } };
975 openils.Util.show('vl-bib-queue-grid-wrapper');
976 openils.Util.hide('vl-auth-queue-grid-wrapper');
977 vlQueueGrid = vlBibQueueGrid;
978 openils.Util.show('add-to-bucket-action', 'table-row');
980 openils.Util.show('vl-auth-queue-grid-wrapper');
981 openils.Util.hide('vl-bib-queue-grid-wrapper');
982 vlQueueGrid = vlAuthQueueGrid;
983 openils.Util.hide('add-to-bucket-action');
987 if(valLastQueueType != type) {
988 valLastQueueType = type;
989 vlQueueGridLayout = vlQueueGrid.attr('structure');
990 var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
991 attrDefMap[type] = {};
992 for(var i = 0; i < defs.length; i++) {
994 attrDefMap[type][def.code()] = def.id();
996 name:def.description(),
997 field:'attr.' + def.code(),
999 selectableColumn:true
1001 vlQueueGridLayout[0].cells[0].push(col);
1005 dojo.forEach(vlQueueGridLayout[0].cells[0],
1007 if(cell.field.match(/^\+/))
1008 cell.nonSelectable=true;
1014 storeData = vqbr.toStoreData(queuedRecords);
1016 storeData = vqar.toStoreData(queuedRecords);
1018 var store = new dojo.data.ItemFileReadStore({data:storeData});
1019 vlQueueGrid.setStore(store);
1021 if(vlQueueGridColumePicker[type]) {
1022 vlQueueGrid.update();
1025 vlQueueGridColumePicker[type] =
1026 new openils.widget.GridColumnPicker(
1027 authtoken, 'vandelay.queue.'+type, vlQueueGrid, vlQueueGridLayout);
1028 vlQueueGridColumePicker[type].load();
1032 function vlQueueGridPrevPage() {
1033 var page = parseInt(vlQueueDisplayPage.getValue());
1034 if(page < 2) return;
1035 vlQueueDisplayPage.setValue(page - 1);
1036 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1039 function vlQueueGridNextPage() {
1040 vlQueueDisplayPage.setValue(parseInt(vlQueueDisplayPage.getValue())+1);
1041 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1044 function vlDeleteQueue(type, queueId, onload) {
1045 fieldmapper.standardRequest(
1046 ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.delete'],
1048 params: [authtoken, queueId],
1049 oncomplete: function(r) {
1050 var resp = r.recv().content();
1051 if(e = openils.Event.parse(resp))
1060 function vlQueueGridDrawSelectBox(rowIdx, item) {
1061 return item && this.grid.store.getValue(item, 'id');
1064 function vlQueueGridFormatSelectBox(id) {
1065 var domId = 'vl-record-list-selected-' + id;
1066 if (id) { selectableGridRecords[domId] = id; }
1067 return "<div><input type='checkbox' id='"+domId+"'/></div>";
1070 function vlSelectAllQueueGridRecords() {
1071 for(var id in selectableGridRecords)
1072 dojo.byId(id).checked = true;
1074 function vlSelectNoQueueGridRecords() {
1075 for(var id in selectableGridRecords)
1076 dojo.byId(id).checked = false;
1078 function vlToggleQueueGridSelect() {
1079 if(dojo.byId('vl-queue-grid-row-selector').checked)
1080 vlSelectAllQueueGridRecords();
1082 vlSelectNoQueueGridRecords();
1085 var handleRetrieveRecords = function() {
1086 buildRecordGrid(currentType);
1087 vlFetchQueueSummary(currentQueueId, currentType,
1089 dojo.byId('vl-queue-summary-name').innerHTML = summary.queue.name();
1090 dojo.byId('vl-queue-summary-total-count').innerHTML = summary.total +'';
1091 dojo.byId('vl-queue-summary-import-count').innerHTML = summary.imported + '';
1092 dojo.byId('vl-queue-summary-import-item-count').innerHTML = summary.total_items + '';
1093 dojo.byId('vl-queue-summary-import-item-imported-count').innerHTML = summary.total_items_imported + '';
1094 dojo.byId('vl-queue-summary-rec-error-count').innerHTML = summary.rec_import_errors + '';
1095 dojo.byId('vl-queue-summary-item-error-count').innerHTML = summary.item_import_errors + '';
1097 if (dojo.byId('create-bucket-dialog-name')) {
1098 dojo.byId('create-bucket-dialog-name').value = summary.queue.name();
1104 function vlFetchQueueSummary(qId, type, onload) {
1105 fieldmapper.standardRequest(
1106 ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.summary.retrieve'],
1108 params: [authtoken, qId],
1109 oncomplete : function(r) {
1110 var summary = r.recv().content();
1111 if(e = openils.Event.parse(summary))
1113 return onload(summary);
1119 function handleCreateBucket(args) {
1120 var bname = dojo.byId('create-bucket-dialog-name').value;
1123 progressDialog.show(true);
1124 fieldmapper.standardRequest(
1125 ['open-ils.vandelay', 'open-ils.vandelay.bib_queue.to_bucket'],
1127 params : [authtoken, currentQueueId, bname],
1128 oncomplete : function(r) {
1129 progressDialog.hide();
1130 setTimeout(function() {
1131 var resp = openils.Util.readResponse(r);
1132 if (resp.add_count == 0) {
1133 alert(localeStrings.NO_BUCKET_ITEMS);
1136 dojo.string.substitute(
1137 localeStrings.BUCKET_CREATE_SUCCESS,
1138 [resp.add_count, bname, resp.item_count]
1142 }, 200); // give the dialog a chance to hide
1149 var _importCancelHandler;
1150 var _importGoHandler;
1151 function vlHandleQueueItemsAction(action) {
1153 if(_importCancelHandler) dojo.disconnect(_importCancelHandler);
1155 _importCancelHandler = dojo.connect(
1156 queueItemsImportCancelButton,
1159 queueItemsImportDialog.hide();
1163 if(_importGoHandler)
1164 dojo.disconnect(_importGoHandler);
1166 _importGoHandler = dojo.connect(
1167 queueItemsImportGoButton,
1170 queueItemsImportDialog.hide();
1172 // hack to set the widgets the import funcs will be looking at. Reset them below.
1173 vlUploadQueueImportNoMatch.attr('value', vlUploadQueueImportNoMatch2.attr('value'));
1174 vlUploadQueueAutoOverlayExact.attr('value', vlUploadQueueAutoOverlayExact2.attr('value'));
1175 vlUploadQueueAutoOverlay1Match.attr('value', vlUploadQueueAutoOverlay1Match2.attr('value'));
1176 vlUploadMergeProfile.attr('value', vlUploadMergeProfile2.attr('value'));
1177 vlUploadFtMergeProfile.attr('value', vlUploadFtMergeProfile2.attr('value'));
1178 vlUploadQueueAutoOverlayBestMatch.attr('value', vlUploadQueueAutoOverlayBestMatch2.attr('value'));
1179 vlUploadQueueAutoOverlayBestMatchRatio.attr('value', vlUploadQueueAutoOverlayBestMatchRatio2.attr('value'));
1181 if(action == 'import') {
1182 vlImportSelectedRecords();
1183 } else if(action == 'import_all') {
1184 vlImportAllRecords();
1187 // reset the widgets to prevent accidental future actions
1188 vlUploadQueueImportNoMatch.attr('value', false);
1189 vlUploadQueueImportNoMatch2.attr('value', false);
1190 vlUploadQueueAutoOverlayExact.attr('value', false);
1191 vlUploadQueueAutoOverlayExact2.attr('value', false);
1192 vlUploadQueueAutoOverlay1Match.attr('value', false);
1193 vlUploadQueueAutoOverlay1Match2.attr('value', false);
1194 vlUploadMergeProfile.attr('value', '');
1195 vlUploadMergeProfile2.attr('value', '');
1196 vlUploadFtMergeProfile.attr('value', '');
1197 vlUploadFtMergeProfile2.attr('value', '');
1198 vlUploadQueueAutoOverlayBestMatch.attr('value', false);
1199 vlUploadQueueAutoOverlayBestMatch2.attr('value', false);
1200 vlUploadQueueAutoOverlayBestMatchRatio.attr('value', '0.0');
1201 vlUploadQueueAutoOverlayBestMatchRatio2.attr('value', '0.0');
1205 queueItemsImportDialog.show();
1208 function vlHandleCreateBucket() {
1210 create-bucket-dialog-name
1214 /* import user-selected records */
1215 function vlImportSelectedRecords() {
1218 for(var id in selectableGridRecords) {
1219 if(dojo.byId(id).checked) {
1220 var recId = selectableGridRecords[id];
1221 var rec = queuedRecordsMap[recId];
1222 if(!rec.import_time())
1223 records.push(recId);
1227 vlImportRecordQueue(
1232 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1237 /* import all (non-imported) queue records */
1238 function vlImportAllRecords() {
1239 vlImportRecordQueue(
1244 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1249 /* if recList has values, import only those records */
1250 function vlImportRecordQueue(type, queueId, recList, onload) {
1251 displayGlobalDiv('vl-generic-progress-with-total');
1253 /* set up options */
1254 var options = {overlay_map : currentOverlayRecordsMap};
1256 if(vlUploadQueueImportNoMatch.checked) {
1257 options.import_no_match = true;
1258 vlUploadQueueImportNoMatch.checked = false;
1261 if(vlUploadQueueAutoOverlayExact.checked) {
1262 options.auto_overlay_exact = true;
1263 vlUploadQueueAutoOverlayExact.checked = false;
1266 if(vlUploadQueueAutoOverlayBestMatch.checked) {
1267 options.auto_overlay_best_match = true;
1268 vlUploadQueueAutoOverlayBestMatch.checked = false;
1269 options.match_quality_ratio = vlUploadQueueAutoOverlayBestMatchRatio.attr('value');
1272 if(vlUploadQueueAutoOverlay1Match.checked) {
1273 options.auto_overlay_1match = true;
1274 vlUploadQueueAutoOverlay1Match.checked = false;
1275 options.match_quality_ratio = vlUploadQueueAutoOverlayBestMatchRatio.attr('value');
1278 var profile = vlUploadMergeProfile.attr('value');
1279 if(profile != null && profile != '') {
1280 options.merge_profile = profile;
1283 var ftprofile = vlUploadFtMergeProfile.attr('value');
1284 if(ftprofile != null && ftprofile != '') {
1285 options.fall_through_merge_profile = ftprofile;
1289 /* determine which method we're calling */
1291 var method = 'open-ils.vandelay.bib_queue.import';
1293 method = method.replace('bib', 'auth');
1295 var params = [authtoken, queueId, options];
1297 method = 'open-ils.vandelay.'+currentType+'_record.list.import';
1298 params[1] = recList;
1301 fieldmapper.standardRequest(
1302 ['open-ils.vandelay', method],
1305 onresponse: function(r) {
1306 var resp = r.recv().content();
1307 if(e = openils.Event.parse(resp))
1309 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
1311 oncomplete: function() {onload();}
1318 * Create queue, upload MARC, process spool, load the newly created queue
1320 function batchUpload() {
1321 var queueName = dijit.byId('vl-queue-name').getValue();
1322 currentType = dijit.byId('vl-record-type').getValue();
1324 // could be bib-acq, which makes no sense in most places
1325 if (currentType.match(/bib/)) currentType = 'bib';
1327 var handleProcessSpool = function() {
1329 vlUploadQueueImportNoMatch.checked ||
1330 vlUploadQueueAutoOverlayExact.checked ||
1331 vlUploadQueueAutoOverlay1Match.checked ||
1332 vlUploadQueueAutoOverlayBestMatch.checked ) {
1334 vlImportRecordQueue(
1339 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1343 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
1347 var handleUploadMARC = function(key) {
1348 dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');
1349 processSpool(key, currentQueueId, currentType, handleProcessSpool);
1352 var handleCreateQueue = function(queue) {
1353 currentQueueId = queue.id();
1354 uploadMARC(handleUploadMARC);
1357 if(vlUploadQueueSelector.getValue() && !queueName) {
1358 currentQueueId = vlUploadQueueSelector.getValue();
1359 uploadMARC(handleUploadMARC);
1361 createQueue(queueName, currentType, handleCreateQueue,
1362 vlUploadQueueHoldingsImportProfile.attr('value'),
1363 vlUploadQueueMatchSet.attr('value')
1368 // Inspect Queue no longer uses stores, so put type matching here instead
1369 function vlGetQueueData(type, asStore) {
1375 if(!filter) filter = 'bib';
1376 var bibList = allUserBibQueues.filter(
1378 return (q.queue_type() == filter);
1381 if (!asStore) return bibList;
1382 return vbq.toStoreData(bibList);
1384 if (!asStore) return allUserAuthQueues;
1385 return vaq.toStoreData(allUserAuthQueues);
1389 function vlFleshQueueSelect(selector, type) {
1390 var data = vlGetQueueData(type, true);
1391 selector.store = new dojo.data.ItemFileReadStore({data:data});
1392 selector.setValue(null);
1393 selector.setDisplayedValue('');
1395 selector.setValue(data[0].id());
1397 var qInput = dijit.byId('vl-queue-name');
1399 var selChange = function(val) {
1400 console.log('selector onchange');
1401 // user selected a queue from the selector; clear the input and
1402 // set the item import profile already defined for the queue
1403 var queue = allUserBibQueues.filter(function(q) { return (q.id() == val) })[0];
1405 vlUploadQueueHoldingsImportProfile.attr('value', queue.item_attr_def() || '');
1406 vlUploadQueueHoldingsImportProfile.attr('disabled', true);
1407 vlUploadQueueMatchSet.attr('value', queue.match_set() || '');
1408 vlUploadQueueMatchSet.attr('disabled', true);
1410 vlUploadQueueHoldingsImportProfile.attr('value', '');
1411 vlUploadQueueHoldingsImportProfile.attr('disabled', false);
1412 vlUploadQueueMatchSet.attr('value', '');
1413 vlUploadQueueMatchSet.attr('disabled', false);
1415 dojo.disconnect(qInput._onchange);
1416 qInput.attr('value', '');
1417 qInput._onchange = dojo.connect(qInput, 'onChange', inputChange);
1420 var inputChange = function(val) {
1421 console.log('qinput onchange');
1422 // user entered a new queue name. clear the selector
1423 vlUploadQueueHoldingsImportProfile.attr('disabled', false);
1424 vlUploadQueueMatchSet.attr('disabled', false);
1425 dojo.disconnect(selector._onchange);
1426 selector.attr('value', '');
1427 selector._onchange = dojo.connect(selector, 'onChange', selChange);
1430 selector._onchange = dojo.connect(selector, 'onChange', selChange);
1431 qInput._onchange = dojo.connect(qInput, 'onChange', inputChange);
1434 function vlUpdateMatchSetSelector(type) {
1435 type = (type.match(/bib/)) ? 'biblio' : 'authority';
1436 vlUploadQueueMatchSet.store =
1437 new dojo.data.ItemFileReadStore({data:vms.toStoreData(matchSets[type])});
1440 function vlShowUploadForm() {
1441 displayGlobalDiv('vl-marc-upload-div');
1442 vlFleshQueueSelect(vlUploadQueueSelector, vlUploadRecordType.getValue());
1443 vlUploadSourceSelector.store =
1444 new dojo.data.ItemFileReadStore({data:cbs.toStoreData(vlBibSources, 'source')});
1445 vlUploadSourceSelector.setValue(vlBibSources[0].id());
1446 vlUploadQueueHoldingsImportProfile.store =
1447 new dojo.data.ItemFileReadStore({data:viiad.toStoreData(importItemDefs)});
1448 vlUpdateMatchSetSelector(vlUploadRecordType.getValue());
1450 // use ratio from the merge profile if it's set
1452 vlUploadMergeProfile,
1456 var profile = mergeProfiles.filter(function(p) { return (p.id() == val); })[0];
1457 if(profile.lwm_ratio() != null)
1458 vlUploadQueueAutoOverlayBestMatchRatio.attr('value', profile.lwm_ratio()+'');
1462 vlUploadMergeProfile2,
1466 var profile = mergeProfiles.filter(function(p) { return (p.id() == val); })[0];
1467 if(profile.lwm_ratio() != null)
1468 vlUploadQueueAutoOverlayBestMatchRatio2.attr('value', profile.lwm_ratio()+'');
1474 function vlDeleteSelectedQueues() {
1475 var checkboxes = document.getElementById('vlQueueSelectList').getElementsByTagName('input');
1476 var type = vlQueueSelectType.attr('value').replace(/-.*/, '');
1477 for(var i = 0; i < checkboxes.length; i++) {
1478 if(checkboxes[i].getAttribute('name') == 'delete' && checkboxes[i].checked) {
1479 vlDeleteQueue(type, checkboxes[i].getAttribute('value'), function () {});
1482 window.location.reload();
1485 function vlShowQueueSelect() {
1486 displayGlobalDiv('vl-queue-select-div');
1487 var type = vlQueueSelectType.attr('value');
1488 var data = vlGetQueueData(type, false);
1489 type = type.replace(/-.*/, ''); // To remove any sub-typeish info.
1490 var tbody = document.getElementById('vlQueueSelectList');
1492 while(tbody.firstChild) {
1493 tbody.removeChild(tbody.firstChild);
1496 for(var entry in data) {
1497 var name = data[entry].name();
1498 if(!name.match(/\S/))
1500 var tr = document.createElement('tr');
1501 var td = document.createElement('td');
1502 var checkbox = document.createElement('input');
1503 checkbox.setAttribute('type', 'checkbox');
1504 checkbox.setAttribute('name', 'delete');
1505 checkbox.setAttribute('value', data[entry].id());
1506 td.appendChild(checkbox);
1508 td = document.createElement('td');
1509 var a = document.createElement('a');
1510 a.textContent = name;
1511 a.setAttribute('href', "javascript:retrieveQueuedRecords('" + type + "', " + data[entry].id() + ");");
1514 tbody.appendChild(tr);
1518 function vlShowMatchSetEditor() {
1519 displayGlobalDiv('vl-match-set-editor-div');
1520 dojo.byId('vl-match-set-editor-div').appendChild(
1521 dojo.create('iframe', {
1522 id : 'vl-match-set-iframe',
1523 src : oilsBasePath + '/conify/global/vandelay/match_set',
1524 style : 'width:100%; height:500px; border:none; margin:0px;'
1529 function vlOpenMarcEditWindow(rec, postReloadHTMLHandler) {
1531 To run in Firefox directly, must set signed.applets.codebase_principal_support
1532 to true in about:config
1534 win = window.open('/xul/server/cat/marcedit.xul','','chrome'); // XXX version?
1537 if (currentType == 'bib') {
1543 function onsave(r) {
1544 // after the record is saved, reload the HTML display
1545 var stat = r.recv().content();
1546 if(e = openils.Event.parse(stat))
1548 alert(dojo.byId('vl-marc-edit-complete-label').innerHTML);
1550 vlLoadMARCHtml(rec.id(), false, postReloadHTMLHandler);
1554 record : {marc : rec.marc(), "rtype": type},
1556 label: dojo.byId('vl-marc-edit-save-label').innerHTML,
1557 func: function(xmlString) {
1558 var method = 'open-ils.permacrud.update.' + rec.classname;
1559 rec.marc(xmlString);
1560 fieldmapper.standardRequest(
1561 ['open-ils.permacrud', method],
1563 params: [authtoken, rec],
1569 'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
1570 'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
1574 function vlLoadMarcEditor(type, recId, postReloadHTMLHandler) {
1575 var method = 'open-ils.permacrud.search.vqbr';
1576 if(currentType != 'bib')
1577 method = method.replace(/vqbr/,'vqar');
1579 fieldmapper.standardRequest(
1580 ['open-ils.permacrud', method],
1582 params: [authtoken, {id : recId}],
1583 oncomplete: function(r) {
1584 var rec = r.recv().content();
1585 if(e = openils.Event.parse(rec))
1587 vlOpenMarcEditWindow(rec, postReloadHTMLHandler);
1595 //------------------------------------------------------------
1596 // attribute editors
1598 // attribute-editor global variables
1600 var ATTR_EDITOR_IN_UPDATE_MODE = false; // true on 'edit', false on 'create'
1601 var ATTR_EDIT_ID = null; // id of current 'edit' attribute
1602 var ATTR_EDIT_GROUP = 'bib'; // bib-attrs or auth-attrs
1604 function vlAttrEditorInit() {
1605 // set up tooltips on the edit form
1606 connectTooltip('attr-editor-tags');
1607 connectTooltip('attr-editor-subfields');
1610 function vlShowAttrEditor() {
1611 displayGlobalDiv('vl-attr-editor-div');
1612 loadAttrEditorGrid();
1613 idHide('vl-generic-progress');
1616 function setAttrEditorGroup(groupName) {
1617 // put us into 'bib'-attr or 'auth'-attr mode.
1618 if (ATTR_EDIT_GROUP != groupName) {
1619 ATTR_EDIT_GROUP = groupName;
1620 loadAttrEditorGrid();
1624 function onAttrEditorOpen() {
1625 // the "bars" have the create/update/cancel/etc. buttons.
1626 var create_bar = document.getElementById('attr-editor-create-bar');
1627 var update_bar = document.getElementById('attr-editor-update-bar');
1628 if (ATTR_EDITOR_IN_UPDATE_MODE) {
1629 update_bar.style.display='table-row';
1630 create_bar.style.display='none';
1631 // hide the dropdown-button
1632 idStyle('vl-create-attr-editor-button', 'visibility', 'hidden');
1634 dijit.byId('attr-editor-dialog').reset();
1635 create_bar.style.display='table-row';
1636 update_bar.style.display='none';
1640 function onAttrEditorClose() {
1641 // reset the form to a "create" form. (We may have borrowed it for editing.)
1642 ATTR_EDITOR_IN_UPDATE_MODE = false;
1643 // show the dropdown-button
1644 idStyle('vl-create-attr-editor-button', 'visibility', 'visible');
1647 function loadAttrEditorGrid() {
1648 var _data = (ATTR_EDIT_GROUP == 'auth') ?
1649 vqarad.toStoreData(authAttrDefs) : vqbrad.toStoreData(bibAttrDefs) ;
1651 var store = new dojo.data.ItemFileReadStore({data:_data});
1652 attrEditorGrid.setStore(store);
1653 attrEditorGrid.onRowDblClick = onAttrEditorClick;
1654 attrEditorGrid.update();
1657 function attrGridGetTag(n, item) {
1658 // grid helper: return the tags from the row's xpath column.
1659 return item && xpathParser.parse(this.grid.store.getValue(item, 'xpath')).tags;
1662 function attrGridGetSubfield(n, item) {
1663 // grid helper: return the subfields from the row's xpath column.
1664 return item && xpathParser.parse(this.grid.store.getValue(item, 'xpath')).subfields;
1667 function onAttrEditorClick() {
1668 var row = this.getItem(this.focus.rowIndex);
1669 ATTR_EDIT_ID = this.store.getValue(row, 'id');
1670 ATTR_EDITOR_IN_UPDATE_MODE = true;
1672 // populate the popup editor.
1673 dijit.byId('attr-editor-code').attr('value', this.store.getValue(row, 'code'));
1674 dijit.byId('attr-editor-description').attr('value', this.store.getValue(row, 'description'));
1675 var parsed_xpath = xpathParser.parse(this.store.getValue(row, 'xpath'));
1676 dijit.byId('attr-editor-tags').attr('value', parsed_xpath.tags);
1677 dijit.byId('attr-editor-subfields').attr('value', parsed_xpath.subfields);
1678 dijit.byId('attr-editor-xpath').attr('value', this.store.getValue(row, 'xpath'));
1679 dijit.byId('attr-editor-remove').attr('value', this.store.getValue(row, 'remove'));
1681 // set up UI for editing
1682 dojo.byId('vl-create-attr-editor-button').click();
1685 function vlSaveAttrDefinition(data) {
1686 idHide('vl-attr-editor-div');
1687 idShow('vl-generic-progress');
1689 data.id = ATTR_EDIT_ID;
1691 // this ought to honour custom xpaths, but overwrite xpaths
1692 // derived from tags/subfields.
1693 if (data.xpath == '' || looksLikeDerivedXpath(data.xpath)) {
1694 var _xpath = tagAndSubFieldsToXpath(data.tag, data.subfield);
1695 data.xpath = _xpath;
1698 // build up our permacrud params. Key variables here are
1699 // "create or update" and "bib or auth".
1701 var isAuth = (ATTR_EDIT_GROUP == 'auth');
1702 var isCreate = (ATTR_EDIT_ID == null);
1703 var rad = isAuth ? new vqarad() : new vqbrad() ;
1704 var method = 'open-ils.permacrud' + (isCreate ? '.create.' : '.update.')
1705 + (isAuth ? 'vqarad' : 'vqbrad');
1706 var _data = rad.fromStoreItem(data);
1710 fieldmapper.standardRequest(
1711 ['open-ils.permacrud', method],
1713 params: [authtoken, _data ],
1714 onresponse: function(r) { },
1715 oncomplete: function(r) {
1716 attrEditorFetchAttrDefs(vlShowAttrEditor);
1717 ATTR_EDIT_ID = null;
1719 onerror: function(r) {
1720 alert('vlSaveAttrDefinition comms error: ' + r);
1726 function attrEditorFetchAttrDefs(callback) {
1727 var fn = (ATTR_EDIT_GROUP == 'auth') ? vlFetchAuthAttrDefs : vlFetchBibAttrDefs;
1728 return fn(callback);
1731 function vlAttrDelete() {
1732 idHide('vl-attr-editor-div');
1733 idShow('vl-generic-progress');
1735 var isAuth = (ATTR_EDIT_GROUP == 'auth');
1736 var method = 'open-ils.permacrud.delete.' + (isAuth ? 'vqarad' : 'vqbrad');
1737 var rad = isAuth ? new vqarad() : new vqbrad() ;
1738 fieldmapper.standardRequest(
1739 ['open-ils.permacrud', method],
1741 params: [authtoken, rad.fromHash({ id : ATTR_EDIT_ID }), ],
1742 oncomplete: function() {
1743 dijit.byId('attr-editor-dialog').onCancel(); // close the dialog
1744 attrEditorFetchAttrDefs(vlShowAttrEditor);
1745 ATTR_EDIT_ID = null;
1747 onerror: function(r) {
1748 alert('vlAttrDelete comms error: ' + r);
1754 // ------------------------------------------------------------
1755 // utilities for attribute editors
1757 // dom utilities (maybe dojo does these, and these should be replaced)
1759 function idStyle(obId, k, v) { document.getElementById(obId).style[k] = v; }
1760 function idShow(obId) { idStyle(obId, 'display', 'block'); }
1761 function idHide(obId) { idStyle(obId, 'display' , 'none'); }
1763 function connectTooltip(fieldId) {
1764 // Given an element id, look up a tooltip element in the doc (same
1765 // id with a '-tip' suffix) and associate the two. Maybe dojo has
1766 // a better way to do this?
1767 var fld = dojo.byId(fieldId);
1768 var tip = dojo.byId(fieldId + '-tip');
1769 dojo.connect(fld, 'onfocus', function(evt) {
1770 dijit.showTooltip(tip.innerHTML, fld, ['below', 'after']); });
1771 dojo.connect(fld, 'onblur', function(evt) { dijit.hideTooltip(fld); });
1776 var xpathParser = new openils.MarcXPathParser();
1778 function tagAndSubFieldsToXpath(tags, subfields) {
1779 // given tags, and subfields, build up an XPath.
1782 'tags':tags.match(/[\d]+/g),
1783 'subfields':subfields.match(/[a-zA-z]/g) };
1784 return xpathParser.compile(parts);
1786 return {'parts':null, 'tags':null, 'error':err};
1790 function looksLikeDerivedXpath(path) {
1791 // Does this path look like it was derived from tags and subfields?
1792 var parsed = xpathParser.parse(path);
1793 if (parsed.tags == null)
1795 var compiled = xpathParser.compile(parsed);
1796 return (path == compiled);
1799 // amazing xpath-util unit-tests
1800 if (!looksLikeDerivedXpath('//*[@tag="901"]/*[@code="c"]')) alert('vandelay xpath-utility error');
1801 if ( looksLikeDerivedXpath('ba-boo-ba-boo!')) alert('vandelay xpath-utility error');
1805 var profileContextOrg
1806 function vlShowProfileEditor() {
1807 displayGlobalDiv('vl-profile-editor-div');
1810 var connect = function() {
1811 dojo.connect(profileContextOrgSelector, 'onChange',
1813 profileContextOrg = this.attr('value');
1820 new openils.User().buildPermOrgSelector(
1821 'ADMIN_MERGE_PROFILE', profileContextOrgSelector, null, connect);
1824 function buildProfileGrid() {
1826 if(profileContextOrg == null)
1827 profileContextOrg = openils.User.user.ws_ou();
1830 {order_by : {vmp : 'name'}},
1831 {owner : fieldmapper.aou.fullPath(profileContextOrg, true)}
1835 /* --- Import Item Attr Grid --------------- */
1837 var itemAttrContextOrg;
1838 var itemAttrGridFirstTime = true;
1839 function vlShowImportItemAttrEditor() {
1840 displayGlobalDiv('vl-item-attr-editor-div');
1842 if (itemAttrGridFirstTime) {
1844 buildImportItemAttrGrid();
1846 var connect = function() {
1847 dojo.connect(itemAttrContextOrgSelector, 'onChange',
1849 itemAttrContextOrg = this.attr('value');
1850 itemAttrGrid.resetStore();
1851 buildImportItemAttrGrid();
1856 new openils.User().buildPermOrgSelector(
1857 'ADMIN_IMPORT_ITEM_ATTR_DEF',
1858 itemAttrContextOrgSelector, null, connect);
1860 itemAttrGridFirstTime = false;
1864 function buildImportItemAttrGrid() {
1866 if(itemAttrContextOrg == null)
1867 itemAttrContextOrg = openils.User.user.ws_ou();
1869 itemAttrGrid.loadAll(
1870 {order_by : {viiad : 'name'}},
1871 {owner : fieldmapper.aou.fullPath(itemAttrContextOrg, true)}