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