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