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(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 this.patronBarcodeRegex = new RegExp(/^\d/);
338 // this assumes barcodes start with digits
341 // Subtract the timeout warning interval from the configured timeout
342 // so that when taken together they add up to the configured amount.
343 if(settings[SET_PATRON_TIMEOUT]) {
345 (parseInt(settings[SET_PATRON_TIMEOUT].value) * 1000)
346 - patronTimeoutWarning;
350 SelfCheckManager.prototype.drawLoginPage = function() {
353 var bcHandler = function(barcode_or_usrname) {
354 // handle patron barcode/usrname entry
356 if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
358 // password is required. wire up the scan box to read it
360 msg : localeStrings.ENTER_PASSWORD,
361 handler : function(pw) { self.loginPatron(barcode_or_usrname, pw); },
366 // password is not required, go ahead and login
367 self.loginPatron(barcode_or_usrname);
372 msg : localeStrings.PLEASE_LOGIN,
380 SelfCheckManager.prototype.loginPatron = function(barcode_or_usrname, passwd) {
385 this.setupStaffLogin(true); // verify still valid
389 console.log('testing ' + barcode_or_usrname);
390 if (barcode_or_usrname.match(this.patronBarcodeRegex)) {
391 console.log('barcode');
392 barcode = barcode_or_usrname;
394 console.log('usrname');
395 usrname = barcode_or_usrname;
398 if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
401 // would only happen in dev/debug mode when using the patron= param
402 alert('password required by org setting. remove patron= from URL');
406 // patron password is required. Verify it.
409 new openils.User().auth_verify(
410 { username : usrname, barcode : barcode,
411 type : 'opac', passwd : passwd, agent : 'selfcheck' },
414 self.fetchPatron(barcode, usrname);
417 // auth verify failed
419 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode_or_usrname]),
420 false, 'login-failure'
422 self.drawLoginPage();
428 this.fetchPatron(barcode, usrname);
432 SelfCheckManager.prototype.fetchPatron = function(barcode, usrname) {
434 var patron_id = fieldmapper.standardRequest(
435 ['open-ils.actor', 'open-ils.actor.user.retrieve_id_by_barcode_or_username'],
436 {params : [this.authtoken, barcode, usrname]}
439 // retrieve the fleshed user by id
440 this.patron = fieldmapper.standardRequest(
441 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
442 {params : [this.authtoken, patron_id]}
445 var evt = openils.Event.parse(this.patron);
447 // verify validity of the card used to log in
448 var inactiveCard = false;
452 card = this.patron.cards().filter(
453 function(c) { return (c.barcode() == barcode); })[0];
455 card = this.patron.card();
457 inactiveCard = !openils.Util.isTrue(card.active());
460 if(evt || inactiveCard) {
462 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode || usrname]),
463 false, 'login-failure'
465 this.drawLoginPage();
469 this.handleAlert('', false, 'login-success');
470 dojo.byId('oils-selfck-user-banner').innerHTML =
471 dojo.string.substitute(localeStrings.WELCOME_BANNER, [this.patron.first_given_name()]);
473 if (this.patron.email() && // they have an email address set and ...
474 this.patron.email().match(/.*@.*/).length > 0 // it sorta looks like an email address
476 openils.Util.removeCSSClass( dojo.byId('oils-selfck-receipt-email').parentNode, 'hidden' );
477 if (user_setting_value(this.patron, 'circ.send_email_checkout_receipts') == 'true') // their selected default
478 dojo.byId('oils-selfck-receipt-email').checked = true;
485 function user_setting_value (user, setting) {
487 var list = user.settings().filter(function(s){
488 return s.name() == setting;
491 if (list.length) return list[0].value();
495 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
497 console.log("Handling alert " + message);
499 dojo.byId('oils-selfck-status-div').innerHTML = message;
502 openils.Util.addCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
504 openils.Util.removeCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
506 if(shouldPopup && this.orgSettings[SET_ALERT_POPUP])
509 if(sound && this.orgSettings[SET_ALERT_SOUND])
510 openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
515 * Manages the main input box
516 * @param msg The context message to display with the box
517 * @param clearOnly Don't update the context message, just clear the value and re-focus
518 * @param handler Optional "on-enter" handler.
520 SelfCheckManager.prototype.updateScanBox = function(args) {
524 selfckScanBox.domNode.select();
526 selfckScanBox.attr('value', '');
530 selfckScanBox.domNode.setAttribute('type', 'password');
532 selfckScanBox.domNode.setAttribute('type', '');
536 selfckScanBox.attr('value', args.value);
539 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
541 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
542 dojo.disconnect(selfckScanBox._lastHandler);
546 selfckScanBox._lastHandler = dojo.connect(
550 if(e.keyCode != dojo.keys.ENTER)
552 args.handler(selfckScanBox.attr('value'));
557 selfckScanBox.focus();
561 * Sets up the checkout/renewal interface
563 SelfCheckManager.prototype.drawCircPage = function() {
565 openils.Util.show('oils-selfck-bottom-div');
566 openils.Util.show('oils-selfck-circ-tbody', 'table-row-group');
567 this.goToTab('checkout');
569 while(this.itemsOutTbody.childNodes[0])
570 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
574 msg : localeStrings.ENTER_BARCODE,
575 handler : function(barcode) { self.checkout(barcode); }
578 if(!this.circTemplate)
579 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
582 this.updateFinesSummary();
585 this.updateHoldsSummary();
588 this.updateCircSummary();
590 // render mock checkouts for debugging?
591 if(this.mockCheckouts) {
592 for(var i in [1,2,3])
593 this.displayCheckout(this.mockCheckout, 'checkout');
598 SelfCheckManager.prototype.updateFinesSummary = function() {
602 fieldmapper.standardRequest(
603 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
605 params : [this.authtoken, this.patron.id()],
606 oncomplete : function(r) {
608 var summary = openils.Util.readResponse(r);
610 dojo.byId('oils-selfck-fines-total').innerHTML =
611 dojo.string.substitute(
612 localeStrings.TOTAL_FINES_ACCOUNT,
613 ['<b>' + summary.balance_owed() + '</b>']
616 self.creditPayableBalance = summary.balance_owed();
623 SelfCheckManager.prototype.drawItemsOutPage = function() {
624 openils.Util.hide('oils-selfck-circ-tbody');
626 this.goToTab('items_out');
628 while(this.itemsOutTbody.childNodes[0])
629 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
631 progressDialog.show(true);
634 fieldmapper.standardRequest(
635 ['open-ils.circ', 'open-ils.circ.actor.user.checked_out.atomic'],
638 params : [this.authtoken, this.patron.id()],
639 oncomplete : function(r) {
641 var resp = openils.Util.readResponse(r);
643 var circs = resp.sort(
645 if(a.circ.due_date() > b.circ.due_date())
651 progressDialog.hide();
656 self.itemsOut.push(circ.circ.id());
657 self.displayCheckout(
659 (circ.circ.parent_circ()) ? 'renew' : 'checkout',
670 SelfCheckManager.prototype.goToTab = function(name) {
673 openils.Util.hide('oils-selfck-fines-page');
674 openils.Util.hide('oils-selfck-payment-page');
675 openils.Util.hide('oils-selfck-holds-page');
676 openils.Util.hide('oils-selfck-circ-page');
677 openils.Util.hide('oils-selfck-pay-fines-link');
684 openils.Util.show('oils-selfck-circ-page');
687 openils.Util.show('oils-selfck-circ-page');
690 openils.Util.show('oils-selfck-holds-page');
693 openils.Util.show('oils-selfck-fines-page');
696 openils.Util.show('oils-selfck-payment-page');
702 SelfCheckManager.prototype.printList = function() {
706 switch(this.tabName) {
708 this.printSessionReceipt();
711 this.printItemsOutReceipt();
714 this.printHoldsReceipt();
717 this.printFinesReceipt();
722 SelfCheckManager.prototype.updateHoldsSummary = function() {
724 if(!this.holdsSummary) {
725 var summary = fieldmapper.standardRequest(
726 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
727 {params : [this.authtoken, this.patron.id()]}
730 this.holdsSummary = {};
731 this.holdsSummary.ready = Number(summary['4']);
732 this.holdsSummary.total = 0;
734 for(var i in summary)
735 this.holdsSummary.total += Number(summary[i]);
738 dojo.byId('oils-selfck-holds-total').innerHTML =
739 dojo.string.substitute(
740 localeStrings.TOTAL_HOLDS,
741 ['<b>' + this.holdsSummary.total + '</b>']
744 dojo.byId('oils-selfck-holds-ready').innerHTML =
745 dojo.string.substitute(
746 localeStrings.HOLDS_READY_FOR_PICKUP,
747 ['<b>' + this.holdsSummary.ready + '</b>']
752 SelfCheckManager.prototype.updateCircSummary = function(increment) {
754 if(!this.circSummary) {
756 var summary = fieldmapper.standardRequest(
757 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
758 {params : [this.authtoken, this.patron.id()]}
762 total : Number(summary.out) + Number(summary.overdue),
763 overdue : Number(summary.overdue),
769 // local checkout occurred. Add to the total and the session.
770 this.circSummary.total += 1;
771 this.circSummary.session += 1;
774 dojo.byId('oils-selfck-circ-account-total').innerHTML =
775 dojo.string.substitute(
776 localeStrings.TOTAL_ITEMS_ACCOUNT,
777 ['<b>' + this.circSummary.total + '</b>']
780 dojo.byId('oils-selfck-circ-session-total').innerHTML =
781 dojo.string.substitute(
782 localeStrings.TOTAL_ITEMS_SESSION,
783 ['<b>' + this.circSummary.session + '</b>']
788 SelfCheckManager.prototype.drawHoldsPage = function() {
790 // TODO add option to hid scanBox
791 // this.updateScanBox(...)
793 this.goToTab('holds');
795 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
796 if(!this.holdTemplate)
797 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
798 while(this.holdTbody.childNodes[0])
799 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
801 progressDialog.show(true);
804 fieldmapper.standardRequest( // fetch the hold IDs
806 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
808 params : [this.authtoken, this.patron.id()],
810 oncomplete : function(r) {
811 var ids = openils.Util.readResponse(r);
812 if(!ids || ids.length == 0) {
813 progressDialog.hide();
817 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
818 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve'],
820 params : [self.authtoken, ids],
821 onresponse : function(rr) {
822 progressDialog.hide();
823 self.insertHold(openils.Util.readResponse(rr));
832 SelfCheckManager.prototype.insertHold = function(data) {
834 // store hold data to pass along to receipt printing function
835 this.holds.push(data);
837 var row = this.holdTemplate.cloneNode(true);
839 if(data.mvr.isbn()) {
840 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/r/' + data.mvr.doc_id());
843 this.byName(row, 'title').innerHTML = data.mvr.title();
844 this.byName(row, 'author').innerHTML = data.mvr.author();
846 if(data.status == 4) {
848 // hold is ready for pickup
849 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
853 // hold is still pending
854 this.byName(row, 'status').innerHTML =
855 dojo.string.substitute(
856 localeStrings.HOLD_STATUS_WAITING,
857 [data.queue_position, data.potential_copies]
861 // find the correct place the table to slot in the hold based on queue position
863 var position = (data.status == 4) ? 0 : data.queue_position;
864 row.setAttribute('position', position);
866 for(var i = 0; i < this.holdTbody.childNodes.length; i++) {
867 var node = this.holdTbody.childNodes[i];
868 if(Number(node.getAttribute('position')) >= position) {
869 this.holdTbody.insertBefore(row, node);
874 this.holdTbody.appendChild(row);
878 SelfCheckManager.prototype.drawFinesPage = function() {
880 // TODO add option to hid scanBox
881 // this.updateScanBox(...)
883 this.goToTab('fines');
884 progressDialog.show(true);
886 if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
887 openils.Util.show('oils-selfck-pay-fines-link', 'inline');
890 this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
891 if(!this.finesTemplate)
892 this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
893 while(this.finesTbody.childNodes[0])
894 this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
896 // when user clicks on a selector checkbox, update the total owed
897 var updateSelected = function() {
900 dojo.query('[name=selector]', this.finesTbody),
903 total += Number(input.getAttribute('balance_owed'));
907 total = total.toFixed(2);
908 dojo.byId('oils-selfck-selected-total').innerHTML =
909 dojo.string.substitute(localeStrings.TOTAL_FINES_SELECTED, [total]);
912 // wire up the batch on/off selector
913 var sel = dojo.byId('oils-selfck-fines-selector');
914 sel.onchange = function() {
916 dojo.query('[name=selector]', this.finesTbody),
918 input.checked = sel.checked;
924 var handler = function(dataList) {
926 self.finesCount = dataList.length;
927 self.finesData = dataList;
929 for(var i in dataList) {
931 var data = dataList[i];
932 var row = self.finesTemplate.cloneNode(true);
933 var type = data.transaction.xact_type();
935 if(type == 'circulation') {
936 self.byName(row, 'type').innerHTML = type;
937 self.byName(row, 'details').innerHTML = data.record.title();
939 } else if(type == 'grocery') {
940 self.byName(row, 'type').innerHTML = localeStrings.MISCELLANEOUS; // Go ahead and head off any confusion around "grocery".
941 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
944 self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
945 self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
946 self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
949 var selector = self.byName(row, 'selector')
950 selector.onchange = updateSelected;
951 selector.setAttribute('xact', data.transaction.id());
952 selector.setAttribute('balance_owed', data.transaction.balance_owed());
953 selector.checked = true;
955 self.finesTbody.appendChild(row);
962 fieldmapper.standardRequest(
963 ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
965 params : [this.authtoken, this.patron.id()],
966 oncomplete : function(r) {
967 progressDialog.hide();
968 handler(openils.Util.readResponse(r));
974 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
976 var resp = fieldmapper.standardRequest(
977 ['open-ils.circ', 'open-ils.circ.transit.abort'],
978 {params : [this.authtoken, {barcode : barcode}]}
981 // resp == 1 on success
982 if(openils.Event.parse(resp))
985 var resp = fieldmapper.standardRequest(
986 ['open-ils.circ', 'open-ils.circ.checkin.override'],
989 patron_id : this.patron.id(),
990 copy_barcode : barcode,
996 if(!resp.length) resp = [resp];
997 for(var i = 0; i < resp.length; i++) {
998 var tc = openils.Event.parse(resp[i]).textcode;
999 if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
1010 * Check out a single item. If the item is already checked
1011 * out to the patron, redirect to renew()
1013 SelfCheckManager.prototype.checkout = function(barcode, override) {
1018 this.prevCirc = null;
1021 this.updateScanbox(null, true);
1025 if(this.mockCheckouts) {
1026 // if we're in mock-checkout mode, just insert another
1027 // fake circ into the table and get out of here.
1028 this.displayCheckout(this.mockCheckout, 'checkout');
1032 // TODO see if it's a patron barcode
1033 // TODO see if this item has already been checked out in this session
1035 var method = 'open-ils.circ.checkout.full';
1036 if(override) method += '.override';
1038 console.log("Checkout out item " + barcode + " with method " + method);
1040 var result = fieldmapper.standardRequest(
1041 ['open-ils.circ', method],
1044 patron_id : this.patron.id(),
1045 copy_barcode : barcode
1050 var stat = this.handleXactResult('checkout', barcode, result);
1053 this.checkout(barcode, true);
1054 } else if(stat.doOver) {
1055 this.checkout(barcode);
1056 } else if(stat.renew) {
1057 this.renew(barcode);
1061 SelfCheckManager.prototype.failPartMessage = function(result) {
1062 if (result.payload && result.payload.fail_part) {
1063 var stringKey = "FAIL_PART_" +
1064 result.payload.fail_part.replace(/\./g, "_");
1065 return localeStrings[stringKey];
1071 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
1073 var displayText = '';
1075 // If true, the display message is important enough to pop up. Whether or not
1076 // an alert() actually occurs, depends on org unit settings
1078 var sound = ''; // sound file reference
1079 var payload = result.payload || {};
1080 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
1081 var blockStatuses = this.orgSettings[SET_BLOCK_CHECKOUT_ON_COPY_STATUS];
1083 if(result.textcode == 'NO_SESSION') {
1085 return this.logoutStaff();
1087 } else if(result.textcode == 'SUCCESS') {
1089 if(action == 'checkout') {
1091 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
1092 this.displayCheckout(result, 'checkout');
1094 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
1095 // A hold was fulfilled, update the hold numbers in the circ summary
1096 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
1097 this.holdsSummary = null;
1098 this.updateHoldsSummary();
1101 this.updateCircSummary(true);
1103 } else if(action == 'renew') {
1105 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
1106 this.displayCheckout(result, 'renew');
1109 this.checkouts.push({circ : result.payload.circ.id()});
1110 sound = 'checkout-success';
1111 this.updateScanBox();
1113 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
1115 // Server says the item is already checked out. If it's checked out to the
1116 // current user, we may need to renew it.
1118 if(payload.old_circ) {
1121 old_circ refers to the previous checkout IFF it's for the same user.
1122 If no auto-renew interval is not defined, assume we should renew it
1123 If an auto-renew interval is defined and the payload comes back with
1124 auto_renew set to true, do the renewal. Otherwise, let the patron know
1125 the item is already checked out to them. */
1127 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
1128 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
1129 this.prevCirc = payload.old_circ.id();
1130 return { renew : true };
1134 sound = 'checkout-failure';
1135 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
1139 if( // copy is marked lost. if configured to do so, check it in and try again.
1140 result.payload.copy &&
1141 result.payload.copy.status() == /* LOST */ 3 &&
1142 overrideEvents && overrideEvents.length &&
1143 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
1145 if(this.checkin(item)) {
1146 return { doOver : true };
1151 // item is checked out to some other user
1153 sound = 'checkout-failure';
1154 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1157 this.updateScanBox({select:true});
1162 if(overrideEvents && overrideEvents.length) {
1164 // see if the events we received are all in the list of
1165 // events to override
1167 if(!result.length) result = [result];
1169 var override = true;
1170 for(var i = 0; i < result.length; i++) {
1172 var match = overrideEvents.filter(function(e) { return (e == result[i].textcode); })[0];
1179 if(result[i].textcode == 'COPY_NOT_AVAILABLE' && blockStatuses && blockStatuses.length) {
1181 var stat = result[i].payload.status(); // copy status
1182 if(typeof stat == 'object') stat = stat.id();
1184 var match2 = blockStatuses.filter(function(e) { return (e == stat); })[0];
1186 if(match2) { // copy is in a blocked status
1192 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1193 // to override a transit, we have to abort the transit and check it in first
1194 if(this.checkin(item, true)) {
1195 return { doOver : true };
1203 return { override : true };
1206 this.updateScanBox({select : true});
1208 sound = 'checkout-failure';
1210 if(action == 'renew')
1211 this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1216 switch(result.textcode) {
1218 // TODO custom handler for blocking penalties
1220 case 'MAX_RENEWALS_REACHED' :
1221 displayText = dojo.string.substitute(
1222 localeStrings.MAX_RENEWALS, [item]);
1225 case 'ITEM_NOT_CATALOGED' :
1226 displayText = dojo.string.substitute(
1227 localeStrings.ITEM_NOT_CATALOGED, [item]);
1230 case 'OPEN_CIRCULATION_EXISTS' :
1231 displayText = dojo.string.substitute(
1232 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1237 console.error('Unhandled event ' + result.textcode);
1239 if (!(displayText = this.failPartMessage(result))) {
1240 if (action == 'checkout' || action == 'renew') {
1241 displayText = dojo.string.substitute(
1242 localeStrings.GENERIC_CIRC_FAILURE, [item]);
1244 displayText = dojo.string.substitute(
1245 localeStrings.UNKNOWN_ERROR, [result.textcode]);
1251 this.handleAlert(displayText, popup, sound);
1259 SelfCheckManager.prototype.renew = function(barcode, override) {
1261 var method = 'open-ils.circ.renew';
1262 if(override) method += '.override';
1264 console.log("Renewing item " + barcode + " with method " + method);
1266 var result = fieldmapper.standardRequest(
1267 ['open-ils.circ', method],
1270 patron_id : this.patron.id(),
1271 copy_barcode : barcode
1276 console.log(js2JSON(result));
1278 var stat = this.handleXactResult('renew', barcode, result);
1281 this.renew(barcode, true);
1285 * Display the result of a checkout or renewal in the items out table
1287 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1289 var copy = evt.payload.copy;
1290 var record = evt.payload.record;
1291 var circ = evt.payload.circ;
1292 var row = this.circTemplate.cloneNode(true);
1294 if(record.doc_id()) {
1295 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/r/' + record.doc_id());
1298 this.byName(row, 'barcode').innerHTML = copy.barcode();
1299 this.byName(row, 'title').innerHTML = record.title();
1300 this.byName(row, 'author').innerHTML = record.author();
1301 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1302 openils.Util.show(this.byName(row, type));
1304 var date = dojo.date.stamp.fromISOString(circ.due_date());
1305 this.byName(row, 'due_date').innerHTML =
1306 dojo.date.locale.format(date, {selector : 'date'});
1308 // put new circs at the top of the list
1309 var tbody = this.circTbody;
1310 if(itemsOut) tbody = this.itemsOutTbody;
1311 tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1315 SelfCheckManager.prototype.byName = function(node, name) {
1316 return dojo.query('[name=' + name+']', node)[0];
1320 SelfCheckManager.prototype.initPrinter = function() {
1321 try { // Mozilla only
1322 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1323 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1324 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1325 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1326 var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1328 pref.setBoolPref('print.always_print_silent', true);
1330 console.log("Unable to initialize auto-printing");
1335 * Email a receipt for this session's checkouts
1337 SelfCheckManager.prototype.emailSessionReceipt = function(callback) {
1341 // collect the circs and failure info
1345 circIds.push(blob.circ);
1356 fieldmapper.standardRequest(
1357 ['open-ils.circ', 'open-ils.circ.checkout.batch_notify.session.atomic'],
1361 oncomplete : function() {
1362 if (callback) callback(); // fire and forget
1369 * Print a receipt for this session's checkouts
1371 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1374 var circCtx = []; // circ context data. in this case, renewal_failure info
1376 // collect the circs and failure info
1380 circIds.push(blob.circ);
1381 circCtx.push({renewal_failure:blob.renewal_failure});
1389 'format.selfcheck.checkout',
1396 fieldmapper.standardRequest(
1397 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1401 oncomplete : function(r) {
1402 var resp = openils.Util.readResponse(r);
1403 var output = resp.template_output();
1405 self.printData(output.data(), self.checkouts.length, callback);
1407 var error = resp.error_output();
1409 throw new Error("Error creating receipt: " + error.data());
1411 throw new Error("No receipt data returned from server");
1419 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1421 var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1,chrome');
1422 win.document.body.innerHTML = data;
1426 * There is no way to know when the browser is done printing.
1427 * Make a best guess at when to close the print window by basing
1428 * the setTimeout wait on the number of items to be printed plus
1431 var sleepTime = 1000;
1433 sleepTime += (numItems / 2) * 1000;
1437 win.close(); // close the print window
1439 callback(); // fire optional post-print callback
1448 * Print a receipt for this user's items out
1450 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1452 if(!this.itemsOut.length) return;
1454 progressDialog.show(true);
1460 'format.selfcheck.items_out',
1466 fieldmapper.standardRequest(
1467 ['open-ils.circ', 'open-ils.circ.fire_circ_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.itemsOut.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 * Print a receipt for this user's holds
1493 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1495 if(!this.holds.length) return;
1497 progressDialog.show(true);
1502 dojo.forEach(this.holds,
1504 holdIds.push(data.hold.id());
1506 //get pickup library info
1507 var pu = fieldmapper.standardRequest(['open-ils.actor','open-ils.actor.org_unit.retrieve'],[null,data.hold.pickup_lib()]);
1509 if(data.status == 4) {
1512 item_title : data.mvr.title(),
1513 item_author : data.mvr.author(),
1514 pickup_lib : pu.name()
1518 queue_position : data.queue_position,
1519 potential_copies : data.potential_copies,
1520 item_title : data.mvr.title(),
1521 item_author : data.mvr.author(),
1522 pickup_lib : pu.name()
1532 'format.selfcheck.holds',
1539 fieldmapper.standardRequest(
1540 ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1544 oncomplete : function(r) {
1545 progressDialog.hide();
1546 var resp = openils.Util.readResponse(r);
1547 var output = resp.template_output();
1549 self.printData(output.data(), self.holds.length, callback);
1551 var error = resp.error_output();
1553 throw new Error("Error creating receipt: " + error.data());
1555 throw new Error("No receipt data returned from server");
1564 SelfCheckManager.prototype.printPaymentReceipt = function(response, callback) {
1567 progressDialog.show(true);
1569 fieldmapper.standardRequest(
1570 ['open-ils.circ', 'open-ils.circ.money.payment_receipt.print'],
1573 params : [this.authtoken, response.payments],
1574 oncomplete : function(r) {
1575 var resp = openils.Util.readResponse(r);
1576 var output = resp.template_output();
1577 progressDialog.hide();
1579 self.printData(output.data(), 1, callback);
1581 var error = resp.error_output();
1583 throw new Error("Error creating receipt: " + error.data());
1585 throw new Error("No receipt data returned from server");
1594 * Print a receipt for this user's fines
1596 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1598 if(!this.creditPayableBalance.length) return;
1599 progressDialog.show(true);
1605 'format.selfcheck.fines',
1611 fieldmapper.standardRequest(
1612 ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1616 oncomplete : function(r) {
1617 progressDialog.hide();
1618 var resp = openils.Util.readResponse(r);
1619 var output = resp.template_output();
1621 self.printData(output.data(), self.finesCount, callback);
1623 var error = resp.error_output();
1625 throw new Error("Error creating receipt: " + error.data());
1627 throw new Error("No receipt data returned from server");
1639 * Logout the patron and return to the login page
1641 SelfCheckManager.prototype.logoutPatron = function(print) {
1642 progressDialog.show(true); // prevent patron from clicking logout link twice
1643 if(print && this.checkouts.length) {
1644 if (dojo.byId('oils-selfck-receipt-print').checked) {
1645 this.printSessionReceipt(
1647 location.href = location.href;
1650 } else if (dojo.byId('oils-selfck-receipt-email').checked) {
1651 this.emailSessionReceipt(
1653 location.href = location.href;
1657 // user elected to get no receipt
1658 location.href = location.href;
1661 location.href = location.href;
1667 * Fire up the manager on page load
1669 openils.Util.addOnLoad(
1671 new SelfCheckManager().init();