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