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