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';
20 //openils.Util.playAudioUrl('/xul/server/skin/media/audio/bonus.wav');
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();
76 // connect onclick handlers to the various navigation links
78 'oils-selfck-hold-details-link' : function() { self.drawHoldsPage(); },
79 'oils-selfck-nav-holds' : function() { self.drawHoldsPage(); },
80 'oils-selfck-pay-fines-link' : function() { self.drawFinesPage(); },
81 'oils-selfck-nav-fines' : function() { self.drawFinesPage(); },
82 'oils-selfck-nav-home' : function() { self.drawCircPage(); },
83 'oils-selfck-nav-logout' : function() { self.logoutPatron(); }
86 for(var id in linkHandlers)
87 dojo.connect(dojo.byId(id), 'onclick', linkHandlers[id]);
90 if(this.cgi.param('patron')) {
92 // Patron barcode via cgi param. Mainly used for debugging and
93 // only works if password is not required by policy
94 this.loginPatron(this.cgi.param('patron'));
102 * Loads the org unit settings
104 SelfCheckManager.prototype.loadOrgSettings = function() {
106 var settings = fieldmapper.aou.fetchOrgSettingBatch(
107 this.staff.ws_ou(), [
110 SET_ALERT_ON_CHECKOUT_EVENT,
111 SET_AUTO_OVERRIDE_EVENTS,
112 SET_PATRON_PASSWORD_REQUIRED,
113 SET_AUTO_RENEW_INTERVAL,
119 this.orgSettings[k] = settings[k].value;
122 if(settings[SET_BARCODE_REGEX])
123 this.patronBarcodeRegex = new RegExp(settings[SET_BARCODE_REGEX].value);
126 SelfCheckManager.prototype.drawLoginPage = function() {
129 var bcHandler = function(barcode) {
130 // handle patron barcode entry
132 if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
134 // password is required. wire up the scan box to read it
136 msg : 'Please enter your password', // TODO i18n
137 handler : function(pw) { self.loginPatron(barcode, pw); }
141 // password is not required, go ahead and login
142 self.loginPatron(barcode);
147 msg : 'Please log in with your library barcode.', // TODO
155 SelfCheckManager.prototype.loginPatron = function(barcode, passwd) {
157 if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
159 // patron password is required. Verify it.
161 var res = fieldmapper.standardRequest(
162 ['open-ils.actor', 'open-ils.actor.verify_user_password'],
163 {params : [this.authtoken, barcode, null, hex_md5(passwd)]}
167 // user-not-found results in login failure
168 this.handleXactResult('login', barcode, {textcode : 'ACTOR_USER_NOT_FOUND'});
172 // retrieve the fleshed user by barcode
173 this.patron = fieldmapper.standardRequest(
174 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve_by_barcode'],
175 {params : [this.authtoken, barcode]}
178 var evt = openils.Event.parse(this.patron);
180 this.handleXactResult('login', barcode, evt);
184 dojo.byId('oils-selfck-status-div').innerHTML = '';
185 dojo.byId('oils-selfck-user-banner').innerHTML = 'Welcome, ' + this.patron.usrname(); // TODO i18n
192 * Manages the main input box
193 * @param msg The context message to display with the box
194 * @param clearOnly Don't update the context message, just clear the value and re-focus
195 * @param handler Optional "on-enter" handler.
197 SelfCheckManager.prototype.updateScanBox = function(args) {
201 selfckScanBox.domNode.select();
203 selfckScanBox.attr('value', '');
207 selfckScanBox.attr('value', args.value);
210 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
212 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
213 dojo.disconnect(selfckScanBox._lastHandler);
217 selfckScanBox._lastHandler = dojo.connect(
221 if(e.keyCode != dojo.keys.ENTER)
223 args.handler(selfckScanBox.attr('value'));
228 selfckScanBox.focus();
232 * Sets up the checkout/renewal interface
234 SelfCheckManager.prototype.drawCircPage = function() {
238 msg : 'Please enter an item barcode', // TODO i18n
239 handler : function(barcode) { self.checkout(barcode); }
242 openils.Util.hide('oils-selfck-payment-page');
243 openils.Util.hide('oils-selfck-holds-page');
244 openils.Util.show('oils-selfck-circ-page');
246 this.circTbody = dojo.byId('oils-selfck-circ-tbody');
247 if(!this.circTemplate)
248 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
250 // items out, holds, and fines summaries
253 fieldmapper.standardRequest(
254 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
256 params : [this.authtoken, this.patron.id()],
257 oncomplete : function(r) {
258 var summary = openils.Util.readResponse(r);
259 dojo.byId('oils-selfck-fines-total').innerHTML =
260 dojo.string.substitute(
261 localeStrings.TOTAL_FINES_ACCOUNT,
262 [summary.balance_owed()]
269 this.updateHoldsSummary();
272 this.updateCircSummary();
274 // render mock checkouts for debugging?
275 if(this.mockCheckouts) {
276 for(var i in [1,2,3])
277 this.displayCheckout(this.mockCheckout, 'checkout');
281 SelfCheckManager.prototype.updateHoldsSummary = function() {
283 if(!this.holdsSummary) {
284 var summary = fieldmapper.standardRequest(
285 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
286 {params : [this.authtoken, this.patron.id()]}
289 this.holdsSummary = {};
290 this.holdsSummary.ready = Number(summary['4']);
291 this.holdsSummary.total = 0;
293 for(var i in summary)
294 this.holdsSummary.total += Number(summary[i]);
297 dojo.byId('oils-selfck-holds-total').innerHTML =
298 dojo.string.substitute(
299 localeStrings.TOTAL_HOLDS,
300 [this.holdsSummary.total]
303 dojo.byId('oils-selfck-holds-ready').innerHTML =
304 dojo.string.substitute(
305 localeStrings.HOLDS_READY_FOR_PICKUP,
306 [this.holdsSummary.ready]
311 SelfCheckManager.prototype.updateCircSummary = function(increment) {
313 if(!this.circSummary) {
315 var summary = fieldmapper.standardRequest(
316 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
317 {params : [this.authtoken, this.patron.id()]}
321 total : Number(summary.out) + Number(summary.overdue),
322 overdue : Number(summary.overdue),
328 // local checkout occurred. Add to the total and the session.
329 this.circSummary.total += 1;
330 this.circSummary.session += 1;
333 dojo.byId('oils-selfck-circ-account-total').innerHTML =
334 dojo.string.substitute(
335 localeStrings.TOTAL_ITEMS_ACCOUNT,
336 [this.circSummary.total]
339 dojo.byId('oils-selfck-circ-session-total').innerHTML =
340 dojo.string.substitute(
341 localeStrings.TOTAL_ITEMS_SESSION,
342 [this.circSummary.session]
347 SelfCheckManager.prototype.drawHoldsPage = function() {
349 // TODO add option to hid scanBox
350 // this.updateScanBox(...)
352 openils.Util.hide('oils-selfck-circ-page');
353 openils.Util.hide('oils-selfck-payment-page');
354 openils.Util.show('oils-selfck-holds-page');
356 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
357 if(!this.holdTemplate)
358 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
359 while(this.holdTbody.childNodes[0])
360 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
362 progressDialog.show(true);
365 fieldmapper.standardRequest( // fetch the hold IDs
367 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
369 params : [this.authtoken, this.patron.id()],
371 oncomplete : function(r) {
372 var ids = openils.Util.readResponse(r);
373 if(!ids || ids.length == 0) {
374 progressDialog.hide();
378 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
379 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve.atomic'],
381 params : [self.authtoken, ids],
383 oncomplete : function(rr) {
384 self.drawHolds(openils.Util.readResponse(rr));
394 * Fetch and add a single hold to the list of holds
396 SelfCheckManager.prototype.drawHolds = function(holds) {
399 // sort available holds to the top of the list
400 // followed by queue position order
402 if(a.status == 4) return -1;
403 if(a.queue_position < b.queue_position) return -1;
408 progressDialog.hide();
410 for(var i in holds) {
413 var row = this.holdTemplate.cloneNode(true);
415 if(data.mvr.isbn()) {
416 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + data.mvr.isbn());
419 this.byName(row, 'title').innerHTML = data.mvr.title();
420 this.byName(row, 'author').innerHTML = data.mvr.author();
422 if(data.status == 4) {
424 // hold is ready for pickup
425 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
429 // hold is still pending
430 this.byName(row, 'status').innerHTML =
431 dojo.string.substitute(
432 localeStrings.HOLD_STATUS_WAITING,
433 [data.queue_position, data.potential_copies]
437 this.holdTbody.appendChild(row);
444 * Check out a single item. If the item is already checked
445 * out to the patron, redirect to renew()
447 SelfCheckManager.prototype.checkout = function(barcode, override) {
450 this.updateScanbox(null, true);
454 if(this.mockCheckouts) {
455 // if we're in mock-checkout mode, just insert another
456 // fake circ into the table and get out of here.
457 this.displayCheckout(this.mockCheckout, 'checkout');
461 // TODO see if it's a patron barcode
462 // TODO see if this item has already been checked out in this session
464 var method = 'open-ils.circ.checkout.full';
465 if(override) method += '.override';
467 console.log("Checkout out item " + barcode + " with method " + method);
469 var result = fieldmapper.standardRequest(
470 ['open-ils.circ', 'open-ils.circ.checkout.full'],
473 patron_id : this.patron.id(),
474 copy_barcode : barcode
479 console.log(js2JSON(result));
481 var stat = this.handleXactResult('checkout', barcode, result);
484 this.checkout(barcode, true);
485 } else if(stat.renew) {
491 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
493 var displayText = '';
495 // If true, the display message is important enough to pop up. Whether or not
496 // an alert() actually occurs, depends on org unit settings
499 // TODO handle lost/missing/etc checkin+checkout override steps
501 var payload = result.payload || {};
503 if(result.textcode == 'NO_SESSION') {
505 return this.logoutStaff();
507 } else if(result.textcode == 'SUCCESS') {
509 if(action == 'checkout') {
511 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
512 this.displayCheckout(result, 'checkout');
514 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
515 // A hold was fulfilled, update the hold numbers in the circ summary
516 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
517 this.holdsSummary = null;
518 this.updateHoldsSummary();
521 this.updateCircSummary(true);
523 } else if(action == 'renew') {
525 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
526 this.displayCheckout(result, 'renew');
529 this.updateScanBox();
531 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
533 // Server says the item is already checked out. If it's checked out to the
534 // current user, we may need to renew it.
536 if(payload.old_circ) {
539 old_circ refers to the previous checkout IFF it's for the same user.
540 If no auto-renew interval is not defined, assume we should renew it
541 If an auto-renew interval is defined and the payload comes back with
542 auto_renew set to true, do the renewal. Otherwise, let the patron know
543 the item is already checked out to them. */
545 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
546 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
547 return { renew : true };
551 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
555 // item is checked out to some other user
557 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
560 this.updateScanBox({select:true});
564 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
566 if(overrideEvents && overrideEvents.length) {
568 // see if the events we received are all in the list of
569 // events to override
571 if(!result.length) result = [result];
574 for(var i = 0; i < result.length; i++) {
575 var match = overrideEvents.filter(
576 function(e) { return (e == result[i].textcode); })[0];
584 return { override : true };
587 this.updateScanBox({select : true});
593 switch(result.textcode) {
595 case 'ACTOR_USER_NOT_FOUND' :
596 displayText = dojo.string.substitute(
597 localeStrings.LOGIN_FAILED, [item]);
600 case 'MAX_RENEWALS_REACHED' :
601 displayText = dojo.string.substitute(
602 localeStrings.MAX_RENEWALS, [item]);
605 case 'ITEM_NOT_CATALOGED' :
606 displayText = dojo.string.substitute(
607 localeStrings.ITEM_NOT_CATALOGED, [item]);
610 case 'OPEN_CIRCULATION_EXISTS' :
611 displayText = dojo.string.substitute(
612 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
616 console.error('Unhandled event ' + result.textcode);
618 if(action == 'checkout' || action == 'renew') {
619 displayText = dojo.string.substitute(
620 localeStrings.GENERIC_CIRC_FAILURE, [item]);
622 displayText = dojo.string.substitute(
623 localeStrings.UNKNOWN_ERROR, [result.textcode]);
628 console.log("Updating status with " + displayText);
630 dojo.byId('oils-selfck-status-div').innerHTML = displayText;
632 if(popup && this.orgSettings[SET_ALERT_ON_CHECKOUT_EVENT])
642 SelfCheckManager.prototype.renew = function(barcode, override) {
644 var method = 'open-ils.circ.renew';
645 if(override) method += '.override';
647 console.log("Renewing item " + barcode + " with method " + method);
649 var result = fieldmapper.standardRequest(
650 ['open-ils.circ', method],
653 patron_id : this.patron.id(),
654 copy_barcode : barcode
659 console.log(js2JSON(result));
661 var stat = this.handleXactResult('renew', barcode, result);
664 this.renew(barcode, true);
668 * Display the result of a checkout or renewal in the items out table
670 SelfCheckManager.prototype.displayCheckout = function(evt, type) {
672 var copy = evt.payload.copy;
673 var record = evt.payload.record;
674 var circ = evt.payload.circ;
675 var row = this.circTemplate.cloneNode(true);
678 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + record.isbn());
681 this.byName(row, 'barcode').innerHTML = copy.barcode();
682 this.byName(row, 'title').innerHTML = record.title();
683 this.byName(row, 'author').innerHTML = record.author();
684 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
685 openils.Util.show(this.byName(row, type));
687 var date = dojo.date.stamp.fromISOString(circ.due_date());
688 this.byName(row, 'due_date').innerHTML =
689 dojo.date.locale.format(date, {selector : 'date'});
691 // put new circs at the top of the list
692 this.circTbody.insertBefore(row, this.circTbody.getElementsByTagName('tr')[0]);
696 SelfCheckManager.prototype.byName = function(node, name) {
697 return dojo.query('[name=' + name+']', node)[0];
701 SelfCheckManager.prototype.drawFinesPage = function() {
703 openils.Util.hide('oils-selfck-circ-page');
704 openils.Util.hide('oils-selfck-holds-page');
705 openils.Util.show('oils-selfck-payment-page');
712 SelfCheckManager.prototype.printReceipt = function() {
717 * Logout the patron and return to the login page
719 SelfCheckManager.prototype.logoutPatron = function() {
722 this.holdsSummary = null;
723 this.circSummary = null;
725 this.drawLoginPage();
730 * Fire up the manager on page load
732 openils.Util.addOnLoad(
734 new SelfCheckManager().init();