]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/item/app.js
LP#1402797 add a Retrieve All These Patrons button
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / cat / item / app.js
1 /**
2  * Item Display
3  */
4
5 angular.module('egItemStatus', 
6     ['ngRoute', 'ui.bootstrap', 'egCoreMod', 'egUiMod', 'egGridMod'])
7
8 .config(function($routeProvider, $locationProvider, $compileProvider) {
9     $locationProvider.html5Mode(true);
10     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob):/); // grid export
11
12     var resolver = {delay : function(egStartup) {return egStartup.go()}};
13
14     // search page shows the list view by default
15     $routeProvider.when('/cat/item/search', {
16         templateUrl: './cat/item/t_list',
17         controller: 'ListCtrl',
18         resolve : resolver
19     });
20
21     $routeProvider.when('/cat/item/:id', {
22         templateUrl: './cat/item/t_view',
23         controller: 'ViewCtrl',
24         resolve : resolver
25     });
26
27     $routeProvider.when('/cat/item/:id/:tab', {
28         templateUrl: './cat/item/t_view',
29         controller: 'ViewCtrl',
30         resolve : resolver
31     });
32
33     // default page / bucket view
34     $routeProvider.otherwise({redirectTo : '/cat/item/search'});
35 })
36
37 .factory('itemSvc', 
38        ['egCore',
39 function(egCore) {
40
41     var service = {
42         copies : [], // copy barcode search results
43         index : 0 // search grid index
44     };
45
46     service.flesh = {   
47         flesh : 3, 
48         flesh_fields : {
49             acp : ['call_number','location','status','location'],
50             acn : ['record','prefix','suffix'],
51             bre : ['simple_record','creator','editor']
52         },
53         select : { 
54             // avoid fleshing MARC on the bre
55             // note: don't add simple_record.. not sure why
56             bre : ['id','tcn_value','creator','editor'],
57         } 
58     }
59
60     // resolved with the last received copy
61     service.fetch = function(barcode, id, noListDupes) {
62         var promise;
63
64         if (barcode) {
65             promise = egCore.pcrud.search('acp', 
66                 {barcode : barcode, deleted : 'f'}, service.flesh);
67         } else {
68             promise = egCore.pcrud.retrieve('acp', id, service.flesh);
69         }
70
71         var lastRes;
72         return promise.then(
73             function() {return lastRes},
74             null, // error
75
76             // notify reads the stream of copies, one at a time.
77             function(copy) {
78
79                 var flatCopy;
80                 if (noListDupes) {
81                     // use the existing copy if possible
82                     flatCopy = service.copies.filter(
83                         function(c) {return c.id == copy.id()})[0];
84                 }
85
86                 if (!flatCopy) {
87                     flatCopy = egCore.idl.toHash(copy, true);
88                     flatCopy.index = service.index++;
89                     service.copies.unshift(flatCopy);
90                 }
91
92                 return lastRes = {
93                     copy : copy, 
94                     index : flatCopy.index
95                 }
96             }
97         );
98     }
99
100     return service;
101 }])
102
103 /**
104  * Search bar along the top of the page.
105  * Parent scope for list and detail views
106  */
107 .controller('SearchCtrl', 
108        ['$scope','$location','egCore','egGridDataProvider','itemSvc',
109 function($scope , $location , egCore , egGridDataProvider , itemSvc) {
110     $scope.args = {}; // search args
111
112     // sub-scopes (search / detail-view) apply their version 
113     // of retrieval function to $scope.context.search
114     // and display toggling via $scope.context.toggleDisplay
115     $scope.context = {
116         selectBarcode : true
117     };
118
119     $scope.toggleView = function($event) {
120         $scope.context.toggleDisplay();
121         $event.preventDefault(); // avoid form submission
122     }
123 }])
124
125 /**
126  * List view - grid stuff
127  */
128 .controller('ListCtrl', 
129        ['$scope','$q','$location','$timeout','egCore','egGridDataProvider','itemSvc',
130 function($scope , $q , $location , $timeout , egCore , egGridDataProvider , itemSvc) {
131     $scope.context.page = 'list';
132
133     /*
134     var provider = egGridDataProvider.instance();
135     provider.get = function(offset, count) {
136     }
137     */
138
139     $scope.gridDataProvider = egGridDataProvider.instance({
140         get : function(offset, count) {
141             //return provider.arrayNotifier(itemSvc.copies, offset, count);
142             return this.arrayNotifier(itemSvc.copies, offset, count);
143         }
144     });
145
146     // If a copy was just displayed in the detail view, ensure it's
147     // focused in the list view.
148     var selected = false;
149     var copyGrid = $scope.gridControls = {
150         itemRetrieved : function(item) {
151             if (selected || !itemSvc.copy) return;
152             if (itemSvc.copy.id() == item.id) {
153                 copyGrid.selectItems([item.index]);
154                 selected = true;
155             }
156         }
157     };
158
159     $scope.$watch('barcodesFromFile', function(newVal, oldVal) {
160         if (newVal && newVal != oldVal) {
161             $scope.args.barcode = '';
162             var barcodes = [];
163
164             angular.forEach(newVal.split(/\n/), function(line) {
165                 if (!line) return;
166                 // scrub any trailing spaces or commas from the barcode
167                 line = line.replace(/(.*?)($|\s.*|,.*)/,'$1');
168                 barcodes.push(line);
169             });
170
171             itemSvc.fetch(barcodes).then(
172                 function() {
173                     copyGrid.refresh();
174                     copyGrid.selectItems([itemSvc.copies[0].index]);
175                 }
176             );
177         }
178     });
179
180     $scope.context.search = function(args) {
181         if (!args.barcode) return;
182         $scope.context.itemNotFound = false;
183         itemSvc.fetch(args.barcode).then(function(res) {
184             if (res) {
185                 copyGrid.refresh();
186                 copyGrid.selectItems([res.index]);
187                 $scope.args.barcode = '';
188             } else {
189                 $scope.context.itemNotFound = true;
190             }
191             $scope.context.selectBarcode = true;
192         })
193     }
194
195     $scope.context.toggleDisplay = function() {
196         var item = copyGrid.selectedItems()[0];
197         if (item) 
198             $location.path('/cat/item/' + item.id);
199     }
200
201     $scope.context.show_triggered_events = function() {
202         var item = copyGrid.selectedItems()[0];
203         if (item) 
204             $location.path('/cat/item/' + item.id + '/triggered_events');
205     }
206
207 }])
208
209 /**
210  * Detail view -- shows one copy
211  */
212 .controller('ViewCtrl', 
213        ['$scope','$q','$location','$routeParams','$timeout','$window','egCore','itemSvc','egBilling',
214 function($scope , $q , $location , $routeParams , $timeout , $window , egCore , itemSvc , egBilling) {
215     var copyId = $routeParams.id;
216     $scope.tab = $routeParams.tab || 'summary';
217     $scope.context.page = 'detail';
218
219     // use the cached record info
220     if (itemSvc.copy)
221         $scope.summaryRecord = itemSvc.copy.call_number().record();
222
223     function loadCopy(barcode) {
224         $scope.context.itemNotFound = false;
225
226         // Avoid re-fetching the same copy while jumping tabs.
227         // In addition to being quicker, this helps to avoid flickering
228         // of the top panel which is always visible in the detail view.
229         //
230         // 'barcode' represents the loading of a new item - refetch it
231         // regardless of whether it matches the current item.
232         if (!barcode && itemSvc.copy && itemSvc.copy.id() == copyId) {
233             $scope.copy = itemSvc.copy;
234             $scope.recordId = itemSvc.copy.call_number().record().id();
235             return $q.when();
236         }
237
238         delete $scope.copy;
239         delete itemSvc.copy;
240
241         var deferred = $q.defer();
242         itemSvc.fetch(barcode, copyId, true).then(function(res) {
243             $scope.context.selectBarcode = true;
244
245             if (!res) {
246                 copyId = null;
247                 $scope.context.itemNotFound = true;
248                 deferred.reject(); // avoid propagation of data fetch calls
249                 return;
250             }
251
252             var copy = res.copy;
253             itemSvc.copy = copy;
254
255
256             $scope.copy = copy;
257             $scope.recordId = copy.call_number().record().id();
258             $scope.summaryRecord = itemSvc.copy.call_number().record();
259             $scope.args.barcode = '';
260
261             // locally flesh org units
262             copy.circ_lib(egCore.org.get(copy.circ_lib()));
263             copy.call_number().owning_lib(
264                 egCore.org.get(copy.call_number().owning_lib()));
265
266             var r = copy.call_number().record();
267             if (r.owner()) r.owner(egCore.org.get(r.owner())); 
268
269             // make boolean for auto-magic true/false display
270             angular.forEach(
271                 ['ref','opac_visible','holdable','floating','circulate'],
272                 function(field) { copy[field](Boolean(copy[field]() == 't')) }
273             );
274
275             // finally, if this is a different copy, redirect.
276             // Note that we flesh first since the copy we just
277             // fetched will be used after the redirect.
278             if (copyId && copyId != copy.id()) {
279                 // if a new barcode is scanned in the detail view,
280                 // update the url to match the ID of the new copy
281                 $location.path('/cat/item/' + copy.id() + '/' + $scope.tab);
282                 deferred.reject(); // avoid propagation of data fetch calls
283                 return;
284             }
285             copyId = copy.id();
286
287             deferred.resolve();
288         });
289
290         return deferred.promise;
291     }
292
293     // if loadPrev load the two most recent circulations
294     function loadCurrentCirc(loadPrev) {
295         delete $scope.circ;
296         delete $scope.circ_summary;
297         delete $scope.prev_circ_summary;
298         if (!copyId) return;
299         
300         egCore.pcrud.search('circ', 
301             {target_copy : copyId},
302             {   flesh : 2,
303                 flesh_fields : {
304                     circ : [
305                         'usr',
306                         'workstation',                                         
307                         'checkin_workstation',                                 
308                         'duration_rule',                                       
309                         'max_fine_rule',                                       
310                         'recurring_fine_rule'   
311                     ],
312                     au : ['card']
313                 },
314                 order_by : {circ : 'xact_start desc'}, 
315                 limit :  1
316             }
317
318         ).then(null, null, function(circ) {
319             $scope.circ = circ;
320
321             // load the chain for this circ
322             egCore.net.request(
323                 'open-ils.circ',
324                 'open-ils.circ.renewal_chain.retrieve_by_circ.summary',
325                 egCore.auth.token(), $scope.circ.id()
326             ).then(function(summary) {
327                 $scope.circ_summary = summary.summary;
328             });
329
330             if (!loadPrev) return;
331
332             // load the chain for the previous circ, plus the user
333             egCore.net.request(
334                 'open-ils.circ',
335                 'open-ils.circ.prev_renewal_chain.retrieve_by_circ.summary',
336                 egCore.auth.token(), $scope.circ.id()
337
338             ).then(null, null, function(summary) {
339                 $scope.prev_circ_summary = summary.summary;
340
341                 egCore.pcrud.retrieve('au', summary.usr,
342                     {flesh : 1, flesh_fields : {au : ['card']}})
343
344                 .then(function(user) {
345                     $scope.prev_circ_usr = user;
346                 });
347             });
348         });
349     }
350
351     var maxHistory;
352     function fetchMaxCircHistory() {
353         if (maxHistory) return $q.when(maxHistory);
354         return egCore.org.settings(
355             'circ.item_checkout_history.max')
356         .then(function(set) {
357             maxHistory = set['circ.item_checkout_history.max'] || 4;
358             return maxHistory;
359         });
360     }
361
362     $scope.addBilling = function(circ) {
363         egBilling.showBillDialog({
364             xact_id : circ.id(),
365             patron : circ.usr()
366         });
367     }
368
369     $scope.retrieveAllPatrons = function() {
370         var users = new Set();
371         angular.forEach($scope.circ_list.map(function(circ) { return circ.usr(); }),function(usr) {
372             users.add(usr);
373         });
374         users.forEach(function(usr) {
375             $timeout(function() {
376                 var url = $location.absUrl().replace(
377                     /\/cat\/.*/,
378                     '/circ/patron/' + usr.id() + '/checkout');
379                 $window.open(url, '_blank')
380             });
381         });
382     }
383
384     function loadCircHistory() {
385         $scope.circ_list = [];
386
387         var copy_org = 
388             itemSvc.copy.call_number().id() == -1 ?
389             itemSvc.copy.circ_lib().id() :
390             itemSvc.copy.call_number().owning_lib().id()
391
392         // there is an extra layer of permissibility over circ
393         // history views
394         egCore.perm.hasPermAt('VIEW_COPY_CHECKOUT_HISTORY', true)
395         .then(function(orgIds) {
396
397             if (orgIds.indexOf(copy_org) == -1) {
398                 console.log('User is not allowed to view circ history');
399                 return $q.when(0);
400             }
401
402             return fetchMaxCircHistory();
403
404         }).then(function(count) {
405
406             egCore.pcrud.search('circ', 
407                 {target_copy : copyId},
408                 {   flesh : 2,
409                     flesh_fields : {
410                         circ : [
411                             'usr',
412                             'workstation',                                         
413                             'checkin_workstation',                                 
414                             'recurring_fine_rule'   
415                         ],
416                         au : ['card']
417                     },
418                     order_by : {circ : 'xact_start desc'}, 
419                     limit :  count
420                 }
421
422             ).then(null, null, function(circ) {
423
424                 // flesh circ_lib locally
425                 circ.circ_lib(egCore.org.get(circ.circ_lib()));
426                 circ.checkin_lib(egCore.org.get(circ.checkin_lib()));
427                 $scope.circ_list.push(circ);
428             });
429         });
430     }
431
432
433     function loadCircCounts() {
434
435         delete $scope.circ_counts;
436         $scope.total_circs = 0;
437         $scope.total_circs_this_year = 0;
438         $scope.total_circs_prev_year = 0;
439         if (!copyId) return;
440
441         egCore.pcrud.search('circbyyr', 
442             {copy : copyId}, null, {atomic : true})
443
444         .then(function(counts) {
445             $scope.circ_counts = counts;
446
447             angular.forEach(counts, function(count) {
448                 $scope.total_circs += Number(count.count());
449             });
450
451             var this_year = counts.filter(function(c) {
452                 return c.year() == new Date().getFullYear();
453             });
454
455             $scope.total_circs_this_year = 
456                 this_year.length ? this_year[0].count() : 0;
457
458             var prev_year = counts.filter(function(c) {
459                 return c.year() == new Date().getFullYear() - 1;
460             });
461
462             $scope.total_circs_prev_year = 
463                 prev_year.length ? prev_year[0].count() : 0;
464
465         });
466     }
467
468     function loadHolds() {
469         delete $scope.hold;
470         if (!copyId) return;
471
472         egCore.pcrud.search('ahr', 
473             {   current_copy : copyId, 
474                 cancel_time : null, 
475                 fulfillment_time : null,
476                 capture_time : {'<>' : null}
477             }, {
478                 flesh : 2,
479                 flesh_fields : {
480                     ahr : ['requestor', 'usr'],
481                     au  : ['card']
482                 }
483             }
484         ).then(null, null, function(hold) {
485             $scope.hold = hold;
486             hold.pickup_lib(egCore.org.get(hold.pickup_lib()));
487             if (hold.current_shelf_lib()) {
488                 hold.current_shelf_lib(
489                     egCore.org.get(hold.current_shelf_lib()));
490             }
491             hold.behind_desk(Boolean(hold.behind_desk() == 't'));
492         });
493     }
494
495     function loadTransits() {
496         delete $scope.transit;
497         delete $scope.hold_transit;
498         if (!copyId) return;
499
500         egCore.pcrud.search('atc', 
501             {target_copy : copyId},
502             {order_by : {atc : 'source_send_time DESC'}}
503
504         ).then(null, null, function(transit) {
505             $scope.transit = transit;
506             transit.source(egCore.org.get(transit.source()));
507             transit.dest(egCore.org.get(transit.dest()));
508         })
509     }
510
511
512     // we don't need all data on all tabs, so fetch what's needed when needed.
513     function loadTabData() {
514         switch($scope.tab) {
515             case 'summary':
516                 loadCurrentCirc();
517                 loadCircCounts();
518                 break;
519
520             case 'circs':
521                 loadCurrentCirc(true);
522                 break;
523
524             case 'circ_list':
525                 loadCircHistory();
526                 break;
527
528             case 'holds':
529                 loadHolds()
530                 loadTransits();
531                 break;
532
533             case 'triggered_events':
534                 var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
535                 url += '?copy_id=' + encodeURIComponent(copyId);
536                 $scope.triggered_events_url = url;
537                 $scope.funcs = {};
538         }
539     }
540
541     $scope.context.toggleDisplay = function() {
542         $location.path('/cat/item/search');
543     }
544
545     // handle the barcode scan box, which will replace our current copy
546     $scope.context.search = function(args) {
547         loadCopy(args.barcode).then(loadTabData);
548     }
549
550     $scope.context.show_triggered_events = function() {
551         $location.path('/cat/item/' + copyId + '/triggered_events');
552     }
553
554     loadCopy().then(loadTabData);
555 }])