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 self.updateFinesSummary();
111 self.drawFinesPage();
115 'oils-selfck-nav-home' : function() { self.drawCircPage(); },
116 'oils-selfck-nav-logout' : function() { self.logoutPatron(); },
117 'oils-selfck-nav-logout-print' : function() { self.logoutPatron(true); },
118 'oils-selfck-items-out-details-link' : function() { self.drawItemsOutPage(); },
119 'oils-selfck-print-list-link' : function() { self.printList(); }
122 for(var id in linkHandlers)
123 dojo.connect(dojo.byId(id), 'onclick', linkHandlers[id]);
126 if(this.cgi.param('patron')) {
128 // Patron barcode via cgi param. Mainly used for debugging and
129 // only works if password is not required by policy
130 this.loginPatron(this.cgi.param('patron'));
133 this.drawLoginPage();
137 * To test printing, pass a URL param of 'testprint'. The value for the param
138 * should be a JSON string like so: [{circ:<circ_id>}, ...]
140 var testPrint = this.cgi.param('testprint');
142 this.checkouts = JSON2js(testPrint);
143 this.printSessionReceipt();
149 SelfCheckManager.prototype.getSelectedFinesTotal = function() {
152 dojo.query("[name=selector]", this.finesTbody),
155 total += Number(input.getAttribute("balance_owed"));
158 return total.toFixed(2);
161 SelfCheckManager.prototype.getSelectedFineTransactions = function() {
162 return dojo.query("[name=selector]", this.finesTbody).
163 filter(function (o) { return o.checked }).
167 o.getAttribute("xact"),
168 Number(o.getAttribute("balance_owed")).toFixed(2)
175 * Registers a new workstion
177 SelfCheckManager.prototype.registerWorkstation = function() {
179 oilsSelfckWsDialog.show();
181 new openils.User().buildPermOrgSelector(
182 'REGISTER_WORKSTATION',
183 oilsSelfckWsLocSelector,
189 dojo.connect(oilsSelfckWsSubmit, 'onClick',
192 oilsSelfckWsDialog.hide();
193 var name = oilsSelfckWsLocSelector.attr('displayedValue') + '-' + oilsSelfckWsName.attr('value');
195 var res = fieldmapper.standardRequest(
196 ['open-ils.actor', 'open-ils.actor.workstation.register'],
198 self.authtoken, name, oilsSelfckWsLocSelector.attr('value')
203 if(evt = openils.Event.parse(res)) {
204 if(evt.textcode == 'WORKSTATION_NAME_EXISTS') {
205 if(confirm(localeStrings.WORKSTATION_EXISTS)) {
206 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
208 self.registerWorkstation();
215 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
222 * Loads the org unit settings
224 SelfCheckManager.prototype.loadOrgSettings = function() {
226 var settings = fieldmapper.aou.fetchOrgSettingBatch(
227 this.staff.ws_ou(), [
232 SET_AUTO_OVERRIDE_EVENTS,
233 SET_PATRON_PASSWORD_REQUIRED,
234 SET_AUTO_RENEW_INTERVAL,
235 SET_WORKSTATION_REQUIRED,
236 SET_CC_PAYMENT_ALLOWED
242 this.orgSettings[k] = settings[k].value;
245 if(settings[SET_BARCODE_REGEX])
246 this.patronBarcodeRegex = new RegExp(settings[SET_BARCODE_REGEX].value);
249 SelfCheckManager.prototype.drawLoginPage = function() {
252 var bcHandler = function(barcode) {
253 // handle patron barcode entry
255 if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
257 // password is required. wire up the scan box to read it
259 msg : 'Please enter your password', // TODO i18n
260 handler : function(pw) { self.loginPatron(barcode, pw); },
265 // password is not required, go ahead and login
266 self.loginPatron(barcode);
271 msg : 'Please log in with your library barcode.', // TODO
279 SelfCheckManager.prototype.loginPatron = function(barcode, passwd) {
281 if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
284 // would only happen in dev/debug mode when using the patron= param
285 alert('password required by org setting. remove patron= from URL');
289 // patron password is required. Verify it.
291 var res = fieldmapper.standardRequest(
292 ['open-ils.actor', 'open-ils.actor.verify_user_password'],
293 {params : [this.authtoken, barcode, null, hex_md5(passwd)]}
297 // user-not-found results in login failure
299 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]),
300 false, 'login-failure'
302 this.drawLoginPage();
307 // retrieve the fleshed user by barcode
308 this.patron = fieldmapper.standardRequest(
309 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve_by_barcode'],
310 {params : [this.authtoken, barcode]}
313 var evt = openils.Event.parse(this.patron);
316 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]),
317 false, 'login-failure'
319 this.drawLoginPage();
323 this.handleAlert('', false, 'login-success');
324 dojo.byId('oils-selfck-user-banner').innerHTML =
325 dojo.string.substitute(localeStrings.WELCOME_BANNER, [this.patron.first_given_name()]);
331 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
333 console.log("Handling alert " + message);
335 dojo.byId('oils-selfck-status-div').innerHTML = message;
337 if(shouldPopup && this.orgSettings[SET_ALERT_POPUP])
340 if(sound && this.orgSettings[SET_ALERT_SOUND])
341 openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
346 * Manages the main input box
347 * @param msg The context message to display with the box
348 * @param clearOnly Don't update the context message, just clear the value and re-focus
349 * @param handler Optional "on-enter" handler.
351 SelfCheckManager.prototype.updateScanBox = function(args) {
355 selfckScanBox.domNode.select();
357 selfckScanBox.attr('value', '');
361 selfckScanBox.domNode.setAttribute('type', 'password');
363 selfckScanBox.domNode.setAttribute('type', '');
367 selfckScanBox.attr('value', args.value);
370 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
372 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
373 dojo.disconnect(selfckScanBox._lastHandler);
377 selfckScanBox._lastHandler = dojo.connect(
381 if(e.keyCode != dojo.keys.ENTER)
383 args.handler(selfckScanBox.attr('value'));
388 selfckScanBox.focus();
392 * Sets up the checkout/renewal interface
394 SelfCheckManager.prototype.drawCircPage = function() {
396 openils.Util.show('oils-selfck-circ-tbody', 'table-row-group');
397 this.goToTab('checkout');
399 while(this.itemsOutTbody.childNodes[0])
400 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
404 msg : 'Please enter an item barcode', // TODO i18n
405 handler : function(barcode) { self.checkout(barcode); }
408 if(!this.circTemplate)
409 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
412 this.updateFinesSummary();
415 this.updateHoldsSummary();
418 this.updateCircSummary();
420 // render mock checkouts for debugging?
421 if(this.mockCheckouts) {
422 for(var i in [1,2,3])
423 this.displayCheckout(this.mockCheckout, 'checkout');
428 SelfCheckManager.prototype.updateFinesSummary = function() {
432 fieldmapper.standardRequest(
433 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
435 params : [this.authtoken, this.patron.id()],
436 oncomplete : function(r) {
438 var summary = openils.Util.readResponse(r);
440 dojo.byId('oils-selfck-fines-total').innerHTML =
441 dojo.string.substitute(
442 localeStrings.TOTAL_FINES_ACCOUNT,
443 [summary.balance_owed()]
446 self.creditPayableBalance = summary.balance_owed();
453 SelfCheckManager.prototype.drawItemsOutPage = function() {
454 openils.Util.hide('oils-selfck-circ-tbody');
456 this.goToTab('items_out');
458 while(this.itemsOutTbody.childNodes[0])
459 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
461 progressDialog.show(true);
464 fieldmapper.standardRequest(
465 ['open-ils.circ', 'open-ils.circ.actor.user.checked_out.atomic'],
468 params : [this.authtoken, this.patron.id()],
469 oncomplete : function(r) {
471 var resp = openils.Util.readResponse(r);
473 var circs = resp.sort(
475 if(a.circ.due_date() > b.circ.due_date())
481 progressDialog.hide();
486 self.itemsOut.push(circ.circ.id());
487 self.displayCheckout(
489 (circ.circ.parent_circ()) ? 'renew' : 'checkout',
500 SelfCheckManager.prototype.goToTab = function(name) {
503 openils.Util.hide('oils-selfck-fines-page');
504 openils.Util.hide('oils-selfck-payment-page');
505 openils.Util.hide('oils-selfck-holds-page');
506 openils.Util.hide('oils-selfck-circ-page');
507 openils.Util.hide('oils-selfck-pay-fines-link');
511 openils.Util.show('oils-selfck-circ-page');
514 openils.Util.show('oils-selfck-circ-page');
517 openils.Util.show('oils-selfck-holds-page');
520 openils.Util.show('oils-selfck-fines-page');
523 openils.Util.show('oils-selfck-payment-page');
529 SelfCheckManager.prototype.printList = function() {
530 switch(this.tabName) {
532 this.printSessionReceipt();
535 this.printItemsOutReceipt();
538 this.printHoldsReceipt();
541 this.printFinesReceipt();
546 SelfCheckManager.prototype.updateHoldsSummary = function() {
548 if(!this.holdsSummary) {
549 var summary = fieldmapper.standardRequest(
550 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
551 {params : [this.authtoken, this.patron.id()]}
554 this.holdsSummary = {};
555 this.holdsSummary.ready = Number(summary['4']);
556 this.holdsSummary.total = 0;
558 for(var i in summary)
559 this.holdsSummary.total += Number(summary[i]);
562 dojo.byId('oils-selfck-holds-total').innerHTML =
563 dojo.string.substitute(
564 localeStrings.TOTAL_HOLDS,
565 [this.holdsSummary.total]
568 dojo.byId('oils-selfck-holds-ready').innerHTML =
569 dojo.string.substitute(
570 localeStrings.HOLDS_READY_FOR_PICKUP,
571 [this.holdsSummary.ready]
576 SelfCheckManager.prototype.updateCircSummary = function(increment) {
578 if(!this.circSummary) {
580 var summary = fieldmapper.standardRequest(
581 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
582 {params : [this.authtoken, this.patron.id()]}
586 total : Number(summary.out) + Number(summary.overdue),
587 overdue : Number(summary.overdue),
593 // local checkout occurred. Add to the total and the session.
594 this.circSummary.total += 1;
595 this.circSummary.session += 1;
598 dojo.byId('oils-selfck-circ-account-total').innerHTML =
599 dojo.string.substitute(
600 localeStrings.TOTAL_ITEMS_ACCOUNT,
601 [this.circSummary.total]
604 dojo.byId('oils-selfck-circ-session-total').innerHTML =
605 dojo.string.substitute(
606 localeStrings.TOTAL_ITEMS_SESSION,
607 [this.circSummary.session]
612 SelfCheckManager.prototype.drawHoldsPage = function() {
614 // TODO add option to hid scanBox
615 // this.updateScanBox(...)
617 this.goToTab('holds');
619 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
620 if(!this.holdTemplate)
621 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
622 while(this.holdTbody.childNodes[0])
623 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
625 progressDialog.show(true);
628 fieldmapper.standardRequest( // fetch the hold IDs
630 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
632 params : [this.authtoken, this.patron.id()],
634 oncomplete : function(r) {
635 var ids = openils.Util.readResponse(r);
636 if(!ids || ids.length == 0) {
637 progressDialog.hide();
641 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
642 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve.atomic'],
644 params : [self.authtoken, ids],
646 oncomplete : function(rr) {
647 self.drawHolds(openils.Util.readResponse(rr));
657 * Fetch and add a single hold to the list of holds
659 SelfCheckManager.prototype.drawHolds = function(holds) {
662 // sort available holds to the top of the list
663 // followed by queue position order
665 if(a.status == 4) return -1;
666 if(a.queue_position < b.queue_position) return -1;
673 progressDialog.hide();
675 for(var i in holds) {
678 var row = this.holdTemplate.cloneNode(true);
680 if(data.mvr.isbn()) {
681 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + data.mvr.isbn());
684 this.byName(row, 'title').innerHTML = data.mvr.title();
685 this.byName(row, 'author').innerHTML = data.mvr.author();
687 if(data.status == 4) {
689 // hold is ready for pickup
690 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
694 // hold is still pending
695 this.byName(row, 'status').innerHTML =
696 dojo.string.substitute(
697 localeStrings.HOLD_STATUS_WAITING,
698 [data.queue_position, data.potential_copies]
702 this.holdTbody.appendChild(row);
707 SelfCheckManager.prototype.drawFinesPage = function() {
709 // TODO add option to hid scanBox
710 // this.updateScanBox(...)
712 this.goToTab('fines');
713 progressDialog.show(true);
715 if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
716 openils.Util.show('oils-selfck-pay-fines-link', 'inline');
719 this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
720 if(!this.finesTemplate)
721 this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
722 while(this.finesTbody.childNodes[0])
723 this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
725 // when user clicks on a selector checkbox, update the total owed
726 var updateSelected = function() {
729 dojo.query('[name=selector]', this.finesTbody),
732 total += Number(input.getAttribute('balance_owed'));
736 total = total.toFixed(2);
737 dojo.byId('oils-selfck-selected-total').innerHTML =
738 dojo.string.substitute(localeStrings.TOTAL_FINES_SELECTED, [total]);
741 // wire up the batch on/off selector
742 var sel = dojo.byId('oils-selfck-fines-selector');
743 sel.onchange = function() {
745 dojo.query('[name=selector]', this.finesTbody),
747 input.checked = sel.checked;
753 var handler = function(dataList) {
755 self.finesCount = dataList.length;
756 self.finesData = dataList;
758 for(var i in dataList) {
760 var data = dataList[i];
761 var row = self.finesTemplate.cloneNode(true);
762 var type = data.transaction.xact_type();
764 if(type == 'circulation') {
765 self.byName(row, 'type').innerHTML = type;
766 self.byName(row, 'details').innerHTML = data.record.title();
768 } else if(type == 'grocery') {
769 self.byName(row, 'type').innerHTML = 'Miscellaneous'; // Go ahead and head off any confusion around "grocery". TODO i18n
770 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
773 self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
774 self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
775 self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
778 var selector = self.byName(row, 'selector')
779 selector.onchange = updateSelected;
780 selector.setAttribute('xact', data.transaction.id());
781 selector.setAttribute('balance_owed', data.transaction.balance_owed());
782 selector.checked = true;
784 self.finesTbody.appendChild(row);
791 fieldmapper.standardRequest(
792 ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
794 params : [this.authtoken, this.patron.id()],
795 oncomplete : function(r) {
796 progressDialog.hide();
797 handler(openils.Util.readResponse(r));
803 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
805 var resp = fieldmapper.standardRequest(
806 ['open-ils.circ', 'open-ils.circ.transit.abort'],
807 {params : [this.authtoken, {barcode : barcode}]}
810 // resp == 1 on success
811 if(openils.Event.parse(resp))
814 var resp = fieldmapper.standardRequest(
815 ['open-ils.circ', 'open-ils.circ.checkin.override'],
818 patron_id : this.patron.id(),
819 copy_barcode : barcode,
825 if(!resp.length) resp = [resp];
826 for(var i = 0; i < resp.length; i++) {
827 var tc = openils.Event.parse(resp[i]).textcode;
828 if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
839 * Check out a single item. If the item is already checked
840 * out to the patron, redirect to renew()
842 SelfCheckManager.prototype.checkout = function(barcode, override) {
844 this.prevCirc = null;
847 this.updateScanbox(null, true);
851 if(this.mockCheckouts) {
852 // if we're in mock-checkout mode, just insert another
853 // fake circ into the table and get out of here.
854 this.displayCheckout(this.mockCheckout, 'checkout');
858 // TODO see if it's a patron barcode
859 // TODO see if this item has already been checked out in this session
861 var method = 'open-ils.circ.checkout.full';
862 if(override) method += '.override';
864 console.log("Checkout out item " + barcode + " with method " + method);
866 var result = fieldmapper.standardRequest(
867 ['open-ils.circ', 'open-ils.circ.checkout.full'],
870 patron_id : this.patron.id(),
871 copy_barcode : barcode
876 var stat = this.handleXactResult('checkout', barcode, result);
879 this.checkout(barcode, true);
880 } else if(stat.doOver) {
881 this.checkout(barcode);
882 } else if(stat.renew) {
887 SelfCheckManager.prototype.failPartMessage = function(result) {
888 if (result.payload && result.payload.fail_part) {
889 var stringKey = "FAIL_PART_" +
890 result.payload.fail_part.replace(/\./g, "_");
891 return localeStrings[stringKey];
897 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
899 var displayText = '';
901 // If true, the display message is important enough to pop up. Whether or not
902 // an alert() actually occurs, depends on org unit settings
904 var sound = ''; // sound file reference
905 var payload = result.payload || {};
906 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
908 if(result.textcode == 'NO_SESSION') {
910 return this.logoutStaff();
912 } else if(result.textcode == 'SUCCESS') {
914 if(action == 'checkout') {
916 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
917 this.displayCheckout(result, 'checkout');
919 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
920 // A hold was fulfilled, update the hold numbers in the circ summary
921 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
922 this.holdsSummary = null;
923 this.updateHoldsSummary();
926 this.updateCircSummary(true);
928 } else if(action == 'renew') {
930 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
931 this.displayCheckout(result, 'renew');
934 this.checkouts.push({circ : result.payload.circ.id()});
935 sound = 'checkout-success';
936 this.updateScanBox();
938 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
940 // Server says the item is already checked out. If it's checked out to the
941 // current user, we may need to renew it.
943 if(payload.old_circ) {
946 old_circ refers to the previous checkout IFF it's for the same user.
947 If no auto-renew interval is not defined, assume we should renew it
948 If an auto-renew interval is defined and the payload comes back with
949 auto_renew set to true, do the renewal. Otherwise, let the patron know
950 the item is already checked out to them. */
952 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
953 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
954 this.prevCirc = payload.old_circ.id();
955 return { renew : true };
959 sound = 'checkout-failure';
960 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
964 if( // copy is marked lost. if configured to do so, check it in and try again.
965 result.payload.copy &&
966 result.payload.copy.status() == /* LOST */ 3 &&
967 overrideEvents && overrideEvents.length &&
968 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
970 if(this.checkin(item)) {
971 return { doOver : true };
976 // item is checked out to some other user
978 sound = 'checkout-failure';
979 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
982 this.updateScanBox({select:true});
987 if(overrideEvents && overrideEvents.length) {
989 // see if the events we received are all in the list of
990 // events to override
992 if(!result.length) result = [result];
995 for(var i = 0; i < result.length; i++) {
996 var match = overrideEvents.filter(
997 function(e) { return (e == result[i].textcode); })[0];
1003 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1004 // to override a transit, we have to abort the transit and check it in first
1005 if(this.checkin(item, true)) {
1006 return { doOver : true };
1015 return { override : true };
1018 this.updateScanBox({select : true});
1020 sound = 'checkout-failure';
1022 if(action == 'renew')
1023 this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1028 switch(result.textcode) {
1030 // TODO custom handler for blocking penalties
1032 case 'MAX_RENEWALS_REACHED' :
1033 displayText = dojo.string.substitute(
1034 localeStrings.MAX_RENEWALS, [item]);
1037 case 'ITEM_NOT_CATALOGED' :
1038 displayText = dojo.string.substitute(
1039 localeStrings.ITEM_NOT_CATALOGED, [item]);
1042 case 'OPEN_CIRCULATION_EXISTS' :
1043 displayText = dojo.string.substitute(
1044 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1049 console.error('Unhandled event ' + result.textcode);
1051 if (!(displayText = this.failPartMessage(result))) {
1052 if (action == 'checkout' || action == 'renew') {
1053 displayText = dojo.string.substitute(
1054 localeStrings.GENERIC_CIRC_FAILURE, [item]);
1056 displayText = dojo.string.substitute(
1057 localeStrings.UNKNOWN_ERROR, [result.textcode]);
1063 this.handleAlert(displayText, popup, sound);
1071 SelfCheckManager.prototype.renew = function(barcode, override) {
1073 var method = 'open-ils.circ.renew';
1074 if(override) method += '.override';
1076 console.log("Renewing item " + barcode + " with method " + method);
1078 var result = fieldmapper.standardRequest(
1079 ['open-ils.circ', method],
1082 patron_id : this.patron.id(),
1083 copy_barcode : barcode
1088 console.log(js2JSON(result));
1090 var stat = this.handleXactResult('renew', barcode, result);
1093 this.renew(barcode, true);
1097 * Display the result of a checkout or renewal in the items out table
1099 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1101 var copy = evt.payload.copy;
1102 var record = evt.payload.record;
1103 var circ = evt.payload.circ;
1104 var row = this.circTemplate.cloneNode(true);
1107 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + record.isbn());
1110 this.byName(row, 'barcode').innerHTML = copy.barcode();
1111 this.byName(row, 'title').innerHTML = record.title();
1112 this.byName(row, 'author').innerHTML = record.author();
1113 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1114 openils.Util.show(this.byName(row, type));
1116 var date = dojo.date.stamp.fromISOString(circ.due_date());
1117 this.byName(row, 'due_date').innerHTML =
1118 dojo.date.locale.format(date, {selector : 'date'});
1120 // put new circs at the top of the list
1121 var tbody = this.circTbody;
1122 if(itemsOut) tbody = this.itemsOutTbody;
1123 tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1127 SelfCheckManager.prototype.byName = function(node, name) {
1128 return dojo.query('[name=' + name+']', node)[0];
1132 SelfCheckManager.prototype.initPrinter = function() {
1133 try { // Mozilla only
1134 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1135 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1136 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1137 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1138 var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1140 pref.setBoolPref('print.always_print_silent', true);
1142 console.log("Unable to initialize auto-printing");
1147 * Print a receipt for this session's checkouts
1149 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1152 var circCtx = []; // circ context data. in this case, renewal_failure info
1154 // collect the circs and failure info
1158 circIds.push(blob.circ);
1159 circCtx.push({renewal_failure:blob.renewal_failure});
1167 'format.selfcheck.checkout',
1174 fieldmapper.standardRequest(
1175 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1179 oncomplete : function(r) {
1180 var resp = openils.Util.readResponse(r);
1181 var output = resp.template_output();
1183 self.printData(output.data(), self.checkouts.length, callback);
1185 var error = resp.error_output();
1187 throw new Error("Error creating receipt: " + error.data());
1189 throw new Error("No receipt data returned from server");
1197 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1199 var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1');
1200 win.document.body.innerHTML = data;
1204 * There is no way to know when the browser is done printing.
1205 * Make a best guess at when to close the print window by basing
1206 * the setTimeout wait on the number of items to be printed plus
1209 var sleepTime = 1000;
1211 sleepTime += (numItems / 2) * 1000;
1215 win.close(); // close the print window
1217 callback(); // fire optional post-print callback
1225 * Print a receipt for this user's items out
1227 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1229 if(!this.itemsOut.length) return;
1231 progressDialog.show(true);
1237 'format.selfcheck.items_out',
1243 fieldmapper.standardRequest(
1244 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1248 oncomplete : function(r) {
1249 progressDialog.hide();
1250 var resp = openils.Util.readResponse(r);
1251 var output = resp.template_output();
1253 self.printData(output.data(), self.itemsOut.length, callback);
1255 var error = resp.error_output();
1257 throw new Error("Error creating receipt: " + error.data());
1259 throw new Error("No receipt data returned from server");
1268 * Print a receipt for this user's items out
1270 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1272 if(!this.holds.length) return;
1274 progressDialog.show(true);
1279 dojo.forEach(this.holds,
1281 holdIds.push(data.hold.id());
1282 if(data.status == 4) {
1283 holdData.push({ready : true});
1286 queue_position : data.queue_position,
1287 potential_copies : data.potential_copies
1297 'format.selfcheck.holds',
1304 fieldmapper.standardRequest(
1305 ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1309 oncomplete : function(r) {
1310 progressDialog.hide();
1311 var resp = openils.Util.readResponse(r);
1312 var output = resp.template_output();
1314 self.printData(output.data(), self.holds.length, callback);
1316 var error = resp.error_output();
1318 throw new Error("Error creating receipt: " + error.data());
1320 throw new Error("No receipt data returned from server");
1330 * Print a receipt for this user's items out
1332 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1334 progressDialog.show(true);
1340 'format.selfcheck.fines',
1346 fieldmapper.standardRequest(
1347 ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1351 oncomplete : function(r) {
1352 progressDialog.hide();
1353 var resp = openils.Util.readResponse(r);
1354 var output = resp.template_output();
1356 self.printData(output.data(), self.finesCount, callback);
1358 var error = resp.error_output();
1360 throw new Error("Error creating receipt: " + error.data());
1362 throw new Error("No receipt data returned from server");
1374 * Logout the patron and return to the login page
1376 SelfCheckManager.prototype.logoutPatron = function(print) {
1377 if(print && this.checkouts.length) {
1378 this.printSessionReceipt(
1380 location.href = location.href;
1384 location.href = location.href;
1390 * Fire up the manager on page load
1392 openils.Util.addOnLoad(
1394 new SelfCheckManager().init();