1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.cookie');
3 dojo.require('dojo.date.stamp');
4 dojo.require('dijit.form.CheckBox');
5 dojo.require('dijit.form.NumberSpinner');
6 dojo.require('openils.CGI');
7 dojo.require('openils.Util');
8 dojo.require('openils.User');
9 dojo.require('openils.Event');
10 dojo.require('openils.widget.ProgressDialog');
11 dojo.require('openils.widget.OrgUnitFilteringSelect');
14 dojo.requireLocalization('openils.circ', 'selfcheck');
15 var localeStrings = dojo.i18n.getLocalization('openils.circ', 'selfcheck');
17 // set patron timeout default
18 var patronTimeout = 160000; /* 2 minutes, 40 seconds */
20 // 20 second inactivity warning; total default timeout is 3 minutes.
21 var patronTimeoutWarning = 20000;
22 var selfckWarningSetup = false;
23 var selfckWarningTimer;
25 const SET_BARCODE_REGEX = 'opac.barcode_regex';
26 const SET_PATRON_TIMEOUT = 'circ.selfcheck.patron_login_timeout';
27 const SET_AUTO_OVERRIDE_EVENTS = 'circ.selfcheck.auto_override_checkout_events';
28 const SET_PATRON_PASSWORD_REQUIRED = 'circ.selfcheck.patron_password_required';
29 const SET_AUTO_RENEW_INTERVAL = 'circ.checkout_auto_renew_age';
30 const SET_WORKSTATION_REQUIRED = 'circ.selfcheck.workstation_required';
31 const SET_ALERT_POPUP = 'circ.selfcheck.alert.popup';
32 const SET_ALERT_SOUND = 'circ.selfcheck.alert.sound';
33 const SET_CC_PAYMENT_ALLOWED = 'credit.payments.allow';
34 // This setting only comes into play if COPY_NOT_AVAILABLE is in the SET_AUTO_OVERRIDE_EVENTS list
35 const SET_BLOCK_CHECKOUT_ON_COPY_STATUS = 'circ.selfcheck.block_checkout_on_copy_status';
37 // set before the login dialog is rendered
38 openils.User.default_login_agent = 'selfcheck';
40 // start the logout timer
41 function selfckStartTimer() {
44 selfckLogoutWarning();
50 // reset the logout timer
51 function selfckResetTimer() {
52 clearTimeout(timerId);
56 function selfckLogoutWarning() {
58 // connect the logout warning dialog button handlers if needed
59 if (!selfckWarningSetup) {
60 selfckWarningSetup = true;
62 dojo.connect(oilsSelfckLogout, 'onClick',
64 clearTimeout(selfckWarningTimer);
65 oilsSelfckLogoutDialog.hide();
66 SelfCheckManager.prototype.logoutPatron();
70 dojo.connect(oilsSelfckContinue, 'onClick',
72 clearTimeout(selfckWarningTimer);
73 oilsSelfckLogoutDialog.hide();
79 // warn the patron of imminent logout
80 oilsSelfckLogoutDialog.show();
81 selfckWarningTimer = setTimeout(
83 // no action was taken, force a logout.
84 oilsSelfckLogoutDialog.hide();
85 SelfCheckManager.prototype.logoutPatron();
91 function SelfCheckManager() {
93 this.cgi = new openils.CGI();
95 this.workstation = null;
96 this.authtoken = null;
99 this.patronBarcodeRegex = null;
105 // During renewals, keep track of the ID of the previous circulation.
106 // Previous circ is used for tracking failed renewals (for receipts).
107 this.prevCirc = null;
109 // current item barcode
110 this.itemBarcode = null;
112 // are we currently performing a renewal?
113 this.isRenewal = false;
115 // dict of org unit settings for "here"
116 this.orgSettings = {};
118 // Construct a mock checkout for debugging purposes
119 if(this.mockCheckouts = this.cgi.param('mock-circ')) {
121 this.mockCheckout = {
123 record : new fieldmapper.mvr(),
124 copy : new fieldmapper.acp(),
125 circ : new fieldmapper.circ()
129 this.mockCheckout.payload.record.title('Jazz improvisation for guitar');
130 this.mockCheckout.payload.record.author('Wise, Les');
131 this.mockCheckout.payload.record.isbn('0634033565');
132 this.mockCheckout.payload.copy.barcode('123456789');
133 this.mockCheckout.payload.circ.renewal_remaining(1);
134 this.mockCheckout.payload.circ.parent_circ(1);
135 this.mockCheckout.payload.circ.due_date('2012-12-21');
141 SelfCheckManager.prototype.setupStaffLogin = function(verify) {
143 if(verify) oilsSetupUser();
144 this.staff = openils.User.user;
145 this.workstation = openils.User.workstation;
146 this.authtoken = openils.User.authtoken;
152 * Fetch the org-unit settings, initialize the display, etc.
154 SelfCheckManager.prototype.init = function() {
156 this.setupStaffLogin();
157 this.loadOrgSettings();
159 this.circTbody = dojo.byId('oils-selfck-circ-tbody');
160 this.itemsOutTbody = dojo.byId('oils-selfck-circ-out-tbody');
162 // workstation is required but none provided
163 if(this.orgSettings[SET_WORKSTATION_REQUIRED] && !this.workstation) {
164 if(confirm(dojo.string.substitute(localeStrings.WORKSTATION_REQUIRED))) {
165 this.registerWorkstation();
171 // connect onclick handlers to the various navigation links
173 'oils-selfck-hold-details-link' : function() { self.drawHoldsPage(); },
174 'oils-selfck-view-fines-link' : function() { self.drawFinesPage(); },
175 'oils-selfck-pay-fines-link' : function() {
176 self.goToTab("payment");
177 self.drawPayFinesPage(
179 self.getSelectedFinesTotal(),
180 self.getSelectedFineTransactions(),
182 var evt = openils.Event.parse(resp);
184 var message = evt + '';
185 if(evt.textcode == 'CREDIT_PROCESSOR_DECLINED_TRANSACTION' && evt.payload)
186 message += '\n' + evt.payload.error_message;
187 if(evt.textcode == 'INVALID_USER_XACT_ID')
188 message += '\n' + localeStrings.PAYMENT_INVALID_USER_XACT_ID;
189 self.handleAlert(message, true, 'payment-failure');
193 self.patron.last_xact_id(resp.last_xact_id); // update to match latest from server
194 self.printPaymentReceipt(
197 self.updateFinesSummary();
198 self.drawFinesPage();
204 'oils-selfck-nav-home' : function() { self.drawCircPage(); },
205 'oils-selfck-nav-logout' : function() { self.logoutPatron(); },
206 'oils-selfck-nav-logout-print' : function() { self.logoutPatron(true); },
207 'oils-selfck-items-out-details-link' : function() { self.drawItemsOutPage(); },
208 'oils-selfck-print-list-link' : function() { self.printList(); }
211 for(var id in linkHandlers)
212 dojo.connect(dojo.byId(id), 'onclick', linkHandlers[id]);
215 if(this.cgi.param('patron')) {
217 // Patron barcode via cgi param. Mainly used for debugging and
218 // only works if password is not required by policy
219 this.loginPatron(this.cgi.param('patron'));
222 this.drawLoginPage();
226 * To test printing, pass a URL param of 'testprint'. The value for the param
227 * should be a JSON string like so: [{circ:<circ_id>}, ...]
229 var testPrint = this.cgi.param('testprint');
231 this.checkouts = JSON2js(testPrint);
232 this.printSessionReceipt();
238 SelfCheckManager.prototype.getSelectedFinesTotal = function() {
241 dojo.query("[name=selector]", this.finesTbody),
244 total += Number(input.getAttribute("balance_owed"));
247 return total.toFixed(2);
250 SelfCheckManager.prototype.getSelectedFineTransactions = function() {
251 return dojo.query("[name=selector]", this.finesTbody).
252 filter(function (o) { return o.checked }).
256 o.getAttribute("xact"),
257 Number(o.getAttribute("balance_owed")).toFixed(2)
264 * Registers a new workstion
266 SelfCheckManager.prototype.registerWorkstation = function() {
268 oilsSelfckWsDialog.show();
270 new openils.User().buildPermOrgSelector(
271 'REGISTER_WORKSTATION',
272 oilsSelfckWsLocSelector,
278 dojo.connect(oilsSelfckWsSubmit, 'onClick',
281 oilsSelfckWsDialog.hide();
282 var name = oilsSelfckWsLocSelector.attr('displayedValue') + '-' + oilsSelfckWsName.attr('value');
284 var res = fieldmapper.standardRequest(
285 ['open-ils.actor', 'open-ils.actor.workstation.register'],
287 self.authtoken, name, oilsSelfckWsLocSelector.attr('value')
292 if(evt = openils.Event.parse(res)) {
293 if(evt.textcode == 'WORKSTATION_NAME_EXISTS') {
294 if(confirm(localeStrings.WORKSTATION_EXISTS)) {
295 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
297 self.registerWorkstation();
304 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
311 * Loads the org unit settings
313 SelfCheckManager.prototype.loadOrgSettings = function() {
315 var settings = fieldmapper.aou.fetchOrgSettingBatch(
316 this.staff.ws_ou(), [
321 SET_AUTO_OVERRIDE_EVENTS,
322 SET_BLOCK_CHECKOUT_ON_COPY_STATUS,
323 SET_PATRON_PASSWORD_REQUIRED,
324 SET_AUTO_RENEW_INTERVAL,
325 SET_WORKSTATION_REQUIRED,
326 SET_CC_PAYMENT_ALLOWED
332 this.orgSettings[k] = settings[k].value;
335 if(settings[SET_BARCODE_REGEX])
336 this.patronBarcodeRegex = new RegExp(settings[SET_BARCODE_REGEX].value);
338 // Subtract the timeout warning interval from the configured timeout
339 // so that when taken together they add up to the configured amount.
340 if(settings[SET_PATRON_TIMEOUT]) {
342 (parseInt(settings[SET_PATRON_TIMEOUT].value) * 1000)
343 - patronTimeoutWarning;
347 SelfCheckManager.prototype.drawLoginPage = function() {
350 var bcHandler = function(barcode_or_usrname) {
351 // handle patron barcode/usrname entry
353 if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
355 // password is required. wire up the scan box to read it
357 msg : localeStrings.ENTER_PASSWORD,
358 handler : function(pw) { self.loginPatron(barcode_or_usrname, pw); },
363 // password is not required, go ahead and login
364 self.loginPatron(barcode_or_usrname);
369 msg : localeStrings.PLEASE_LOGIN,
377 SelfCheckManager.prototype.loginPatron = function(barcode_or_usrname, passwd) {
382 this.setupStaffLogin(true); // verify still valid
386 console.log('testing ' + barcode_or_usrname);
387 if (barcode_or_usrname.match(this.patronBarcodeRegex)) {
388 console.log('barcode');
389 barcode = barcode_or_usrname;
391 console.log('usrname');
392 usrname = barcode_or_usrname;
395 if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
398 // would only happen in dev/debug mode when using the patron= param
399 alert('password required by org setting. remove patron= from URL');
403 // patron password is required. Verify it.
406 new openils.User().auth_verify(
407 { username : usrname, barcode : barcode,
408 type : 'opac', passwd : passwd, agent : 'selfcheck' },
411 self.fetchPatron(barcode, usrname);
414 // auth verify failed
416 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode_or_usrname]),
417 false, 'login-failure'
419 self.drawLoginPage();
425 this.fetchPatron(barcode, usrname);
429 SelfCheckManager.prototype.fetchPatron = function(barcode, usrname) {
431 var patron_id = fieldmapper.standardRequest(
432 ['open-ils.actor', 'open-ils.actor.user.retrieve_id_by_barcode_or_username'],
433 {params : [this.authtoken, barcode, usrname]}
436 // retrieve the fleshed user by id
437 this.patron = fieldmapper.standardRequest(
438 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
439 {params : [this.authtoken, patron_id]}
442 var evt = openils.Event.parse(this.patron);
444 // verify validity of the card used to log in
445 var inactiveCard = false;
449 card = this.patron.cards().filter(
450 function(c) { return (c.barcode() == barcode); })[0];
452 card = this.patron.card();
454 inactiveCard = !openils.Util.isTrue(card.active());
457 if(evt || inactiveCard) {
459 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode || usrname]),
460 false, 'login-failure'
462 this.drawLoginPage();
466 this.handleAlert('', false, 'login-success');
467 dojo.byId('oils-selfck-user-banner').innerHTML =
468 dojo.string.substitute(localeStrings.WELCOME_BANNER, [this.patron.first_given_name()]);
474 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
476 console.log("Handling alert " + message);
478 dojo.byId('oils-selfck-status-div').innerHTML = message;
481 openils.Util.addCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
483 openils.Util.removeCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
485 if(shouldPopup && this.orgSettings[SET_ALERT_POPUP])
488 if(sound && this.orgSettings[SET_ALERT_SOUND])
489 openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
494 * Manages the main input box
495 * @param msg The context message to display with the box
496 * @param clearOnly Don't update the context message, just clear the value and re-focus
497 * @param handler Optional "on-enter" handler.
499 SelfCheckManager.prototype.updateScanBox = function(args) {
503 selfckScanBox.domNode.select();
505 selfckScanBox.attr('value', '');
509 selfckScanBox.domNode.setAttribute('type', 'password');
511 selfckScanBox.domNode.setAttribute('type', '');
515 selfckScanBox.attr('value', args.value);
518 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
520 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
521 dojo.disconnect(selfckScanBox._lastHandler);
525 selfckScanBox._lastHandler = dojo.connect(
529 if(e.keyCode != dojo.keys.ENTER)
531 args.handler(selfckScanBox.attr('value'));
536 selfckScanBox.focus();
540 * Sets up the checkout/renewal interface
542 SelfCheckManager.prototype.drawCircPage = function() {
544 openils.Util.show('oils-selfck-bottom-div');
545 openils.Util.show('oils-selfck-circ-tbody', 'table-row-group');
546 this.goToTab('checkout');
548 while(this.itemsOutTbody.childNodes[0])
549 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
553 msg : localeStrings.ENTER_BARCODE,
554 handler : function(barcode) { self.checkout(barcode); }
557 if(!this.circTemplate)
558 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
561 this.updateFinesSummary();
564 this.updateHoldsSummary();
567 this.updateCircSummary();
569 // render mock checkouts for debugging?
570 if(this.mockCheckouts) {
571 for(var i in [1,2,3])
572 this.displayCheckout(this.mockCheckout, 'checkout');
577 SelfCheckManager.prototype.updateFinesSummary = function() {
581 fieldmapper.standardRequest(
582 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
584 params : [this.authtoken, this.patron.id()],
585 oncomplete : function(r) {
587 var summary = openils.Util.readResponse(r);
589 dojo.byId('oils-selfck-fines-total').innerHTML =
590 dojo.string.substitute(
591 localeStrings.TOTAL_FINES_ACCOUNT,
592 ['<b>' + summary.balance_owed() + '</b>']
595 self.creditPayableBalance = summary.balance_owed();
602 SelfCheckManager.prototype.drawItemsOutPage = function() {
603 openils.Util.hide('oils-selfck-circ-tbody');
605 this.goToTab('items_out');
607 while(this.itemsOutTbody.childNodes[0])
608 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
610 progressDialog.show(true);
613 fieldmapper.standardRequest(
614 ['open-ils.circ', 'open-ils.circ.actor.user.checked_out.atomic'],
617 params : [this.authtoken, this.patron.id()],
618 oncomplete : function(r) {
620 var resp = openils.Util.readResponse(r);
622 var circs = resp.sort(
624 if(a.circ.due_date() > b.circ.due_date())
630 progressDialog.hide();
635 self.itemsOut.push(circ.circ.id());
636 self.displayCheckout(
638 (circ.circ.parent_circ()) ? 'renew' : 'checkout',
649 SelfCheckManager.prototype.goToTab = function(name) {
652 openils.Util.hide('oils-selfck-fines-page');
653 openils.Util.hide('oils-selfck-payment-page');
654 openils.Util.hide('oils-selfck-holds-page');
655 openils.Util.hide('oils-selfck-circ-page');
656 openils.Util.hide('oils-selfck-pay-fines-link');
663 openils.Util.show('oils-selfck-circ-page');
666 openils.Util.show('oils-selfck-circ-page');
669 openils.Util.show('oils-selfck-holds-page');
672 openils.Util.show('oils-selfck-fines-page');
675 openils.Util.show('oils-selfck-payment-page');
681 SelfCheckManager.prototype.printList = function() {
685 switch(this.tabName) {
687 this.printSessionReceipt();
690 this.printItemsOutReceipt();
693 this.printHoldsReceipt();
696 this.printFinesReceipt();
701 SelfCheckManager.prototype.updateHoldsSummary = function() {
703 if(!this.holdsSummary) {
704 var summary = fieldmapper.standardRequest(
705 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
706 {params : [this.authtoken, this.patron.id()]}
709 this.holdsSummary = {};
710 this.holdsSummary.ready = Number(summary['4']);
711 this.holdsSummary.total = 0;
713 for(var i in summary)
714 this.holdsSummary.total += Number(summary[i]);
717 dojo.byId('oils-selfck-holds-total').innerHTML =
718 dojo.string.substitute(
719 localeStrings.TOTAL_HOLDS,
720 ['<b>' + this.holdsSummary.total + '</b>']
723 dojo.byId('oils-selfck-holds-ready').innerHTML =
724 dojo.string.substitute(
725 localeStrings.HOLDS_READY_FOR_PICKUP,
726 ['<b>' + this.holdsSummary.ready + '</b>']
731 SelfCheckManager.prototype.updateCircSummary = function(increment) {
733 if(!this.circSummary) {
735 var summary = fieldmapper.standardRequest(
736 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
737 {params : [this.authtoken, this.patron.id()]}
741 total : Number(summary.out) + Number(summary.overdue),
742 overdue : Number(summary.overdue),
748 // local checkout occurred. Add to the total and the session.
749 this.circSummary.total += 1;
750 this.circSummary.session += 1;
753 dojo.byId('oils-selfck-circ-account-total').innerHTML =
754 dojo.string.substitute(
755 localeStrings.TOTAL_ITEMS_ACCOUNT,
756 ['<b>' + this.circSummary.total + '</b>']
759 dojo.byId('oils-selfck-circ-session-total').innerHTML =
760 dojo.string.substitute(
761 localeStrings.TOTAL_ITEMS_SESSION,
762 ['<b>' + this.circSummary.session + '</b>']
767 SelfCheckManager.prototype.drawHoldsPage = function() {
769 // TODO add option to hid scanBox
770 // this.updateScanBox(...)
772 this.goToTab('holds');
774 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
775 if(!this.holdTemplate)
776 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
777 while(this.holdTbody.childNodes[0])
778 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
780 progressDialog.show(true);
783 fieldmapper.standardRequest( // fetch the hold IDs
785 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
787 params : [this.authtoken, this.patron.id()],
789 oncomplete : function(r) {
790 var ids = openils.Util.readResponse(r);
791 if(!ids || ids.length == 0) {
792 progressDialog.hide();
796 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
797 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve'],
799 params : [self.authtoken, ids],
800 onresponse : function(rr) {
801 progressDialog.hide();
802 self.insertHold(openils.Util.readResponse(rr));
811 SelfCheckManager.prototype.insertHold = function(data) {
813 // store hold data to pass along to receipt printing function
814 this.holds.push(data);
816 var row = this.holdTemplate.cloneNode(true);
818 if(data.mvr.isbn()) {
819 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/r/' + data.mvr.doc_id());
822 this.byName(row, 'title').innerHTML = data.mvr.title();
823 this.byName(row, 'author').innerHTML = data.mvr.author();
825 if(data.status == 4) {
827 // hold is ready for pickup
828 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
832 // hold is still pending
833 this.byName(row, 'status').innerHTML =
834 dojo.string.substitute(
835 localeStrings.HOLD_STATUS_WAITING,
836 [data.queue_position, data.potential_copies]
840 // find the correct place the table to slot in the hold based on queue position
842 var position = (data.status == 4) ? 0 : data.queue_position;
843 row.setAttribute('position', position);
845 for(var i = 0; i < this.holdTbody.childNodes.length; i++) {
846 var node = this.holdTbody.childNodes[i];
847 if(Number(node.getAttribute('position')) >= position) {
848 this.holdTbody.insertBefore(row, node);
853 this.holdTbody.appendChild(row);
857 SelfCheckManager.prototype.drawFinesPage = function() {
859 // TODO add option to hid scanBox
860 // this.updateScanBox(...)
862 this.goToTab('fines');
863 progressDialog.show(true);
865 if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
866 openils.Util.show('oils-selfck-pay-fines-link', 'inline');
869 this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
870 if(!this.finesTemplate)
871 this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
872 while(this.finesTbody.childNodes[0])
873 this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
875 // when user clicks on a selector checkbox, update the total owed
876 var updateSelected = function() {
879 dojo.query('[name=selector]', this.finesTbody),
882 total += Number(input.getAttribute('balance_owed'));
886 total = total.toFixed(2);
887 dojo.byId('oils-selfck-selected-total').innerHTML =
888 dojo.string.substitute(localeStrings.TOTAL_FINES_SELECTED, [total]);
891 // wire up the batch on/off selector
892 var sel = dojo.byId('oils-selfck-fines-selector');
893 sel.onchange = function() {
895 dojo.query('[name=selector]', this.finesTbody),
897 input.checked = sel.checked;
903 var handler = function(dataList) {
905 self.finesCount = dataList.length;
906 self.finesData = dataList;
908 for(var i in dataList) {
910 var data = dataList[i];
911 var row = self.finesTemplate.cloneNode(true);
912 var type = data.transaction.xact_type();
914 if(type == 'circulation') {
915 self.byName(row, 'type').innerHTML = type;
916 self.byName(row, 'details').innerHTML = data.record.title();
918 } else if(type == 'grocery') {
919 self.byName(row, 'type').innerHTML = localeStrings.MISCELLANEOUS; // Go ahead and head off any confusion around "grocery".
920 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
923 self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
924 self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
925 self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
928 var selector = self.byName(row, 'selector')
929 selector.onchange = updateSelected;
930 selector.setAttribute('xact', data.transaction.id());
931 selector.setAttribute('balance_owed', data.transaction.balance_owed());
932 selector.checked = true;
934 self.finesTbody.appendChild(row);
941 fieldmapper.standardRequest(
942 ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
944 params : [this.authtoken, this.patron.id()],
945 oncomplete : function(r) {
946 progressDialog.hide();
947 handler(openils.Util.readResponse(r));
953 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
955 var resp = fieldmapper.standardRequest(
956 ['open-ils.circ', 'open-ils.circ.transit.abort'],
957 {params : [this.authtoken, {barcode : barcode}]}
960 // resp == 1 on success
961 if(openils.Event.parse(resp))
964 var resp = fieldmapper.standardRequest(
965 ['open-ils.circ', 'open-ils.circ.checkin.override'],
968 patron_id : this.patron.id(),
969 copy_barcode : barcode,
975 if(!resp.length) resp = [resp];
976 for(var i = 0; i < resp.length; i++) {
977 var tc = openils.Event.parse(resp[i]).textcode;
978 if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
989 * Check out a single item. If the item is already checked
990 * out to the patron, redirect to renew()
992 SelfCheckManager.prototype.checkout = function(barcode, override) {
997 this.prevCirc = null;
1000 this.updateScanbox(null, true);
1004 if(this.mockCheckouts) {
1005 // if we're in mock-checkout mode, just insert another
1006 // fake circ into the table and get out of here.
1007 this.displayCheckout(this.mockCheckout, 'checkout');
1011 // TODO see if it's a patron barcode
1012 // TODO see if this item has already been checked out in this session
1014 var method = 'open-ils.circ.checkout.full';
1015 if(override) method += '.override';
1017 console.log("Checkout out item " + barcode + " with method " + method);
1019 var result = fieldmapper.standardRequest(
1020 ['open-ils.circ', method],
1023 patron_id : this.patron.id(),
1024 copy_barcode : barcode
1029 var stat = this.handleXactResult('checkout', barcode, result);
1032 this.checkout(barcode, true);
1033 } else if(stat.doOver) {
1034 this.checkout(barcode);
1035 } else if(stat.renew) {
1036 this.renew(barcode);
1040 SelfCheckManager.prototype.failPartMessage = function(result) {
1041 if (result.payload && result.payload.fail_part) {
1042 var stringKey = "FAIL_PART_" +
1043 result.payload.fail_part.replace(/\./g, "_");
1044 return localeStrings[stringKey];
1050 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
1052 var displayText = '';
1054 // If true, the display message is important enough to pop up. Whether or not
1055 // an alert() actually occurs, depends on org unit settings
1057 var sound = ''; // sound file reference
1058 var payload = result.payload || {};
1059 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
1060 var blockStatuses = this.orgSettings[SET_BLOCK_CHECKOUT_ON_COPY_STATUS];
1062 if(result.textcode == 'NO_SESSION') {
1064 return this.logoutStaff();
1066 } else if(result.textcode == 'SUCCESS') {
1068 if(action == 'checkout') {
1070 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
1071 this.displayCheckout(result, 'checkout');
1073 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
1074 // A hold was fulfilled, update the hold numbers in the circ summary
1075 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
1076 this.holdsSummary = null;
1077 this.updateHoldsSummary();
1080 this.updateCircSummary(true);
1082 } else if(action == 'renew') {
1084 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
1085 this.displayCheckout(result, 'renew');
1088 this.checkouts.push({circ : result.payload.circ.id()});
1089 sound = 'checkout-success';
1090 this.updateScanBox();
1092 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
1094 // Server says the item is already checked out. If it's checked out to the
1095 // current user, we may need to renew it.
1097 if(payload.old_circ) {
1100 old_circ refers to the previous checkout IFF it's for the same user.
1101 If no auto-renew interval is not defined, assume we should renew it
1102 If an auto-renew interval is defined and the payload comes back with
1103 auto_renew set to true, do the renewal. Otherwise, let the patron know
1104 the item is already checked out to them. */
1106 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
1107 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
1108 this.prevCirc = payload.old_circ.id();
1109 return { renew : true };
1113 sound = 'checkout-failure';
1114 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
1118 if( // copy is marked lost. if configured to do so, check it in and try again.
1119 result.payload.copy &&
1120 result.payload.copy.status() == /* LOST */ 3 &&
1121 overrideEvents && overrideEvents.length &&
1122 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
1124 if(this.checkin(item)) {
1125 return { doOver : true };
1130 // item is checked out to some other user
1132 sound = 'checkout-failure';
1133 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1136 this.updateScanBox({select:true});
1141 if(overrideEvents && overrideEvents.length) {
1143 // see if the events we received are all in the list of
1144 // events to override
1146 if(!result.length) result = [result];
1148 var override = true;
1149 for(var i = 0; i < result.length; i++) {
1151 var match = overrideEvents.filter(function(e) { return (e == result[i].textcode); })[0];
1158 if(result[i].textcode == 'COPY_NOT_AVAILABLE' && blockStatuses && blockStatuses.length) {
1160 var stat = result[i].payload.status(); // copy status
1161 if(typeof stat == 'object') stat = stat.id();
1163 var match2 = blockStatuses.filter(function(e) { return (e == stat); })[0];
1165 if(match2) { // copy is in a blocked status
1171 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1172 // to override a transit, we have to abort the transit and check it in first
1173 if(this.checkin(item, true)) {
1174 return { doOver : true };
1182 return { override : true };
1185 this.updateScanBox({select : true});
1187 sound = 'checkout-failure';
1189 if(action == 'renew')
1190 this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1195 switch(result.textcode) {
1197 // TODO custom handler for blocking penalties
1199 case 'MAX_RENEWALS_REACHED' :
1200 displayText = dojo.string.substitute(
1201 localeStrings.MAX_RENEWALS, [item]);
1204 case 'ITEM_NOT_CATALOGED' :
1205 displayText = dojo.string.substitute(
1206 localeStrings.ITEM_NOT_CATALOGED, [item]);
1209 case 'OPEN_CIRCULATION_EXISTS' :
1210 displayText = dojo.string.substitute(
1211 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1216 console.error('Unhandled event ' + result.textcode);
1218 if (!(displayText = this.failPartMessage(result))) {
1219 if (action == 'checkout' || action == 'renew') {
1220 displayText = dojo.string.substitute(
1221 localeStrings.GENERIC_CIRC_FAILURE, [item]);
1223 displayText = dojo.string.substitute(
1224 localeStrings.UNKNOWN_ERROR, [result.textcode]);
1230 this.handleAlert(displayText, popup, sound);
1238 SelfCheckManager.prototype.renew = function(barcode, override) {
1240 var method = 'open-ils.circ.renew';
1241 if(override) method += '.override';
1243 console.log("Renewing item " + barcode + " with method " + method);
1245 var result = fieldmapper.standardRequest(
1246 ['open-ils.circ', method],
1249 patron_id : this.patron.id(),
1250 copy_barcode : barcode
1255 console.log(js2JSON(result));
1257 var stat = this.handleXactResult('renew', barcode, result);
1260 this.renew(barcode, true);
1264 * Display the result of a checkout or renewal in the items out table
1266 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1268 var copy = evt.payload.copy;
1269 var record = evt.payload.record;
1270 var circ = evt.payload.circ;
1271 var row = this.circTemplate.cloneNode(true);
1273 if(record.doc_id()) {
1274 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/r/' + record.doc_id());
1277 this.byName(row, 'barcode').innerHTML = copy.barcode();
1278 this.byName(row, 'title').innerHTML = record.title();
1279 this.byName(row, 'author').innerHTML = record.author();
1280 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1281 openils.Util.show(this.byName(row, type));
1283 var date = dojo.date.stamp.fromISOString(circ.due_date());
1284 this.byName(row, 'due_date').innerHTML =
1285 dojo.date.locale.format(date, {selector : 'date'});
1287 // put new circs at the top of the list
1288 var tbody = this.circTbody;
1289 if(itemsOut) tbody = this.itemsOutTbody;
1290 tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1294 SelfCheckManager.prototype.byName = function(node, name) {
1295 return dojo.query('[name=' + name+']', node)[0];
1299 SelfCheckManager.prototype.initPrinter = function() {
1300 try { // Mozilla only
1301 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1302 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1303 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1304 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1305 var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1307 pref.setBoolPref('print.always_print_silent', true);
1309 console.log("Unable to initialize auto-printing");
1314 * Print a receipt for this session's checkouts
1316 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1319 var circCtx = []; // circ context data. in this case, renewal_failure info
1321 // collect the circs and failure info
1325 circIds.push(blob.circ);
1326 circCtx.push({renewal_failure:blob.renewal_failure});
1334 'format.selfcheck.checkout',
1341 fieldmapper.standardRequest(
1342 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1346 oncomplete : function(r) {
1347 var resp = openils.Util.readResponse(r);
1348 var output = resp.template_output();
1350 self.printData(output.data(), self.checkouts.length, callback);
1352 var error = resp.error_output();
1354 throw new Error("Error creating receipt: " + error.data());
1356 throw new Error("No receipt data returned from server");
1364 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1366 var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1,chrome');
1367 win.document.body.innerHTML = data;
1371 * There is no way to know when the browser is done printing.
1372 * Make a best guess at when to close the print window by basing
1373 * the setTimeout wait on the number of items to be printed plus
1376 var sleepTime = 1000;
1378 sleepTime += (numItems / 2) * 1000;
1382 win.close(); // close the print window
1384 callback(); // fire optional post-print callback
1392 * Print a receipt for this user's items out
1394 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1396 if(!this.itemsOut.length) return;
1398 progressDialog.show(true);
1404 'format.selfcheck.items_out',
1410 fieldmapper.standardRequest(
1411 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1415 oncomplete : function(r) {
1416 progressDialog.hide();
1417 var resp = openils.Util.readResponse(r);
1418 var output = resp.template_output();
1420 self.printData(output.data(), self.itemsOut.length, callback);
1422 var error = resp.error_output();
1424 throw new Error("Error creating receipt: " + error.data());
1426 throw new Error("No receipt data returned from server");
1435 * Print a receipt for this user's holds
1437 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1439 if(!this.holds.length) return;
1441 progressDialog.show(true);
1446 dojo.forEach(this.holds,
1448 holdIds.push(data.hold.id());
1450 //get pickup library info
1451 var pu = fieldmapper.standardRequest(['open-ils.actor','open-ils.actor.org_unit.retrieve'],[null,data.hold.pickup_lib()]);
1453 if(data.status == 4) {
1456 item_title : data.mvr.title(),
1457 item_author : data.mvr.author(),
1458 pickup_lib : pu.name()
1462 queue_position : data.queue_position,
1463 potential_copies : data.potential_copies,
1464 item_title : data.mvr.title(),
1465 item_author : data.mvr.author(),
1466 pickup_lib : pu.name()
1476 'format.selfcheck.holds',
1483 fieldmapper.standardRequest(
1484 ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1488 oncomplete : function(r) {
1489 progressDialog.hide();
1490 var resp = openils.Util.readResponse(r);
1491 var output = resp.template_output();
1493 self.printData(output.data(), self.holds.length, callback);
1495 var error = resp.error_output();
1497 throw new Error("Error creating receipt: " + error.data());
1499 throw new Error("No receipt data returned from server");
1508 SelfCheckManager.prototype.printPaymentReceipt = function(response, callback) {
1511 progressDialog.show(true);
1513 fieldmapper.standardRequest(
1514 ['open-ils.circ', 'open-ils.circ.money.payment_receipt.print'],
1517 params : [this.authtoken, response.payments],
1518 oncomplete : function(r) {
1519 var resp = openils.Util.readResponse(r);
1520 var output = resp.template_output();
1521 progressDialog.hide();
1523 self.printData(output.data(), 1, callback);
1525 var error = resp.error_output();
1527 throw new Error("Error creating receipt: " + error.data());
1529 throw new Error("No receipt data returned from server");
1538 * Print a receipt for this user's fines
1540 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1542 if(!this.creditPayableBalance.length) return;
1543 progressDialog.show(true);
1549 'format.selfcheck.fines',
1555 fieldmapper.standardRequest(
1556 ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1560 oncomplete : function(r) {
1561 progressDialog.hide();
1562 var resp = openils.Util.readResponse(r);
1563 var output = resp.template_output();
1565 self.printData(output.data(), self.finesCount, callback);
1567 var error = resp.error_output();
1569 throw new Error("Error creating receipt: " + error.data());
1571 throw new Error("No receipt data returned from server");
1583 * Logout the patron and return to the login page
1585 SelfCheckManager.prototype.logoutPatron = function(print) {
1586 progressDialog.show(true); // prevent patron from clicking logout link twice
1587 if(print && this.checkouts.length) {
1588 this.printSessionReceipt(
1590 location.href = location.href;
1594 location.href = location.href;
1600 * Fire up the manager on page load
1602 openils.Util.addOnLoad(
1604 new SelfCheckManager().init();