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.Button");
19 dojo.require("dijit.form.FilteringSelect");
20 dojo.require("dijit.layout.ContentPane");
21 dojo.require("dijit.layout.TabContainer");
22 dojo.require("dijit.layout.LayoutContainer");
23 dojo.require('dijit.form.Button');
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.Grid");
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('openils.CGI');
36 dojo.require('openils.User');
37 dojo.require('openils.Event');
38 dojo.require('openils.MarcXPathParser');
39 dojo.require('openils.GridColumnPicker');
43 'vl-generic-progress',
44 'vl-generic-progress-with-total',
49 'vl-queue-select-div',
50 'vl-marc-upload-status-div',
56 var VANDELAY_URL = '/vandelay-upload';
58 var authAttrDefs = [];
59 var queuedRecords = [];
60 var queuedRecordsMap = {};
61 var bibAttrsFetched = false;
62 var authAttrsFetched = false;
63 var attrDefMap = {}; // maps attr def code names to attr def ids
65 var currentQueueId = null;
67 var currentMatchedRecords; // set of loaded matched bib records
68 var currentOverlayRecordsMap; // map of import record to overlay record
69 var currentOverlayRecordsMapGid; // map of import record to overlay record grid id
70 var currentImportRecId; // when analyzing matches, this is the current import record
71 var userBibQueues = []; // only non-complete queues
72 var userAuthQueues = []; // only non-complete queues
74 var allUserAuthQueues;
75 var selectableGridRecords;
76 var cgi = new openils.CGI();
77 var vlQueueGridColumePicker;
83 authtoken = dojo.cookie('ses') || cgi.param('ses');
84 var initNeeded = 4; // how many async responses do we need before we're init'd
85 var initCount = 0; // how many async reponses we've received
87 function checkInitDone() {
89 if(initCount == initNeeded)
93 // Fetch the bib and authority attribute definitions
94 vlFetchBibAttrDefs(function () { checkInitDone(); });
95 vlFetchAuthAttrDefs(function () { checkInitDone(); });
97 vlRetrieveQueueList('bib', null,
99 allUserBibQueues = list;
100 for(var i = 0; i < allUserBibQueues.length; i++) {
101 if(allUserBibQueues[i].complete() == 'f')
102 userBibQueues.push(allUserBibQueues[i]);
108 vlRetrieveQueueList('auth', null,
110 allUserAuthQueues = list;
111 for(var i = 0; i < allUserAuthQueues.length; i++) {
112 if(allUserAuthQueues[i].complete() == 'f')
113 userAuthQueues.push(allUserAuthQueues[i]);
123 dojo.addOnLoad(vlInit);
126 // fetch the bib and authority attribute definitions
128 function vlFetchBibAttrDefs(postcomplete) {
130 fieldmapper.standardRequest(
131 ['open-ils.permacrud', 'open-ils.permacrud.search.vqbrad'],
133 params: [authtoken, {id:{'!=':null}}],
134 onresponse: function(r) {
135 var def = r.recv().content();
136 if(e = openils.Event.parse(def[0]))
138 bibAttrDefs.push(def);
140 oncomplete: function() {
141 bibAttrDefs = bibAttrDefs.sort(
143 if(a.id() > b.id()) return 1;
144 if(a.id() < b.id()) return -1;
154 function vlFetchAuthAttrDefs(postcomplete) {
156 fieldmapper.standardRequest(
157 ['open-ils.permacrud', 'open-ils.permacrud.search.vqarad'],
159 params: [authtoken, {id:{'!=':null}}],
160 onresponse: function(r) {
161 var def = r.recv().content();
162 if(e = openils.Event.parse(def[0]))
164 authAttrDefs.push(def);
166 oncomplete: function() {
167 authAttrDefs = authAttrDefs.sort(
169 if(a.id() > b.id()) return 1;
170 if(a.id() < b.id()) return -1;
180 function vlRetrieveQueueList(type, filter, onload) {
181 type = (type == 'bib') ? type : 'authority';
182 fieldmapper.standardRequest(
183 ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.owner.retrieve.atomic'],
185 params: [authtoken, null, filter],
186 oncomplete: function(r) {
187 var list = r.recv().content();
188 if(e = openils.Event.parse(list[0]))
197 function displayGlobalDiv(id) {
198 for(var i = 0; i < globalDivs.length; i++) {
200 dojo.style(dojo.byId(globalDivs[i]), 'display', 'none');
202 alert('please define div ' + globalDivs[i]);
205 dojo.style(dojo.byId(id),'display','block');
208 function runStartupCommands() {
209 currentQueueId = cgi.param('qid');
210 currentType = cgi.param('qtype');
211 dojo.style('vl-nav-bar', 'visibility', 'visible');
213 return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
218 * asynchronously upload a file of MARC records
220 function uploadMARC(onload){
221 dojo.byId('vl-upload-status-count').innerHTML = '0';
222 dojo.byId('vl-ses-input').value = authtoken;
223 displayGlobalDiv('vl-marc-upload-status-div');
224 dojo.io.iframe.send({
228 form: dojo.byId('vl-marc-upload-form'),
229 handle: function(data,ioArgs){
230 var content = data.documentElement.textContent;
237 * Creates a new vandelay queue
239 function createQueue(queueName, type, onload) {
240 var name = (type=='bib') ? 'bib' : 'authority';
241 var method = 'open-ils.vandelay.'+ name +'_queue.create'
242 fieldmapper.standardRequest(
243 ['open-ils.vandelay', method],
245 params: [authtoken, queueName, null, name],
246 oncomplete : function(r) {
247 var queue = r.recv().content();
248 if(e = openils.Event.parse(queue))
257 * Tells vandelay to pull a batch of records from the cache and explode them
258 * out into the vandelay tables
260 function processSpool(key, queueId, type, onload) {
261 fieldmapper.standardRequest(
262 ['open-ils.vandelay', 'open-ils.vandelay.'+type+'.process_spool'],
264 params: [authtoken, key, queueId],
265 onresponse : function(r) {
266 var resp = r.recv().content();
267 if(e = openils.Event.parse(resp))
269 dojo.byId('vl-upload-status-count').innerHTML = resp;
271 oncomplete : function(r) {onload();}
276 function retrieveQueuedRecords(type, queueId, onload) {
277 displayGlobalDiv('vl-generic-progress');
279 queuedRecordsMap = {};
280 currentOverlayRecordsMap = {};
281 currentOverlayRecordsMapGid = {};
282 selectableGridRecords = {};
283 resetVlQueueGridLayout();
285 var method = 'open-ils.vandelay.'+type+'_queue.records.retrieve.atomic';
286 if(vlQueueGridShowMatches.checked)
287 method = method.replace('records', 'records.matches');
289 var limit = parseInt(vlQueueDisplayLimit.getValue());
290 var offset = limit * parseInt(vlQueueDisplayPage.getValue()-1);
292 fieldmapper.standardRequest(
293 ['open-ils.vandelay', method],
295 params: [authtoken, queueId,
301 /* intermittent bug in streaming, multipart requests prevents use of onreponse for now...
302 onresponse: function(r) {
303 var rec = r.recv().content();
304 if(e = openils.Event.parse(rec))
306 queuedRecords.push(rec);
307 queuedRecordsMap[rec.id()] = rec;
310 oncomplete: function(r){
311 var recs = r.recv().content();
312 if(e = openils.Event.parse(recs[0]))
314 for(var i = 0; i < recs.length; i++) {
316 queuedRecords.push(rec);
317 queuedRecordsMap[rec.id()] = rec;
325 function vlLoadMatchUI(recId) {
326 displayGlobalDiv('vl-generic-progress');
327 var matches = queuedRecordsMap[recId].matches();
329 currentImportRecId = recId;
330 for(var i = 0; i < matches.length; i++)
331 records.push(matches[i].eg_record());
333 var retrieve = ['open-ils.search', 'open-ils.search.biblio.record_entry.slim.retrieve'];
334 var params = [records];
335 if(currentType == 'auth') {
336 retrieve = ['open-ils.cat', 'open-ils.cat.authority.record.retrieve'];
337 parmas = [authtoken, records, {clear_marc:1}];
340 fieldmapper.standardRequest(
344 oncomplete: function(r) {
345 var recs = r.recv().content();
346 if(e = openils.Event.parse(recs))
350 displayGlobalDiv('vl-match-div');
351 resetVlMatchGridLayout();
352 currentMatchedRecords = recs;
353 if(!vlMatchGrid.structure)
354 vlMatchGrid.setStructure(vlMatchGridLayout);
356 // build the data store of records with match information
357 var dataStore = bre.toStoreData(recs, null,
358 {virtualFields:['dest_matchpoint', 'src_matchpoint', '_id']});
359 dataStore.identifier = '_id';
361 var matchSeenMap = {};
363 for(var i = 0; i < dataStore.items.length; i++) {
364 var item = dataStore.items[i];
365 item._id = i; // just need something unique
366 for(var j = 0; j < matches.length; j++) {
367 var match = matches[j];
368 if(match.eg_record() == item.id && !matchSeenMap[match.id()]) {
369 item.dest_matchpoint = match.field_type();
370 var attr = getRecAttrFromMatch(queuedRecordsMap[recId], match);
371 item.src_matchpoint = getRecAttrDefFromAttr(attr, currentType).code();
372 matchSeenMap[match.id()] = 1;
378 // now populate the grid
379 vlPopulateMatchGrid(vlMatchGrid, dataStore);
385 function vlPopulateMatchGrid(grid, data) {
386 var store = new dojo.data.ItemFileReadStore({data:data});
387 var model = new dojox.grid.data.DojoData(
388 null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
389 grid.setModel(model);
393 function showMe(id) {
394 dojo.style(dojo.byId(id), 'display', 'block');
396 function hideMe(id) {
397 dojo.style(dojo.byId(id), 'display', 'none');
401 function vlLoadMARCHtml(recId, inCat, oncomplete) {
402 dijit.byId('vl-marc-html-done-button').onClick = oncomplete;
403 displayGlobalDiv('vl-generic-progress');
405 var params = [recId, 1];
408 hideMe('vl-marc-html-edit-button'); // don't show marc editor button
409 dijit.byId('vl-marc-html-edit-button').onClick = function(){}
410 api = ['open-ils.search', 'open-ils.search.biblio.record.html'];
411 if(currentType == 'auth')
412 api = ['open-ils.search', 'open-ils.search.authority.to_html'];
414 showMe('vl-marc-html-edit-button'); // plug in the marc editor button
415 dijit.byId('vl-marc-html-edit-button').onClick =
416 function() {vlLoadMarcEditor(currentType, recId, oncomplete);};
417 params = [authtoken, recId];
418 api = ['open-ils.vandelay', 'open-ils.vandelay.queued_bib_record.html'];
419 if(currentType == 'auth')
420 api = ['open-ils.vandelay', 'open-ils.vandelay.queued_authority_record.html'];
423 fieldmapper.standardRequest(
427 oncomplete: function(r) {
428 displayGlobalDiv('vl-marc-html-div');
429 var html = r.recv().content();
430 dojo.byId('vl-marc-record-html').innerHTML = html;
438 function getRecMatchesFromAttrCode(rec, attrCode) {
440 var attr = getRecAttrFromCode(rec, attrCode);
441 for(var j = 0; j < rec.matches().length; j++) {
442 var match = rec.matches()[j];
443 if(match.matched_attr() == attr.id())
450 function getRecAttrFromMatch(rec, match) {
451 for(var i = 0; i < rec.attributes().length; i++) {
452 var attr = rec.attributes()[i];
453 if(attr.id() == match.matched_attr())
458 function getRecAttrDefFromAttr(attr, type) {
459 var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
460 for(var i = 0; i < defs.length; i++) {
462 if(def.id() == attr.field())
467 function getRecAttrFromCode(rec, attrCode) {
468 var defId = attrDefMap[attrCode];
469 var attrs = rec.attributes();
470 for(var i = 0; i < attrs.length; i++) {
472 if(attr.field() == defId)
478 function vlGetViewMatches(rowIdx) {
479 var data = this.grid.model.getRow(rowIdx);
481 var rec = queuedRecordsMap[data.id];
482 if(rec.matches().length > 0)
483 return this.value.replace('RECID', data.id);
487 function getAttrValue(rowIdx) {
488 var data = this.grid.model.getRow(rowIdx);
490 var attrCode = this.field.split('.')[1];
491 var rec = queuedRecordsMap[data.id];
492 var attr = getRecAttrFromCode(rec, attrCode);
493 return (attr) ? attr.attr_value() : '';
496 function vlGetDateTimeField(rowIdx) {
497 data = this.grid.model.getRow(rowIdx);
499 if(!data[this.field]) return '';
500 var date = dojo.date.stamp.fromISOString(data[this.field]);
501 return dojo.date.locale.format(date, {selector:'date'});
504 function vlGetCreator(rowIdx) {
505 data = this.grid.model.getRow(rowIdx);
507 var id = data.creator;
509 return userCache[id].usrname();
510 var user = fieldmapper.standardRequest(
511 ['open-ils.actor', 'open-ils.actor.user.retrieve'], [authtoken, id]);
512 if(e = openils.Event.parse(user))
514 userCache[id] = user;
515 return user.usrname();
518 function vlGetViewMARC(rowIdx) {
519 data = this.grid.model.getRow(rowIdx);
521 return this.value.replace('RECID', data.id);
524 function vlGetOverlayTargetSelector(rowIdx) {
525 data = this.grid.model.getRow(rowIdx);
527 var value = this.value.replace(/GRIDID/g, data._id);
528 value = value.replace(/RECID/g, currentImportRecId);
529 value = value.replace(/ID/g, data.id);
530 if(data._id == currentOverlayRecordsMapGid[currentImportRecId])
531 return value.replace('/>', 'checked="checked"/>');
537 * see if the user has enabled overlays for the current match set and,
538 * if so, map the current import record to the overlay target.
540 function vlHandleOverlayTargetSelected(recId, gridId) {
541 var noneSelected = true;
542 var checkboxes = dojo.query('[name=vl-overlay-target-'+currentImportRecId+']');
543 for(var i = 0; i < checkboxes.length; i++) {
544 var checkbox = checkboxes[i];
545 var matchRecId = checkbox.getAttribute('match');
546 var gid = checkbox.getAttribute('gridid');
547 if(checkbox.checked) {
548 if(matchRecId == recId && gid == gridId) {
549 noneSelected = false;
550 currentOverlayRecordsMap[currentImportRecId] = matchRecId;
551 currentOverlayRecordsMapGid[currentImportRecId] = gid;
552 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = true;
553 dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = 'overlay_selected';
555 checkbox.checked = false;
561 delete currentOverlayRecordsMap[currentImportRecId];
562 delete currentOverlayRecordsMapGid[currentImportRecId];
563 dojo.byId('vl-record-list-selected-' + currentImportRecId).checked = false;
564 dojo.byId('vl-record-list-selected-' + currentImportRecId).parentNode.className = '';
568 var vlQueueGridBuilt = false;
569 function buildRecordGrid(type) {
570 displayGlobalDiv('vl-queue-div');
572 currentOverlayRecordsMap = {};
574 if(!vlQueueGridBuilt) {
575 var defs = (type == 'bib') ? bibAttrDefs : authAttrDefs;
576 for(var i = 0; i < defs.length; i++) {
578 attrDefMap[def.code()] = def.id();
580 name:def.description(),
581 field:'attr.' + def.code(),
583 selectableColumn:true
585 vlQueueGridLayout[0].cells[0].push(col);
587 vlQueueGridBuilt = true;
592 storeData = vqbr.toStoreData(queuedRecords);
594 storeData = vqar.toStoreData(queuedRecords);
596 var store = new dojo.data.ItemFileReadStore({data:storeData});
597 var model = new dojox.grid.data.DojoData(
598 null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
599 vlQueueGrid.setModel(model);
601 if(vlQueueGridColumePicker) {
602 vlQueueGrid.update();
604 vlQueueGridColumePicker =
605 new openils.GridColumnPicker(vlQueueGridColumePickerDialog,
606 vlQueueGrid, vlQueueGridLayout, authtoken, 'vandelay.queue');
607 vlQueueGridColumePicker.load();
611 function vlQueueGridPrevPage() {
612 var page = parseInt(vlQueueDisplayPage.getValue());
614 vlQueueDisplayPage.setValue(page - 1);
615 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
618 function vlQueueGridNextPage() {
619 vlQueueDisplayPage.setValue(parseInt(vlQueueDisplayPage.getValue())+1);
620 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
623 function vlDeleteQueue(type, queueId, onload) {
624 fieldmapper.standardRequest(
625 ['open-ils.vandelay', 'open-ils.vandelay.'+type+'_queue.delete'],
627 params: [authtoken, queueId],
628 oncomplete: function(r) {
629 var resp = r.recv().content();
630 if(e = openils.Event.parse(resp))
639 function vlQueueGridDrawSelectBox(rowIdx) {
640 var data = this.grid.model.getRow(rowIdx);
642 var domId = 'vl-record-list-selected-' +data.id;
643 selectableGridRecords[domId] = data.id;
644 return "<div><input type='checkbox' id='"+domId+"'/></div>";
647 function vlSelectAllQueueGridRecords() {
648 for(var id in selectableGridRecords)
649 dojo.byId(id).checked = true;
651 function vlSelectNoQueueGridRecords() {
652 for(var id in selectableGridRecords)
653 dojo.byId(id).checked = false;
655 function vlToggleQueueGridSelect() {
656 if(dojo.byId('vl-queue-grid-row-selector').checked)
657 vlSelectAllQueueGridRecords();
659 vlSelectNoQueueGridRecords();
662 var handleRetrieveRecords = function() {
663 buildRecordGrid(currentType);
666 function vlImportSelectedRecords() {
667 displayGlobalDiv('vl-generic-progress-with-total');
670 for(var id in selectableGridRecords) {
671 if(dojo.byId(id).checked) {
672 var recId = selectableGridRecords[id];
673 var rec = queuedRecordsMap[recId];
674 if(!rec.import_time())
679 fieldmapper.standardRequest(
680 ['open-ils.vandelay', 'open-ils.vandelay.'+currentType+'_record.list.import'],
682 params: [authtoken, records, {overlay_map:currentOverlayRecordsMap}],
683 onresponse: function(r) {
684 var resp = r.recv().content();
685 if(e = openils.Event.parse(resp))
687 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
689 oncomplete: function() {
690 return retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
696 function vlImportRecordQueue(type, queueId, noMatchOnly, onload) {
697 displayGlobalDiv('vl-generic-progress-with-total');
698 var method = 'open-ils.vandelay.bib_queue.import';
700 method = method.replace('import', 'nomatch.import');
702 method = method.replace('bib', 'auth');
704 fieldmapper.standardRequest(
705 ['open-ils.vandelay', method],
707 params: [authtoken, queueId],
708 onresponse: function(r) {
709 var resp = r.recv().content();
710 if(e = openils.Event.parse(resp))
712 vlControlledProgressBar.update({maximum:resp.total, progress:resp.progress});
714 oncomplete: function() {onload();}
721 * Create queue, upload MARC, process spool, load the newly created queue
723 function batchUpload() {
724 var queueName = dijit.byId('vl-queue-name').getValue();
725 currentType = dijit.byId('vl-record-type').getValue();
727 var handleProcessSpool = function() {
728 console.log('records uploaded and spooled');
729 if(vlUploadQueueAutoImport.checked) {
730 vlImportRecordQueue(currentType, currentQueueId, true,
732 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
736 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
740 var handleUploadMARC = function(key) {
741 console.log('marc uploaded');
742 dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');
743 processSpool(key, currentQueueId, currentType, handleProcessSpool);
746 var handleCreateQueue = function(queue) {
747 console.log('queue created ' + queue.name());
748 currentQueueId = queue.id();
749 uploadMARC(handleUploadMARC);
752 if(vlUploadQueueSelector.getValue() && !queueName) {
753 currentQueueId = vlUploadQueueSelector.getValue();
754 console.log('adding records to existing queue ' + currentQueueId);
755 uploadMARC(handleUploadMARC);
757 createQueue(queueName, currentType, handleCreateQueue);
762 function vlFleshQueueSelect(selector, type) {
763 var data = (type == 'bib') ? vbq.toStoreData(allUserBibQueues) : vaq.toStoreData(allUserAuthQueues);
764 selector.store = new dojo.data.ItemFileReadStore({data:data});
765 selector.setValue(null);
766 selector.setDisplayedValue('');
768 selector.setValue(data[0].id());
771 function vlShowUploadForm() {
772 displayGlobalDiv('vl-marc-upload-div');
773 vlFleshQueueSelect(vlUploadQueueSelector, vlUploadRecordType.getValue());
776 function vlShowQueueSelect() {
777 displayGlobalDiv('vl-queue-select-div');
778 vlFleshQueueSelect(vlQueueSelectQueueList, vlQueueSelectType.getValue());
781 function vlFetchQueueFromForm() {
782 currentType = vlQueueSelectType.getValue();
783 currentQueueId = vlQueueSelectQueueList.getValue();
784 retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);
787 function vlOpenMarcEditWindow(rec, postReloadHTMLHandler) {
789 To run in Firefox directly, must set signed.applets.codebase_principal_support
790 to true in about:config
792 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
793 win = window.open('/xul/server/cat/marcedit.xul'); // XXX version?
796 // after the record is saved, reload the HTML display
797 var stat = r.recv().content();
798 if(e = openils.Event.parse(stat))
800 alert(dojo.byId('vl-marc-edit-complete-label').innerHTML);
802 vlLoadMARCHtml(rec.id(), false, postReloadHTMLHandler);
806 record : {marc : rec.marc()},
808 label: dojo.byId('vl-marc-edit-save-label').innerHTML,
809 func: function(xmlString) {
810 var method = 'open-ils.permacrud.update.' + rec.classname;
812 fieldmapper.standardRequest(
813 ['open-ils.permacrud', method],
815 params: [authtoken, rec],
824 function vlLoadMarcEditor(type, recId, postReloadHTMLHandler) {
825 var method = 'open-ils.permacrud.search.vqbr';
826 if(currentType != 'bib')
827 method = method.replace(/vqbr/,'vqar');
829 fieldmapper.standardRequest(
830 ['open-ils.permacrud', method],
832 params: [authtoken, {id : recId}],
833 oncomplete: function(r) {
834 var rec = r.recv().content();
835 if(e = openils.Event.parse(rec))
837 vlOpenMarcEditWindow(rec, postReloadHTMLHandler);
845 //------------------------------------------------------------
848 // attribute-editor global variables
850 var ATTR_EDITOR_IN_UPDATE_MODE = false; // true on 'edit', false on 'create'
851 var ATTR_EDIT_ID = null; // id of current 'edit' attribute
852 var ATTR_EDIT_GROUP = 'bib'; // bib-attrs or auth-attrs
854 function vlAttrEditorInit() {
855 // set up tooltips on the edit form
856 connectTooltip('attr-editor-tags');
857 connectTooltip('attr-editor-subfields');
860 function vlShowAttrEditor() {
861 displayGlobalDiv('vl-attr-editor-div');
862 loadAttrEditorGrid();
863 idHide('vl-generic-progress');
866 function setAttrEditorGroup(groupName) {
867 // put us into 'bib'-attr or 'auth'-attr mode.
868 if (ATTR_EDIT_GROUP != groupName) {
869 ATTR_EDIT_GROUP = groupName;
870 loadAttrEditorGrid();
874 function onAttrEditorOpen() {
875 // the "bars" have the create/update/cancel/etc. buttons.
876 var create_bar = document.getElementById('attr-editor-create-bar');
877 var update_bar = document.getElementById('attr-editor-update-bar');
878 if (ATTR_EDITOR_IN_UPDATE_MODE) {
879 update_bar.style.display='table-row';
880 create_bar.style.display='none';
881 // hide the dropdown-button
882 idStyle('vl-create-attr-editor-button', 'visibility', 'hidden');
884 dijit.byId('attr-editor-dialog').reset();
885 create_bar.style.display='table-row';
886 update_bar.style.display='none';
890 function onAttrEditorClose() {
891 // reset the form to a "create" form. (We may have borrowed it for editing.)
892 ATTR_EDITOR_IN_UPDATE_MODE = false;
893 // show the dropdown-button
894 idStyle('vl-create-attr-editor-button', 'visibility', 'visible');
897 function loadAttrEditorGrid() {
898 var _data = (ATTR_EDIT_GROUP == 'auth') ?
899 vqarad.toStoreData(authAttrDefs) : vqbrad.toStoreData(bibAttrDefs) ;
901 var store = new dojo.data.ItemFileReadStore({data:_data});
902 var model = new dojox.grid.data.DojoData(
903 null, store, {rowsPerPage: 100, clientSort: true, query:{id:'*'}});
904 attrEditorGrid.setModel(model);
905 attrEditorGrid.setStructure(vlAttrGridLayout);
906 attrEditorGrid.onRowClick = onAttrEditorClick;
907 attrEditorGrid.update();
910 function attrGridGetTag(n) {
911 // grid helper: return the tags from the row's xpath column.
912 var xp = this.grid.model.getRow(n);
913 return xp && xpathParser.parse(xp.xpath).tags;
916 function attrGridGetSubfield(n) {
917 // grid helper: return the subfields from the row's xpath column.
918 var xp = this.grid.model.getRow(n);
919 return xp && xpathParser.parse(xp.xpath).subfields;
922 function onAttrEditorClick(evt) {
923 var row = attrEditorGrid.model.getRow(evt.rowIndex);
924 ATTR_EDIT_ID = row.id;
925 ATTR_EDITOR_IN_UPDATE_MODE = true;
927 // populate the popup editor.
928 dojo.byId('attr-editor-code').value = row.code;
929 dojo.byId('attr-editor-description').value = row.description;
930 var parsed_xpath = xpathParser.parse(row.xpath);
931 dojo.byId('attr-editor-tags').value = parsed_xpath.tags;
932 dojo.byId('attr-editor-subfields').value = parsed_xpath.subfields;
933 dojo.byId('attr-editor-identifier').value = (row.ident ? 'True':'False');
934 dojo.byId('attr-editor-xpath').value = row.xpath;
935 dojo.byId('attr-editor-remove').value = row.remove;
937 // set up UI for editing
938 dojo.byId('vl-create-attr-editor-button').click();
941 function vlSaveAttrDefinition(data) {
942 idHide('vl-attr-editor-div');
943 idShow('vl-generic-progress');
945 data.id = ATTR_EDIT_ID;
947 // this ought to honour custom xpaths, but overwrite xpaths
948 // derived from tags/subfields.
949 if (data.xpath == '' || looksLikeDerivedXpath(data.xpath)) {
950 var _xpath = tagAndSubFieldsToXpath(data.tag, data.subfield);
954 // build up our permacrud params. Key variables here are
955 // "create or update" and "bib or auth".
957 var isAuth = (ATTR_EDIT_GROUP == 'auth');
958 var isCreate = (ATTR_EDIT_ID == null);
959 var rad = isAuth ? new vqarad() : new vqbrad() ;
960 var method = 'open-ils.permacrud' + (isCreate ? '.create.' : '.update.')
961 + (isAuth ? 'vqarad' : 'vqbrad');
962 var _data = rad.fromStoreItem(data);
966 fieldmapper.standardRequest(
967 ['open-ils.permacrud', method],
969 params: [authtoken, _data ],
970 onresponse: function(r) { },
971 oncomplete: function(r) {
972 attrEditorFetchAttrDefs(vlShowAttrEditor);
975 onerror: function(r) {
976 alert('vlSaveAttrDefinition comms error: ' + r);
982 function attrEditorFetchAttrDefs(callback) {
983 var fn = (ATTR_EDIT_GROUP == 'auth') ? vlFetchAuthAttrDefs : vlFetchBibAttrDefs;
987 function vlAttrDelete() {
988 idHide('vl-attr-editor-div');
989 idShow('vl-generic-progress');
991 var isAuth = (ATTR_EDIT_GROUP == 'auth');
992 var method = 'open-ils.permacrud.delete.' + (isAuth ? 'vqarad' : 'vqbrad');
993 var rad = isAuth ? new vqarad() : new vqbrad() ;
994 fieldmapper.standardRequest(
995 ['open-ils.permacrud', method],
997 params: [authtoken, rad.fromHash({ id : ATTR_EDIT_ID }), ],
998 oncomplete: function() {
999 dijit.byId('attr-editor-dialog').onCancel(); // close the dialog
1000 attrEditorFetchAttrDefs(vlShowAttrEditor);
1001 ATTR_EDIT_ID = null;
1003 onerror: function(r) {
1004 alert('vlAttrDelete comms error: ' + r);
1010 // ------------------------------------------------------------
1011 // utilities for attribute editors
1013 // dom utilities (maybe dojo does these, and these should be replaced)
1015 function idStyle(obId, k, v) { document.getElementById(obId).style[k] = v; }
1016 function idShow(obId) { idStyle(obId, 'display', 'block'); }
1017 function idHide(obId) { idStyle(obId, 'display' , 'none'); }
1019 function connectTooltip(fieldId) {
1020 // Given an element id, look up a tooltip element in the doc (same
1021 // id with a '-tip' suffix) and associate the two. Maybe dojo has
1022 // a better way to do this?
1023 var fld = dojo.byId(fieldId);
1024 var tip = dojo.byId(fieldId + '-tip');
1025 dojo.connect(fld, 'onfocus', function(evt) {
1026 dijit.showTooltip(tip.innerHTML, fld, ['below', 'after']); });
1027 dojo.connect(fld, 'onblur', function(evt) { dijit.hideTooltip(fld); });
1032 var xpathParser = new openils.MarcXPathParser();
1034 function tagAndSubFieldsToXpath(tags, subfields) {
1035 // given tags, and subfields, build up an XPath.
1038 'tags':tags.match(/[\d]+/g),
1039 'subfields':subfields.match(/[a-zA-z]/g) };
1040 return xpathParser.compile(parts);
1042 return {'parts':null, 'tags':null, 'error':err};
1046 function looksLikeDerivedXpath(path) {
1047 // Does this path look like it was derived from tags and subfields?
1048 var parsed = xpathParser.parse(path);
1049 if (parsed.tags == null)
1051 var compiled = xpathParser.compile(parsed);
1052 return (path == compiled);
1055 // amazing xpath-util unit-tests
1056 if (!looksLikeDerivedXpath('//*[@tag="901"]/*[@code="c"]')) alert('vandelay xpath-utility error');
1057 if ( looksLikeDerivedXpath('ba-boo-ba-boo!')) alert('vandelay xpath-utility error');