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