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 function SelfCheckManager() {
32 this.cgi = new openils.CGI();
34 this.workstation = null;
35 this.authtoken = null;
38 this.patronBarcodeRegex = null;
43 // During renewals, keep track of the ID of the previous circulation.
44 // Previous circ is used for tracking failed renewals (for receipts).
47 // current item barcode
48 this.itemBarcode = null;
50 // are we currently performing a renewal?
51 this.isRenewal = false;
53 // dict of org unit settings for "here"
54 this.orgSettings = {};
56 // Construct a mock checkout for debugging purposes
57 if(this.mockCheckouts = this.cgi.param('mock-circ')) {
61 record : new fieldmapper.mvr(),
62 copy : new fieldmapper.acp(),
63 circ : new fieldmapper.circ()
67 this.mockCheckout.payload.record.title('Jazz improvisation for guitar');
68 this.mockCheckout.payload.record.author('Wise, Les');
69 this.mockCheckout.payload.record.isbn('0634033565');
70 this.mockCheckout.payload.copy.barcode('123456789');
71 this.mockCheckout.payload.circ.renewal_remaining(1);
72 this.mockCheckout.payload.circ.parent_circ(1);
73 this.mockCheckout.payload.circ.due_date('2012-12-21');
79 SelfCheckManager.prototype.setupStaffLogin = function(verify) {
81 if(verify) oilsSetupUser();
82 this.staff = openils.User.user;
83 this.workstation = openils.User.workstation;
84 this.authtoken = openils.User.authtoken;
90 * Fetch the org-unit settings, initialize the display, etc.
92 SelfCheckManager.prototype.init = function() {
94 this.setupStaffLogin();
95 this.loadOrgSettings();
97 this.circTbody = dojo.byId('oils-selfck-circ-tbody');
98 this.itemsOutTbody = dojo.byId('oils-selfck-circ-out-tbody');
100 // workstation is required but none provided
101 if(this.orgSettings[SET_WORKSTATION_REQUIRED] && !this.workstation) {
102 if(confirm(dojo.string.substitute(localeStrings.WORKSTATION_REQUIRED))) {
103 this.registerWorkstation();
109 // connect onclick handlers to the various navigation links
111 'oils-selfck-hold-details-link' : function() { self.drawHoldsPage(); },
112 'oils-selfck-view-fines-link' : function() { self.drawFinesPage(); },
113 'oils-selfck-pay-fines-link' : function() {
114 self.goToTab("payment");
115 self.drawPayFinesPage(
117 self.getSelectedFinesTotal(),
118 self.getSelectedFineTransactions(),
120 var evt = openils.Event.parse(resp);
122 var message = evt + '';
123 if(evt.textcode == 'CREDIT_PROCESSOR_DECLINED_TRANSACTION' && evt.payload)
124 message += '\n' + evt.payload.error_message;
125 if(evt.textcode == 'INVALID_USER_XACT_ID')
126 message += '\n' + localeStrings.PAYMENT_INVALID_USER_XACT_ID;
127 self.handleAlert(message, true, 'payment-failure');
131 self.patron.last_xact_id(resp.last_xact_id); // update to match latest from server
132 self.printPaymentReceipt(
135 self.updateFinesSummary();
136 self.drawFinesPage();
142 'oils-selfck-nav-home' : function() { self.drawCircPage(); },
143 'oils-selfck-nav-logout' : function() { self.logoutPatron(); },
144 'oils-selfck-nav-logout-print' : function() { self.logoutPatron(true); },
145 'oils-selfck-items-out-details-link' : function() { self.drawItemsOutPage(); },
146 'oils-selfck-print-list-link' : function() { self.printList(); }
149 for(var id in linkHandlers)
150 dojo.connect(dojo.byId(id), 'onclick', linkHandlers[id]);
153 if(this.cgi.param('patron')) {
155 // Patron barcode via cgi param. Mainly used for debugging and
156 // only works if password is not required by policy
157 this.loginPatron(this.cgi.param('patron'));
160 this.drawLoginPage();
164 * To test printing, pass a URL param of 'testprint'. The value for the param
165 * should be a JSON string like so: [{circ:<circ_id>}, ...]
167 var testPrint = this.cgi.param('testprint');
169 this.checkouts = JSON2js(testPrint);
170 this.printSessionReceipt();
176 SelfCheckManager.prototype.getSelectedFinesTotal = function() {
179 dojo.query("[name=selector]", this.finesTbody),
182 total += Number(input.getAttribute("balance_owed"));
185 return total.toFixed(2);
188 SelfCheckManager.prototype.getSelectedFineTransactions = function() {
189 return dojo.query("[name=selector]", this.finesTbody).
190 filter(function (o) { return o.checked }).
194 o.getAttribute("xact"),
195 Number(o.getAttribute("balance_owed")).toFixed(2)
202 * Registers a new workstion
204 SelfCheckManager.prototype.registerWorkstation = function() {
206 oilsSelfckWsDialog.show();
208 new openils.User().buildPermOrgSelector(
209 'REGISTER_WORKSTATION',
210 oilsSelfckWsLocSelector,
216 dojo.connect(oilsSelfckWsSubmit, 'onClick',
219 oilsSelfckWsDialog.hide();
220 var name = oilsSelfckWsLocSelector.attr('displayedValue') + '-' + oilsSelfckWsName.attr('value');
222 var res = fieldmapper.standardRequest(
223 ['open-ils.actor', 'open-ils.actor.workstation.register'],
225 self.authtoken, name, oilsSelfckWsLocSelector.attr('value')
230 if(evt = openils.Event.parse(res)) {
231 if(evt.textcode == 'WORKSTATION_NAME_EXISTS') {
232 if(confirm(localeStrings.WORKSTATION_EXISTS)) {
233 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
235 self.registerWorkstation();
242 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
249 * Loads the org unit settings
251 SelfCheckManager.prototype.loadOrgSettings = function() {
253 var settings = fieldmapper.aou.fetchOrgSettingBatch(
254 this.staff.ws_ou(), [
259 SET_AUTO_OVERRIDE_EVENTS,
260 SET_BLOCK_CHECKOUT_ON_COPY_STATUS,
261 SET_PATRON_PASSWORD_REQUIRED,
262 SET_AUTO_RENEW_INTERVAL,
263 SET_WORKSTATION_REQUIRED,
264 SET_CC_PAYMENT_ALLOWED
270 this.orgSettings[k] = settings[k].value;
273 if(settings[SET_BARCODE_REGEX])
274 this.patronBarcodeRegex = new RegExp(settings[SET_BARCODE_REGEX].value);
277 SelfCheckManager.prototype.drawLoginPage = function() {
280 var bcHandler = function(barcode) {
281 // handle patron barcode entry
283 if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
285 // password is required. wire up the scan box to read it
287 msg : 'Please enter your password', // TODO i18n
288 handler : function(pw) { self.loginPatron(barcode, pw); },
293 // password is not required, go ahead and login
294 self.loginPatron(barcode);
299 msg : 'Please log in with your library barcode.', // TODO
307 SelfCheckManager.prototype.loginPatron = function(barcode, passwd) {
309 this.setupStaffLogin(true); // verify still valid
311 if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
314 // would only happen in dev/debug mode when using the patron= param
315 alert('password required by org setting. remove patron= from URL');
319 // patron password is required. Verify it.
321 var res = fieldmapper.standardRequest(
322 ['open-ils.actor', 'open-ils.actor.verify_user_password'],
323 {params : [this.authtoken, barcode, null, hex_md5(passwd)]}
327 // user-not-found results in login failure
329 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]),
330 false, 'login-failure'
332 this.drawLoginPage();
337 // retrieve the fleshed user by barcode
338 this.patron = fieldmapper.standardRequest(
339 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve_by_barcode'],
340 {params : [this.authtoken, barcode]}
343 var evt = openils.Event.parse(this.patron);
345 // verify validity of the card used to log in
346 var inactiveCard = false;
348 var card = this.patron.cards().filter(
349 function(c) { return (c.barcode() == barcode); })[0];
350 inactiveCard = !openils.Util.isTrue(card.active());
353 if(evt || inactiveCard) {
355 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]),
356 false, 'login-failure'
358 this.drawLoginPage();
362 this.handleAlert('', false, 'login-success');
363 dojo.byId('oils-selfck-user-banner').innerHTML =
364 dojo.string.substitute(localeStrings.WELCOME_BANNER, [this.patron.first_given_name()]);
370 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
372 console.log("Handling alert " + message);
374 dojo.byId('oils-selfck-status-div').innerHTML = message;
376 if(shouldPopup && this.orgSettings[SET_ALERT_POPUP])
379 if(sound && this.orgSettings[SET_ALERT_SOUND])
380 openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
385 * Manages the main input box
386 * @param msg The context message to display with the box
387 * @param clearOnly Don't update the context message, just clear the value and re-focus
388 * @param handler Optional "on-enter" handler.
390 SelfCheckManager.prototype.updateScanBox = function(args) {
394 selfckScanBox.domNode.select();
396 selfckScanBox.attr('value', '');
400 selfckScanBox.domNode.setAttribute('type', 'password');
402 selfckScanBox.domNode.setAttribute('type', '');
406 selfckScanBox.attr('value', args.value);
409 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
411 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
412 dojo.disconnect(selfckScanBox._lastHandler);
416 selfckScanBox._lastHandler = dojo.connect(
420 if(e.keyCode != dojo.keys.ENTER)
422 args.handler(selfckScanBox.attr('value'));
427 selfckScanBox.focus();
431 * Sets up the checkout/renewal interface
433 SelfCheckManager.prototype.drawCircPage = function() {
435 openils.Util.show('oils-selfck-circ-tbody', 'table-row-group');
436 this.goToTab('checkout');
438 while(this.itemsOutTbody.childNodes[0])
439 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
443 msg : 'Please enter an item barcode', // TODO i18n
444 handler : function(barcode) { self.checkout(barcode); }
447 if(!this.circTemplate)
448 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
451 this.updateFinesSummary();
454 this.updateHoldsSummary();
457 this.updateCircSummary();
459 // render mock checkouts for debugging?
460 if(this.mockCheckouts) {
461 for(var i in [1,2,3])
462 this.displayCheckout(this.mockCheckout, 'checkout');
467 SelfCheckManager.prototype.updateFinesSummary = function() {
471 fieldmapper.standardRequest(
472 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
474 params : [this.authtoken, this.patron.id()],
475 oncomplete : function(r) {
477 var summary = openils.Util.readResponse(r);
479 dojo.byId('oils-selfck-fines-total').innerHTML =
480 dojo.string.substitute(
481 localeStrings.TOTAL_FINES_ACCOUNT,
482 [summary.balance_owed()]
485 self.creditPayableBalance = summary.balance_owed();
492 SelfCheckManager.prototype.drawItemsOutPage = function() {
493 openils.Util.hide('oils-selfck-circ-tbody');
495 this.goToTab('items_out');
497 while(this.itemsOutTbody.childNodes[0])
498 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
500 progressDialog.show(true);
503 fieldmapper.standardRequest(
504 ['open-ils.circ', 'open-ils.circ.actor.user.checked_out.atomic'],
507 params : [this.authtoken, this.patron.id()],
508 oncomplete : function(r) {
510 var resp = openils.Util.readResponse(r);
512 var circs = resp.sort(
514 if(a.circ.due_date() > b.circ.due_date())
520 progressDialog.hide();
525 self.itemsOut.push(circ.circ.id());
526 self.displayCheckout(
528 (circ.circ.parent_circ()) ? 'renew' : 'checkout',
539 SelfCheckManager.prototype.goToTab = function(name) {
542 openils.Util.hide('oils-selfck-fines-page');
543 openils.Util.hide('oils-selfck-payment-page');
544 openils.Util.hide('oils-selfck-holds-page');
545 openils.Util.hide('oils-selfck-circ-page');
546 openils.Util.hide('oils-selfck-pay-fines-link');
550 openils.Util.show('oils-selfck-circ-page');
553 openils.Util.show('oils-selfck-circ-page');
556 openils.Util.show('oils-selfck-holds-page');
559 openils.Util.show('oils-selfck-fines-page');
562 openils.Util.show('oils-selfck-payment-page');
568 SelfCheckManager.prototype.printList = function() {
569 switch(this.tabName) {
571 this.printSessionReceipt();
574 this.printItemsOutReceipt();
577 this.printHoldsReceipt();
580 this.printFinesReceipt();
585 SelfCheckManager.prototype.updateHoldsSummary = function() {
587 if(!this.holdsSummary) {
588 var summary = fieldmapper.standardRequest(
589 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
590 {params : [this.authtoken, this.patron.id()]}
593 this.holdsSummary = {};
594 this.holdsSummary.ready = Number(summary['4']);
595 this.holdsSummary.total = 0;
597 for(var i in summary)
598 this.holdsSummary.total += Number(summary[i]);
601 dojo.byId('oils-selfck-holds-total').innerHTML =
602 dojo.string.substitute(
603 localeStrings.TOTAL_HOLDS,
604 [this.holdsSummary.total]
607 dojo.byId('oils-selfck-holds-ready').innerHTML =
608 dojo.string.substitute(
609 localeStrings.HOLDS_READY_FOR_PICKUP,
610 [this.holdsSummary.ready]
615 SelfCheckManager.prototype.updateCircSummary = function(increment) {
617 if(!this.circSummary) {
619 var summary = fieldmapper.standardRequest(
620 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
621 {params : [this.authtoken, this.patron.id()]}
625 total : Number(summary.out) + Number(summary.overdue),
626 overdue : Number(summary.overdue),
632 // local checkout occurred. Add to the total and the session.
633 this.circSummary.total += 1;
634 this.circSummary.session += 1;
637 dojo.byId('oils-selfck-circ-account-total').innerHTML =
638 dojo.string.substitute(
639 localeStrings.TOTAL_ITEMS_ACCOUNT,
640 [this.circSummary.total]
643 dojo.byId('oils-selfck-circ-session-total').innerHTML =
644 dojo.string.substitute(
645 localeStrings.TOTAL_ITEMS_SESSION,
646 [this.circSummary.session]
651 SelfCheckManager.prototype.drawHoldsPage = function() {
653 // TODO add option to hid scanBox
654 // this.updateScanBox(...)
656 this.goToTab('holds');
658 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
659 if(!this.holdTemplate)
660 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
661 while(this.holdTbody.childNodes[0])
662 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
664 progressDialog.show(true);
667 fieldmapper.standardRequest( // fetch the hold IDs
669 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
671 params : [this.authtoken, this.patron.id()],
673 oncomplete : function(r) {
674 var ids = openils.Util.readResponse(r);
675 if(!ids || ids.length == 0) {
676 progressDialog.hide();
680 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
681 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve'],
683 params : [self.authtoken, ids],
684 onresponse : function(rr) {
685 progressDialog.hide();
686 self.insertHold(openils.Util.readResponse(rr));
695 SelfCheckManager.prototype.insertHold = function(data) {
696 var row = this.holdTemplate.cloneNode(true);
698 if(data.mvr.isbn()) {
699 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + data.mvr.isbn());
702 this.byName(row, 'title').innerHTML = data.mvr.title();
703 this.byName(row, 'author').innerHTML = data.mvr.author();
705 if(data.status == 4) {
707 // hold is ready for pickup
708 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
712 // hold is still pending
713 this.byName(row, 'status').innerHTML =
714 dojo.string.substitute(
715 localeStrings.HOLD_STATUS_WAITING,
716 [data.queue_position, data.potential_copies]
720 // find the correct place the table to slot in the hold based on queue position
722 var position = (data.status == 4) ? 0 : data.queue_position;
723 row.setAttribute('position', position);
725 for(var i = 0; i < this.holdTbody.childNodes.length; i++) {
726 var node = this.holdTbody.childNodes[i];
727 if(Number(node.getAttribute('position')) >= position) {
728 this.holdTbody.insertBefore(row, node);
733 this.holdTbody.appendChild(row);
737 SelfCheckManager.prototype.drawFinesPage = function() {
739 // TODO add option to hid scanBox
740 // this.updateScanBox(...)
742 this.goToTab('fines');
743 progressDialog.show(true);
745 if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
746 openils.Util.show('oils-selfck-pay-fines-link', 'inline');
749 this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
750 if(!this.finesTemplate)
751 this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
752 while(this.finesTbody.childNodes[0])
753 this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
755 // when user clicks on a selector checkbox, update the total owed
756 var updateSelected = function() {
759 dojo.query('[name=selector]', this.finesTbody),
762 total += Number(input.getAttribute('balance_owed'));
766 total = total.toFixed(2);
767 dojo.byId('oils-selfck-selected-total').innerHTML =
768 dojo.string.substitute(localeStrings.TOTAL_FINES_SELECTED, [total]);
771 // wire up the batch on/off selector
772 var sel = dojo.byId('oils-selfck-fines-selector');
773 sel.onchange = function() {
775 dojo.query('[name=selector]', this.finesTbody),
777 input.checked = sel.checked;
783 var handler = function(dataList) {
785 self.finesCount = dataList.length;
786 self.finesData = dataList;
788 for(var i in dataList) {
790 var data = dataList[i];
791 var row = self.finesTemplate.cloneNode(true);
792 var type = data.transaction.xact_type();
794 if(type == 'circulation') {
795 self.byName(row, 'type').innerHTML = type;
796 self.byName(row, 'details').innerHTML = data.record.title();
798 } else if(type == 'grocery') {
799 self.byName(row, 'type').innerHTML = 'Miscellaneous'; // Go ahead and head off any confusion around "grocery". TODO i18n
800 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
803 self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
804 self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
805 self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
808 var selector = self.byName(row, 'selector')
809 selector.onchange = updateSelected;
810 selector.setAttribute('xact', data.transaction.id());
811 selector.setAttribute('balance_owed', data.transaction.balance_owed());
812 selector.checked = true;
814 self.finesTbody.appendChild(row);
821 fieldmapper.standardRequest(
822 ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
824 params : [this.authtoken, this.patron.id()],
825 oncomplete : function(r) {
826 progressDialog.hide();
827 handler(openils.Util.readResponse(r));
833 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
835 var resp = fieldmapper.standardRequest(
836 ['open-ils.circ', 'open-ils.circ.transit.abort'],
837 {params : [this.authtoken, {barcode : barcode}]}
840 // resp == 1 on success
841 if(openils.Event.parse(resp))
844 var resp = fieldmapper.standardRequest(
845 ['open-ils.circ', 'open-ils.circ.checkin.override'],
848 patron_id : this.patron.id(),
849 copy_barcode : barcode,
855 if(!resp.length) resp = [resp];
856 for(var i = 0; i < resp.length; i++) {
857 var tc = openils.Event.parse(resp[i]).textcode;
858 if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
869 * Check out a single item. If the item is already checked
870 * out to the patron, redirect to renew()
872 SelfCheckManager.prototype.checkout = function(barcode, override) {
874 this.prevCirc = null;
877 this.updateScanbox(null, true);
881 if(this.mockCheckouts) {
882 // if we're in mock-checkout mode, just insert another
883 // fake circ into the table and get out of here.
884 this.displayCheckout(this.mockCheckout, 'checkout');
888 // TODO see if it's a patron barcode
889 // TODO see if this item has already been checked out in this session
891 var method = 'open-ils.circ.checkout.full';
892 if(override) method += '.override';
894 console.log("Checkout out item " + barcode + " with method " + method);
896 var result = fieldmapper.standardRequest(
897 ['open-ils.circ', method],
900 patron_id : this.patron.id(),
901 copy_barcode : barcode
906 var stat = this.handleXactResult('checkout', barcode, result);
909 this.checkout(barcode, true);
910 } else if(stat.doOver) {
911 this.checkout(barcode);
912 } else if(stat.renew) {
917 SelfCheckManager.prototype.failPartMessage = function(result) {
918 if (result.payload && result.payload.fail_part) {
919 var stringKey = "FAIL_PART_" +
920 result.payload.fail_part.replace(/\./g, "_");
921 return localeStrings[stringKey];
927 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
929 var displayText = '';
931 // If true, the display message is important enough to pop up. Whether or not
932 // an alert() actually occurs, depends on org unit settings
934 var sound = ''; // sound file reference
935 var payload = result.payload || {};
936 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
937 var blockStatuses = this.orgSettings[SET_BLOCK_CHECKOUT_ON_COPY_STATUS];
939 if(result.textcode == 'NO_SESSION') {
941 return this.logoutStaff();
943 } else if(result.textcode == 'SUCCESS') {
945 if(action == 'checkout') {
947 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
948 this.displayCheckout(result, 'checkout');
950 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
951 // A hold was fulfilled, update the hold numbers in the circ summary
952 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
953 this.holdsSummary = null;
954 this.updateHoldsSummary();
957 this.updateCircSummary(true);
959 } else if(action == 'renew') {
961 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
962 this.displayCheckout(result, 'renew');
965 this.checkouts.push({circ : result.payload.circ.id()});
966 sound = 'checkout-success';
967 this.updateScanBox();
969 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
971 // Server says the item is already checked out. If it's checked out to the
972 // current user, we may need to renew it.
974 if(payload.old_circ) {
977 old_circ refers to the previous checkout IFF it's for the same user.
978 If no auto-renew interval is not defined, assume we should renew it
979 If an auto-renew interval is defined and the payload comes back with
980 auto_renew set to true, do the renewal. Otherwise, let the patron know
981 the item is already checked out to them. */
983 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
984 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
985 this.prevCirc = payload.old_circ.id();
986 return { renew : true };
990 sound = 'checkout-failure';
991 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
995 if( // copy is marked lost. if configured to do so, check it in and try again.
996 result.payload.copy &&
997 result.payload.copy.status() == /* LOST */ 3 &&
998 overrideEvents && overrideEvents.length &&
999 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
1001 if(this.checkin(item)) {
1002 return { doOver : true };
1007 // item is checked out to some other user
1009 sound = 'checkout-failure';
1010 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1013 this.updateScanBox({select:true});
1018 if(overrideEvents && overrideEvents.length) {
1020 // see if the events we received are all in the list of
1021 // events to override
1023 if(!result.length) result = [result];
1025 var override = true;
1026 for(var i = 0; i < result.length; i++) {
1028 var match = overrideEvents.filter(function(e) { return (e == result[i].textcode); })[0];
1035 if(result[i].textcode == 'COPY_NOT_AVAILABLE' && blockStatuses && blockStatuses.length) {
1037 var stat = result[i].payload.status(); // copy status
1038 if(typeof stat == 'object') stat = stat.id();
1040 var match2 = blockStatuses.filter(function(e) { return (e == stat); })[0];
1042 if(match2) { // copy is in a blocked status
1048 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1049 // to override a transit, we have to abort the transit and check it in first
1050 if(this.checkin(item, true)) {
1051 return { doOver : true };
1059 return { override : true };
1062 this.updateScanBox({select : true});
1064 sound = 'checkout-failure';
1066 if(action == 'renew')
1067 this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1072 switch(result.textcode) {
1074 // TODO custom handler for blocking penalties
1076 case 'MAX_RENEWALS_REACHED' :
1077 displayText = dojo.string.substitute(
1078 localeStrings.MAX_RENEWALS, [item]);
1081 case 'ITEM_NOT_CATALOGED' :
1082 displayText = dojo.string.substitute(
1083 localeStrings.ITEM_NOT_CATALOGED, [item]);
1086 case 'OPEN_CIRCULATION_EXISTS' :
1087 displayText = dojo.string.substitute(
1088 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1093 console.error('Unhandled event ' + result.textcode);
1095 if (!(displayText = this.failPartMessage(result))) {
1096 if (action == 'checkout' || action == 'renew') {
1097 displayText = dojo.string.substitute(
1098 localeStrings.GENERIC_CIRC_FAILURE, [item]);
1100 displayText = dojo.string.substitute(
1101 localeStrings.UNKNOWN_ERROR, [result.textcode]);
1107 this.handleAlert(displayText, popup, sound);
1115 SelfCheckManager.prototype.renew = function(barcode, override) {
1117 var method = 'open-ils.circ.renew';
1118 if(override) method += '.override';
1120 console.log("Renewing item " + barcode + " with method " + method);
1122 var result = fieldmapper.standardRequest(
1123 ['open-ils.circ', method],
1126 patron_id : this.patron.id(),
1127 copy_barcode : barcode
1132 console.log(js2JSON(result));
1134 var stat = this.handleXactResult('renew', barcode, result);
1137 this.renew(barcode, true);
1141 * Display the result of a checkout or renewal in the items out table
1143 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1145 var copy = evt.payload.copy;
1146 var record = evt.payload.record;
1147 var circ = evt.payload.circ;
1148 var row = this.circTemplate.cloneNode(true);
1151 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + record.isbn());
1154 this.byName(row, 'barcode').innerHTML = copy.barcode();
1155 this.byName(row, 'title').innerHTML = record.title();
1156 this.byName(row, 'author').innerHTML = record.author();
1157 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1158 openils.Util.show(this.byName(row, type));
1160 var date = dojo.date.stamp.fromISOString(circ.due_date());
1161 this.byName(row, 'due_date').innerHTML =
1162 dojo.date.locale.format(date, {selector : 'date'});
1164 // put new circs at the top of the list
1165 var tbody = this.circTbody;
1166 if(itemsOut) tbody = this.itemsOutTbody;
1167 tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1171 SelfCheckManager.prototype.byName = function(node, name) {
1172 return dojo.query('[name=' + name+']', node)[0];
1176 SelfCheckManager.prototype.initPrinter = function() {
1177 try { // Mozilla only
1178 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1179 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1180 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1181 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1182 var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1184 pref.setBoolPref('print.always_print_silent', true);
1186 console.log("Unable to initialize auto-printing");
1191 * Print a receipt for this session's checkouts
1193 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1196 var circCtx = []; // circ context data. in this case, renewal_failure info
1198 // collect the circs and failure info
1202 circIds.push(blob.circ);
1203 circCtx.push({renewal_failure:blob.renewal_failure});
1211 'format.selfcheck.checkout',
1218 fieldmapper.standardRequest(
1219 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1223 oncomplete : function(r) {
1224 var resp = openils.Util.readResponse(r);
1225 var output = resp.template_output();
1227 self.printData(output.data(), self.checkouts.length, callback);
1229 var error = resp.error_output();
1231 throw new Error("Error creating receipt: " + error.data());
1233 throw new Error("No receipt data returned from server");
1241 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1243 var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1');
1244 win.document.body.innerHTML = data;
1248 * There is no way to know when the browser is done printing.
1249 * Make a best guess at when to close the print window by basing
1250 * the setTimeout wait on the number of items to be printed plus
1253 var sleepTime = 1000;
1255 sleepTime += (numItems / 2) * 1000;
1259 win.close(); // close the print window
1261 callback(); // fire optional post-print callback
1269 * Print a receipt for this user's items out
1271 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1273 if(!this.itemsOut.length) return;
1275 progressDialog.show(true);
1281 'format.selfcheck.items_out',
1287 fieldmapper.standardRequest(
1288 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1292 oncomplete : function(r) {
1293 progressDialog.hide();
1294 var resp = openils.Util.readResponse(r);
1295 var output = resp.template_output();
1297 self.printData(output.data(), self.itemsOut.length, callback);
1299 var error = resp.error_output();
1301 throw new Error("Error creating receipt: " + error.data());
1303 throw new Error("No receipt data returned from server");
1312 * Print a receipt for this user's items out
1314 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1316 if(!this.holds.length) return;
1318 progressDialog.show(true);
1323 dojo.forEach(this.holds,
1325 holdIds.push(data.hold.id());
1326 if(data.status == 4) {
1327 holdData.push({ready : true});
1330 queue_position : data.queue_position,
1331 potential_copies : data.potential_copies
1341 'format.selfcheck.holds',
1348 fieldmapper.standardRequest(
1349 ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1353 oncomplete : function(r) {
1354 progressDialog.hide();
1355 var resp = openils.Util.readResponse(r);
1356 var output = resp.template_output();
1358 self.printData(output.data(), self.holds.length, callback);
1360 var error = resp.error_output();
1362 throw new Error("Error creating receipt: " + error.data());
1364 throw new Error("No receipt data returned from server");
1373 SelfCheckManager.prototype.printPaymentReceipt = function(response, callback) {
1376 progressDialog.show(true);
1378 fieldmapper.standardRequest(
1379 ['open-ils.circ', 'open-ils.circ.money.payment_receipt.print'],
1382 params : [this.authtoken, response.payments],
1383 oncomplete : function(r) {
1384 var resp = openils.Util.readResponse(r);
1385 var output = resp.template_output();
1386 progressDialog.hide();
1388 self.printData(output.data(), 1, callback);
1390 var error = resp.error_output();
1392 throw new Error("Error creating receipt: " + error.data());
1394 throw new Error("No receipt data returned from server");
1403 * Print a receipt for this user's items out
1405 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1407 progressDialog.show(true);
1413 'format.selfcheck.fines',
1419 fieldmapper.standardRequest(
1420 ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1424 oncomplete : function(r) {
1425 progressDialog.hide();
1426 var resp = openils.Util.readResponse(r);
1427 var output = resp.template_output();
1429 self.printData(output.data(), self.finesCount, callback);
1431 var error = resp.error_output();
1433 throw new Error("Error creating receipt: " + error.data());
1435 throw new Error("No receipt data returned from server");
1447 * Logout the patron and return to the login page
1449 SelfCheckManager.prototype.logoutPatron = function(print) {
1450 if(print && this.checkouts.length) {
1451 this.printSessionReceipt(
1453 location.href = location.href;
1457 location.href = location.href;
1463 * Fire up the manager on page load
1465 openils.Util.addOnLoad(
1467 new SelfCheckManager().init();