]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/item/app.js
LP#1350042 Browser client templates/scripts (phase 1)
[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','egCore','itemSvc','egBilling',
214 function($scope , $q , $location , $routeParams , 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     function loadCircHistory() {
370         $scope.circ_list = [];
371
372         var copy_org = 
373             itemSvc.copy.call_number().id() == -1 ?
374             itemSvc.copy.circ_lib().id() :
375             itemSvc.copy.call_number().owning_lib().id()
376
377         // there is an extra layer of permissibility over circ
378         // history views
379         egCore.perm.hasPermAt('VIEW_COPY_CHECKOUT_HISTORY', true)
380         .then(function(orgIds) {
381
382             if (orgIds.indexOf(copy_org) == -1) {
383                 console.log('User is not allowed to view circ history');
384                 return $q.when(0);
385             }
386
387             return fetchMaxCircHistory();
388
389         }).then(function(count) {
390
391             egCore.pcrud.search('circ', 
392                 {target_copy : copyId},
393                 {   flesh : 2,
394                     flesh_fields : {
395                         circ : [
396                             'usr',
397                             'workstation',                                         
398                             'checkin_workstation',                                 
399                             'recurring_fine_rule'   
400                         ],
401                         au : ['card']
402                     },
403                     order_by : {circ : 'xact_start desc'}, 
404                     limit :  count
405                 }
406
407             ).then(null, null, function(circ) {
408
409                 // flesh circ_lib locally
410                 circ.circ_lib(egCore.org.get(circ.circ_lib()));
411                 circ.checkin_lib(egCore.org.get(circ.checkin_lib()));
412                 $scope.circ_list.push(circ);
413             });
414         });
415     }
416
417
418     function loadCircCounts() {
419
420         delete $scope.circ_counts;
421         $scope.total_circs = 0;
422         $scope.total_circs_this_year = 0;
423         $scope.total_circs_prev_year = 0;
424         if (!copyId) return;
425
426         egCore.pcrud.search('circbyyr', 
427             {copy : copyId}, null, {atomic : true})
428
429         .then(function(counts) {
430             $scope.circ_counts = counts;
431
432             angular.forEach(counts, function(count) {
433                 $scope.total_circs += Number(count.count());
434             });
435
436             var this_year = counts.filter(function(c) {
437                 return c.year() == new Date().getFullYear();
438             });
439
440             $scope.total_circs_this_year = 
441                 this_year.length ? this_year[0].count() : 0;
442
443             var prev_year = counts.filter(function(c) {
444                 return c.year() == new Date().getFullYear() - 1;
445             });
446
447             $scope.total_circs_prev_year = 
448                 prev_year.length ? prev_year[0].count() : 0;
449
450         });
451     }
452
453     function loadHolds() {
454         delete $scope.hold;
455         if (!copyId) return;
456
457         egCore.pcrud.search('ahr', 
458             {   current_copy : copyId, 
459                 cancel_time : null, 
460                 fulfillment_time : null,
461                 capture_time : {'<>' : null}
462             }, {
463                 flesh : 2,
464                 flesh_fields : {
465                     ahr : ['requestor', 'usr'],
466                     au  : ['card']
467                 }
468             }
469         ).then(null, null, function(hold) {
470             $scope.hold = hold;
471             hold.pickup_lib(egCore.org.get(hold.pickup_lib()));
472             if (hold.current_shelf_lib()) {
473                 hold.current_shelf_lib(
474                     egCore.org.get(hold.current_shelf_lib()));
475             }
476             hold.behind_desk(Boolean(hold.behind_desk() == 't'));
477         });
478     }
479
480     function loadTransits() {
481         delete $scope.transit;
482         delete $scope.hold_transit;
483         if (!copyId) return;
484
485         egCore.pcrud.search('atc', 
486             {target_copy : copyId},
487             {order_by : {atc : 'source_send_time DESC'}}
488
489         ).then(null, null, function(transit) {
490             $scope.transit = transit;
491             transit.source(egCore.org.get(transit.source()));
492             transit.dest(egCore.org.get(transit.dest()));
493         })
494     }
495
496
497     // we don't need all data on all tabs, so fetch what's needed when needed.
498     function loadTabData() {
499         switch($scope.tab) {
500             case 'summary':
501                 loadCurrentCirc();
502                 loadCircCounts();
503                 break;
504
505             case 'circs':
506                 loadCurrentCirc(true);
507                 break;
508
509             case 'circ_list':
510                 loadCircHistory();
511                 break;
512
513             case 'holds':
514                 loadHolds()
515                 loadTransits();
516                 break;
517
518             case 'triggered_events':
519                 var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
520                 url += '?copy_id=' + encodeURIComponent(copyId);
521                 $scope.triggered_events_url = url;
522                 $scope.funcs = {};
523         }
524     }
525
526     $scope.context.toggleDisplay = function() {
527         $location.path('/cat/item/search');
528     }
529
530     // handle the barcode scan box, which will replace our current copy
531     $scope.context.search = function(args) {
532         loadCopy(args.barcode).then(loadTabData);
533     }
534
535     $scope.context.show_triggered_events = function() {
536         $location.path('/cat/item/' + copyId + '/triggered_events');
537     }
538
539     loadCopy().then(loadTabData);
540 }])