1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dijit.form.CheckBox');
4 dojo.require('dijit.form.NumberSpinner');
5 dojo.require('openils.CGI');
6 dojo.require('openils.Util');
7 dojo.require('openils.User');
8 dojo.require('openils.Event');
9 dojo.require('openils.widget.ProgressDialog');
10 dojo.require('openils.widget.OrgUnitFilteringSelect');
12 dojo.requireLocalization('openils.circ', 'selfcheck');
13 var localeStrings = dojo.i18n.getLocalization('openils.circ', 'selfcheck');
16 const SET_BARCODE_REGEX = 'opac.barcode_regex';
17 const SET_PATRON_TIMEOUT = 'circ.selfcheck.patron_login_timeout';
18 const SET_AUTO_OVERRIDE_EVENTS = 'circ.selfcheck.auto_override_checkout_events';
19 const SET_PATRON_PASSWORD_REQUIRED = 'circ.selfcheck.patron_password_required';
20 const SET_AUTO_RENEW_INTERVAL = 'circ.checkout_auto_renew_age';
21 const SET_WORKSTATION_REQUIRED = 'circ.selfcheck.workstation_required';
22 const SET_ALERT_POPUP = 'circ.selfcheck.alert.popup';
23 const SET_ALERT_SOUND = 'circ.selfcheck.alert.sound';
24 const SET_CC_PAYMENT_ALLOWED = 'credit.payments.allow';
26 function SelfCheckManager() {
28 this.cgi = new openils.CGI();
30 this.workstation = null;
31 this.authtoken = null;
34 this.patronBarcodeRegex = null;
39 // During renewals, keep track of the ID of the previous circulation.
40 // Previous circ is used for tracking failed renewals (for receipts).
43 // current item barcode
44 this.itemBarcode = null;
46 // are we currently performing a renewal?
47 this.isRenewal = false;
49 // dict of org unit settings for "here"
50 this.orgSettings = {};
52 // Construct a mock checkout for debugging purposes
53 if(this.mockCheckouts = this.cgi.param('mock-circ')) {
57 record : new fieldmapper.mvr(),
58 copy : new fieldmapper.acp(),
59 circ : new fieldmapper.circ()
63 this.mockCheckout.payload.record.title('Jazz improvisation for guitar');
64 this.mockCheckout.payload.record.author('Wise, Les');
65 this.mockCheckout.payload.record.isbn('0634033565');
66 this.mockCheckout.payload.copy.barcode('123456789');
67 this.mockCheckout.payload.circ.renewal_remaining(1);
68 this.mockCheckout.payload.circ.parent_circ(1);
69 this.mockCheckout.payload.circ.due_date('2012-12-21');
78 * Fetch the org-unit settings, initialize the display, etc.
80 SelfCheckManager.prototype.init = function() {
82 this.staff = openils.User.user;
83 this.workstation = openils.User.workstation;
84 this.authtoken = openils.User.authtoken;
85 this.loadOrgSettings();
87 this.circTbody = dojo.byId('oils-selfck-circ-tbody');
88 this.itemsOutTbody = dojo.byId('oils-selfck-circ-out-tbody');
90 // workstation is required but none provided
91 if(this.orgSettings[SET_WORKSTATION_REQUIRED] && !this.workstation) {
92 if(confirm(dojo.string.substitute(localeStrings.WORKSTATION_REQUIRED))) {
93 this.registerWorkstation();
99 // connect onclick handlers to the various navigation links
101 'oils-selfck-hold-details-link' : function() { self.drawHoldsPage(); },
102 'oils-selfck-view-fines-link' : function() { self.drawFinesPage(); },
103 'oils-selfck-pay-fines-link' : function() {
104 self.goToTab("payment");
105 self.drawPayFinesPage(
107 self.getSelectedFinesTotal(),
108 self.getSelectedFineTransactions(),
110 var evt = openils.Event.parse(resp);
112 var message = evt + '';
113 if(evt.textcode == 'CREDIT_PROCESSOR_DECLINED_TRANSACTION' && evt.payload)
114 message += '\n' + evt.payload.error_message;
115 self.handleAlert(message, true, 'payment-failure');
118 self.printPaymentReceipt(
121 self.updateFinesSummary();
122 self.drawFinesPage();
128 'oils-selfck-nav-home' : function() { self.drawCircPage(); },
129 'oils-selfck-nav-logout' : function() { self.logoutPatron(); },
130 'oils-selfck-nav-logout-print' : function() { self.logoutPatron(true); },
131 'oils-selfck-items-out-details-link' : function() { self.drawItemsOutPage(); },
132 'oils-selfck-print-list-link' : function() { self.printList(); }
135 for(var id in linkHandlers)
136 dojo.connect(dojo.byId(id), 'onclick', linkHandlers[id]);
139 if(this.cgi.param('patron')) {
141 // Patron barcode via cgi param. Mainly used for debugging and
142 // only works if password is not required by policy
143 this.loginPatron(this.cgi.param('patron'));
146 this.drawLoginPage();
150 * To test printing, pass a URL param of 'testprint'. The value for the param
151 * should be a JSON string like so: [{circ:<circ_id>}, ...]
153 var testPrint = this.cgi.param('testprint');
155 this.checkouts = JSON2js(testPrint);
156 this.printSessionReceipt();
162 SelfCheckManager.prototype.getSelectedFinesTotal = function() {
165 dojo.query("[name=selector]", this.finesTbody),
168 total += Number(input.getAttribute("balance_owed"));
171 return total.toFixed(2);
174 SelfCheckManager.prototype.getSelectedFineTransactions = function() {
175 return dojo.query("[name=selector]", this.finesTbody).
176 filter(function (o) { return o.checked }).
180 o.getAttribute("xact"),
181 Number(o.getAttribute("balance_owed")).toFixed(2)
188 * Registers a new workstion
190 SelfCheckManager.prototype.registerWorkstation = function() {
192 oilsSelfckWsDialog.show();
194 new openils.User().buildPermOrgSelector(
195 'REGISTER_WORKSTATION',
196 oilsSelfckWsLocSelector,
202 dojo.connect(oilsSelfckWsSubmit, 'onClick',
205 oilsSelfckWsDialog.hide();
206 var name = oilsSelfckWsLocSelector.attr('displayedValue') + '-' + oilsSelfckWsName.attr('value');
208 var res = fieldmapper.standardRequest(
209 ['open-ils.actor', 'open-ils.actor.workstation.register'],
211 self.authtoken, name, oilsSelfckWsLocSelector.attr('value')
216 if(evt = openils.Event.parse(res)) {
217 if(evt.textcode == 'WORKSTATION_NAME_EXISTS') {
218 if(confirm(localeStrings.WORKSTATION_EXISTS)) {
219 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
221 self.registerWorkstation();
228 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
235 * Loads the org unit settings
237 SelfCheckManager.prototype.loadOrgSettings = function() {
239 var settings = fieldmapper.aou.fetchOrgSettingBatch(
240 this.staff.ws_ou(), [
245 SET_AUTO_OVERRIDE_EVENTS,
246 SET_PATRON_PASSWORD_REQUIRED,
247 SET_AUTO_RENEW_INTERVAL,
248 SET_WORKSTATION_REQUIRED,
249 SET_CC_PAYMENT_ALLOWED
255 this.orgSettings[k] = settings[k].value;
258 if(settings[SET_BARCODE_REGEX])
259 this.patronBarcodeRegex = new RegExp(settings[SET_BARCODE_REGEX].value);
262 SelfCheckManager.prototype.drawLoginPage = function() {
265 var bcHandler = function(barcode) {
266 // handle patron barcode entry
268 if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
270 // password is required. wire up the scan box to read it
272 msg : 'Please enter your password', // TODO i18n
273 handler : function(pw) { self.loginPatron(barcode, pw); },
278 // password is not required, go ahead and login
279 self.loginPatron(barcode);
284 msg : 'Please log in with your library barcode.', // TODO
292 SelfCheckManager.prototype.loginPatron = function(barcode, passwd) {
294 if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
297 // would only happen in dev/debug mode when using the patron= param
298 alert('password required by org setting. remove patron= from URL');
302 // patron password is required. Verify it.
304 var res = fieldmapper.standardRequest(
305 ['open-ils.actor', 'open-ils.actor.verify_user_password'],
306 {params : [this.authtoken, barcode, null, hex_md5(passwd)]}
310 // user-not-found results in login failure
312 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]),
313 false, 'login-failure'
315 this.drawLoginPage();
320 // retrieve the fleshed user by barcode
321 this.patron = fieldmapper.standardRequest(
322 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve_by_barcode'],
323 {params : [this.authtoken, barcode]}
326 var evt = openils.Event.parse(this.patron);
329 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]),
330 false, 'login-failure'
332 this.drawLoginPage();
336 this.handleAlert('', false, 'login-success');
337 dojo.byId('oils-selfck-user-banner').innerHTML =
338 dojo.string.substitute(localeStrings.WELCOME_BANNER, [this.patron.first_given_name()]);
344 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
346 console.log("Handling alert " + message);
348 dojo.byId('oils-selfck-status-div').innerHTML = message;
350 if(shouldPopup && this.orgSettings[SET_ALERT_POPUP])
353 if(sound && this.orgSettings[SET_ALERT_SOUND])
354 openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
359 * Manages the main input box
360 * @param msg The context message to display with the box
361 * @param clearOnly Don't update the context message, just clear the value and re-focus
362 * @param handler Optional "on-enter" handler.
364 SelfCheckManager.prototype.updateScanBox = function(args) {
368 selfckScanBox.domNode.select();
370 selfckScanBox.attr('value', '');
374 selfckScanBox.domNode.setAttribute('type', 'password');
376 selfckScanBox.domNode.setAttribute('type', '');
380 selfckScanBox.attr('value', args.value);
383 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
385 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
386 dojo.disconnect(selfckScanBox._lastHandler);
390 selfckScanBox._lastHandler = dojo.connect(
394 if(e.keyCode != dojo.keys.ENTER)
396 args.handler(selfckScanBox.attr('value'));
401 selfckScanBox.focus();
405 * Sets up the checkout/renewal interface
407 SelfCheckManager.prototype.drawCircPage = function() {
409 openils.Util.show('oils-selfck-circ-tbody', 'table-row-group');
410 this.goToTab('checkout');
412 while(this.itemsOutTbody.childNodes[0])
413 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
417 msg : 'Please enter an item barcode', // TODO i18n
418 handler : function(barcode) { self.checkout(barcode); }
421 if(!this.circTemplate)
422 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
425 this.updateFinesSummary();
428 this.updateHoldsSummary();
431 this.updateCircSummary();
433 // render mock checkouts for debugging?
434 if(this.mockCheckouts) {
435 for(var i in [1,2,3])
436 this.displayCheckout(this.mockCheckout, 'checkout');
441 SelfCheckManager.prototype.updateFinesSummary = function() {
445 fieldmapper.standardRequest(
446 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
448 params : [this.authtoken, this.patron.id()],
449 oncomplete : function(r) {
451 var summary = openils.Util.readResponse(r);
453 dojo.byId('oils-selfck-fines-total').innerHTML =
454 dojo.string.substitute(
455 localeStrings.TOTAL_FINES_ACCOUNT,
456 [summary.balance_owed()]
459 self.creditPayableBalance = summary.balance_owed();
466 SelfCheckManager.prototype.drawItemsOutPage = function() {
467 openils.Util.hide('oils-selfck-circ-tbody');
469 this.goToTab('items_out');
471 while(this.itemsOutTbody.childNodes[0])
472 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
474 progressDialog.show(true);
477 fieldmapper.standardRequest(
478 ['open-ils.circ', 'open-ils.circ.actor.user.checked_out.atomic'],
481 params : [this.authtoken, this.patron.id()],
482 oncomplete : function(r) {
484 var resp = openils.Util.readResponse(r);
486 var circs = resp.sort(
488 if(a.circ.due_date() > b.circ.due_date())
494 progressDialog.hide();
499 self.itemsOut.push(circ.circ.id());
500 self.displayCheckout(
502 (circ.circ.parent_circ()) ? 'renew' : 'checkout',
513 SelfCheckManager.prototype.goToTab = function(name) {
516 openils.Util.hide('oils-selfck-fines-page');
517 openils.Util.hide('oils-selfck-payment-page');
518 openils.Util.hide('oils-selfck-holds-page');
519 openils.Util.hide('oils-selfck-circ-page');
520 openils.Util.hide('oils-selfck-pay-fines-link');
524 openils.Util.show('oils-selfck-circ-page');
527 openils.Util.show('oils-selfck-circ-page');
530 openils.Util.show('oils-selfck-holds-page');
533 openils.Util.show('oils-selfck-fines-page');
536 openils.Util.show('oils-selfck-payment-page');
542 SelfCheckManager.prototype.printList = function() {
543 switch(this.tabName) {
545 this.printSessionReceipt();
548 this.printItemsOutReceipt();
551 this.printHoldsReceipt();
554 this.printFinesReceipt();
559 SelfCheckManager.prototype.updateHoldsSummary = function() {
561 if(!this.holdsSummary) {
562 var summary = fieldmapper.standardRequest(
563 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
564 {params : [this.authtoken, this.patron.id()]}
567 this.holdsSummary = {};
568 this.holdsSummary.ready = Number(summary['4']);
569 this.holdsSummary.total = 0;
571 for(var i in summary)
572 this.holdsSummary.total += Number(summary[i]);
575 dojo.byId('oils-selfck-holds-total').innerHTML =
576 dojo.string.substitute(
577 localeStrings.TOTAL_HOLDS,
578 [this.holdsSummary.total]
581 dojo.byId('oils-selfck-holds-ready').innerHTML =
582 dojo.string.substitute(
583 localeStrings.HOLDS_READY_FOR_PICKUP,
584 [this.holdsSummary.ready]
589 SelfCheckManager.prototype.updateCircSummary = function(increment) {
591 if(!this.circSummary) {
593 var summary = fieldmapper.standardRequest(
594 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
595 {params : [this.authtoken, this.patron.id()]}
599 total : Number(summary.out) + Number(summary.overdue),
600 overdue : Number(summary.overdue),
606 // local checkout occurred. Add to the total and the session.
607 this.circSummary.total += 1;
608 this.circSummary.session += 1;
611 dojo.byId('oils-selfck-circ-account-total').innerHTML =
612 dojo.string.substitute(
613 localeStrings.TOTAL_ITEMS_ACCOUNT,
614 [this.circSummary.total]
617 dojo.byId('oils-selfck-circ-session-total').innerHTML =
618 dojo.string.substitute(
619 localeStrings.TOTAL_ITEMS_SESSION,
620 [this.circSummary.session]
625 SelfCheckManager.prototype.drawHoldsPage = function() {
627 // TODO add option to hid scanBox
628 // this.updateScanBox(...)
630 this.goToTab('holds');
632 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
633 if(!this.holdTemplate)
634 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
635 while(this.holdTbody.childNodes[0])
636 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
638 progressDialog.show(true);
641 fieldmapper.standardRequest( // fetch the hold IDs
643 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
645 params : [this.authtoken, this.patron.id()],
647 oncomplete : function(r) {
648 var ids = openils.Util.readResponse(r);
649 if(!ids || ids.length == 0) {
650 progressDialog.hide();
654 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
655 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve.atomic'],
657 params : [self.authtoken, ids],
659 oncomplete : function(rr) {
660 self.drawHolds(openils.Util.readResponse(rr));
670 * Fetch and add a single hold to the list of holds
672 SelfCheckManager.prototype.drawHolds = function(holds) {
675 // sort available holds to the top of the list
676 // followed by queue position order
678 if(a.status == 4) return -1;
679 if(a.queue_position < b.queue_position) return -1;
686 progressDialog.hide();
688 for(var i in holds) {
691 var row = this.holdTemplate.cloneNode(true);
693 if(data.mvr.isbn()) {
694 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + data.mvr.isbn());
697 this.byName(row, 'title').innerHTML = data.mvr.title();
698 this.byName(row, 'author').innerHTML = data.mvr.author();
700 if(data.status == 4) {
702 // hold is ready for pickup
703 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
707 // hold is still pending
708 this.byName(row, 'status').innerHTML =
709 dojo.string.substitute(
710 localeStrings.HOLD_STATUS_WAITING,
711 [data.queue_position, data.potential_copies]
715 this.holdTbody.appendChild(row);
720 SelfCheckManager.prototype.drawFinesPage = function() {
722 // TODO add option to hid scanBox
723 // this.updateScanBox(...)
725 this.goToTab('fines');
726 progressDialog.show(true);
728 if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
729 openils.Util.show('oils-selfck-pay-fines-link', 'inline');
732 this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
733 if(!this.finesTemplate)
734 this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
735 while(this.finesTbody.childNodes[0])
736 this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
738 // when user clicks on a selector checkbox, update the total owed
739 var updateSelected = function() {
742 dojo.query('[name=selector]', this.finesTbody),
745 total += Number(input.getAttribute('balance_owed'));
749 total = total.toFixed(2);
750 dojo.byId('oils-selfck-selected-total').innerHTML =
751 dojo.string.substitute(localeStrings.TOTAL_FINES_SELECTED, [total]);
754 // wire up the batch on/off selector
755 var sel = dojo.byId('oils-selfck-fines-selector');
756 sel.onchange = function() {
758 dojo.query('[name=selector]', this.finesTbody),
760 input.checked = sel.checked;
766 var handler = function(dataList) {
768 self.finesCount = dataList.length;
769 self.finesData = dataList;
771 for(var i in dataList) {
773 var data = dataList[i];
774 var row = self.finesTemplate.cloneNode(true);
775 var type = data.transaction.xact_type();
777 if(type == 'circulation') {
778 self.byName(row, 'type').innerHTML = type;
779 self.byName(row, 'details').innerHTML = data.record.title();
781 } else if(type == 'grocery') {
782 self.byName(row, 'type').innerHTML = 'Miscellaneous'; // Go ahead and head off any confusion around "grocery". TODO i18n
783 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
786 self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
787 self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
788 self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
791 var selector = self.byName(row, 'selector')
792 selector.onchange = updateSelected;
793 selector.setAttribute('xact', data.transaction.id());
794 selector.setAttribute('balance_owed', data.transaction.balance_owed());
795 selector.checked = true;
797 self.finesTbody.appendChild(row);
804 fieldmapper.standardRequest(
805 ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
807 params : [this.authtoken, this.patron.id()],
808 oncomplete : function(r) {
809 progressDialog.hide();
810 handler(openils.Util.readResponse(r));
816 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
818 var resp = fieldmapper.standardRequest(
819 ['open-ils.circ', 'open-ils.circ.transit.abort'],
820 {params : [this.authtoken, {barcode : barcode}]}
823 // resp == 1 on success
824 if(openils.Event.parse(resp))
827 var resp = fieldmapper.standardRequest(
828 ['open-ils.circ', 'open-ils.circ.checkin.override'],
831 patron_id : this.patron.id(),
832 copy_barcode : barcode,
838 if(!resp.length) resp = [resp];
839 for(var i = 0; i < resp.length; i++) {
840 var tc = openils.Event.parse(resp[i]).textcode;
841 if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
852 * Check out a single item. If the item is already checked
853 * out to the patron, redirect to renew()
855 SelfCheckManager.prototype.checkout = function(barcode, override) {
857 this.prevCirc = null;
860 this.updateScanbox(null, true);
864 if(this.mockCheckouts) {
865 // if we're in mock-checkout mode, just insert another
866 // fake circ into the table and get out of here.
867 this.displayCheckout(this.mockCheckout, 'checkout');
871 // TODO see if it's a patron barcode
872 // TODO see if this item has already been checked out in this session
874 var method = 'open-ils.circ.checkout.full';
875 if(override) method += '.override';
877 console.log("Checkout out item " + barcode + " with method " + method);
879 var result = fieldmapper.standardRequest(
880 ['open-ils.circ', 'open-ils.circ.checkout.full'],
883 patron_id : this.patron.id(),
884 copy_barcode : barcode
889 var stat = this.handleXactResult('checkout', barcode, result);
892 this.checkout(barcode, true);
893 } else if(stat.doOver) {
894 this.checkout(barcode);
895 } else if(stat.renew) {
900 SelfCheckManager.prototype.failPartMessage = function(result) {
901 if (result.payload && result.payload.fail_part) {
902 var stringKey = "FAIL_PART_" +
903 result.payload.fail_part.replace(/\./g, "_");
904 return localeStrings[stringKey];
910 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
912 var displayText = '';
914 // If true, the display message is important enough to pop up. Whether or not
915 // an alert() actually occurs, depends on org unit settings
917 var sound = ''; // sound file reference
918 var payload = result.payload || {};
919 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
921 if(result.textcode == 'NO_SESSION') {
923 return this.logoutStaff();
925 } else if(result.textcode == 'SUCCESS') {
927 if(action == 'checkout') {
929 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
930 this.displayCheckout(result, 'checkout');
932 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
933 // A hold was fulfilled, update the hold numbers in the circ summary
934 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
935 this.holdsSummary = null;
936 this.updateHoldsSummary();
939 this.updateCircSummary(true);
941 } else if(action == 'renew') {
943 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
944 this.displayCheckout(result, 'renew');
947 this.checkouts.push({circ : result.payload.circ.id()});
948 sound = 'checkout-success';
949 this.updateScanBox();
951 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
953 // Server says the item is already checked out. If it's checked out to the
954 // current user, we may need to renew it.
956 if(payload.old_circ) {
959 old_circ refers to the previous checkout IFF it's for the same user.
960 If no auto-renew interval is not defined, assume we should renew it
961 If an auto-renew interval is defined and the payload comes back with
962 auto_renew set to true, do the renewal. Otherwise, let the patron know
963 the item is already checked out to them. */
965 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
966 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
967 this.prevCirc = payload.old_circ.id();
968 return { renew : true };
972 sound = 'checkout-failure';
973 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
977 if( // copy is marked lost. if configured to do so, check it in and try again.
978 result.payload.copy &&
979 result.payload.copy.status() == /* LOST */ 3 &&
980 overrideEvents && overrideEvents.length &&
981 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
983 if(this.checkin(item)) {
984 return { doOver : true };
989 // item is checked out to some other user
991 sound = 'checkout-failure';
992 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
995 this.updateScanBox({select:true});
1000 if(overrideEvents && overrideEvents.length) {
1002 // see if the events we received are all in the list of
1003 // events to override
1005 if(!result.length) result = [result];
1007 var override = true;
1008 for(var i = 0; i < result.length; i++) {
1009 var match = overrideEvents.filter(
1010 function(e) { return (e == result[i].textcode); })[0];
1016 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1017 // to override a transit, we have to abort the transit and check it in first
1018 if(this.checkin(item, true)) {
1019 return { doOver : true };
1028 return { override : true };
1031 this.updateScanBox({select : true});
1033 sound = 'checkout-failure';
1035 if(action == 'renew')
1036 this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1041 switch(result.textcode) {
1043 // TODO custom handler for blocking penalties
1045 case 'MAX_RENEWALS_REACHED' :
1046 displayText = dojo.string.substitute(
1047 localeStrings.MAX_RENEWALS, [item]);
1050 case 'ITEM_NOT_CATALOGED' :
1051 displayText = dojo.string.substitute(
1052 localeStrings.ITEM_NOT_CATALOGED, [item]);
1055 case 'OPEN_CIRCULATION_EXISTS' :
1056 displayText = dojo.string.substitute(
1057 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1062 console.error('Unhandled event ' + result.textcode);
1064 if (!(displayText = this.failPartMessage(result))) {
1065 if (action == 'checkout' || action == 'renew') {
1066 displayText = dojo.string.substitute(
1067 localeStrings.GENERIC_CIRC_FAILURE, [item]);
1069 displayText = dojo.string.substitute(
1070 localeStrings.UNKNOWN_ERROR, [result.textcode]);
1076 this.handleAlert(displayText, popup, sound);
1084 SelfCheckManager.prototype.renew = function(barcode, override) {
1086 var method = 'open-ils.circ.renew';
1087 if(override) method += '.override';
1089 console.log("Renewing item " + barcode + " with method " + method);
1091 var result = fieldmapper.standardRequest(
1092 ['open-ils.circ', method],
1095 patron_id : this.patron.id(),
1096 copy_barcode : barcode
1101 console.log(js2JSON(result));
1103 var stat = this.handleXactResult('renew', barcode, result);
1106 this.renew(barcode, true);
1110 * Display the result of a checkout or renewal in the items out table
1112 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1114 var copy = evt.payload.copy;
1115 var record = evt.payload.record;
1116 var circ = evt.payload.circ;
1117 var row = this.circTemplate.cloneNode(true);
1120 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + record.isbn());
1123 this.byName(row, 'barcode').innerHTML = copy.barcode();
1124 this.byName(row, 'title').innerHTML = record.title();
1125 this.byName(row, 'author').innerHTML = record.author();
1126 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1127 openils.Util.show(this.byName(row, type));
1129 var date = dojo.date.stamp.fromISOString(circ.due_date());
1130 this.byName(row, 'due_date').innerHTML =
1131 dojo.date.locale.format(date, {selector : 'date'});
1133 // put new circs at the top of the list
1134 var tbody = this.circTbody;
1135 if(itemsOut) tbody = this.itemsOutTbody;
1136 tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1140 SelfCheckManager.prototype.byName = function(node, name) {
1141 return dojo.query('[name=' + name+']', node)[0];
1145 SelfCheckManager.prototype.initPrinter = function() {
1146 try { // Mozilla only
1147 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1148 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1149 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1150 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1151 var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1153 pref.setBoolPref('print.always_print_silent', true);
1155 console.log("Unable to initialize auto-printing");
1160 * Print a receipt for this session's checkouts
1162 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1165 var circCtx = []; // circ context data. in this case, renewal_failure info
1167 // collect the circs and failure info
1171 circIds.push(blob.circ);
1172 circCtx.push({renewal_failure:blob.renewal_failure});
1180 'format.selfcheck.checkout',
1187 fieldmapper.standardRequest(
1188 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1192 oncomplete : function(r) {
1193 var resp = openils.Util.readResponse(r);
1194 var output = resp.template_output();
1196 self.printData(output.data(), self.checkouts.length, callback);
1198 var error = resp.error_output();
1200 throw new Error("Error creating receipt: " + error.data());
1202 throw new Error("No receipt data returned from server");
1210 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1212 var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1');
1213 win.document.body.innerHTML = data;
1217 * There is no way to know when the browser is done printing.
1218 * Make a best guess at when to close the print window by basing
1219 * the setTimeout wait on the number of items to be printed plus
1222 var sleepTime = 1000;
1224 sleepTime += (numItems / 2) * 1000;
1228 win.close(); // close the print window
1230 callback(); // fire optional post-print callback
1238 * Print a receipt for this user's items out
1240 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1242 if(!this.itemsOut.length) return;
1244 progressDialog.show(true);
1250 'format.selfcheck.items_out',
1256 fieldmapper.standardRequest(
1257 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1261 oncomplete : function(r) {
1262 progressDialog.hide();
1263 var resp = openils.Util.readResponse(r);
1264 var output = resp.template_output();
1266 self.printData(output.data(), self.itemsOut.length, callback);
1268 var error = resp.error_output();
1270 throw new Error("Error creating receipt: " + error.data());
1272 throw new Error("No receipt data returned from server");
1281 * Print a receipt for this user's items out
1283 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1285 if(!this.holds.length) return;
1287 progressDialog.show(true);
1292 dojo.forEach(this.holds,
1294 holdIds.push(data.hold.id());
1295 if(data.status == 4) {
1296 holdData.push({ready : true});
1299 queue_position : data.queue_position,
1300 potential_copies : data.potential_copies
1310 'format.selfcheck.holds',
1317 fieldmapper.standardRequest(
1318 ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1322 oncomplete : function(r) {
1323 progressDialog.hide();
1324 var resp = openils.Util.readResponse(r);
1325 var output = resp.template_output();
1327 self.printData(output.data(), self.holds.length, callback);
1329 var error = resp.error_output();
1331 throw new Error("Error creating receipt: " + error.data());
1333 throw new Error("No receipt data returned from server");
1342 SelfCheckManager.prototype.printPaymentReceipt = function(paymentIds, callback) {
1345 progressDialog.show(true);
1347 fieldmapper.standardRequest(
1348 ['open-ils.circ', 'open-ils.circ.money.payment_receipt.print'],
1351 params : [this.authtoken, paymentIds],
1352 oncomplete : function(r) {
1353 var resp = openils.Util.readResponse(r);
1354 var output = resp.template_output();
1355 progressDialog.hide();
1357 self.printData(output.data(), 1, callback);
1359 var error = resp.error_output();
1361 throw new Error("Error creating receipt: " + error.data());
1363 throw new Error("No receipt data returned from server");
1372 * Print a receipt for this user's items out
1374 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1376 progressDialog.show(true);
1382 'format.selfcheck.fines',
1388 fieldmapper.standardRequest(
1389 ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1393 oncomplete : function(r) {
1394 progressDialog.hide();
1395 var resp = openils.Util.readResponse(r);
1396 var output = resp.template_output();
1398 self.printData(output.data(), self.finesCount, callback);
1400 var error = resp.error_output();
1402 throw new Error("Error creating receipt: " + error.data());
1404 throw new Error("No receipt data returned from server");
1416 * Logout the patron and return to the login page
1418 SelfCheckManager.prototype.logoutPatron = function(print) {
1419 if(print && this.checkouts.length) {
1420 this.printSessionReceipt(
1422 location.href = location.href;
1426 location.href = location.href;
1432 * Fire up the manager on page load
1434 openils.Util.addOnLoad(
1436 new SelfCheckManager().init();