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');
17 // set patron timeout default
18 var patronTimeout = 160000; /* 2 minutes, 40 seconds */
20 // 20 second inactivity warning; total default timeout is 3 minutes.
21 var patronTimeoutWarning = 20000;
22 var selfckWarningSetup = false;
23 var selfckWarningTimer;
25 const SET_BARCODE_REGEX = 'opac.barcode_regex';
26 const SET_PATRON_TIMEOUT = 'circ.selfcheck.patron_login_timeout';
27 const SET_AUTO_OVERRIDE_EVENTS = 'circ.selfcheck.auto_override_checkout_events';
28 const SET_PATRON_PASSWORD_REQUIRED = 'circ.selfcheck.patron_password_required';
29 const SET_AUTO_RENEW_INTERVAL = 'circ.checkout_auto_renew_age';
30 const SET_WORKSTATION_REQUIRED = 'circ.selfcheck.workstation_required';
31 const SET_ALERT_POPUP = 'circ.selfcheck.alert.popup';
32 const SET_ALERT_SOUND = 'circ.selfcheck.alert.sound';
33 const SET_CC_PAYMENT_ALLOWED = 'credit.payments.allow';
34 // This setting only comes into play if COPY_NOT_AVAILABLE is in the SET_AUTO_OVERRIDE_EVENTS list
35 const SET_BLOCK_CHECKOUT_ON_COPY_STATUS = 'circ.selfcheck.block_checkout_on_copy_status';
37 // set before the login dialog is rendered
38 openils.User.default_login_agent = 'selfcheck';
40 // start the logout timer
41 function selfckStartTimer() {
44 selfckLogoutWarning();
50 // reset the logout timer
51 function selfckResetTimer() {
52 clearTimeout(timerId);
56 function selfckLogoutWarning() {
58 // connect the logout warning dialog button handlers if needed
59 if (!selfckWarningSetup) {
60 selfckWarningSetup = true;
62 dojo.connect(oilsSelfckLogout, 'onClick',
64 clearTimeout(selfckWarningTimer);
65 oilsSelfckLogoutDialog.hide();
66 SelfCheckManager.prototype.logoutPatron();
70 dojo.connect(oilsSelfckContinue, 'onClick',
72 clearTimeout(selfckWarningTimer);
73 oilsSelfckLogoutDialog.hide();
79 // warn the patron of imminent logout
80 oilsSelfckLogoutDialog.show();
81 selfckWarningTimer = setTimeout(
83 // no action was taken, force a logout.
84 oilsSelfckLogoutDialog.hide();
85 SelfCheckManager.prototype.logoutPatron();
91 function SelfCheckManager() {
93 this.cgi = new openils.CGI();
95 this.workstation = null;
96 this.authtoken = null;
99 this.patronBarcodeRegex = null;
104 // During renewals, keep track of the ID of the previous circulation.
105 // Previous circ is used for tracking failed renewals (for receipts).
106 this.prevCirc = null;
108 // current item barcode
109 this.itemBarcode = null;
111 // are we currently performing a renewal?
112 this.isRenewal = false;
114 // dict of org unit settings for "here"
115 this.orgSettings = {};
117 // Construct a mock checkout for debugging purposes
118 if(this.mockCheckouts = this.cgi.param('mock-circ')) {
120 this.mockCheckout = {
122 record : new fieldmapper.mvr(),
123 copy : new fieldmapper.acp(),
124 circ : new fieldmapper.circ()
128 this.mockCheckout.payload.record.title('Jazz improvisation for guitar');
129 this.mockCheckout.payload.record.author('Wise, Les');
130 this.mockCheckout.payload.record.isbn('0634033565');
131 this.mockCheckout.payload.copy.barcode('123456789');
132 this.mockCheckout.payload.circ.renewal_remaining(1);
133 this.mockCheckout.payload.circ.parent_circ(1);
134 this.mockCheckout.payload.circ.due_date('2012-12-21');
140 SelfCheckManager.prototype.setupStaffLogin = function(verify) {
142 if(verify) oilsSetupUser();
143 this.staff = openils.User.user;
144 this.workstation = openils.User.workstation;
145 this.authtoken = openils.User.authtoken;
151 * Fetch the org-unit settings, initialize the display, etc.
153 SelfCheckManager.prototype.init = function() {
155 this.setupStaffLogin();
156 this.loadOrgSettings();
158 this.circTbody = dojo.byId('oils-selfck-circ-tbody');
159 this.itemsOutTbody = dojo.byId('oils-selfck-circ-out-tbody');
161 // workstation is required but none provided
162 if(this.orgSettings[SET_WORKSTATION_REQUIRED] && !this.workstation) {
163 if(confirm(dojo.string.substitute(localeStrings.WORKSTATION_REQUIRED))) {
164 this.registerWorkstation();
170 // connect onclick handlers to the various navigation links
172 'oils-selfck-hold-details-link' : function() { self.drawHoldsPage(); },
173 'oils-selfck-view-fines-link' : function() { self.drawFinesPage(); },
174 'oils-selfck-pay-fines-link' : function() {
175 self.goToTab("payment");
176 self.drawPayFinesPage(
178 self.getSelectedFinesTotal(),
179 self.getSelectedFineTransactions(),
181 var evt = openils.Event.parse(resp);
183 var message = evt + '';
184 if(evt.textcode == 'CREDIT_PROCESSOR_DECLINED_TRANSACTION' && evt.payload)
185 message += '\n' + evt.payload.error_message;
186 if(evt.textcode == 'INVALID_USER_XACT_ID')
187 message += '\n' + localeStrings.PAYMENT_INVALID_USER_XACT_ID;
188 self.handleAlert(message, true, 'payment-failure');
192 self.patron.last_xact_id(resp.last_xact_id); // update to match latest from server
193 self.printPaymentReceipt(
196 self.updateFinesSummary();
197 self.drawFinesPage();
203 'oils-selfck-nav-home' : function() { self.drawCircPage(); },
204 'oils-selfck-nav-logout' : function() { self.logoutPatron(); },
205 'oils-selfck-nav-logout-print' : function() { self.logoutPatron(true); },
206 'oils-selfck-items-out-details-link' : function() { self.drawItemsOutPage(); },
207 'oils-selfck-print-list-link' : function() { self.printList(); }
210 for(var id in linkHandlers)
211 dojo.connect(dojo.byId(id), 'onclick', linkHandlers[id]);
214 if(this.cgi.param('patron')) {
216 // Patron barcode via cgi param. Mainly used for debugging and
217 // only works if password is not required by policy
218 this.loginPatron(this.cgi.param('patron'));
221 this.drawLoginPage();
225 * To test printing, pass a URL param of 'testprint'. The value for the param
226 * should be a JSON string like so: [{circ:<circ_id>}, ...]
228 var testPrint = this.cgi.param('testprint');
230 this.checkouts = JSON2js(testPrint);
231 this.printSessionReceipt();
237 SelfCheckManager.prototype.getSelectedFinesTotal = function() {
240 dojo.query("[name=selector]", this.finesTbody),
243 total += Number(input.getAttribute("balance_owed"));
246 return total.toFixed(2);
249 SelfCheckManager.prototype.getSelectedFineTransactions = function() {
250 return dojo.query("[name=selector]", this.finesTbody).
251 filter(function (o) { return o.checked }).
255 o.getAttribute("xact"),
256 Number(o.getAttribute("balance_owed")).toFixed(2)
263 * Registers a new workstion
265 SelfCheckManager.prototype.registerWorkstation = function() {
267 oilsSelfckWsDialog.show();
269 new openils.User().buildPermOrgSelector(
270 'REGISTER_WORKSTATION',
271 oilsSelfckWsLocSelector,
277 dojo.connect(oilsSelfckWsSubmit, 'onClick',
280 oilsSelfckWsDialog.hide();
281 var name = oilsSelfckWsLocSelector.attr('displayedValue') + '-' + oilsSelfckWsName.attr('value');
283 var res = fieldmapper.standardRequest(
284 ['open-ils.actor', 'open-ils.actor.workstation.register'],
286 self.authtoken, name, oilsSelfckWsLocSelector.attr('value')
291 if(evt = openils.Event.parse(res)) {
292 if(evt.textcode == 'WORKSTATION_NAME_EXISTS') {
293 if(confirm(localeStrings.WORKSTATION_EXISTS)) {
294 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
296 self.registerWorkstation();
303 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
310 * Loads the org unit settings
312 SelfCheckManager.prototype.loadOrgSettings = function() {
314 var settings = fieldmapper.aou.fetchOrgSettingBatch(
315 this.staff.ws_ou(), [
320 SET_AUTO_OVERRIDE_EVENTS,
321 SET_BLOCK_CHECKOUT_ON_COPY_STATUS,
322 SET_PATRON_PASSWORD_REQUIRED,
323 SET_AUTO_RENEW_INTERVAL,
324 SET_WORKSTATION_REQUIRED,
325 SET_CC_PAYMENT_ALLOWED
331 this.orgSettings[k] = settings[k].value;
334 if(settings[SET_BARCODE_REGEX])
335 this.patronBarcodeRegex = new RegExp(settings[SET_BARCODE_REGEX].value);
337 // Subtract the timeout warning interval from the configured timeout
338 // so that when taken together they add up to the configured amount.
339 if(settings[SET_PATRON_TIMEOUT]) {
341 (parseInt(settings[SET_PATRON_TIMEOUT].value) * 1000)
342 - patronTimeoutWarning;
346 SelfCheckManager.prototype.drawLoginPage = function() {
349 var bcHandler = function(barcode_or_usrname) {
350 // handle patron barcode/usrname entry
352 if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
354 // password is required. wire up the scan box to read it
356 msg : localeStrings.ENTER_PASSWORD,
357 handler : function(pw) { self.loginPatron(barcode_or_usrname, pw); },
362 // password is not required, go ahead and login
363 self.loginPatron(barcode_or_usrname);
368 msg : localeStrings.PLEASE_LOGIN,
376 SelfCheckManager.prototype.loginPatron = function(barcode_or_usrname, passwd) {
381 this.setupStaffLogin(true); // verify still valid
385 console.log('testing ' + barcode_or_usrname);
386 if (barcode_or_usrname.match(this.patronBarcodeRegex)) {
387 console.log('barcode');
388 barcode = barcode_or_usrname;
390 console.log('usrname');
391 usrname = barcode_or_usrname;
394 if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
397 // would only happen in dev/debug mode when using the patron= param
398 alert('password required by org setting. remove patron= from URL');
402 // patron password is required. Verify it.
405 new openils.User().auth_verify(
406 { username : usrname, barcode : barcode,
407 type : 'opac', passwd : passwd, agent : 'selfcheck' },
410 self.fetchPatron(barcode, usrname);
413 // auth verify failed
415 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode_or_usrname]),
416 false, 'login-failure'
418 self.drawLoginPage();
424 this.fetchPatron(barcode, usrname);
428 SelfCheckManager.prototype.fetchPatron = function(barcode, usrname) {
430 var patron_id = fieldmapper.standardRequest(
431 ['open-ils.actor', 'open-ils.actor.user.retrieve_id_by_barcode_or_username'],
432 {params : [this.authtoken, barcode, usrname]}
435 // retrieve the fleshed user by id
436 this.patron = fieldmapper.standardRequest(
437 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
438 {params : [this.authtoken, patron_id]}
441 var evt = openils.Event.parse(this.patron);
443 // verify validity of the card used to log in
444 var inactiveCard = false;
448 card = this.patron.cards().filter(
449 function(c) { return (c.barcode() == barcode); })[0];
451 card = this.patron.card();
453 inactiveCard = !openils.Util.isTrue(card.active());
456 if(evt || inactiveCard) {
458 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode || usrname]),
459 false, 'login-failure'
461 this.drawLoginPage();
465 this.handleAlert('', false, 'login-success');
466 dojo.byId('oils-selfck-user-banner').innerHTML =
467 dojo.string.substitute(localeStrings.WELCOME_BANNER, [this.patron.first_given_name()]);
473 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
475 console.log("Handling alert " + message);
477 dojo.byId('oils-selfck-status-div').innerHTML = message;
480 openils.Util.addCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
482 openils.Util.removeCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
484 if(shouldPopup && this.orgSettings[SET_ALERT_POPUP])
487 if(sound && this.orgSettings[SET_ALERT_SOUND])
488 openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
493 * Manages the main input box
494 * @param msg The context message to display with the box
495 * @param clearOnly Don't update the context message, just clear the value and re-focus
496 * @param handler Optional "on-enter" handler.
498 SelfCheckManager.prototype.updateScanBox = function(args) {
502 selfckScanBox.domNode.select();
504 selfckScanBox.attr('value', '');
508 selfckScanBox.domNode.setAttribute('type', 'password');
510 selfckScanBox.domNode.setAttribute('type', '');
514 selfckScanBox.attr('value', args.value);
517 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
519 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
520 dojo.disconnect(selfckScanBox._lastHandler);
524 selfckScanBox._lastHandler = dojo.connect(
528 if(e.keyCode != dojo.keys.ENTER)
530 args.handler(selfckScanBox.attr('value'));
535 selfckScanBox.focus();
539 * Sets up the checkout/renewal interface
541 SelfCheckManager.prototype.drawCircPage = function() {
543 openils.Util.show('oils-selfck-bottom-div');
544 openils.Util.show('oils-selfck-circ-tbody', 'table-row-group');
545 this.goToTab('checkout');
547 while(this.itemsOutTbody.childNodes[0])
548 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
552 msg : localeStrings.ENTER_BARCODE,
553 handler : function(barcode) { self.checkout(barcode); }
556 if(!this.circTemplate)
557 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
560 this.updateFinesSummary();
563 this.updateHoldsSummary();
566 this.updateCircSummary();
568 // render mock checkouts for debugging?
569 if(this.mockCheckouts) {
570 for(var i in [1,2,3])
571 this.displayCheckout(this.mockCheckout, 'checkout');
576 SelfCheckManager.prototype.updateFinesSummary = function() {
580 fieldmapper.standardRequest(
581 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
583 params : [this.authtoken, this.patron.id()],
584 oncomplete : function(r) {
586 var summary = openils.Util.readResponse(r);
588 dojo.byId('oils-selfck-fines-total').innerHTML =
589 dojo.string.substitute(
590 localeStrings.TOTAL_FINES_ACCOUNT,
591 ['<b>' + summary.balance_owed() + '</b>']
594 self.creditPayableBalance = summary.balance_owed();
601 SelfCheckManager.prototype.drawItemsOutPage = function() {
602 openils.Util.hide('oils-selfck-circ-tbody');
604 this.goToTab('items_out');
606 while(this.itemsOutTbody.childNodes[0])
607 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
609 progressDialog.show(true);
612 fieldmapper.standardRequest(
613 ['open-ils.circ', 'open-ils.circ.actor.user.checked_out.atomic'],
616 params : [this.authtoken, this.patron.id()],
617 oncomplete : function(r) {
619 var resp = openils.Util.readResponse(r);
621 var circs = resp.sort(
623 if(a.circ.due_date() > b.circ.due_date())
629 progressDialog.hide();
634 self.itemsOut.push(circ.circ.id());
635 self.displayCheckout(
637 (circ.circ.parent_circ()) ? 'renew' : 'checkout',
648 SelfCheckManager.prototype.goToTab = function(name) {
651 openils.Util.hide('oils-selfck-fines-page');
652 openils.Util.hide('oils-selfck-payment-page');
653 openils.Util.hide('oils-selfck-holds-page');
654 openils.Util.hide('oils-selfck-circ-page');
655 openils.Util.hide('oils-selfck-pay-fines-link');
662 openils.Util.show('oils-selfck-circ-page');
665 openils.Util.show('oils-selfck-circ-page');
668 openils.Util.show('oils-selfck-holds-page');
671 openils.Util.show('oils-selfck-fines-page');
674 openils.Util.show('oils-selfck-payment-page');
680 SelfCheckManager.prototype.printList = function() {
684 switch(this.tabName) {
686 this.printSessionReceipt();
689 this.printItemsOutReceipt();
692 this.printHoldsReceipt();
695 this.printFinesReceipt();
700 SelfCheckManager.prototype.updateHoldsSummary = function() {
702 if(!this.holdsSummary) {
703 var summary = fieldmapper.standardRequest(
704 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
705 {params : [this.authtoken, this.patron.id()]}
708 this.holdsSummary = {};
709 this.holdsSummary.ready = Number(summary['4']);
710 this.holdsSummary.total = 0;
712 for(var i in summary)
713 this.holdsSummary.total += Number(summary[i]);
716 dojo.byId('oils-selfck-holds-total').innerHTML =
717 dojo.string.substitute(
718 localeStrings.TOTAL_HOLDS,
719 ['<b>' + this.holdsSummary.total + '</b>']
722 dojo.byId('oils-selfck-holds-ready').innerHTML =
723 dojo.string.substitute(
724 localeStrings.HOLDS_READY_FOR_PICKUP,
725 ['<b>' + this.holdsSummary.ready + '</b>']
730 SelfCheckManager.prototype.updateCircSummary = function(increment) {
732 if(!this.circSummary) {
734 var summary = fieldmapper.standardRequest(
735 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
736 {params : [this.authtoken, this.patron.id()]}
740 total : Number(summary.out) + Number(summary.overdue),
741 overdue : Number(summary.overdue),
747 // local checkout occurred. Add to the total and the session.
748 this.circSummary.total += 1;
749 this.circSummary.session += 1;
752 dojo.byId('oils-selfck-circ-account-total').innerHTML =
753 dojo.string.substitute(
754 localeStrings.TOTAL_ITEMS_ACCOUNT,
755 ['<b>' + this.circSummary.total + '</b>']
758 dojo.byId('oils-selfck-circ-session-total').innerHTML =
759 dojo.string.substitute(
760 localeStrings.TOTAL_ITEMS_SESSION,
761 ['<b>' + this.circSummary.session + '</b>']
766 SelfCheckManager.prototype.drawHoldsPage = function() {
768 // TODO add option to hid scanBox
769 // this.updateScanBox(...)
771 this.goToTab('holds');
773 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
774 if(!this.holdTemplate)
775 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
776 while(this.holdTbody.childNodes[0])
777 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
779 progressDialog.show(true);
782 fieldmapper.standardRequest( // fetch the hold IDs
784 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
786 params : [this.authtoken, this.patron.id()],
788 oncomplete : function(r) {
789 var ids = openils.Util.readResponse(r);
790 if(!ids || ids.length == 0) {
791 progressDialog.hide();
795 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
796 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve'],
798 params : [self.authtoken, ids],
799 onresponse : function(rr) {
800 progressDialog.hide();
801 self.insertHold(openils.Util.readResponse(rr));
810 SelfCheckManager.prototype.insertHold = function(data) {
811 var row = this.holdTemplate.cloneNode(true);
813 if(data.mvr.isbn()) {
814 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/r/' + data.mvr.doc_id());
817 this.byName(row, 'title').innerHTML = data.mvr.title();
818 this.byName(row, 'author').innerHTML = data.mvr.author();
820 if(data.status == 4) {
822 // hold is ready for pickup
823 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
827 // hold is still pending
828 this.byName(row, 'status').innerHTML =
829 dojo.string.substitute(
830 localeStrings.HOLD_STATUS_WAITING,
831 [data.queue_position, data.potential_copies]
835 // find the correct place the table to slot in the hold based on queue position
837 var position = (data.status == 4) ? 0 : data.queue_position;
838 row.setAttribute('position', position);
840 for(var i = 0; i < this.holdTbody.childNodes.length; i++) {
841 var node = this.holdTbody.childNodes[i];
842 if(Number(node.getAttribute('position')) >= position) {
843 this.holdTbody.insertBefore(row, node);
848 this.holdTbody.appendChild(row);
852 SelfCheckManager.prototype.drawFinesPage = function() {
854 // TODO add option to hid scanBox
855 // this.updateScanBox(...)
857 this.goToTab('fines');
858 progressDialog.show(true);
860 if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
861 openils.Util.show('oils-selfck-pay-fines-link', 'inline');
864 this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
865 if(!this.finesTemplate)
866 this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
867 while(this.finesTbody.childNodes[0])
868 this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
870 // when user clicks on a selector checkbox, update the total owed
871 var updateSelected = function() {
874 dojo.query('[name=selector]', this.finesTbody),
877 total += Number(input.getAttribute('balance_owed'));
881 total = total.toFixed(2);
882 dojo.byId('oils-selfck-selected-total').innerHTML =
883 dojo.string.substitute(localeStrings.TOTAL_FINES_SELECTED, [total]);
886 // wire up the batch on/off selector
887 var sel = dojo.byId('oils-selfck-fines-selector');
888 sel.onchange = function() {
890 dojo.query('[name=selector]', this.finesTbody),
892 input.checked = sel.checked;
898 var handler = function(dataList) {
900 self.finesCount = dataList.length;
901 self.finesData = dataList;
903 for(var i in dataList) {
905 var data = dataList[i];
906 var row = self.finesTemplate.cloneNode(true);
907 var type = data.transaction.xact_type();
909 if(type == 'circulation') {
910 self.byName(row, 'type').innerHTML = type;
911 self.byName(row, 'details').innerHTML = data.record.title();
913 } else if(type == 'grocery') {
914 self.byName(row, 'type').innerHTML = localeStrings.MISCELLANEOUS; // Go ahead and head off any confusion around "grocery".
915 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
918 self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
919 self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
920 self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
923 var selector = self.byName(row, 'selector')
924 selector.onchange = updateSelected;
925 selector.setAttribute('xact', data.transaction.id());
926 selector.setAttribute('balance_owed', data.transaction.balance_owed());
927 selector.checked = true;
929 self.finesTbody.appendChild(row);
936 fieldmapper.standardRequest(
937 ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
939 params : [this.authtoken, this.patron.id()],
940 oncomplete : function(r) {
941 progressDialog.hide();
942 handler(openils.Util.readResponse(r));
948 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
950 var resp = fieldmapper.standardRequest(
951 ['open-ils.circ', 'open-ils.circ.transit.abort'],
952 {params : [this.authtoken, {barcode : barcode}]}
955 // resp == 1 on success
956 if(openils.Event.parse(resp))
959 var resp = fieldmapper.standardRequest(
960 ['open-ils.circ', 'open-ils.circ.checkin.override'],
963 patron_id : this.patron.id(),
964 copy_barcode : barcode,
970 if(!resp.length) resp = [resp];
971 for(var i = 0; i < resp.length; i++) {
972 var tc = openils.Event.parse(resp[i]).textcode;
973 if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
984 * Check out a single item. If the item is already checked
985 * out to the patron, redirect to renew()
987 SelfCheckManager.prototype.checkout = function(barcode, override) {
992 this.prevCirc = null;
995 this.updateScanbox(null, true);
999 if(this.mockCheckouts) {
1000 // if we're in mock-checkout mode, just insert another
1001 // fake circ into the table and get out of here.
1002 this.displayCheckout(this.mockCheckout, 'checkout');
1006 // TODO see if it's a patron barcode
1007 // TODO see if this item has already been checked out in this session
1009 var method = 'open-ils.circ.checkout.full';
1010 if(override) method += '.override';
1012 console.log("Checkout out item " + barcode + " with method " + method);
1014 var result = fieldmapper.standardRequest(
1015 ['open-ils.circ', method],
1018 patron_id : this.patron.id(),
1019 copy_barcode : barcode
1024 var stat = this.handleXactResult('checkout', barcode, result);
1027 this.checkout(barcode, true);
1028 } else if(stat.doOver) {
1029 this.checkout(barcode);
1030 } else if(stat.renew) {
1031 this.renew(barcode);
1035 SelfCheckManager.prototype.failPartMessage = function(result) {
1036 if (result.payload && result.payload.fail_part) {
1037 var stringKey = "FAIL_PART_" +
1038 result.payload.fail_part.replace(/\./g, "_");
1039 return localeStrings[stringKey];
1045 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
1047 var displayText = '';
1049 // If true, the display message is important enough to pop up. Whether or not
1050 // an alert() actually occurs, depends on org unit settings
1052 var sound = ''; // sound file reference
1053 var payload = result.payload || {};
1054 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
1055 var blockStatuses = this.orgSettings[SET_BLOCK_CHECKOUT_ON_COPY_STATUS];
1057 if(result.textcode == 'NO_SESSION') {
1059 return this.logoutStaff();
1061 } else if(result.textcode == 'SUCCESS') {
1063 if(action == 'checkout') {
1065 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
1066 this.displayCheckout(result, 'checkout');
1068 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
1069 // A hold was fulfilled, update the hold numbers in the circ summary
1070 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
1071 this.holdsSummary = null;
1072 this.updateHoldsSummary();
1075 this.updateCircSummary(true);
1077 } else if(action == 'renew') {
1079 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
1080 this.displayCheckout(result, 'renew');
1083 this.checkouts.push({circ : result.payload.circ.id()});
1084 sound = 'checkout-success';
1085 this.updateScanBox();
1087 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
1089 // Server says the item is already checked out. If it's checked out to the
1090 // current user, we may need to renew it.
1092 if(payload.old_circ) {
1095 old_circ refers to the previous checkout IFF it's for the same user.
1096 If no auto-renew interval is not defined, assume we should renew it
1097 If an auto-renew interval is defined and the payload comes back with
1098 auto_renew set to true, do the renewal. Otherwise, let the patron know
1099 the item is already checked out to them. */
1101 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
1102 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
1103 this.prevCirc = payload.old_circ.id();
1104 return { renew : true };
1108 sound = 'checkout-failure';
1109 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
1113 if( // copy is marked lost. if configured to do so, check it in and try again.
1114 result.payload.copy &&
1115 result.payload.copy.status() == /* LOST */ 3 &&
1116 overrideEvents && overrideEvents.length &&
1117 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
1119 if(this.checkin(item)) {
1120 return { doOver : true };
1125 // item is checked out to some other user
1127 sound = 'checkout-failure';
1128 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1131 this.updateScanBox({select:true});
1136 if(overrideEvents && overrideEvents.length) {
1138 // see if the events we received are all in the list of
1139 // events to override
1141 if(!result.length) result = [result];
1143 var override = true;
1144 for(var i = 0; i < result.length; i++) {
1146 var match = overrideEvents.filter(function(e) { return (e == result[i].textcode); })[0];
1153 if(result[i].textcode == 'COPY_NOT_AVAILABLE' && blockStatuses && blockStatuses.length) {
1155 var stat = result[i].payload.status(); // copy status
1156 if(typeof stat == 'object') stat = stat.id();
1158 var match2 = blockStatuses.filter(function(e) { return (e == stat); })[0];
1160 if(match2) { // copy is in a blocked status
1166 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1167 // to override a transit, we have to abort the transit and check it in first
1168 if(this.checkin(item, true)) {
1169 return { doOver : true };
1177 return { override : true };
1180 this.updateScanBox({select : true});
1182 sound = 'checkout-failure';
1184 if(action == 'renew')
1185 this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1190 switch(result.textcode) {
1192 // TODO custom handler for blocking penalties
1194 case 'MAX_RENEWALS_REACHED' :
1195 displayText = dojo.string.substitute(
1196 localeStrings.MAX_RENEWALS, [item]);
1199 case 'ITEM_NOT_CATALOGED' :
1200 displayText = dojo.string.substitute(
1201 localeStrings.ITEM_NOT_CATALOGED, [item]);
1204 case 'OPEN_CIRCULATION_EXISTS' :
1205 displayText = dojo.string.substitute(
1206 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1211 console.error('Unhandled event ' + result.textcode);
1213 if (!(displayText = this.failPartMessage(result))) {
1214 if (action == 'checkout' || action == 'renew') {
1215 displayText = dojo.string.substitute(
1216 localeStrings.GENERIC_CIRC_FAILURE, [item]);
1218 displayText = dojo.string.substitute(
1219 localeStrings.UNKNOWN_ERROR, [result.textcode]);
1225 this.handleAlert(displayText, popup, sound);
1233 SelfCheckManager.prototype.renew = function(barcode, override) {
1235 var method = 'open-ils.circ.renew';
1236 if(override) method += '.override';
1238 console.log("Renewing item " + barcode + " with method " + method);
1240 var result = fieldmapper.standardRequest(
1241 ['open-ils.circ', method],
1244 patron_id : this.patron.id(),
1245 copy_barcode : barcode
1250 console.log(js2JSON(result));
1252 var stat = this.handleXactResult('renew', barcode, result);
1255 this.renew(barcode, true);
1259 * Display the result of a checkout or renewal in the items out table
1261 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1263 var copy = evt.payload.copy;
1264 var record = evt.payload.record;
1265 var circ = evt.payload.circ;
1266 var row = this.circTemplate.cloneNode(true);
1268 if(record.doc_id()) {
1269 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/r/' + record.doc_id());
1272 this.byName(row, 'barcode').innerHTML = copy.barcode();
1273 this.byName(row, 'title').innerHTML = record.title();
1274 this.byName(row, 'author').innerHTML = record.author();
1275 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1276 openils.Util.show(this.byName(row, type));
1278 var date = dojo.date.stamp.fromISOString(circ.due_date());
1279 this.byName(row, 'due_date').innerHTML =
1280 dojo.date.locale.format(date, {selector : 'date'});
1282 // put new circs at the top of the list
1283 var tbody = this.circTbody;
1284 if(itemsOut) tbody = this.itemsOutTbody;
1285 tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1289 SelfCheckManager.prototype.byName = function(node, name) {
1290 return dojo.query('[name=' + name+']', node)[0];
1294 SelfCheckManager.prototype.initPrinter = function() {
1295 try { // Mozilla only
1296 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1297 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1298 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1299 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1300 var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1302 pref.setBoolPref('print.always_print_silent', true);
1304 console.log("Unable to initialize auto-printing");
1309 * Print a receipt for this session's checkouts
1311 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1314 var circCtx = []; // circ context data. in this case, renewal_failure info
1316 // collect the circs and failure info
1320 circIds.push(blob.circ);
1321 circCtx.push({renewal_failure:blob.renewal_failure});
1329 'format.selfcheck.checkout',
1336 fieldmapper.standardRequest(
1337 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1341 oncomplete : function(r) {
1342 var resp = openils.Util.readResponse(r);
1343 var output = resp.template_output();
1345 self.printData(output.data(), self.checkouts.length, callback);
1347 var error = resp.error_output();
1349 throw new Error("Error creating receipt: " + error.data());
1351 throw new Error("No receipt data returned from server");
1359 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1361 var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1,chrome');
1362 win.document.body.innerHTML = data;
1366 * There is no way to know when the browser is done printing.
1367 * Make a best guess at when to close the print window by basing
1368 * the setTimeout wait on the number of items to be printed plus
1371 var sleepTime = 1000;
1373 sleepTime += (numItems / 2) * 1000;
1377 win.close(); // close the print window
1379 callback(); // fire optional post-print callback
1387 * Print a receipt for this user's items out
1389 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1391 if(!this.itemsOut.length) return;
1393 progressDialog.show(true);
1399 'format.selfcheck.items_out',
1405 fieldmapper.standardRequest(
1406 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1410 oncomplete : function(r) {
1411 progressDialog.hide();
1412 var resp = openils.Util.readResponse(r);
1413 var output = resp.template_output();
1415 self.printData(output.data(), self.itemsOut.length, callback);
1417 var error = resp.error_output();
1419 throw new Error("Error creating receipt: " + error.data());
1421 throw new Error("No receipt data returned from server");
1430 * Print a receipt for this user's items out
1432 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1434 if(!this.holds.length) return;
1436 progressDialog.show(true);
1441 dojo.forEach(this.holds,
1443 holdIds.push(data.hold.id());
1444 if(data.status == 4) {
1445 holdData.push({ready : true});
1448 queue_position : data.queue_position,
1449 potential_copies : data.potential_copies
1459 'format.selfcheck.holds',
1466 fieldmapper.standardRequest(
1467 ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1471 oncomplete : function(r) {
1472 progressDialog.hide();
1473 var resp = openils.Util.readResponse(r);
1474 var output = resp.template_output();
1476 self.printData(output.data(), self.holds.length, callback);
1478 var error = resp.error_output();
1480 throw new Error("Error creating receipt: " + error.data());
1482 throw new Error("No receipt data returned from server");
1491 SelfCheckManager.prototype.printPaymentReceipt = function(response, callback) {
1494 progressDialog.show(true);
1496 fieldmapper.standardRequest(
1497 ['open-ils.circ', 'open-ils.circ.money.payment_receipt.print'],
1500 params : [this.authtoken, response.payments],
1501 oncomplete : function(r) {
1502 var resp = openils.Util.readResponse(r);
1503 var output = resp.template_output();
1504 progressDialog.hide();
1506 self.printData(output.data(), 1, callback);
1508 var error = resp.error_output();
1510 throw new Error("Error creating receipt: " + error.data());
1512 throw new Error("No receipt data returned from server");
1521 * Print a receipt for this user's items out
1523 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1525 progressDialog.show(true);
1531 'format.selfcheck.fines',
1537 fieldmapper.standardRequest(
1538 ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1542 oncomplete : function(r) {
1543 progressDialog.hide();
1544 var resp = openils.Util.readResponse(r);
1545 var output = resp.template_output();
1547 self.printData(output.data(), self.finesCount, callback);
1549 var error = resp.error_output();
1551 throw new Error("Error creating receipt: " + error.data());
1553 throw new Error("No receipt data returned from server");
1565 * Logout the patron and return to the login page
1567 SelfCheckManager.prototype.logoutPatron = function(print) {
1568 progressDialog.show(true); // prevent patron from clicking logout link twice
1569 if(print && this.checkouts.length) {
1570 this.printSessionReceipt(
1572 location.href = location.href;
1576 location.href = location.href;
1582 * Fire up the manager on page load
1584 openils.Util.addOnLoad(
1586 new SelfCheckManager().init();