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