]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/cat/authority/list.js
7486427d13f1b3ba587094d56fbddde46a5da02c
[working/Evergreen.git] / Open-ILS / web / js / ui / default / cat / authority / list.js
1 dojo.require('dijit.Dialog');
2 dojo.require('dijit.form.Button');
3 dojo.require('dijit.form.DropDownButton');
4 dojo.require('dijit.form.FilteringSelect');
5 dojo.require('dijit.form.Form');
6 dojo.require('dijit.form.NumberSpinner');
7 dojo.require('dijit.form.TextBox');
8 dojo.require("dijit.Menu");
9 dojo.require("dijit.MenuItem");
10 dojo.require('dojox.xml.parser');
11 dojo.require('DojoSRF');
12 dojo.require("fieldmapper.Fieldmapper");
13 dojo.require('openils.CGI');
14 dojo.require('openils.PermaCrud');
15 dojo.require('openils.XUL');
16 dojo.require('openils.widget.OrgUnitFilteringSelect');
17 dojo.require("openils.widget.PCrudAutocompleteBox");
18 dojo.require("MARC.FixedFields");
19 dojo.requireLocalization("openils.authority", "authority");
20 var auth_strings = dojo.i18n.getLocalization("openils.authority", "authority");
21
22 var cgi = new openils.CGI();
23 var pcrud = new openils.PermaCrud();
24
25 var _acs_cache_by_at = {};
26 function fetch_control_set(thesaurus) {
27     if (!_acs_cache_by_at[thesaurus]) {
28         var at = pcrud.retrieve(
29             "at", thesaurus,
30             {"flesh": 1, "flesh_fields": {"at": ["control_set"]}}
31         );
32         _acs_cache_by_at[thesaurus] = at.control_set();
33     }
34     return _acs_cache_by_at[thesaurus];
35 }
36
37 /*
38 // OrgUnits do not currently affect the retrieval of authority records,
39 // but this is how to display them if they become OrgUnit-aware
40 function authOUListInit() {
41     new openils.User().buildPermOrgSelector(
42         "STAFF_LOGIN", // anywhere you can log in
43         dijit.byId("authOU"),
44         null, // pre-selected org
45         null
46     );
47 }
48 dojo.addOnLoad(authOUListInit);
49 */
50 function displayAuthorities(data) { 
51
52     var idArr = [];
53     // Grab each record from the returned authority records
54     dojo.query("record", data).forEach(function(node) {
55         var auth = {};
56         auth.text = '';
57         auth.thesaurus = '|';
58         auth.id = 0;
59
60         // Grab each authority record field from the authority record
61         dojo.query("datafield[tag^='1']", node).forEach(function(dfNode) {
62             auth.text += dojox.xml.parser.textContent(dfNode); 
63             auth.name = dojo.attr(dfNode, 'tag');
64             auth.ind1 = dojo.attr(dfNode, 'ind1');
65             auth.ind2 = dojo.attr(dfNode, 'ind2');
66         });
67
68         
69         // Grab the ID of the authority record
70         dojo.query("datafield[tag='901'] subfield[code='c']", node).forEach(function(dfNode) {
71             auth.id = dojox.xml.parser.textContent(dfNode); 
72         });
73
74         /* I wrap this in try/catch only because:
75          *  a) this interface hasn't hitherto relied on MARC.Record, and
76          *  b) the functionality we need it for is optional
77          */
78         try {
79             var marc = new MARC.Record({"rtype": "AUT", "xml": node});
80             auth.thesaurus = marc.extractFixedField("Subj", "|");
81         } catch (E) {
82             console.warn(
83                 "MARC.Record didn't work for authority record " +
84                 auth.id + ": " + E
85             );
86         }
87
88         idArr.push(parseInt(auth.id));
89
90         // Create the authority record listing entry. XXX i18n
91         dojo.place(
92             '<div class="authEntry" id="auth' + auth.id + '">' +
93             '<div class="text" id="authLabel' + auth.id + '">' + auth.text + '</div>' +
94             '<div class="authority-control-set">Control Set: <span class="acs-name">' +
95             fetch_control_set(auth.thesaurus).name() +
96             '</span> <span class="acs-id">(#' +
97             fetch_control_set(auth.thesaurus).id() + ')</span></div></div>',
98             "authlist-div", "last"
99         );
100
101         // Add the menu of new/edit/delete/mark-for-merge options
102         var auth_menu = new dijit.Menu({});
103
104         // "Edit" menu item
105         new dijit.MenuItem({"id": "edit_" + auth.id, "onClick": function(){
106             var auth_rec = pcrud.retrieve("are", auth.id);
107             if (auth_rec) {
108                 loadMarcEditor(pcrud, auth_rec);
109             }
110         }, "label":auth_strings.MENU_EDIT}).placeAt(auth_menu, "first");
111
112         // "Merge" menu item
113         new dijit.MenuItem({"id": "merge_" + auth.id, "onClick":function(){
114             auth.text = '';
115             dojo.query('#auth' + auth.id + ' span.text').forEach(function(node) {
116                 auth.text += dojox.xml.parser.textContent(node); 
117             });
118
119             // If there is a toMerge item already, this is a target record
120             var mergeRole = '<td style="border: 1px solid black; padding-left: 0.5em; padding-right: 1em;">';
121             var isTarget = dojo.query('.toMerge').length;
122             if (isTarget) {
123                 mergeRole += auth_strings.TARGET_RECORD + '</td>';
124             } else {
125                 mergeRole += auth_strings.MASTER_RECORD + '</td>';
126             }
127
128             dojo.place('<tr class="toMerge" id="toMerge_' + auth.id + '"><td>' + mergeRole + '</td><td  style="border: 1px solid black;" id="mergeMeta_' + auth.id + '"></td><td style="border: 1px solid black; padding-left: 1em; padding-right: 1em;" >' + auth.text + '</td></tr>', 'mergebox-tbody', 'last');
129             dojo.place('<span class="authmeta" style="font-family: monospace;">' + auth.name + ' ' + auth.ind1 + auth.ind2 + '</span>', 'mergeMeta_' + auth.id, 'last');
130             dojo.removeClass('mergebox-div', 'hidden');
131         }, "label":auth_strings.MENU_MERGE}).placeAt(auth_menu, "last");
132
133         // "Delete" menu item
134         new dijit.MenuItem({
135             "id": "delete_" + auth.id,
136             "onClick":function(){
137                 auth.text = '';
138
139                 var auth_rec = pcrud.retrieve("are", auth.id);
140
141                 // Bit of a hack to get the linked bib count until an explicit ID
142                 var linkedBibs = dojox.xml.parser.textContent(
143                     dojo.query("#authLabel" + auth.id)[0].previousSibling
144                 );
145
146                 var delDlg = dijit.byId("delDialog_" + auth.id);
147
148                 dojo.query('#auth' + auth.id + ' span.text').forEach(function(node) {
149                     auth.text += dojo.trim(dojox.xml.parser.textContent(node)); 
150                 });
151
152                 if (!delDlg) {
153                     var content = '<div>' + dojo.string.substitute(auth_strings.CONFIRM_DELETE_TITLE, [auth.text]) + '</div>';
154                     if (parseInt(linkedBibs) > 0) {
155                         content = "<div id='delAuthSum_" + auth.id + "'>"
156                             + dojo.string.substitute(auth_strings.LINKED_BIBS, [linkedBibs])
157                             + "</div>";
158                     }
159                     content += "<div id='authMARC" + auth.id + "' style='width: 100%; display:none;'>";
160                     content += "<hr style='width: 100%;' />";
161                     content += marcToHTML(auth_rec.marc());
162                     content += "</div><hr style='width: 100%;' /><div>";
163                     content += "<input type='button' dojoType='dijit.form.Button' label='" + auth_strings.CANCEL + "' onClick='cancelDelete(" + auth.id + ")'/>";
164                     content += "<input type='button' dojoType='dijit.form.Button' label='" + auth_strings.DELETE + "' onClick='confirmDelete(" + auth.id + ")'/>";
165                     content += "<input id='viewMARC" + auth.id + "' type='button' "
166                         + "style='float:right;' dojoType='dijit.form.Button' "
167                         + "label='" + auth_strings.VIEW_MARC + "' onClick='viewMARC(" + auth.id + ")'/>";
168                     content += "<input id='hideMARC" + auth.id + "' type='button' "
169                         + "style='display: none; float:right;' dojoType='dijit.form.Button' "
170                         + "label='" + auth_strings.HIDE_MARC + "' onClick='hideMARC(" + auth.id + ")'/>";
171                     content += "</div>";
172                     delDlg = new dijit.Dialog({
173                         "id":"delDialog_" + auth.id,
174                         "title": dojo.string.substitute(auth_strings.CONFIRM_DELETE_PROMPT, [auth.id]),
175                         "content": content
176                     });
177                 }
178                 delDlg.show();
179
180         }, "label":auth_strings.DELETE}).placeAt(auth_menu, "last");
181
182         auth_mb = new dijit.form.DropDownButton({dropDown: auth_menu, label: auth_strings.ACTIONS, id:"menu" + auth.id});
183         auth_mb.placeAt(dojo.create("div", null, "auth" + auth.id, "first"), "first");
184         auth_menu.startup();
185     });
186
187     showBibCount(idArr);
188 }
189
190 function viewMARC(recId) {
191     dojo.style(dojo.byId("authMARC" + recId), 'display', 'block');
192     dojo.style(dijit.byId("viewMARC" + recId).domNode, 'display', 'none');
193     dojo.style(dijit.byId("hideMARC" + recId).domNode, 'display', 'block');
194 }
195
196 function hideMARC(recId) {
197     dojo.style(dojo.byId("authMARC" + recId), 'display', 'none');
198     dojo.style(dijit.byId("hideMARC" + recId).domNode, 'display', 'none');
199     dojo.style(dijit.byId("viewMARC" + recId).domNode, 'display', 'block');
200 }
201
202 function marcToHTML(marc) {
203     var html = '<table><tbody>';
204     marc = dojox.xml.parser.parse(marc);
205     dojo.query('leader', marc).forEach(function(node) {
206         html += '<tr><td>LDR</td><td>&nbsp;</td><td>&nbsp;</td><td>' + dojox.xml.parser.textContent(node) + '</td></tr>';
207     });
208     dojo.query('controlfield', marc).forEach(function(node) {
209         html += '<tr><td>' + dojo.attr(node, "tag") + '</td><td>&nbsp;</td><td>&nbsp;</td><td>' + dojox.xml.parser.textContent(node) + '</td></tr>';
210     });
211     dojo.query('datafield', marc).forEach(function(node) {
212         var cnt = 0;
213         html += '<tr><td>' + dojo.attr(node, "tag") + '</td><td>' + dojo.attr(node, "ind1") + '</td><td>' + dojo.attr(node, "ind2") + '</td>';
214         dojo.query('subfield', node).forEach(function(sf) {
215             if (cnt == 0) {
216                 html += '<td>$' + dojo.attr(sf, "code") + ' ' + dojox.xml.parser.textContent(sf) + '</td></tr>';
217                 cnt = 1;
218             } else {
219                 html += '<tr><td colspan="3"></td><td>$' + dojo.attr(sf, "code") + ' ' + dojox.xml.parser.textContent(sf) + '</td></tr>';
220             }
221         });
222     });
223     html += '</tbody></table>';
224     return html;
225 }
226
227 function cancelDelete(recId) {
228     dijit.byId("delDialog_" + recId).hide();
229 }
230
231 function confirmDelete(recId) {
232     var auth_rec = pcrud.retrieve("are", recId);
233     if (auth_rec) {
234         pcrud.eliminate(auth_rec);
235         dijit.byId("delDialog_" + recId).attr("content", dojo.string.substitute(auth_strings.CONFIRM_DELETE_RESULT, [recId]));
236         setTimeout(function() {
237             dijit.byId("delDialog_" + recId).hide();
238         }, 3000);
239     }
240 }
241
242 function showBibCount(authIds) {
243     /* Decorate the list with # of bibs linked to each authority record */
244     var ses = new OpenSRF.ClientSession('open-ils.cat');
245     var req = ses.request('open-ils.cat.authority.records.count_linked_bibs', authIds);
246     var linkedIds = [];
247     req.oncomplete = function(r) {
248         var msg = r.recv().content();
249         dojo.forEach(msg, function(auth) {
250                 linkedIds.push(auth.authority);
251                 dojo.place('<span class="bibcount">' + auth.bibs + '</span> ', 'authLabel' + auth.authority, 'first');
252             }
253         );
254
255         /* Assign counts of 0 for every non-linked authority */
256         dojo.forEach(authIds, function (id) {
257             var found = false;
258             dojo.forEach(linkedIds, function (lid) {
259                 if (id == lid) {
260                     found = true;
261                 }
262             });
263             if (!found) {
264                 dojo.place('<span class="bibcount">0</span> ', 'authLabel' + id, 'first');
265             }
266         });
267     }
268     req.send();
269 }
270
271 function loadMarcEditor(pcrud, rec) {
272     /*
273        To run in Firefox directly, must set signed.applets.codebase_principal_support
274        to true in about:config
275      */
276     netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
277     win = window.open('/xul/server/cat/marcedit.xul'); // XXX version?
278
279     win.xulG = {
280         "record": {"marc": rec.marc(), "rtype": "are"},
281         "save": {
282             "label": auth_strings.SAVE,
283             "func": function(xmlString) {
284                 rec.marc(xmlString);
285                 rec.edit_date('now');
286                 rec.ischanged(true);
287                 pcrud.update(rec);
288                 alert(auth_strings.SAVE_RESULT_SUCCESS);
289                 win.close();
290             }
291         },
292         'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
293         'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
294     };
295 }
296
297 function authListInit() {
298     var term = cgi.param('authTerm') || '';
299     var page = cgi.param('authPage') || 0;
300     var axis = cgi.param('authAxis') || 'authority.author';
301     if (axis) {
302         dijit.byId('authAxis').attr('value', axis);
303     }
304     if (page) {
305         dijit.byId('authPage').attr('value', page);
306     }
307     if (term) {
308         dijit.byId('authTerm').attr('value', term);
309         displayRecords();
310     }
311
312     dojo.connect(dijit.byId('authAxis'), 'onKeyPress', function(evt) {
313         if (evt.keyCode == dojo.keys.ENTER) {
314             dijit.byId('authPage').attr('value', 0);
315             displayRecords();
316         }
317     }); 
318
319     dojo.connect(dijit.byId('authPage'), 'onKeyPress', function(evt) {
320         if (evt.keyCode == dojo.keys.ENTER) {
321             dijit.byId('authPage').attr('value', 0);
322             displayRecords();
323         }
324     });
325
326     dojo.connect(dijit.byId('authTerm'), 'onKeyPress', function(evt) {
327         if (evt.keyCode == dojo.keys.ENTER) {
328             dijit.byId('authPage').attr('value', 0);
329             displayRecords();
330         }
331     });
332
333     dijit.byId('authTerm').focus();
334
335 }
336 dojo.addOnLoad(authListInit);
337
338 function displayRecords(parms) {
339
340     if (parms && parms.page) {
341         if (parms.page == 'next') {
342             page = dijit.byId('authPage').attr('value');
343             dijit.byId('authPage').attr('value', page + 1);
344         } else if (parms.page == 'prev') {
345             page = dijit.byId('authPage').attr('value');
346             dijit.byId('authPage').attr('value', page - 1);
347         } else {
348             dijit.byId('authPage').attr('value', parms.page);
349         }
350     }
351
352     /* Protect against null input */
353     if (!dijit.byId('authTerm').attr('value')) {
354         return;
355     }
356
357     /* Clear out the current contents of the page */
358     var widgets = dijit.findWidgets(dojo.byId('authlist-div'));
359     dojo.forEach(widgets, function(w) { w.destroyRecursive(true); });
360
361     dojo.query("#authlist-div div").orphan();
362
363     var url = '/opac/extras/browse/marcxml/authority.'
364         + dijit.byId('authAxis').attr('value')
365         // + '/' + dijit.byId('authOU').attr('value')
366         + '/1' // replace with preceding line if OUs gain some meaning
367         + '/' + dijit.byId('authTerm').attr('value')
368         + '/' + dijit.byId('authPage').attr('value')
369         + '/' + '20' // 20 results per page
370     ;
371     dojo.xhrGet({"url":url, "handleAs":"xml", "content":{"format":"marcxml"}, "preventCache": true, "load":displayAuthorities });
372 }
373
374 function clearMergeRecords() {
375     var records = dojo.query('.toMerge').orphan();
376     dojo.addClass('mergebox-div', 'hidden');
377 }
378
379 function mergeRecords() {
380     var records = dojo.query('.toMerge').attr('id');
381     dojo.forEach(records, function(item, idx) {
382         records[idx] = parseInt(item.slice(item.lastIndexOf('_') + 1));
383     });
384
385     /* Take the first record in the list and use that as the master */
386     fieldmapper.standardRequest(
387         ['open-ils.cat', 'open-ils.cat.authority.records.merge'],
388         {   async: false,
389             params: [openils.User.authtoken, records.shift(), records],
390             oncomplete : function(r) {
391                 alert(auth_strings.MERGE_RESULT_SUCCESS);
392                 clearMergeRecords();
393                 displayRecords();
394             }
395         }
396     );
397 }