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