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