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;
105 // During renewals, keep track of the ID of the previous circulation.
106 // Previous circ is used for tracking failed renewals (for receipts).
107 this.prevCirc = null;
109 // current item barcode
110 this.itemBarcode = null;
112 // are we currently performing a renewal?
113 this.isRenewal = false;
115 // dict of org unit settings for "here"
116 this.orgSettings = {};
118 // Construct a mock checkout for debugging purposes
119 if(this.mockCheckouts = this.cgi.param('mock-circ')) {
121 this.mockCheckout = {
123 record : new fieldmapper.mvr(),
124 copy : new fieldmapper.acp(),
125 circ : new fieldmapper.circ()
129 this.mockCheckout.payload.record.title('Jazz improvisation for guitar');
130 this.mockCheckout.payload.record.author('Wise, Les');
131 this.mockCheckout.payload.record.isbn('0634033565');
132 this.mockCheckout.payload.copy.barcode('123456789');
133 this.mockCheckout.payload.circ.renewal_remaining(1);
134 this.mockCheckout.payload.circ.parent_circ(1);
135 this.mockCheckout.payload.circ.due_date('2012-12-21');
141 SelfCheckManager.prototype.setupStaffLogin = function(verify) {
143 if(verify) oilsSetupUser();
144 this.staff = openils.User.user;
145 this.workstation = openils.User.workstation;
146 this.authtoken = openils.User.authtoken;
152 * Fetch the org-unit settings, initialize the display, etc.
154 SelfCheckManager.prototype.init = function() {
156 this.setupStaffLogin();
157 this.loadOrgSettings();
159 this.circTbody = dojo.byId('oils-selfck-circ-tbody');
160 this.itemsOutTbody = dojo.byId('oils-selfck-circ-out-tbody');
162 // workstation is required but none provided
163 if(this.orgSettings[SET_WORKSTATION_REQUIRED] && !this.workstation) {
164 if(confirm(dojo.string.substitute(localeStrings.WORKSTATION_REQUIRED))) {
165 this.registerWorkstation();
171 // connect onclick handlers to the various navigation links
173 'oils-selfck-hold-details-link' : function() { self.drawHoldsPage(); },
174 'oils-selfck-view-fines-link' : function() { self.drawFinesPage(); },
175 'oils-selfck-pay-fines-link' : function() {
176 self.goToTab("payment");
177 self.drawPayFinesPage(
179 self.getSelectedFinesTotal(),
180 self.getSelectedFineTransactions(),
182 var evt = openils.Event.parse(resp);
184 var message = evt + '';
185 if(evt.textcode == 'CREDIT_PROCESSOR_DECLINED_TRANSACTION' && evt.payload)
186 message += '\n' + evt.payload.error_message;
187 if(evt.textcode == 'INVALID_USER_XACT_ID')
188 message += '\n' + localeStrings.PAYMENT_INVALID_USER_XACT_ID;
189 self.handleAlert(message, true, 'payment-failure');
193 self.patron.last_xact_id(resp.last_xact_id); // update to match latest from server
194 self.printPaymentReceipt(
197 self.updateFinesSummary();
198 self.drawFinesPage();
204 'oils-selfck-nav-home' : function() { self.drawCircPage(); },
205 'oils-selfck-nav-logout' : function() { self.logoutPatron(); },
206 'oils-selfck-nav-logout-print' : function() { self.logoutPatron(true); },
207 'oils-selfck-items-out-details-link' : function() { self.drawItemsOutPage(); },
208 'oils-selfck-print-list-link' : function() { self.printList(); }
211 for(var id in linkHandlers)
212 dojo.connect(dojo.byId(id), 'onclick', linkHandlers[id]);
215 if(this.cgi.param('patron')) {
217 // Patron barcode via cgi param. Mainly used for debugging and
218 // only works if password is not required by policy
219 this.loginPatron(this.cgi.param('patron'));
222 this.drawLoginPage();
226 * To test printing, pass a URL param of 'testprint'. The value for the param
227 * should be a JSON string like so: [{circ:<circ_id>}, ...]
229 var testPrint = this.cgi.param('testprint');
231 this.checkouts = JSON2js(testPrint);
232 this.printSessionReceipt();
238 SelfCheckManager.prototype.getSelectedFinesTotal = function() {
241 dojo.query("[name=selector]", this.finesTbody),
244 total += Number(input.getAttribute("balance_owed"));
247 return total.toFixed(2);
250 SelfCheckManager.prototype.getSelectedFineTransactions = function() {
251 return dojo.query("[name=selector]", this.finesTbody).
252 filter(function (o) { return o.checked }).
256 o.getAttribute("xact"),
257 Number(o.getAttribute("balance_owed")).toFixed(2)
264 * Registers a new workstion
266 SelfCheckManager.prototype.registerWorkstation = function() {
268 oilsSelfckWsDialog.show();
270 new openils.User().buildPermOrgSelector(
271 'REGISTER_WORKSTATION',
272 oilsSelfckWsLocSelector,
278 dojo.connect(oilsSelfckWsSubmit, 'onClick',
281 oilsSelfckWsDialog.hide();
282 var name = oilsSelfckWsLocSelector.attr('displayedValue') + '-' + oilsSelfckWsName.attr('value');
284 var res = fieldmapper.standardRequest(
285 ['open-ils.actor', 'open-ils.actor.workstation.register'],
287 self.authtoken, name, oilsSelfckWsLocSelector.attr('value')
292 if(evt = openils.Event.parse(res)) {
293 if(evt.textcode == 'WORKSTATION_NAME_EXISTS') {
294 if(confirm(localeStrings.WORKSTATION_EXISTS)) {
295 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
297 self.registerWorkstation();
304 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
311 * Loads the org unit settings
313 SelfCheckManager.prototype.loadOrgSettings = function() {
315 var settings = fieldmapper.aou.fetchOrgSettingBatch(
316 this.staff.ws_ou(), [
321 SET_AUTO_OVERRIDE_EVENTS,
322 SET_BLOCK_CHECKOUT_ON_COPY_STATUS,
323 SET_PATRON_PASSWORD_REQUIRED,
324 SET_AUTO_RENEW_INTERVAL,
325 SET_WORKSTATION_REQUIRED,
326 SET_CC_PAYMENT_ALLOWED
332 this.orgSettings[k] = settings[k].value;
335 if(settings[SET_BARCODE_REGEX])
336 this.patronBarcodeRegex = new RegExp(settings[SET_BARCODE_REGEX].value);
338 // Subtract the timeout warning interval from the configured timeout
339 // so that when taken together they add up to the configured amount.
340 if(settings[SET_PATRON_TIMEOUT]) {
342 (parseInt(settings[SET_PATRON_TIMEOUT].value) * 1000)
343 - patronTimeoutWarning;
347 SelfCheckManager.prototype.drawLoginPage = function() {
350 var bcHandler = function(barcode_or_usrname) {
351 // handle patron barcode/usrname entry
353 if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
355 // password is required. wire up the scan box to read it
357 msg : localeStrings.ENTER_PASSWORD,
358 handler : function(pw) { self.loginPatron(barcode_or_usrname, pw); },
363 // password is not required, go ahead and login
364 self.loginPatron(barcode_or_usrname);
369 msg : localeStrings.PLEASE_LOGIN,
377 SelfCheckManager.prototype.loginPatron = function(barcode_or_usrname, passwd) {
382 this.setupStaffLogin(true); // verify still valid
386 console.log('testing ' + barcode_or_usrname);
387 if (barcode_or_usrname.match(this.patronBarcodeRegex)) {
388 console.log('barcode');
389 barcode = barcode_or_usrname;
391 console.log('usrname');
392 usrname = barcode_or_usrname;
395 if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
398 // would only happen in dev/debug mode when using the patron= param
399 alert('password required by org setting. remove patron= from URL');
403 // patron password is required. Verify it.
406 new openils.User().auth_verify(
407 { username : usrname, barcode : barcode,
408 type : 'opac', passwd : passwd, agent : 'selfcheck' },
411 self.fetchPatron(barcode, usrname);
414 // auth verify failed
416 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode_or_usrname]),
417 false, 'login-failure'
419 self.drawLoginPage();
425 this.fetchPatron(barcode, usrname);
429 SelfCheckManager.prototype.fetchPatron = function(barcode, usrname) {
431 var patron_id = fieldmapper.standardRequest(
432 ['open-ils.actor', 'open-ils.actor.user.retrieve_id_by_barcode_or_username'],
433 {params : [this.authtoken, barcode, usrname]}
436 // retrieve the fleshed user by id
437 this.patron = fieldmapper.standardRequest(
438 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
439 {params : [this.authtoken, patron_id]}
442 var evt = openils.Event.parse(this.patron);
444 // verify validity of the card used to log in
445 var inactiveCard = false;
449 card = this.patron.cards().filter(
450 function(c) { return (c.barcode() == barcode); })[0];
452 card = this.patron.card();
454 inactiveCard = !openils.Util.isTrue(card.active());
457 if(evt || inactiveCard) {
459 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode || usrname]),
460 false, 'login-failure'
462 this.drawLoginPage();
466 this.handleAlert('', false, 'login-success');
467 dojo.byId('oils-selfck-user-banner').innerHTML =
468 dojo.string.substitute(localeStrings.WELCOME_BANNER, [this.patron.first_given_name()]);
474 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
476 console.log("Handling alert " + message);
478 dojo.byId('oils-selfck-status-div').innerHTML = message;
481 openils.Util.addCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
483 openils.Util.removeCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
485 if(shouldPopup && this.orgSettings[SET_ALERT_POPUP])
488 if(sound && this.orgSettings[SET_ALERT_SOUND])
489 openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
494 * Manages the main input box
495 * @param msg The context message to display with the box
496 * @param clearOnly Don't update the context message, just clear the value and re-focus
497 * @param handler Optional "on-enter" handler.
499 SelfCheckManager.prototype.updateScanBox = function(args) {
503 selfckScanBox.domNode.select();
505 selfckScanBox.attr('value', '');
509 selfckScanBox.domNode.setAttribute('type', 'password');
511 selfckScanBox.domNode.setAttribute('type', '');
515 selfckScanBox.attr('value', args.value);
518 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
520 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
521 dojo.disconnect(selfckScanBox._lastHandler);
525 selfckScanBox._lastHandler = dojo.connect(
529 if(e.keyCode != dojo.keys.ENTER)
531 args.handler(selfckScanBox.attr('value'));
536 selfckScanBox.focus();
540 * Sets up the checkout/renewal interface
542 SelfCheckManager.prototype.drawCircPage = function() {
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) {
812 // store hold data to pass along to receipt printing function
813 this.holds.push(data);
815 var row = this.holdTemplate.cloneNode(true);
817 if(data.mvr.isbn()) {
818 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/r/' + data.mvr.doc_id());
821 this.byName(row, 'title').innerHTML = data.mvr.title();
822 this.byName(row, 'author').innerHTML = data.mvr.author();
824 if(data.status == 4) {
826 // hold is ready for pickup
827 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
831 // hold is still pending
832 this.byName(row, 'status').innerHTML =
833 dojo.string.substitute(
834 localeStrings.HOLD_STATUS_WAITING,
835 [data.queue_position, data.potential_copies]
839 // find the correct place the table to slot in the hold based on queue position
841 var position = (data.status == 4) ? 0 : data.queue_position;
842 row.setAttribute('position', position);
844 for(var i = 0; i < this.holdTbody.childNodes.length; i++) {
845 var node = this.holdTbody.childNodes[i];
846 if(Number(node.getAttribute('position')) >= position) {
847 this.holdTbody.insertBefore(row, node);
852 this.holdTbody.appendChild(row);
856 SelfCheckManager.prototype.drawFinesPage = function() {
858 // TODO add option to hid scanBox
859 // this.updateScanBox(...)
861 this.goToTab('fines');
862 progressDialog.show(true);
864 if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
865 openils.Util.show('oils-selfck-pay-fines-link', 'inline');
868 this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
869 if(!this.finesTemplate)
870 this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
871 while(this.finesTbody.childNodes[0])
872 this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
874 // when user clicks on a selector checkbox, update the total owed
875 var updateSelected = function() {
878 dojo.query('[name=selector]', this.finesTbody),
881 total += Number(input.getAttribute('balance_owed'));
885 total = total.toFixed(2);
886 dojo.byId('oils-selfck-selected-total').innerHTML =
887 dojo.string.substitute(localeStrings.TOTAL_FINES_SELECTED, [total]);
890 // wire up the batch on/off selector
891 var sel = dojo.byId('oils-selfck-fines-selector');
892 sel.onchange = function() {
894 dojo.query('[name=selector]', this.finesTbody),
896 input.checked = sel.checked;
902 var handler = function(dataList) {
904 self.finesCount = dataList.length;
905 self.finesData = dataList;
907 for(var i in dataList) {
909 var data = dataList[i];
910 var row = self.finesTemplate.cloneNode(true);
911 var type = data.transaction.xact_type();
913 if(type == 'circulation') {
914 self.byName(row, 'type').innerHTML = type;
915 self.byName(row, 'details').innerHTML = data.record.title();
917 } else if(type == 'grocery') {
918 self.byName(row, 'type').innerHTML = localeStrings.MISCELLANEOUS; // Go ahead and head off any confusion around "grocery".
919 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
922 self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
923 self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
924 self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
927 var selector = self.byName(row, 'selector')
928 selector.onchange = updateSelected;
929 selector.setAttribute('xact', data.transaction.id());
930 selector.setAttribute('balance_owed', data.transaction.balance_owed());
931 selector.checked = true;
933 self.finesTbody.appendChild(row);
940 fieldmapper.standardRequest(
941 ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
943 params : [this.authtoken, this.patron.id()],
944 oncomplete : function(r) {
945 progressDialog.hide();
946 handler(openils.Util.readResponse(r));
952 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
954 var resp = fieldmapper.standardRequest(
955 ['open-ils.circ', 'open-ils.circ.transit.abort'],
956 {params : [this.authtoken, {barcode : barcode}]}
959 // resp == 1 on success
960 if(openils.Event.parse(resp))
963 var resp = fieldmapper.standardRequest(
964 ['open-ils.circ', 'open-ils.circ.checkin.override'],
967 patron_id : this.patron.id(),
968 copy_barcode : barcode,
974 if(!resp.length) resp = [resp];
975 for(var i = 0; i < resp.length; i++) {
976 var tc = openils.Event.parse(resp[i]).textcode;
977 if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
988 * Check out a single item. If the item is already checked
989 * out to the patron, redirect to renew()
991 SelfCheckManager.prototype.checkout = function(barcode, override) {
996 this.prevCirc = null;
999 this.updateScanbox(null, true);
1003 if(this.mockCheckouts) {
1004 // if we're in mock-checkout mode, just insert another
1005 // fake circ into the table and get out of here.
1006 this.displayCheckout(this.mockCheckout, 'checkout');
1010 // TODO see if it's a patron barcode
1011 // TODO see if this item has already been checked out in this session
1013 var method = 'open-ils.circ.checkout.full';
1014 if(override) method += '.override';
1016 console.log("Checkout out item " + barcode + " with method " + method);
1018 var result = fieldmapper.standardRequest(
1019 ['open-ils.circ', method],
1022 patron_id : this.patron.id(),
1023 copy_barcode : barcode
1028 var stat = this.handleXactResult('checkout', barcode, result);
1031 this.checkout(barcode, true);
1032 } else if(stat.doOver) {
1033 this.checkout(barcode);
1034 } else if(stat.renew) {
1035 this.renew(barcode);
1039 SelfCheckManager.prototype.failPartMessage = function(result) {
1040 if (result.payload && result.payload.fail_part) {
1041 var stringKey = "FAIL_PART_" +
1042 result.payload.fail_part.replace(/\./g, "_");
1043 return localeStrings[stringKey];
1049 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
1051 var displayText = '';
1053 // If true, the display message is important enough to pop up. Whether or not
1054 // an alert() actually occurs, depends on org unit settings
1056 var sound = ''; // sound file reference
1057 var payload = result.payload || {};
1058 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
1059 var blockStatuses = this.orgSettings[SET_BLOCK_CHECKOUT_ON_COPY_STATUS];
1061 if(result.textcode == 'NO_SESSION') {
1063 return this.logoutStaff();
1065 } else if(result.textcode == 'SUCCESS') {
1067 if(action == 'checkout') {
1069 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
1070 this.displayCheckout(result, 'checkout');
1072 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
1073 // A hold was fulfilled, update the hold numbers in the circ summary
1074 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
1075 this.holdsSummary = null;
1076 this.updateHoldsSummary();
1079 this.updateCircSummary(true);
1081 } else if(action == 'renew') {
1083 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
1084 this.displayCheckout(result, 'renew');
1087 this.checkouts.push({circ : result.payload.circ.id()});
1088 sound = 'checkout-success';
1089 this.updateScanBox();
1091 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
1093 // Server says the item is already checked out. If it's checked out to the
1094 // current user, we may need to renew it.
1096 if(payload.old_circ) {
1099 old_circ refers to the previous checkout IFF it's for the same user.
1100 If no auto-renew interval is not defined, assume we should renew it
1101 If an auto-renew interval is defined and the payload comes back with
1102 auto_renew set to true, do the renewal. Otherwise, let the patron know
1103 the item is already checked out to them. */
1105 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
1106 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
1107 this.prevCirc = payload.old_circ.id();
1108 return { renew : true };
1112 sound = 'checkout-failure';
1113 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
1117 if( // copy is marked lost. if configured to do so, check it in and try again.
1118 result.payload.copy &&
1119 result.payload.copy.status() == /* LOST */ 3 &&
1120 overrideEvents && overrideEvents.length &&
1121 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
1123 if(this.checkin(item)) {
1124 return { doOver : true };
1129 // item is checked out to some other user
1131 sound = 'checkout-failure';
1132 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1135 this.updateScanBox({select:true});
1140 if(overrideEvents && overrideEvents.length) {
1142 // see if the events we received are all in the list of
1143 // events to override
1145 if(!result.length) result = [result];
1147 var override = true;
1148 for(var i = 0; i < result.length; i++) {
1150 var match = overrideEvents.filter(function(e) { return (e == result[i].textcode); })[0];
1157 if(result[i].textcode == 'COPY_NOT_AVAILABLE' && blockStatuses && blockStatuses.length) {
1159 var stat = result[i].payload.status(); // copy status
1160 if(typeof stat == 'object') stat = stat.id();
1162 var match2 = blockStatuses.filter(function(e) { return (e == stat); })[0];
1164 if(match2) { // copy is in a blocked status
1170 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1171 // to override a transit, we have to abort the transit and check it in first
1172 if(this.checkin(item, true)) {
1173 return { doOver : true };
1181 return { override : true };
1184 this.updateScanBox({select : true});
1186 sound = 'checkout-failure';
1188 if(action == 'renew')
1189 this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1194 switch(result.textcode) {
1196 // TODO custom handler for blocking penalties
1198 case 'MAX_RENEWALS_REACHED' :
1199 displayText = dojo.string.substitute(
1200 localeStrings.MAX_RENEWALS, [item]);
1203 case 'ITEM_NOT_CATALOGED' :
1204 displayText = dojo.string.substitute(
1205 localeStrings.ITEM_NOT_CATALOGED, [item]);
1208 case 'OPEN_CIRCULATION_EXISTS' :
1209 displayText = dojo.string.substitute(
1210 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1215 console.error('Unhandled event ' + result.textcode);
1217 if (!(displayText = this.failPartMessage(result))) {
1218 if (action == 'checkout' || action == 'renew') {
1219 displayText = dojo.string.substitute(
1220 localeStrings.GENERIC_CIRC_FAILURE, [item]);
1222 displayText = dojo.string.substitute(
1223 localeStrings.UNKNOWN_ERROR, [result.textcode]);
1229 this.handleAlert(displayText, popup, sound);
1237 SelfCheckManager.prototype.renew = function(barcode, override) {
1239 var method = 'open-ils.circ.renew';
1240 if(override) method += '.override';
1242 console.log("Renewing item " + barcode + " with method " + method);
1244 var result = fieldmapper.standardRequest(
1245 ['open-ils.circ', method],
1248 patron_id : this.patron.id(),
1249 copy_barcode : barcode
1254 console.log(js2JSON(result));
1256 var stat = this.handleXactResult('renew', barcode, result);
1259 this.renew(barcode, true);
1263 * Display the result of a checkout or renewal in the items out table
1265 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1267 var copy = evt.payload.copy;
1268 var record = evt.payload.record;
1269 var circ = evt.payload.circ;
1270 var row = this.circTemplate.cloneNode(true);
1272 if(record.doc_id()) {
1273 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/r/' + record.doc_id());
1276 this.byName(row, 'barcode').innerHTML = copy.barcode();
1277 this.byName(row, 'title').innerHTML = record.title();
1278 this.byName(row, 'author').innerHTML = record.author();
1279 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1280 openils.Util.show(this.byName(row, type));
1282 var date = dojo.date.stamp.fromISOString(circ.due_date());
1283 this.byName(row, 'due_date').innerHTML =
1284 dojo.date.locale.format(date, {selector : 'date'});
1286 // put new circs at the top of the list
1287 var tbody = this.circTbody;
1288 if(itemsOut) tbody = this.itemsOutTbody;
1289 tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1293 SelfCheckManager.prototype.byName = function(node, name) {
1294 return dojo.query('[name=' + name+']', node)[0];
1298 SelfCheckManager.prototype.initPrinter = function() {
1299 try { // Mozilla only
1300 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1301 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1302 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1303 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1304 var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1306 pref.setBoolPref('print.always_print_silent', true);
1308 console.log("Unable to initialize auto-printing");
1313 * Print a receipt for this session's checkouts
1315 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1318 var circCtx = []; // circ context data. in this case, renewal_failure info
1320 // collect the circs and failure info
1324 circIds.push(blob.circ);
1325 circCtx.push({renewal_failure:blob.renewal_failure});
1333 'format.selfcheck.checkout',
1340 fieldmapper.standardRequest(
1341 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1345 oncomplete : function(r) {
1346 var resp = openils.Util.readResponse(r);
1347 var output = resp.template_output();
1349 self.printData(output.data(), self.checkouts.length, callback);
1351 var error = resp.error_output();
1353 throw new Error("Error creating receipt: " + error.data());
1355 throw new Error("No receipt data returned from server");
1363 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1365 var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1,chrome');
1366 win.document.body.innerHTML = data;
1370 * There is no way to know when the browser is done printing.
1371 * Make a best guess at when to close the print window by basing
1372 * the setTimeout wait on the number of items to be printed plus
1375 var sleepTime = 1000;
1377 sleepTime += (numItems / 2) * 1000;
1381 win.close(); // close the print window
1383 callback(); // fire optional post-print callback
1391 * Print a receipt for this user's items out
1393 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1395 if(!this.itemsOut.length) return;
1397 progressDialog.show(true);
1403 'format.selfcheck.items_out',
1409 fieldmapper.standardRequest(
1410 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1414 oncomplete : function(r) {
1415 progressDialog.hide();
1416 var resp = openils.Util.readResponse(r);
1417 var output = resp.template_output();
1419 self.printData(output.data(), self.itemsOut.length, callback);
1421 var error = resp.error_output();
1423 throw new Error("Error creating receipt: " + error.data());
1425 throw new Error("No receipt data returned from server");
1434 * Print a receipt for this user's holds
1436 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1438 if(!this.holds.length) return;
1440 progressDialog.show(true);
1445 dojo.forEach(this.holds,
1447 holdIds.push(data.hold.id());
1449 //get pickup library info
1450 var pu = fieldmapper.standardRequest(['open-ils.actor','open-ils.actor.org_unit.retrieve'],[null,data.hold.pickup_lib()]);
1452 if(data.status == 4) {
1455 item_title : data.mvr.title(),
1456 item_author : data.mvr.author(),
1457 pickup_lib : pu.name()
1461 queue_position : data.queue_position,
1462 potential_copies : data.potential_copies,
1463 item_title : data.mvr.title(),
1464 item_author : data.mvr.author(),
1465 pickup_lib : pu.name()
1475 'format.selfcheck.holds',
1482 fieldmapper.standardRequest(
1483 ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1487 oncomplete : function(r) {
1488 progressDialog.hide();
1489 var resp = openils.Util.readResponse(r);
1490 var output = resp.template_output();
1492 self.printData(output.data(), self.holds.length, callback);
1494 var error = resp.error_output();
1496 throw new Error("Error creating receipt: " + error.data());
1498 throw new Error("No receipt data returned from server");
1507 SelfCheckManager.prototype.printPaymentReceipt = function(response, callback) {
1510 progressDialog.show(true);
1512 fieldmapper.standardRequest(
1513 ['open-ils.circ', 'open-ils.circ.money.payment_receipt.print'],
1516 params : [this.authtoken, response.payments],
1517 oncomplete : function(r) {
1518 var resp = openils.Util.readResponse(r);
1519 var output = resp.template_output();
1520 progressDialog.hide();
1522 self.printData(output.data(), 1, callback);
1524 var error = resp.error_output();
1526 throw new Error("Error creating receipt: " + error.data());
1528 throw new Error("No receipt data returned from server");
1537 * Print a receipt for this user's fines
1539 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1541 if(!this.creditPayableBalance.length) return;
1542 progressDialog.show(true);
1548 'format.selfcheck.fines',
1554 fieldmapper.standardRequest(
1555 ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1559 oncomplete : function(r) {
1560 progressDialog.hide();
1561 var resp = openils.Util.readResponse(r);
1562 var output = resp.template_output();
1564 self.printData(output.data(), self.finesCount, callback);
1566 var error = resp.error_output();
1568 throw new Error("Error creating receipt: " + error.data());
1570 throw new Error("No receipt data returned from server");
1582 * Logout the patron and return to the login page
1584 SelfCheckManager.prototype.logoutPatron = function(print) {
1585 progressDialog.show(true); // prevent patron from clicking logout link twice
1586 if(print && this.checkouts.length) {
1587 this.printSessionReceipt(
1589 location.href = location.href;
1593 location.href = location.href;
1599 * Fire up the manager on page load
1601 openils.Util.addOnLoad(
1603 new SelfCheckManager().init();