]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/items_out.js
92184a11fa68fd5cd00bcdaa579faf6f9774ba18
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / circ / patron / items_out.js
1 /**
2  * List of patron items checked out
3  */
4
5 angular.module('egPatronApp')
6
7 .controller('PatronItemsOutCtrl',
8        ['$scope','$q','$routeParams','$timeout','egCore','egUser','patronSvc',
9         '$location','egGridDataProvider','$uibModal','egCirc','egConfirmDialog',
10         'egBilling','$window','egBibDisplay',
11 function($scope , $q , $routeParams , $timeout , egCore , egUser , patronSvc , 
12          $location , egGridDataProvider , $uibModal , egCirc , egConfirmDialog , 
13          egBilling , $window , egBibDisplay) {
14
15     // list of noncatatloged circulations. Define before initTab to 
16     // avoid any possibility of race condition, since they are loaded
17     // during init, but may be referenced before init completes.
18     $scope.noncat_list = [];
19
20     $scope.initTab('items_out', $routeParams.id).then(function() {
21         // sort inline to support paging
22         $scope.noncat_list = patronSvc.noncat_ids.sort();
23     });
24
25     // cache of circ objects for grid display
26     patronSvc.items_out = [];
27
28     // main list of checked out items
29     $scope.main_list = [];
30
31     // list of alt circs (lost, etc.) and/or check-in with fines circs
32     $scope.alt_list = []; 
33
34     // these are fetched during startup (i.e. .configure())
35     // By default, show lost/lo/cr items in the alt list
36     var display_lost = Number(
37         egCore.env.aous['ui.circ.items_out.lost']) || 2;
38     var display_lo = Number(
39         egCore.env.aous['ui.circ.items_out.longoverdue']) || 2;
40     var display_cr = Number(
41         egCore.env.aous['ui.circ.items_out.claimsreturned']) || 2;
42
43     var fetch_checked_in = true;
44     $scope.show_alt_circs = true;
45     if (display_lost & 4 && display_lo & 4 && display_cr & 4) {
46         // all special types are configured to be hidden once
47         // checked in, so there's no need to fetch checked-in circs.
48         fetch_checked_in = false;
49
50         if (display_lost & 1 && display_lo & 1 && display_cr & 1) {                 
51             // additionally, if all types are configured to display    
52             // in the main list while checked out, nothing will         
53             // ever appear in the alternate list, so we can hide          
54             // the alternate list from the UI.  
55             $scope.show_alt_circs = false;
56         }
57     }
58
59     $scope.items_out_display = 'main';
60     $scope.show_main_list = function(refresh_grid) {
61         // don't need a full reset_page() to swap tabs
62         $scope.items_out_display = 'main';
63         patronSvc.items_out = [];
64         // only refresh the grid when navigating from a tab that 
65         // shares the same grid.
66         if (refresh_grid) provider.refresh();
67     }
68
69     $scope.show_alt_list = function(refresh_grid) {
70         // don't need a full reset_page() to swap tabs
71         $scope.items_out_display = 'alt';
72         patronSvc.items_out = [];
73         // only refresh the grid when navigating from a tab that 
74         // shares the same grid.
75         if (refresh_grid) provider.refresh();
76     }
77
78     $scope.show_noncat_list = function() {
79         // don't need a full reset_page() to swap tabs
80         $scope.items_out_display = 'noncat';
81         patronSvc.items_out = [];
82         // Grid refresh is not necessary because switching to the
83         // noncat_list always involves instantiating a new grid.
84     }
85
86     // Reload the user to pick up changes in items out, fines, etc.
87     // Reload circs since the contents of the main vs. alt list may
88     // have changed.
89     function reset_page() {
90         patronSvc.refreshPrimary();
91         patronSvc.items_out = []; 
92         $scope.main_list = [];
93         $scope.alt_list = [];
94         $timeout(provider.refresh);  // allow scope changes to propagate
95     }
96
97     var provider = egGridDataProvider.instance({});
98     $scope.gridDataProvider = provider;
99
100     function fetch_circs(id_list, offset, count) {
101         if (!id_list.length || id_list.length < offset + 1) return $q.when();
102
103         var deferred = $q.defer();
104         var rendered = 0;
105
106         // fetch the lot of circs and stream the results back via notify
107         egCore.pcrud.search('circ', {id : id_list},
108             {   flesh : 4,
109                 flesh_fields : {
110                     circ : ['target_copy', 'workstation', 'checkin_workstation'],
111                     acp : ['call_number', 'holds_count', 'status', 'circ_lib', 'location', 'floating', 'age_protect'],
112                     acn : ['record', 'owning_lib', 'prefix', 'suffix'],
113                     bre : ['wide_display_entry']
114                 },
115                 // avoid fetching the MARC blob by specifying which 
116                 // fields on the bre to select.  More may be needed.
117                 // note that fleshed fields are explicitly selected.
118                 select : { bre : ['id'] },
119                 // TODO: LP#1697954 Fetch all circs on grid render 
120                 // to support client-side sorting.  Migrate to server-side
121                 // sorting to avoid the need for fetching all items.
122                 //limit  : count,
123                 //offset : offset,
124                 // we need an order-by to support paging
125                 order_by : {circ : ['xact_start']} 
126
127         }).then(deferred.resolve, null, function(circ) {
128             circ.circ_lib(egCore.org.get(circ.circ_lib())); // local fleshing
129
130             // Translate bib display field JSON blobs to JS.
131             // Collapse multi/array fields down to comma-separated strings.
132             egBibDisplay.mwdeJSONToJS(
133                 circ.target_copy().call_number().record().wide_display_entry(), true);
134
135             if (circ.target_copy().call_number().id() == -1) {
136                 // dummy-up a record for precat items
137                 circ.target_copy().call_number().record().wide_display_entry({
138                     title : function() {return circ.target_copy().dummy_title()},
139                     author : function() {return circ.target_copy().dummy_author()},
140                     isbn : function() {return circ.target_copy().dummy_isbn()}
141                 })
142             }
143
144             // call open-ils to get overdue notice count and  Last notice date
145             
146            egCore.net.request(
147                'open-ils.actor',
148                'open-ils.actor.user.itemsout.notices',
149                egCore.auth.token(), circ.id(), $scope.patron_id)
150            .then(function(notice){
151                if (notice.numNotices){
152                    circ.action_trigger_event_count = notice.numNotices;
153                    circ.action_trigger_latest_event_date = notice.lastDt;
154                }
155                patronSvc.items_out.push(circ);
156            });
157
158                if (rendered++ >= offset && rendered <= count){ deferred.notify(circ) };
159         });
160
161         return deferred.promise;
162     }
163
164     function fetch_noncat_circs(id_list, offset, count) {
165         if (!id_list.length) return $q.when();
166
167         var deferred = $q.defer();
168         var rendered = 0;
169
170         egCore.pcrud.search('ancc', {id : id_list},
171             {   flesh : 1,
172                 flesh_fields : {ancc : ['item_type','staff']},
173                 // TODO: LP#1697954 Fetch all circs on grid render 
174                 // to support client-side sorting.  Migrate to server-side
175                 // sorting to avoid the need for fetching all items.
176                 //limit  : count,
177                 //offset : offset,
178                 // we need an order-by to support paging
179                 order_by : {circ : ['circ_time']} 
180
181         }).then(deferred.resolve, null, function(noncat_circ) {
182
183             // calculate the virtual due date from the item type duration
184             var seconds = egCore.date.intervalToSeconds(
185                 noncat_circ.item_type().circ_duration());
186             var d = new Date(Date.parse(noncat_circ.circ_time()));
187             d.setSeconds(d.getSeconds() + seconds);
188             noncat_circ.duedate(d.toISOString());
189
190             // local flesh org unit
191             noncat_circ.circ_lib(egCore.org.get(noncat_circ.circ_lib()));
192
193             patronSvc.items_out.push(noncat_circ); // cache it
194
195             // We fetch all noncat circs for client-side sorting, but
196             // only notify the caller for the page of requested circs.  
197             if (rendered++ >= offset && rendered <= count)
198                 deferred.notify(noncat_circ);
199         });
200
201         return deferred.promise;
202     }
203
204
205     // decide which list each circ belongs to
206     function promote_circs(list, display_code, open) {
207         if (open) {                                                    
208             if (1 & display_code) { // bitflag 1 == top list                   
209                 $scope.main_list = $scope.main_list.concat(list);
210             } else {                                                   
211                 $scope.alt_list = $scope.alt_list.concat(list);
212             }                                                          
213         } else {                                                       
214             if (4 & display_code) return;  // bitflag 4 == hide on checkin     
215             $scope.alt_list = $scope.alt_list.concat(list);
216         } 
217     }
218
219     // fetch IDs for circs we care about
220     function get_circ_ids() {
221         $scope.main_list = [];
222         $scope.alt_list = [];
223
224         // we can fetch these in parallel
225         var promise1 = egCore.net.request(
226             'open-ils.actor',
227             'open-ils.actor.user.checked_out.authoritative',
228             egCore.auth.token(), $scope.patron_id
229         ).then(function(outs) {
230             $scope.main_list = outs.overdue.concat(outs.out);
231             promote_circs(outs.lost, display_lost, true);                            
232             promote_circs(outs.long_overdue, display_lo, true);             
233             promote_circs(outs.claims_returned, display_cr, true);
234         });
235
236         // only fetched checked-in-with-bills circs if configured to display
237         var promise2 = !fetch_checked_in ? $q.when() : egCore.net.request(
238             'open-ils.actor',
239             'open-ils.actor.user.checked_in_with_fines.authoritative',
240             egCore.auth.token(), $scope.patron_id
241         ).then(function(outs) {
242             promote_circs(outs.lost, display_lost);
243             promote_circs(outs.long_overdue, display_lo);
244             promote_circs(outs.claims_returned, display_cr);
245         });
246
247         return $q.all([promise1, promise2]);
248     }
249
250     provider.get = function(offset, count) {
251
252         var id_list = $scope[$scope.items_out_display + '_list'];
253
254         // see if we have the requested range cached
255         // Note this items_out list is reset w/ each items-out tab change
256         if (patronSvc.items_out[offset]) {
257             return provider.arrayNotifier(
258                 patronSvc.items_out, offset, count);
259         }
260
261         if ($scope.items_out_display == 'noncat') {
262             // if there are any noncat circ IDs, we already have them
263             return fetch_noncat_circs(id_list, offset, count);
264         }
265
266         // See if we have the circ IDs for this range already loaded.
267         // this would happen navigating to a subsequent page.
268         if (id_list[offset]) {
269             return fetch_circs(id_list, offset, count);
270         }
271
272         // avoid returning the request directly to the caller so the
273         // notify()'s from egCore.net.request don't leak into the 
274         // final set of notifies (i.e. the real responses);
275
276         var deferred = $q.defer();
277         get_circ_ids().then(function() {
278
279             id_list = $scope[$scope.items_out_display + '_list'];
280             $scope.gridDataProvider.grid.totalCount = id_list.length;
281             // relay the notified circs back to the grid through our promise
282             fetch_circs(id_list, offset, count).then(
283                 deferred.resolve, null, deferred.notify);
284         });
285
286         return deferred.promise;
287     }
288
289
290     // true if circ is overdue, false otherwise
291     $scope.circIsOverdue = function(circ) {
292         // circ may not exist yet for rendered row
293         if (!circ) return false;
294
295         var date = new Date();
296         date.setTime(Date.parse(circ.due_date()));
297         return date < new Date();
298     }
299
300     $scope.edit_due_date = function(items) {
301         if (!items.length) return;
302
303         $uibModal.open({
304             templateUrl : './circ/patron/t_edit_due_date_dialog',
305             backdrop: 'static',
306             controller : [
307                         '$scope','$uibModalInstance',
308                 function($scope , $uibModalInstance) {
309
310                     // if there is only one circ, default to the due date
311                     // of that circ.  Otherwise, default to today.
312                     var due_date = items.length == 1 ? 
313                         Date.parse(items[0].due_date()) : new Date();
314
315                     $scope.args = {
316                         num_circs : items.length,
317                         due_date : due_date
318                     }
319
320                     // Fire off the due-date updater for each circ.
321                     // When all is done, close the dialog
322                     $scope.ok = function(args) {
323                         var due = $scope.args.due_date.toISOString();
324                         console.debug("applying due date of " + due);
325
326                         var promises = [];
327                         angular.forEach(items, function(circ) {
328                             promises.push(
329                                 egCore.net.request(
330                                     'open-ils.circ',
331                                     'open-ils.circ.circulation.due_date.update',
332                                     egCore.auth.token(), circ.id(), due
333
334                                 ).then(function(new_circ) {
335                                     // update the grid circ with the canonical 
336                                     // date from the modified circulation.
337                                     circ.due_date(new_circ.due_date());
338                                 })
339                             );
340                         });
341
342                         $q.all(promises).then(function() {
343                             $uibModalInstance.close();
344                             provider.refresh();
345                         });
346                     }
347                     $scope.cancel = function($event) {
348                         $uibModalInstance.dismiss();
349                         $event.preventDefault();
350                     }
351                 }
352             ]
353         });
354     }
355
356     $scope.print_receipt = function(items) {
357         if (items.length == 0) return $q.when();
358         var print_data = {circulations : []};
359         var cusr = patronSvc.current;
360
361         angular.forEach(items, function(circ) {
362             print_data.circulations.push({
363                 circ : egCore.idl.toHash(circ),
364                 copy : egCore.idl.toHash(circ.target_copy()),
365                 call_number : egCore.idl.toHash(circ.target_copy().call_number()),
366                 title : circ.target_copy().call_number().record().wide_display_entry().title(),
367                 author : circ.target_copy().call_number().record().wide_display_entry().author()
368             })
369         });
370
371         print_data.patron = {
372             prefix : cusr.prefix(),
373             first_given_name : cusr.first_given_name(),
374             second_given_name : cusr.second_given_name(),
375             family_name : cusr.family_name(),
376             suffix : cusr.suffix(),
377             pref_prefix : cusr.pref_prefix(),
378             pref_first_given_name : cusr.pref_first_given_name(),
379             pref_second_given_name : cusr.pref_second_given_name(),
380             pref_family_name : cusr.pref_family_name(),
381             pref_suffix : cusr.pref_suffix(),
382             card : { barcode : cusr.card().barcode() },
383             money_summary : patronSvc.patron_stats.fines,
384             expire_date : cusr.expire_date(),
385             alias : cusr.alias(),
386             has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/)),
387             has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
388         };
389
390         return egCore.print.print({
391             context : 'default', 
392             template : 'items_out', 
393             scope : print_data,
394         });
395     }
396
397     function batch_action_with_barcodes(items, action) {
398         if (!items.length) return;
399         var barcodes = items.map(function(circ) 
400             { return circ.target_copy().barcode() });
401         action(barcodes).then(reset_page);
402     }
403     $scope.mark_lost = function(items) {
404         batch_action_with_barcodes(items, egCirc.mark_lost);
405     }
406     $scope.mark_claims_returned = function(items) {
407         batch_action_with_barcodes(items, egCirc.mark_claims_returned_dialog);
408     }
409     $scope.mark_claims_never_checked_out = function(items) {
410         batch_action_with_barcodes(items, egCirc.mark_claims_never_checked_out);
411     }
412
413     $scope.show_recent_circs = function(items) {
414         var focus = items.length == 1;
415         angular.forEach(items, function(item) {
416             var url = egCore.env.basePath +
417                       '/cat/item/' +
418                       item.target_copy().id() +
419                       '/circ_list';
420             $timeout(function() { var x = $window.open(url, '_blank'); if (focus) x.focus() });
421         });
422     }
423
424     $scope.show_triggered_events = function(items) {
425         var focus = items.length == 1;
426         angular.forEach(items, function(item) {
427             var url = egCore.env.basePath +
428                       '/cat/item/' +
429                       item.target_copy().id() +
430                       '/triggered_events';
431             $timeout(function() { var x = $window.open(url, '_blank'); if (focus) x.focus() });
432         });
433     }
434
435     $scope.renew = function(items, msg) {
436         if (!items.length) return;
437         var barcodes = items.map(function(circ) 
438             { return circ.target_copy().barcode() });
439
440         if (!msg) msg = egCore.strings.RENEW_ITEMS;
441
442         return egConfirmDialog.open(msg, barcodes.join(' '), {}).result
443         .then(function() {
444             function do_one() {
445                 var bc = barcodes.pop();
446                 if (!bc) { reset_page(); return }
447                 // finally -> continue even when one fails
448                 egCirc.renew({copy_barcode : bc}).finally(do_one);
449             }
450             do_one();
451         });
452     }
453
454     $scope.renew_all = function() {
455         var circs = patronSvc.items_out.filter(function(circ) {
456             return (
457                 // all others will be rejected at the server
458                 !circ.stop_fines() ||
459                 circ.stop_fines() == 'MAXFINES'
460             );
461         });
462         $scope.renew(circs, egCore.strings.RENEW_ALL_ITEMS);
463     }
464
465     $scope.renew_with_date = function(items) {
466         if (!items.length) return;
467         var barcodes = items.map(function(circ) 
468             { return circ.target_copy().barcode() });
469
470         return $uibModal.open({
471             templateUrl : './circ/patron/t_renew_with_date_dialog',
472             backdrop: 'static',
473             controller : [
474                         '$scope','$uibModalInstance',
475                 function($scope , $uibModalInstance) {
476                     $scope.args = {
477                         barcodes : barcodes,
478                         date : new Date()
479                     }
480                     $scope.cancel = function() {$uibModalInstance.dismiss()}
481
482                     // Fire off the due-date updater for each circ.
483                     // When all is done, close the dialog
484                     $scope.ok = function() {
485                         var due = $scope.args.date.toISOString().replace(/T.*/,'');
486                         console.debug("renewing with due date: " + due);
487
488                         function do_one() {
489                             if (bc = barcodes.pop()) {
490                                 egCirc.renew({copy_barcode : bc, due_date : due})
491                                 .finally(do_one);
492                             } else {
493                                 $uibModalInstance.close(); 
494                                 reset_page();
495                             }
496                         }
497                        do_one(); // kick it off
498                     }
499                 }
500             ]
501         }).result;
502     }
503
504     $scope.checkin = function(items) {
505         if (!items.length) return;
506         var copies = items.map(function(circ) { return circ.target_copy() });
507         var barcodes = copies.map(function(copy) { return copy.barcode() });
508
509         return egConfirmDialog.open(
510             egCore.strings.CHECK_IN_CONFIRM, barcodes.join(' '), {
511
512         }).result.then(function() {
513             var copy;
514             function do_one() {
515                 if (copy = copies.pop()) {
516                     // Checkin expects a barcode, but will pass other
517                     // parameters too.  Passing the copy ID allows
518                     // for the checkin of deleted copies on the server.
519                     egCirc.checkin(
520                         {copy_barcode: copy.barcode(), copy_id: copy.id()})
521                     .finally(do_one);
522                 } else {
523                     reset_page();
524                 }
525             }
526             do_one(); // kick it off
527         });
528     }
529
530     $scope.add_billing = function(items) {
531         if (!items.length) return;
532         var circs = items.concat(); // don't pop from grid array
533         function do_one() {
534             var circ; // don't clobber window.circ!
535             if (circ = circs.pop()) {
536                 egBilling.showBillDialog({
537                     // let the dialog fetch the transaction, since it's
538                     // not sufficiently fleshed here.
539                     xact_id : circ.id(),
540                     patron : patronSvc.current
541                 }).finally(do_one);
542             } else {
543                 reset_page();
544             }
545         }
546         do_one();
547     }
548
549 }]);
550