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.atomic'],
683 params : [self.authtoken, ids],
685 oncomplete : function(rr) {
686 self.drawHolds(openils.Util.readResponse(rr));
696 * Fetch and add a single hold to the list of holds
698 SelfCheckManager.prototype.drawHolds = function(holds) {
701 // sort available holds to the top of the list
702 // followed by queue position order
704 if(a.status == 4) return -1;
705 if(a.queue_position < b.queue_position) return -1;
712 progressDialog.hide();
714 for(var i in holds) {
717 var row = this.holdTemplate.cloneNode(true);
719 if(data.mvr.isbn()) {
720 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + data.mvr.isbn());
723 this.byName(row, 'title').innerHTML = data.mvr.title();
724 this.byName(row, 'author').innerHTML = data.mvr.author();
726 if(data.status == 4) {
728 // hold is ready for pickup
729 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
733 // hold is still pending
734 this.byName(row, 'status').innerHTML =
735 dojo.string.substitute(
736 localeStrings.HOLD_STATUS_WAITING,
737 [data.queue_position, data.potential_copies]
741 this.holdTbody.appendChild(row);
746 SelfCheckManager.prototype.drawFinesPage = function() {
748 // TODO add option to hid scanBox
749 // this.updateScanBox(...)
751 this.goToTab('fines');
752 progressDialog.show(true);
754 if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
755 openils.Util.show('oils-selfck-pay-fines-link', 'inline');
758 this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
759 if(!this.finesTemplate)
760 this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
761 while(this.finesTbody.childNodes[0])
762 this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
764 // when user clicks on a selector checkbox, update the total owed
765 var updateSelected = function() {
768 dojo.query('[name=selector]', this.finesTbody),
771 total += Number(input.getAttribute('balance_owed'));
775 total = total.toFixed(2);
776 dojo.byId('oils-selfck-selected-total').innerHTML =
777 dojo.string.substitute(localeStrings.TOTAL_FINES_SELECTED, [total]);
780 // wire up the batch on/off selector
781 var sel = dojo.byId('oils-selfck-fines-selector');
782 sel.onchange = function() {
784 dojo.query('[name=selector]', this.finesTbody),
786 input.checked = sel.checked;
792 var handler = function(dataList) {
794 self.finesCount = dataList.length;
795 self.finesData = dataList;
797 for(var i in dataList) {
799 var data = dataList[i];
800 var row = self.finesTemplate.cloneNode(true);
801 var type = data.transaction.xact_type();
803 if(type == 'circulation') {
804 self.byName(row, 'type').innerHTML = type;
805 self.byName(row, 'details').innerHTML = data.record.title();
807 } else if(type == 'grocery') {
808 self.byName(row, 'type').innerHTML = 'Miscellaneous'; // Go ahead and head off any confusion around "grocery". TODO i18n
809 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
812 self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
813 self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
814 self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
817 var selector = self.byName(row, 'selector')
818 selector.onchange = updateSelected;
819 selector.setAttribute('xact', data.transaction.id());
820 selector.setAttribute('balance_owed', data.transaction.balance_owed());
821 selector.checked = true;
823 self.finesTbody.appendChild(row);
830 fieldmapper.standardRequest(
831 ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
833 params : [this.authtoken, this.patron.id()],
834 oncomplete : function(r) {
835 progressDialog.hide();
836 handler(openils.Util.readResponse(r));
842 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
844 var resp = fieldmapper.standardRequest(
845 ['open-ils.circ', 'open-ils.circ.transit.abort'],
846 {params : [this.authtoken, {barcode : barcode}]}
849 // resp == 1 on success
850 if(openils.Event.parse(resp))
853 var resp = fieldmapper.standardRequest(
854 ['open-ils.circ', 'open-ils.circ.checkin.override'],
857 patron_id : this.patron.id(),
858 copy_barcode : barcode,
864 if(!resp.length) resp = [resp];
865 for(var i = 0; i < resp.length; i++) {
866 var tc = openils.Event.parse(resp[i]).textcode;
867 if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
878 * Check out a single item. If the item is already checked
879 * out to the patron, redirect to renew()
881 SelfCheckManager.prototype.checkout = function(barcode, override) {
883 this.prevCirc = null;
886 this.updateScanbox(null, true);
890 if(this.mockCheckouts) {
891 // if we're in mock-checkout mode, just insert another
892 // fake circ into the table and get out of here.
893 this.displayCheckout(this.mockCheckout, 'checkout');
897 // TODO see if it's a patron barcode
898 // TODO see if this item has already been checked out in this session
900 var method = 'open-ils.circ.checkout.full';
901 if(override) method += '.override';
903 console.log("Checkout out item " + barcode + " with method " + method);
905 var result = fieldmapper.standardRequest(
906 ['open-ils.circ', method],
909 patron_id : this.patron.id(),
910 copy_barcode : barcode
915 var stat = this.handleXactResult('checkout', barcode, result);
918 this.checkout(barcode, true);
919 } else if(stat.doOver) {
920 this.checkout(barcode);
921 } else if(stat.renew) {
926 SelfCheckManager.prototype.failPartMessage = function(result) {
927 if (result.payload && result.payload.fail_part) {
928 var stringKey = "FAIL_PART_" +
929 result.payload.fail_part.replace(/\./g, "_");
930 return localeStrings[stringKey];
936 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
938 var displayText = '';
940 // If true, the display message is important enough to pop up. Whether or not
941 // an alert() actually occurs, depends on org unit settings
943 var sound = ''; // sound file reference
944 var payload = result.payload || {};
945 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
946 var blockStatuses = this.orgSettings[SET_BLOCK_CHECKOUT_ON_COPY_STATUS];
948 if(result.textcode == 'NO_SESSION') {
950 return this.logoutStaff();
952 } else if(result.textcode == 'SUCCESS') {
954 if(action == 'checkout') {
956 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
957 this.displayCheckout(result, 'checkout');
959 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
960 // A hold was fulfilled, update the hold numbers in the circ summary
961 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
962 this.holdsSummary = null;
963 this.updateHoldsSummary();
966 this.updateCircSummary(true);
968 } else if(action == 'renew') {
970 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
971 this.displayCheckout(result, 'renew');
974 this.checkouts.push({circ : result.payload.circ.id()});
975 sound = 'checkout-success';
976 this.updateScanBox();
978 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
980 // Server says the item is already checked out. If it's checked out to the
981 // current user, we may need to renew it.
983 if(payload.old_circ) {
986 old_circ refers to the previous checkout IFF it's for the same user.
987 If no auto-renew interval is not defined, assume we should renew it
988 If an auto-renew interval is defined and the payload comes back with
989 auto_renew set to true, do the renewal. Otherwise, let the patron know
990 the item is already checked out to them. */
992 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
993 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
994 this.prevCirc = payload.old_circ.id();
995 return { renew : true };
999 sound = 'checkout-failure';
1000 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
1004 if( // copy is marked lost. if configured to do so, check it in and try again.
1005 result.payload.copy &&
1006 result.payload.copy.status() == /* LOST */ 3 &&
1007 overrideEvents && overrideEvents.length &&
1008 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
1010 if(this.checkin(item)) {
1011 return { doOver : true };
1016 // item is checked out to some other user
1018 sound = 'checkout-failure';
1019 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1022 this.updateScanBox({select:true});
1027 if(overrideEvents && overrideEvents.length) {
1029 // see if the events we received are all in the list of
1030 // events to override
1032 if(!result.length) result = [result];
1034 var override = true;
1035 for(var i = 0; i < result.length; i++) {
1037 var match = overrideEvents.filter(function(e) { return (e == result[i].textcode); })[0];
1044 if(result[i].textcode == 'COPY_NOT_AVAILABLE' && blockStatuses && blockStatuses.length) {
1046 var stat = result[i].payload.status(); // copy status
1047 if(typeof stat == 'object') stat = stat.id();
1049 var match2 = blockStatuses.filter(function(e) { return (e == stat); })[0];
1051 if(match2) { // copy is in a blocked status
1057 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1058 // to override a transit, we have to abort the transit and check it in first
1059 if(this.checkin(item, true)) {
1060 return { doOver : true };
1068 return { override : true };
1071 this.updateScanBox({select : true});
1073 sound = 'checkout-failure';
1075 if(action == 'renew')
1076 this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1081 switch(result.textcode) {
1083 // TODO custom handler for blocking penalties
1085 case 'MAX_RENEWALS_REACHED' :
1086 displayText = dojo.string.substitute(
1087 localeStrings.MAX_RENEWALS, [item]);
1090 case 'ITEM_NOT_CATALOGED' :
1091 displayText = dojo.string.substitute(
1092 localeStrings.ITEM_NOT_CATALOGED, [item]);
1095 case 'OPEN_CIRCULATION_EXISTS' :
1096 displayText = dojo.string.substitute(
1097 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1102 console.error('Unhandled event ' + result.textcode);
1104 if (!(displayText = this.failPartMessage(result))) {
1105 if (action == 'checkout' || action == 'renew') {
1106 displayText = dojo.string.substitute(
1107 localeStrings.GENERIC_CIRC_FAILURE, [item]);
1109 displayText = dojo.string.substitute(
1110 localeStrings.UNKNOWN_ERROR, [result.textcode]);
1116 this.handleAlert(displayText, popup, sound);
1124 SelfCheckManager.prototype.renew = function(barcode, override) {
1126 var method = 'open-ils.circ.renew';
1127 if(override) method += '.override';
1129 console.log("Renewing item " + barcode + " with method " + method);
1131 var result = fieldmapper.standardRequest(
1132 ['open-ils.circ', method],
1135 patron_id : this.patron.id(),
1136 copy_barcode : barcode
1141 console.log(js2JSON(result));
1143 var stat = this.handleXactResult('renew', barcode, result);
1146 this.renew(barcode, true);
1150 * Display the result of a checkout or renewal in the items out table
1152 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1154 var copy = evt.payload.copy;
1155 var record = evt.payload.record;
1156 var circ = evt.payload.circ;
1157 var row = this.circTemplate.cloneNode(true);
1160 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + record.isbn());
1163 this.byName(row, 'barcode').innerHTML = copy.barcode();
1164 this.byName(row, 'title').innerHTML = record.title();
1165 this.byName(row, 'author').innerHTML = record.author();
1166 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1167 openils.Util.show(this.byName(row, type));
1169 var date = dojo.date.stamp.fromISOString(circ.due_date());
1170 this.byName(row, 'due_date').innerHTML =
1171 dojo.date.locale.format(date, {selector : 'date'});
1173 // put new circs at the top of the list
1174 var tbody = this.circTbody;
1175 if(itemsOut) tbody = this.itemsOutTbody;
1176 tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1180 SelfCheckManager.prototype.byName = function(node, name) {
1181 return dojo.query('[name=' + name+']', node)[0];
1185 SelfCheckManager.prototype.initPrinter = function() {
1186 try { // Mozilla only
1187 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1188 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1189 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1190 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1191 var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1193 pref.setBoolPref('print.always_print_silent', true);
1195 console.log("Unable to initialize auto-printing");
1200 * Print a receipt for this session's checkouts
1202 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1205 var circCtx = []; // circ context data. in this case, renewal_failure info
1207 // collect the circs and failure info
1211 circIds.push(blob.circ);
1212 circCtx.push({renewal_failure:blob.renewal_failure});
1220 'format.selfcheck.checkout',
1227 fieldmapper.standardRequest(
1228 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1232 oncomplete : function(r) {
1233 var resp = openils.Util.readResponse(r);
1234 var output = resp.template_output();
1236 self.printData(output.data(), self.checkouts.length, callback);
1238 var error = resp.error_output();
1240 throw new Error("Error creating receipt: " + error.data());
1242 throw new Error("No receipt data returned from server");
1250 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1252 var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1');
1253 win.document.body.innerHTML = data;
1257 * There is no way to know when the browser is done printing.
1258 * Make a best guess at when to close the print window by basing
1259 * the setTimeout wait on the number of items to be printed plus
1262 var sleepTime = 1000;
1264 sleepTime += (numItems / 2) * 1000;
1268 win.close(); // close the print window
1270 callback(); // fire optional post-print callback
1278 * Print a receipt for this user's items out
1280 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1282 if(!this.itemsOut.length) return;
1284 progressDialog.show(true);
1290 'format.selfcheck.items_out',
1296 fieldmapper.standardRequest(
1297 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1301 oncomplete : function(r) {
1302 progressDialog.hide();
1303 var resp = openils.Util.readResponse(r);
1304 var output = resp.template_output();
1306 self.printData(output.data(), self.itemsOut.length, callback);
1308 var error = resp.error_output();
1310 throw new Error("Error creating receipt: " + error.data());
1312 throw new Error("No receipt data returned from server");
1321 * Print a receipt for this user's items out
1323 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1325 if(!this.holds.length) return;
1327 progressDialog.show(true);
1332 dojo.forEach(this.holds,
1334 holdIds.push(data.hold.id());
1335 if(data.status == 4) {
1336 holdData.push({ready : true});
1339 queue_position : data.queue_position,
1340 potential_copies : data.potential_copies
1350 'format.selfcheck.holds',
1357 fieldmapper.standardRequest(
1358 ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1362 oncomplete : function(r) {
1363 progressDialog.hide();
1364 var resp = openils.Util.readResponse(r);
1365 var output = resp.template_output();
1367 self.printData(output.data(), self.holds.length, callback);
1369 var error = resp.error_output();
1371 throw new Error("Error creating receipt: " + error.data());
1373 throw new Error("No receipt data returned from server");
1382 SelfCheckManager.prototype.printPaymentReceipt = function(response, callback) {
1385 progressDialog.show(true);
1387 fieldmapper.standardRequest(
1388 ['open-ils.circ', 'open-ils.circ.money.payment_receipt.print'],
1391 params : [this.authtoken, response.payments],
1392 oncomplete : function(r) {
1393 var resp = openils.Util.readResponse(r);
1394 var output = resp.template_output();
1395 progressDialog.hide();
1397 self.printData(output.data(), 1, 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 * Print a receipt for this user's items out
1414 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1416 progressDialog.show(true);
1422 'format.selfcheck.fines',
1428 fieldmapper.standardRequest(
1429 ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1433 oncomplete : function(r) {
1434 progressDialog.hide();
1435 var resp = openils.Util.readResponse(r);
1436 var output = resp.template_output();
1438 self.printData(output.data(), self.finesCount, callback);
1440 var error = resp.error_output();
1442 throw new Error("Error creating receipt: " + error.data());
1444 throw new Error("No receipt data returned from server");
1456 * Logout the patron and return to the login page
1458 SelfCheckManager.prototype.logoutPatron = function(print) {
1459 if(print && this.checkouts.length) {
1460 this.printSessionReceipt(
1462 location.href = location.href;
1466 location.href = location.href;
1472 * Fire up the manager on page load
1474 openils.Util.addOnLoad(
1476 new SelfCheckManager().init();