]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/circ/selfcheck/selfcheck.js
3959fbca07e0ebf07a408bc2562fdd23bb3e0992
[Evergreen.git] / Open-ILS / web / js / ui / default / circ / selfcheck / selfcheck.js
1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.cookie');
3 dojo.require('dojo.date.stamp');
4 dojo.require('dijit.form.CheckBox');
5 dojo.require('dijit.form.NumberSpinner');
6 dojo.require('openils.CGI');
7 dojo.require('openils.Util');
8 dojo.require('openils.User');
9 dojo.require('openils.Event');
10 dojo.require('openils.widget.ProgressDialog');
11 dojo.require('openils.widget.OrgUnitFilteringSelect');
12
13
14 dojo.requireLocalization('openils.circ', 'selfcheck');
15 var localeStrings = dojo.i18n.getLocalization('openils.circ', 'selfcheck');
16
17 // set patron timeout default
18 var patronTimeout = 160000; /* 2 minutes, 40 seconds */
19 var timerId = null;
20 // 20 second inactivity warning; total default timeout is 3 minutes.
21 var patronTimeoutWarning = 20000; 
22 var selfckWarningSetup = false;
23 var selfckWarningTimer;
24
25 const SET_BARCODE_REGEX = 'opac.barcode_regex';
26 const SET_PATRON_TIMEOUT = 'circ.selfcheck.patron_login_timeout';
27 const SET_AUTO_OVERRIDE_EVENTS = 'circ.selfcheck.auto_override_checkout_events';
28 const SET_PATRON_PASSWORD_REQUIRED = 'circ.selfcheck.patron_password_required';
29 const SET_AUTO_RENEW_INTERVAL = 'circ.checkout_auto_renew_age';
30 const SET_WORKSTATION_REQUIRED = 'circ.selfcheck.workstation_required';
31 const SET_ALERT_POPUP = 'circ.selfcheck.alert.popup';
32 const SET_ALERT_SOUND = 'circ.selfcheck.alert.sound';
33 const SET_CC_PAYMENT_ALLOWED = 'credit.payments.allow';
34 // This setting only comes into play if COPY_NOT_AVAILABLE is in the SET_AUTO_OVERRIDE_EVENTS list
35 const SET_BLOCK_CHECKOUT_ON_COPY_STATUS = 'circ.selfcheck.block_checkout_on_copy_status';
36
37 // set before the login dialog is rendered
38 openils.User.default_login_agent = 'selfcheck';
39
40 // start the logout timer
41 function selfckStartTimer() {
42     timerId = setTimeout(
43         function() {
44             selfckLogoutWarning();
45         },
46         patronTimeout
47     );
48 }
49
50 // reset the logout timer
51 function selfckResetTimer() {
52     clearTimeout(timerId);
53     selfckStartTimer();
54 }
55
56 function selfckLogoutWarning() {
57
58     // connect the logout warning dialog button handlers if needed
59     if (!selfckWarningSetup) {
60         selfckWarningSetup = true;
61
62         dojo.connect(oilsSelfckLogout, 'onClick', 
63             function() {
64                 clearTimeout(selfckWarningTimer);
65                 oilsSelfckLogoutDialog.hide();
66                 SelfCheckManager.prototype.logoutPatron();
67             }
68         );
69
70         dojo.connect(oilsSelfckContinue, 'onClick', 
71             function() {
72                 clearTimeout(selfckWarningTimer);
73                 oilsSelfckLogoutDialog.hide();
74                 selfckResetTimer();
75             }
76         );
77     }
78
79     // warn the patron of imminent logout
80     oilsSelfckLogoutDialog.show();
81     selfckWarningTimer = setTimeout(
82         function() {
83             // no action was taken, force a logout.
84             oilsSelfckLogoutDialog.hide();
85             SelfCheckManager.prototype.logoutPatron();
86         },
87         patronTimeoutWarning
88     );
89 }
90
91 function SelfCheckManager() {
92
93     this.cgi = new openils.CGI();
94     this.staff = null; 
95     this.workstation = null;
96     this.authtoken = null;
97
98     this.patron = null; 
99     this.patronBarcodeRegex = null;
100
101     this.checkouts = [];
102     this.itemsOut = [];
103     this.holds = []; 
104
105     // During renewals, keep track of the ID of the previous circulation. 
106     // Previous circ is used for tracking failed renewals (for receipts).
107     this.prevCirc = null;
108
109     // current item barcode
110     this.itemBarcode = null; 
111
112     // are we currently performing a renewal?
113     this.isRenewal = false; 
114
115     // dict of org unit settings for "here"
116     this.orgSettings = {};
117
118     // Construct a mock checkout for debugging purposes
119     if(this.mockCheckouts = this.cgi.param('mock-circ')) {
120
121         this.mockCheckout = {
122             payload : {
123                 record : new fieldmapper.mvr(),
124                 copy : new fieldmapper.acp(),
125                 circ : new fieldmapper.circ()
126             }
127         };
128
129         this.mockCheckout.payload.record.title('Jazz improvisation for guitar');
130         this.mockCheckout.payload.record.author('Wise, Les');
131         this.mockCheckout.payload.record.isbn('0634033565');
132         this.mockCheckout.payload.copy.barcode('123456789');
133         this.mockCheckout.payload.circ.renewal_remaining(1);
134         this.mockCheckout.payload.circ.parent_circ(1);
135         this.mockCheckout.payload.circ.due_date('2012-12-21');
136     }
137
138     this.initPrinter();
139 }
140
141 SelfCheckManager.prototype.setupStaffLogin = function(verify) {
142
143     if(verify) oilsSetupUser(); 
144     this.staff = openils.User.user;
145     this.workstation = openils.User.workstation;
146     this.authtoken = openils.User.authtoken;
147 }
148
149
150
151 /**
152  * Fetch the org-unit settings, initialize the display, etc.
153  */
154 SelfCheckManager.prototype.init = function() {
155
156     this.setupStaffLogin();
157     this.loadOrgSettings();
158
159     this.circTbody = dojo.byId('oils-selfck-circ-tbody');
160     this.itemsOutTbody = dojo.byId('oils-selfck-circ-out-tbody');
161
162     // workstation is required but none provided
163     if(this.orgSettings[SET_WORKSTATION_REQUIRED] && !this.workstation) {
164         if(confirm(dojo.string.substitute(localeStrings.WORKSTATION_REQUIRED))) {
165             this.registerWorkstation();
166         }
167         return;
168     }
169     
170     var self = this;
171     // connect onclick handlers to the various navigation links
172     var linkHandlers = {
173         'oils-selfck-hold-details-link' : function() { self.drawHoldsPage(); },
174         'oils-selfck-view-fines-link' : function() { self.drawFinesPage(); },
175         'oils-selfck-pay-fines-link' : function() {
176             self.goToTab("payment");
177             self.drawPayFinesPage(
178                 self.patron,
179                 self.getSelectedFinesTotal(),
180                 self.getSelectedFineTransactions(),
181                 function(resp) {
182                     var evt = openils.Event.parse(resp);
183                     if(evt) {
184                         var message = evt + '';
185                         if(evt.textcode == 'CREDIT_PROCESSOR_DECLINED_TRANSACTION' && evt.payload)
186                             message += '\n' + evt.payload.error_message;
187                         if(evt.textcode == 'INVALID_USER_XACT_ID')
188                             message += '\n' + localeStrings.PAYMENT_INVALID_USER_XACT_ID;
189                         self.handleAlert(message, true, 'payment-failure');
190                         return;
191                     }
192
193                     self.patron.last_xact_id(resp.last_xact_id); // update to match latest from server
194                     self.printPaymentReceipt(
195                         resp,
196                         function() {
197                             self.updateFinesSummary();
198                             self.drawFinesPage();
199                         }
200                     );
201                 }
202             );
203         },
204         'oils-selfck-nav-home' : function() { self.drawCircPage(); },
205         'oils-selfck-nav-logout' : function() { self.logoutPatron(true); },
206         'oils-selfck-items-out-details-link' : function() { self.drawItemsOutPage(); },
207         'oils-selfck-print-list-link' : function() { self.printList(); }
208     }
209
210     for(var id in linkHandlers) 
211         dojo.connect(dojo.byId(id), 'onclick', linkHandlers[id]);
212
213
214     if(this.cgi.param('patron')) {
215         
216         // Patron barcode via cgi param.  Mainly used for debugging and
217         // only works if password is not required by policy
218         this.loginPatron(this.cgi.param('patron'));
219
220     } else {
221         this.drawLoginPage();
222     }
223
224     /**
225      * To test printing, pass a URL param of 'testprint'.  The value for the param
226      * should be a JSON string like so:  [{circ:<circ_id>}, ...]
227      */
228     var testPrint = this.cgi.param('testprint');
229     if(testPrint) {
230         this.checkouts = JSON2js(testPrint);
231         this.printSessionReceipt();
232         this.checkouts = [];
233     }
234 }
235
236
237 SelfCheckManager.prototype.getSelectedFinesTotal = function() {
238     var total = 0;
239     dojo.forEach(
240         dojo.query("[name=selector]", this.finesTbody),
241         function(input) {
242             if(input.checked)
243                 total += Number(input.getAttribute("balance_owed"));
244         }
245     );
246     return total.toFixed(2);
247 };
248
249 SelfCheckManager.prototype.getSelectedFineTransactions = function() {
250     return dojo.query("[name=selector]", this.finesTbody).
251         filter(function (o) { return o.checked }).
252         map(
253             function (o) {
254                 return [
255                     o.getAttribute("xact"),
256                     Number(o.getAttribute("balance_owed")).toFixed(2)
257                 ];
258             }
259         );
260 };
261
262 /**
263  * Registers a new workstion
264  */
265 SelfCheckManager.prototype.registerWorkstation = function() {
266     
267     oilsSelfckWsDialog.show();
268
269     new openils.User().buildPermOrgSelector(
270         'REGISTER_WORKSTATION', 
271         oilsSelfckWsLocSelector, 
272         this.staff.home_ou()
273     );
274
275
276     var self = this;
277     dojo.connect(oilsSelfckWsSubmit, 'onClick', 
278
279         function() {
280             oilsSelfckWsDialog.hide();
281             var name = oilsSelfckWsLocSelector.attr('displayedValue') + '-' + oilsSelfckWsName.attr('value');
282
283             var res = fieldmapper.standardRequest(
284                 ['open-ils.actor', 'open-ils.actor.workstation.register'],
285                 { params : [
286                         self.authtoken, name, oilsSelfckWsLocSelector.attr('value')
287                     ]
288                 }
289             );
290
291             if(evt = openils.Event.parse(res)) {
292                 if(evt.textcode == 'WORKSTATION_NAME_EXISTS') {
293                     if(confirm(localeStrings.WORKSTATION_EXISTS)) {
294                         location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
295                     } else {
296                         self.registerWorkstation();
297                     }
298                     return;
299                 } else {
300                     alert(evt);
301                 }
302             } else {
303                 location.href = location.href.replace(/\?.*/, '') + '?ws=' + name;
304             }
305         }
306     );
307 }
308
309 /**
310  * Loads the org unit settings
311  */
312 SelfCheckManager.prototype.loadOrgSettings = function() {
313
314     var settings = fieldmapper.aou.fetchOrgSettingBatch(
315         this.staff.ws_ou(), [
316             SET_BARCODE_REGEX,
317             SET_PATRON_TIMEOUT,
318             SET_ALERT_POPUP,
319             SET_ALERT_SOUND,
320             SET_AUTO_OVERRIDE_EVENTS,
321             SET_BLOCK_CHECKOUT_ON_COPY_STATUS,
322             SET_PATRON_PASSWORD_REQUIRED,
323             SET_AUTO_RENEW_INTERVAL,
324             SET_WORKSTATION_REQUIRED,
325             SET_CC_PAYMENT_ALLOWED
326         ]
327     );
328
329     for(k in settings) {
330         if(settings[k])
331             this.orgSettings[k] = settings[k].value;
332     }
333
334     if(settings[SET_BARCODE_REGEX]) 
335         this.patronBarcodeRegex = new RegExp(settings[SET_BARCODE_REGEX].value);
336
337     // Subtract the timeout warning interval from the configured timeout 
338     // so that when taken together they add up to the configured amount.
339     if(settings[SET_PATRON_TIMEOUT]) {
340         patronTimeout = 
341             (parseInt(settings[SET_PATRON_TIMEOUT].value) * 1000) 
342             - patronTimeoutWarning;
343     }
344 }
345
346 SelfCheckManager.prototype.drawLoginPage = function() {
347     var self = this;
348
349     var bcHandler = function(barcode_or_usrname) {
350         // handle patron barcode/usrname entry
351
352         if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
353             
354             // password is required.  wire up the scan box to read it
355             self.updateScanBox({
356                 msg : localeStrings.ENTER_PASSWORD,
357                 handler : function(pw) { self.loginPatron(barcode_or_usrname, pw); },
358                 password : true
359             });
360
361         } else {
362             // password is not required, go ahead and login
363             self.loginPatron(barcode_or_usrname);
364         }
365     };
366
367     this.updateScanBox({
368         msg : localeStrings.PLEASE_LOGIN,
369         handler : bcHandler
370     });
371 }
372
373 /**
374  * Login the patron.  
375  */
376 SelfCheckManager.prototype.loginPatron = function(barcode_or_usrname, passwd) {
377
378     // reset timeout
379     selfckResetTimer();
380
381     this.setupStaffLogin(true); // verify still valid
382
383     var barcode = null;
384     var usrname = null;
385     console.log('testing ' + barcode_or_usrname);
386     if (barcode_or_usrname.match(this.patronBarcodeRegex)) {
387         console.log('barcode');
388         barcode = barcode_or_usrname;
389     } else {
390         console.log('usrname');
391         usrname = barcode_or_usrname;
392     }
393
394     if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
395         
396         if(!passwd) {
397             // would only happen in dev/debug mode when using the patron= param
398             alert('password required by org setting.  remove patron= from URL'); 
399             return;
400         }
401
402         // patron password is required.  Verify it.
403
404         var self = this;
405         new openils.User().auth_verify(
406             {   username : usrname, barcode : barcode, 
407                 type : 'opac', passwd : passwd, agent : 'selfcheck' },
408             function(OK) {
409                 if (OK) {
410                     self.fetchPatron(barcode, usrname);
411
412                 } else {
413                     // auth verify failed
414                     self.handleAlert(
415                         dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode_or_usrname]),
416                         false, 'login-failure'
417                     );
418                     self.drawLoginPage();
419                 }
420             }
421         );
422
423     } else {
424         this.fetchPatron(barcode, usrname);
425     }
426 };
427
428 SelfCheckManager.prototype.fetchPatron = function(barcode, usrname) {
429
430     var patron_id = fieldmapper.standardRequest(
431         ['open-ils.actor', 'open-ils.actor.user.retrieve_id_by_barcode_or_username'],
432         {params : [this.authtoken, barcode, usrname]}
433     );
434
435     // retrieve the fleshed user by id
436     this.patron = fieldmapper.standardRequest(
437         ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve.authoritative'],
438         {params : [this.authtoken, patron_id]}
439     );
440
441     var evt = openils.Event.parse(this.patron);
442     
443     // verify validity of the card used to log in
444     var inactiveCard = false;
445     if(!evt) {
446         var card;
447         if (barcode) {
448             card = this.patron.cards().filter(
449                 function(c) { return (c.barcode() == barcode); })[0];
450         } else {
451             card = this.patron.card();
452         }
453         inactiveCard = !openils.Util.isTrue(card.active());
454     }
455
456     if(evt || inactiveCard) {
457         this.handleAlert(
458             dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode || usrname]),
459             false, 'login-failure'
460         );
461         this.drawLoginPage();
462
463     } else {
464
465         this.handleAlert('', false, 'login-success');
466         dojo.byId('oils-selfck-user-banner').innerHTML = 
467             dojo.string.substitute(localeStrings.WELCOME_BANNER, [this.patron.first_given_name()]);
468
469         if (this.patron.email() && // they have an email address set and ...
470             this.patron.email().match(/.*@.*/).length > 0 // it sorta looks like an email address
471         ) {
472             openils.Util.removeCSSClass( dojo.byId('oils-selfck-receipt-email').parentNode, 'hidden' );
473             if (user_setting_value(this.patron, 'circ.send_email_checkout_receipts') == 'true') // their selected default
474                 dojo.byId('oils-selfck-receipt-email').checked = true;
475         }
476
477         this.drawCircPage();
478     }
479 }
480
481 function user_setting_value (user, setting) {
482     if (user) {
483         var list = user.settings().filter(function(s){
484             return s.name() == setting;
485         });
486
487         if (list.length) return list[0].value();
488     }
489 }
490
491 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
492
493     console.log("Handling alert " + message);
494
495     dojo.byId('oils-selfck-status-div').innerHTML = message;
496
497     if(shouldPopup)
498         openils.Util.addCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
499     else
500         openils.Util.removeCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
501
502     if(shouldPopup && this.orgSettings[SET_ALERT_POPUP]) 
503         alert(message);
504
505     if(sound && this.orgSettings[SET_ALERT_SOUND])
506         openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
507 }
508
509
510 /**
511  * Manages the main input box
512  * @param msg The context message to display with the box
513  * @param clearOnly Don't update the context message, just clear the value and re-focus
514  * @param handler Optional "on-enter" handler.  
515  */
516 SelfCheckManager.prototype.updateScanBox = function(args) {
517     args = args || {};
518
519     if(args.select) {
520         selfckScanBox.domNode.select();
521     } else {
522         selfckScanBox.attr('value', '');
523     }
524
525     if(args.password) {
526         selfckScanBox.domNode.setAttribute('type', 'password');
527     } else {
528         selfckScanBox.domNode.setAttribute('type', '');
529     }
530
531     if(args.value)
532         selfckScanBox.attr('value', args.value);
533
534     if(args.msg) 
535         dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
536
537     if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
538         dojo.disconnect(selfckScanBox._lastHandler);
539     }
540
541     if(args.handler) {
542         selfckScanBox._lastHandler = dojo.connect(
543             selfckScanBox, 
544             'onKeyDown', 
545             function(e) {
546                 if(e.keyCode != dojo.keys.ENTER) 
547                     return;
548                 args.handler(selfckScanBox.attr('value'));
549             }
550         );
551     }
552
553     selfckScanBox.focus();
554 }
555
556 /**
557  *  Sets up the checkout/renewal interface
558  */
559 SelfCheckManager.prototype.drawCircPage = function() {
560
561     openils.Util.show('oils-selfck-bottom-div');
562     openils.Util.show('oils-selfck-circ-tbody', 'table-row-group');
563     this.goToTab('checkout');
564
565     while(this.itemsOutTbody.childNodes[0])
566         this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
567
568     var self = this;
569     this.updateScanBox({
570         msg : localeStrings.ENTER_BARCODE,
571         handler : function(barcode) { self.checkout(barcode); }
572     });
573
574     if(!this.circTemplate)
575         this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
576
577     // fines summary
578     this.updateFinesSummary();
579
580     // holds summary
581     this.updateHoldsSummary();
582
583     // items out summary
584     this.updateCircSummary();
585
586     // render mock checkouts for debugging?
587     if(this.mockCheckouts) {
588         for(var i in [1,2,3]) 
589             this.displayCheckout(this.mockCheckout, 'checkout');
590     }
591 }
592
593
594 SelfCheckManager.prototype.updateFinesSummary = function() {
595     var self = this; 
596
597     // fines summary
598     fieldmapper.standardRequest(
599         ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
600         {   async : true,
601             params : [this.authtoken, this.patron.id()],
602             oncomplete : function(r) {
603
604                 var summary = openils.Util.readResponse(r);
605
606                 dojo.byId('oils-selfck-fines-total').innerHTML = 
607                     dojo.string.substitute(
608                         localeStrings.TOTAL_FINES_ACCOUNT, 
609                         ['<b>' + summary.balance_owed() + '</b>']
610                     );
611
612                 self.creditPayableBalance = summary.balance_owed();
613             }
614         }
615     );
616 }
617
618
619 SelfCheckManager.prototype.drawItemsOutPage = function() {
620     openils.Util.hide('oils-selfck-circ-tbody');
621
622     this.goToTab('items_out');
623
624     while(this.itemsOutTbody.childNodes[0])
625         this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
626
627     progressDialog.show(true);
628     
629     var self = this;
630     fieldmapper.standardRequest(
631         ['open-ils.circ', 'open-ils.circ.actor.user.checked_out.atomic'],
632         {
633             async : true,
634             params : [this.authtoken, this.patron.id()],
635             oncomplete : function(r) {
636
637                 var resp = openils.Util.readResponse(r);
638
639                 var circs = resp.sort(
640                     function(a, b) {
641                         if(a.circ.due_date() > b.circ.due_date())
642                             return -1;
643                         return 1;
644                     }
645                 );
646
647                 progressDialog.hide();
648
649                 self.itemsOut = [];
650                 dojo.forEach(circs,
651                     function(circ) {
652                         self.itemsOut.push(circ.circ.id());
653                         self.displayCheckout(
654                             {payload : circ}, 
655                             (circ.circ.parent_circ()) ? 'renew' : 'checkout',
656                             true
657                         );
658                     }
659                 );
660             }
661         }
662     );
663 }
664
665
666 SelfCheckManager.prototype.goToTab = function(name) {
667     this.tabName = name;
668
669     openils.Util.hide('oils-selfck-fines-page');
670     openils.Util.hide('oils-selfck-payment-page');
671     openils.Util.hide('oils-selfck-holds-page');
672     openils.Util.hide('oils-selfck-circ-page');
673     openils.Util.hide('oils-selfck-pay-fines-link');
674
675     // reset timeout
676     selfckResetTimer()
677     
678     switch(name) {
679         case 'checkout':
680             openils.Util.show('oils-selfck-circ-page');
681             break;
682         case 'items_out':
683             openils.Util.show('oils-selfck-circ-page');
684             break;
685         case 'holds':
686             openils.Util.show('oils-selfck-holds-page');
687             break;
688         case 'fines':
689             openils.Util.show('oils-selfck-fines-page');
690             break;
691         case 'payment':
692             openils.Util.show('oils-selfck-payment-page');
693             break;
694     }
695 }
696
697
698 SelfCheckManager.prototype.printList = function() {
699     // reset timeout
700     selfckResetTimer()
701
702     switch(this.tabName) {
703         case 'checkout':
704             this.printSessionReceipt();
705             break;
706         case 'items_out':
707             this.printItemsOutReceipt();
708             break;
709         case 'holds':
710             this.printHoldsReceipt();
711             break;
712         case 'fines':
713             this.printFinesReceipt();
714             break;
715     }
716 }
717
718 SelfCheckManager.prototype.updateHoldsSummary = function() {
719
720     if(!this.holdsSummary) {
721         var summary = fieldmapper.standardRequest(
722             ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
723             {params : [this.authtoken, this.patron.id()]}
724         );
725
726         this.holdsSummary = {};
727         this.holdsSummary.ready = Number(summary['4']);
728         this.holdsSummary.total = 0;
729
730         for(var i in summary) 
731             this.holdsSummary.total += Number(summary[i]);
732     }
733
734     dojo.byId('oils-selfck-holds-total').innerHTML = 
735         dojo.string.substitute(
736             localeStrings.TOTAL_HOLDS, 
737             ['<b>' + this.holdsSummary.total + '</b>']
738         );
739
740     dojo.byId('oils-selfck-holds-ready').innerHTML = 
741         dojo.string.substitute(
742             localeStrings.HOLDS_READY_FOR_PICKUP, 
743             ['<b>' + this.holdsSummary.ready + '</b>']
744         );
745 }
746
747
748 SelfCheckManager.prototype.updateCircSummary = function(increment) {
749
750     if(!this.circSummary) {
751
752         var summary = fieldmapper.standardRequest(
753             ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
754             {params : [this.authtoken, this.patron.id()]}
755         );
756
757         this.circSummary = {
758             total : Number(summary.out) + Number(summary.overdue),
759             overdue : Number(summary.overdue),
760             session : 0
761         };
762     }
763
764     if(increment) {
765         // local checkout occurred.  Add to the total and the session.
766         this.circSummary.total += 1;
767         this.circSummary.session += 1;
768     }
769
770     dojo.byId('oils-selfck-circ-account-total').innerHTML = 
771         dojo.string.substitute(
772             localeStrings.TOTAL_ITEMS_ACCOUNT, 
773             ['<b>' + this.circSummary.total + '</b>']
774         );
775
776     dojo.byId('oils-selfck-circ-session-total').innerHTML = 
777         dojo.string.substitute(
778             localeStrings.TOTAL_ITEMS_SESSION, 
779             ['<b>' + this.circSummary.session + '</b>']
780         );
781 }
782
783
784 SelfCheckManager.prototype.drawHoldsPage = function() {
785
786     // TODO add option to hid scanBox
787     // this.updateScanBox(...)
788
789     this.goToTab('holds');
790
791     this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
792     if(!this.holdTemplate)
793         this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
794     while(this.holdTbody.childNodes[0])
795         this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
796
797     progressDialog.show(true);
798
799     var self = this;
800     fieldmapper.standardRequest( // fetch the hold IDs
801
802         ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
803         {   async : true,
804             params : [this.authtoken, this.patron.id()],
805
806             oncomplete : function(r) { 
807                 var ids = openils.Util.readResponse(r);
808                 if(!ids || ids.length == 0) {
809                     progressDialog.hide();
810                     return;
811                 }
812
813                 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
814                     ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve'],
815                     {   async : true,
816                         params : [self.authtoken, ids],
817                         onresponse : function(rr) {
818                             progressDialog.hide();
819                             self.insertHold(openils.Util.readResponse(rr));
820                         }
821                     }
822                 );
823             }
824         }
825     );
826 }
827
828 SelfCheckManager.prototype.insertHold = function(data) {
829
830     // store hold data to pass along to receipt printing function
831     this.holds.push(data);
832
833     var row = this.holdTemplate.cloneNode(true);
834
835     if(data.mvr.isbn()) {
836         this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/r/' + data.mvr.doc_id());
837     }
838
839     this.byName(row, 'title').innerHTML = data.mvr.title();
840     this.byName(row, 'author').innerHTML = data.mvr.author();
841
842     if(data.status == 4) {
843
844         // hold is ready for pickup
845         this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
846
847     } else {
848
849         // hold is still pending
850         this.byName(row, 'status').innerHTML = 
851             dojo.string.substitute(
852                 localeStrings.HOLD_STATUS_WAITING,
853                 [data.queue_position, data.potential_copies]
854             );
855     }
856
857     // find the correct place the table to slot in the hold based on queue position
858
859     var position = (data.status == 4) ? 0 : data.queue_position;
860     row.setAttribute('position', position);
861
862     for(var i = 0; i < this.holdTbody.childNodes.length; i++) {
863         var node = this.holdTbody.childNodes[i];
864         if(Number(node.getAttribute('position')) >= position) {
865             this.holdTbody.insertBefore(row, node);
866             return;
867         }
868     }
869
870     this.holdTbody.appendChild(row);
871 }
872
873
874 SelfCheckManager.prototype.drawFinesPage = function() {
875
876     // TODO add option to hid scanBox
877     // this.updateScanBox(...)
878
879     this.goToTab('fines');
880     progressDialog.show(true);
881
882     if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
883         openils.Util.show('oils-selfck-pay-fines-link', 'inline');
884     }
885
886     this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
887     if(!this.finesTemplate)
888         this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
889     while(this.finesTbody.childNodes[0])
890         this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
891
892     // when user clicks on a selector checkbox, update the total owed
893     var updateSelected = function() {
894         var total = 0;
895         dojo.forEach(
896             dojo.query('[name=selector]', this.finesTbody),
897             function(input) {
898                 if(input.checked)
899                     total += Number(input.getAttribute('balance_owed'));
900             }
901         );
902
903         total = total.toFixed(2);
904         dojo.byId('oils-selfck-selected-total').innerHTML = 
905             dojo.string.substitute(localeStrings.TOTAL_FINES_SELECTED, [total]);
906     }
907
908     // wire up the batch on/off selector
909     var sel = dojo.byId('oils-selfck-fines-selector');
910     sel.onchange = function() {
911         dojo.forEach(
912             dojo.query('[name=selector]', this.finesTbody),
913             function(input) {
914                 input.checked = sel.checked;
915             }
916         );
917     };
918
919     var self = this;
920     var handler = function(dataList) {
921
922         self.finesCount = dataList.length;
923         self.finesData = dataList;
924
925         for(var i in dataList) {
926
927             var data = dataList[i];
928             var row = self.finesTemplate.cloneNode(true);
929             var type = data.transaction.xact_type();
930
931             if(type == 'circulation') {
932                 self.byName(row, 'type').innerHTML = type;
933                 self.byName(row, 'details').innerHTML = data.record.title();
934
935             } else if(type == 'grocery') {
936                 self.byName(row, 'type').innerHTML = localeStrings.MISCELLANEOUS; // Go ahead and head off any confusion around "grocery".
937                 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
938             }
939
940             self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
941             self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
942             self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
943
944             // row selector
945             var selector = self.byName(row, 'selector')
946             selector.onchange = updateSelected;
947             selector.setAttribute('xact', data.transaction.id());
948             selector.setAttribute('balance_owed', data.transaction.balance_owed());
949             selector.checked = true;
950
951             self.finesTbody.appendChild(row);
952         }
953
954         updateSelected();
955     }
956
957
958     fieldmapper.standardRequest( 
959         ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
960         {   async : true,
961             params : [this.authtoken, this.patron.id()],
962             oncomplete : function(r) { 
963                 progressDialog.hide();
964                 handler(openils.Util.readResponse(r));
965             }
966         }
967     );
968 }
969
970 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
971
972     var resp = fieldmapper.standardRequest(
973         ['open-ils.circ', 'open-ils.circ.transit.abort'],
974         {params : [this.authtoken, {barcode : barcode}]}
975     );
976
977     // resp == 1 on success
978     if(openils.Event.parse(resp))
979         return false;
980
981     var resp = fieldmapper.standardRequest(
982         ['open-ils.circ', 'open-ils.circ.checkin.override'],
983         {params : [
984             this.authtoken, {
985                 patron_id : this.patron.id(),
986                 copy_barcode : barcode,
987                 noop : true
988             }
989         ]}
990     );
991
992     if(!resp.length) resp = [resp];
993     for(var i = 0; i < resp.length; i++) {
994         var tc = openils.Event.parse(resp[i]).textcode;
995         if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
996             continue;
997         } else {
998             return false;
999         }
1000     }
1001
1002     return true;
1003 }
1004
1005 /**
1006  * Check out a single item.  If the item is already checked 
1007  * out to the patron, redirect to renew()
1008  */
1009 SelfCheckManager.prototype.checkout = function(barcode, override) {
1010
1011     // reset timeout
1012     selfckResetTimer();
1013
1014     this.prevCirc = null;
1015
1016     if(!barcode) {
1017         this.updateScanbox(null, true);
1018         return;
1019     }
1020
1021     if(this.mockCheckouts) {
1022         // if we're in mock-checkout mode, just insert another
1023         // fake circ into the table and get out of here.
1024         this.displayCheckout(this.mockCheckout, 'checkout');
1025         return;
1026     }
1027
1028     // TODO see if it's a patron barcode
1029     // TODO see if this item has already been checked out in this session
1030
1031     var method = 'open-ils.circ.checkout.full';
1032     if(override) method += '.override';
1033
1034     console.log("Checkout out item " + barcode + " with method " + method);
1035
1036     var result = fieldmapper.standardRequest(
1037         ['open-ils.circ', method],
1038         {params: [
1039             this.authtoken, {
1040                 patron_id : this.patron.id(),
1041                 copy_barcode : barcode
1042             }
1043         ]}
1044     );
1045
1046     var stat = this.handleXactResult('checkout', barcode, result);
1047
1048     if(stat.override) {
1049         this.checkout(barcode, true);
1050     } else if(stat.doOver) {
1051         this.checkout(barcode);
1052     } else if(stat.renew) {
1053         this.renew(barcode);
1054     }
1055 }
1056
1057 SelfCheckManager.prototype.failPartMessage = function(result) {
1058     if (result.payload && result.payload.fail_part) {
1059         var stringKey = "FAIL_PART_" +
1060             result.payload.fail_part.replace(/\./g, "_");
1061         return localeStrings[stringKey];
1062     } else {
1063         return null;
1064     }
1065 }
1066
1067 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
1068
1069     var displayText = '';
1070
1071     // If true, the display message is important enough to pop up.  Whether or not
1072     // an alert() actually occurs, depends on org unit settings
1073     var popup = false;  
1074     var sound = ''; // sound file reference
1075     var payload = result.payload || {};
1076     var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
1077     var blockStatuses = this.orgSettings[SET_BLOCK_CHECKOUT_ON_COPY_STATUS];
1078         
1079     if(result.textcode == 'NO_SESSION') {
1080
1081         return this.logoutStaff();
1082
1083     } else if(result.textcode == 'SUCCESS') {
1084
1085         if(action == 'checkout') {
1086
1087             displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
1088             this.displayCheckout(result, 'checkout');
1089
1090             if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
1091                 // A hold was fulfilled, update the hold numbers in the circ summary
1092                 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
1093                 this.holdsSummary = null;
1094                 this.updateHoldsSummary();
1095             }
1096
1097             this.updateCircSummary(true);
1098
1099         } else if(action == 'renew') {
1100
1101             displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
1102             this.displayCheckout(result, 'renew');
1103         }
1104
1105         this.checkouts.push({circ : result.payload.circ.id()});
1106         sound = 'checkout-success';
1107         this.updateScanBox();
1108
1109     } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
1110
1111         // Server says the item is already checked out.  If it's checked out to the
1112         // current user, we may need to renew it.  
1113
1114         if(payload.old_circ) { 
1115
1116             /*
1117             old_circ refers to the previous checkout IFF it's for the same user. 
1118             If no auto-renew interval is not defined, assume we should renew it
1119             If an auto-renew interval is defined and the payload comes back with
1120             auto_renew set to true, do the renewal.  Otherwise, let the patron know
1121             the item is already checked out to them.  */
1122
1123             if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
1124                 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
1125                 this.prevCirc = payload.old_circ.id();
1126                 return { renew : true };
1127             }
1128
1129             popup = true;
1130             sound = 'checkout-failure';
1131             displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
1132
1133         } else {
1134
1135             if( // copy is marked lost.  if configured to do so, check it in and try again.
1136                 result.payload.copy && 
1137                 result.payload.copy.status() == /* LOST */ 3 &&
1138                 overrideEvents && overrideEvents.length &&
1139                 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
1140
1141                     if(this.checkin(item)) {
1142                         return { doOver : true };
1143                     }
1144             }
1145
1146             
1147             // item is checked out to some other user
1148             popup = true;
1149             sound = 'checkout-failure';
1150             displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1151         }
1152
1153         this.updateScanBox({select:true});
1154
1155     } else {
1156
1157     
1158         if(overrideEvents && overrideEvents.length) {
1159             
1160             // see if the events we received are all in the list of
1161             // events to override
1162     
1163             if(!result.length) result = [result];
1164     
1165             var override = true;
1166             for(var i = 0; i < result.length; i++) {
1167
1168                 var match = overrideEvents.filter(function(e) { return (e == result[i].textcode); })[0];
1169
1170                 if(!match) {
1171                     override = false;
1172                     break;
1173                 }
1174
1175                 if(result[i].textcode == 'COPY_NOT_AVAILABLE' && blockStatuses && blockStatuses.length) {
1176
1177                     var stat = result[i].payload.status(); // copy status
1178                     if(typeof stat == 'object') stat = stat.id();
1179
1180                     var match2 = blockStatuses.filter(function(e) { return (e == stat); })[0];
1181
1182                     if(match2) { // copy is in a blocked status
1183                         override = false;
1184                         break;
1185                     }
1186                 }
1187
1188                 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1189                     // to override a transit, we have to abort the transit and check it in first
1190                     if(this.checkin(item, true)) {
1191                         return { doOver : true };
1192                     } else {
1193                         override = false;
1194                     }
1195                 }
1196             }
1197
1198             if(override) 
1199                 return { override : true };
1200         }
1201     
1202         this.updateScanBox({select : true});
1203         popup = true;
1204         sound = 'checkout-failure';
1205
1206         if(action == 'renew')
1207             this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1208
1209         if(result.length) 
1210             result = result[0];
1211
1212         switch(result.textcode) {
1213
1214             // TODO custom handler for blocking penalties
1215
1216             case 'MAX_RENEWALS_REACHED' :
1217                 displayText = dojo.string.substitute(
1218                     localeStrings.MAX_RENEWALS, [item]);
1219                 break;
1220
1221             case 'ITEM_NOT_CATALOGED' :
1222                 displayText = dojo.string.substitute(
1223                     localeStrings.ITEM_NOT_CATALOGED, [item]);
1224                 break;
1225
1226             case 'OPEN_CIRCULATION_EXISTS' :
1227                 displayText = dojo.string.substitute(
1228                     localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1229
1230                 break;
1231
1232             default:
1233                 console.error('Unhandled event ' + result.textcode);
1234
1235                 if (!(displayText = this.failPartMessage(result))) {
1236                     if (action == 'checkout' || action == 'renew') {
1237                         displayText = dojo.string.substitute(
1238                             localeStrings.GENERIC_CIRC_FAILURE, [item]);
1239                     } else {
1240                         displayText = dojo.string.substitute(
1241                             localeStrings.UNKNOWN_ERROR, [result.textcode]);
1242                     }
1243                 }
1244         }
1245     }
1246
1247     this.handleAlert(displayText, popup, sound);
1248     return {};
1249 }
1250
1251
1252 /**
1253  * Renew an item
1254  */
1255 SelfCheckManager.prototype.renew = function(barcode, override) {
1256
1257     var method = 'open-ils.circ.renew';
1258     if(override) method += '.override';
1259
1260     console.log("Renewing item " + barcode + " with method " + method);
1261
1262     var result = fieldmapper.standardRequest(
1263         ['open-ils.circ', method],
1264         {params: [
1265             this.authtoken, {
1266                 patron_id : this.patron.id(),
1267                 copy_barcode : barcode
1268             }
1269         ]}
1270     );
1271
1272     console.log(js2JSON(result));
1273
1274     var stat = this.handleXactResult('renew', barcode, result);
1275
1276     if(stat.override)
1277         this.renew(barcode, true);
1278 }
1279
1280 /**
1281  * Display the result of a checkout or renewal in the items out table
1282  */
1283 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1284
1285     var copy = evt.payload.copy;
1286     var record = evt.payload.record;
1287     var circ = evt.payload.circ;
1288     var row = this.circTemplate.cloneNode(true);
1289
1290     if(record.doc_id()) {
1291         this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/r/' + record.doc_id());
1292     }
1293
1294     this.byName(row, 'barcode').innerHTML = copy.barcode();
1295     this.byName(row, 'title').innerHTML = record.title();
1296     this.byName(row, 'author').innerHTML = record.author();
1297     this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1298     openils.Util.show(this.byName(row, type));
1299
1300     var date = dojo.date.stamp.fromISOString(circ.due_date());
1301     this.byName(row, 'due_date').innerHTML = 
1302         dojo.date.locale.format(date, {selector : 'date'});
1303
1304     // put new circs at the top of the list
1305     var tbody = this.circTbody;
1306     if(itemsOut) tbody = this.itemsOutTbody;
1307     tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1308 }
1309
1310
1311 SelfCheckManager.prototype.byName = function(node, name) {
1312     return dojo.query('[name=' + name+']', node)[0];
1313 }
1314
1315
1316 SelfCheckManager.prototype.initPrinter = function() {
1317     try { // Mozilla only
1318                 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1319         netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1320         netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1321         netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1322         var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1323         if (pref)
1324             pref.setBoolPref('print.always_print_silent', true);
1325     } catch(E) {
1326         console.log("Unable to initialize auto-printing"); 
1327     }
1328 }
1329
1330 /**
1331  * Email a receipt for this session's checkouts
1332  */
1333 SelfCheckManager.prototype.emailSessionReceipt = function(callback) {
1334
1335     var circIds = [];
1336
1337     // collect the circs and failure info
1338     dojo.forEach(
1339         this.checkouts, 
1340         function(blob) {
1341             circIds.push(blob.circ);
1342         }
1343     );
1344
1345     var params = [
1346         this.authtoken, 
1347         this.patron.id(),
1348         circIds
1349     ];
1350
1351     var self = this;
1352     fieldmapper.standardRequest(
1353         ['open-ils.circ', 'open-ils.circ.checkout.batch_notify.session.atomic'],
1354         {   
1355             async : true,
1356             params : params,
1357             oncomplete : function() {
1358                 if (callback) callback(); // fire and forget
1359             }
1360         }
1361     );
1362 }
1363
1364 /**
1365  * Print a receipt for this session's checkouts
1366  */
1367 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1368
1369     var circIds = [];
1370     var circCtx = []; // circ context data.  in this case, renewal_failure info
1371
1372     // collect the circs and failure info
1373     dojo.forEach(
1374         this.checkouts, 
1375         function(blob) {
1376             circIds.push(blob.circ);
1377             circCtx.push({renewal_failure:blob.renewal_failure});
1378         }
1379     );
1380
1381     var params = [
1382         this.authtoken, 
1383         this.staff.ws_ou(),
1384         null,
1385         'format.selfcheck.checkout',
1386         'print-on-demand',
1387         circIds,
1388         circCtx
1389     ];
1390
1391     var self = this;
1392     fieldmapper.standardRequest(
1393         ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1394         {   
1395             async : true,
1396             params : params,
1397             oncomplete : function(r) {
1398                 var resp = openils.Util.readResponse(r);
1399                 var output = resp.template_output();
1400                 if(output) {
1401                     self.printData(output.data(), self.checkouts.length, callback); 
1402                 } else {
1403                     var error = resp.error_output();
1404                     if(error) {
1405                         throw new Error("Error creating receipt: " + error.data());
1406                     } else {
1407                         throw new Error("No receipt data returned from server");
1408                     }
1409                 }
1410             }
1411         }
1412     );
1413 }
1414
1415 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1416
1417     var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1,chrome'); 
1418     win.document.body.innerHTML = data;
1419     win.print();
1420
1421     /*
1422      * There is no way to know when the browser is done printing.
1423      * Make a best guess at when to close the print window by basing
1424      * the setTimeout wait on the number of items to be printed plus
1425      * a small buffer
1426      */
1427     var sleepTime = 1000;
1428     if(numItems > 0) 
1429         sleepTime += (numItems / 2) * 1000;
1430
1431     setTimeout(
1432         function() { 
1433             win.close(); // close the print window
1434             if(callback)
1435                 callback(); // fire optional post-print callback
1436         },
1437         sleepTime 
1438     );
1439 }
1440
1441
1442
1443 /**
1444  * Print a receipt for this user's items out
1445  */
1446 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1447
1448     if(!this.itemsOut.length) return;
1449
1450     progressDialog.show(true);
1451
1452     var params = [
1453         this.authtoken, 
1454         this.staff.ws_ou(),
1455         null,
1456         'format.selfcheck.items_out',
1457         'print-on-demand',
1458         this.itemsOut
1459     ];
1460
1461     var self = this;
1462     fieldmapper.standardRequest(
1463         ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1464         {   
1465             async : true,
1466             params : params,
1467             oncomplete : function(r) {
1468                 progressDialog.hide();
1469                 var resp = openils.Util.readResponse(r);
1470                 var output = resp.template_output();
1471                 if(output) {
1472                     self.printData(output.data(), self.itemsOut.length, callback); 
1473                 } else {
1474                     var error = resp.error_output();
1475                     if(error) {
1476                         throw new Error("Error creating receipt: " + error.data());
1477                     } else {
1478                         throw new Error("No receipt data returned from server");
1479                     }
1480                 }
1481             }
1482         }
1483     );
1484 }
1485
1486 /**
1487  * Print a receipt for this user's holds
1488  */
1489 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1490
1491     if(!this.holds.length) return;
1492
1493     progressDialog.show(true);
1494
1495     var holdIds = [];
1496     var holdData = [];
1497
1498     dojo.forEach(this.holds,
1499         function(data) {
1500             holdIds.push(data.hold.id());
1501
1502             //get pickup library info
1503             var pu = fieldmapper.standardRequest(['open-ils.actor','open-ils.actor.org_unit.retrieve'],[null,data.hold.pickup_lib()]);
1504             
1505             if(data.status == 4) {
1506                 holdData.push({
1507                     ready : true,
1508                     item_title : data.mvr.title(),
1509                     item_author : data.mvr.author(),
1510                     pickup_lib : pu.name()
1511                 });
1512             } else {
1513                 holdData.push({
1514                     queue_position : data.queue_position, 
1515                     potential_copies : data.potential_copies,
1516                     item_title : data.mvr.title(),
1517                     item_author : data.mvr.author(),
1518                     pickup_lib : pu.name()
1519                 });
1520             }
1521         }
1522     );
1523
1524     var params = [
1525         this.authtoken, 
1526         this.staff.ws_ou(),
1527         null,
1528         'format.selfcheck.holds',
1529         'print-on-demand',
1530         holdIds,
1531         holdData
1532     ];
1533
1534     var self = this;
1535     fieldmapper.standardRequest(
1536         ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1537         {   
1538             async : true,
1539             params : params,
1540             oncomplete : function(r) {
1541                 progressDialog.hide();
1542                 var resp = openils.Util.readResponse(r);
1543                 var output = resp.template_output();
1544                 if(output) {
1545                     self.printData(output.data(), self.holds.length, callback); 
1546                 } else {
1547                     var error = resp.error_output();
1548                     if(error) {
1549                         throw new Error("Error creating receipt: " + error.data());
1550                     } else {
1551                         throw new Error("No receipt data returned from server");
1552                     }
1553                 }
1554             }
1555         }
1556     );
1557 }
1558
1559
1560 SelfCheckManager.prototype.printPaymentReceipt = function(response, callback) {
1561     
1562     var self = this;
1563     progressDialog.show(true);
1564
1565     fieldmapper.standardRequest(
1566         ['open-ils.circ', 'open-ils.circ.money.payment_receipt.print'],
1567         {
1568             async : true,
1569             params : [this.authtoken, response.payments],
1570             oncomplete : function(r) {
1571                 var resp = openils.Util.readResponse(r);
1572                 var output = resp.template_output();
1573                 progressDialog.hide();
1574                 if(output) {
1575                     self.printData(output.data(), 1, callback); 
1576                 } else {
1577                     var error = resp.error_output();
1578                     if(error) {
1579                         throw new Error("Error creating receipt: " + error.data());
1580                     } else {
1581                         throw new Error("No receipt data returned from server");
1582                     }
1583                 }
1584             }
1585         }
1586     );
1587 }
1588
1589 /**
1590  * Print a receipt for this user's fines
1591  */
1592 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1593
1594     if(!this.creditPayableBalance.length) return;
1595     progressDialog.show(true);
1596
1597     var params = [
1598         this.authtoken, 
1599         this.staff.ws_ou(),
1600         null,
1601         'format.selfcheck.fines',
1602         'print-on-demand',
1603         [this.patron.id()]
1604     ];
1605
1606     var self = this;
1607     fieldmapper.standardRequest(
1608         ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1609         {   
1610             async : true,
1611             params : params,
1612             oncomplete : function(r) {
1613                 progressDialog.hide();
1614                 var resp = openils.Util.readResponse(r);
1615                 var output = resp.template_output();
1616                 if(output) {
1617                     self.printData(output.data(), self.finesCount, callback); 
1618                 } else {
1619                     var error = resp.error_output();
1620                     if(error) {
1621                         throw new Error("Error creating receipt: " + error.data());
1622                     } else {
1623                         throw new Error("No receipt data returned from server");
1624                     }
1625                 }
1626             }
1627         }
1628     );
1629 }
1630
1631
1632
1633
1634 /**
1635  * Logout the patron and return to the login page
1636  */
1637 SelfCheckManager.prototype.logoutPatron = function(print) {
1638     progressDialog.show(true); // prevent patron from clicking logout link twice
1639     if(print && this.checkouts.length) {
1640         if (dojo.byId('oils-selfck-receipt-print').checked) {
1641             this.printSessionReceipt(
1642                 function() {
1643                     location.href = location.href;
1644                 }
1645             );
1646         } else if (dojo.byId('oils-selfck-receipt-email').checked) {
1647             this.emailSessionReceipt(
1648                 function() {
1649                     location.href = location.href;
1650                 }
1651             );
1652         } else {
1653             // user elected to get no receipt
1654             location.href = location.href;
1655         }
1656     } else {
1657         location.href = location.href;
1658     }
1659 }
1660
1661
1662 /**
1663  * Fire up the manager on page load
1664  */
1665 openils.Util.addOnLoad(
1666     function() {
1667         new SelfCheckManager().init();
1668     }
1669 );