]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/circ/selfcheck/selfcheck.js
plugged in checkout/renewal receipt printing and patron logout
[working/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('openils.CGI');
4 dojo.require('openils.Util');
5 dojo.require('openils.User');
6 dojo.require('openils.Event');
7 dojo.require('openils.widget.ProgressDialog');
8
9 dojo.requireLocalization('openils.circ', 'selfcheck');
10 var localeStrings = dojo.i18n.getLocalization('openils.circ', 'selfcheck');
11
12
13 const SET_BARCODE_REGEX = 'opac.barcode_regex';
14 const SET_PATRON_TIMEOUT = 'circ.selfcheck.patron_login_timeout';
15 const SET_AUTO_OVERRIDE_EVENTS = 'circ.selfcheck.auto_override_checkout_events';
16 const SET_PATRON_PASSWORD_REQUIRED = 'circ.selfcheck.patron_password_required';
17 const SET_AUTO_RENEW_INTERVAL = 'circ.checkout_auto_renew_age';
18 const SET_WORKSTATION_REQUIRED = 'circ.selfcheck.workstation_required';
19 const SET_ALERT_POPUP = 'circ.selfcheck.alert.popup';
20 const SET_ALERT_SOUND = 'circ.selfcheck.alert.sound';
21
22 function SelfCheckManager() {
23
24     this.cgi = new openils.CGI();
25     this.staff = null; 
26     this.workstation = null;
27     this.authtoken = null;
28
29     this.patron = null; 
30     this.patronBarcodeRegex = null;
31
32     this.checkouts = [];
33
34     // During renewals, keep track of the ID of the previous circulation. 
35     // Previous circ is used for tracking failed renewals (for receipts).
36     this.prevCirc = null;
37
38     // current item barcode
39     this.itemBarcode = null; 
40
41     // are we currently performing a renewal?
42     this.isRenewal = false; 
43
44     // dict of org unit settings for "here"
45     this.orgSettings = {};
46
47     // Construct a mock checkout for debugging purposes
48     if(this.mockCheckouts = this.cgi.param('mock-circ')) {
49
50         this.mockCheckout = {
51             payload : {
52                 record : new fieldmapper.mvr(),
53                 copy : new fieldmapper.acp(),
54                 circ : new fieldmapper.circ()
55             }
56         };
57
58         this.mockCheckout.payload.record.title('Jazz improvisation for guitar');
59         this.mockCheckout.payload.record.author('Wise, Les');
60         this.mockCheckout.payload.record.isbn('0634033565');
61         this.mockCheckout.payload.copy.barcode('123456789');
62         this.mockCheckout.payload.circ.renewal_remaining(1);
63         this.mockCheckout.payload.circ.parent_circ(1);
64         this.mockCheckout.payload.circ.due_date('2012-12-21');
65     }
66 }
67
68
69
70 /**
71  * Fetch the org-unit settings, initialize the display, etc.
72  */
73 SelfCheckManager.prototype.init = function() {
74
75     this.staff = openils.User.user;
76     this.workstation = openils.User.workstation;
77     this.authtoken = openils.User.authtoken;
78     this.loadOrgSettings();
79
80     // workstation is required but none provided
81     if(this.orgSettings[SET_WORKSTATION_REQUIRED] && !this.workstation) {
82         alert(dojo.string.substitute(localeStrings.WORKSTATION_REQUIRED));
83         return;
84     }
85     
86     var self = this;
87     // connect onclick handlers to the various navigation links
88     var linkHandlers = {
89         'oils-selfck-hold-details-link' : function() { self.drawHoldsPage(); },
90         'oils-selfck-nav-holds' : function() { self.drawHoldsPage(); },
91         'oils-selfck-pay-fines-link' : function() { self.drawFinesPage(); },
92         'oils-selfck-nav-fines' : function() { self.drawFinesPage(); },
93         'oils-selfck-nav-home' : function() { self.drawCircPage(); },
94         'oils-selfck-nav-logout' : function() { self.logoutPatron(); }
95     }
96
97     for(var id in linkHandlers) 
98         dojo.connect(dojo.byId(id), 'onclick', linkHandlers[id]);
99
100
101     if(this.cgi.param('patron')) {
102         
103         // Patron barcode via cgi param.  Mainly used for debugging and
104         // only works if password is not required by policy
105         this.loginPatron(this.cgi.param('patron'));
106
107     } else {
108         this.drawLoginPage();
109     }
110
111     /**
112      * To test printing, pass a URL param of 'testprint'.  The value for the param
113      * should be a JSON string like so:  [{circ:<circ_id>}, ...]
114      */
115     var testPrint = this.cgi.param('testprint');
116     if(testPrint) {
117         this.checkouts = JSON2js(testPrint);
118         this.printReceipt();
119         this.checkouts = [];
120     }
121 }
122
123 /**
124  * Loads the org unit settings
125  */
126 SelfCheckManager.prototype.loadOrgSettings = function() {
127
128     var settings = fieldmapper.aou.fetchOrgSettingBatch(
129         this.staff.ws_ou(), [
130             SET_BARCODE_REGEX,
131             SET_PATRON_TIMEOUT,
132             SET_ALERT_POPUP,
133             SET_ALERT_SOUND,
134             SET_AUTO_OVERRIDE_EVENTS,
135             SET_PATRON_PASSWORD_REQUIRED,
136             SET_AUTO_RENEW_INTERVAL,
137             SET_WORKSTATION_REQUIRED
138         ]
139     );
140
141     for(k in settings) {
142         if(settings[k])
143             this.orgSettings[k] = settings[k].value;
144     }
145
146     if(settings[SET_BARCODE_REGEX]) 
147         this.patronBarcodeRegex = new RegExp(settings[SET_BARCODE_REGEX].value);
148 }
149
150 SelfCheckManager.prototype.drawLoginPage = function() {
151     var self = this;
152
153     var bcHandler = function(barcode) {
154         // handle patron barcode entry
155
156         if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
157             
158             // password is required.  wire up the scan box to read it
159             self.updateScanBox({
160                 msg : 'Please enter your password', // TODO i18n 
161                 handler : function(pw) { self.loginPatron(barcode, pw); },
162                 password : true
163             });
164
165         } else {
166             // password is not required, go ahead and login
167             self.loginPatron(barcode);
168         }
169     };
170
171     this.updateScanBox({
172         msg : 'Please log in with your library barcode.', // TODO
173         handler : bcHandler
174     });
175 }
176
177 /**
178  * Login the patron.  
179  */
180 SelfCheckManager.prototype.loginPatron = function(barcode, passwd) {
181
182     if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
183         
184         if(!passwd) {
185             // would only happen in dev/debug mode when using the patron= param
186             alert('password required by org setting.  remove patron= from URL'); 
187             return;
188         }
189
190         // patron password is required.  Verify it.
191
192         var res = fieldmapper.standardRequest(
193             ['open-ils.actor', 'open-ils.actor.verify_user_password'],
194             {params : [this.authtoken, barcode, null, hex_md5(passwd)]}
195         );
196
197         if(res == 0) {
198             // user-not-found results in login failure
199             this.handleAlert(
200                 dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]),
201                 false, 'login-failure'
202             );
203             this.drawLoginPage();
204             return;
205         }
206     } 
207
208     // retrieve the fleshed user by barcode
209     this.patron = fieldmapper.standardRequest(
210         ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve_by_barcode'],
211         {params : [this.authtoken, barcode]}
212     );
213
214     var evt = openils.Event.parse(this.patron);
215     if(evt) {
216         this.handleAlert(
217             dojo.string.substitute(localeStrings.LOGIN_FAILED, [barcode]),
218             false, 'login-failure'
219         );
220         this.drawLoginPage();
221
222     } else {
223
224         this.handleAlert('', false, 'login-success');
225         dojo.byId('oils-selfck-user-banner').innerHTML = 'Welcome, ' + this.patron.usrname(); // TODO i18n
226         this.drawCircPage();
227     }
228 }
229
230
231 SelfCheckManager.prototype.handleAlert = function(message, shouldPopup, sound) {
232
233     console.log("Handling alert " + message);
234
235     dojo.byId('oils-selfck-status-div').innerHTML = message;
236
237     if(shouldPopup && this.orgSettings[SET_ALERT_POPUP]) 
238         alert(message);
239
240     if(sound && this.orgSettings[SET_ALERT_SOUND])
241         openils.Util.playAudioUrl(SelfCheckManager.audioConfig[sound]);
242 }
243
244
245 /**
246  * Manages the main input box
247  * @param msg The context message to display with the box
248  * @param clearOnly Don't update the context message, just clear the value and re-focus
249  * @param handler Optional "on-enter" handler.  
250  */
251 SelfCheckManager.prototype.updateScanBox = function(args) {
252     args = args || {};
253
254     if(args.select) {
255         selfckScanBox.domNode.select();
256     } else {
257         selfckScanBox.attr('value', '');
258     }
259
260     if(args.password) {
261         selfckScanBox.domNode.setAttribute('type', 'password');
262     } else {
263         selfckScanBox.domNode.setAttribute('type', '');
264     }
265
266     if(args.value)
267         selfckScanBox.attr('value', args.value);
268
269     if(args.msg) 
270         dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
271
272     if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
273         dojo.disconnect(selfckScanBox._lastHandler);
274     }
275
276     if(args.handler) {
277         selfckScanBox._lastHandler = dojo.connect(
278             selfckScanBox, 
279             'onKeyDown', 
280             function(e) {
281                 if(e.keyCode != dojo.keys.ENTER) 
282                     return;
283                 args.handler(selfckScanBox.attr('value'));
284             }
285         );
286     }
287
288     selfckScanBox.focus();
289 }
290
291 /**
292  *  Sets up the checkout/renewal interface
293  */
294 SelfCheckManager.prototype.drawCircPage = function() {
295
296     var self = this;
297     this.updateScanBox({
298         msg : 'Please enter an item barcode', // TODO i18n
299         handler : function(barcode) { self.checkout(barcode); }
300     });
301
302     openils.Util.hide('oils-selfck-payment-page');
303     openils.Util.hide('oils-selfck-holds-page');
304     openils.Util.show('oils-selfck-circ-page');
305
306     this.circTbody = dojo.byId('oils-selfck-circ-tbody');
307     if(!this.circTemplate)
308         this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
309
310     // items out, holds, and fines summaries
311
312     // fines summary
313     fieldmapper.standardRequest(
314         ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
315         {   async : true,
316             params : [this.authtoken, this.patron.id()],
317             oncomplete : function(r) {
318                 var summary = openils.Util.readResponse(r);
319                 dojo.byId('oils-selfck-fines-total').innerHTML = 
320                     dojo.string.substitute(
321                         localeStrings.TOTAL_FINES_ACCOUNT, 
322                         [summary.balance_owed()]
323                     );
324             }
325         }
326     );
327
328     // holds summary
329     this.updateHoldsSummary();
330
331     // items out summary
332     this.updateCircSummary();
333
334     // render mock checkouts for debugging?
335     if(this.mockCheckouts) {
336         for(var i in [1,2,3]) 
337             this.displayCheckout(this.mockCheckout, 'checkout');
338     }
339 }
340
341 SelfCheckManager.prototype.updateHoldsSummary = function() {
342
343     if(!this.holdsSummary) {
344         var summary = fieldmapper.standardRequest(
345             ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
346             {params : [this.authtoken, this.patron.id()]}
347         );
348
349         this.holdsSummary = {};
350         this.holdsSummary.ready = Number(summary['4']);
351         this.holdsSummary.total = 0;
352
353         for(var i in summary) 
354             this.holdsSummary.total += Number(summary[i]);
355     }
356
357     dojo.byId('oils-selfck-holds-total').innerHTML = 
358         dojo.string.substitute(
359             localeStrings.TOTAL_HOLDS, 
360             [this.holdsSummary.total]
361         );
362
363     dojo.byId('oils-selfck-holds-ready').innerHTML = 
364         dojo.string.substitute(
365             localeStrings.HOLDS_READY_FOR_PICKUP, 
366             [this.holdsSummary.ready]
367         );
368 }
369
370
371 SelfCheckManager.prototype.updateCircSummary = function(increment) {
372
373     if(!this.circSummary) {
374
375         var summary = fieldmapper.standardRequest(
376             ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
377             {params : [this.authtoken, this.patron.id()]}
378         );
379
380         this.circSummary = {
381             total : Number(summary.out) + Number(summary.overdue),
382             overdue : Number(summary.overdue),
383             session : 0
384         };
385     }
386
387     if(increment) {
388         // local checkout occurred.  Add to the total and the session.
389         this.circSummary.total += 1;
390         this.circSummary.session += 1;
391     }
392
393     dojo.byId('oils-selfck-circ-account-total').innerHTML = 
394         dojo.string.substitute(
395             localeStrings.TOTAL_ITEMS_ACCOUNT, 
396             [this.circSummary.total]
397         );
398
399     dojo.byId('oils-selfck-circ-session-total').innerHTML = 
400         dojo.string.substitute(
401             localeStrings.TOTAL_ITEMS_SESSION, 
402             [this.circSummary.session]
403         );
404 }
405
406
407 SelfCheckManager.prototype.drawHoldsPage = function() {
408
409     // TODO add option to hid scanBox
410     // this.updateScanBox(...)
411
412     openils.Util.hide('oils-selfck-circ-page');
413     openils.Util.hide('oils-selfck-payment-page');
414     openils.Util.show('oils-selfck-holds-page');
415
416     this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
417     if(!this.holdTemplate)
418         this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
419     while(this.holdTbody.childNodes[0])
420         this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
421
422     progressDialog.show(true);
423
424     var self = this;
425     fieldmapper.standardRequest( // fetch the hold IDs
426
427         ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
428         {   async : true,
429             params : [this.authtoken, this.patron.id()],
430
431             oncomplete : function(r) { 
432                 var ids = openils.Util.readResponse(r);
433                 if(!ids || ids.length == 0) {
434                     progressDialog.hide();
435                     return;
436                 }
437
438                 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
439                     ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve.atomic'],
440                     {   async : true,
441                         params : [self.authtoken, ids],
442
443                         oncomplete : function(rr) {
444                             self.drawHolds(openils.Util.readResponse(rr));
445                         }
446                     }
447                 );
448             }
449         }
450     );
451 }
452
453 /**
454  * Fetch and add a single hold to the list of holds
455  */
456 SelfCheckManager.prototype.drawHolds = function(holds) {
457
458     holds = holds.sort(
459         // sort available holds to the top of the list
460         // followed by queue position order
461         function(a, b) {
462             if(a.status == 4) return -1;
463             if(a.queue_position < b.queue_position) return -1;
464             return 1;
465         }
466     );
467
468     progressDialog.hide();
469
470     for(var i in holds) {
471
472         var data = holds[i];
473         var row = this.holdTemplate.cloneNode(true);
474
475         if(data.mvr.isbn()) {
476             this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + data.mvr.isbn());
477         }
478
479         this.byName(row, 'title').innerHTML = data.mvr.title();
480         this.byName(row, 'author').innerHTML = data.mvr.author();
481
482         if(data.status == 4) {
483
484             // hold is ready for pickup
485             this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
486
487         } else {
488
489             // hold is still pending
490             this.byName(row, 'status').innerHTML = 
491                 dojo.string.substitute(
492                     localeStrings.HOLD_STATUS_WAITING,
493                     [data.queue_position, data.potential_copies]
494                 );
495         }
496
497         this.holdTbody.appendChild(row);
498     }
499 }
500
501
502
503 /**
504  * Check out a single item.  If the item is already checked 
505  * out to the patron, redirect to renew()
506  */
507 SelfCheckManager.prototype.checkout = function(barcode, override) {
508
509     this.prevCirc = null;
510
511     if(!barcode) {
512         this.updateScanbox(null, true);
513         return;
514     }
515
516     if(this.mockCheckouts) {
517         // if we're in mock-checkout mode, just insert another
518         // fake circ into the table and get out of here.
519         this.displayCheckout(this.mockCheckout, 'checkout');
520         return;
521     }
522
523     // TODO see if it's a patron barcode
524     // TODO see if this item has already been checked out in this session
525
526     var method = 'open-ils.circ.checkout.full';
527     if(override) method += '.override';
528
529     console.log("Checkout out item " + barcode + " with method " + method);
530
531     var result = fieldmapper.standardRequest(
532         ['open-ils.circ', 'open-ils.circ.checkout.full'],
533         {params: [
534             this.authtoken, {
535                 patron_id : this.patron.id(),
536                 copy_barcode : barcode
537             }
538         ]}
539     );
540
541     console.log(js2JSON(result));
542
543     var stat = this.handleXactResult('checkout', barcode, result);
544
545     if(stat.override) {
546         this.checkout(barcode, true);
547     } else if(stat.renew) {
548         this.renew(barcode);
549     }
550 }
551
552
553 SelfCheckManager.prototype.handleXactResult = function(action, item, result) {
554
555     var displayText = '';
556
557     // If true, the display message is important enough to pop up.  Whether or not
558     // an alert() actually occurs, depends on org unit settings
559     var popup = false;  
560
561     var sound = '';
562
563     // TODO handle lost/missing/etc checkin+checkout override steps
564     
565     var payload = result.payload || {};
566         
567     if(result.textcode == 'NO_SESSION') {
568
569         return this.logoutStaff();
570
571     } else if(result.textcode == 'SUCCESS') {
572
573         if(action == 'checkout') {
574
575             displayText = dojo.string.substitute(localeStrings.CHECKOUT_SUCCESS, [item]);
576             this.displayCheckout(result, 'checkout');
577
578             if(payload.holds_fulfilled && payload.holds_fulfilled.length) {
579                 // A hold was fulfilled, update the hold numbers in the circ summary
580                 console.log("fulfilled hold " + payload.holds_fulfilled + " during checkout");
581                 this.holdsSummary = null;
582                 this.updateHoldsSummary();
583             }
584
585             this.updateCircSummary(true);
586
587         } else if(action == 'renew') {
588
589             displayText = dojo.string.substitute(localeStrings.RENEW_SUCCESS, [item]);
590             this.displayCheckout(result, 'renew');
591         }
592
593         this.checkouts.push({circ : result.payload.circ.id()});
594         sound = 'checkout-success';
595         this.updateScanBox();
596
597     } else if(result.textcode == 'OPEN_CIRCULATION_EXISTS' && action == 'checkout') {
598
599         // Server says the item is already checked out.  If it's checked out to the
600         // current user, we may need to renew it.  
601
602         if(payload.old_circ) { 
603
604             /*
605             old_circ refers to the previous checkout IFF it's for the same user. 
606             If no auto-renew interval is not defined, assume we should renew it
607             If an auto-renew interval is defined and the payload comes back with
608             auto_renew set to true, do the renewal.  Otherwise, let the patron know
609             the item is already checked out to them.  */
610
611             if( !this.orgSettings[SET_AUTO_RENEW_INTERVAL] ||
612                 (this.orgSettings[SET_AUTO_RENEW_INTERVAL] && payload.auto_renew) ) {
613                 this.prevCirc = payload.old_circ.id();
614                 return { renew : true };
615             }
616
617             popup = true;
618             sound = 'checkout-failure';
619             displayText = dojo.string.substitute(localeStrings.ALREADY_OUT, [item]);
620
621         } else {
622             
623             // item is checked out to some other user
624             popup = true;
625             sound = 'checkout-failure';
626             displayText = dojo.string.substitute(localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
627         }
628
629         this.updateScanBox({select:true});
630
631     } else {
632
633         var overrideEvents = this.orgSettings[SET_AUTO_OVERRIDE_EVENTS];
634     
635         if(overrideEvents && overrideEvents.length) {
636             
637             // see if the events we received are all in the list of
638             // events to override
639     
640             if(!result.length) result = [result];
641     
642             var override = true;
643             for(var i = 0; i < result.length; i++) {
644                 var match = overrideEvents.filter(
645                     function(e) { return (e == result[i].textcode); })[0];
646                 if(!match) {
647                     override = false;
648                     break;
649                 }
650             }
651
652             if(override) 
653                 return { override : true };
654         }
655     
656         this.updateScanBox({select : true});
657         popup = true;
658         sound = 'checkout-failure';
659
660         if(action == 'renew')
661             this.checkouts.push({circ : this.prevCirc, renewal_failure : true});
662
663         if(result.length) 
664             result = result[0];
665
666         switch(result.textcode) {
667
668             // TODO custom handler for blocking penalties
669
670             case 'MAX_RENEWALS_REACHED' :
671                 displayText = dojo.string.substitute(
672                     localeStrings.MAX_RENEWALS, [item]);
673                 break;
674
675             case 'ITEM_NOT_CATALOGED' :
676                 displayText = dojo.string.substitute(
677                     localeStrings.ITEM_NOT_CATALOGED, [item]);
678                 break;
679
680             case 'OPEN_CIRCULATION_EXISTS' :
681                 displayText = dojo.string.substitute(
682                     localeStrings.OPEN_CIRCULATION_EXISTS, [item]);
683                 break;
684
685             default:
686                 console.error('Unhandled event ' + result.textcode);
687
688                 if(action == 'checkout' || action == 'renew') {
689                     displayText = dojo.string.substitute(
690                         localeStrings.GENERIC_CIRC_FAILURE, [item]);
691                 } else {
692                     displayText = dojo.string.substitute(
693                         localeStrings.UNKNOWN_ERROR, [result.textcode]);
694                 }
695         }
696     }
697
698     this.handleAlert(displayText, popup, sound);
699     return {};
700 }
701
702
703 /**
704  * Renew an item
705  */
706 SelfCheckManager.prototype.renew = function(barcode, override) {
707
708     var method = 'open-ils.circ.renew';
709     if(override) method += '.override';
710
711     console.log("Renewing item " + barcode + " with method " + method);
712
713     var result = fieldmapper.standardRequest(
714         ['open-ils.circ', method],
715         {params: [
716             this.authtoken, {
717                 patron_id : this.patron.id(),
718                 copy_barcode : barcode
719             }
720         ]}
721     );
722
723     console.log(js2JSON(result));
724
725     var stat = this.handleXactResult('renew', barcode, result);
726
727     if(stat.override)
728         this.renew(barcode, true);
729 }
730
731 /**
732  * Display the result of a checkout or renewal in the items out table
733  */
734 SelfCheckManager.prototype.displayCheckout = function(evt, type) {
735
736     var copy = evt.payload.copy;
737     var record = evt.payload.record;
738     var circ = evt.payload.circ;
739     var row = this.circTemplate.cloneNode(true);
740
741     if(record.isbn()) {
742         this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + record.isbn());
743     }
744
745     this.byName(row, 'barcode').innerHTML = copy.barcode();
746     this.byName(row, 'title').innerHTML = record.title();
747     this.byName(row, 'author').innerHTML = record.author();
748     this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
749     openils.Util.show(this.byName(row, type));
750
751     var date = dojo.date.stamp.fromISOString(circ.due_date());
752     this.byName(row, 'due_date').innerHTML = 
753         dojo.date.locale.format(date, {selector : 'date'});
754
755     // put new circs at the top of the list
756     this.circTbody.insertBefore(row, this.circTbody.getElementsByTagName('tr')[0]);
757 }
758
759
760 SelfCheckManager.prototype.byName = function(node, name) {
761     return dojo.query('[name=' + name+']', node)[0];
762 }
763
764
765 SelfCheckManager.prototype.drawFinesPage = function() {
766     openils.Util.hide('oils-selfck-circ-page');
767     openils.Util.hide('oils-selfck-holds-page');
768     openils.Util.show('oils-selfck-payment-page');
769 }
770
771
772 SelfCheckManager.prototype.initPrinter = function() {
773     try { // Mozilla only
774                 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
775         netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
776         netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
777         netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
778         var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
779         if (pref)
780             pref.setBoolPref('print.always_print_silent', true);
781     } catch(E) {
782         console.log("Unable to initialize auto-printing"); 
783     }
784 }
785
786 /**
787  * Print a receipt
788  */
789 SelfCheckManager.prototype.printReceipt = function(callback) {
790
791     var circIds = [];
792     var circCtx = []; // circ context data.  in this case, renewal_failure info
793
794     // collect the circs and failure info
795     dojo.forEach(
796         this.checkouts, 
797         function(blob) {
798             circIds.push(blob.circ);
799             circCtx.push({renewal_failure:blob.renewal_failure});
800         }
801     );
802
803     var params = [
804         this.authtoken, 
805         this.staff.ws_ou(),
806         null,
807         'format.selfcheck.checkout',
808         'print-on-demand',
809         circIds,
810         circCtx
811     ];
812
813     var self = this;
814     fieldmapper.standardRequest(
815         ['open-ils.circ', 'open-ils.circ.fire_circ_trigger_events'],
816         {   
817             async : true,
818             params : params,
819             oncomplete : function(r) {
820                 var resp = openils.Util.readResponse(r);
821                 var output = resp.template_output();
822                 if(output) {
823                     self.printData(output.data(), self.checkouts.length, callback); 
824                 } else {
825                     var error = resp.error_output();
826                     if(error) {
827                         throw new Error("Error creating receipt: " + error.data());
828                     } else {
829                         throw new Error("No receipt data returned from server");
830                     }
831                 }
832             }
833         }
834     );
835 }
836
837 SelfCheckManager.prototype.printData = function(data, numItems, callback) {
838
839     var win = window.open('', '', 'resizable,width=700,height=500,scrollbars=1'); 
840     win.document.body.innerHTML = data;
841     win.print();
842
843     /*
844      * There is no way to know when the browser is done printing.
845      * Make a best guess at when to close the print window by basing
846      * the setTimeout wait on the number of items to be printed plus
847      * a small buffer
848      */
849     var sleepTime = 1000;
850     if(numItems > 0) 
851         sleepTime += (numItems / 2) * 1000;
852
853     setTimeout(
854         function() { 
855             win.close(); // close the print window
856             if(callback)
857                 callback(); // fire optional post-print callback
858         },
859         sleepTime 
860     );
861 }
862
863
864
865 /**
866  * Logout the patron and return to the login page
867  */
868 SelfCheckManager.prototype.logoutPatron = function() {
869     if(this.checkouts.length) {
870         this.printReceipt(
871             function() {
872                 location.href = location.href;
873             }
874         );
875     } else {
876         location.href = location.href;
877     }
878 }
879
880
881 /**
882  * Fire up the manager on page load
883  */
884 openils.Util.addOnLoad(
885     function() {
886         new SelfCheckManager().init();
887     }
888 );