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