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