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;
377 openils.Util.addCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
379 openils.Util.removeCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
381 if(shouldPopup && this.orgSettings[SET_ALERT_POPUP])
384 if(sound && this.orgSettings[SET_ALERT_SOUND])
385 openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
390 * Manages the main input box
391 * @param msg The context message to display with the box
392 * @param clearOnly Don't update the context message, just clear the value and re-focus
393 * @param handler Optional "on-enter" handler.
395 SelfCheckManager.prototype.updateScanBox = function(args) {
399 selfckScanBox.domNode.select();
401 selfckScanBox.attr('value', '');
405 selfckScanBox.domNode.setAttribute('type', 'password');
407 selfckScanBox.domNode.setAttribute('type', '');
411 selfckScanBox.attr('value', args.value);
414 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
416 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
417 dojo.disconnect(selfckScanBox._lastHandler);
421 selfckScanBox._lastHandler = dojo.connect(
425 if(e.keyCode != dojo.keys.ENTER)
427 args.handler(selfckScanBox.attr('value'));
432 selfckScanBox.focus();
436 * Sets up the checkout/renewal interface
438 SelfCheckManager.prototype.drawCircPage = function() {
440 openils.Util.show('oils-selfck-circ-tbody', 'table-row-group');
441 this.goToTab('checkout');
443 while(this.itemsOutTbody.childNodes[0])
444 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
448 msg : 'Please enter an item barcode', // TODO i18n
449 handler : function(barcode) { self.checkout(barcode); }
452 if(!this.circTemplate)
453 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
456 this.updateFinesSummary();
459 this.updateHoldsSummary();
462 this.updateCircSummary();
464 // render mock checkouts for debugging?
465 if(this.mockCheckouts) {
466 for(var i in [1,2,3])
467 this.displayCheckout(this.mockCheckout, 'checkout');
472 SelfCheckManager.prototype.updateFinesSummary = function() {
476 fieldmapper.standardRequest(
477 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
479 params : [this.authtoken, this.patron.id()],
480 oncomplete : function(r) {
482 var summary = openils.Util.readResponse(r);
484 dojo.byId('oils-selfck-fines-total').innerHTML =
485 dojo.string.substitute(
486 localeStrings.TOTAL_FINES_ACCOUNT,
487 [summary.balance_owed()]
490 self.creditPayableBalance = summary.balance_owed();
497 SelfCheckManager.prototype.drawItemsOutPage = function() {
498 openils.Util.hide('oils-selfck-circ-tbody');
500 this.goToTab('items_out');
502 while(this.itemsOutTbody.childNodes[0])
503 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
505 progressDialog.show(true);
508 fieldmapper.standardRequest(
509 ['open-ils.circ', 'open-ils.circ.actor.user.checked_out.atomic'],
512 params : [this.authtoken, this.patron.id()],
513 oncomplete : function(r) {
515 var resp = openils.Util.readResponse(r);
517 var circs = resp.sort(
519 if(a.circ.due_date() > b.circ.due_date())
525 progressDialog.hide();
530 self.itemsOut.push(circ.circ.id());
531 self.displayCheckout(
533 (circ.circ.parent_circ()) ? 'renew' : 'checkout',
544 SelfCheckManager.prototype.goToTab = function(name) {
547 openils.Util.hide('oils-selfck-fines-page');
548 openils.Util.hide('oils-selfck-payment-page');
549 openils.Util.hide('oils-selfck-holds-page');
550 openils.Util.hide('oils-selfck-circ-page');
551 openils.Util.hide('oils-selfck-pay-fines-link');
555 openils.Util.show('oils-selfck-circ-page');
558 openils.Util.show('oils-selfck-circ-page');
561 openils.Util.show('oils-selfck-holds-page');
564 openils.Util.show('oils-selfck-fines-page');
567 openils.Util.show('oils-selfck-payment-page');
573 SelfCheckManager.prototype.printList = function() {
574 switch(this.tabName) {
576 this.printSessionReceipt();
579 this.printItemsOutReceipt();
582 this.printHoldsReceipt();
585 this.printFinesReceipt();
590 SelfCheckManager.prototype.updateHoldsSummary = function() {
592 if(!this.holdsSummary) {
593 var summary = fieldmapper.standardRequest(
594 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
595 {params : [this.authtoken, this.patron.id()]}
598 this.holdsSummary = {};
599 this.holdsSummary.ready = Number(summary['4']);
600 this.holdsSummary.total = 0;
602 for(var i in summary)
603 this.holdsSummary.total += Number(summary[i]);
606 dojo.byId('oils-selfck-holds-total').innerHTML =
607 dojo.string.substitute(
608 localeStrings.TOTAL_HOLDS,
609 [this.holdsSummary.total]
612 dojo.byId('oils-selfck-holds-ready').innerHTML =
613 dojo.string.substitute(
614 localeStrings.HOLDS_READY_FOR_PICKUP,
615 [this.holdsSummary.ready]
620 SelfCheckManager.prototype.updateCircSummary = function(increment) {
622 if(!this.circSummary) {
624 var summary = fieldmapper.standardRequest(
625 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
626 {params : [this.authtoken, this.patron.id()]}
630 total : Number(summary.out) + Number(summary.overdue),
631 overdue : Number(summary.overdue),
637 // local checkout occurred. Add to the total and the session.
638 this.circSummary.total += 1;
639 this.circSummary.session += 1;
642 dojo.byId('oils-selfck-circ-account-total').innerHTML =
643 dojo.string.substitute(
644 localeStrings.TOTAL_ITEMS_ACCOUNT,
645 [this.circSummary.total]
648 dojo.byId('oils-selfck-circ-session-total').innerHTML =
649 dojo.string.substitute(
650 localeStrings.TOTAL_ITEMS_SESSION,
651 [this.circSummary.session]
656 SelfCheckManager.prototype.drawHoldsPage = function() {
658 // TODO add option to hid scanBox
659 // this.updateScanBox(...)
661 this.goToTab('holds');
663 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
664 if(!this.holdTemplate)
665 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
666 while(this.holdTbody.childNodes[0])
667 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
669 progressDialog.show(true);
672 fieldmapper.standardRequest( // fetch the hold IDs
674 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
676 params : [this.authtoken, this.patron.id()],
678 oncomplete : function(r) {
679 var ids = openils.Util.readResponse(r);
680 if(!ids || ids.length == 0) {
681 progressDialog.hide();
685 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
686 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve'],
688 params : [self.authtoken, ids],
689 onresponse : function(rr) {
690 progressDialog.hide();
691 self.insertHold(openils.Util.readResponse(rr));
700 SelfCheckManager.prototype.insertHold = function(data) {
701 var row = this.holdTemplate.cloneNode(true);
703 if(data.mvr.isbn()) {
704 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + data.mvr.isbn());
707 this.byName(row, 'title').innerHTML = data.mvr.title();
708 this.byName(row, 'author').innerHTML = data.mvr.author();
710 if(data.status == 4) {
712 // hold is ready for pickup
713 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
717 // hold is still pending
718 this.byName(row, 'status').innerHTML =
719 dojo.string.substitute(
720 localeStrings.HOLD_STATUS_WAITING,
721 [data.queue_position, data.potential_copies]
725 // find the correct place the table to slot in the hold based on queue position
727 var position = (data.status == 4) ? 0 : data.queue_position;
728 row.setAttribute('position', position);
730 for(var i = 0; i < this.holdTbody.childNodes.length; i++) {
731 var node = this.holdTbody.childNodes[i];
732 if(Number(node.getAttribute('position')) >= position) {
733 this.holdTbody.insertBefore(row, node);
738 this.holdTbody.appendChild(row);
742 SelfCheckManager.prototype.drawFinesPage = function() {
744 // TODO add option to hid scanBox
745 // this.updateScanBox(...)
747 this.goToTab('fines');
748 progressDialog.show(true);
750 if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
751 openils.Util.show('oils-selfck-pay-fines-link', 'inline');
754 this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
755 if(!this.finesTemplate)
756 this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
757 while(this.finesTbody.childNodes[0])
758 this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
760 // when user clicks on a selector checkbox, update the total owed
761 var updateSelected = function() {
764 dojo.query('[name=selector]', this.finesTbody),
767 total += Number(input.getAttribute('balance_owed'));
771 total = total.toFixed(2);
772 dojo.byId('oils-selfck-selected-total').innerHTML =
773 dojo.string.substitute(localeStrings.TOTAL_FINES_SELECTED, [total]);
776 // wire up the batch on/off selector
777 var sel = dojo.byId('oils-selfck-fines-selector');
778 sel.onchange = function() {
780 dojo.query('[name=selector]', this.finesTbody),
782 input.checked = sel.checked;
788 var handler = function(dataList) {
790 self.finesCount = dataList.length;
791 self.finesData = dataList;
793 for(var i in dataList) {
795 var data = dataList[i];
796 var row = self.finesTemplate.cloneNode(true);
797 var type = data.transaction.xact_type();
799 if(type == 'circulation') {
800 self.byName(row, 'type').innerHTML = type;
801 self.byName(row, 'details').innerHTML = data.record.title();
803 } else if(type == 'grocery') {
804 self.byName(row, 'type').innerHTML = 'Miscellaneous'; // Go ahead and head off any confusion around "grocery". TODO i18n
805 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
808 self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
809 self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
810 self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
813 var selector = self.byName(row, 'selector')
814 selector.onchange = updateSelected;
815 selector.setAttribute('xact', data.transaction.id());
816 selector.setAttribute('balance_owed', data.transaction.balance_owed());
817 selector.checked = true;
819 self.finesTbody.appendChild(row);
826 fieldmapper.standardRequest(
827 ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
829 params : [this.authtoken, this.patron.id()],
830 oncomplete : function(r) {
831 progressDialog.hide();
832 handler(openils.Util.readResponse(r));
838 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
840 var resp = fieldmapper.standardRequest(
841 ['open-ils.circ', 'open-ils.circ.transit.abort'],
842 {params : [this.authtoken, {barcode : barcode}]}
845 // resp == 1 on success
846 if(openils.Event.parse(resp))
849 var resp = fieldmapper.standardRequest(
850 ['open-ils.circ', 'open-ils.circ.checkin.override'],
853 patron_id : this.patron.id(),
854 copy_barcode : barcode,
860 if(!resp.length) resp = [resp];
861 for(var i = 0; i < resp.length; i++) {
862 var tc = openils.Event.parse(resp[i]).textcode;
863 if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
874 * Check out a single item. If the item is already checked
875 * out to the patron, redirect to renew()
877 SelfCheckManager.prototype.checkout = function(barcode, override) {
879 this.prevCirc = null;
882 this.updateScanbox(null, true);
886 if(this.mockCheckouts) {
887 // if we're in mock-checkout mode, just insert another
888 // fake circ into the table and get out of here.
889 this.displayCheckout(this.mockCheckout, 'checkout');
893 // TODO see if it's a patron barcode
894 // TODO see if this item has already been checked out in this session
896 var method = 'open-ils.circ.checkout.full';
897 if(override) method += '.override';
899 console.log("Checkout out item " + barcode + " with method " + method);
901 var result = fieldmapper.standardRequest(
902 ['open-ils.circ', method],
905 patron_id : this.patron.id(),
906 copy_barcode : barcode
911 var stat = this.handleXactResult('checkout', barcode, result);
914 this.checkout(barcode, true);
915 } else if(stat.doOver) {
916 this.checkout(barcode);
917 } else if(stat.renew) {
922 SelfCheckManager.prototype.failPartMessage = function(result) {
923 if (result.payload && result.payload.fail_part) {
924 var stringKey = "FAIL_PART_" +
925 result.payload.fail_part.replace(/\./g, "_");
926 return localeStrings[stringKey];
932 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
934 var displayText = '';
936 // If true, the display message is important enough to pop up. Whether or not
937 // an alert() actually occurs, depends on org unit settings
939 var sound = ''; // sound file reference
940 var payload = result.payload || {};
941 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
942 var blockStatuses = this.orgSettings[SET_BLOCK_CHECKOUT_ON_COPY_STATUS];
944 if(result.textcode == 'NO_SESSION') {
946 return this.logoutStaff();
948 } else if(result.textcode == 'SUCCESS') {
950 if(action == 'checkout') {
952 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
953 this.displayCheckout(result, 'checkout');
955 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
956 // A hold was fulfilled, update the hold numbers in the circ summary
957 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
958 this.holdsSummary = null;
959 this.updateHoldsSummary();
962 this.updateCircSummary(true);
964 } else if(action == 'renew') {
966 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
967 this.displayCheckout(result, 'renew');
970 this.checkouts.push({circ : result.payload.circ.id()});
971 sound = 'checkout-success';
972 this.updateScanBox();
974 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
976 // Server says the item is already checked out. If it's checked out to the
977 // current user, we may need to renew it.
979 if(payload.old_circ) {
982 old_circ refers to the previous checkout IFF it's for the same user.
983 If no auto-renew interval is not defined, assume we should renew it
984 If an auto-renew interval is defined and the payload comes back with
985 auto_renew set to true, do the renewal. Otherwise, let the patron know
986 the item is already checked out to them. */
988 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
989 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
990 this.prevCirc = payload.old_circ.id();
991 return { renew : true };
995 sound = 'checkout-failure';
996 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
1000 if( // copy is marked lost. if configured to do so, check it in and try again.
1001 result.payload.copy &&
1002 result.payload.copy.status() == /* LOST */ 3 &&
1003 overrideEvents && overrideEvents.length &&
1004 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
1006 if(this.checkin(item)) {
1007 return { doOver : true };
1012 // item is checked out to some other user
1014 sound = 'checkout-failure';
1015 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1018 this.updateScanBox({select:true});
1023 if(overrideEvents && overrideEvents.length) {
1025 // see if the events we received are all in the list of
1026 // events to override
1028 if(!result.length) result = [result];
1030 var override = true;
1031 for(var i = 0; i < result.length; i++) {
1033 var match = overrideEvents.filter(function(e) { return (e == result[i].textcode); })[0];
1040 if(result[i].textcode == 'COPY_NOT_AVAILABLE' && blockStatuses && blockStatuses.length) {
1042 var stat = result[i].payload.status(); // copy status
1043 if(typeof stat == 'object') stat = stat.id();
1045 var match2 = blockStatuses.filter(function(e) { return (e == stat); })[0];
1047 if(match2) { // copy is in a blocked status
1053 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1054 // to override a transit, we have to abort the transit and check it in first
1055 if(this.checkin(item, true)) {
1056 return { doOver : true };
1064 return { override : true };
1067 this.updateScanBox({select : true});
1069 sound = 'checkout-failure';
1071 if(action == 'renew')
1072 this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1077 switch(result.textcode) {
1079 // TODO custom handler for blocking penalties
1081 case 'MAX_RENEWALS_REACHED' :
1082 displayText = dojo.string.substitute(
1083 localeStrings.MAX_RENEWALS, [item]);
1086 case 'ITEM_NOT_CATALOGED' :
1087 displayText = dojo.string.substitute(
1088 localeStrings.ITEM_NOT_CATALOGED, [item]);
1091 case 'OPEN_CIRCULATION_EXISTS' :
1092 displayText = dojo.string.substitute(
1093 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1098 console.error('Unhandled event ' + result.textcode);
1100 if (!(displayText = this.failPartMessage(result))) {
1101 if (action == 'checkout' || action == 'renew') {
1102 displayText = dojo.string.substitute(
1103 localeStrings.GENERIC_CIRC_FAILURE, [item]);
1105 displayText = dojo.string.substitute(
1106 localeStrings.UNKNOWN_ERROR, [result.textcode]);
1112 this.handleAlert(displayText, popup, sound);
1120 SelfCheckManager.prototype.renew = function(barcode, override) {
1122 var method = 'open-ils.circ.renew';
1123 if(override) method += '.override';
1125 console.log("Renewing item " + barcode + " with method " + method);
1127 var result = fieldmapper.standardRequest(
1128 ['open-ils.circ', method],
1131 patron_id : this.patron.id(),
1132 copy_barcode : barcode
1137 console.log(js2JSON(result));
1139 var stat = this.handleXactResult('renew', barcode, result);
1142 this.renew(barcode, true);
1146 * Display the result of a checkout or renewal in the items out table
1148 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1150 var copy = evt.payload.copy;
1151 var record = evt.payload.record;
1152 var circ = evt.payload.circ;
1153 var row = this.circTemplate.cloneNode(true);
1156 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + record.isbn());
1159 this.byName(row, 'barcode').innerHTML = copy.barcode();
1160 this.byName(row, 'title').innerHTML = record.title();
1161 this.byName(row, 'author').innerHTML = record.author();
1162 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1163 openils.Util.show(this.byName(row, type));
1165 var date = dojo.date.stamp.fromISOString(circ.due_date());
1166 this.byName(row, 'due_date').innerHTML =
1167 dojo.date.locale.format(date, {selector : 'date'});
1169 // put new circs at the top of the list
1170 var tbody = this.circTbody;
1171 if(itemsOut) tbody = this.itemsOutTbody;
1172 tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1176 SelfCheckManager.prototype.byName = function(node, name) {
1177 return dojo.query('[name=' + name+']', node)[0];
1181 SelfCheckManager.prototype.initPrinter = function() {
1182 try { // Mozilla only
1183 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1184 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1185 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1186 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1187 var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1189 pref.setBoolPref('print.always_print_silent', true);
1191 console.log("Unable to initialize auto-printing");
1196 * Print a receipt for this session's checkouts
1198 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1201 var circCtx = []; // circ context data. in this case, renewal_failure info
1203 // collect the circs and failure info
1207 circIds.push(blob.circ);
1208 circCtx.push({renewal_failure:blob.renewal_failure});
1216 'format.selfcheck.checkout',
1223 fieldmapper.standardRequest(
1224 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1228 oncomplete : function(r) {
1229 var resp = openils.Util.readResponse(r);
1230 var output = resp.template_output();
1232 self.printData(output.data(), self.checkouts.length, callback);
1234 var error = resp.error_output();
1236 throw new Error("Error creating receipt: " + error.data());
1238 throw new Error("No receipt data returned from server");
1246 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1248 var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1');
1249 win.document.body.innerHTML = data;
1253 * There is no way to know when the browser is done printing.
1254 * Make a best guess at when to close the print window by basing
1255 * the setTimeout wait on the number of items to be printed plus
1258 var sleepTime = 1000;
1260 sleepTime += (numItems / 2) * 1000;
1264 win.close(); // close the print window
1266 callback(); // fire optional post-print callback
1274 * Print a receipt for this user's items out
1276 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1278 if(!this.itemsOut.length) return;
1280 progressDialog.show(true);
1286 'format.selfcheck.items_out',
1292 fieldmapper.standardRequest(
1293 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1297 oncomplete : function(r) {
1298 progressDialog.hide();
1299 var resp = openils.Util.readResponse(r);
1300 var output = resp.template_output();
1302 self.printData(output.data(), self.itemsOut.length, callback);
1304 var error = resp.error_output();
1306 throw new Error("Error creating receipt: " + error.data());
1308 throw new Error("No receipt data returned from server");
1317 * Print a receipt for this user's items out
1319 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1321 if(!this.holds.length) return;
1323 progressDialog.show(true);
1328 dojo.forEach(this.holds,
1330 holdIds.push(data.hold.id());
1331 if(data.status == 4) {
1332 holdData.push({ready : true});
1335 queue_position : data.queue_position,
1336 potential_copies : data.potential_copies
1346 'format.selfcheck.holds',
1353 fieldmapper.standardRequest(
1354 ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1358 oncomplete : function(r) {
1359 progressDialog.hide();
1360 var resp = openils.Util.readResponse(r);
1361 var output = resp.template_output();
1363 self.printData(output.data(), self.holds.length, callback);
1365 var error = resp.error_output();
1367 throw new Error("Error creating receipt: " + error.data());
1369 throw new Error("No receipt data returned from server");
1378 SelfCheckManager.prototype.printPaymentReceipt = function(response, callback) {
1381 progressDialog.show(true);
1383 fieldmapper.standardRequest(
1384 ['open-ils.circ', 'open-ils.circ.money.payment_receipt.print'],
1387 params : [this.authtoken, response.payments],
1388 oncomplete : function(r) {
1389 var resp = openils.Util.readResponse(r);
1390 var output = resp.template_output();
1391 progressDialog.hide();
1393 self.printData(output.data(), 1, callback);
1395 var error = resp.error_output();
1397 throw new Error("Error creating receipt: " + error.data());
1399 throw new Error("No receipt data returned from server");
1408 * Print a receipt for this user's items out
1410 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1412 progressDialog.show(true);
1418 'format.selfcheck.fines',
1424 fieldmapper.standardRequest(
1425 ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1429 oncomplete : function(r) {
1430 progressDialog.hide();
1431 var resp = openils.Util.readResponse(r);
1432 var output = resp.template_output();
1434 self.printData(output.data(), self.finesCount, callback);
1436 var error = resp.error_output();
1438 throw new Error("Error creating receipt: " + error.data());
1440 throw new Error("No receipt data returned from server");
1452 * Logout the patron and return to the login page
1454 SelfCheckManager.prototype.logoutPatron = function(print) {
1455 progressDialog.show(true); // prevent patron from clicking logout link twice
1456 if(print && this.checkouts.length) {
1457 this.printSessionReceipt(
1459 location.href = location.href;
1463 location.href = location.href;
1469 * Fire up the manager on page load
1471 openils.Util.addOnLoad(
1473 new SelfCheckManager().init();