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';
25 // This setting only comes into play if COPY_NOT_AVAILABLE is in the SET_AUTO_OVERRIDE_EVENTS list
26 const SET_BLOCK_CHECKOUT_ON_COPY_STATUS = 'circ.selfcheck.block_checkout_on_copy_status';
28 function SelfCheckManager() {
30 this.cgi = new openils.CGI();
32 this.workstation = null;
33 this.authtoken = null;
36 this.patronBarcodeRegex = null;
41 // During renewals, keep track of the ID of the previous circulation.
42 // Previous circ is used for tracking failed renewals (for receipts).
45 // current item barcode
46 this.itemBarcode = null;
48 // are we currently performing a renewal?
49 this.isRenewal = false;
51 // dict of org unit settings for "here"
52 this.orgSettings = {};
54 // Construct a mock checkout for debugging purposes
55 if(this.mockCheckouts = this.cgi.param('mock-circ')) {
59 record : new fieldmapper.mvr(),
60 copy : new fieldmapper.acp(),
61 circ : new fieldmapper.circ()
65 this.mockCheckout.payload.record.title('Jazz improvisation for guitar');
66 this.mockCheckout.payload.record.author('Wise, Les');
67 this.mockCheckout.payload.record.isbn('0634033565');
68 this.mockCheckout.payload.copy.barcode('123456789');
69 this.mockCheckout.payload.circ.renewal_remaining(1);
70 this.mockCheckout.payload.circ.parent_circ(1);
71 this.mockCheckout.payload.circ.due_date('2012-12-21');
80 * Fetch the org-unit settings, initialize the display, etc.
82 SelfCheckManager.prototype.init = function() {
84 this.staff = openils.User.user;
85 this.workstation = openils.User.workstation;
86 this.authtoken = openils.User.authtoken;
87 this.loadOrgSettings();
89 this.circTbody = dojo.byId('oils-selfck-circ-tbody');
90 this.itemsOutTbody = dojo.byId('oils-selfck-circ-out-tbody');
92 // workstation is required but none provided
93 if(this.orgSettings[SET_WORKSTATION_REQUIRED] && !this.workstation) {
94 if(confirm(dojo.string.substitute(localeStrings.WORKSTATION_REQUIRED))) {
95 this.registerWorkstation();
101 // connect onclick handlers to the various navigation links
103 'oils-selfck-hold-details-link' : function() { self.drawHoldsPage(); },
104 'oils-selfck-view-fines-link' : function() { self.drawFinesPage(); },
105 'oils-selfck-pay-fines-link' : function() {
106 self.goToTab("payment");
107 self.drawPayFinesPage(
109 self.getSelectedFinesTotal(),
110 self.getSelectedFineTransactions(),
112 var evt = openils.Event.parse(resp);
114 var message = evt + '';
115 if(evt.textcode == 'CREDIT_PROCESSOR_DECLINED_TRANSACTION' && evt.payload)
116 message += '\n' + evt.payload.error_message;
117 if(evt.textcode == 'INVALID_USER_XACT_ID')
118 message += '\n' + localeStrings.PAYMENT_INVALID_USER_XACT_ID;
119 self.handleAlert(message, true, 'payment-failure');
123 self.patron.last_xact_id(resp.last_xact_id); // update to match latest from server
124 self.printPaymentReceipt(
127 self.updateFinesSummary();
128 self.drawFinesPage();
134 'oils-selfck-nav-home' : function() { self.drawCircPage(); },
135 'oils-selfck-nav-logout' : function() { self.logoutPatron(); },
136 'oils-selfck-nav-logout-print' : function() { self.logoutPatron(true); },
137 'oils-selfck-items-out-details-link' : function() { self.drawItemsOutPage(); },
138 'oils-selfck-print-list-link' : function() { self.printList(); }
141 for(var id in linkHandlers)
142 dojo.connect(dojo.byId(id), 'onclick', linkHandlers[id]);
145 if(this.cgi.param('patron')) {
147 // Patron barcode via cgi param. Mainly used for debugging and
148 // only works if password is not required by policy
149 this.loginPatron(this.cgi.param('patron'));
152 this.drawLoginPage();
156 * To test printing, pass a URL param of 'testprint'. The value for the param
157 * should be a JSON string like so: [{circ:<circ_id>}, ...]
159 var testPrint = this.cgi.param('testprint');
161 this.checkouts = JSON2js(testPrint);
162 this.printSessionReceipt();
168 SelfCheckManager.prototype.getSelectedFinesTotal = function() {
171 dojo.query("[name=selector]", this.finesTbody),
174 total += Number(input.getAttribute("balance_owed"));
177 return total.toFixed(2);
180 SelfCheckManager.prototype.getSelectedFineTransactions = function() {
181 return dojo.query("[name=selector]", this.finesTbody).
182 filter(function (o) { return o.checked }).
186 o.getAttribute("xact"),
187 Number(o.getAttribute("balance_owed")).toFixed(2)
194 * Registers a new workstion
196 SelfCheckManager.prototype.registerWorkstation = function() {
198 oilsSelfckWsDialog.show();
200 new openils.User().buildPermOrgSelector(
201 'REGISTER_WORKSTATION',
202 oilsSelfckWsLocSelector,
208 dojo.connect(oilsSelfckWsSubmit, 'onClick',
211 oilsSelfckWsDialog.hide();
212 var name = oilsSelfckWsLocSelector.attr('displayedValue') + '-' + oilsSelfckWsName.attr('value');
214 var res = fieldmapper.standardRequest(
215 ['open-ils.actor', 'open-ils.actor.workstation.register'],
217 self.authtoken, name, oilsSelfckWsLocSelector.attr('value')
222 if(evt = openils.Event.parse(res)) {
223 if(evt.textcode == 'WORKSTATION_NAME_EXISTS') {
224 if(confirm(localeStrings.WORKSTATION_EXISTS)) {
225 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
227 self.registerWorkstation();
234 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
241 * Loads the org unit settings
243 SelfCheckManager.prototype.loadOrgSettings = function() {
245 var settings = fieldmapper.aou.fetchOrgSettingBatch(
246 this.staff.ws_ou(), [
251 SET_AUTO_OVERRIDE_EVENTS,
252 SET_BLOCK_CHECKOUT_ON_COPY_STATUS,
253 SET_PATRON_PASSWORD_REQUIRED,
254 SET_AUTO_RENEW_INTERVAL,
255 SET_WORKSTATION_REQUIRED,
256 SET_CC_PAYMENT_ALLOWED
262 this.orgSettings[k] = settings[k].value;
265 if(settings[SET_BARCODE_REGEX])
266 this.patronBarcodeRegex = new RegExp(settings[SET_BARCODE_REGEX].value);
269 SelfCheckManager.prototype.drawLoginPage = function() {
272 var bcHandler = function(barcode) {
273 // handle patron barcode entry
275 if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
277 // password is required. wire up the scan box to read it
279 msg : 'Please enter your password', // TODO i18n
280 handler : function(pw) { self.loginPatron(barcode, pw); },
285 // password is not required, go ahead and login
286 self.loginPatron(barcode);
291 msg : 'Please log in with your library barcode.', // TODO
299 SelfCheckManager.prototype.loginPatron = function(barcode, passwd) {
301 if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
304 // would only happen in dev/debug mode when using the patron= param
305 alert('password required by org setting. remove patron= from URL');
309 // patron password is required. Verify it.
311 var res = fieldmapper.standardRequest(
312 ['open-ils.actor', 'open-ils.actor.verify_user_password'],
313 {params : [this.authtoken, barcode, null, hex_md5(passwd)]}
317 // user-not-found results in login failure
319 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]),
320 false, 'login-failure'
322 this.drawLoginPage();
327 // retrieve the fleshed user by barcode
328 this.patron = fieldmapper.standardRequest(
329 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve_by_barcode'],
330 {params : [this.authtoken, barcode]}
333 var evt = openils.Event.parse(this.patron);
336 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]),
337 false, 'login-failure'
339 this.drawLoginPage();
343 this.handleAlert('', false, 'login-success');
344 dojo.byId('oils-selfck-user-banner').innerHTML =
345 dojo.string.substitute(localeStrings.WELCOME_BANNER, [this.patron.first_given_name()]);
351 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
353 console.log("Handling alert " + message);
355 dojo.byId('oils-selfck-status-div').innerHTML = message;
357 if(shouldPopup && this.orgSettings[SET_ALERT_POPUP])
360 if(sound && this.orgSettings[SET_ALERT_SOUND])
361 openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
366 * Manages the main input box
367 * @param msg The context message to display with the box
368 * @param clearOnly Don't update the context message, just clear the value and re-focus
369 * @param handler Optional "on-enter" handler.
371 SelfCheckManager.prototype.updateScanBox = function(args) {
375 selfckScanBox.domNode.select();
377 selfckScanBox.attr('value', '');
381 selfckScanBox.domNode.setAttribute('type', 'password');
383 selfckScanBox.domNode.setAttribute('type', '');
387 selfckScanBox.attr('value', args.value);
390 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
392 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
393 dojo.disconnect(selfckScanBox._lastHandler);
397 selfckScanBox._lastHandler = dojo.connect(
401 if(e.keyCode != dojo.keys.ENTER)
403 args.handler(selfckScanBox.attr('value'));
408 selfckScanBox.focus();
412 * Sets up the checkout/renewal interface
414 SelfCheckManager.prototype.drawCircPage = function() {
416 openils.Util.show('oils-selfck-circ-tbody', 'table-row-group');
417 this.goToTab('checkout');
419 while(this.itemsOutTbody.childNodes[0])
420 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
424 msg : 'Please enter an item barcode', // TODO i18n
425 handler : function(barcode) { self.checkout(barcode); }
428 if(!this.circTemplate)
429 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
432 this.updateFinesSummary();
435 this.updateHoldsSummary();
438 this.updateCircSummary();
440 // render mock checkouts for debugging?
441 if(this.mockCheckouts) {
442 for(var i in [1,2,3])
443 this.displayCheckout(this.mockCheckout, 'checkout');
448 SelfCheckManager.prototype.updateFinesSummary = function() {
452 fieldmapper.standardRequest(
453 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
455 params : [this.authtoken, this.patron.id()],
456 oncomplete : function(r) {
458 var summary = openils.Util.readResponse(r);
460 dojo.byId('oils-selfck-fines-total').innerHTML =
461 dojo.string.substitute(
462 localeStrings.TOTAL_FINES_ACCOUNT,
463 [summary.balance_owed()]
466 self.creditPayableBalance = summary.balance_owed();
473 SelfCheckManager.prototype.drawItemsOutPage = function() {
474 openils.Util.hide('oils-selfck-circ-tbody');
476 this.goToTab('items_out');
478 while(this.itemsOutTbody.childNodes[0])
479 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
481 progressDialog.show(true);
484 fieldmapper.standardRequest(
485 ['open-ils.circ', 'open-ils.circ.actor.user.checked_out.atomic'],
488 params : [this.authtoken, this.patron.id()],
489 oncomplete : function(r) {
491 var resp = openils.Util.readResponse(r);
493 var circs = resp.sort(
495 if(a.circ.due_date() > b.circ.due_date())
501 progressDialog.hide();
506 self.itemsOut.push(circ.circ.id());
507 self.displayCheckout(
509 (circ.circ.parent_circ()) ? 'renew' : 'checkout',
520 SelfCheckManager.prototype.goToTab = function(name) {
523 openils.Util.hide('oils-selfck-fines-page');
524 openils.Util.hide('oils-selfck-payment-page');
525 openils.Util.hide('oils-selfck-holds-page');
526 openils.Util.hide('oils-selfck-circ-page');
527 openils.Util.hide('oils-selfck-pay-fines-link');
531 openils.Util.show('oils-selfck-circ-page');
534 openils.Util.show('oils-selfck-circ-page');
537 openils.Util.show('oils-selfck-holds-page');
540 openils.Util.show('oils-selfck-fines-page');
543 openils.Util.show('oils-selfck-payment-page');
549 SelfCheckManager.prototype.printList = function() {
550 switch(this.tabName) {
552 this.printSessionReceipt();
555 this.printItemsOutReceipt();
558 this.printHoldsReceipt();
561 this.printFinesReceipt();
566 SelfCheckManager.prototype.updateHoldsSummary = function() {
568 if(!this.holdsSummary) {
569 var summary = fieldmapper.standardRequest(
570 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
571 {params : [this.authtoken, this.patron.id()]}
574 this.holdsSummary = {};
575 this.holdsSummary.ready = Number(summary['4']);
576 this.holdsSummary.total = 0;
578 for(var i in summary)
579 this.holdsSummary.total += Number(summary[i]);
582 dojo.byId('oils-selfck-holds-total').innerHTML =
583 dojo.string.substitute(
584 localeStrings.TOTAL_HOLDS,
585 [this.holdsSummary.total]
588 dojo.byId('oils-selfck-holds-ready').innerHTML =
589 dojo.string.substitute(
590 localeStrings.HOLDS_READY_FOR_PICKUP,
591 [this.holdsSummary.ready]
596 SelfCheckManager.prototype.updateCircSummary = function(increment) {
598 if(!this.circSummary) {
600 var summary = fieldmapper.standardRequest(
601 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
602 {params : [this.authtoken, this.patron.id()]}
606 total : Number(summary.out) + Number(summary.overdue),
607 overdue : Number(summary.overdue),
613 // local checkout occurred. Add to the total and the session.
614 this.circSummary.total += 1;
615 this.circSummary.session += 1;
618 dojo.byId('oils-selfck-circ-account-total').innerHTML =
619 dojo.string.substitute(
620 localeStrings.TOTAL_ITEMS_ACCOUNT,
621 [this.circSummary.total]
624 dojo.byId('oils-selfck-circ-session-total').innerHTML =
625 dojo.string.substitute(
626 localeStrings.TOTAL_ITEMS_SESSION,
627 [this.circSummary.session]
632 SelfCheckManager.prototype.drawHoldsPage = function() {
634 // TODO add option to hid scanBox
635 // this.updateScanBox(...)
637 this.goToTab('holds');
639 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
640 if(!this.holdTemplate)
641 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
642 while(this.holdTbody.childNodes[0])
643 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
645 progressDialog.show(true);
648 fieldmapper.standardRequest( // fetch the hold IDs
650 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
652 params : [this.authtoken, this.patron.id()],
654 oncomplete : function(r) {
655 var ids = openils.Util.readResponse(r);
656 if(!ids || ids.length == 0) {
657 progressDialog.hide();
661 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
662 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve.atomic'],
664 params : [self.authtoken, ids],
666 oncomplete : function(rr) {
667 self.drawHolds(openils.Util.readResponse(rr));
677 * Fetch and add a single hold to the list of holds
679 SelfCheckManager.prototype.drawHolds = function(holds) {
682 // sort available holds to the top of the list
683 // followed by queue position order
685 if(a.status == 4) return -1;
686 if(a.queue_position < b.queue_position) return -1;
693 progressDialog.hide();
695 for(var i in holds) {
698 var row = this.holdTemplate.cloneNode(true);
700 if(data.mvr.isbn()) {
701 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + data.mvr.isbn());
704 this.byName(row, 'title').innerHTML = data.mvr.title();
705 this.byName(row, 'author').innerHTML = data.mvr.author();
707 if(data.status == 4) {
709 // hold is ready for pickup
710 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
714 // hold is still pending
715 this.byName(row, 'status').innerHTML =
716 dojo.string.substitute(
717 localeStrings.HOLD_STATUS_WAITING,
718 [data.queue_position, data.potential_copies]
722 this.holdTbody.appendChild(row);
727 SelfCheckManager.prototype.drawFinesPage = function() {
729 // TODO add option to hid scanBox
730 // this.updateScanBox(...)
732 this.goToTab('fines');
733 progressDialog.show(true);
735 if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
736 openils.Util.show('oils-selfck-pay-fines-link', 'inline');
739 this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
740 if(!this.finesTemplate)
741 this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
742 while(this.finesTbody.childNodes[0])
743 this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
745 // when user clicks on a selector checkbox, update the total owed
746 var updateSelected = function() {
749 dojo.query('[name=selector]', this.finesTbody),
752 total += Number(input.getAttribute('balance_owed'));
756 total = total.toFixed(2);
757 dojo.byId('oils-selfck-selected-total').innerHTML =
758 dojo.string.substitute(localeStrings.TOTAL_FINES_SELECTED, [total]);
761 // wire up the batch on/off selector
762 var sel = dojo.byId('oils-selfck-fines-selector');
763 sel.onchange = function() {
765 dojo.query('[name=selector]', this.finesTbody),
767 input.checked = sel.checked;
773 var handler = function(dataList) {
775 self.finesCount = dataList.length;
776 self.finesData = dataList;
778 for(var i in dataList) {
780 var data = dataList[i];
781 var row = self.finesTemplate.cloneNode(true);
782 var type = data.transaction.xact_type();
784 if(type == 'circulation') {
785 self.byName(row, 'type').innerHTML = type;
786 self.byName(row, 'details').innerHTML = data.record.title();
788 } else if(type == 'grocery') {
789 self.byName(row, 'type').innerHTML = 'Miscellaneous'; // Go ahead and head off any confusion around "grocery". TODO i18n
790 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
793 self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
794 self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
795 self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
798 var selector = self.byName(row, 'selector')
799 selector.onchange = updateSelected;
800 selector.setAttribute('xact', data.transaction.id());
801 selector.setAttribute('balance_owed', data.transaction.balance_owed());
802 selector.checked = true;
804 self.finesTbody.appendChild(row);
811 fieldmapper.standardRequest(
812 ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
814 params : [this.authtoken, this.patron.id()],
815 oncomplete : function(r) {
816 progressDialog.hide();
817 handler(openils.Util.readResponse(r));
823 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
825 var resp = fieldmapper.standardRequest(
826 ['open-ils.circ', 'open-ils.circ.transit.abort'],
827 {params : [this.authtoken, {barcode : barcode}]}
830 // resp == 1 on success
831 if(openils.Event.parse(resp))
834 var resp = fieldmapper.standardRequest(
835 ['open-ils.circ', 'open-ils.circ.checkin.override'],
838 patron_id : this.patron.id(),
839 copy_barcode : barcode,
845 if(!resp.length) resp = [resp];
846 for(var i = 0; i < resp.length; i++) {
847 var tc = openils.Event.parse(resp[i]).textcode;
848 if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
859 * Check out a single item. If the item is already checked
860 * out to the patron, redirect to renew()
862 SelfCheckManager.prototype.checkout = function(barcode, override) {
864 this.prevCirc = null;
867 this.updateScanbox(null, true);
871 if(this.mockCheckouts) {
872 // if we're in mock-checkout mode, just insert another
873 // fake circ into the table and get out of here.
874 this.displayCheckout(this.mockCheckout, 'checkout');
878 // TODO see if it's a patron barcode
879 // TODO see if this item has already been checked out in this session
881 var method = 'open-ils.circ.checkout.full';
882 if(override) method += '.override';
884 console.log("Checkout out item " + barcode + " with method " + method);
886 var result = fieldmapper.standardRequest(
887 ['open-ils.circ', method],
890 patron_id : this.patron.id(),
891 copy_barcode : barcode
896 var stat = this.handleXactResult('checkout', barcode, result);
899 this.checkout(barcode, true);
900 } else if(stat.doOver) {
901 this.checkout(barcode);
902 } else if(stat.renew) {
907 SelfCheckManager.prototype.failPartMessage = function(result) {
908 if (result.payload && result.payload.fail_part) {
909 var stringKey = "FAIL_PART_" +
910 result.payload.fail_part.replace(/\./g, "_");
911 return localeStrings[stringKey];
917 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
919 var displayText = '';
921 // If true, the display message is important enough to pop up. Whether or not
922 // an alert() actually occurs, depends on org unit settings
924 var sound = ''; // sound file reference
925 var payload = result.payload || {};
926 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
927 var blockStatuses = this.orgSettings[SET_BLOCK_CHECKOUT_ON_COPY_STATUS];
929 if(result.textcode == 'NO_SESSION') {
931 return this.logoutStaff();
933 } else if(result.textcode == 'SUCCESS') {
935 if(action == 'checkout') {
937 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
938 this.displayCheckout(result, 'checkout');
940 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
941 // A hold was fulfilled, update the hold numbers in the circ summary
942 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
943 this.holdsSummary = null;
944 this.updateHoldsSummary();
947 this.updateCircSummary(true);
949 } else if(action == 'renew') {
951 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
952 this.displayCheckout(result, 'renew');
955 this.checkouts.push({circ : result.payload.circ.id()});
956 sound = 'checkout-success';
957 this.updateScanBox();
959 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
961 // Server says the item is already checked out. If it's checked out to the
962 // current user, we may need to renew it.
964 if(payload.old_circ) {
967 old_circ refers to the previous checkout IFF it's for the same user.
968 If no auto-renew interval is not defined, assume we should renew it
969 If an auto-renew interval is defined and the payload comes back with
970 auto_renew set to true, do the renewal. Otherwise, let the patron know
971 the item is already checked out to them. */
973 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
974 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
975 this.prevCirc = payload.old_circ.id();
976 return { renew : true };
980 sound = 'checkout-failure';
981 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
985 if( // copy is marked lost. if configured to do so, check it in and try again.
986 result.payload.copy &&
987 result.payload.copy.status() == /* LOST */ 3 &&
988 overrideEvents && overrideEvents.length &&
989 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
991 if(this.checkin(item)) {
992 return { doOver : true };
997 // item is checked out to some other user
999 sound = 'checkout-failure';
1000 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1003 this.updateScanBox({select:true});
1008 if(overrideEvents && overrideEvents.length) {
1010 // see if the events we received are all in the list of
1011 // events to override
1013 if(!result.length) result = [result];
1015 var override = true;
1016 for(var i = 0; i < result.length; i++) {
1018 var match = overrideEvents.filter(function(e) { return (e == result[i].textcode); })[0];
1025 if(result[i].textcode == 'COPY_NOT_AVAILABLE' && blockStatuses && blockStatuses.length) {
1027 var stat = result[i].payload.status(); // copy status
1028 if(typeof stat == 'object') stat = stat.id();
1030 var match2 = blockStatuses.filter(function(e) { return (e == stat); })[0];
1032 if(match2) { // copy is in a blocked status
1038 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1039 // to override a transit, we have to abort the transit and check it in first
1040 if(this.checkin(item, true)) {
1041 return { doOver : true };
1049 return { override : true };
1052 this.updateScanBox({select : true});
1054 sound = 'checkout-failure';
1056 if(action == 'renew')
1057 this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1062 switch(result.textcode) {
1064 // TODO custom handler for blocking penalties
1066 case 'MAX_RENEWALS_REACHED' :
1067 displayText = dojo.string.substitute(
1068 localeStrings.MAX_RENEWALS, [item]);
1071 case 'ITEM_NOT_CATALOGED' :
1072 displayText = dojo.string.substitute(
1073 localeStrings.ITEM_NOT_CATALOGED, [item]);
1076 case 'OPEN_CIRCULATION_EXISTS' :
1077 displayText = dojo.string.substitute(
1078 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1083 console.error('Unhandled event ' + result.textcode);
1085 if (!(displayText = this.failPartMessage(result))) {
1086 if (action == 'checkout' || action == 'renew') {
1087 displayText = dojo.string.substitute(
1088 localeStrings.GENERIC_CIRC_FAILURE, [item]);
1090 displayText = dojo.string.substitute(
1091 localeStrings.UNKNOWN_ERROR, [result.textcode]);
1097 this.handleAlert(displayText, popup, sound);
1105 SelfCheckManager.prototype.renew = function(barcode, override) {
1107 var method = 'open-ils.circ.renew';
1108 if(override) method += '.override';
1110 console.log("Renewing item " + barcode + " with method " + method);
1112 var result = fieldmapper.standardRequest(
1113 ['open-ils.circ', method],
1116 patron_id : this.patron.id(),
1117 copy_barcode : barcode
1122 console.log(js2JSON(result));
1124 var stat = this.handleXactResult('renew', barcode, result);
1127 this.renew(barcode, true);
1131 * Display the result of a checkout or renewal in the items out table
1133 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1135 var copy = evt.payload.copy;
1136 var record = evt.payload.record;
1137 var circ = evt.payload.circ;
1138 var row = this.circTemplate.cloneNode(true);
1141 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + record.isbn());
1144 this.byName(row, 'barcode').innerHTML = copy.barcode();
1145 this.byName(row, 'title').innerHTML = record.title();
1146 this.byName(row, 'author').innerHTML = record.author();
1147 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1148 openils.Util.show(this.byName(row, type));
1150 var date = dojo.date.stamp.fromISOString(circ.due_date());
1151 this.byName(row, 'due_date').innerHTML =
1152 dojo.date.locale.format(date, {selector : 'date'});
1154 // put new circs at the top of the list
1155 var tbody = this.circTbody;
1156 if(itemsOut) tbody = this.itemsOutTbody;
1157 tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1161 SelfCheckManager.prototype.byName = function(node, name) {
1162 return dojo.query('[name=' + name+']', node)[0];
1166 SelfCheckManager.prototype.initPrinter = function() {
1167 try { // Mozilla only
1168 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1169 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1170 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1171 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1172 var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1174 pref.setBoolPref('print.always_print_silent', true);
1176 console.log("Unable to initialize auto-printing");
1181 * Print a receipt for this session's checkouts
1183 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1186 var circCtx = []; // circ context data. in this case, renewal_failure info
1188 // collect the circs and failure info
1192 circIds.push(blob.circ);
1193 circCtx.push({renewal_failure:blob.renewal_failure});
1201 'format.selfcheck.checkout',
1208 fieldmapper.standardRequest(
1209 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1213 oncomplete : function(r) {
1214 var resp = openils.Util.readResponse(r);
1215 var output = resp.template_output();
1217 self.printData(output.data(), self.checkouts.length, callback);
1219 var error = resp.error_output();
1221 throw new Error("Error creating receipt: " + error.data());
1223 throw new Error("No receipt data returned from server");
1231 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1233 var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1');
1234 win.document.body.innerHTML = data;
1238 * There is no way to know when the browser is done printing.
1239 * Make a best guess at when to close the print window by basing
1240 * the setTimeout wait on the number of items to be printed plus
1243 var sleepTime = 1000;
1245 sleepTime += (numItems / 2) * 1000;
1249 win.close(); // close the print window
1251 callback(); // fire optional post-print callback
1259 * Print a receipt for this user's items out
1261 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1263 if(!this.itemsOut.length) return;
1265 progressDialog.show(true);
1271 'format.selfcheck.items_out',
1277 fieldmapper.standardRequest(
1278 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1282 oncomplete : function(r) {
1283 progressDialog.hide();
1284 var resp = openils.Util.readResponse(r);
1285 var output = resp.template_output();
1287 self.printData(output.data(), self.itemsOut.length, callback);
1289 var error = resp.error_output();
1291 throw new Error("Error creating receipt: " + error.data());
1293 throw new Error("No receipt data returned from server");
1302 * Print a receipt for this user's items out
1304 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1306 if(!this.holds.length) return;
1308 progressDialog.show(true);
1313 dojo.forEach(this.holds,
1315 holdIds.push(data.hold.id());
1316 if(data.status == 4) {
1317 holdData.push({ready : true});
1320 queue_position : data.queue_position,
1321 potential_copies : data.potential_copies
1331 'format.selfcheck.holds',
1338 fieldmapper.standardRequest(
1339 ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1343 oncomplete : function(r) {
1344 progressDialog.hide();
1345 var resp = openils.Util.readResponse(r);
1346 var output = resp.template_output();
1348 self.printData(output.data(), self.holds.length, callback);
1350 var error = resp.error_output();
1352 throw new Error("Error creating receipt: " + error.data());
1354 throw new Error("No receipt data returned from server");
1363 SelfCheckManager.prototype.printPaymentReceipt = function(response, callback) {
1366 progressDialog.show(true);
1368 fieldmapper.standardRequest(
1369 ['open-ils.circ', 'open-ils.circ.money.payment_receipt.print'],
1372 params : [this.authtoken, response.payments],
1373 oncomplete : function(r) {
1374 var resp = openils.Util.readResponse(r);
1375 var output = resp.template_output();
1376 progressDialog.hide();
1378 self.printData(output.data(), 1, callback);
1380 var error = resp.error_output();
1382 throw new Error("Error creating receipt: " + error.data());
1384 throw new Error("No receipt data returned from server");
1393 * Print a receipt for this user's items out
1395 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1397 progressDialog.show(true);
1403 'format.selfcheck.fines',
1409 fieldmapper.standardRequest(
1410 ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1414 oncomplete : function(r) {
1415 progressDialog.hide();
1416 var resp = openils.Util.readResponse(r);
1417 var output = resp.template_output();
1419 self.printData(output.data(), self.finesCount, callback);
1421 var error = resp.error_output();
1423 throw new Error("Error creating receipt: " + error.data());
1425 throw new Error("No receipt data returned from server");
1437 * Logout the patron and return to the login page
1439 SelfCheckManager.prototype.logoutPatron = function(print) {
1440 if(print && this.checkouts.length) {
1441 this.printSessionReceipt(
1443 location.href = location.href;
1447 location.href = location.href;
1453 * Fire up the manager on page load
1455 openils.Util.addOnLoad(
1457 new SelfCheckManager().init();