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');
76 * Fetch the org-unit settings, initialize the display, etc.
78 SelfCheckManager.prototype.init = function() {
80 this.staff = openils.User.user;
81 this.workstation = openils.User.workstation;
82 this.authtoken = openils.User.authtoken;
83 this.loadOrgSettings();
85 this.circTbody = dojo.byId('oils-selfck-circ-tbody');
86 this.itemsOutTbody = dojo.byId('oils-selfck-circ-out-tbody');
88 // workstation is required but none provided
89 if(this.orgSettings[SET_WORKSTATION_REQUIRED] && !this.workstation) {
90 if(confirm(dojo.string.substitute(localeStrings.WORKSTATION_REQUIRED))) {
91 this.registerWorkstation();
97 // connect onclick handlers to the various navigation links
99 'oils-selfck-hold-details-link' : function() { self.drawHoldsPage(); },
100 'oils-selfck-view-fines-link' : function() { self.drawFinesPage(); },
101 'oils-selfck-pay-fines-link' : function() { self.drawPayFinesPage(); },
102 'oils-selfck-nav-home' : function() { self.drawCircPage(); },
103 'oils-selfck-nav-logout' : function() { self.logoutPatron(); },
104 'oils-selfck-nav-logout-print' : function() { self.logoutPatron(true); },
105 'oils-selfck-items-out-details-link' : function() { self.drawItemsOutPage(); },
106 'oils-selfck-print-list-link' : function() { self.printList(); }
109 for(var id in linkHandlers)
110 dojo.connect(dojo.byId(id), 'onclick', linkHandlers[id]);
113 if(this.cgi.param('patron')) {
115 // Patron barcode via cgi param. Mainly used for debugging and
116 // only works if password is not required by policy
117 this.loginPatron(this.cgi.param('patron'));
120 this.drawLoginPage();
124 * To test printing, pass a URL param of 'testprint'. The value for the param
125 * should be a JSON string like so: [{circ:<circ_id>}, ...]
127 var testPrint = this.cgi.param('testprint');
129 this.checkouts = JSON2js(testPrint);
130 this.printSessionReceipt();
137 * Registers a new workstion
139 SelfCheckManager.prototype.registerWorkstation = function() {
141 oilsSelfckWsDialog.show();
143 new openils.User().buildPermOrgSelector(
144 'REGISTER_WORKSTATION',
145 oilsSelfckWsLocSelector,
151 dojo.connect(oilsSelfckWsSubmit, 'onClick',
154 oilsSelfckWsDialog.hide();
155 var name = oilsSelfckWsLocSelector.attr('displayedValue') + '-' + oilsSelfckWsName.attr('value');
157 var res = fieldmapper.standardRequest(
158 ['open-ils.actor', 'open-ils.actor.workstation.register'],
160 self.authtoken, name, oilsSelfckWsLocSelector.attr('value')
165 if(evt = openils.Event.parse(res)) {
166 if(evt.textcode == 'WORKSTATION_NAME_EXISTS') {
167 if(confirm(localeStrings.WORKSTATION_EXISTS)) {
168 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
170 self.registerWorkstation();
177 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
184 * Loads the org unit settings
186 SelfCheckManager.prototype.loadOrgSettings = function() {
188 var settings = fieldmapper.aou.fetchOrgSettingBatch(
189 this.staff.ws_ou(), [
194 SET_AUTO_OVERRIDE_EVENTS,
195 SET_PATRON_PASSWORD_REQUIRED,
196 SET_AUTO_RENEW_INTERVAL,
197 SET_WORKSTATION_REQUIRED,
198 SET_CC_PAYMENT_ALLOWED
204 this.orgSettings[k] = settings[k].value;
207 if(settings[SET_BARCODE_REGEX])
208 this.patronBarcodeRegex = new RegExp(settings[SET_BARCODE_REGEX].value);
211 SelfCheckManager.prototype.drawLoginPage = function() {
214 var bcHandler = function(barcode) {
215 // handle patron barcode entry
217 if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
219 // password is required. wire up the scan box to read it
221 msg : 'Please enter your password', // TODO i18n
222 handler : function(pw) { self.loginPatron(barcode, pw); },
227 // password is not required, go ahead and login
228 self.loginPatron(barcode);
233 msg : 'Please log in with your library barcode.', // TODO
241 SelfCheckManager.prototype.loginPatron = function(barcode, passwd) {
243 if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
246 // would only happen in dev/debug mode when using the patron= param
247 alert('password required by org setting. remove patron= from URL');
251 // patron password is required. Verify it.
253 var res = fieldmapper.standardRequest(
254 ['open-ils.actor', 'open-ils.actor.verify_user_password'],
255 {params : [this.authtoken, barcode, null, hex_md5(passwd)]}
259 // user-not-found results in login failure
261 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]),
262 false, 'login-failure'
264 this.drawLoginPage();
269 // retrieve the fleshed user by barcode
270 this.patron = fieldmapper.standardRequest(
271 ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve_by_barcode'],
272 {params : [this.authtoken, barcode]}
275 var evt = openils.Event.parse(this.patron);
278 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]),
279 false, 'login-failure'
281 this.drawLoginPage();
285 this.handleAlert('', false, 'login-success');
286 dojo.byId('oils-selfck-user-banner').innerHTML = 'Welcome, ' + this.patron.first_given_name(); // TODO i18n
292 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
294 console.log("Handling alert " + message);
296 dojo.byId('oils-selfck-status-div').innerHTML = message;
298 if(shouldPopup && this.orgSettings[SET_ALERT_POPUP])
301 if(sound && this.orgSettings[SET_ALERT_SOUND])
302 openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
307 * Manages the main input box
308 * @param msg The context message to display with the box
309 * @param clearOnly Don't update the context message, just clear the value and re-focus
310 * @param handler Optional "on-enter" handler.
312 SelfCheckManager.prototype.updateScanBox = function(args) {
316 selfckScanBox.domNode.select();
318 selfckScanBox.attr('value', '');
322 selfckScanBox.domNode.setAttribute('type', 'password');
324 selfckScanBox.domNode.setAttribute('type', '');
328 selfckScanBox.attr('value', args.value);
331 dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
333 if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
334 dojo.disconnect(selfckScanBox._lastHandler);
338 selfckScanBox._lastHandler = dojo.connect(
342 if(e.keyCode != dojo.keys.ENTER)
344 args.handler(selfckScanBox.attr('value'));
349 selfckScanBox.focus();
353 * Sets up the checkout/renewal interface
355 SelfCheckManager.prototype.drawCircPage = function() {
357 openils.Util.show('oils-selfck-circ-tbody', 'table-row-group');
358 this.goToTab('checkout');
360 while(this.itemsOutTbody.childNodes[0])
361 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
365 msg : 'Please enter an item barcode', // TODO i18n
366 handler : function(barcode) { self.checkout(barcode); }
369 if(!this.circTemplate)
370 this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
373 this.updateFinesSummary();
376 this.updateHoldsSummary();
379 this.updateCircSummary();
381 // render mock checkouts for debugging?
382 if(this.mockCheckouts) {
383 for(var i in [1,2,3])
384 this.displayCheckout(this.mockCheckout, 'checkout');
389 SelfCheckManager.prototype.updateFinesSummary = function() {
393 fieldmapper.standardRequest(
394 ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
396 params : [this.authtoken, this.patron.id()],
397 oncomplete : function(r) {
399 var summary = openils.Util.readResponse(r);
401 dojo.byId('oils-selfck-fines-total').innerHTML =
402 dojo.string.substitute(
403 localeStrings.TOTAL_FINES_ACCOUNT,
404 [summary.balance_owed()]
407 self.creditPayableBalance = summary.balance_owed();
414 SelfCheckManager.prototype.drawItemsOutPage = function() {
415 openils.Util.hide('oils-selfck-circ-tbody');
417 this.goToTab('items_out');
419 while(this.itemsOutTbody.childNodes[0])
420 this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
422 progressDialog.show(true);
425 fieldmapper.standardRequest(
426 ['open-ils.circ', 'open-ils.circ.actor.user.checked_out.atomic'],
429 params : [this.authtoken, this.patron.id()],
430 oncomplete : function(r) {
432 var resp = openils.Util.readResponse(r);
434 var circs = resp.sort(
436 if(a.circ.due_date() > b.circ.due_date())
442 progressDialog.hide();
447 self.itemsOut.push(circ.circ.id());
448 self.displayCheckout(
450 (circ.circ.parent_circ()) ? 'renew' : 'checkout',
461 SelfCheckManager.prototype.goToTab = function(name) {
464 openils.Util.hide('oils-selfck-fines-page');
465 openils.Util.hide('oils-selfck-payment-page');
466 openils.Util.hide('oils-selfck-holds-page');
467 openils.Util.hide('oils-selfck-circ-page');
468 openils.Util.hide('oils-selfck-pay-fines-link');
472 openils.Util.show('oils-selfck-circ-page');
475 openils.Util.show('oils-selfck-circ-page');
478 openils.Util.show('oils-selfck-holds-page');
481 openils.Util.show('oils-selfck-fines-page');
484 openils.Util.show('oils-selfck-payment-page');
490 SelfCheckManager.prototype.printList = function() {
491 switch(this.tabName) {
493 this.printSessionReceipt();
496 this.printItemsOutReceipt();
499 this.printHoldsReceipt();
502 this.printFinesReceipt();
507 SelfCheckManager.prototype.updateHoldsSummary = function() {
509 if(!this.holdsSummary) {
510 var summary = fieldmapper.standardRequest(
511 ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
512 {params : [this.authtoken, this.patron.id()]}
515 this.holdsSummary = {};
516 this.holdsSummary.ready = Number(summary['4']);
517 this.holdsSummary.total = 0;
519 for(var i in summary)
520 this.holdsSummary.total += Number(summary[i]);
523 dojo.byId('oils-selfck-holds-total').innerHTML =
524 dojo.string.substitute(
525 localeStrings.TOTAL_HOLDS,
526 [this.holdsSummary.total]
529 dojo.byId('oils-selfck-holds-ready').innerHTML =
530 dojo.string.substitute(
531 localeStrings.HOLDS_READY_FOR_PICKUP,
532 [this.holdsSummary.ready]
537 SelfCheckManager.prototype.updateCircSummary = function(increment) {
539 if(!this.circSummary) {
541 var summary = fieldmapper.standardRequest(
542 ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
543 {params : [this.authtoken, this.patron.id()]}
547 total : Number(summary.out) + Number(summary.overdue),
548 overdue : Number(summary.overdue),
554 // local checkout occurred. Add to the total and the session.
555 this.circSummary.total += 1;
556 this.circSummary.session += 1;
559 dojo.byId('oils-selfck-circ-account-total').innerHTML =
560 dojo.string.substitute(
561 localeStrings.TOTAL_ITEMS_ACCOUNT,
562 [this.circSummary.total]
565 dojo.byId('oils-selfck-circ-session-total').innerHTML =
566 dojo.string.substitute(
567 localeStrings.TOTAL_ITEMS_SESSION,
568 [this.circSummary.session]
573 SelfCheckManager.prototype.drawHoldsPage = function() {
575 // TODO add option to hid scanBox
576 // this.updateScanBox(...)
578 this.goToTab('holds');
580 this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
581 if(!this.holdTemplate)
582 this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
583 while(this.holdTbody.childNodes[0])
584 this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
586 progressDialog.show(true);
589 fieldmapper.standardRequest( // fetch the hold IDs
591 ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
593 params : [this.authtoken, this.patron.id()],
595 oncomplete : function(r) {
596 var ids = openils.Util.readResponse(r);
597 if(!ids || ids.length == 0) {
598 progressDialog.hide();
602 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
603 ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve.atomic'],
605 params : [self.authtoken, ids],
607 oncomplete : function(rr) {
608 self.drawHolds(openils.Util.readResponse(rr));
618 * Fetch and add a single hold to the list of holds
620 SelfCheckManager.prototype.drawHolds = function(holds) {
623 // sort available holds to the top of the list
624 // followed by queue position order
626 if(a.status == 4) return -1;
627 if(a.queue_position < b.queue_position) return -1;
634 progressDialog.hide();
636 for(var i in holds) {
639 var row = this.holdTemplate.cloneNode(true);
641 if(data.mvr.isbn()) {
642 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + data.mvr.isbn());
645 this.byName(row, 'title').innerHTML = data.mvr.title();
646 this.byName(row, 'author').innerHTML = data.mvr.author();
648 if(data.status == 4) {
650 // hold is ready for pickup
651 this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
655 // hold is still pending
656 this.byName(row, 'status').innerHTML =
657 dojo.string.substitute(
658 localeStrings.HOLD_STATUS_WAITING,
659 [data.queue_position, data.potential_copies]
663 this.holdTbody.appendChild(row);
668 SelfCheckManager.prototype.drawPayFinesPage = function() {
669 this.goToTab('payment');
671 dojo.byId('oils-selfck-cc-payment-summary').innerHTML =
672 dojo.string.substitute(
673 localeStrings.CC_PAYABLE_BALANCE,
674 [this.creditPayableBalance]
677 oilsSelfckCCNumber.attr('value', '');
678 oilsSelfckCCMonth.attr('value', '01');
679 oilsSelfckCCAmount.attr('value', this.creditPayableBalance);
680 oilsSelfckCCYear.attr('value', new Date().getFullYear());
681 oilsSelfckCCFName.attr('value', this.patron.first_given_name());
682 oilsSelfckCCLName.attr('value', this.patron.family_name());
683 var addr = this.patron.billing_address() || this.patron.mailing_address();
686 oilsSelfckCCStreet.attr('value', addr.street1()+' '+addr.street2());
687 oilsSelfckCCCity.attr('value', addr.city());
688 oilsSelfckCCState.attr('value', addr.state());
689 oilsSelfckCCZip.attr('value', addr.post_code());
692 dojo.connect(oilsSelfckEditDetails, 'onChange',
702 function(dij) { dij.attr('disabled', !newVal); }
709 dojo.connect(oilsSelfckCCSubmit, 'onClick',
711 progressDialog.show(true);
712 self.sendCCPayment();
718 // In this form, this code only supports global on/off credit card
719 // payments and does not dissallow payments to transactions that started
720 // at remote locations or transactions that have accumulated billings at
721 // remote locations that dissalow credit card payments.
722 // TODO add per-transaction blocks for orgs that do not support CC payments
724 SelfCheckManager.prototype.sendCCPayment = function() {
727 userid : this.patron.id(),
728 payment_type : 'credit_card_payment',
732 number : oilsSelfckCCNumber.attr('value'),
733 expire_year : oilsSelfckCCYear.attr('value'),
734 expire_month : oilsSelfckCCMonth.attr('value'),
735 billing_first : oilsSelfckCCFName.attr('value'),
736 billing_last : oilsSelfckCCLName.attr('value'),
737 billing_address : oilsSelfckCCStreet.attr('value'),
738 billing_city : oilsSelfckCCCity.attr('value'),
739 billing_state : oilsSelfckCCState.attr('value'),
740 billing_zip : oilsSelfckCCZip.attr('value')
744 var funds = oilsSelfckCCAmount.attr('value');
746 xacts = this.finesData.sort(
748 if(a.transaction.xact_start() < b.transaction.xact_start())
754 for(var i in xacts) {
755 var xact = xacts[i].transaction;
756 var paying = Math.min(funds, xact.balance_owed());
757 args.payments.push([xact.id(), paying]);
759 if(funds <= 0) break;
762 var resp = fieldmapper.standardRequest(
763 ['open-ils.circ', 'open-ils.circ.money.payment'],
764 {params : [this.authtoken, args]}
767 progressDialog.hide();
769 var evt = openils.Event.parse(resp);
773 this.updateFinesSummary();
774 this.drawFinesPage();
779 SelfCheckManager.prototype.drawFinesPage = function() {
781 // TODO add option to hid scanBox
782 // this.updateScanBox(...)
784 this.goToTab('fines');
785 progressDialog.show(true);
787 if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
788 openils.Util.show('oils-selfck-pay-fines-link', 'inline');
791 this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
792 if(!this.finesTemplate)
793 this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
794 while(this.finesTbody.childNodes[0])
795 this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
798 var handler = function(dataList) {
799 self.finesCount = dataList.length;
800 self.finesData = dataList;
801 for(var i in dataList) {
802 var data = dataList[i];
803 var row = self.finesTemplate.cloneNode(true);
804 var type = data.transaction.xact_type();
805 if(type == 'circulation') {
806 self.byName(row, 'type').innerHTML = type;
807 self.byName(row, 'details').innerHTML = data.record.title();
808 } else if(type == 'grocery') {
809 self.byName(row, 'type').innerHTML = 'Miscellaneous'; // Go ahead and head off any confusion around "grocery". TODO i18n
810 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
812 self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
813 self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
814 self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
815 self.finesTbody.appendChild(row);
819 fieldmapper.standardRequest(
820 ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
822 params : [this.authtoken, this.patron.id()],
823 oncomplete : function(r) {
824 progressDialog.hide();
825 handler(openils.Util.readResponse(r));
831 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
833 var resp = fieldmapper.standardRequest(
834 ['open-ils.circ', 'open-ils.circ.transit.abort'],
835 {params : [this.authtoken, {barcode : barcode}]}
838 // resp == 1 on success
839 if(openils.Event.parse(resp))
842 var resp = fieldmapper.standardRequest(
843 ['open-ils.circ', 'open-ils.circ.checkin.override'],
846 patron_id : this.patron.id(),
847 copy_barcode : barcode,
853 if(!resp.length) resp = [resp];
854 for(var i = 0; i < resp.length; i++) {
855 var tc = openils.Event.parse(resp[i]).textcode;
856 if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
867 * Check out a single item. If the item is already checked
868 * out to the patron, redirect to renew()
870 SelfCheckManager.prototype.checkout = function(barcode, override) {
872 this.prevCirc = null;
875 this.updateScanbox(null, true);
879 if(this.mockCheckouts) {
880 // if we're in mock-checkout mode, just insert another
881 // fake circ into the table and get out of here.
882 this.displayCheckout(this.mockCheckout, 'checkout');
886 // TODO see if it's a patron barcode
887 // TODO see if this item has already been checked out in this session
889 var method = 'open-ils.circ.checkout.full';
890 if(override) method += '.override';
892 console.log("Checkout out item " + barcode + " with method " + method);
894 var result = fieldmapper.standardRequest(
895 ['open-ils.circ', 'open-ils.circ.checkout.full'],
898 patron_id : this.patron.id(),
899 copy_barcode : barcode
904 var stat = this.handleXactResult('checkout', barcode, result);
907 this.checkout(barcode, true);
908 } else if(stat.doOver) {
909 this.checkout(barcode);
910 } else if(stat.renew) {
916 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
918 var displayText = '';
920 // If true, the display message is important enough to pop up. Whether or not
921 // an alert() actually occurs, depends on org unit settings
923 var sound = ''; // sound file reference
924 var payload = result.payload || {};
925 var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
927 if(result.textcode == 'NO_SESSION') {
929 return this.logoutStaff();
931 } else if(result.textcode == 'SUCCESS') {
933 if(action == 'checkout') {
935 displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
936 this.displayCheckout(result, 'checkout');
938 if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
939 // A hold was fulfilled, update the hold numbers in the circ summary
940 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
941 this.holdsSummary = null;
942 this.updateHoldsSummary();
945 this.updateCircSummary(true);
947 } else if(action == 'renew') {
949 displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
950 this.displayCheckout(result, 'renew');
953 this.checkouts.push({circ : result.payload.circ.id()});
954 sound = 'checkout-success';
955 this.updateScanBox();
957 } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
959 // Server says the item is already checked out. If it's checked out to the
960 // current user, we may need to renew it.
962 if(payload.old_circ) {
965 old_circ refers to the previous checkout IFF it's for the same user.
966 If no auto-renew interval is not defined, assume we should renew it
967 If an auto-renew interval is defined and the payload comes back with
968 auto_renew set to true, do the renewal. Otherwise, let the patron know
969 the item is already checked out to them. */
971 if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
972 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
973 this.prevCirc = payload.old_circ.id();
974 return { renew : true };
978 sound = 'checkout-failure';
979 displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
983 if( // copy is marked lost. if configured to do so, check it in and try again.
984 result.payload.copy &&
985 result.payload.copy.status() == /* LOST */ 3 &&
986 overrideEvents && overrideEvents.length &&
987 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
989 if(this.checkin(item)) {
990 return { doOver : true };
995 // item is checked out to some other user
997 sound = 'checkout-failure';
998 displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1001 this.updateScanBox({select:true});
1006 if(overrideEvents && overrideEvents.length) {
1008 // see if the events we received are all in the list of
1009 // events to override
1011 if(!result.length) result = [result];
1013 var override = true;
1014 for(var i = 0; i < result.length; i++) {
1015 var match = overrideEvents.filter(
1016 function(e) { return (e == result[i].textcode); })[0];
1022 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1023 // to override a transit, we have to abort the transit and check it in first
1024 if(this.checkin(item, true)) {
1025 return { doOver : true };
1034 return { override : true };
1037 this.updateScanBox({select : true});
1039 sound = 'checkout-failure';
1041 if(action == 'renew')
1042 this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1047 switch(result.textcode) {
1049 // TODO custom handler for blocking penalties
1051 case 'MAX_RENEWALS_REACHED' :
1052 displayText = dojo.string.substitute(
1053 localeStrings.MAX_RENEWALS, [item]);
1056 case 'ITEM_NOT_CATALOGED' :
1057 displayText = dojo.string.substitute(
1058 localeStrings.ITEM_NOT_CATALOGED, [item]);
1061 case 'OPEN_CIRCULATION_EXISTS' :
1062 displayText = dojo.string.substitute(
1063 localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1068 console.error('Unhandled event ' + result.textcode);
1070 if(action == 'checkout' || action == 'renew') {
1071 displayText = dojo.string.substitute(
1072 localeStrings.GENERIC_CIRC_FAILURE, [item]);
1074 displayText = dojo.string.substitute(
1075 localeStrings.UNKNOWN_ERROR, [result.textcode]);
1080 this.handleAlert(displayText, popup, sound);
1088 SelfCheckManager.prototype.renew = function(barcode, override) {
1090 var method = 'open-ils.circ.renew';
1091 if(override) method += '.override';
1093 console.log("Renewing item " + barcode + " with method " + method);
1095 var result = fieldmapper.standardRequest(
1096 ['open-ils.circ', method],
1099 patron_id : this.patron.id(),
1100 copy_barcode : barcode
1105 console.log(js2JSON(result));
1107 var stat = this.handleXactResult('renew', barcode, result);
1110 this.renew(barcode, true);
1114 * Display the result of a checkout or renewal in the items out table
1116 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1118 var copy = evt.payload.copy;
1119 var record = evt.payload.record;
1120 var circ = evt.payload.circ;
1121 var row = this.circTemplate.cloneNode(true);
1124 this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + record.isbn());
1127 this.byName(row, 'barcode').innerHTML = copy.barcode();
1128 this.byName(row, 'title').innerHTML = record.title();
1129 this.byName(row, 'author').innerHTML = record.author();
1130 this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1131 openils.Util.show(this.byName(row, type));
1133 var date = dojo.date.stamp.fromISOString(circ.due_date());
1134 this.byName(row, 'due_date').innerHTML =
1135 dojo.date.locale.format(date, {selector : 'date'});
1137 // put new circs at the top of the list
1138 var tbody = this.circTbody;
1139 if(itemsOut) tbody = this.itemsOutTbody;
1140 tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1144 SelfCheckManager.prototype.byName = function(node, name) {
1145 return dojo.query('[name=' + name+']', node)[0];
1149 SelfCheckManager.prototype.initPrinter = function() {
1150 try { // Mozilla only
1151 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1152 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1153 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1154 netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1155 var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1157 pref.setBoolPref('print.always_print_silent', true);
1159 console.log("Unable to initialize auto-printing");
1164 * Print a receipt for this session's checkouts
1166 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1169 var circCtx = []; // circ context data. in this case, renewal_failure info
1171 // collect the circs and failure info
1175 circIds.push(blob.circ);
1176 circCtx.push({renewal_failure:blob.renewal_failure});
1184 'format.selfcheck.checkout',
1191 fieldmapper.standardRequest(
1192 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1196 oncomplete : function(r) {
1197 var resp = openils.Util.readResponse(r);
1198 var output = resp.template_output();
1200 self.printData(output.data(), self.checkouts.length, callback);
1202 var error = resp.error_output();
1204 throw new Error("Error creating receipt: " + error.data());
1206 throw new Error("No receipt data returned from server");
1214 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1216 var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1');
1217 win.document.body.innerHTML = data;
1221 * There is no way to know when the browser is done printing.
1222 * Make a best guess at when to close the print window by basing
1223 * the setTimeout wait on the number of items to be printed plus
1226 var sleepTime = 1000;
1228 sleepTime += (numItems / 2) * 1000;
1232 win.close(); // close the print window
1234 callback(); // fire optional post-print callback
1242 * Print a receipt for this user's items out
1244 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1246 if(!this.itemsOut.length) return;
1248 progressDialog.show(true);
1254 'format.selfcheck.items_out',
1260 fieldmapper.standardRequest(
1261 ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1265 oncomplete : function(r) {
1266 progressDialog.hide();
1267 var resp = openils.Util.readResponse(r);
1268 var output = resp.template_output();
1270 self.printData(output.data(), self.itemsOut.length, callback);
1272 var error = resp.error_output();
1274 throw new Error("Error creating receipt: " + error.data());
1276 throw new Error("No receipt data returned from server");
1285 * Print a receipt for this user's items out
1287 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1289 if(!this.holds.length) return;
1291 progressDialog.show(true);
1296 dojo.forEach(this.holds,
1298 holdIds.push(data.hold.id());
1299 if(data.status == 4) {
1300 holdData.push({ready : true});
1303 queue_position : data.queue_position,
1304 potential_copies : data.potential_copies
1314 'format.selfcheck.holds',
1321 fieldmapper.standardRequest(
1322 ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1326 oncomplete : function(r) {
1327 progressDialog.hide();
1328 var resp = openils.Util.readResponse(r);
1329 var output = resp.template_output();
1331 self.printData(output.data(), self.holds.length, callback);
1333 var error = resp.error_output();
1335 throw new Error("Error creating receipt: " + error.data());
1337 throw new Error("No receipt data returned from server");
1347 * Print a receipt for this user's items out
1349 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1351 progressDialog.show(true);
1357 'format.selfcheck.fines',
1363 fieldmapper.standardRequest(
1364 ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1368 oncomplete : function(r) {
1369 progressDialog.hide();
1370 var resp = openils.Util.readResponse(r);
1371 var output = resp.template_output();
1373 self.printData(output.data(), self.finesCount, callback);
1375 var error = resp.error_output();
1377 throw new Error("Error creating receipt: " + error.data());
1379 throw new Error("No receipt data returned from server");
1391 * Logout the patron and return to the login page
1393 SelfCheckManager.prototype.logoutPatron = function(print) {
1394 if(print && this.checkouts.length) {
1395 this.printSessionReceipt(
1397 location.href = location.href;
1401 location.href = location.href;
1407 * Fire up the manager on page load
1409 openils.Util.addOnLoad(
1411 new SelfCheckManager().init();