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 this.patronBarcodeRegex = new RegExp(/^\d/);
339 // this assumes barcodes start with digits
342 // Subtract the timeout warning interval from the configured timeout
343 // so that when taken together they add up to the configured amount.
344 if(settings[SET_PATRON_TIMEOUT]) {
346 (parseInt(settings[SET_PATRON_TIMEOUT].value) * 1000)
347 - patronTimeoutWarning;
351 SelfCheckManager.prototype.drawLoginPage = function() {
354 var bcHandler = function(barcode_or_usrname) {
355 // handle patron barcode/usrname entry
357 if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
359 // password is required. wire up the scan box to read it
361 msg : localeStrings.ENTER_PASSWORD,
362 handler : function(pw) { self.loginPatron(barcode_or_usrname, pw); },
367 // password is not required, go ahead and login
368 self.loginPatron(barcode_or_usrname);
373 msg : localeStrings.PLEASE_LOGIN,
381 SelfCheckManager.prototype.loginPatron = function(barcode_or_usrname, passwd) {
386 this.setupStaffLogin(true); // verify still valid
390 console.log('testing ' + barcode_or_usrname);
391 if (barcode_or_usrname.match(this.patronBarcodeRegex)) {
392 console.log('barcode');
393 barcode = barcode_or_usrname;
395 console.log('usrname');
396 usrname = barcode_or_usrname;
399 if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
402 // would only happen in dev/debug mode when using the patron= param
403 alert('password required by org setting. remove patron= from URL');
407 // patron password is required. Verify it.
410 new openils.User().auth_verify(
411 { username : usrname, barcode : barcode,
412 type : 'opac', passwd : passwd, agent : 'selfcheck' },
415 self.fetchPatron(barcode, usrname);
418 // auth verify failed
420 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode_or_usrname]),
421 false, 'login-failure'
423 self.drawLoginPage();
429 this.fetchPatron(barcode, usrname);
433 SelfCheckManager.prototype.fetchPatron = function(barcode, usrname) {
435 var patron_id = fieldmapper.standardRequest(
436 ['open-ils.actor', 'open-ils.actor.user.retrieve_id_by_barcode_or_username'],
437 {params : [this.authtoken, barcode, usrname]}
440 // retrieve the fleshed user by id
441 this.patron = fieldmapper.standardRequest(
442 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
443 {params : [this.authtoken, patron_id]}
446 var evt = openils.Event.parse(this.patron);
448 // verify validity of the card used to log in
449 var inactiveCard = false;
453 card = this.patron.cards().filter(
454 function(c) { return (c.barcode() == barcode); })[0];
456 card = this.patron.card();
458 inactiveCard = !openils.Util.isTrue(card.active());
461 if(evt || inactiveCard) {
463 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode || usrname]),
464 false, 'login-failure'
466 this.drawLoginPage();
470 this.handleAlert('', false, 'login-success');
471 dojo.byId('oils-selfck-user-banner').innerHTML =
472 dojo.string.substitute(localeStrings.WELCOME_BANNER, [this.patron.first_given_name()]);
478 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
480 console.log("Handling alert " + message);
482 dojo.byId('oils-selfck-status-div').innerHTML = message;
485 openils.Util.addCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
487 openils.Util.removeCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
489 if(shouldPopup && this.orgSettings[SET_ALERT_POPUP])
492 if(sound && this.orgSettings[SET_ALERT_SOUND])
493 openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
498 * Manages the main input box
499 * @param msg The context message to display with the box
500 * @param clearOnly Don't update the context message, just clear the value and re-focus
501 * @param handler Optional "on-enter" handler.
503 SelfCheckManager.prototype.updateScanBox = function(args) {
507 selfckScanBox.domNode.select();
509 selfckScanBox.attr('value', '');
513 selfckScanBox.domNode.setAttribute('type', 'password');
515 selfckScanBox.domNode.setAttribute('type', '');
519 selfckScanBox.attr('value', args.value);
522 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
524 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
525 dojo.disconnect(selfckScanBox._lastHandler);
529 selfckScanBox._lastHandler = dojo.connect(
533 if(e.keyCode != dojo.keys.ENTER)
535 args.handler(selfckScanBox.attr('value'));
540 selfckScanBox.focus();
544 * Sets up the checkout/renewal interface
546 SelfCheckManager.prototype.drawCircPage = function() {
548 openils.Util.show('oils-selfck-bottom-div');
549 openils.Util.show('oils-selfck-circ-tbody', 'table-row-group');
550 this.goToTab('checkout');
552 while(this.itemsOutTbody.childNodes[0])
553 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
557 msg : localeStrings.ENTER_BARCODE,
558 handler : function(barcode) { self.checkout(barcode); }
561 if(!this.circTemplate)
562 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
565 this.updateFinesSummary();
568 this.updateHoldsSummary();
571 this.updateCircSummary();
573 // render mock checkouts for debugging?
574 if(this.mockCheckouts) {
575 for(var i in [1,2,3])
576 this.displayCheckout(this.mockCheckout, 'checkout');
581 SelfCheckManager.prototype.updateFinesSummary = function() {
585 fieldmapper.standardRequest(
586 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
588 params : [this.authtoken, this.patron.id()],
589 oncomplete : function(r) {
591 var summary = openils.Util.readResponse(r);
593 dojo.byId('oils-selfck-fines-total').innerHTML =
594 dojo.string.substitute(
595 localeStrings.TOTAL_FINES_ACCOUNT,
596 ['<b>' + summary.balance_owed() + '</b>']
599 self.creditPayableBalance = summary.balance_owed();
606 SelfCheckManager.prototype.drawItemsOutPage = function() {
607 openils.Util.hide('oils-selfck-circ-tbody');
609 this.goToTab('items_out');
611 while(this.itemsOutTbody.childNodes[0])
612 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
614 progressDialog.show(true);
617 fieldmapper.standardRequest(
618 ['open-ils.circ', 'open-ils.circ.actor.user.checked_out.atomic'],
621 params : [this.authtoken, this.patron.id()],
622 oncomplete : function(r) {
624 var resp = openils.Util.readResponse(r);
626 var circs = resp.sort(
628 if(a.circ.due_date() > b.circ.due_date())
634 progressDialog.hide();
639 self.itemsOut.push(circ.circ.id());
640 self.displayCheckout(
642 (circ.circ.parent_circ()) ? 'renew' : 'checkout',
653 SelfCheckManager.prototype.goToTab = function(name) {
656 openils.Util.hide('oils-selfck-fines-page');
657 openils.Util.hide('oils-selfck-payment-page');
658 openils.Util.hide('oils-selfck-holds-page');
659 openils.Util.hide('oils-selfck-circ-page');
660 openils.Util.hide('oils-selfck-pay-fines-link');
667 openils.Util.show('oils-selfck-circ-page');
670 openils.Util.show('oils-selfck-circ-page');
673 openils.Util.show('oils-selfck-holds-page');
676 openils.Util.show('oils-selfck-fines-page');
679 openils.Util.show('oils-selfck-payment-page');
685 SelfCheckManager.prototype.printList = function() {
689 switch(this.tabName) {
691 this.printSessionReceipt();
694 this.printItemsOutReceipt();
697 this.printHoldsReceipt();
700 this.printFinesReceipt();
705 SelfCheckManager.prototype.updateHoldsSummary = function() {
707 if(!this.holdsSummary) {
708 var summary = fieldmapper.standardRequest(
709 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
710 {params : [this.authtoken, this.patron.id()]}
713 this.holdsSummary = {};
714 this.holdsSummary.ready = Number(summary['4']);
715 this.holdsSummary.total = 0;
717 for(var i in summary)
718 this.holdsSummary.total += Number(summary[i]);
721 dojo.byId('oils-selfck-holds-total').innerHTML =
722 dojo.string.substitute(
723 localeStrings.TOTAL_HOLDS,
724 ['<b>' + this.holdsSummary.total + '</b>']
727 dojo.byId('oils-selfck-holds-ready').innerHTML =
728 dojo.string.substitute(
729 localeStrings.HOLDS_READY_FOR_PICKUP,
730 ['<b>' + this.holdsSummary.ready + '</b>']
735 SelfCheckManager.prototype.updateCircSummary = function(increment) {
737 if(!this.circSummary) {
739 var summary = fieldmapper.standardRequest(
740 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
741 {params : [this.authtoken, this.patron.id()]}
745 total : Number(summary.out) + Number(summary.overdue),
746 overdue : Number(summary.overdue),
752 // local checkout occurred. Add to the total and the session.
753 this.circSummary.total += 1;
754 this.circSummary.session += 1;
757 dojo.byId('oils-selfck-circ-account-total').innerHTML =
758 dojo.string.substitute(
759 localeStrings.TOTAL_ITEMS_ACCOUNT,
760 ['<b>' + this.circSummary.total + '</b>']
763 dojo.byId('oils-selfck-circ-session-total').innerHTML =
764 dojo.string.substitute(
765 localeStrings.TOTAL_ITEMS_SESSION,
766 ['<b>' + this.circSummary.session + '</b>']
771 SelfCheckManager.prototype.drawHoldsPage = function() {
773 // TODO add option to hid scanBox
774 // this.updateScanBox(...)
776 this.goToTab('holds');
778 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
779 if(!this.holdTemplate)
780 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
781 while(this.holdTbody.childNodes[0])
782 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
784 progressDialog.show(true);
787 fieldmapper.standardRequest( // fetch the hold IDs
789 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
791 params : [this.authtoken, this.patron.id()],
793 oncomplete : function(r) {
794 var ids = openils.Util.readResponse(r);
795 if(!ids || ids.length == 0) {
796 progressDialog.hide();
800 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
801 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve'],
803 params : [self.authtoken, ids],
804 onresponse : function(rr) {
805 progressDialog.hide();
806 self.insertHold(openils.Util.readResponse(rr));
815 SelfCheckManager.prototype.insertHold = function(data) {
817 // store hold data to pass along to receipt printing function
818 this.holds.push(data);
820 var row = this.holdTemplate.cloneNode(true);
822 if(data.mvr.isbn()) {
823 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/r/' + data.mvr.doc_id());
826 this.byName(row, 'title').innerHTML = data.mvr.title();
827 this.byName(row, 'author').innerHTML = data.mvr.author();
829 if(data.status == 4) {
831 // hold is ready for pickup
832 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
836 // hold is still pending
837 this.byName(row, 'status').innerHTML =
838 dojo.string.substitute(
839 localeStrings.HOLD_STATUS_WAITING,
840 [data.queue_position, data.potential_copies]
844 // find the correct place the table to slot in the hold based on queue position
846 var position = (data.status == 4) ? 0 : data.queue_position;
847 row.setAttribute('position', position);
849 for(var i = 0; i < this.holdTbody.childNodes.length; i++) {
850 var node = this.holdTbody.childNodes[i];
851 if(Number(node.getAttribute('position')) >= position) {
852 this.holdTbody.insertBefore(row, node);
857 this.holdTbody.appendChild(row);
861 SelfCheckManager.prototype.drawFinesPage = function() {
863 // TODO add option to hid scanBox
864 // this.updateScanBox(...)
866 this.goToTab('fines');
867 progressDialog.show(true);
869 if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
870 openils.Util.show('oils-selfck-pay-fines-link', 'inline');
873 this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
874 if(!this.finesTemplate)
875 this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
876 while(this.finesTbody.childNodes[0])
877 this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
879 // when user clicks on a selector checkbox, update the total owed
880 var updateSelected = function() {
883 dojo.query('[name=selector]', this.finesTbody),
886 total += Number(input.getAttribute('balance_owed'));
890 total = total.toFixed(2);
891 dojo.byId('oils-selfck-selected-total').innerHTML =
892 dojo.string.substitute(localeStrings.TOTAL_FINES_SELECTED, [total]);
895 // wire up the batch on/off selector
896 var sel = dojo.byId('oils-selfck-fines-selector');
897 sel.onchange = function() {
899 dojo.query('[name=selector]', this.finesTbody),
901 input.checked = sel.checked;
907 var handler = function(dataList) {
909 self.finesCount = dataList.length;
910 self.finesData = dataList;
912 for(var i in dataList) {
914 var data = dataList[i];
915 var row = self.finesTemplate.cloneNode(true);
916 var type = data.transaction.xact_type();
918 if(type == 'circulation') {
919 self.byName(row, 'type').innerHTML = type;
920 self.byName(row, 'details').innerHTML = data.record.title();
922 } else if(type == 'grocery') {
923 self.byName(row, 'type').innerHTML = localeStrings.MISCELLANEOUS; // Go ahead and head off any confusion around "grocery".
924 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
927 self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
928 self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
929 self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
932 var selector = self.byName(row, 'selector')
933 selector.onchange = updateSelected;
934 selector.setAttribute('xact', data.transaction.id());
935 selector.setAttribute('balance_owed', data.transaction.balance_owed());
936 selector.checked = true;
938 self.finesTbody.appendChild(row);
945 fieldmapper.standardRequest(
946 ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
948 params : [this.authtoken, this.patron.id()],
949 oncomplete : function(r) {
950 progressDialog.hide();
951 handler(openils.Util.readResponse(r));
957 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
959 var resp = fieldmapper.standardRequest(
960 ['open-ils.circ', 'open-ils.circ.transit.abort'],
961 {params : [this.authtoken, {barcode : barcode}]}
964 // resp == 1 on success
965 if(openils.Event.parse(resp))
968 var resp = fieldmapper.standardRequest(
969 ['open-ils.circ', 'open-ils.circ.checkin.override'],
972 patron_id : this.patron.id(),
973 copy_barcode : barcode,
979 if(!resp.length) resp = [resp];
980 for(var i = 0; i < resp.length; i++) {
981 var tc = openils.Event.parse(resp[i]).textcode;
982 if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
993 * Check out a single item. If the item is already checked
994 * out to the patron, redirect to renew()
996 SelfCheckManager.prototype.checkout = function(barcode, override) {
1001 this.prevCirc = null;
1004 this.updateScanbox(null, true);
1008 if(this.mockCheckouts) {
1009 // if we're in mock-checkout mode, just insert another
1010 // fake circ into the table and get out of here.
1011 this.displayCheckout(this.mockCheckout, 'checkout');
1015 // TODO see if it's a patron barcode
1016 // TODO see if this item has already been checked out in this session
1018 var method = 'open-ils.circ.checkout.full';
1019 if(override) method += '.override';
1021 console.log("Checkout out item " + barcode + " with method " + method);
1023 var result = fieldmapper.standardRequest(
1024 ['open-ils.circ', method],
1027 patron_id : this.patron.id(),
1028 copy_barcode : barcode
1033 var stat = this.handleXactResult('checkout', barcode, result);
1036 this.checkout(barcode, true);
1037 } else if(stat.doOver) {
1038 this.checkout(barcode);
1039 } else if(stat.renew) {
1040 this.renew(barcode);
1044 SelfCheckManager.prototype.failPartMessage = function(result) {
1045 if (result.payload && result.payload.fail_part) {
1046 var stringKey = "FAIL_PART_" +
1047 result.payload.fail_part.replace(/\./g, "_");
1048 return localeStrings[stringKey];
1054 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
1056 var displayText = '';
1058 // If true, the display message is important enough to pop up. Whether or not
1059 // an alert() actually occurs, depends on org unit settings
1061 var sound = ''; // sound file reference
1062 var payload = result.payload || {};
1063 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
1064 var blockStatuses = this.orgSettings[SET_BLOCK_CHECKOUT_ON_COPY_STATUS];
1066 if(result.textcode == 'NO_SESSION') {
1068 return this.logoutStaff();
1070 } else if(result.textcode == 'SUCCESS') {
1072 if(action == 'checkout') {
1074 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
1075 this.displayCheckout(result, 'checkout');
1077 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
1078 // A hold was fulfilled, update the hold numbers in the circ summary
1079 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
1080 this.holdsSummary = null;
1081 this.updateHoldsSummary();
1084 this.updateCircSummary(true);
1086 } else if(action == 'renew') {
1088 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
1089 this.displayCheckout(result, 'renew');
1092 this.checkouts.push({circ : result.payload.circ.id()});
1093 sound = 'checkout-success';
1094 this.updateScanBox();
1096 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
1098 // Server says the item is already checked out. If it's checked out to the
1099 // current user, we may need to renew it.
1101 if(payload.old_circ) {
1104 old_circ refers to the previous checkout IFF it's for the same user.
1105 If no auto-renew interval is not defined, assume we should renew it
1106 If an auto-renew interval is defined and the payload comes back with
1107 auto_renew set to true, do the renewal. Otherwise, let the patron know
1108 the item is already checked out to them. */
1110 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
1111 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
1112 this.prevCirc = payload.old_circ.id();
1113 return { renew : true };
1117 sound = 'checkout-failure';
1118 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
1122 if( // copy is marked lost. if configured to do so, check it in and try again.
1123 result.payload.copy &&
1124 result.payload.copy.status() == /* LOST */ 3 &&
1125 overrideEvents && overrideEvents.length &&
1126 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
1128 if(this.checkin(item)) {
1129 return { doOver : true };
1134 // item is checked out to some other user
1136 sound = 'checkout-failure';
1137 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1140 this.updateScanBox({select:true});
1145 if(overrideEvents && overrideEvents.length) {
1147 // see if the events we received are all in the list of
1148 // events to override
1150 if(!result.length) result = [result];
1152 var override = true;
1153 for(var i = 0; i < result.length; i++) {
1155 var match = overrideEvents.filter(function(e) { return (e == result[i].textcode); })[0];
1162 if(result[i].textcode == 'COPY_NOT_AVAILABLE' && blockStatuses && blockStatuses.length) {
1164 var stat = result[i].payload.status(); // copy status
1165 if(typeof stat == 'object') stat = stat.id();
1167 var match2 = blockStatuses.filter(function(e) { return (e == stat); })[0];
1169 if(match2) { // copy is in a blocked status
1175 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1176 // to override a transit, we have to abort the transit and check it in first
1177 if(this.checkin(item, true)) {
1178 return { doOver : true };
1186 return { override : true };
1189 this.updateScanBox({select : true});
1191 sound = 'checkout-failure';
1193 if(action == 'renew')
1194 this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1199 switch(result.textcode) {
1201 // TODO custom handler for blocking penalties
1203 case 'MAX_RENEWALS_REACHED' :
1204 displayText = dojo.string.substitute(
1205 localeStrings.MAX_RENEWALS, [item]);
1208 case 'ITEM_NOT_CATALOGED' :
1209 displayText = dojo.string.substitute(
1210 localeStrings.ITEM_NOT_CATALOGED, [item]);
1213 case 'OPEN_CIRCULATION_EXISTS' :
1214 displayText = dojo.string.substitute(
1215 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1220 console.error('Unhandled event ' + result.textcode);
1222 if (!(displayText = this.failPartMessage(result))) {
1223 if (action == 'checkout' || action == 'renew') {
1224 displayText = dojo.string.substitute(
1225 localeStrings.GENERIC_CIRC_FAILURE, [item]);
1227 displayText = dojo.string.substitute(
1228 localeStrings.UNKNOWN_ERROR, [result.textcode]);
1234 this.handleAlert(displayText, popup, sound);
1242 SelfCheckManager.prototype.renew = function(barcode, override) {
1244 var method = 'open-ils.circ.renew';
1245 if(override) method += '.override';
1247 console.log("Renewing item " + barcode + " with method " + method);
1249 var result = fieldmapper.standardRequest(
1250 ['open-ils.circ', method],
1253 patron_id : this.patron.id(),
1254 copy_barcode : barcode
1259 console.log(js2JSON(result));
1261 var stat = this.handleXactResult('renew', barcode, result);
1264 this.renew(barcode, true);
1268 * Display the result of a checkout or renewal in the items out table
1270 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1272 var copy = evt.payload.copy;
1273 var record = evt.payload.record;
1274 var circ = evt.payload.circ;
1275 var row = this.circTemplate.cloneNode(true);
1277 if(record.doc_id()) {
1278 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/r/' + record.doc_id());
1281 this.byName(row, 'barcode').innerHTML = copy.barcode();
1282 this.byName(row, 'title').innerHTML = record.title();
1283 this.byName(row, 'author').innerHTML = record.author();
1284 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1285 openils.Util.show(this.byName(row, type));
1287 var date = dojo.date.stamp.fromISOString(circ.due_date());
1288 this.byName(row, 'due_date').innerHTML =
1289 dojo.date.locale.format(date, {selector : 'date'});
1291 // put new circs at the top of the list
1292 var tbody = this.circTbody;
1293 if(itemsOut) tbody = this.itemsOutTbody;
1294 tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1298 SelfCheckManager.prototype.byName = function(node, name) {
1299 return dojo.query('[name=' + name+']', node)[0];
1303 SelfCheckManager.prototype.initPrinter = function() {
1304 try { // Mozilla only
1305 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1306 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1307 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1308 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1309 var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1311 pref.setBoolPref('print.always_print_silent', true);
1313 console.log("Unable to initialize auto-printing");
1318 * Print a receipt for this session's checkouts
1320 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1323 var circCtx = []; // circ context data. in this case, renewal_failure info
1325 // collect the circs and failure info
1329 circIds.push(blob.circ);
1330 circCtx.push({renewal_failure:blob.renewal_failure});
1338 'format.selfcheck.checkout',
1345 fieldmapper.standardRequest(
1346 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1350 oncomplete : function(r) {
1351 var resp = openils.Util.readResponse(r);
1352 var output = resp.template_output();
1354 self.printData(output.data(), self.checkouts.length, callback);
1356 var error = resp.error_output();
1358 throw new Error("Error creating receipt: " + error.data());
1360 throw new Error("No receipt data returned from server");
1368 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1370 var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1,chrome');
1371 win.document.body.innerHTML = data;
1375 * There is no way to know when the browser is done printing.
1376 * Make a best guess at when to close the print window by basing
1377 * the setTimeout wait on the number of items to be printed plus
1380 var sleepTime = 1000;
1382 sleepTime += (numItems / 2) * 1000;
1386 win.close(); // close the print window
1388 callback(); // fire optional post-print callback
1396 * Print a receipt for this user's items out
1398 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1400 if(!this.itemsOut.length) return;
1402 progressDialog.show(true);
1408 'format.selfcheck.items_out',
1414 fieldmapper.standardRequest(
1415 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1419 oncomplete : function(r) {
1420 progressDialog.hide();
1421 var resp = openils.Util.readResponse(r);
1422 var output = resp.template_output();
1424 self.printData(output.data(), self.itemsOut.length, callback);
1426 var error = resp.error_output();
1428 throw new Error("Error creating receipt: " + error.data());
1430 throw new Error("No receipt data returned from server");
1439 * Print a receipt for this user's holds
1441 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1443 if(!this.holds.length) return;
1445 progressDialog.show(true);
1450 dojo.forEach(this.holds,
1452 holdIds.push(data.hold.id());
1454 //get pickup library info
1455 var pu = fieldmapper.standardRequest(['open-ils.actor','open-ils.actor.org_unit.retrieve'],[null,data.hold.pickup_lib()]);
1457 if(data.status == 4) {
1460 item_title : data.mvr.title(),
1461 item_author : data.mvr.author(),
1462 pickup_lib : pu.name()
1466 queue_position : data.queue_position,
1467 potential_copies : data.potential_copies,
1468 item_title : data.mvr.title(),
1469 item_author : data.mvr.author(),
1470 pickup_lib : pu.name()
1480 'format.selfcheck.holds',
1487 fieldmapper.standardRequest(
1488 ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1492 oncomplete : function(r) {
1493 progressDialog.hide();
1494 var resp = openils.Util.readResponse(r);
1495 var output = resp.template_output();
1497 self.printData(output.data(), self.holds.length, callback);
1499 var error = resp.error_output();
1501 throw new Error("Error creating receipt: " + error.data());
1503 throw new Error("No receipt data returned from server");
1512 SelfCheckManager.prototype.printPaymentReceipt = function(response, callback) {
1515 progressDialog.show(true);
1517 fieldmapper.standardRequest(
1518 ['open-ils.circ', 'open-ils.circ.money.payment_receipt.print'],
1521 params : [this.authtoken, response.payments],
1522 oncomplete : function(r) {
1523 var resp = openils.Util.readResponse(r);
1524 var output = resp.template_output();
1525 progressDialog.hide();
1527 self.printData(output.data(), 1, callback);
1529 var error = resp.error_output();
1531 throw new Error("Error creating receipt: " + error.data());
1533 throw new Error("No receipt data returned from server");
1542 * Print a receipt for this user's fines
1544 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1546 if(!this.creditPayableBalance.length) return;
1547 progressDialog.show(true);
1553 'format.selfcheck.fines',
1559 fieldmapper.standardRequest(
1560 ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1564 oncomplete : function(r) {
1565 progressDialog.hide();
1566 var resp = openils.Util.readResponse(r);
1567 var output = resp.template_output();
1569 self.printData(output.data(), self.finesCount, callback);
1571 var error = resp.error_output();
1573 throw new Error("Error creating receipt: " + error.data());
1575 throw new Error("No receipt data returned from server");
1587 * Logout the patron and return to the login page
1589 SelfCheckManager.prototype.logoutPatron = function(print) {
1590 progressDialog.show(true); // prevent patron from clicking logout link twice
1591 if(print && this.checkouts.length) {
1592 this.printSessionReceipt(
1594 location.href = location.href;
1598 location.href = location.href;
1604 * Fire up the manager on page load
1606 openils.Util.addOnLoad(
1608 new SelfCheckManager().init();