]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/circ/selfcheck/selfcheck.js
66551c9c78827a7ce4380ded3f72bcfc27054a26
[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
19 function SelfCheckManager() {
20
21     this.cgi = new openils.CGI();
22     this.staff = null; 
23     this.workstation = null;
24     this.authtoken = null;
25
26     this.patron = null; 
27     this.patronBarcodeRegex = null;
28
29     // current item barcode
30     this.itemBarcode = null; 
31
32     // are we currently performing a renewal?
33     this.isRenewal = false; 
34
35     // is a transaction pending?
36     this.pendingXact = false; 
37
38     // dict of org unit settings for "here"
39     this.orgSettings = {};
40
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     
76     var self = this;
77     // connect onclick handlers to the various navigation links
78     var linkHandlers = {
79         'oils-selfck-hold-details-link' : function() { self.drawHoldsPage(); },
80         'oils-selfck-nav-holds' : function() { self.drawHoldsPage(); },
81         'oils-selfck-pay-fines-link' : function() { self.drawFinesPage(); },
82         'oils-selfck-nav-fines' : function() { self.drawFinesPage(); },
83         'oils-selfck-nav-home' : function() { self.drawCircPage(); },
84         'oils-selfck-nav-logout' : function() { self.logoutPatron(); }
85     }
86
87     for(var id in linkHandlers) 
88         dojo.connect(dojo.byId(id), 'onclick', linkHandlers[id]);
89
90
91     if(this.cgi.param('patron')) {
92         
93         // Patron barcode via cgi param.  Mainly used for debugging and
94         // only works if password is not required by policy
95         this.loginPatron(this.cgi.param('patron'));
96
97     } else {
98         this.drawLoginPage();
99     }
100 }
101
102 /**
103  * Loads the org unit settings
104  */
105 SelfCheckManager.prototype.loadOrgSettings = function() {
106
107     var settings = fieldmapper.aou.fetchOrgSettingBatch(
108         this.staff.ws_ou(), [
109             SET_BARCODE_REGEX,
110             SET_PATRON_TIMEOUT,
111             SET_ALERT_ON_CHECKOUT_EVENT,
112             SET_AUTO_OVERRIDE_EVENTS,
113         ]
114     );
115
116     for(k in settings) {
117         if(settings[k])
118             this.orgSettings[k] = settings[k].value;
119     }
120
121     if(settings[SET_BARCODE_REGEX]) 
122         this.patronBarcodeRegex = new RegExp(settings[SET_BARCODE_REGEX].value);
123 }
124
125 SelfCheckManager.prototype.drawLoginPage = function() {
126     var self = this;
127
128     var bcHandler = function(barcode) {
129         // handle patron barcode entry
130
131         if(self.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
132             
133             // password is required.  wire up the scan box to read it
134             self.updateScanBox({
135                 msg : 'Please enter your password', // TODO i18n 
136                 handler : function(pw) { self.loginPatron(barcode, pw); }
137             });
138
139         } else {
140             // password is not required, go ahead and login
141             self.loginPatron(barcode);
142         }
143     };
144
145     this.updateScanBox({
146         msg : 'Please log in with your library barcode.', // TODO
147         handler : bcHandler
148     });
149 }
150
151 /**
152  * Login the patron.  
153  */
154 SelfCheckManager.prototype.loginPatron = function(barcode, passwd) {
155
156     if(this.orgSettings[SET_PATRON_PASSWORD_REQUIRED]) {
157
158         // patron password is required.  Verify it.
159
160         var res = fieldmapper.standardRequest(
161             ['open-ils.actor', 'open-ils.actor.verify_user_password'],
162             {params : [this.authtoken, barcode, null, hex_md5(passwd)]}
163         );
164
165         if(res == 0) {
166             return alert('login failed'); // TODO
167         }
168     } 
169
170     // retrieve the fleshed user by barcode
171     this.patron = fieldmapper.standardRequest(
172         ['open-ils.actor', 'open-ils.actor.user.fleshed.retrieve_by_barcode'],
173         {params : [this.authtoken, barcode]}
174     );
175
176     var evt = openils.Event.parse(this.patron);
177     if(evt) {
178
179         // User login failed, why?
180         
181         switch(evt.textcode) {
182
183             case 'ACTOR_USER_NOT_FOUND':
184                 return alert('user not found'); // TODO
185
186             case 'NO_SESSION':
187                 return alert('staff login timed out'); // TODO
188
189             default:
190                 return alert('unexpected patron login error occured: ' + evt.textcode); // TODO
191         }
192     }
193
194     // patron login succeeded
195     dojo.byId('oils-selfck-user-banner').innerHTML = 'Welcome, ' + this.patron.usrname(); // TODO i18n
196     this.drawCircPage();
197 }
198
199
200 /**
201  * Manages the main input box
202  * @param msg The context message to display with the box
203  * @param clearOnly Don't update the context message, just clear the value and re-focus
204  * @param handler Optional "on-enter" handler.  
205  */
206 SelfCheckManager.prototype.updateScanBox = function(args) {
207
208     if(args.select) {
209         selfckScanBox.domNode.select();
210     } else {
211         selfckScanBox.attr('value', '');
212     }
213
214     if(args.value)
215         selfckScanBox.attr('value', args.value);
216
217     if(args.msg) 
218         dojo.byId('oils-selfck-scan-text').innerHTML = args.msg;
219
220     if(selfckScanBox._lastHandler && (args.handler || args.clearHandler)) {
221         dojo.disconnect(selfckScanBox._lastHandler);
222     }
223
224     if(args.handler) {
225         selfckScanBox._lastHandler = dojo.connect(
226             selfckScanBox, 
227             'onKeyDown', 
228             function(e) {
229                 if(e.keyCode != dojo.keys.ENTER) 
230                     return;
231                 args.handler(selfckScanBox.attr('value'));
232             }
233         );
234     }
235
236     selfckScanBox.focus();
237 }
238
239 /**
240  *  Sets up the checkout/renewal interface
241  */
242 SelfCheckManager.prototype.drawCircPage = function() {
243
244     var self = this;
245     this.updateScanBox({
246         msg : 'Please enter an item barcode', // TODO i18n
247         handler : function(barcode) { self.checkout(barcode); }
248     });
249
250     openils.Util.hide('oils-selfck-payment-page');
251     openils.Util.hide('oils-selfck-holds-page');
252     openils.Util.show('oils-selfck-circ-page');
253
254     this.circTbody = dojo.byId('oils-selfck-circ-tbody');
255     if(!this.circTemplate)
256         this.circTemplate = this.circTbody.removeChild(dojo.byId('oils-selfck-circ-row'));
257
258     // items out, holds, and fines summaries
259
260     // fines summary
261     fieldmapper.standardRequest(
262         ['open-ils.actor', 'open-ils.actor.user.fines.summary'],
263         {   async : true,
264             params : [this.authtoken, this.patron.id()],
265             oncomplete : function(r) {
266                 var summary = openils.Util.readResponse(r);
267                 dojo.byId('oils-selfck-fines-total').innerHTML = 
268                     dojo.string.substitute(
269                         localeStrings.TOTAL_FINES_ACCOUNT, 
270                         [summary.balance_owed()]
271                     );
272             }
273         }
274     );
275
276     // holds summary
277     this.updateHoldsSummary();
278
279     // items out summary
280     this.updateCircSummary();
281
282     // render mock checkouts for debugging?
283     if(this.mockCheckouts) {
284         for(var i in [1,2,3]) 
285             this.displayCheckout(this.mockCheckout);
286     }
287 }
288
289 SelfCheckManager.prototype.updateHoldsSummary = function(decrement) {
290
291     if(!this.holdsSummary) {
292         var summary = fieldmapper.standardRequest(
293             ['open-ils.circ', 'open-ils.circ.holds.user_summary'],
294             {params : [this.authtoken, this.patron.id()]}
295         );
296
297         this.holdsSummary = {};
298         this.holdsSummary.ready = Number(summary['4']);
299         this.holdsSummary.total = 0;
300
301         for(var i in summary) 
302             this.holdsSummary.total += Number(summary[i]);
303     }
304
305     if(this.decrement) 
306         this.holdsSummary.ready -= 1;
307
308     dojo.byId('oils-selfck-holds-total').innerHTML = 
309         dojo.string.substitute(
310             localeStrings.TOTAL_HOLDS, 
311             [this.holdsSummary.total]
312         );
313
314     dojo.byId('oils-selfck-holds-ready').innerHTML = 
315         dojo.string.substitute(
316             localeStrings.HOLDS_READY_FOR_PICKUP, 
317             [this.holdsSummary.ready]
318         );
319 }
320
321
322 SelfCheckManager.prototype.updateCircSummary = function(increment) {
323
324     if(!this.circSummary) {
325
326         var summary = fieldmapper.standardRequest(
327             ['open-ils.actor', 'open-ils.actor.user.checked_out.count'],
328             {params : [this.authtoken, this.patron.id()]}
329         );
330
331         this.circSummary = {
332             total : Number(summary.out) + Number(summary.overdue),
333             overdue : Number(summary.overdue),
334             session : 0
335         };
336     }
337
338     if(increment) {
339         // local checkout occurred.  Add to the total and the session.
340         this.circSummary.total += 1;
341         this.circSummary.session += 1;
342     }
343
344     dojo.byId('oils-selfck-circ-account-total').innerHTML = 
345         dojo.string.substitute(
346             localeStrings.TOTAL_ITEMS_ACCOUNT, 
347             [this.circSummary.total]
348         );
349
350     dojo.byId('oils-selfck-circ-session-total').innerHTML = 
351         dojo.string.substitute(
352             localeStrings.TOTAL_ITEMS_SESSION, 
353             [this.circSummary.session]
354         );
355 }
356
357
358 SelfCheckManager.prototype.drawHoldsPage = function() {
359
360     // TODO add option to hid scanBox
361     // this.updateScanBox(...)
362
363     openils.Util.hide('oils-selfck-circ-page');
364     openils.Util.hide('oils-selfck-payment-page');
365     openils.Util.show('oils-selfck-holds-page');
366
367     this.holdTbody = dojo.byId('oils-selfck-hold-tbody');
368     if(!this.holdTemplate)
369         this.holdTemplate = this.holdTbody.removeChild(dojo.byId('oils-selfck-hold-row'));
370     while(this.holdTbody.childNodes[0])
371         this.holdTbody.removeChild(this.holdTbody.childNodes[0]);
372
373     progressDialog.show(true);
374
375     var self = this;
376     fieldmapper.standardRequest( // fetch the hold IDs
377
378         ['open-ils.circ', 'open-ils.circ.holds.id_list.retrieve'],
379         {   async : true,
380             params : [this.authtoken, this.patron.id()],
381
382             oncomplete : function(r) { 
383                 var ids = openils.Util.readResponse(r);
384                 if(!ids || ids.length == 0) {
385                     progressDialog.hide();
386                     return;
387                 }
388
389                 fieldmapper.standardRequest( // fetch the hold objects with fleshed details
390                     ['open-ils.circ', 'open-ils.circ.hold.details.batch.retrieve.atomic'],
391                     {   async : true,
392                         params : [self.authtoken, ids],
393
394                         oncomplete : function(rr) {
395                             self.drawHolds(openils.Util.readResponse(rr));
396                         }
397                     }
398                 );
399             }
400         }
401     );
402 }
403
404 /**
405  * Fetch and add a single hold to the list of holds
406  */
407 SelfCheckManager.prototype.drawHolds = function(holds) {
408
409     holds = holds.sort(
410         // sort available holds to the top of the list
411         // followed by queue position order
412         function(a, b) {
413             if(a.status == 4) return -1;
414             if(a.queue_position < b.queue_position) return -1;
415             return 1;
416         }
417     );
418
419     progressDialog.hide();
420
421     for(var i in holds) {
422
423         var data = holds[i];
424         var row = this.holdTemplate.cloneNode(true);
425
426         if(data.mvr.isbn()) {
427             this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + data.mvr.isbn());
428         }
429
430         this.byName(row, 'title').innerHTML = data.mvr.title();
431         this.byName(row, 'author').innerHTML = data.mvr.author();
432
433         if(data.status == 4) {
434
435             // hold is ready for pickup
436             this.byName(row, 'status').innerHTML = localeStrings.HOLD_STATUS_READY;
437
438         } else {
439
440             // hold is still pending
441             this.byName(row, 'status').innerHTML = 
442                 dojo.string.substitute(
443                     localeStrings.HOLD_STATUS_WAITING,
444                     [data.queue_position, data.potential_copies]
445                 );
446         }
447
448         this.holdTbody.appendChild(row);
449     }
450 }
451
452
453
454 /**
455  * Check out a single item.  If the item is already checked 
456  * out to the patron, redirect to renew()
457  */
458 SelfCheckManager.prototype.checkout = function(barcode, override) {
459
460     if(!barcode) {
461         this.updateScanbox(null, true);
462         return;
463     }
464
465     if(this.mockCheckouts) {
466         // if we're in mock-checkout mode, just insert another
467         // fake circ into the table and get out of here.
468         this.displayCheckout(this.mockCheckout);
469         return;
470     }
471
472     // TODO see if it's a patron barcode
473     // TODO see if this item has already been checked out in this session
474
475     var method = 'open-ils.circ.checkout.full';
476     if(override) method += '.override';
477
478     var result = fieldmapper.standardRequest(
479         ['open-ils.circ', 'open-ils.circ.checkout.full'],
480         {params: [
481             this.authtoken, {
482                 patron_id : this.patron.id(),
483                 copy_barcode : barcode
484             }
485         ]}
486     );
487
488
489     if(dojo.isArray(result)) {
490         // list of results.  See if we can override all of them.
491
492     } else {
493         var evt = openils.Event.parse(result);
494
495         switch(evt.textcode) {
496             // standard result events
497             
498             case 'SUCCESS':
499                 this.displayCheckout(evt);
500                 break;
501
502             case 'OPEN_CIRCULATION_EXISTS':
503                 // TODO renewal
504                 break;
505
506             case 'NO_SESSION':
507                 // TODO logout staff?
508                 break;
509
510             default:
511                 dojo.byId('oils-selfck-status-div').innerHTML = evt.textcode;
512                 this.updateScanBox({select:true});
513         }
514     }
515
516     console.log("Circ resulted in " + js2JSON(result));
517 }
518
519 /**
520  * Renew an item
521  */
522 SelfCheckManager.prototype.renew = function() {
523 }
524
525 /**
526  * Display the result of a checkout or renewal in the items out table
527  */
528 SelfCheckManager.prototype.displayCheckout = function(evt) {
529
530     var copy = evt.payload.copy;
531     var record = evt.payload.record;
532     var circ = evt.payload.circ;
533     var row = this.circTemplate.cloneNode(true);
534
535     if(record.isbn()) {
536         this.byName(row, 'jacket').setAttribute('src', '/opac/extras/ac/jacket/small/' + record.isbn());
537     }
538
539     this.byName(row, 'barcode').innerHTML = copy.barcode();
540     this.byName(row, 'title').innerHTML = record.title();
541     this.byName(row, 'author').innerHTML = record.author();
542     this.byName(row, 'remaining').innerHTML = circ.renewal_remaining();
543
544     var date = dojo.date.stamp.fromISOString(circ.due_date());
545     this.byName(row, 'due_date').innerHTML = 
546         dojo.date.locale.format(date, {selector : 'date'});
547
548     // put new circs at the top of the list
549     this.circTbody.insertBefore(row, this.circTbody.getElementsByTagName('tr')[0]);
550 }
551
552
553 SelfCheckManager.prototype.byName = function(node, name) {
554     return dojo.query('[name=' + name+']', node)[0];
555 }
556
557
558 SelfCheckManager.prototype.drawFinesPage = function() {
559
560     openils.Util.hide('oils-selfck-circ-page');
561     openils.Util.hide('oils-selfck-holds-page');
562     openils.Util.show('oils-selfck-payment-page');
563
564 }
565
566 /**
567  * Print a receipt
568  */
569 SelfCheckManager.prototype.printReceipt = function() {
570 }
571
572
573 /**
574  * Logout the patron and return to the login page
575  */
576 SelfCheckManager.prototype.logoutPatron = function() {
577 }
578
579
580 /**
581  * Fire up the manager on page load
582  */
583 openils.Util.addOnLoad(
584     function() {
585         new SelfCheckManager().init();
586     }
587 );