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