1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.cookie');
3 dojo.require('dojo.date.stamp');
4 dojo.require('dijit.form.CheckBox');
5 dojo.require('dijit.form.NumberSpinner');
6 dojo.require('openils.CGI');
7 dojo.require('openils.Util');
8 dojo.require('openils.User');
9 dojo.require('openils.Event');
10 dojo.require('openils.widget.ProgressDialog');
11 dojo.require('openils.widget.OrgUnitFilteringSelect');
14 dojo.requireLocalization('openils.circ', 'selfcheck');
15 var localeStrings = dojo.i18n.getLocalization('openils.circ', 'selfcheck');
18 const SET_BARCODE_REGEX = 'opac.barcode_regex';
19 const SET_PATRON_TIMEOUT = 'circ.selfcheck.patron_login_timeout';
20 const SET_AUTO_OVERRIDE_EVENTS = 'circ.selfcheck.auto_override_checkout_events';
21 const SET_PATRON_PASSWORD_REQUIRED = 'circ.selfcheck.patron_password_required';
22 const SET_AUTO_RENEW_INTERVAL = 'circ.checkout_auto_renew_age';
23 const SET_WORKSTATION_REQUIRED = 'circ.selfcheck.workstation_required';
24 const SET_ALERT_POPUP = 'circ.selfcheck.alert.popup';
25 const SET_ALERT_SOUND = 'circ.selfcheck.alert.sound';
26 const SET_CC_PAYMENT_ALLOWED = 'credit.payments.allow';
27 // This setting only comes into play if COPY_NOT_AVAILABLE is in the SET_AUTO_OVERRIDE_EVENTS list
28 const SET_BLOCK_CHECKOUT_ON_COPY_STATUS = 'circ.selfcheck.block_checkout_on_copy_status';
30 // set before the login dialog is rendered
31 openils.User.default_login_agent = 'selfcheck';
33 function SelfCheckManager() {
35 this.cgi = new openils.CGI();
37 this.workstation = null;
38 this.authtoken = null;
41 this.patronBarcodeRegex = null;
46 // During renewals, keep track of the ID of the previous circulation.
47 // Previous circ is used for tracking failed renewals (for receipts).
50 // current item barcode
51 this.itemBarcode = null;
53 // are we currently performing a renewal?
54 this.isRenewal = false;
56 // dict of org unit settings for "here"
57 this.orgSettings = {};
59 // Construct a mock checkout for debugging purposes
60 if(this.mockCheckouts = this.cgi.param('mock-circ')) {
64 record : new fieldmapper.mvr(),
65 copy : new fieldmapper.acp(),
66 circ : new fieldmapper.circ()
70 this.mockCheckout.payload.record.title('Jazz improvisation for guitar');
71 this.mockCheckout.payload.record.author('Wise, Les');
72 this.mockCheckout.payload.record.isbn('0634033565');
73 this.mockCheckout.payload.copy.barcode('123456789');
74 this.mockCheckout.payload.circ.renewal_remaining(1);
75 this.mockCheckout.payload.circ.parent_circ(1);
76 this.mockCheckout.payload.circ.due_date('2012-12-21');
82 SelfCheckManager.prototype.setupStaffLogin = function(verify) {
84 if(verify) oilsSetupUser();
85 this.staff = openils.User.user;
86 this.workstation = openils.User.workstation;
87 this.authtoken = openils.User.authtoken;
93 * Fetch the org-unit settings, initialize the display, etc.
95 SelfCheckManager.prototype.init = function() {
97 this.setupStaffLogin();
98 this.loadOrgSettings();
100 this.circTbody = dojo.byId('oils-selfck-circ-tbody');
101 this.itemsOutTbody = dojo.byId('oils-selfck-circ-out-tbody');
103 // workstation is required but none provided
104 if(this.orgSettings[SET_WORKSTATION_REQUIRED] && !this.workstation) {
105 if(confirm(dojo.string.substitute(localeStrings.WORKSTATION_REQUIRED))) {
106 this.registerWorkstation();
112 // connect onclick handlers to the various navigation links
114 'oils-selfck-hold-details-link' : function() { self.drawHoldsPage(); },
115 'oils-selfck-view-fines-link' : function() { self.drawFinesPage(); },
116 'oils-selfck-pay-fines-link' : function() {
117 self.goToTab("payment");
118 self.drawPayFinesPage(
120 self.getSelectedFinesTotal(),
121 self.getSelectedFineTransactions(),
123 var evt = openils.Event.parse(resp);
125 var message = evt + '';
126 if(evt.textcode == 'CREDIT_PROCESSOR_DECLINED_TRANSACTION' && evt.payload)
127 message += '\n' + evt.payload.error_message;
128 if(evt.textcode == 'INVALID_USER_XACT_ID')
129 message += '\n' + localeStrings.PAYMENT_INVALID_USER_XACT_ID;
130 self.handleAlert(message, true, 'payment-failure');
134 self.patron.last_xact_id(resp.last_xact_id); // update to match latest from server
135 self.printPaymentReceipt(
138 self.updateFinesSummary();
139 self.drawFinesPage();
145 'oils-selfck-nav-home' : function() { self.drawCircPage(); },
146 'oils-selfck-nav-logout' : function() { self.logoutPatron(); },
147 'oils-selfck-nav-logout-print' : function() { self.logoutPatron(true); },
148 'oils-selfck-items-out-details-link' : function() { self.drawItemsOutPage(); },
149 'oils-selfck-print-list-link' : function() { self.printList(); }
152 for(var id in linkHandlers)
153 dojo.connect(dojo.byId(id), 'onclick', linkHandlers[id]);
156 if(this.cgi.param('patron')) {
158 // Patron barcode via cgi param. Mainly used for debugging and
159 // only works if password is not required by policy
160 this.loginPatron(this.cgi.param('patron'));
163 this.drawLoginPage();
167 * To test printing, pass a URL param of 'testprint'. The value for the param
168 * should be a JSON string like so: [{circ:<circ_id>}, ...]
170 var testPrint = this.cgi.param('testprint');
172 this.checkouts = JSON2js(testPrint);
173 this.printSessionReceipt();
179 SelfCheckManager.prototype.getSelectedFinesTotal = function() {
182 dojo.query("[name=selector]", this.finesTbody),
185 total += Number(input.getAttribute("balance_owed"));
188 return total.toFixed(2);
191 SelfCheckManager.prototype.getSelectedFineTransactions = function() {
192 return dojo.query("[name=selector]", this.finesTbody).
193 filter(function (o) { return o.checked }).
197 o.getAttribute("xact"),
198 Number(o.getAttribute("balance_owed")).toFixed(2)
205 * Registers a new workstion
207 SelfCheckManager.prototype.registerWorkstation = function() {
209 oilsSelfckWsDialog.show();
211 new openils.User().buildPermOrgSelector(
212 'REGISTER_WORKSTATION',
213 oilsSelfckWsLocSelector,
219 dojo.connect(oilsSelfckWsSubmit, 'onClick',
222 oilsSelfckWsDialog.hide();
223 var name = oilsSelfckWsLocSelector.attr('displayedValue') + '-' + oilsSelfckWsName.attr('value');
225 var res = fieldmapper.standardRequest(
226 ['open-ils.actor', 'open-ils.actor.workstation.register'],
228 self.authtoken, name, oilsSelfckWsLocSelector.attr('value')
233 if(evt = openils.Event.parse(res)) {
234 if(evt.textcode == 'WORKSTATION_NAME_EXISTS') {
235 if(confirm(localeStrings.WORKSTATION_EXISTS)) {
236 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
238 self.registerWorkstation();
245 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
252 * Loads the org unit settings
254 SelfCheckManager.prototype.loadOrgSettings = function() {
256 var settings = fieldmapper.aou.fetchOrgSettingBatch(
257 this.staff.ws_ou(), [
262 SET_AUTO_OVERRIDE_EVENTS,
263 SET_BLOCK_CHECKOUT_ON_COPY_STATUS,
264 SET_PATRON_PASSWORD_REQUIRED,
265 SET_AUTO_RENEW_INTERVAL,
266 SET_WORKSTATION_REQUIRED,
267 SET_CC_PAYMENT_ALLOWED
273 this.orgSettings[k] = settings[k].value;
276 if(settings[SET_BARCODE_REGEX])
277 this.patronBarcodeRegex = new RegExp(settings[SET_BARCODE_REGEX].value);
280 SelfCheckManager.prototype.drawLoginPage = function() {
283 var bcHandler = function(barcode_or_usrname) {
284 // handle patron barcode/usrname entry
286 if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
288 // password is required. wire up the scan box to read it
290 msg : localeStrings.ENTER_PASSWORD,
291 handler : function(pw) { self.loginPatron(barcode_or_usrname, pw); },
296 // password is not required, go ahead and login
297 self.loginPatron(barcode_or_usrname);
302 msg : localeStrings.PLEASE_LOGIN,
310 SelfCheckManager.prototype.loginPatron = function(barcode_or_usrname, passwd) {
312 this.setupStaffLogin(true); // verify still valid
316 console.log('testing ' + barcode_or_usrname);
317 if (barcode_or_usrname.match(this.patronBarcodeRegex)) {
318 console.log('barcode');
319 barcode = barcode_or_usrname;
321 console.log('usrname');
322 usrname = barcode_or_usrname;
325 if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
328 // would only happen in dev/debug mode when using the patron= param
329 alert('password required by org setting. remove patron= from URL');
333 // patron password is required. Verify it.
336 new openils.User().auth_verify(
337 { username : usrname, barcode : barcode,
338 type : 'opac', passwd : passwd, agent : 'selfcheck' },
341 self.fetchPatron(barcode, usrname);
344 // auth verify failed
346 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode_or_usrname]),
347 false, 'login-failure'
349 self.drawLoginPage();
355 this.fetchPatron(barcode, usrname);
359 SelfCheckManager.prototype.fetchPatron = function(barcode, usrname) {
361 var patron_id = fieldmapper.standardRequest(
362 ['open-ils.actor', 'open-ils.actor.user.retrieve_id_by_barcode_or_username'],
363 {params : [this.authtoken, barcode, usrname]}
366 // retrieve the fleshed user by id
367 this.patron = fieldmapper.standardRequest(
368 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
369 {params : [this.authtoken, patron_id]}
372 var evt = openils.Event.parse(this.patron);
374 // verify validity of the card used to log in
375 var inactiveCard = false;
379 card = this.patron.cards().filter(
380 function(c) { return (c.barcode() == barcode); })[0];
382 card = this.patron.card();
384 inactiveCard = !openils.Util.isTrue(card.active());
387 if(evt || inactiveCard) {
389 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode || usrname]),
390 false, 'login-failure'
392 this.drawLoginPage();
396 this.handleAlert('', false, 'login-success');
397 dojo.byId('oils-selfck-user-banner').innerHTML =
398 dojo.string.substitute(localeStrings.WELCOME_BANNER, [this.patron.first_given_name()]);
404 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
406 console.log("Handling alert " + message);
408 dojo.byId('oils-selfck-status-div').innerHTML = message;
411 openils.Util.addCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
413 openils.Util.removeCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
415 if(shouldPopup && this.orgSettings[SET_ALERT_POPUP])
418 if(sound && this.orgSettings[SET_ALERT_SOUND])
419 openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
424 * Manages the main input box
425 * @param msg The context message to display with the box
426 * @param clearOnly Don't update the context message, just clear the value and re-focus
427 * @param handler Optional "on-enter" handler.
429 SelfCheckManager.prototype.updateScanBox = function(args) {
433 selfckScanBox.domNode.select();
435 selfckScanBox.attr('value', '');
439 selfckScanBox.domNode.setAttribute('type', 'password');
441 selfckScanBox.domNode.setAttribute('type', '');
445 selfckScanBox.attr('value', args.value);
448 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
450 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
451 dojo.disconnect(selfckScanBox._lastHandler);
455 selfckScanBox._lastHandler = dojo.connect(
459 if(e.keyCode != dojo.keys.ENTER)
461 args.handler(selfckScanBox.attr('value'));
466 selfckScanBox.focus();
470 * Sets up the checkout/renewal interface
472 SelfCheckManager.prototype.drawCircPage = function() {
474 openils.Util.show('oils-selfck-circ-tbody', 'table-row-group');
475 this.goToTab('checkout');
477 while(this.itemsOutTbody.childNodes[0])
478 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
482 msg : localeStrings.ENTER_BARCODE,
483 handler : function(barcode) { self.checkout(barcode); }
486 if(!this.circTemplate)
487 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
490 this.updateFinesSummary();
493 this.updateHoldsSummary();
496 this.updateCircSummary();
498 // render mock checkouts for debugging?
499 if(this.mockCheckouts) {
500 for(var i in [1,2,3])
501 this.displayCheckout(this.mockCheckout, 'checkout');
506 SelfCheckManager.prototype.updateFinesSummary = function() {
510 fieldmapper.standardRequest(
511 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
513 params : [this.authtoken, this.patron.id()],
514 oncomplete : function(r) {
516 var summary = openils.Util.readResponse(r);
518 dojo.byId('oils-selfck-fines-total').innerHTML =
519 dojo.string.substitute(
520 localeStrings.TOTAL_FINES_ACCOUNT,
521 [summary.balance_owed()]
524 self.creditPayableBalance = summary.balance_owed();
531 SelfCheckManager.prototype.drawItemsOutPage = function() {
532 openils.Util.hide('oils-selfck-circ-tbody');
534 this.goToTab('items_out');
536 while(this.itemsOutTbody.childNodes[0])
537 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
539 progressDialog.show(true);
542 fieldmapper.standardRequest(
543 ['open-ils.circ', 'open-ils.circ.actor.user.checked_out.atomic'],
546 params : [this.authtoken, this.patron.id()],
547 oncomplete : function(r) {
549 var resp = openils.Util.readResponse(r);
551 var circs = resp.sort(
553 if(a.circ.due_date() > b.circ.due_date())
559 progressDialog.hide();
564 self.itemsOut.push(circ.circ.id());
565 self.displayCheckout(
567 (circ.circ.parent_circ()) ? 'renew' : 'checkout',
578 SelfCheckManager.prototype.goToTab = function(name) {
581 openils.Util.hide('oils-selfck-fines-page');
582 openils.Util.hide('oils-selfck-payment-page');
583 openils.Util.hide('oils-selfck-holds-page');
584 openils.Util.hide('oils-selfck-circ-page');
585 openils.Util.hide('oils-selfck-pay-fines-link');
589 openils.Util.show('oils-selfck-circ-page');
592 openils.Util.show('oils-selfck-circ-page');
595 openils.Util.show('oils-selfck-holds-page');
598 openils.Util.show('oils-selfck-fines-page');
601 openils.Util.show('oils-selfck-payment-page');
607 SelfCheckManager.prototype.printList = function() {
608 switch(this.tabName) {
610 this.printSessionReceipt();
613 this.printItemsOutReceipt();
616 this.printHoldsReceipt();
619 this.printFinesReceipt();
624 SelfCheckManager.prototype.updateHoldsSummary = function() {
626 if(!this.holdsSummary) {
627 var summary = fieldmapper.standardRequest(
628 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
629 {params : [this.authtoken, this.patron.id()]}
632 this.holdsSummary = {};
633 this.holdsSummary.ready = Number(summary['4']);
634 this.holdsSummary.total = 0;
636 for(var i in summary)
637 this.holdsSummary.total += Number(summary[i]);
640 dojo.byId('oils-selfck-holds-total').innerHTML =
641 dojo.string.substitute(
642 localeStrings.TOTAL_HOLDS,
643 [this.holdsSummary.total]
646 dojo.byId('oils-selfck-holds-ready').innerHTML =
647 dojo.string.substitute(
648 localeStrings.HOLDS_READY_FOR_PICKUP,
649 [this.holdsSummary.ready]
654 SelfCheckManager.prototype.updateCircSummary = function(increment) {
656 if(!this.circSummary) {
658 var summary = fieldmapper.standardRequest(
659 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
660 {params : [this.authtoken, this.patron.id()]}
664 total : Number(summary.out) + Number(summary.overdue),
665 overdue : Number(summary.overdue),
671 // local checkout occurred. Add to the total and the session.
672 this.circSummary.total += 1;
673 this.circSummary.session += 1;
676 dojo.byId('oils-selfck-circ-account-total').innerHTML =
677 dojo.string.substitute(
678 localeStrings.TOTAL_ITEMS_ACCOUNT,
679 [this.circSummary.total]
682 dojo.byId('oils-selfck-circ-session-total').innerHTML =
683 dojo.string.substitute(
684 localeStrings.TOTAL_ITEMS_SESSION,
685 [this.circSummary.session]
690 SelfCheckManager.prototype.drawHoldsPage = function() {
692 // TODO add option to hid scanBox
693 // this.updateScanBox(...)
695 this.goToTab('holds');
697 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
698 if(!this.holdTemplate)
699 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
700 while(this.holdTbody.childNodes[0])
701 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
703 progressDialog.show(true);
706 fieldmapper.standardRequest( // fetch the hold IDs
708 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
710 params : [this.authtoken, this.patron.id()],
712 oncomplete : function(r) {
713 var ids = openils.Util.readResponse(r);
714 if(!ids || ids.length == 0) {
715 progressDialog.hide();
719 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
720 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve'],
722 params : [self.authtoken, ids],
723 onresponse : function(rr) {
724 progressDialog.hide();
725 self.insertHold(openils.Util.readResponse(rr));
734 SelfCheckManager.prototype.insertHold = function(data) {
735 var row = this.holdTemplate.cloneNode(true);
737 if(data.mvr.isbn()) {
738 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + data.mvr.isbn());
741 this.byName(row, 'title').innerHTML = data.mvr.title();
742 this.byName(row, 'author').innerHTML = data.mvr.author();
744 if(data.status == 4) {
746 // hold is ready for pickup
747 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
751 // hold is still pending
752 this.byName(row, 'status').innerHTML =
753 dojo.string.substitute(
754 localeStrings.HOLD_STATUS_WAITING,
755 [data.queue_position, data.potential_copies]
759 // find the correct place the table to slot in the hold based on queue position
761 var position = (data.status == 4) ? 0 : data.queue_position;
762 row.setAttribute('position', position);
764 for(var i = 0; i < this.holdTbody.childNodes.length; i++) {
765 var node = this.holdTbody.childNodes[i];
766 if(Number(node.getAttribute('position')) >= position) {
767 this.holdTbody.insertBefore(row, node);
772 this.holdTbody.appendChild(row);
776 SelfCheckManager.prototype.drawFinesPage = function() {
778 // TODO add option to hid scanBox
779 // this.updateScanBox(...)
781 this.goToTab('fines');
782 progressDialog.show(true);
784 if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
785 openils.Util.show('oils-selfck-pay-fines-link', 'inline');
788 this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
789 if(!this.finesTemplate)
790 this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
791 while(this.finesTbody.childNodes[0])
792 this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
794 // when user clicks on a selector checkbox, update the total owed
795 var updateSelected = function() {
798 dojo.query('[name=selector]', this.finesTbody),
801 total += Number(input.getAttribute('balance_owed'));
805 total = total.toFixed(2);
806 dojo.byId('oils-selfck-selected-total').innerHTML =
807 dojo.string.substitute(localeStrings.TOTAL_FINES_SELECTED, [total]);
810 // wire up the batch on/off selector
811 var sel = dojo.byId('oils-selfck-fines-selector');
812 sel.onchange = function() {
814 dojo.query('[name=selector]', this.finesTbody),
816 input.checked = sel.checked;
822 var handler = function(dataList) {
824 self.finesCount = dataList.length;
825 self.finesData = dataList;
827 for(var i in dataList) {
829 var data = dataList[i];
830 var row = self.finesTemplate.cloneNode(true);
831 var type = data.transaction.xact_type();
833 if(type == 'circulation') {
834 self.byName(row, 'type').innerHTML = type;
835 self.byName(row, 'details').innerHTML = data.record.title();
837 } else if(type == 'grocery') {
838 self.byName(row, 'type').innerHTML = localeStrings.MISCELLANEOUS; // Go ahead and head off any confusion around "grocery".
839 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
842 self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
843 self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
844 self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
847 var selector = self.byName(row, 'selector')
848 selector.onchange = updateSelected;
849 selector.setAttribute('xact', data.transaction.id());
850 selector.setAttribute('balance_owed', data.transaction.balance_owed());
851 selector.checked = true;
853 self.finesTbody.appendChild(row);
860 fieldmapper.standardRequest(
861 ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
863 params : [this.authtoken, this.patron.id()],
864 oncomplete : function(r) {
865 progressDialog.hide();
866 handler(openils.Util.readResponse(r));
872 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
874 var resp = fieldmapper.standardRequest(
875 ['open-ils.circ', 'open-ils.circ.transit.abort'],
876 {params : [this.authtoken, {barcode : barcode}]}
879 // resp == 1 on success
880 if(openils.Event.parse(resp))
883 var resp = fieldmapper.standardRequest(
884 ['open-ils.circ', 'open-ils.circ.checkin.override'],
887 patron_id : this.patron.id(),
888 copy_barcode : barcode,
894 if(!resp.length) resp = [resp];
895 for(var i = 0; i < resp.length; i++) {
896 var tc = openils.Event.parse(resp[i]).textcode;
897 if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
908 * Check out a single item. If the item is already checked
909 * out to the patron, redirect to renew()
911 SelfCheckManager.prototype.checkout = function(barcode, override) {
913 this.prevCirc = null;
916 this.updateScanbox(null, true);
920 if(this.mockCheckouts) {
921 // if we're in mock-checkout mode, just insert another
922 // fake circ into the table and get out of here.
923 this.displayCheckout(this.mockCheckout, 'checkout');
927 // TODO see if it's a patron barcode
928 // TODO see if this item has already been checked out in this session
930 var method = 'open-ils.circ.checkout.full';
931 if(override) method += '.override';
933 console.log("Checkout out item " + barcode + " with method " + method);
935 var result = fieldmapper.standardRequest(
936 ['open-ils.circ', method],
939 patron_id : this.patron.id(),
940 copy_barcode : barcode
945 var stat = this.handleXactResult('checkout', barcode, result);
948 this.checkout(barcode, true);
949 } else if(stat.doOver) {
950 this.checkout(barcode);
951 } else if(stat.renew) {
956 SelfCheckManager.prototype.failPartMessage = function(result) {
957 if (result.payload && result.payload.fail_part) {
958 var stringKey = "FAIL_PART_" +
959 result.payload.fail_part.replace(/\./g, "_");
960 return localeStrings[stringKey];
966 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
968 var displayText = '';
970 // If true, the display message is important enough to pop up. Whether or not
971 // an alert() actually occurs, depends on org unit settings
973 var sound = ''; // sound file reference
974 var payload = result.payload || {};
975 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
976 var blockStatuses = this.orgSettings[SET_BLOCK_CHECKOUT_ON_COPY_STATUS];
978 if(result.textcode == 'NO_SESSION') {
980 return this.logoutStaff();
982 } else if(result.textcode == 'SUCCESS') {
984 if(action == 'checkout') {
986 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
987 this.displayCheckout(result, 'checkout');
989 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
990 // A hold was fulfilled, update the hold numbers in the circ summary
991 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
992 this.holdsSummary = null;
993 this.updateHoldsSummary();
996 this.updateCircSummary(true);
998 } else if(action == 'renew') {
1000 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
1001 this.displayCheckout(result, 'renew');
1004 this.checkouts.push({circ : result.payload.circ.id()});
1005 sound = 'checkout-success';
1006 this.updateScanBox();
1008 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
1010 // Server says the item is already checked out. If it's checked out to the
1011 // current user, we may need to renew it.
1013 if(payload.old_circ) {
1016 old_circ refers to the previous checkout IFF it's for the same user.
1017 If no auto-renew interval is not defined, assume we should renew it
1018 If an auto-renew interval is defined and the payload comes back with
1019 auto_renew set to true, do the renewal. Otherwise, let the patron know
1020 the item is already checked out to them. */
1022 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
1023 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
1024 this.prevCirc = payload.old_circ.id();
1025 return { renew : true };
1029 sound = 'checkout-failure';
1030 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
1034 if( // copy is marked lost. if configured to do so, check it in and try again.
1035 result.payload.copy &&
1036 result.payload.copy.status() == /* LOST */ 3 &&
1037 overrideEvents && overrideEvents.length &&
1038 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
1040 if(this.checkin(item)) {
1041 return { doOver : true };
1046 // item is checked out to some other user
1048 sound = 'checkout-failure';
1049 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1052 this.updateScanBox({select:true});
1057 if(overrideEvents && overrideEvents.length) {
1059 // see if the events we received are all in the list of
1060 // events to override
1062 if(!result.length) result = [result];
1064 var override = true;
1065 for(var i = 0; i < result.length; i++) {
1067 var match = overrideEvents.filter(function(e) { return (e == result[i].textcode); })[0];
1074 if(result[i].textcode == 'COPY_NOT_AVAILABLE' && blockStatuses && blockStatuses.length) {
1076 var stat = result[i].payload.status(); // copy status
1077 if(typeof stat == 'object') stat = stat.id();
1079 var match2 = blockStatuses.filter(function(e) { return (e == stat); })[0];
1081 if(match2) { // copy is in a blocked status
1087 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1088 // to override a transit, we have to abort the transit and check it in first
1089 if(this.checkin(item, true)) {
1090 return { doOver : true };
1098 return { override : true };
1101 this.updateScanBox({select : true});
1103 sound = 'checkout-failure';
1105 if(action == 'renew')
1106 this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1111 switch(result.textcode) {
1113 // TODO custom handler for blocking penalties
1115 case 'MAX_RENEWALS_REACHED' :
1116 displayText = dojo.string.substitute(
1117 localeStrings.MAX_RENEWALS, [item]);
1120 case 'ITEM_NOT_CATALOGED' :
1121 displayText = dojo.string.substitute(
1122 localeStrings.ITEM_NOT_CATALOGED, [item]);
1125 case 'OPEN_CIRCULATION_EXISTS' :
1126 displayText = dojo.string.substitute(
1127 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1132 console.error('Unhandled event ' + result.textcode);
1134 if (!(displayText = this.failPartMessage(result))) {
1135 if (action == 'checkout' || action == 'renew') {
1136 displayText = dojo.string.substitute(
1137 localeStrings.GENERIC_CIRC_FAILURE, [item]);
1139 displayText = dojo.string.substitute(
1140 localeStrings.UNKNOWN_ERROR, [result.textcode]);
1146 this.handleAlert(displayText, popup, sound);
1154 SelfCheckManager.prototype.renew = function(barcode, override) {
1156 var method = 'open-ils.circ.renew';
1157 if(override) method += '.override';
1159 console.log("Renewing item " + barcode + " with method " + method);
1161 var result = fieldmapper.standardRequest(
1162 ['open-ils.circ', method],
1165 patron_id : this.patron.id(),
1166 copy_barcode : barcode
1171 console.log(js2JSON(result));
1173 var stat = this.handleXactResult('renew', barcode, result);
1176 this.renew(barcode, true);
1180 * Display the result of a checkout or renewal in the items out table
1182 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1184 var copy = evt.payload.copy;
1185 var record = evt.payload.record;
1186 var circ = evt.payload.circ;
1187 var row = this.circTemplate.cloneNode(true);
1190 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + record.isbn());
1193 this.byName(row, 'barcode').innerHTML = copy.barcode();
1194 this.byName(row, 'title').innerHTML = record.title();
1195 this.byName(row, 'author').innerHTML = record.author();
1196 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1197 openils.Util.show(this.byName(row, type));
1199 var date = dojo.date.stamp.fromISOString(circ.due_date());
1200 this.byName(row, 'due_date').innerHTML =
1201 dojo.date.locale.format(date, {selector : 'date'});
1203 // put new circs at the top of the list
1204 var tbody = this.circTbody;
1205 if(itemsOut) tbody = this.itemsOutTbody;
1206 tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1210 SelfCheckManager.prototype.byName = function(node, name) {
1211 return dojo.query('[name=' + name+']', node)[0];
1215 SelfCheckManager.prototype.initPrinter = function() {
1216 try { // Mozilla only
1217 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1218 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1219 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1220 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1221 var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1223 pref.setBoolPref('print.always_print_silent', true);
1225 console.log("Unable to initialize auto-printing");
1230 * Print a receipt for this session's checkouts
1232 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1235 var circCtx = []; // circ context data. in this case, renewal_failure info
1237 // collect the circs and failure info
1241 circIds.push(blob.circ);
1242 circCtx.push({renewal_failure:blob.renewal_failure});
1250 'format.selfcheck.checkout',
1257 fieldmapper.standardRequest(
1258 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1262 oncomplete : function(r) {
1263 var resp = openils.Util.readResponse(r);
1264 var output = resp.template_output();
1266 self.printData(output.data(), self.checkouts.length, callback);
1268 var error = resp.error_output();
1270 throw new Error("Error creating receipt: " + error.data());
1272 throw new Error("No receipt data returned from server");
1280 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1282 var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1,chrome');
1283 win.document.body.innerHTML = data;
1287 * There is no way to know when the browser is done printing.
1288 * Make a best guess at when to close the print window by basing
1289 * the setTimeout wait on the number of items to be printed plus
1292 var sleepTime = 1000;
1294 sleepTime += (numItems / 2) * 1000;
1298 win.close(); // close the print window
1300 callback(); // fire optional post-print callback
1308 * Print a receipt for this user's items out
1310 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1312 if(!this.itemsOut.length) return;
1314 progressDialog.show(true);
1320 'format.selfcheck.items_out',
1326 fieldmapper.standardRequest(
1327 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1331 oncomplete : function(r) {
1332 progressDialog.hide();
1333 var resp = openils.Util.readResponse(r);
1334 var output = resp.template_output();
1336 self.printData(output.data(), self.itemsOut.length, callback);
1338 var error = resp.error_output();
1340 throw new Error("Error creating receipt: " + error.data());
1342 throw new Error("No receipt data returned from server");
1351 * Print a receipt for this user's items out
1353 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1355 if(!this.holds.length) return;
1357 progressDialog.show(true);
1362 dojo.forEach(this.holds,
1364 holdIds.push(data.hold.id());
1365 if(data.status == 4) {
1366 holdData.push({ready : true});
1369 queue_position : data.queue_position,
1370 potential_copies : data.potential_copies
1380 'format.selfcheck.holds',
1387 fieldmapper.standardRequest(
1388 ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1392 oncomplete : function(r) {
1393 progressDialog.hide();
1394 var resp = openils.Util.readResponse(r);
1395 var output = resp.template_output();
1397 self.printData(output.data(), self.holds.length, callback);
1399 var error = resp.error_output();
1401 throw new Error("Error creating receipt: " + error.data());
1403 throw new Error("No receipt data returned from server");
1412 SelfCheckManager.prototype.printPaymentReceipt = function(response, callback) {
1415 progressDialog.show(true);
1417 fieldmapper.standardRequest(
1418 ['open-ils.circ', 'open-ils.circ.money.payment_receipt.print'],
1421 params : [this.authtoken, response.payments],
1422 oncomplete : function(r) {
1423 var resp = openils.Util.readResponse(r);
1424 var output = resp.template_output();
1425 progressDialog.hide();
1427 self.printData(output.data(), 1, callback);
1429 var error = resp.error_output();
1431 throw new Error("Error creating receipt: " + error.data());
1433 throw new Error("No receipt data returned from server");
1442 * Print a receipt for this user's items out
1444 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1446 progressDialog.show(true);
1452 'format.selfcheck.fines',
1458 fieldmapper.standardRequest(
1459 ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1463 oncomplete : function(r) {
1464 progressDialog.hide();
1465 var resp = openils.Util.readResponse(r);
1466 var output = resp.template_output();
1468 self.printData(output.data(), self.finesCount, callback);
1470 var error = resp.error_output();
1472 throw new Error("Error creating receipt: " + error.data());
1474 throw new Error("No receipt data returned from server");
1486 * Logout the patron and return to the login page
1488 SelfCheckManager.prototype.logoutPatron = function(print) {
1489 progressDialog.show(true); // prevent patron from clicking logout link twice
1490 if(print && this.checkouts.length) {
1491 this.printSessionReceipt(
1493 location.href = location.href;
1497 location.href = location.href;
1503 * Fire up the manager on page load
1505 openils.Util.addOnLoad(
1507 new SelfCheckManager().init();