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_or_usrname) {
281 // handle patron barcode/usrname 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_or_usrname, pw); },
293 // password is not required, go ahead and login
294 self.loginPatron(barcode_or_usrname);
299 msg : 'Please log in with your username or library barcode.', // TODO
307 SelfCheckManager.prototype.loginPatron = function(barcode_or_usrname, passwd) {
309 this.setupStaffLogin(true); // verify still valid
313 console.log('testing ' + barcode_or_usrname);
314 if (barcode_or_usrname.match(this.patronBarcodeRegex)) {
315 console.log('barcode');
316 barcode = barcode_or_usrname;
318 console.log('usrname');
319 usrname = barcode_or_usrname;
322 if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
325 // would only happen in dev/debug mode when using the patron= param
326 alert('password required by org setting. remove patron= from URL');
330 // patron password is required. Verify it.
332 var res = fieldmapper.standardRequest(
333 ['open-ils.actor', 'open-ils.actor.verify_user_password'],
334 {params : [this.authtoken, barcode, usrname, hex_md5(passwd)]}
338 // user-not-found results in login failure
340 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode_or_usrname]),
341 false, 'login-failure'
343 this.drawLoginPage();
348 var patron_id = fieldmapper.standardRequest(
349 ['open-ils.actor', 'open-ils.actor.user.retrieve_id_by_barcode_or_username'],
350 {params : [this.authtoken, barcode, usrname]}
353 // retrieve the fleshed user by id
354 this.patron = fieldmapper.standardRequest(
355 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
356 {params : [this.authtoken, patron_id]}
359 var evt = openils.Event.parse(this.patron);
361 // verify validity of the card used to log in
362 var inactiveCard = false;
366 card = this.patron.cards().filter(
367 function(c) { return (c.barcode() == barcode); })[0];
369 card = this.patron.card();
371 inactiveCard = !openils.Util.isTrue(card.active());
374 if(evt || inactiveCard) {
376 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode_or_usrname]),
377 false, 'login-failure'
379 this.drawLoginPage();
383 this.handleAlert('', false, 'login-success');
384 dojo.byId('oils-selfck-user-banner').innerHTML =
385 dojo.string.substitute(localeStrings.WELCOME_BANNER, [this.patron.first_given_name()]);
391 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
393 console.log("Handling alert " + message);
395 dojo.byId('oils-selfck-status-div').innerHTML = message;
398 openils.Util.addCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
400 openils.Util.removeCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
402 if(shouldPopup && this.orgSettings[SET_ALERT_POPUP])
405 if(sound && this.orgSettings[SET_ALERT_SOUND])
406 openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
411 * Manages the main input box
412 * @param msg The context message to display with the box
413 * @param clearOnly Don't update the context message, just clear the value and re-focus
414 * @param handler Optional "on-enter" handler.
416 SelfCheckManager.prototype.updateScanBox = function(args) {
420 selfckScanBox.domNode.select();
422 selfckScanBox.attr('value', '');
426 selfckScanBox.domNode.setAttribute('type', 'password');
428 selfckScanBox.domNode.setAttribute('type', '');
432 selfckScanBox.attr('value', args.value);
435 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
437 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
438 dojo.disconnect(selfckScanBox._lastHandler);
442 selfckScanBox._lastHandler = dojo.connect(
446 if(e.keyCode != dojo.keys.ENTER)
448 args.handler(selfckScanBox.attr('value'));
453 selfckScanBox.focus();
457 * Sets up the checkout/renewal interface
459 SelfCheckManager.prototype.drawCircPage = function() {
461 openils.Util.show('oils-selfck-circ-tbody', 'table-row-group');
462 this.goToTab('checkout');
464 while(this.itemsOutTbody.childNodes[0])
465 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
469 msg : 'Please enter an item barcode', // TODO i18n
470 handler : function(barcode) { self.checkout(barcode); }
473 if(!this.circTemplate)
474 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
477 this.updateFinesSummary();
480 this.updateHoldsSummary();
483 this.updateCircSummary();
485 // render mock checkouts for debugging?
486 if(this.mockCheckouts) {
487 for(var i in [1,2,3])
488 this.displayCheckout(this.mockCheckout, 'checkout');
493 SelfCheckManager.prototype.updateFinesSummary = function() {
497 fieldmapper.standardRequest(
498 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
500 params : [this.authtoken, this.patron.id()],
501 oncomplete : function(r) {
503 var summary = openils.Util.readResponse(r);
505 dojo.byId('oils-selfck-fines-total').innerHTML =
506 dojo.string.substitute(
507 localeStrings.TOTAL_FINES_ACCOUNT,
508 [summary.balance_owed()]
511 self.creditPayableBalance = summary.balance_owed();
518 SelfCheckManager.prototype.drawItemsOutPage = function() {
519 openils.Util.hide('oils-selfck-circ-tbody');
521 this.goToTab('items_out');
523 while(this.itemsOutTbody.childNodes[0])
524 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
526 progressDialog.show(true);
529 fieldmapper.standardRequest(
530 ['open-ils.circ', 'open-ils.circ.actor.user.checked_out.atomic'],
533 params : [this.authtoken, this.patron.id()],
534 oncomplete : function(r) {
536 var resp = openils.Util.readResponse(r);
538 var circs = resp.sort(
540 if(a.circ.due_date() > b.circ.due_date())
546 progressDialog.hide();
551 self.itemsOut.push(circ.circ.id());
552 self.displayCheckout(
554 (circ.circ.parent_circ()) ? 'renew' : 'checkout',
565 SelfCheckManager.prototype.goToTab = function(name) {
568 openils.Util.hide('oils-selfck-fines-page');
569 openils.Util.hide('oils-selfck-payment-page');
570 openils.Util.hide('oils-selfck-holds-page');
571 openils.Util.hide('oils-selfck-circ-page');
572 openils.Util.hide('oils-selfck-pay-fines-link');
576 openils.Util.show('oils-selfck-circ-page');
579 openils.Util.show('oils-selfck-circ-page');
582 openils.Util.show('oils-selfck-holds-page');
585 openils.Util.show('oils-selfck-fines-page');
588 openils.Util.show('oils-selfck-payment-page');
594 SelfCheckManager.prototype.printList = function() {
595 switch(this.tabName) {
597 this.printSessionReceipt();
600 this.printItemsOutReceipt();
603 this.printHoldsReceipt();
606 this.printFinesReceipt();
611 SelfCheckManager.prototype.updateHoldsSummary = function() {
613 if(!this.holdsSummary) {
614 var summary = fieldmapper.standardRequest(
615 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
616 {params : [this.authtoken, this.patron.id()]}
619 this.holdsSummary = {};
620 this.holdsSummary.ready = Number(summary['4']);
621 this.holdsSummary.total = 0;
623 for(var i in summary)
624 this.holdsSummary.total += Number(summary[i]);
627 dojo.byId('oils-selfck-holds-total').innerHTML =
628 dojo.string.substitute(
629 localeStrings.TOTAL_HOLDS,
630 [this.holdsSummary.total]
633 dojo.byId('oils-selfck-holds-ready').innerHTML =
634 dojo.string.substitute(
635 localeStrings.HOLDS_READY_FOR_PICKUP,
636 [this.holdsSummary.ready]
641 SelfCheckManager.prototype.updateCircSummary = function(increment) {
643 if(!this.circSummary) {
645 var summary = fieldmapper.standardRequest(
646 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
647 {params : [this.authtoken, this.patron.id()]}
651 total : Number(summary.out) + Number(summary.overdue),
652 overdue : Number(summary.overdue),
658 // local checkout occurred. Add to the total and the session.
659 this.circSummary.total += 1;
660 this.circSummary.session += 1;
663 dojo.byId('oils-selfck-circ-account-total').innerHTML =
664 dojo.string.substitute(
665 localeStrings.TOTAL_ITEMS_ACCOUNT,
666 [this.circSummary.total]
669 dojo.byId('oils-selfck-circ-session-total').innerHTML =
670 dojo.string.substitute(
671 localeStrings.TOTAL_ITEMS_SESSION,
672 [this.circSummary.session]
677 SelfCheckManager.prototype.drawHoldsPage = function() {
679 // TODO add option to hid scanBox
680 // this.updateScanBox(...)
682 this.goToTab('holds');
684 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
685 if(!this.holdTemplate)
686 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
687 while(this.holdTbody.childNodes[0])
688 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
690 progressDialog.show(true);
693 fieldmapper.standardRequest( // fetch the hold IDs
695 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
697 params : [this.authtoken, this.patron.id()],
699 oncomplete : function(r) {
700 var ids = openils.Util.readResponse(r);
701 if(!ids || ids.length == 0) {
702 progressDialog.hide();
706 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
707 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve'],
709 params : [self.authtoken, ids],
710 onresponse : function(rr) {
711 progressDialog.hide();
712 self.insertHold(openils.Util.readResponse(rr));
721 SelfCheckManager.prototype.insertHold = function(data) {
722 var row = this.holdTemplate.cloneNode(true);
724 if(data.mvr.isbn()) {
725 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + data.mvr.isbn());
728 this.byName(row, 'title').innerHTML = data.mvr.title();
729 this.byName(row, 'author').innerHTML = data.mvr.author();
731 if(data.status == 4) {
733 // hold is ready for pickup
734 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
738 // hold is still pending
739 this.byName(row, 'status').innerHTML =
740 dojo.string.substitute(
741 localeStrings.HOLD_STATUS_WAITING,
742 [data.queue_position, data.potential_copies]
746 // find the correct place the table to slot in the hold based on queue position
748 var position = (data.status == 4) ? 0 : data.queue_position;
749 row.setAttribute('position', position);
751 for(var i = 0; i < this.holdTbody.childNodes.length; i++) {
752 var node = this.holdTbody.childNodes[i];
753 if(Number(node.getAttribute('position')) >= position) {
754 this.holdTbody.insertBefore(row, node);
759 this.holdTbody.appendChild(row);
763 SelfCheckManager.prototype.drawFinesPage = function() {
765 // TODO add option to hid scanBox
766 // this.updateScanBox(...)
768 this.goToTab('fines');
769 progressDialog.show(true);
771 if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
772 openils.Util.show('oils-selfck-pay-fines-link', 'inline');
775 this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
776 if(!this.finesTemplate)
777 this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
778 while(this.finesTbody.childNodes[0])
779 this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
781 // when user clicks on a selector checkbox, update the total owed
782 var updateSelected = function() {
785 dojo.query('[name=selector]', this.finesTbody),
788 total += Number(input.getAttribute('balance_owed'));
792 total = total.toFixed(2);
793 dojo.byId('oils-selfck-selected-total').innerHTML =
794 dojo.string.substitute(localeStrings.TOTAL_FINES_SELECTED, [total]);
797 // wire up the batch on/off selector
798 var sel = dojo.byId('oils-selfck-fines-selector');
799 sel.onchange = function() {
801 dojo.query('[name=selector]', this.finesTbody),
803 input.checked = sel.checked;
809 var handler = function(dataList) {
811 self.finesCount = dataList.length;
812 self.finesData = dataList;
814 for(var i in dataList) {
816 var data = dataList[i];
817 var row = self.finesTemplate.cloneNode(true);
818 var type = data.transaction.xact_type();
820 if(type == 'circulation') {
821 self.byName(row, 'type').innerHTML = type;
822 self.byName(row, 'details').innerHTML = data.record.title();
824 } else if(type == 'grocery') {
825 self.byName(row, 'type').innerHTML = 'Miscellaneous'; // Go ahead and head off any confusion around "grocery". TODO i18n
826 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
829 self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
830 self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
831 self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
834 var selector = self.byName(row, 'selector')
835 selector.onchange = updateSelected;
836 selector.setAttribute('xact', data.transaction.id());
837 selector.setAttribute('balance_owed', data.transaction.balance_owed());
838 selector.checked = true;
840 self.finesTbody.appendChild(row);
847 fieldmapper.standardRequest(
848 ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
850 params : [this.authtoken, this.patron.id()],
851 oncomplete : function(r) {
852 progressDialog.hide();
853 handler(openils.Util.readResponse(r));
859 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
861 var resp = fieldmapper.standardRequest(
862 ['open-ils.circ', 'open-ils.circ.transit.abort'],
863 {params : [this.authtoken, {barcode : barcode}]}
866 // resp == 1 on success
867 if(openils.Event.parse(resp))
870 var resp = fieldmapper.standardRequest(
871 ['open-ils.circ', 'open-ils.circ.checkin.override'],
874 patron_id : this.patron.id(),
875 copy_barcode : barcode,
881 if(!resp.length) resp = [resp];
882 for(var i = 0; i < resp.length; i++) {
883 var tc = openils.Event.parse(resp[i]).textcode;
884 if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
895 * Check out a single item. If the item is already checked
896 * out to the patron, redirect to renew()
898 SelfCheckManager.prototype.checkout = function(barcode, override) {
900 this.prevCirc = null;
903 this.updateScanbox(null, true);
907 if(this.mockCheckouts) {
908 // if we're in mock-checkout mode, just insert another
909 // fake circ into the table and get out of here.
910 this.displayCheckout(this.mockCheckout, 'checkout');
914 // TODO see if it's a patron barcode
915 // TODO see if this item has already been checked out in this session
917 var method = 'open-ils.circ.checkout.full';
918 if(override) method += '.override';
920 console.log("Checkout out item " + barcode + " with method " + method);
922 var result = fieldmapper.standardRequest(
923 ['open-ils.circ', method],
926 patron_id : this.patron.id(),
927 copy_barcode : barcode
932 var stat = this.handleXactResult('checkout', barcode, result);
935 this.checkout(barcode, true);
936 } else if(stat.doOver) {
937 this.checkout(barcode);
938 } else if(stat.renew) {
943 SelfCheckManager.prototype.failPartMessage = function(result) {
944 if (result.payload && result.payload.fail_part) {
945 var stringKey = "FAIL_PART_" +
946 result.payload.fail_part.replace(/\./g, "_");
947 return localeStrings[stringKey];
953 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
955 var displayText = '';
957 // If true, the display message is important enough to pop up. Whether or not
958 // an alert() actually occurs, depends on org unit settings
960 var sound = ''; // sound file reference
961 var payload = result.payload || {};
962 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
963 var blockStatuses = this.orgSettings[SET_BLOCK_CHECKOUT_ON_COPY_STATUS];
965 if(result.textcode == 'NO_SESSION') {
967 return this.logoutStaff();
969 } else if(result.textcode == 'SUCCESS') {
971 if(action == 'checkout') {
973 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
974 this.displayCheckout(result, 'checkout');
976 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
977 // A hold was fulfilled, update the hold numbers in the circ summary
978 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
979 this.holdsSummary = null;
980 this.updateHoldsSummary();
983 this.updateCircSummary(true);
985 } else if(action == 'renew') {
987 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
988 this.displayCheckout(result, 'renew');
991 this.checkouts.push({circ : result.payload.circ.id()});
992 sound = 'checkout-success';
993 this.updateScanBox();
995 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
997 // Server says the item is already checked out. If it's checked out to the
998 // current user, we may need to renew it.
1000 if(payload.old_circ) {
1003 old_circ refers to the previous checkout IFF it's for the same user.
1004 If no auto-renew interval is not defined, assume we should renew it
1005 If an auto-renew interval is defined and the payload comes back with
1006 auto_renew set to true, do the renewal. Otherwise, let the patron know
1007 the item is already checked out to them. */
1009 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
1010 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
1011 this.prevCirc = payload.old_circ.id();
1012 return { renew : true };
1016 sound = 'checkout-failure';
1017 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
1021 if( // copy is marked lost. if configured to do so, check it in and try again.
1022 result.payload.copy &&
1023 result.payload.copy.status() == /* LOST */ 3 &&
1024 overrideEvents && overrideEvents.length &&
1025 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
1027 if(this.checkin(item)) {
1028 return { doOver : true };
1033 // item is checked out to some other user
1035 sound = 'checkout-failure';
1036 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1039 this.updateScanBox({select:true});
1044 if(overrideEvents && overrideEvents.length) {
1046 // see if the events we received are all in the list of
1047 // events to override
1049 if(!result.length) result = [result];
1051 var override = true;
1052 for(var i = 0; i < result.length; i++) {
1054 var match = overrideEvents.filter(function(e) { return (e == result[i].textcode); })[0];
1061 if(result[i].textcode == 'COPY_NOT_AVAILABLE' && blockStatuses && blockStatuses.length) {
1063 var stat = result[i].payload.status(); // copy status
1064 if(typeof stat == 'object') stat = stat.id();
1066 var match2 = blockStatuses.filter(function(e) { return (e == stat); })[0];
1068 if(match2) { // copy is in a blocked status
1074 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1075 // to override a transit, we have to abort the transit and check it in first
1076 if(this.checkin(item, true)) {
1077 return { doOver : true };
1085 return { override : true };
1088 this.updateScanBox({select : true});
1090 sound = 'checkout-failure';
1092 if(action == 'renew')
1093 this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1098 switch(result.textcode) {
1100 // TODO custom handler for blocking penalties
1102 case 'MAX_RENEWALS_REACHED' :
1103 displayText = dojo.string.substitute(
1104 localeStrings.MAX_RENEWALS, [item]);
1107 case 'ITEM_NOT_CATALOGED' :
1108 displayText = dojo.string.substitute(
1109 localeStrings.ITEM_NOT_CATALOGED, [item]);
1112 case 'OPEN_CIRCULATION_EXISTS' :
1113 displayText = dojo.string.substitute(
1114 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1119 console.error('Unhandled event ' + result.textcode);
1121 if (!(displayText = this.failPartMessage(result))) {
1122 if (action == 'checkout' || action == 'renew') {
1123 displayText = dojo.string.substitute(
1124 localeStrings.GENERIC_CIRC_FAILURE, [item]);
1126 displayText = dojo.string.substitute(
1127 localeStrings.UNKNOWN_ERROR, [result.textcode]);
1133 this.handleAlert(displayText, popup, sound);
1141 SelfCheckManager.prototype.renew = function(barcode, override) {
1143 var method = 'open-ils.circ.renew';
1144 if(override) method += '.override';
1146 console.log("Renewing item " + barcode + " with method " + method);
1148 var result = fieldmapper.standardRequest(
1149 ['open-ils.circ', method],
1152 patron_id : this.patron.id(),
1153 copy_barcode : barcode
1158 console.log(js2JSON(result));
1160 var stat = this.handleXactResult('renew', barcode, result);
1163 this.renew(barcode, true);
1167 * Display the result of a checkout or renewal in the items out table
1169 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1171 var copy = evt.payload.copy;
1172 var record = evt.payload.record;
1173 var circ = evt.payload.circ;
1174 var row = this.circTemplate.cloneNode(true);
1177 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + record.isbn());
1180 this.byName(row, 'barcode').innerHTML = copy.barcode();
1181 this.byName(row, 'title').innerHTML = record.title();
1182 this.byName(row, 'author').innerHTML = record.author();
1183 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1184 openils.Util.show(this.byName(row, type));
1186 var date = dojo.date.stamp.fromISOString(circ.due_date());
1187 this.byName(row, 'due_date').innerHTML =
1188 dojo.date.locale.format(date, {selector : 'date'});
1190 // put new circs at the top of the list
1191 var tbody = this.circTbody;
1192 if(itemsOut) tbody = this.itemsOutTbody;
1193 tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1197 SelfCheckManager.prototype.byName = function(node, name) {
1198 return dojo.query('[name=' + name+']', node)[0];
1202 SelfCheckManager.prototype.initPrinter = function() {
1203 try { // Mozilla only
1204 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1205 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1206 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1207 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1208 var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1210 pref.setBoolPref('print.always_print_silent', true);
1212 console.log("Unable to initialize auto-printing");
1217 * Print a receipt for this session's checkouts
1219 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1222 var circCtx = []; // circ context data. in this case, renewal_failure info
1224 // collect the circs and failure info
1228 circIds.push(blob.circ);
1229 circCtx.push({renewal_failure:blob.renewal_failure});
1237 'format.selfcheck.checkout',
1244 fieldmapper.standardRequest(
1245 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1249 oncomplete : function(r) {
1250 var resp = openils.Util.readResponse(r);
1251 var output = resp.template_output();
1253 self.printData(output.data(), self.checkouts.length, callback);
1255 var error = resp.error_output();
1257 throw new Error("Error creating receipt: " + error.data());
1259 throw new Error("No receipt data returned from server");
1267 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1269 var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1');
1270 win.document.body.innerHTML = data;
1274 * There is no way to know when the browser is done printing.
1275 * Make a best guess at when to close the print window by basing
1276 * the setTimeout wait on the number of items to be printed plus
1279 var sleepTime = 1000;
1281 sleepTime += (numItems / 2) * 1000;
1285 win.close(); // close the print window
1287 callback(); // fire optional post-print callback
1295 * Print a receipt for this user's items out
1297 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1299 if(!this.itemsOut.length) return;
1301 progressDialog.show(true);
1307 'format.selfcheck.items_out',
1313 fieldmapper.standardRequest(
1314 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1318 oncomplete : function(r) {
1319 progressDialog.hide();
1320 var resp = openils.Util.readResponse(r);
1321 var output = resp.template_output();
1323 self.printData(output.data(), self.itemsOut.length, callback);
1325 var error = resp.error_output();
1327 throw new Error("Error creating receipt: " + error.data());
1329 throw new Error("No receipt data returned from server");
1338 * Print a receipt for this user's items out
1340 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1342 if(!this.holds.length) return;
1344 progressDialog.show(true);
1349 dojo.forEach(this.holds,
1351 holdIds.push(data.hold.id());
1352 if(data.status == 4) {
1353 holdData.push({ready : true});
1356 queue_position : data.queue_position,
1357 potential_copies : data.potential_copies
1367 'format.selfcheck.holds',
1374 fieldmapper.standardRequest(
1375 ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1379 oncomplete : function(r) {
1380 progressDialog.hide();
1381 var resp = openils.Util.readResponse(r);
1382 var output = resp.template_output();
1384 self.printData(output.data(), self.holds.length, callback);
1386 var error = resp.error_output();
1388 throw new Error("Error creating receipt: " + error.data());
1390 throw new Error("No receipt data returned from server");
1399 SelfCheckManager.prototype.printPaymentReceipt = function(response, callback) {
1402 progressDialog.show(true);
1404 fieldmapper.standardRequest(
1405 ['open-ils.circ', 'open-ils.circ.money.payment_receipt.print'],
1408 params : [this.authtoken, response.payments],
1409 oncomplete : function(r) {
1410 var resp = openils.Util.readResponse(r);
1411 var output = resp.template_output();
1412 progressDialog.hide();
1414 self.printData(output.data(), 1, callback);
1416 var error = resp.error_output();
1418 throw new Error("Error creating receipt: " + error.data());
1420 throw new Error("No receipt data returned from server");
1429 * Print a receipt for this user's items out
1431 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1433 progressDialog.show(true);
1439 'format.selfcheck.fines',
1445 fieldmapper.standardRequest(
1446 ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1450 oncomplete : function(r) {
1451 progressDialog.hide();
1452 var resp = openils.Util.readResponse(r);
1453 var output = resp.template_output();
1455 self.printData(output.data(), self.finesCount, callback);
1457 var error = resp.error_output();
1459 throw new Error("Error creating receipt: " + error.data());
1461 throw new Error("No receipt data returned from server");
1473 * Logout the patron and return to the login page
1475 SelfCheckManager.prototype.logoutPatron = function(print) {
1476 progressDialog.show(true); // prevent patron from clicking logout link twice
1477 if(print && this.checkouts.length) {
1478 this.printSessionReceipt(
1480 location.href = location.href;
1484 location.href = location.href;
1490 * Fire up the manager on page load
1492 openils.Util.addOnLoad(
1494 new SelfCheckManager().init();