1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('openils.CGI');
4 dojo.require('openils.Util');
5 dojo.require('openils.User');
6 dojo.require('openils.Event');
7 dojo.require('openils.widget.ProgressDialog');
9 dojo.requireLocalization('openils.circ', 'selfcheck');
10 var localeStrings = dojo.i18n.getLocalization('openils.circ', 'selfcheck');
13 const SET_BARCODE_REGEX = 'opac.barcode_regex';
14 const SET_PATRON_TIMEOUT = 'circ.selfcheck.patron_login_timeout';
15 const SET_AUTO_OVERRIDE_EVENTS = 'circ.selfcheck.auto_override_checkout_events';
16 const SET_PATRON_PASSWORD_REQUIRED = 'circ.selfcheck.patron_password_required';
17 const SET_AUTO_RENEW_INTERVAL = 'circ.checkout_auto_renew_age';
18 const SET_WORKSTATION_REQUIRED = 'circ.selfcheck.workstation_required';
19 const SET_ALERT_POPUP = 'circ.selfcheck.alert.popup';
20 const SET_ALERT_SOUND = 'circ.selfcheck.alert.sound';
22 function SelfCheckManager() {
24 this.cgi = new openils.CGI();
26 this.workstation = null;
27 this.authtoken = null;
30 this.patronBarcodeRegex = null;
34 // During renewals, keep track of the ID of the previous circulation.
35 // Previous circ is used for tracking failed renewals (for receipts).
38 // current item barcode
39 this.itemBarcode = null;
41 // are we currently performing a renewal?
42 this.isRenewal = false;
44 // dict of org unit settings for "here"
45 this.orgSettings = {};
47 // Construct a mock checkout for debugging purposes
48 if(this.mockCheckouts = this.cgi.param('mock-circ')) {
52 record : new fieldmapper.mvr(),
53 copy : new fieldmapper.acp(),
54 circ : new fieldmapper.circ()
58 this.mockCheckout.payload.record.title('Jazz improvisation for guitar');
59 this.mockCheckout.payload.record.author('Wise, Les');
60 this.mockCheckout.payload.record.isbn('0634033565');
61 this.mockCheckout.payload.copy.barcode('123456789');
62 this.mockCheckout.payload.circ.renewal_remaining(1);
63 this.mockCheckout.payload.circ.parent_circ(1);
64 this.mockCheckout.payload.circ.due_date('2012-12-21');
71 * Fetch the org-unit settings, initialize the display, etc.
73 SelfCheckManager.prototype.init = function() {
75 this.staff = openils.User.user;
76 this.workstation = openils.User.workstation;
77 this.authtoken = openils.User.authtoken;
78 this.loadOrgSettings();
80 // workstation is required but none provided
81 if(this.orgSettings[SET_WORKSTATION_REQUIRED] && !this.workstation) {
82 alert(dojo.string.substitute(localeStrings.WORKSTATION_REQUIRED));
87 // connect onclick handlers to the various navigation links
89 'oils-selfck-hold-details-link' : function() { self.drawHoldsPage(); },
90 'oils-selfck-nav-holds' : function() { self.drawHoldsPage(); },
91 'oils-selfck-pay-fines-link' : function() { self.drawFinesPage(); },
92 'oils-selfck-nav-fines' : function() { self.drawFinesPage(); },
93 'oils-selfck-nav-home' : function() { self.drawCircPage(); },
94 'oils-selfck-nav-logout' : function() { self.logoutPatron(); }
97 for(var id in linkHandlers)
98 dojo.connect(dojo.byId(id), 'onclick', linkHandlers[id]);
101 if(this.cgi.param('patron')) {
103 // Patron barcode via cgi param. Mainly used for debugging and
104 // only works if password is not required by policy
105 this.loginPatron(this.cgi.param('patron'));
108 this.drawLoginPage();
112 * To test printing, pass a URL param of 'testprint'. The value for the param
113 * should be a JSON string like so: [{circ:<circ_id>}, ...]
115 var testPrint = this.cgi.param('testprint');
117 this.checkouts = JSON2js(testPrint);
124 * Loads the org unit settings
126 SelfCheckManager.prototype.loadOrgSettings = function() {
128 var settings = fieldmapper.aou.fetchOrgSettingBatch(
129 this.staff.ws_ou(), [
134 SET_AUTO_OVERRIDE_EVENTS,
135 SET_PATRON_PASSWORD_REQUIRED,
136 SET_AUTO_RENEW_INTERVAL,
137 SET_WORKSTATION_REQUIRED
143 this.orgSettings[k] = settings[k].value;
146 if(settings[SET_BARCODE_REGEX])
147 this.patronBarcodeRegex = new RegExp(settings[SET_BARCODE_REGEX].value);
150 SelfCheckManager.prototype.drawLoginPage = function() {
153 var bcHandler = function(barcode) {
154 // handle patron barcode entry
156 if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
158 // password is required. wire up the scan box to read it
160 msg : 'Please enter your password', // TODO i18n
161 handler : function(pw) { self.loginPatron(barcode, pw); },
166 // password is not required, go ahead and login
167 self.loginPatron(barcode);
172 msg : 'Please log in with your library barcode.', // TODO
180 SelfCheckManager.prototype.loginPatron = function(barcode, passwd) {
182 if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
185 // would only happen in dev/debug mode when using the patron= param
186 alert('password required by org setting. remove patron= from URL');
190 // patron password is required. Verify it.
192 var res = fieldmapper.standardRequest(
193 ['open-ils.actor', 'open-ils.actor.verify_user_password'],
194 {params : [this.authtoken, barcode, null, hex_md5(passwd)]}
198 // user-not-found results in login failure
200 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]),
201 false, 'login-failure'
203 this.drawLoginPage();
208 // retrieve the fleshed user by barcode
209 this.patron = fieldmapper.standardRequest(
210 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve_by_barcode'],
211 {params : [this.authtoken, barcode]}
214 var evt = openils.Event.parse(this.patron);
217 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]),
218 false, 'login-failure'
220 this.drawLoginPage();
224 this.handleAlert('', false, 'login-success');
225 dojo.byId('oils-selfck-user-banner').innerHTML = 'Welcome, ' + this.patron.usrname(); // TODO i18n
231 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
233 console.log("Handling alert " + message);
235 dojo.byId('oils-selfck-status-div').innerHTML = message;
237 if(shouldPopup && this.orgSettings[SET_ALERT_POPUP])
240 if(sound && this.orgSettings[SET_ALERT_SOUND])
241 openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
246 * Manages the main input box
247 * @param msg The context message to display with the box
248 * @param clearOnly Don't update the context message, just clear the value and re-focus
249 * @param handler Optional "on-enter" handler.
251 SelfCheckManager.prototype.updateScanBox = function(args) {
255 selfckScanBox.domNode.select();
257 selfckScanBox.attr('value', '');
261 selfckScanBox.domNode.setAttribute('type', 'password');
263 selfckScanBox.domNode.setAttribute('type', '');
267 selfckScanBox.attr('value', args.value);
270 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
272 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
273 dojo.disconnect(selfckScanBox._lastHandler);
277 selfckScanBox._lastHandler = dojo.connect(
281 if(e.keyCode != dojo.keys.ENTER)
283 args.handler(selfckScanBox.attr('value'));
288 selfckScanBox.focus();
292 * Sets up the checkout/renewal interface
294 SelfCheckManager.prototype.drawCircPage = function() {
298 msg : 'Please enter an item barcode', // TODO i18n
299 handler : function(barcode) { self.checkout(barcode); }
302 openils.Util.hide('oils-selfck-payment-page');
303 openils.Util.hide('oils-selfck-holds-page');
304 openils.Util.show('oils-selfck-circ-page');
306 this.circTbody = dojo.byId('oils-selfck-circ-tbody');
307 if(!this.circTemplate)
308 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
310 // items out, holds, and fines summaries
313 fieldmapper.standardRequest(
314 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
316 params : [this.authtoken, this.patron.id()],
317 oncomplete : function(r) {
318 var summary = openils.Util.readResponse(r);
319 dojo.byId('oils-selfck-fines-total').innerHTML =
320 dojo.string.substitute(
321 localeStrings.TOTAL_FINES_ACCOUNT,
322 [summary.balance_owed()]
329 this.updateHoldsSummary();
332 this.updateCircSummary();
334 // render mock checkouts for debugging?
335 if(this.mockCheckouts) {
336 for(var i in [1,2,3])
337 this.displayCheckout(this.mockCheckout, 'checkout');
341 SelfCheckManager.prototype.updateHoldsSummary = function() {
343 if(!this.holdsSummary) {
344 var summary = fieldmapper.standardRequest(
345 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
346 {params : [this.authtoken, this.patron.id()]}
349 this.holdsSummary = {};
350 this.holdsSummary.ready = Number(summary['4']);
351 this.holdsSummary.total = 0;
353 for(var i in summary)
354 this.holdsSummary.total += Number(summary[i]);
357 dojo.byId('oils-selfck-holds-total').innerHTML =
358 dojo.string.substitute(
359 localeStrings.TOTAL_HOLDS,
360 [this.holdsSummary.total]
363 dojo.byId('oils-selfck-holds-ready').innerHTML =
364 dojo.string.substitute(
365 localeStrings.HOLDS_READY_FOR_PICKUP,
366 [this.holdsSummary.ready]
371 SelfCheckManager.prototype.updateCircSummary = function(increment) {
373 if(!this.circSummary) {
375 var summary = fieldmapper.standardRequest(
376 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
377 {params : [this.authtoken, this.patron.id()]}
381 total : Number(summary.out) + Number(summary.overdue),
382 overdue : Number(summary.overdue),
388 // local checkout occurred. Add to the total and the session.
389 this.circSummary.total += 1;
390 this.circSummary.session += 1;
393 dojo.byId('oils-selfck-circ-account-total').innerHTML =
394 dojo.string.substitute(
395 localeStrings.TOTAL_ITEMS_ACCOUNT,
396 [this.circSummary.total]
399 dojo.byId('oils-selfck-circ-session-total').innerHTML =
400 dojo.string.substitute(
401 localeStrings.TOTAL_ITEMS_SESSION,
402 [this.circSummary.session]
407 SelfCheckManager.prototype.drawHoldsPage = function() {
409 // TODO add option to hid scanBox
410 // this.updateScanBox(...)
412 openils.Util.hide('oils-selfck-circ-page');
413 openils.Util.hide('oils-selfck-payment-page');
414 openils.Util.show('oils-selfck-holds-page');
416 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
417 if(!this.holdTemplate)
418 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
419 while(this.holdTbody.childNodes[0])
420 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
422 progressDialog.show(true);
425 fieldmapper.standardRequest( // fetch the hold IDs
427 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
429 params : [this.authtoken, this.patron.id()],
431 oncomplete : function(r) {
432 var ids = openils.Util.readResponse(r);
433 if(!ids || ids.length == 0) {
434 progressDialog.hide();
438 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
439 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve.atomic'],
441 params : [self.authtoken, ids],
443 oncomplete : function(rr) {
444 self.drawHolds(openils.Util.readResponse(rr));
454 * Fetch and add a single hold to the list of holds
456 SelfCheckManager.prototype.drawHolds = function(holds) {
459 // sort available holds to the top of the list
460 // followed by queue position order
462 if(a.status == 4) return -1;
463 if(a.queue_position < b.queue_position) return -1;
468 progressDialog.hide();
470 for(var i in holds) {
473 var row = this.holdTemplate.cloneNode(true);
475 if(data.mvr.isbn()) {
476 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + data.mvr.isbn());
479 this.byName(row, 'title').innerHTML = data.mvr.title();
480 this.byName(row, 'author').innerHTML = data.mvr.author();
482 if(data.status == 4) {
484 // hold is ready for pickup
485 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
489 // hold is still pending
490 this.byName(row, 'status').innerHTML =
491 dojo.string.substitute(
492 localeStrings.HOLD_STATUS_WAITING,
493 [data.queue_position, data.potential_copies]
497 this.holdTbody.appendChild(row);
504 * Check out a single item. If the item is already checked
505 * out to the patron, redirect to renew()
507 SelfCheckManager.prototype.checkout = function(barcode, override) {
509 this.prevCirc = null;
512 this.updateScanbox(null, true);
516 if(this.mockCheckouts) {
517 // if we're in mock-checkout mode, just insert another
518 // fake circ into the table and get out of here.
519 this.displayCheckout(this.mockCheckout, 'checkout');
523 // TODO see if it's a patron barcode
524 // TODO see if this item has already been checked out in this session
526 var method = 'open-ils.circ.checkout.full';
527 if(override) method += '.override';
529 console.log("Checkout out item " + barcode + " with method " + method);
531 var result = fieldmapper.standardRequest(
532 ['open-ils.circ', 'open-ils.circ.checkout.full'],
535 patron_id : this.patron.id(),
536 copy_barcode : barcode
541 console.log(js2JSON(result));
543 var stat = this.handleXactResult('checkout', barcode, result);
546 this.checkout(barcode, true);
547 } else if(stat.renew) {
553 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
555 var displayText = '';
557 // If true, the display message is important enough to pop up. Whether or not
558 // an alert() actually occurs, depends on org unit settings
563 // TODO handle lost/missing/etc checkin+checkout override steps
565 var payload = result.payload || {};
567 if(result.textcode == 'NO_SESSION') {
569 return this.logoutStaff();
571 } else if(result.textcode == 'SUCCESS') {
573 if(action == 'checkout') {
575 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
576 this.displayCheckout(result, 'checkout');
578 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
579 // A hold was fulfilled, update the hold numbers in the circ summary
580 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
581 this.holdsSummary = null;
582 this.updateHoldsSummary();
585 this.updateCircSummary(true);
587 } else if(action == 'renew') {
589 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
590 this.displayCheckout(result, 'renew');
593 this.checkouts.push({circ : result.payload.circ.id()});
594 sound = 'checkout-success';
595 this.updateScanBox();
597 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
599 // Server says the item is already checked out. If it's checked out to the
600 // current user, we may need to renew it.
602 if(payload.old_circ) {
605 old_circ refers to the previous checkout IFF it's for the same user.
606 If no auto-renew interval is not defined, assume we should renew it
607 If an auto-renew interval is defined and the payload comes back with
608 auto_renew set to true, do the renewal. Otherwise, let the patron know
609 the item is already checked out to them. */
611 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
612 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
613 this.prevCirc = payload.old_circ.id();
614 return { renew : true };
618 sound = 'checkout-failure';
619 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
623 // item is checked out to some other user
625 sound = 'checkout-failure';
626 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
629 this.updateScanBox({select:true});
633 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
635 if(overrideEvents && overrideEvents.length) {
637 // see if the events we received are all in the list of
638 // events to override
640 if(!result.length) result = [result];
643 for(var i = 0; i < result.length; i++) {
644 var match = overrideEvents.filter(
645 function(e) { return (e == result[i].textcode); })[0];
653 return { override : true };
656 this.updateScanBox({select : true});
658 sound = 'checkout-failure';
660 if(action == 'renew')
661 this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
666 switch(result.textcode) {
668 // TODO custom handler for blocking penalties
670 case 'MAX_RENEWALS_REACHED' :
671 displayText = dojo.string.substitute(
672 localeStrings.MAX_RENEWALS, [item]);
675 case 'ITEM_NOT_CATALOGED' :
676 displayText = dojo.string.substitute(
677 localeStrings.ITEM_NOT_CATALOGED, [item]);
680 case 'OPEN_CIRCULATION_EXISTS' :
681 displayText = dojo.string.substitute(
682 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
686 console.error('Unhandled event ' + result.textcode);
688 if(action == 'checkout' || action == 'renew') {
689 displayText = dojo.string.substitute(
690 localeStrings.GENERIC_CIRC_FAILURE, [item]);
692 displayText = dojo.string.substitute(
693 localeStrings.UNKNOWN_ERROR, [result.textcode]);
698 this.handleAlert(displayText, popup, sound);
706 SelfCheckManager.prototype.renew = function(barcode, override) {
708 var method = 'open-ils.circ.renew';
709 if(override) method += '.override';
711 console.log("Renewing item " + barcode + " with method " + method);
713 var result = fieldmapper.standardRequest(
714 ['open-ils.circ', method],
717 patron_id : this.patron.id(),
718 copy_barcode : barcode
723 console.log(js2JSON(result));
725 var stat = this.handleXactResult('renew', barcode, result);
728 this.renew(barcode, true);
732 * Display the result of a checkout or renewal in the items out table
734 SelfCheckManager.prototype.displayCheckout = function(evt, type) {
736 var copy = evt.payload.copy;
737 var record = evt.payload.record;
738 var circ = evt.payload.circ;
739 var row = this.circTemplate.cloneNode(true);
742 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + record.isbn());
745 this.byName(row, 'barcode').innerHTML = copy.barcode();
746 this.byName(row, 'title').innerHTML = record.title();
747 this.byName(row, 'author').innerHTML = record.author();
748 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
749 openils.Util.show(this.byName(row, type));
751 var date = dojo.date.stamp.fromISOString(circ.due_date());
752 this.byName(row, 'due_date').innerHTML =
753 dojo.date.locale.format(date, {selector : 'date'});
755 // put new circs at the top of the list
756 this.circTbody.insertBefore(row, this.circTbody.getElementsByTagName('tr')[0]);
760 SelfCheckManager.prototype.byName = function(node, name) {
761 return dojo.query('[name=' + name+']', node)[0];
765 SelfCheckManager.prototype.drawFinesPage = function() {
766 openils.Util.hide('oils-selfck-circ-page');
767 openils.Util.hide('oils-selfck-holds-page');
768 openils.Util.show('oils-selfck-payment-page');
772 SelfCheckManager.prototype.initPrinter = function() {
773 try { // Mozilla only
774 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
775 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
776 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
777 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
778 var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
780 pref.setBoolPref('print.always_print_silent', true);
782 console.log("Unable to initialize auto-printing");
789 SelfCheckManager.prototype.printReceipt = function(callback) {
792 var circCtx = []; // circ context data. in this case, renewal_failure info
794 // collect the circs and failure info
798 circIds.push(blob.circ);
799 circCtx.push({renewal_failure:blob.renewal_failure});
807 'format.selfcheck.checkout',
814 fieldmapper.standardRequest(
815 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
819 oncomplete : function(r) {
820 var resp = openils.Util.readResponse(r);
821 var output = resp.template_output();
823 self.printData(output.data(), self.checkouts.length, callback);
825 var error = resp.error_output();
827 throw new Error("Error creating receipt: " + error.data());
829 throw new Error("No receipt data returned from server");
837 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
839 var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1');
840 win.document.body.innerHTML = data;
844 * There is no way to know when the browser is done printing.
845 * Make a best guess at when to close the print window by basing
846 * the setTimeout wait on the number of items to be printed plus
849 var sleepTime = 1000;
851 sleepTime += (numItems / 2) * 1000;
855 win.close(); // close the print window
857 callback(); // fire optional post-print callback
866 * Logout the patron and return to the login page
868 SelfCheckManager.prototype.logoutPatron = function() {
869 if(this.checkouts.length) {
872 location.href = location.href;
876 location.href = location.href;
882 * Fire up the manager on page load
884 openils.Util.addOnLoad(
886 new SelfCheckManager().init();