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;
32 // current item barcode
33 this.itemBarcode = null;
35 // are we currently performing a renewal?
36 this.isRenewal = false;
38 // dict of org unit settings for "here"
39 this.orgSettings = {};
41 // Construct a mock checkout for debugging purposes
42 if(this.mockCheckouts = this.cgi.param('mock-circ')) {
46 record : new fieldmapper.mvr(),
47 copy : new fieldmapper.acp(),
48 circ : new fieldmapper.circ()
52 this.mockCheckout.payload.record.title('Jazz improvisation for guitar');
53 this.mockCheckout.payload.record.author('Wise, Les');
54 this.mockCheckout.payload.record.isbn('0634033565');
55 this.mockCheckout.payload.copy.barcode('123456789');
56 this.mockCheckout.payload.circ.renewal_remaining(1);
57 this.mockCheckout.payload.circ.parent_circ(1);
58 this.mockCheckout.payload.circ.due_date('2012-12-21');
65 * Fetch the org-unit settings, initialize the display, etc.
67 SelfCheckManager.prototype.init = function() {
69 this.staff = openils.User.user;
70 this.workstation = openils.User.workstation;
71 this.authtoken = openils.User.authtoken;
72 this.loadOrgSettings();
74 // workstation is required but none provided
75 if(this.orgSettings[SET_WORKSTATION_REQUIRED] && !this.workstation) {
76 alert(dojo.string.substitute(localeStrings.WORKSTATION_REQUIRED));
81 // connect onclick handlers to the various navigation links
83 'oils-selfck-hold-details-link' : function() { self.drawHoldsPage(); },
84 'oils-selfck-nav-holds' : function() { self.drawHoldsPage(); },
85 'oils-selfck-pay-fines-link' : function() { self.drawFinesPage(); },
86 'oils-selfck-nav-fines' : function() { self.drawFinesPage(); },
87 'oils-selfck-nav-home' : function() { self.drawCircPage(); },
88 'oils-selfck-nav-logout' : function() { self.logoutPatron(); }
91 for(var id in linkHandlers)
92 dojo.connect(dojo.byId(id), 'onclick', linkHandlers[id]);
95 if(this.cgi.param('patron')) {
97 // Patron barcode via cgi param. Mainly used for debugging and
98 // only works if password is not required by policy
99 this.loginPatron(this.cgi.param('patron'));
102 this.drawLoginPage();
107 * Loads the org unit settings
109 SelfCheckManager.prototype.loadOrgSettings = function() {
111 var settings = fieldmapper.aou.fetchOrgSettingBatch(
112 this.staff.ws_ou(), [
116 SET_AUTO_OVERRIDE_EVENTS,
117 SET_PATRON_PASSWORD_REQUIRED,
118 SET_AUTO_RENEW_INTERVAL,
119 SET_WORKSTATION_REQUIRED
125 this.orgSettings[k] = settings[k].value;
128 if(settings[SET_BARCODE_REGEX])
129 this.patronBarcodeRegex = new RegExp(settings[SET_BARCODE_REGEX].value);
132 SelfCheckManager.prototype.drawLoginPage = function() {
135 var bcHandler = function(barcode) {
136 // handle patron barcode entry
138 if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
140 // password is required. wire up the scan box to read it
142 msg : 'Please enter your password', // TODO i18n
143 handler : function(pw) { self.loginPatron(barcode, pw); },
148 // password is not required, go ahead and login
149 self.loginPatron(barcode);
154 msg : 'Please log in with your library barcode.', // TODO
162 SelfCheckManager.prototype.loginPatron = function(barcode, passwd) {
164 if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
167 // would only happen in dev/debug mode when using the patron= param
168 alert('password required by org setting. remove patron= from URL');
172 // patron password is required. Verify it.
174 var res = fieldmapper.standardRequest(
175 ['open-ils.actor', 'open-ils.actor.verify_user_password'],
176 {params : [this.authtoken, barcode, null, hex_md5(passwd)]}
180 // user-not-found results in login failure
182 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]),
183 false, 'login-failure'
185 this.drawLoginPage();
190 // retrieve the fleshed user by barcode
191 this.patron = fieldmapper.standardRequest(
192 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve_by_barcode'],
193 {params : [this.authtoken, barcode]}
196 var evt = openils.Event.parse(this.patron);
199 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]),
200 false, 'login-failure'
202 this.drawLoginPage();
206 this.handleAlert('', false, 'login-success');
207 dojo.byId('oils-selfck-user-banner').innerHTML = 'Welcome, ' + this.patron.usrname(); // TODO i18n
213 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
215 console.log("Handling alert " + message);
217 dojo.byId('oils-selfck-status-div').innerHTML = message;
219 if(shouldPopup && this.orgSettings[SET_ALERT_POPUP])
222 if(sound && this.orgSettings[SET_ALERT_SOUND])
223 openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
228 * Manages the main input box
229 * @param msg The context message to display with the box
230 * @param clearOnly Don't update the context message, just clear the value and re-focus
231 * @param handler Optional "on-enter" handler.
233 SelfCheckManager.prototype.updateScanBox = function(args) {
237 selfckScanBox.domNode.select();
239 selfckScanBox.attr('value', '');
243 selfckScanBox.domNode.setAttribute('type', 'password');
245 selfckScanBox.domNode.setAttribute('type', '');
249 selfckScanBox.attr('value', args.value);
252 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
254 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
255 dojo.disconnect(selfckScanBox._lastHandler);
259 selfckScanBox._lastHandler = dojo.connect(
263 if(e.keyCode != dojo.keys.ENTER)
265 args.handler(selfckScanBox.attr('value'));
270 selfckScanBox.focus();
274 * Sets up the checkout/renewal interface
276 SelfCheckManager.prototype.drawCircPage = function() {
280 msg : 'Please enter an item barcode', // TODO i18n
281 handler : function(barcode) { self.checkout(barcode); }
284 openils.Util.hide('oils-selfck-payment-page');
285 openils.Util.hide('oils-selfck-holds-page');
286 openils.Util.show('oils-selfck-circ-page');
288 this.circTbody = dojo.byId('oils-selfck-circ-tbody');
289 if(!this.circTemplate)
290 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
292 // items out, holds, and fines summaries
295 fieldmapper.standardRequest(
296 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
298 params : [this.authtoken, this.patron.id()],
299 oncomplete : function(r) {
300 var summary = openils.Util.readResponse(r);
301 dojo.byId('oils-selfck-fines-total').innerHTML =
302 dojo.string.substitute(
303 localeStrings.TOTAL_FINES_ACCOUNT,
304 [summary.balance_owed()]
311 this.updateHoldsSummary();
314 this.updateCircSummary();
316 // render mock checkouts for debugging?
317 if(this.mockCheckouts) {
318 for(var i in [1,2,3])
319 this.displayCheckout(this.mockCheckout, 'checkout');
323 SelfCheckManager.prototype.updateHoldsSummary = function() {
325 if(!this.holdsSummary) {
326 var summary = fieldmapper.standardRequest(
327 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
328 {params : [this.authtoken, this.patron.id()]}
331 this.holdsSummary = {};
332 this.holdsSummary.ready = Number(summary['4']);
333 this.holdsSummary.total = 0;
335 for(var i in summary)
336 this.holdsSummary.total += Number(summary[i]);
339 dojo.byId('oils-selfck-holds-total').innerHTML =
340 dojo.string.substitute(
341 localeStrings.TOTAL_HOLDS,
342 [this.holdsSummary.total]
345 dojo.byId('oils-selfck-holds-ready').innerHTML =
346 dojo.string.substitute(
347 localeStrings.HOLDS_READY_FOR_PICKUP,
348 [this.holdsSummary.ready]
353 SelfCheckManager.prototype.updateCircSummary = function(increment) {
355 if(!this.circSummary) {
357 var summary = fieldmapper.standardRequest(
358 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
359 {params : [this.authtoken, this.patron.id()]}
363 total : Number(summary.out) + Number(summary.overdue),
364 overdue : Number(summary.overdue),
370 // local checkout occurred. Add to the total and the session.
371 this.circSummary.total += 1;
372 this.circSummary.session += 1;
375 dojo.byId('oils-selfck-circ-account-total').innerHTML =
376 dojo.string.substitute(
377 localeStrings.TOTAL_ITEMS_ACCOUNT,
378 [this.circSummary.total]
381 dojo.byId('oils-selfck-circ-session-total').innerHTML =
382 dojo.string.substitute(
383 localeStrings.TOTAL_ITEMS_SESSION,
384 [this.circSummary.session]
389 SelfCheckManager.prototype.drawHoldsPage = function() {
391 // TODO add option to hid scanBox
392 // this.updateScanBox(...)
394 openils.Util.hide('oils-selfck-circ-page');
395 openils.Util.hide('oils-selfck-payment-page');
396 openils.Util.show('oils-selfck-holds-page');
398 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
399 if(!this.holdTemplate)
400 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
401 while(this.holdTbody.childNodes[0])
402 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
404 progressDialog.show(true);
407 fieldmapper.standardRequest( // fetch the hold IDs
409 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
411 params : [this.authtoken, this.patron.id()],
413 oncomplete : function(r) {
414 var ids = openils.Util.readResponse(r);
415 if(!ids || ids.length == 0) {
416 progressDialog.hide();
420 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
421 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve.atomic'],
423 params : [self.authtoken, ids],
425 oncomplete : function(rr) {
426 self.drawHolds(openils.Util.readResponse(rr));
436 * Fetch and add a single hold to the list of holds
438 SelfCheckManager.prototype.drawHolds = function(holds) {
441 // sort available holds to the top of the list
442 // followed by queue position order
444 if(a.status == 4) return -1;
445 if(a.queue_position < b.queue_position) return -1;
450 progressDialog.hide();
452 for(var i in holds) {
455 var row = this.holdTemplate.cloneNode(true);
457 if(data.mvr.isbn()) {
458 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + data.mvr.isbn());
461 this.byName(row, 'title').innerHTML = data.mvr.title();
462 this.byName(row, 'author').innerHTML = data.mvr.author();
464 if(data.status == 4) {
466 // hold is ready for pickup
467 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
471 // hold is still pending
472 this.byName(row, 'status').innerHTML =
473 dojo.string.substitute(
474 localeStrings.HOLD_STATUS_WAITING,
475 [data.queue_position, data.potential_copies]
479 this.holdTbody.appendChild(row);
486 * Check out a single item. If the item is already checked
487 * out to the patron, redirect to renew()
489 SelfCheckManager.prototype.checkout = function(barcode, override) {
492 this.updateScanbox(null, true);
496 if(this.mockCheckouts) {
497 // if we're in mock-checkout mode, just insert another
498 // fake circ into the table and get out of here.
499 this.displayCheckout(this.mockCheckout, 'checkout');
503 // TODO see if it's a patron barcode
504 // TODO see if this item has already been checked out in this session
506 var method = 'open-ils.circ.checkout.full';
507 if(override) method += '.override';
509 console.log("Checkout out item " + barcode + " with method " + method);
511 var result = fieldmapper.standardRequest(
512 ['open-ils.circ', 'open-ils.circ.checkout.full'],
515 patron_id : this.patron.id(),
516 copy_barcode : barcode
521 console.log(js2JSON(result));
523 var stat = this.handleXactResult('checkout', barcode, result);
526 this.checkout(barcode, true);
527 } else if(stat.renew) {
533 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
535 var displayText = '';
537 // If true, the display message is important enough to pop up. Whether or not
538 // an alert() actually occurs, depends on org unit settings
543 // TODO handle lost/missing/etc checkin+checkout override steps
545 var payload = result.payload || {};
547 if(result.textcode == 'NO_SESSION') {
549 return this.logoutStaff();
551 } else if(result.textcode == 'SUCCESS') {
553 if(action == 'checkout') {
555 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
556 this.displayCheckout(result, 'checkout');
558 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
559 // A hold was fulfilled, update the hold numbers in the circ summary
560 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
561 this.holdsSummary = null;
562 this.updateHoldsSummary();
565 this.updateCircSummary(true);
567 } else if(action == 'renew') {
569 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
570 this.displayCheckout(result, 'renew');
573 sound = 'checkout-success';
574 this.updateScanBox();
576 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
578 // Server says the item is already checked out. If it's checked out to the
579 // current user, we may need to renew it.
581 if(payload.old_circ) {
584 old_circ refers to the previous checkout IFF it's for the same user.
585 If no auto-renew interval is not defined, assume we should renew it
586 If an auto-renew interval is defined and the payload comes back with
587 auto_renew set to true, do the renewal. Otherwise, let the patron know
588 the item is already checked out to them. */
590 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
591 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
592 return { renew : true };
596 sound = 'checkout-failure';
597 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
601 // item is checked out to some other user
603 sound = 'checkout-failure';
604 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
607 this.updateScanBox({select:true});
611 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
613 if(overrideEvents && overrideEvents.length) {
615 // see if the events we received are all in the list of
616 // events to override
618 if(!result.length) result = [result];
621 for(var i = 0; i < result.length; i++) {
622 var match = overrideEvents.filter(
623 function(e) { return (e == result[i].textcode); })[0];
631 return { override : true };
634 this.updateScanBox({select : true});
636 sound = 'checkout-failure';
641 switch(result.textcode) {
643 case 'MAX_RENEWALS_REACHED' :
644 displayText = dojo.string.substitute(
645 localeStrings.MAX_RENEWALS, [item]);
648 case 'ITEM_NOT_CATALOGED' :
649 displayText = dojo.string.substitute(
650 localeStrings.ITEM_NOT_CATALOGED, [item]);
653 case 'OPEN_CIRCULATION_EXISTS' :
654 displayText = dojo.string.substitute(
655 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
659 console.error('Unhandled event ' + result.textcode);
661 if(action == 'checkout' || action == 'renew') {
662 displayText = dojo.string.substitute(
663 localeStrings.GENERIC_CIRC_FAILURE, [item]);
665 displayText = dojo.string.substitute(
666 localeStrings.UNKNOWN_ERROR, [result.textcode]);
671 this.handleAlert(displayText, popup, sound);
679 SelfCheckManager.prototype.renew = function(barcode, override) {
681 var method = 'open-ils.circ.renew';
682 if(override) method += '.override';
684 console.log("Renewing item " + barcode + " with method " + method);
686 var result = fieldmapper.standardRequest(
687 ['open-ils.circ', method],
690 patron_id : this.patron.id(),
691 copy_barcode : barcode
696 console.log(js2JSON(result));
698 var stat = this.handleXactResult('renew', barcode, result);
701 this.renew(barcode, true);
705 * Display the result of a checkout or renewal in the items out table
707 SelfCheckManager.prototype.displayCheckout = function(evt, type) {
709 var copy = evt.payload.copy;
710 var record = evt.payload.record;
711 var circ = evt.payload.circ;
712 var row = this.circTemplate.cloneNode(true);
715 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + record.isbn());
718 this.byName(row, 'barcode').innerHTML = copy.barcode();
719 this.byName(row, 'title').innerHTML = record.title();
720 this.byName(row, 'author').innerHTML = record.author();
721 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
722 openils.Util.show(this.byName(row, type));
724 var date = dojo.date.stamp.fromISOString(circ.due_date());
725 this.byName(row, 'due_date').innerHTML =
726 dojo.date.locale.format(date, {selector : 'date'});
728 // put new circs at the top of the list
729 this.circTbody.insertBefore(row, this.circTbody.getElementsByTagName('tr')[0]);
733 SelfCheckManager.prototype.byName = function(node, name) {
734 return dojo.query('[name=' + name+']', node)[0];
738 SelfCheckManager.prototype.drawFinesPage = function() {
740 openils.Util.hide('oils-selfck-circ-page');
741 openils.Util.hide('oils-selfck-holds-page');
742 openils.Util.show('oils-selfck-payment-page');
749 SelfCheckManager.prototype.printReceipt = function() {
754 * Logout the patron and return to the login page
756 SelfCheckManager.prototype.logoutPatron = function() {
759 this.holdsSummary = null;
760 this.circSummary = null;
762 this.drawLoginPage();
767 * Fire up the manager on page load
769 openils.Util.addOnLoad(
771 new SelfCheckManager().init();