CSS hook for check-in failures with selfcheck
[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)
377         openils.Util.addCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
378     else
379         openils.Util.removeCSSClass( dojo.byId('oils-selfck-status-div'), 'checkout_failure' );
380
381     if(shouldPopup && this.orgSettings[SET_ALERT_POPUP]) 
382         alert(message);
383
384     if(sound && this.orgSettings[SET_ALERT_SOUND])
385         openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
386 }
387
388
389 /**
390  * Manages the main input box
391  * @param msg The context message to display with the box
392  * @param clearOnly Don't update the context message, just clear the value and re-focus
393  * @param handler Optional "on-enter" handler.  
394  */
395 SelfCheckManager.prototype.updateScanBox = function(args) {
396     args = args || {};
397
398     if(args.select) {
399         selfckScanBox.domNode.select();
400     } else {
401         selfckScanBox.attr('value', '');
402     }
403
404     if(args.password) {
405         selfckScanBox.domNode.setAttribute('type', 'password');
406     } else {
407         selfckScanBox.domNode.setAttribute('type', '');
408     }
409
410     if(args.value)
411         selfckScanBox.attr('value', args.value);
412
413     if(args.msg) 
414         dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
415
416     if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
417         dojo.disconnect(selfckScanBox._lastHandler);
418     }
419
420     if(args.handler) {
421         selfckScanBox._lastHandler = dojo.connect(
422             selfckScanBox, 
423             'onKeyDown', 
424             function(e) {
425                 if(e.keyCode != dojo.keys.ENTER) 
426                     return;
427                 args.handler(selfckScanBox.attr('value'));
428             }
429         );
430     }
431
432     selfckScanBox.focus();
433 }
434
435 /**
436  *  Sets up the checkout/renewal interface
437  */
438 SelfCheckManager.prototype.drawCircPage = function() {
439
440     openils.Util.show('oils-selfck-circ-tbody', 'table-row-group');
441     this.goToTab('checkout');
442
443     while(this.itemsOutTbody.childNodes[0])
444         this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
445
446     var self = this;
447     this.updateScanBox({
448         msg : 'Please enter an item barcode', // TODO i18n
449         handler : function(barcode) { self.checkout(barcode); }
450     });
451
452     if(!this.circTemplate)
453         this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
454
455     // fines summary
456     this.updateFinesSummary();
457
458     // holds summary
459     this.updateHoldsSummary();
460
461     // items out summary
462     this.updateCircSummary();
463
464     // render mock checkouts for debugging?
465     if(this.mockCheckouts) {
466         for(var i in [1,2,3]) 
467             this.displayCheckout(this.mockCheckout, 'checkout');
468     }
469 }
470
471
472 SelfCheckManager.prototype.updateFinesSummary = function() {
473     var self = this; 
474
475     // fines summary
476     fieldmapper.standardRequest(
477         ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
478         {   async : true,
479             params : [this.authtoken, this.patron.id()],
480             oncomplete : function(r) {
481
482                 var summary = openils.Util.readResponse(r);
483
484                 dojo.byId('oils-selfck-fines-total').innerHTML = 
485                     dojo.string.substitute(
486                         localeStrings.TOTAL_FINES_ACCOUNT, 
487                         [summary.balance_owed()]
488                     );
489
490                 self.creditPayableBalance = summary.balance_owed();
491             }
492         }
493     );
494 }
495
496
497 SelfCheckManager.prototype.drawItemsOutPage = function() {
498     openils.Util.hide('oils-selfck-circ-tbody');
499
500     this.goToTab('items_out');
501
502     while(this.itemsOutTbody.childNodes[0])
503         this.itemsOutTbody.removeChild(this.itemsOutTbody.childNodes[0]);
504
505     progressDialog.show(true);
506     
507     var self = this;
508     fieldmapper.standardRequest(
509         ['open-ils.circ', 'open-ils.circ.actor.user.checked_out.atomic'],
510         {
511             async : true,
512             params : [this.authtoken, this.patron.id()],
513             oncomplete : function(r) {
514
515                 var resp = openils.Util.readResponse(r);
516
517                 var circs = resp.sort(
518                     function(a, b) {
519                         if(a.circ.due_date() > b.circ.due_date())
520                             return -1;
521                         return 1;
522                     }
523                 );
524
525                 progressDialog.hide();
526
527                 self.itemsOut = [];
528                 dojo.forEach(circs,
529                     function(circ) {
530                         self.itemsOut.push(circ.circ.id());
531                         self.displayCheckout(
532                             {payload : circ}, 
533                             (circ.circ.parent_circ()) ? 'renew' : 'checkout',
534                             true
535                         );
536                     }
537                 );
538             }
539         }
540     );
541 }
542
543
544 SelfCheckManager.prototype.goToTab = function(name) {
545     this.tabName = name;
546
547     openils.Util.hide('oils-selfck-fines-page');
548     openils.Util.hide('oils-selfck-payment-page');
549     openils.Util.hide('oils-selfck-holds-page');
550     openils.Util.hide('oils-selfck-circ-page');
551     openils.Util.hide('oils-selfck-pay-fines-link');
552     
553     switch(name) {
554         case 'checkout':
555             openils.Util.show('oils-selfck-circ-page');
556             break;
557         case 'items_out':
558             openils.Util.show('oils-selfck-circ-page');
559             break;
560         case 'holds':
561             openils.Util.show('oils-selfck-holds-page');
562             break;
563         case 'fines':
564             openils.Util.show('oils-selfck-fines-page');
565             break;
566         case 'payment':
567             openils.Util.show('oils-selfck-payment-page');
568             break;
569     }
570 }
571
572
573 SelfCheckManager.prototype.printList = function() {
574     switch(this.tabName) {
575         case 'checkout':
576             this.printSessionReceipt();
577             break;
578         case 'items_out':
579             this.printItemsOutReceipt();
580             break;
581         case 'holds':
582             this.printHoldsReceipt();
583             break;
584         case 'fines':
585             this.printFinesReceipt();
586             break;
587     }
588 }
589
590 SelfCheckManager.prototype.updateHoldsSummary = function() {
591
592     if(!this.holdsSummary) {
593         var summary = fieldmapper.standardRequest(
594             ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
595             {params : [this.authtoken, this.patron.id()]}
596         );
597
598         this.holdsSummary = {};
599         this.holdsSummary.ready = Number(summary['4']);
600         this.holdsSummary.total = 0;
601
602         for(var i in summary) 
603             this.holdsSummary.total += Number(summary[i]);
604     }
605
606     dojo.byId('oils-selfck-holds-total').innerHTML = 
607         dojo.string.substitute(
608             localeStrings.TOTAL_HOLDS, 
609             [this.holdsSummary.total]
610         );
611
612     dojo.byId('oils-selfck-holds-ready').innerHTML = 
613         dojo.string.substitute(
614             localeStrings.HOLDS_READY_FOR_PICKUP, 
615             [this.holdsSummary.ready]
616         );
617 }
618
619
620 SelfCheckManager.prototype.updateCircSummary = function(increment) {
621
622     if(!this.circSummary) {
623
624         var summary = fieldmapper.standardRequest(
625             ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
626             {params : [this.authtoken, this.patron.id()]}
627         );
628
629         this.circSummary = {
630             total : Number(summary.out) + Number(summary.overdue),
631             overdue : Number(summary.overdue),
632             session : 0
633         };
634     }
635
636     if(increment) {
637         // local checkout occurred.  Add to the total and the session.
638         this.circSummary.total += 1;
639         this.circSummary.session += 1;
640     }
641
642     dojo.byId('oils-selfck-circ-account-total').innerHTML = 
643         dojo.string.substitute(
644             localeStrings.TOTAL_ITEMS_ACCOUNT, 
645             [this.circSummary.total]
646         );
647
648     dojo.byId('oils-selfck-circ-session-total').innerHTML = 
649         dojo.string.substitute(
650             localeStrings.TOTAL_ITEMS_SESSION, 
651             [this.circSummary.session]
652         );
653 }
654
655
656 SelfCheckManager.prototype.drawHoldsPage = function() {
657
658     // TODO add option to hid scanBox
659     // this.updateScanBox(...)
660
661     this.goToTab('holds');
662
663     this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
664     if(!this.holdTemplate)
665         this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
666     while(this.holdTbody.childNodes[0])
667         this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
668
669     progressDialog.show(true);
670
671     var self = this;
672     fieldmapper.standardRequest( // fetch the hold IDs
673
674         ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
675         {   async : true,
676             params : [this.authtoken, this.patron.id()],
677
678             oncomplete : function(r) { 
679                 var ids = openils.Util.readResponse(r);
680                 if(!ids || ids.length == 0) {
681                     progressDialog.hide();
682                     return;
683                 }
684
685                 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
686                     ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve'],
687                     {   async : true,
688                         params : [self.authtoken, ids],
689                         onresponse : function(rr) {
690                             progressDialog.hide();
691                             self.insertHold(openils.Util.readResponse(rr));
692                         }
693                     }
694                 );
695             }
696         }
697     );
698 }
699
700 SelfCheckManager.prototype.insertHold = function(data) {
701     var row = this.holdTemplate.cloneNode(true);
702
703     if(data.mvr.isbn()) {
704         this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + data.mvr.isbn());
705     }
706
707     this.byName(row, 'title').innerHTML = data.mvr.title();
708     this.byName(row, 'author').innerHTML = data.mvr.author();
709
710     if(data.status == 4) {
711
712         // hold is ready for pickup
713         this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
714
715     } else {
716
717         // hold is still pending
718         this.byName(row, 'status').innerHTML = 
719             dojo.string.substitute(
720                 localeStrings.HOLD_STATUS_WAITING,
721                 [data.queue_position, data.potential_copies]
722             );
723     }
724
725     // find the correct place the table to slot in the hold based on queue position
726
727     var position = (data.status == 4) ? 0 : data.queue_position;
728     row.setAttribute('position', position);
729
730     for(var i = 0; i < this.holdTbody.childNodes.length; i++) {
731         var node = this.holdTbody.childNodes[i];
732         if(Number(node.getAttribute('position')) >= position) {
733             this.holdTbody.insertBefore(row, node);
734             return;
735         }
736     }
737
738     this.holdTbody.appendChild(row);
739 }
740
741
742 SelfCheckManager.prototype.drawFinesPage = function() {
743
744     // TODO add option to hid scanBox
745     // this.updateScanBox(...)
746
747     this.goToTab('fines');
748     progressDialog.show(true);
749
750     if(this.creditPayableBalance > 0 && this.orgSettings[SET_CC_PAYMENT_ALLOWED]) {
751         openils.Util.show('oils-selfck-pay-fines-link', 'inline');
752     }
753
754     this.finesTbody = dojo.byId('oils-selfck-fines-tbody');
755     if(!this.finesTemplate)
756         this.finesTemplate = this.finesTbody.removeChild(dojo.byId('oils-selfck-fines-row'));
757     while(this.finesTbody.childNodes[0])
758         this.finesTbody.removeChild(this.finesTbody.childNodes[0]);
759
760     // when user clicks on a selector checkbox, update the total owed
761     var updateSelected = function() {
762         var total = 0;
763         dojo.forEach(
764             dojo.query('[name=selector]', this.finesTbody),
765             function(input) {
766                 if(input.checked)
767                     total += Number(input.getAttribute('balance_owed'));
768             }
769         );
770
771         total = total.toFixed(2);
772         dojo.byId('oils-selfck-selected-total').innerHTML = 
773             dojo.string.substitute(localeStrings.TOTAL_FINES_SELECTED, [total]);
774     }
775
776     // wire up the batch on/off selector
777     var sel = dojo.byId('oils-selfck-fines-selector');
778     sel.onchange = function() {
779         dojo.forEach(
780             dojo.query('[name=selector]', this.finesTbody),
781             function(input) {
782                 input.checked = sel.checked;
783             }
784         );
785     };
786
787     var self = this;
788     var handler = function(dataList) {
789
790         self.finesCount = dataList.length;
791         self.finesData = dataList;
792
793         for(var i in dataList) {
794
795             var data = dataList[i];
796             var row = self.finesTemplate.cloneNode(true);
797             var type = data.transaction.xact_type();
798
799             if(type == 'circulation') {
800                 self.byName(row, 'type').innerHTML = type;
801                 self.byName(row, 'details').innerHTML = data.record.title();
802
803             } else if(type == 'grocery') {
804                 self.byName(row, 'type').innerHTML = 'Miscellaneous'; // Go ahead and head off any confusion around "grocery".  TODO i18n
805                 self.byName(row, 'details').innerHTML = data.transaction.last_billing_type();
806             }
807
808             self.byName(row, 'total_owed').innerHTML = data.transaction.total_owed();
809             self.byName(row, 'total_paid').innerHTML = data.transaction.total_paid();
810             self.byName(row, 'balance').innerHTML = data.transaction.balance_owed();
811
812             // row selector
813             var selector = self.byName(row, 'selector')
814             selector.onchange = updateSelected;
815             selector.setAttribute('xact', data.transaction.id());
816             selector.setAttribute('balance_owed', data.transaction.balance_owed());
817             selector.checked = true;
818
819             self.finesTbody.appendChild(row);
820         }
821
822         updateSelected();
823     }
824
825
826     fieldmapper.standardRequest( 
827         ['open-ils.actor', 'open-ils.actor.user.transactions.have_balance.fleshed'],
828         {   async : true,
829             params : [this.authtoken, this.patron.id()],
830             oncomplete : function(r) { 
831                 progressDialog.hide();
832                 handler(openils.Util.readResponse(r));
833             }
834         }
835     );
836 }
837
838 SelfCheckManager.prototype.checkin = function(barcode, abortTransit) {
839
840     var resp = fieldmapper.standardRequest(
841         ['open-ils.circ', 'open-ils.circ.transit.abort'],
842         {params : [this.authtoken, {barcode : barcode}]}
843     );
844
845     // resp == 1 on success
846     if(openils.Event.parse(resp))
847         return false;
848
849     var resp = fieldmapper.standardRequest(
850         ['open-ils.circ', 'open-ils.circ.checkin.override'],
851         {params : [
852             this.authtoken, {
853                 patron_id : this.patron.id(),
854                 copy_barcode : barcode,
855                 noop : true
856             }
857         ]}
858     );
859
860     if(!resp.length) resp = [resp];
861     for(var i = 0; i < resp.length; i++) {
862         var tc = openils.Event.parse(resp[i]).textcode;
863         if(tc == 'SUCCESS' || tc == 'NO_CHANGE') {
864             continue;
865         } else {
866             return false;
867         }
868     }
869
870     return true;
871 }
872
873 /**
874  * Check out a single item.  If the item is already checked 
875  * out to the patron, redirect to renew()
876  */
877 SelfCheckManager.prototype.checkout = function(barcode, override) {
878
879     this.prevCirc = null;
880
881     if(!barcode) {
882         this.updateScanbox(null, true);
883         return;
884     }
885
886     if(this.mockCheckouts) {
887         // if we're in mock-checkout mode, just insert another
888         // fake circ into the table and get out of here.
889         this.displayCheckout(this.mockCheckout, 'checkout');
890         return;
891     }
892
893     // TODO see if it's a patron barcode
894     // TODO see if this item has already been checked out in this session
895
896     var method = 'open-ils.circ.checkout.full';
897     if(override) method += '.override';
898
899     console.log("Checkout out item " + barcode + " with method " + method);
900
901     var result = fieldmapper.standardRequest(
902         ['open-ils.circ', method],
903         {params: [
904             this.authtoken, {
905                 patron_id : this.patron.id(),
906                 copy_barcode : barcode
907             }
908         ]}
909     );
910
911     var stat = this.handleXactResult('checkout', barcode, result);
912
913     if(stat.override) {
914         this.checkout(barcode, true);
915     } else if(stat.doOver) {
916         this.checkout(barcode);
917     } else if(stat.renew) {
918         this.renew(barcode);
919     }
920 }
921
922 SelfCheckManager.prototype.failPartMessage = function(result) {
923     if (result.payload && result.payload.fail_part) {
924         var stringKey = "FAIL_PART_" +
925             result.payload.fail_part.replace(/\./g, "_");
926         return localeStrings[stringKey];
927     } else {
928         return null;
929     }
930 }
931
932 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
933
934     var displayText = '';
935
936     // If true, the display message is important enough to pop up.  Whether or not
937     // an alert() actually occurs, depends on org unit settings
938     var popup = false;  
939     var sound = ''; // sound file reference
940     var payload = result.payload || {};
941     var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
942     var blockStatuses = this.orgSettings[SET_BLOCK_CHECKOUT_ON_COPY_STATUS];
943         
944     if(result.textcode == 'NO_SESSION') {
945
946         return this.logoutStaff();
947
948     } else if(result.textcode == 'SUCCESS') {
949
950         if(action == 'checkout') {
951
952             displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
953             this.displayCheckout(result, 'checkout');
954
955             if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
956                 // A hold was fulfilled, update the hold numbers in the circ summary
957                 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
958                 this.holdsSummary = null;
959                 this.updateHoldsSummary();
960             }
961
962             this.updateCircSummary(true);
963
964         } else if(action == 'renew') {
965
966             displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
967             this.displayCheckout(result, 'renew');
968         }
969
970         this.checkouts.push({circ : result.payload.circ.id()});
971         sound = 'checkout-success';
972         this.updateScanBox();
973
974     } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
975
976         // Server says the item is already checked out.  If it's checked out to the
977         // current user, we may need to renew it.  
978
979         if(payload.old_circ) { 
980
981             /*
982             old_circ refers to the previous checkout IFF it's for the same user. 
983             If no auto-renew interval is not defined, assume we should renew it
984             If an auto-renew interval is defined and the payload comes back with
985             auto_renew set to true, do the renewal.  Otherwise, let the patron know
986             the item is already checked out to them.  */
987
988             if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
989                 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
990                 this.prevCirc = payload.old_circ.id();
991                 return { renew : true };
992             }
993
994             popup = true;
995             sound = 'checkout-failure';
996             displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
997
998         } else {
999
1000             if( // copy is marked lost.  if configured to do so, check it in and try again.
1001                 result.payload.copy && 
1002                 result.payload.copy.status() == /* LOST */ 3 &&
1003                 overrideEvents && overrideEvents.length &&
1004                 overrideEvents.indexOf('COPY_STATUS_LOST') != -1) {
1005
1006                     if(this.checkin(item)) {
1007                         return { doOver : true };
1008                     }
1009             }
1010
1011             
1012             // item is checked out to some other user
1013             popup = true;
1014             sound = 'checkout-failure';
1015             displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1016         }
1017
1018         this.updateScanBox({select:true});
1019
1020     } else {
1021
1022     
1023         if(overrideEvents && overrideEvents.length) {
1024             
1025             // see if the events we received are all in the list of
1026             // events to override
1027     
1028             if(!result.length) result = [result];
1029     
1030             var override = true;
1031             for(var i = 0; i < result.length; i++) {
1032
1033                 var match = overrideEvents.filter(function(e) { return (e == result[i].textcode); })[0];
1034
1035                 if(!match) {
1036                     override = false;
1037                     break;
1038                 }
1039
1040                 if(result[i].textcode == 'COPY_NOT_AVAILABLE' && blockStatuses && blockStatuses.length) {
1041
1042                     var stat = result[i].payload.status(); // copy status
1043                     if(typeof stat == 'object') stat = stat.id();
1044
1045                     var match2 = blockStatuses.filter(function(e) { return (e == stat); })[0];
1046
1047                     if(match2) { // copy is in a blocked status
1048                         override = false;
1049                         break;
1050                     }
1051                 }
1052
1053                 if(result[i].textcode == 'COPY_IN_TRANSIT') {
1054                     // to override a transit, we have to abort the transit and check it in first
1055                     if(this.checkin(item, true)) {
1056                         return { doOver : true };
1057                     } else {
1058                         override = false;
1059                     }
1060                 }
1061             }
1062
1063             if(override) 
1064                 return { override : true };
1065         }
1066     
1067         this.updateScanBox({select : true});
1068         popup = true;
1069         sound = 'checkout-failure';
1070
1071         if(action == 'renew')
1072             this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
1073
1074         if(result.length) 
1075             result = result[0];
1076
1077         switch(result.textcode) {
1078
1079             // TODO custom handler for blocking penalties
1080
1081             case 'MAX_RENEWALS_REACHED' :
1082                 displayText = dojo.string.substitute(
1083                     localeStrings.MAX_RENEWALS, [item]);
1084                 break;
1085
1086             case 'ITEM_NOT_CATALOGED' :
1087                 displayText = dojo.string.substitute(
1088                     localeStrings.ITEM_NOT_CATALOGED, [item]);
1089                 break;
1090
1091             case 'OPEN_CIRCULATION_EXISTS' :
1092                 displayText = dojo.string.substitute(
1093                     localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
1094
1095                 break;
1096
1097             default:
1098                 console.error('Unhandled event ' + result.textcode);
1099
1100                 if (!(displayText = this.failPartMessage(result))) {
1101                     if (action == 'checkout' || action == 'renew') {
1102                         displayText = dojo.string.substitute(
1103                             localeStrings.GENERIC_CIRC_FAILURE, [item]);
1104                     } else {
1105                         displayText = dojo.string.substitute(
1106                             localeStrings.UNKNOWN_ERROR, [result.textcode]);
1107                     }
1108                 }
1109         }
1110     }
1111
1112     this.handleAlert(displayText, popup, sound);
1113     return {};
1114 }
1115
1116
1117 /**
1118  * Renew an item
1119  */
1120 SelfCheckManager.prototype.renew = function(barcode, override) {
1121
1122     var method = 'open-ils.circ.renew';
1123     if(override) method += '.override';
1124
1125     console.log("Renewing item " + barcode + " with method " + method);
1126
1127     var result = fieldmapper.standardRequest(
1128         ['open-ils.circ', method],
1129         {params: [
1130             this.authtoken, {
1131                 patron_id : this.patron.id(),
1132                 copy_barcode : barcode
1133             }
1134         ]}
1135     );
1136
1137     console.log(js2JSON(result));
1138
1139     var stat = this.handleXactResult('renew', barcode, result);
1140
1141     if(stat.override)
1142         this.renew(barcode, true);
1143 }
1144
1145 /**
1146  * Display the result of a checkout or renewal in the items out table
1147  */
1148 SelfCheckManager.prototype.displayCheckout = function(evt, type, itemsOut) {
1149
1150     var copy = evt.payload.copy;
1151     var record = evt.payload.record;
1152     var circ = evt.payload.circ;
1153     var row = this.circTemplate.cloneNode(true);
1154
1155     if(record.isbn()) {
1156         this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + record.isbn());
1157     }
1158
1159     this.byName(row, 'barcode').innerHTML = copy.barcode();
1160     this.byName(row, 'title').innerHTML = record.title();
1161     this.byName(row, 'author').innerHTML = record.author();
1162     this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
1163     openils.Util.show(this.byName(row, type));
1164
1165     var date = dojo.date.stamp.fromISOString(circ.due_date());
1166     this.byName(row, 'due_date').innerHTML = 
1167         dojo.date.locale.format(date, {selector : 'date'});
1168
1169     // put new circs at the top of the list
1170     var tbody = this.circTbody;
1171     if(itemsOut) tbody = this.itemsOutTbody;
1172     tbody.insertBefore(row, tbody.getElementsByTagName('tr')[0]);
1173 }
1174
1175
1176 SelfCheckManager.prototype.byName = function(node, name) {
1177     return dojo.query('[name=' + name+']', node)[0];
1178 }
1179
1180
1181 SelfCheckManager.prototype.initPrinter = function() {
1182     try { // Mozilla only
1183                 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
1184         netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
1185         netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
1186         netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
1187         var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
1188         if (pref)
1189             pref.setBoolPref('print.always_print_silent', true);
1190     } catch(E) {
1191         console.log("Unable to initialize auto-printing"); 
1192     }
1193 }
1194
1195 /**
1196  * Print a receipt for this session's checkouts
1197  */
1198 SelfCheckManager.prototype.printSessionReceipt = function(callback) {
1199
1200     var circIds = [];
1201     var circCtx = []; // circ context data.  in this case, renewal_failure info
1202
1203     // collect the circs and failure info
1204     dojo.forEach(
1205         this.checkouts, 
1206         function(blob) {
1207             circIds.push(blob.circ);
1208             circCtx.push({renewal_failure:blob.renewal_failure});
1209         }
1210     );
1211
1212     var params = [
1213         this.authtoken, 
1214         this.staff.ws_ou(),
1215         null,
1216         'format.selfcheck.checkout',
1217         'print-on-demand',
1218         circIds,
1219         circCtx
1220     ];
1221
1222     var self = this;
1223     fieldmapper.standardRequest(
1224         ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1225         {   
1226             async : true,
1227             params : params,
1228             oncomplete : function(r) {
1229                 var resp = openils.Util.readResponse(r);
1230                 var output = resp.template_output();
1231                 if(output) {
1232                     self.printData(output.data(), self.checkouts.length, callback); 
1233                 } else {
1234                     var error = resp.error_output();
1235                     if(error) {
1236                         throw new Error("Error creating receipt: " + error.data());
1237                     } else {
1238                         throw new Error("No receipt data returned from server");
1239                     }
1240                 }
1241             }
1242         }
1243     );
1244 }
1245
1246 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
1247
1248     var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1'); 
1249     win.document.body.innerHTML = data;
1250     win.print();
1251
1252     /*
1253      * There is no way to know when the browser is done printing.
1254      * Make a best guess at when to close the print window by basing
1255      * the setTimeout wait on the number of items to be printed plus
1256      * a small buffer
1257      */
1258     var sleepTime = 1000;
1259     if(numItems > 0) 
1260         sleepTime += (numItems / 2) * 1000;
1261
1262     setTimeout(
1263         function() { 
1264             win.close(); // close the print window
1265             if(callback)
1266                 callback(); // fire optional post-print callback
1267         },
1268         sleepTime 
1269     );
1270 }
1271
1272
1273 /**
1274  * Print a receipt for this user's items out
1275  */
1276 SelfCheckManager.prototype.printItemsOutReceipt = function(callback) {
1277
1278     if(!this.itemsOut.length) return;
1279
1280     progressDialog.show(true);
1281
1282     var params = [
1283         this.authtoken, 
1284         this.staff.ws_ou(),
1285         null,
1286         'format.selfcheck.items_out',
1287         'print-on-demand',
1288         this.itemsOut
1289     ];
1290
1291     var self = this;
1292     fieldmapper.standardRequest(
1293         ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
1294         {   
1295             async : true,
1296             params : params,
1297             oncomplete : function(r) {
1298                 progressDialog.hide();
1299                 var resp = openils.Util.readResponse(r);
1300                 var output = resp.template_output();
1301                 if(output) {
1302                     self.printData(output.data(), self.itemsOut.length, callback); 
1303                 } else {
1304                     var error = resp.error_output();
1305                     if(error) {
1306                         throw new Error("Error creating receipt: " + error.data());
1307                     } else {
1308                         throw new Error("No receipt data returned from server");
1309                     }
1310                 }
1311             }
1312         }
1313     );
1314 }
1315
1316 /**
1317  * Print a receipt for this user's items out
1318  */
1319 SelfCheckManager.prototype.printHoldsReceipt = function(callback) {
1320
1321     if(!this.holds.length) return;
1322
1323     progressDialog.show(true);
1324
1325     var holdIds = [];
1326     var holdData = [];
1327
1328     dojo.forEach(this.holds,
1329         function(data) {
1330             holdIds.push(data.hold.id());
1331             if(data.status == 4) {
1332                 holdData.push({ready : true});
1333             } else {
1334                 holdData.push({
1335                     queue_position : data.queue_position, 
1336                     potential_copies : data.potential_copies
1337                 });
1338             }
1339         }
1340     );
1341
1342     var params = [
1343         this.authtoken, 
1344         this.staff.ws_ou(),
1345         null,
1346         'format.selfcheck.holds',
1347         'print-on-demand',
1348         holdIds,
1349         holdData
1350     ];
1351
1352     var self = this;
1353     fieldmapper.standardRequest(
1354         ['open-ils.circ', 'open-ils.circ.fire_hold_trigger_events'],
1355         {   
1356             async : true,
1357             params : params,
1358             oncomplete : function(r) {
1359                 progressDialog.hide();
1360                 var resp = openils.Util.readResponse(r);
1361                 var output = resp.template_output();
1362                 if(output) {
1363                     self.printData(output.data(), self.holds.length, callback); 
1364                 } else {
1365                     var error = resp.error_output();
1366                     if(error) {
1367                         throw new Error("Error creating receipt: " + error.data());
1368                     } else {
1369                         throw new Error("No receipt data returned from server");
1370                     }
1371                 }
1372             }
1373         }
1374     );
1375 }
1376
1377
1378 SelfCheckManager.prototype.printPaymentReceipt = function(response, callback) {
1379     
1380     var self = this;
1381     progressDialog.show(true);
1382
1383     fieldmapper.standardRequest(
1384         ['open-ils.circ', 'open-ils.circ.money.payment_receipt.print'],
1385         {
1386             async : true,
1387             params : [this.authtoken, response.payments],
1388             oncomplete : function(r) {
1389                 var resp = openils.Util.readResponse(r);
1390                 var output = resp.template_output();
1391                 progressDialog.hide();
1392                 if(output) {
1393                     self.printData(output.data(), 1, callback); 
1394                 } else {
1395                     var error = resp.error_output();
1396                     if(error) {
1397                         throw new Error("Error creating receipt: " + error.data());
1398                     } else {
1399                         throw new Error("No receipt data returned from server");
1400                     }
1401                 }
1402             }
1403         }
1404     );
1405 }
1406
1407 /**
1408  * Print a receipt for this user's items out
1409  */
1410 SelfCheckManager.prototype.printFinesReceipt = function(callback) {
1411
1412     progressDialog.show(true);
1413
1414     var params = [
1415         this.authtoken, 
1416         this.staff.ws_ou(),
1417         null,
1418         'format.selfcheck.fines',
1419         'print-on-demand',
1420         [this.patron.id()]
1421     ];
1422
1423     var self = this;
1424     fieldmapper.standardRequest(
1425         ['open-ils.circ', 'open-ils.circ.fire_user_trigger_events'],
1426         {   
1427             async : true,
1428             params : params,
1429             oncomplete : function(r) {
1430                 progressDialog.hide();
1431                 var resp = openils.Util.readResponse(r);
1432                 var output = resp.template_output();
1433                 if(output) {
1434                     self.printData(output.data(), self.finesCount, callback); 
1435                 } else {
1436                     var error = resp.error_output();
1437                     if(error) {
1438                         throw new Error("Error creating receipt: " + error.data());
1439                     } else {
1440                         throw new Error("No receipt data returned from server");
1441                     }
1442                 }
1443             }
1444         }
1445     );
1446 }
1447
1448
1449
1450
1451 /**
1452  * Logout the patron and return to the login page
1453  */
1454 SelfCheckManager.prototype.logoutPatron = function(print) {
1455     progressDialog.show(true); // prevent patron from clicking logout link twice
1456     if(print && this.checkouts.length) {
1457         this.printSessionReceipt(
1458             function() {
1459                 location.href = location.href;
1460             }
1461         );
1462     } else {
1463         location.href = location.href;
1464     }
1465 }
1466
1467
1468 /**
1469  * Fire up the manager on page load
1470  */
1471 openils.Util.addOnLoad(
1472     function() {
1473         new SelfCheckManager().init();
1474     }
1475 );