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, [
472 ( this.patron.pref_first_given_name() ? this.patron.pref_first_given_name() : this.patron.first_given_name() ) ]);
474 if (this.patron.email() && // they have an email address set and ...
475 this.patron.email().match(/.*@.*/).length > 0 // it sorta looks like an email address
477 openils.Util.removeCSSClass( dojo.byId('oils-selfck-receipt-email').parentNode, 'hidden' );
478 if (user_setting_value(this.patron, 'circ.send_email_checkout_receipts') == 'true') // their selected default
479 dojo.byId('oils-selfck-receipt-email').checked = true;
486 function user_setting_value (user, setting) {
488 var list = user.settings().filter(function(s){
489 return s.name() == setting;
492 if (list.length) return list[0].value();
496 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
498 console.log("Handling alert " + message);
500 dojo.byId('oils-selfck-status-div').innerHTML = message;
503 openils.Util.addCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
505 openils.Util.removeCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
507 if(shouldPopup && this.orgSettings[SET_ALERT_POPUP])
510 if(sound && this.orgSettings[SET_ALERT_SOUND])
511 openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
516 * Manages the main input box
517 * @param msg The context message to display with the box
518 * @param clearOnly Don't update the context message, just clear the value and re-focus
519 * @param handler Optional "on-enter" handler.
521 SelfCheckManager.prototype.updateScanBox = function(args) {
525 selfckScanBox.domNode.select();
527 selfckScanBox.attr('value', '');
531 selfckScanBox.domNode.setAttribute('type', 'password');
533 selfckScanBox.domNode.setAttribute('type', '');
537 selfckScanBox.attr('value', args.value);
540 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
542 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
543 dojo.disconnect(selfckScanBox._lastHandler);
547 selfckScanBox._lastHandler = dojo.connect(
551 if(e.keyCode != dojo.keys.ENTER)
553 args.handler(selfckScanBox.attr('value'));
558 selfckScanBox.focus();
562 * Sets up the checkout/renewal interface
564 SelfCheckManager.prototype.drawCircPage = function() {
566 openils.Util.hide('oils-selfck-print-list-link');
567 openils.Util.show('oils-selfck-bottom-div');
568 openils.Util.show('oils-selfck-circ-tbody', 'table-row-group');
569 this.goToTab('checkout');
571 while(this.itemsOutTbody.childNodes[0])
572 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
576 msg : localeStrings.ENTER_BARCODE,
577 handler : function(barcode) { self.checkout(barcode); }
580 if(!this.circTemplate)
581 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
584 this.updateFinesSummary();
587 this.updateHoldsSummary();
590 this.updateCircSummary();
592 // render mock checkouts for debugging?
593 if(this.mockCheckouts) {
594 for(var i in [1,2,3])
595 this.displayCheckout(this.mockCheckout, 'checkout');
600 SelfCheckManager.prototype.updateFinesSummary = function() {
604 fieldmapper.standardRequest(
605 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
607 params : [this.authtoken, this.patron.id()],
608 oncomplete : function(r) {
610 var summary = openils.Util.readResponse(r);
612 dojo.byId('oils-selfck-fines-total').innerHTML =
613 dojo.string.substitute(
614 localeStrings.TOTAL_FINES_ACCOUNT,
615 ['<b>' + summary.balance_owed() + '</b>']
618 self.creditPayableBalance = summary.balance_owed();
625 SelfCheckManager.prototype.drawItemsOutPage = function() {
626 openils.Util.hide('oils-selfck-circ-tbody');
627 openils.Util.show('oils-selfck-print-list-link');
628 this.goToTab('items_out');
630 while(this.itemsOutTbody.childNodes[0])
631 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
633 progressDialog.show(true);
636 fieldmapper.standardRequest(
637 ['open-ils.circ', 'open-ils.circ.actor.user.checked_out.atomic'],
640 params : [this.authtoken, this.patron.id()],
641 oncomplete : function(r) {
643 var resp = openils.Util.readResponse(r);
645 var circs = resp.sort(
647 if(a.circ.due_date() > b.circ.due_date())
653 progressDialog.hide();
658 self.itemsOut.push(circ.circ.id());
659 self.displayCheckout(
661 (circ.circ.parent_circ()) ? 'renew' : 'checkout',
672 SelfCheckManager.prototype.goToTab = function(name) {
675 openils.Util.hide('oils-selfck-fines-page');
676 openils.Util.hide('oils-selfck-payment-page');
677 openils.Util.hide('oils-selfck-holds-page');
678 openils.Util.hide('oils-selfck-circ-page');
679 openils.Util.hide('oils-selfck-pay-fines-link');
686 openils.Util.show('oils-selfck-circ-page');
689 openils.Util.show('oils-selfck-circ-page');
692 openils.Util.show('oils-selfck-holds-page');
695 openils.Util.show('oils-selfck-fines-page');
698 openils.Util.show('oils-selfck-payment-page');
704 SelfCheckManager.prototype.printList = function() {
708 switch(this.tabName) {
710 this.printSessionReceipt();
713 this.printItemsOutReceipt();
716 this.printHoldsReceipt();
719 this.printFinesReceipt();
724 SelfCheckManager.prototype.updateHoldsSummary = function() {
726 if(!this.holdsSummary) {
727 var summary = fieldmapper.standardRequest(
728 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
729 {params : [this.authtoken, this.patron.id()]}
732 this.holdsSummary = {};
733 this.holdsSummary.ready = Number(summary['4']);
734 this.holdsSummary.total = 0;
736 for(var i in summary)
737 this.holdsSummary.total += Number(summary[i]);
740 dojo.byId('oils-selfck-holds-total').innerHTML =
741 dojo.string.substitute(
742 localeStrings.TOTAL_HOLDS,
743 ['<b>' + this.holdsSummary.total + '</b>']
746 dojo.byId('oils-selfck-holds-ready').innerHTML =
747 dojo.string.substitute(
748 localeStrings.HOLDS_READY_FOR_PICKUP,
749 ['<b>' + this.holdsSummary.ready + '</b>']
754 SelfCheckManager.prototype.updateCircSummary = function(increment) {
756 if(!this.circSummary) {
758 var summary = fieldmapper.standardRequest(
759 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
760 {params : [this.authtoken, this.patron.id()]}
764 total : Number(summary.out) + Number(summary.overdue),
765 overdue : Number(summary.overdue),
771 // local checkout occurred. Add to the total and the session.
772 this.circSummary.total += 1;
773 this.circSummary.session += 1;
776 dojo.byId('oils-selfck-circ-account-total').innerHTML =
777 dojo.string.substitute(
778 localeStrings.TOTAL_ITEMS_ACCOUNT,
779 ['<b>' + this.circSummary.total + '</b>']
782 dojo.byId('oils-selfck-circ-session-total').innerHTML =
783 dojo.string.substitute(
784 localeStrings.TOTAL_ITEMS_SESSION,
785 ['<b>' + this.circSummary.session + '</b>']
790 SelfCheckManager.prototype.drawHoldsPage = function() {
792 // TODO add option to hid scanBox
793 // this.updateScanBox(...)
794 openils.Util.show('oils-selfck-print-list-link');
795 this.goToTab('holds');
797 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
798 if(!this.holdTemplate)
799 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
800 while(this.holdTbody.childNodes[0])
801 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
803 progressDialog.show(true);
806 fieldmapper.standardRequest( // fetch the hold IDs
808 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
810 params : [this.authtoken, this.patron.id()],
812 oncomplete : function(r) {
813 var ids = openils.Util.readResponse(r);
814 if(!ids || ids.length == 0) {
815 progressDialog.hide();
819 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
820 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve'],
822 params : [self.authtoken, ids],
823 onresponse : function(rr) {
824 progressDialog.hide();
825 self.insertHold(openils.Util.readResponse(rr));
834 SelfCheckManager.prototype.insertHold = function(data) {
836 // store hold data to pass along to receipt printing function
837 this.holds.push(data);
839 var row = this.holdTemplate.cloneNode(true);
841 if(data.mvr.isbn()) {
842 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/r/' + data.mvr.doc_id());
845 this.byName(row, 'title').innerHTML = data.mvr.title();
846 this.byName(row, 'author').innerHTML = data.mvr.author();
848 if(data.status == 4) {
850 // hold is ready for pickup
851 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
855 // hold is still pending
856 this.byName(row, 'status').innerHTML =
857 dojo.string.substitute(
858 localeStrings.HOLD_STATUS_WAITING,
859 [data.queue_position, data.potential_copies]
863 // find the correct place the table to slot in the hold based on queue position
865 var position = (data.status == 4) ? 0 : data.queue_position;
866 row.setAttribute('position', position);
868 for(var i = 0; i < this.holdTbody.childNodes.length; i++) {
869 var node = this.holdTbody.childNodes[i];
870 if(Number(node.getAttribute('position')) >= position) {
871 this.holdTbody.insertBefore(row, node);
876 this.holdTbody.appendChild(row);
880 SelfCheckManager.prototype.drawFinesPage = function() {
882 // TODO add option to hid scanBox
883 // this.updateScanBox(...)
884 openils.Util.show('oils-selfck-print-list-link');
886 this.goToTab('fines');
887 progressDialog.show(true);
889 if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
890 openils.Util.show('oils-selfck-pay-fines-link', 'inline');
893 this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
894 if(!this.finesTemplate)
895 this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
896 while(this.finesTbody.childNodes[0])
897 this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
899 // when user clicks on a selector checkbox, update the total owed
900 var updateSelected = function() {
903 dojo.query('[name=selector]', this.finesTbody),
906 total += Number(input.getAttribute('balance_owed'));
910 total = total.toFixed(2);
911 dojo.byId('oils-selfck-selected-total').innerHTML =
912 dojo.string.substitute(localeStrings.TOTAL_FINES_SELECTED, [total]);
915 // wire up the batch on/off selector
916 var sel = dojo.byId('oils-selfck-fines-selector');
917 sel.onchange = function() {
919 dojo.query('[name=selector]', this.finesTbody),
921 input.checked = sel.checked;
927 var handler = function(dataList) {
929 self.finesCount = dataList.length;
930 self.finesData = dataList;
932 for(var i in dataList) {
934 var data = dataList[i];
935 var row = self.finesTemplate.cloneNode(true);
936 var type = data.transaction.xact_type();
938 if(type == 'circulation') {
939 self.byName(row, 'type').innerHTML = type;
940 self.byName(row, 'details').innerHTML = data.record.title();
942 } else if(type == 'grocery') {
943 self.byName(row, 'type').innerHTML = localeStrings.MISCELLANEOUS; // Go ahead and head off any confusion around "grocery".
944 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
947 self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
948 self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
949 self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
952 var selector = self.byName(row, 'selector')
953 selector.onchange = updateSelected;
954 selector.setAttribute('xact', data.transaction.id());
955 selector.setAttribute('balance_owed', data.transaction.balance_owed());
956 selector.checked = true;
958 self.finesTbody.appendChild(row);
965 fieldmapper.standardRequest(
966 ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
968 params : [this.authtoken, this.patron.id()],
969 oncomplete : function(r) {
970 progressDialog.hide();
971 handler(openils.Util.readResponse(r));
977 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
979 var resp = fieldmapper.standardRequest(
980 ['open-ils.circ', 'open-ils.circ.transit.abort'],
981 {params : [this.authtoken, {barcode : barcode}]}
984 // resp == 1 on success
985 if(openils.Event.parse(resp))
988 var resp = fieldmapper.standardRequest(
989 ['open-ils.circ', 'open-ils.circ.checkin.override'],
992 patron_id : this.patron.id(),
993 copy_barcode : barcode,
999 if(!resp.length) resp = [resp];
1000 for(var i = 0; i < resp.length; i++) {
1001 var tc = openils.Event.parse(resp[i]).textcode;
1002 if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
1013 * Check out a single item. If the item is already checked
1014 * out to the patron, redirect to renew()
1016 SelfCheckManager.prototype.checkout = function(barcode, override) {
1021 this.prevCirc = null;
1024 this.updateScanbox(null, true);
1028 if(this.mockCheckouts) {
1029 // if we're in mock-checkout mode, just insert another
1030 // fake circ into the table and get out of here.
1031 this.displayCheckout(this.mockCheckout, 'checkout');
1035 // TODO see if it's a patron barcode
1036 // TODO see if this item has already been checked out in this session
1038 var method = 'open-ils.circ.checkout.full';
1039 if(override) method += '.override';
1041 console.log("Checkout out item " + barcode + " with method " + method);
1043 var result = fieldmapper.standardRequest(
1044 ['open-ils.circ', method],
1047 patron_id : this.patron.id(),
1048 copy_barcode : barcode
1053 var stat = this.handleXactResult('checkout', barcode, result);
1056 this.checkout(barcode, true);
1057 } else if(stat.doOver) {
1058 this.checkout(barcode);
1059 } else if(stat.renew) {
1060 this.renew(barcode);
1064 SelfCheckManager.prototype.failPartMessage = function(result) {
1065 if (result.payload && result.payload.fail_part) {
1066 var stringKey = "FAIL_PART_" +
1067 result.payload.fail_part.replace(/\./g, "_");
1068 return localeStrings[stringKey];
1074 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
1076 var displayText = '';
1078 // If true, the display message is important enough to pop up. Whether or not
1079 // an alert() actually occurs, depends on org unit settings
1081 var sound = ''; // sound file reference
1082 var payload = result.payload || {};
1083 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
1084 var blockStatuses = this.orgSettings[SET_BLOCK_CHECKOUT_ON_COPY_STATUS];
1086 if(result.textcode == 'NO_SESSION') {
1088 return this.logoutStaff();
1090 } else if(result.textcode == 'SUCCESS') {
1092 if(action == 'checkout') {
1094 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
1095 this.displayCheckout(result, 'checkout');
1097 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
1098 // A hold was fulfilled, update the hold numbers in the circ summary
1099 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
1100 this.holdsSummary = null;
1101 this.updateHoldsSummary();
1104 this.updateCircSummary(true);
1106 } else if(action == 'renew') {
1108 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
1109 this.displayCheckout(result, 'renew');
1112 this.checkouts.push({circ : result.payload.circ.id()});
1113 sound = 'checkout-success';
1114 this.updateScanBox();
1116 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
1118 // Server says the item is already checked out. If it's checked out to the
1119 // current user, we may need to renew it.
1121 if(payload.old_circ) {
1124 old_circ refers to the previous checkout IFF it's for the same user.
1125 If no auto-renew interval is not defined, assume we should renew it
1126 If an auto-renew interval is defined and the payload comes back with
1127 auto_renew set to true, do the renewal. Otherwise, let the patron know
1128 the item is already checked out to them. */
1130 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
1131 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
1132 this.prevCirc = payload.old_circ.id();
1133 return { renew : true };
1137 sound = 'checkout-failure';
1138 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
1142 if( // copy is marked lost. if configured to do so, check it in and try again.
1143 result.payload.copy &&
1144 result.payload.copy.status() == /* LOST */ 3 &&
1145 overrideEvents && overrideEvents.length &&
1146 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
1148 if(this.checkin(item)) {
1149 return { doOver : true };
1154 // item is checked out to some other user
1156 sound = 'checkout-failure';
1157 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1160 this.updateScanBox({select:true});
1165 if(overrideEvents && overrideEvents.length) {
1167 // see if the events we received are all in the list of
1168 // events to override
1170 if(!result.length) result = [result];
1172 var override = true;
1173 for(var i = 0; i < result.length; i++) {
1175 var match = overrideEvents.filter(function(e) { return (e == result[i].textcode); })[0];
1182 if(result[i].textcode == 'COPY_NOT_AVAILABLE' && blockStatuses && blockStatuses.length) {
1184 var stat = result[i].payload.status(); // copy status
1185 if(typeof stat == 'object') stat = stat.id();
1187 var match2 = blockStatuses.filter(function(e) { return (e == stat); })[0];
1189 if(match2) { // copy is in a blocked status
1195 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1196 // to override a transit, we have to abort the transit and check it in first
1197 if(this.checkin(item, true)) {
1198 return { doOver : true };
1206 return { override : true };
1209 this.updateScanBox({select : true});
1211 sound = 'checkout-failure';
1213 if(action == 'renew')
1214 this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1219 switch(result.textcode) {
1221 // TODO custom handler for blocking penalties
1223 case 'MAX_RENEWALS_REACHED' :
1224 displayText = dojo.string.substitute(
1225 localeStrings.MAX_RENEWALS, [item]);
1228 case 'ITEM_NOT_CATALOGED' :
1229 displayText = dojo.string.substitute(
1230 localeStrings.ITEM_NOT_CATALOGED, [item]);
1233 case 'OPEN_CIRCULATION_EXISTS' :
1234 displayText = dojo.string.substitute(
1235 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1240 console.error('Unhandled event ' + result.textcode);
1242 if (!(displayText = this.failPartMessage(result))) {
1243 if (action == 'checkout' || action == 'renew') {
1244 displayText = dojo.string.substitute(
1245 localeStrings.GENERIC_CIRC_FAILURE, [item]);
1247 displayText = dojo.string.substitute(
1248 localeStrings.UNKNOWN_ERROR, [result.textcode]);
1254 this.handleAlert(displayText, popup, sound);
1262 SelfCheckManager.prototype.renew = function(barcode, override) {
1264 var method = 'open-ils.circ.renew';
1265 if(override) method += '.override';
1267 console.log("Renewing item " + barcode + " with method " + method);
1269 var result = fieldmapper.standardRequest(
1270 ['open-ils.circ', method],
1273 patron_id : this.patron.id(),
1274 copy_barcode : barcode
1279 console.log(js2JSON(result));
1281 var stat = this.handleXactResult('renew', barcode, result);
1284 this.renew(barcode, true);
1288 * Display the result of a checkout or renewal in the items out table
1290 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1292 var copy = evt.payload.copy;
1293 var record = evt.payload.record;
1294 var circ = evt.payload.circ;
1295 var row = this.circTemplate.cloneNode(true);
1297 if(record.doc_id()) {
1298 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/r/' + record.doc_id());
1301 this.byName(row, 'barcode').innerHTML = copy.barcode();
1302 this.byName(row, 'title').innerHTML = record.title();
1303 this.byName(row, 'author').innerHTML = record.author();
1304 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1305 openils.Util.show(this.byName(row, type));
1307 var date = dojo.date.stamp.fromISOString(circ.due_date());
1308 this.byName(row, 'due_date').innerHTML =
1309 dojo.date.locale.format(date, {selector : 'date'});
1311 // put new circs at the top of the list
1312 var tbody = this.circTbody;
1313 if(itemsOut) tbody = this.itemsOutTbody;
1314 tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1318 SelfCheckManager.prototype.byName = function(node, name) {
1319 return dojo.query('[name=' + name+']', node)[0];
1323 SelfCheckManager.prototype.initPrinter = function() {
1324 try { // Mozilla only
1325 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1326 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1327 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1328 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1329 var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1331 pref.setBoolPref('print.always_print_silent', true);
1333 console.log("Unable to initialize auto-printing");
1338 * Email a receipt for this session's checkouts
1340 SelfCheckManager.prototype.emailSessionReceipt = function(callback) {
1344 // collect the circs and failure info
1348 circIds.push(blob.circ);
1359 fieldmapper.standardRequest(
1360 ['open-ils.circ', 'open-ils.circ.checkout.batch_notify.session.atomic'],
1364 oncomplete : function() {
1365 if (callback) callback(); // fire and forget
1372 * Print a receipt for this session's checkouts
1374 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1377 var circCtx = []; // circ context data. in this case, renewal_failure info
1379 // collect the circs and failure info
1383 circIds.push(blob.circ);
1384 circCtx.push({renewal_failure:blob.renewal_failure});
1392 'format.selfcheck.checkout',
1399 fieldmapper.standardRequest(
1400 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1404 oncomplete : function(r) {
1405 var resp = openils.Util.readResponse(r);
1406 var output = resp.template_output();
1408 self.printData(output.data(), self.checkouts.length, callback);
1410 var error = resp.error_output();
1412 throw new Error("Error creating receipt: " + error.data());
1414 throw new Error("No receipt data returned from server");
1422 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1424 var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1,chrome');
1425 win.document.body.innerHTML = data;
1429 * There is no way to know when the browser is done printing.
1430 * Make a best guess at when to close the print window by basing
1431 * the setTimeout wait on the number of items to be printed plus
1434 var sleepTime = 1000;
1436 sleepTime += (numItems / 2) * 1000;
1440 win.close(); // close the print window
1442 callback(); // fire optional post-print callback
1451 * Print a receipt for this user's items out
1453 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1455 if(!this.itemsOut.length) return;
1457 progressDialog.show(true);
1463 'format.selfcheck.items_out',
1469 fieldmapper.standardRequest(
1470 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1474 oncomplete : function(r) {
1475 progressDialog.hide();
1476 var resp = openils.Util.readResponse(r);
1477 var output = resp.template_output();
1479 self.printData(output.data(), self.itemsOut.length, callback);
1481 var error = resp.error_output();
1483 throw new Error("Error creating receipt: " + error.data());
1485 throw new Error("No receipt data returned from server");
1494 * Print a receipt for this user's holds
1496 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1498 if(!this.holds.length) return;
1500 progressDialog.show(true);
1505 dojo.forEach(this.holds,
1507 holdIds.push(data.hold.id());
1509 //get pickup library info
1510 var pu = fieldmapper.standardRequest(['open-ils.actor','open-ils.actor.org_unit.retrieve'],[null,data.hold.pickup_lib()]);
1512 if(data.status == 4) {
1515 item_title : data.mvr.title(),
1516 item_author : data.mvr.author(),
1517 pickup_lib : pu.name()
1521 queue_position : data.queue_position,
1522 potential_copies : data.potential_copies,
1523 item_title : data.mvr.title(),
1524 item_author : data.mvr.author(),
1525 pickup_lib : pu.name()
1535 'format.selfcheck.holds',
1542 fieldmapper.standardRequest(
1543 ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1547 oncomplete : function(r) {
1548 progressDialog.hide();
1549 var resp = openils.Util.readResponse(r);
1550 var output = resp.template_output();
1552 self.printData(output.data(), self.holds.length, callback);
1554 var error = resp.error_output();
1556 throw new Error("Error creating receipt: " + error.data());
1558 throw new Error("No receipt data returned from server");
1567 SelfCheckManager.prototype.printPaymentReceipt = function(response, callback) {
1570 progressDialog.show(true);
1572 fieldmapper.standardRequest(
1573 ['open-ils.circ', 'open-ils.circ.money.payment_receipt.print'],
1576 params : [this.authtoken, response.payments],
1577 oncomplete : function(r) {
1578 var resp = openils.Util.readResponse(r);
1579 var output = resp.template_output();
1580 progressDialog.hide();
1582 self.printData(output.data(), 1, callback);
1584 var error = resp.error_output();
1586 throw new Error("Error creating receipt: " + error.data());
1588 throw new Error("No receipt data returned from server");
1597 * Print a receipt for this user's fines
1599 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1601 if(!this.creditPayableBalance.length) return;
1602 progressDialog.show(true);
1608 'format.selfcheck.fines',
1614 fieldmapper.standardRequest(
1615 ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1619 oncomplete : function(r) {
1620 progressDialog.hide();
1621 var resp = openils.Util.readResponse(r);
1622 var output = resp.template_output();
1624 self.printData(output.data(), self.finesCount, callback);
1626 var error = resp.error_output();
1628 throw new Error("Error creating receipt: " + error.data());
1630 throw new Error("No receipt data returned from server");
1642 * Logout the patron and return to the login page
1644 SelfCheckManager.prototype.logoutPatron = function(print) {
1645 progressDialog.show(true); // prevent patron from clicking logout link twice
1646 if(print && this.checkouts.length) {
1647 if (dojo.byId('oils-selfck-receipt-print').checked) {
1648 this.printSessionReceipt(
1650 location.href = location.href;
1653 } else if (dojo.byId('oils-selfck-receipt-email').checked) {
1654 this.emailSessionReceipt(
1656 location.href = location.href;
1660 // user elected to get no receipt
1661 location.href = location.href;
1664 location.href = location.href;
1670 * Fire up the manager on page load
1672 openils.Util.addOnLoad(
1674 new SelfCheckManager().init();