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_ALERT_ON_CHECKOUT_EVENT = 'circ.selfcheck.alert_on_checkout_event';
16 const SET_AUTO_OVERRIDE_EVENTS = 'circ.selfcheck.auto_override_checkout_events';
17 const SET_PATRON_PASSWORD_REQUIRED = 'circ.selfcheck.patron_password_required';
18 const SET_AUTO_RENEW_INTERVAL = 'circ.checkout_auto_renew_age';
19 const SET_WORKSTATION_REQUIRED = 'circ.selfcheck.workstation_required';
21 //openils.Util.playAudioUrl('/xul/server/skin/media/audio/bonus.wav');
23 function SelfCheckManager() {
25 this.cgi = new openils.CGI();
27 this.workstation = null;
28 this.authtoken = null;
31 this.patronBarcodeRegex = null;
33 // current item barcode
34 this.itemBarcode = null;
36 // are we currently performing a renewal?
37 this.isRenewal = false;
39 // dict of org unit settings for "here"
40 this.orgSettings = {};
42 // Construct a mock checkout for debugging purposes
43 if(this.mockCheckouts = this.cgi.param('mock-circ')) {
47 record : new fieldmapper.mvr(),
48 copy : new fieldmapper.acp(),
49 circ : new fieldmapper.circ()
53 this.mockCheckout.payload.record.title('Jazz improvisation for guitar');
54 this.mockCheckout.payload.record.author('Wise, Les');
55 this.mockCheckout.payload.record.isbn('0634033565');
56 this.mockCheckout.payload.copy.barcode('123456789');
57 this.mockCheckout.payload.circ.renewal_remaining(1);
58 this.mockCheckout.payload.circ.parent_circ(1);
59 this.mockCheckout.payload.circ.due_date('2012-12-21');
66 * Fetch the org-unit settings, initialize the display, etc.
68 SelfCheckManager.prototype.init = function() {
70 this.staff = openils.User.user;
71 this.workstation = openils.User.workstation;
72 this.authtoken = openils.User.authtoken;
73 this.loadOrgSettings();
75 // workstation is required but none provided
76 if(this.orgSettings[SET_WORKSTATION_REQUIRED] && !this.workstation) {
77 alert(dojo.string.substitute(localeStrings.WORKSTATION_REQUIRED));
82 // connect onclick handlers to the various navigation links
84 'oils-selfck-hold-details-link' : function() { self.drawHoldsPage(); },
85 'oils-selfck-nav-holds' : function() { self.drawHoldsPage(); },
86 'oils-selfck-pay-fines-link' : function() { self.drawFinesPage(); },
87 'oils-selfck-nav-fines' : function() { self.drawFinesPage(); },
88 'oils-selfck-nav-home' : function() { self.drawCircPage(); },
89 'oils-selfck-nav-logout' : function() { self.logoutPatron(); }
92 for(var id in linkHandlers)
93 dojo.connect(dojo.byId(id), 'onclick', linkHandlers[id]);
96 if(this.cgi.param('patron')) {
98 // Patron barcode via cgi param. Mainly used for debugging and
99 // only works if password is not required by policy
100 this.loginPatron(this.cgi.param('patron'));
103 this.drawLoginPage();
108 * Loads the org unit settings
110 SelfCheckManager.prototype.loadOrgSettings = function() {
112 var settings = fieldmapper.aou.fetchOrgSettingBatch(
113 this.staff.ws_ou(), [
116 SET_ALERT_ON_CHECKOUT_EVENT,
117 SET_AUTO_OVERRIDE_EVENTS,
118 SET_PATRON_PASSWORD_REQUIRED,
119 SET_AUTO_RENEW_INTERVAL,
120 SET_WORKSTATION_REQUIRED
126 this.orgSettings[k] = settings[k].value;
129 if(settings[SET_BARCODE_REGEX])
130 this.patronBarcodeRegex = new RegExp(settings[SET_BARCODE_REGEX].value);
133 SelfCheckManager.prototype.drawLoginPage = function() {
136 var bcHandler = function(barcode) {
137 // handle patron barcode entry
139 if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
141 // password is required. wire up the scan box to read it
143 msg : 'Please enter your password', // TODO i18n
144 handler : function(pw) { self.loginPatron(barcode, pw); },
149 // password is not required, go ahead and login
150 self.loginPatron(barcode);
155 msg : 'Please log in with your library barcode.', // TODO
163 SelfCheckManager.prototype.loginPatron = function(barcode, passwd) {
165 if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
168 // would only happen in dev/debug mode when using the patron= param
169 alert('password required by org setting. remove patron= from URL');
173 // patron password is required. Verify it.
175 var res = fieldmapper.standardRequest(
176 ['open-ils.actor', 'open-ils.actor.verify_user_password'],
177 {params : [this.authtoken, barcode, null, hex_md5(passwd)]}
181 // user-not-found results in login failure
182 dojo.byId('oils-selfck-status-div').innerHTML =
183 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]);
184 this.drawLoginPage();
189 // retrieve the fleshed user by barcode
190 this.patron = fieldmapper.standardRequest(
191 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve_by_barcode'],
192 {params : [this.authtoken, barcode]}
195 var evt = openils.Event.parse(this.patron);
198 dojo.byId('oils-selfck-status-div').innerHTML =
199 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]);
200 this.drawLoginPage();
204 dojo.byId('oils-selfck-status-div').innerHTML = '';
205 dojo.byId('oils-selfck-user-banner').innerHTML = 'Welcome, ' + this.patron.usrname(); // TODO i18n
212 * Manages the main input box
213 * @param msg The context message to display with the box
214 * @param clearOnly Don't update the context message, just clear the value and re-focus
215 * @param handler Optional "on-enter" handler.
217 SelfCheckManager.prototype.updateScanBox = function(args) {
221 selfckScanBox.domNode.select();
223 selfckScanBox.attr('value', '');
227 selfckScanBox.domNode.setAttribute('type', 'password');
229 selfckScanBox.domNode.setAttribute('type', '');
233 selfckScanBox.attr('value', args.value);
236 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
238 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
239 dojo.disconnect(selfckScanBox._lastHandler);
243 selfckScanBox._lastHandler = dojo.connect(
247 if(e.keyCode != dojo.keys.ENTER)
249 args.handler(selfckScanBox.attr('value'));
254 selfckScanBox.focus();
258 * Sets up the checkout/renewal interface
260 SelfCheckManager.prototype.drawCircPage = function() {
264 msg : 'Please enter an item barcode', // TODO i18n
265 handler : function(barcode) { self.checkout(barcode); }
268 openils.Util.hide('oils-selfck-payment-page');
269 openils.Util.hide('oils-selfck-holds-page');
270 openils.Util.show('oils-selfck-circ-page');
272 this.circTbody = dojo.byId('oils-selfck-circ-tbody');
273 if(!this.circTemplate)
274 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
276 // items out, holds, and fines summaries
279 fieldmapper.standardRequest(
280 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
282 params : [this.authtoken, this.patron.id()],
283 oncomplete : function(r) {
284 var summary = openils.Util.readResponse(r);
285 dojo.byId('oils-selfck-fines-total').innerHTML =
286 dojo.string.substitute(
287 localeStrings.TOTAL_FINES_ACCOUNT,
288 [summary.balance_owed()]
295 this.updateHoldsSummary();
298 this.updateCircSummary();
300 // render mock checkouts for debugging?
301 if(this.mockCheckouts) {
302 for(var i in [1,2,3])
303 this.displayCheckout(this.mockCheckout, 'checkout');
307 SelfCheckManager.prototype.updateHoldsSummary = function() {
309 if(!this.holdsSummary) {
310 var summary = fieldmapper.standardRequest(
311 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
312 {params : [this.authtoken, this.patron.id()]}
315 this.holdsSummary = {};
316 this.holdsSummary.ready = Number(summary['4']);
317 this.holdsSummary.total = 0;
319 for(var i in summary)
320 this.holdsSummary.total += Number(summary[i]);
323 dojo.byId('oils-selfck-holds-total').innerHTML =
324 dojo.string.substitute(
325 localeStrings.TOTAL_HOLDS,
326 [this.holdsSummary.total]
329 dojo.byId('oils-selfck-holds-ready').innerHTML =
330 dojo.string.substitute(
331 localeStrings.HOLDS_READY_FOR_PICKUP,
332 [this.holdsSummary.ready]
337 SelfCheckManager.prototype.updateCircSummary = function(increment) {
339 if(!this.circSummary) {
341 var summary = fieldmapper.standardRequest(
342 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
343 {params : [this.authtoken, this.patron.id()]}
347 total : Number(summary.out) + Number(summary.overdue),
348 overdue : Number(summary.overdue),
354 // local checkout occurred. Add to the total and the session.
355 this.circSummary.total += 1;
356 this.circSummary.session += 1;
359 dojo.byId('oils-selfck-circ-account-total').innerHTML =
360 dojo.string.substitute(
361 localeStrings.TOTAL_ITEMS_ACCOUNT,
362 [this.circSummary.total]
365 dojo.byId('oils-selfck-circ-session-total').innerHTML =
366 dojo.string.substitute(
367 localeStrings.TOTAL_ITEMS_SESSION,
368 [this.circSummary.session]
373 SelfCheckManager.prototype.drawHoldsPage = function() {
375 // TODO add option to hid scanBox
376 // this.updateScanBox(...)
378 openils.Util.hide('oils-selfck-circ-page');
379 openils.Util.hide('oils-selfck-payment-page');
380 openils.Util.show('oils-selfck-holds-page');
382 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
383 if(!this.holdTemplate)
384 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
385 while(this.holdTbody.childNodes[0])
386 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
388 progressDialog.show(true);
391 fieldmapper.standardRequest( // fetch the hold IDs
393 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
395 params : [this.authtoken, this.patron.id()],
397 oncomplete : function(r) {
398 var ids = openils.Util.readResponse(r);
399 if(!ids || ids.length == 0) {
400 progressDialog.hide();
404 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
405 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve.atomic'],
407 params : [self.authtoken, ids],
409 oncomplete : function(rr) {
410 self.drawHolds(openils.Util.readResponse(rr));
420 * Fetch and add a single hold to the list of holds
422 SelfCheckManager.prototype.drawHolds = function(holds) {
425 // sort available holds to the top of the list
426 // followed by queue position order
428 if(a.status == 4) return -1;
429 if(a.queue_position < b.queue_position) return -1;
434 progressDialog.hide();
436 for(var i in holds) {
439 var row = this.holdTemplate.cloneNode(true);
441 if(data.mvr.isbn()) {
442 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + data.mvr.isbn());
445 this.byName(row, 'title').innerHTML = data.mvr.title();
446 this.byName(row, 'author').innerHTML = data.mvr.author();
448 if(data.status == 4) {
450 // hold is ready for pickup
451 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
455 // hold is still pending
456 this.byName(row, 'status').innerHTML =
457 dojo.string.substitute(
458 localeStrings.HOLD_STATUS_WAITING,
459 [data.queue_position, data.potential_copies]
463 this.holdTbody.appendChild(row);
470 * Check out a single item. If the item is already checked
471 * out to the patron, redirect to renew()
473 SelfCheckManager.prototype.checkout = function(barcode, override) {
476 this.updateScanbox(null, true);
480 if(this.mockCheckouts) {
481 // if we're in mock-checkout mode, just insert another
482 // fake circ into the table and get out of here.
483 this.displayCheckout(this.mockCheckout, 'checkout');
487 // TODO see if it's a patron barcode
488 // TODO see if this item has already been checked out in this session
490 var method = 'open-ils.circ.checkout.full';
491 if(override) method += '.override';
493 console.log("Checkout out item " + barcode + " with method " + method);
495 var result = fieldmapper.standardRequest(
496 ['open-ils.circ', 'open-ils.circ.checkout.full'],
499 patron_id : this.patron.id(),
500 copy_barcode : barcode
505 console.log(js2JSON(result));
507 var stat = this.handleXactResult('checkout', barcode, result);
510 this.checkout(barcode, true);
511 } else if(stat.renew) {
517 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
519 var displayText = '';
521 // If true, the display message is important enough to pop up. Whether or not
522 // an alert() actually occurs, depends on org unit settings
525 // TODO handle lost/missing/etc checkin+checkout override steps
527 var payload = result.payload || {};
529 if(result.textcode == 'NO_SESSION') {
531 return this.logoutStaff();
533 } else if(result.textcode == 'SUCCESS') {
535 if(action == 'checkout') {
537 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
538 this.displayCheckout(result, 'checkout');
540 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
541 // A hold was fulfilled, update the hold numbers in the circ summary
542 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
543 this.holdsSummary = null;
544 this.updateHoldsSummary();
547 this.updateCircSummary(true);
549 } else if(action == 'renew') {
551 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
552 this.displayCheckout(result, 'renew');
555 this.updateScanBox();
557 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
559 // Server says the item is already checked out. If it's checked out to the
560 // current user, we may need to renew it.
562 if(payload.old_circ) {
565 old_circ refers to the previous checkout IFF it's for the same user.
566 If no auto-renew interval is not defined, assume we should renew it
567 If an auto-renew interval is defined and the payload comes back with
568 auto_renew set to true, do the renewal. Otherwise, let the patron know
569 the item is already checked out to them. */
571 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
572 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
573 return { renew : true };
577 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
581 // item is checked out to some other user
583 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
586 this.updateScanBox({select:true});
590 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
592 if(overrideEvents && overrideEvents.length) {
594 // see if the events we received are all in the list of
595 // events to override
597 if(!result.length) result = [result];
600 for(var i = 0; i < result.length; i++) {
601 var match = overrideEvents.filter(
602 function(e) { return (e == result[i].textcode); })[0];
610 return { override : true };
613 this.updateScanBox({select : true});
619 switch(result.textcode) {
621 case 'MAX_RENEWALS_REACHED' :
622 displayText = dojo.string.substitute(
623 localeStrings.MAX_RENEWALS, [item]);
626 case 'ITEM_NOT_CATALOGED' :
627 displayText = dojo.string.substitute(
628 localeStrings.ITEM_NOT_CATALOGED, [item]);
631 case 'OPEN_CIRCULATION_EXISTS' :
632 displayText = dojo.string.substitute(
633 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
637 console.error('Unhandled event ' + result.textcode);
639 if(action == 'checkout' || action == 'renew') {
640 displayText = dojo.string.substitute(
641 localeStrings.GENERIC_CIRC_FAILURE, [item]);
643 displayText = dojo.string.substitute(
644 localeStrings.UNKNOWN_ERROR, [result.textcode]);
649 console.log("Updating status with " + displayText);
651 dojo.byId('oils-selfck-status-div').innerHTML = displayText;
653 if(popup && this.orgSettings[SET_ALERT_ON_CHECKOUT_EVENT])
663 SelfCheckManager.prototype.renew = function(barcode, override) {
665 var method = 'open-ils.circ.renew';
666 if(override) method += '.override';
668 console.log("Renewing item " + barcode + " with method " + method);
670 var result = fieldmapper.standardRequest(
671 ['open-ils.circ', method],
674 patron_id : this.patron.id(),
675 copy_barcode : barcode
680 console.log(js2JSON(result));
682 var stat = this.handleXactResult('renew', barcode, result);
685 this.renew(barcode, true);
689 * Display the result of a checkout or renewal in the items out table
691 SelfCheckManager.prototype.displayCheckout = function(evt, type) {
693 var copy = evt.payload.copy;
694 var record = evt.payload.record;
695 var circ = evt.payload.circ;
696 var row = this.circTemplate.cloneNode(true);
699 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + record.isbn());
702 this.byName(row, 'barcode').innerHTML = copy.barcode();
703 this.byName(row, 'title').innerHTML = record.title();
704 this.byName(row, 'author').innerHTML = record.author();
705 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
706 openils.Util.show(this.byName(row, type));
708 var date = dojo.date.stamp.fromISOString(circ.due_date());
709 this.byName(row, 'due_date').innerHTML =
710 dojo.date.locale.format(date, {selector : 'date'});
712 // put new circs at the top of the list
713 this.circTbody.insertBefore(row, this.circTbody.getElementsByTagName('tr')[0]);
717 SelfCheckManager.prototype.byName = function(node, name) {
718 return dojo.query('[name=' + name+']', node)[0];
722 SelfCheckManager.prototype.drawFinesPage = function() {
724 openils.Util.hide('oils-selfck-circ-page');
725 openils.Util.hide('oils-selfck-holds-page');
726 openils.Util.show('oils-selfck-payment-page');
733 SelfCheckManager.prototype.printReceipt = function() {
738 * Logout the patron and return to the login page
740 SelfCheckManager.prototype.logoutPatron = function() {
743 this.holdsSummary = null;
744 this.circSummary = null;
746 this.drawLoginPage();
751 * Fire up the manager on page load
753 openils.Util.addOnLoad(
755 new SelfCheckManager().init();