5ce21aa221884251665fc13db17a76ecf6a38493
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / circ / holds / app.js
1 angular.module('egHoldsApp', 
2     ['ngRoute', 'ui.bootstrap', 'egCoreMod', 'egUiMod', 'egGridMod'])
3
4 .config(function($routeProvider, $locationProvider, $compileProvider) {
5     $locationProvider.html5Mode(true);
6     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob):/); // grid export
7
8     var resolver = {delay : 
9         ['egStartup', function(egStartup) {return egStartup.go()}]}
10
11     $routeProvider.when('/circ/holds/shelf', {
12         templateUrl: './circ/holds/t_shelf',
13         controller: 'HoldsShelfCtrl',
14         resolve : resolver
15     });
16
17     $routeProvider.when('/circ/holds/shelf/:hold_id', {
18         templateUrl: './circ/holds/t_shelf',
19         controller: 'HoldsShelfCtrl',
20         resolve : resolver
21     });
22
23     $routeProvider.when('/circ/holds/pull', {
24         templateUrl: './circ/holds/t_pull',
25         controller: 'HoldsPullListCtrl',
26         resolve : resolver
27     });
28
29     $routeProvider.when('/circ/holds/pull/:hold_id', {
30         templateUrl: './circ/holds/t_pull',
31         controller: 'HoldsPullListCtrl',
32         resolve : resolver
33     });
34
35     $routeProvider.otherwise({redirectTo : '/circ/holds/shelf'});
36 })
37
38
39 .controller('HoldsShelfCtrl',
40        ['$scope','$q','$routeParams','$window','$location','egCore','egHolds','egHoldGridActions','egCirc','egGridDataProvider','egProgressDialog',
41 function($scope , $q , $routeParams , $window , $location , egCore , egHolds , egHoldGridActions , egCirc , egGridDataProvider , egProgressDialog)  {
42     $scope.detail_hold_id = $routeParams.hold_id;
43
44     var holds = [];
45     var clear_mode = false;
46     $scope.gridControls = {};
47     $scope.grid_actions = egHoldGridActions;
48
49     var provider = egGridDataProvider.instance({});
50     $scope.gridDataProvider = provider;
51
52     function refresh_page() {
53         hold_count = 0;
54         holds = [];
55         all_holds = [];
56         provider.refresh();
57     }
58     // called after any egHoldGridActions action occurs
59     $scope.grid_actions.refresh = refresh_page;
60
61     provider.get = function(offset, count) {
62
63         // if in clear mode...
64         if (clear_mode && holds.length) {
65             if (!all_holds.legnth) all_holds = holds;
66             holds = holds.filter(function(h) { return h.hold.clear_me });
67             hold_count = holds.length;
68             return provider.arrayNotifier(holds, offset, count);
69         } else if (all_holds.length) {
70             holds = all_holds;
71             hold_count = holds.length;
72             all_holds = [];
73         }
74
75         // see if we have the requested range cached
76         if (holds[offset]) {
77             return provider.arrayNotifier(holds, offset, count);
78         }
79
80         hold_count = 0;
81         holds = [];
82         var restrictions = {
83                 is_staff_request  : 'true',
84                 last_captured_hold: 'true',
85                 capture_time      : { not : null },
86                 cs_id             : 8, // on holds shelf
87                 fulfillment_time  : null,
88                 current_shelf_lib : $scope.pickup_ou.id()
89         };
90
91         var order_by = [{ shelf_expire_time : null }];
92         if (provider.sort && provider.sort.length) {
93             order_by = [];
94             angular.forEach(provider.sort, function (c) {
95                 if (!angular.isObject(c)) {
96                     if (c.match(/^hold\./)) {
97                         var i = c.replace('hold.','');
98                         var ob = {};
99                         ob[i] = null;
100                         order_by.push(ob);
101                     }
102                 } else {
103                     var i = Object.keys(c)[0];
104                     var direction = c[i];
105                     if (i.match(/^hold\./)) {
106                         i = i.replace('hold.','');
107                         var ob = {}
108                         ob[i] = {dir:direction};
109                         order_by.push(ob);
110                     }
111                 }
112             });
113         }
114
115         egProgressDialog.open({max : 1, value : 0});
116         var first = true;
117         return egHolds.fetch_wide_holds(
118             restrictions,
119             order_by
120         ).then(function () {
121                 return provider.arrayNotifier(holds, offset, count);
122             },
123             null,
124             function(hold_data) { 
125                 if (first) {
126                     hold_count = hold_data;
127                     first = false;
128                     egProgressDialog.update({max:hold_count});
129                 } else {
130                     egProgressDialog.increment();
131                     var new_item = { id : hold_data.id, hold : hold_data };
132                     new_item.status_string =
133                         egCore.strings['HOLD_STATUS_' + hold_data.hold_status]
134                         || hold_data.hold_status;
135
136                     if (clear_mode) {
137                         if (hold_data.clear_me) holds.push(new_item);
138                         all_holds.push(new_item);
139                     } else {
140                         holds.push(new_item);
141                     }
142                 }
143             }
144         ).finally(egProgressDialog.close);
145     }
146
147     // re-draw the grid when user changes the org selector
148     $scope.pickup_ou = egCore.org.get(egCore.auth.user().ws_ou());
149     $scope.$watch('pickup_ou', function(newVal, oldVal) {
150         if (newVal && newVal != oldVal) 
151             refresh_page();
152     });
153
154     $scope.detail_view = function(action, user_data, items) {
155         if (h = items[0]) {
156             $location.path('/circ/holds/shelf/' + h.hold.id);
157         }
158     }
159
160     $scope.list_view = function(items) {
161         $location.path('/circ/holds/shelf');
162     }
163
164     // when the detail hold is fetched (and updated), update the bib
165     // record summary display record id.
166     $scope.set_hold = function(hold_data) {
167         $scope.detail_hold_record_id = hold_data.hold.record_id;
168     }
169
170     // manage active vs. clearable holds display
171     var clearing = false; // true if actively clearing holds (below)
172     $scope.is_clearing = function() { return clearing };
173     $scope.active_mode = function() {return !clear_mode}
174     $scope.clear_mode = function() {return clear_mode}
175     $scope.show_clearable = function() { clear_mode = true; provider.refresh() }
176     $scope.show_active = function() { clear_mode = false; provider.refresh() }
177     $scope.disable_clear = function() { return clearing || !clear_mode }
178
179     // udpate the in-grid hold with the clear-shelf cached response info.
180     function handle_clear_cache_resp(resp) {
181         if (!angular.isArray(resp)) resp = [resp];
182         angular.forEach(resp, function(info) {
183             if (info.action) {
184                 var grid_item = holds.filter(function(item) {
185                     return item.hold.id == info.hold_details.id
186                 })[0];
187
188                 var all_hold_item = all_holds.filter(function(item) {
189                     return item.hold.id == info.hold_details.id
190                 })[0];
191
192                 // there will be no grid item if the hold is off-page
193                 if (grid_item) {
194                     grid_item.post_clear = 
195                         egCore.strings['CLEAR_SHELF_ACTION_' + info.action];
196                     all_hold_item.post_clear = 
197                         egCore.strings['CLEAR_SHELF_ACTION_' + info.action];
198                 }
199             }
200         });
201     }
202
203     $scope.clear_holds = function() {
204         clearing = true;
205         $scope.clear_progress = {max : 0, value : 0};
206
207         // we want to see all processed holds, so (effectively) remove
208         // the grid limit.
209         $scope.gridControls.setLimit(1000, true); 
210
211         // initiate clear shelf and grab cache key
212         egCore.net.request(
213             'open-ils.circ',
214             'open-ils.circ.hold.clear_shelf.process',
215             egCore.auth.token(), $scope.pickup_ou.id(),
216             null, 1
217
218         // request responses from the clear shelf cache
219         ).then(
220             
221             // clear shelf done; fetch the cached results.
222             function(resp) {
223                 clearing = false;
224                 egCore.net.request(
225                     'open-ils.circ',
226                     'open-ils.circ.hold.clear_shelf.get_cache',
227                     egCore.auth.token(), resp.cache_key, 1
228                 ).then(null, null, handle_clear_cache_resp);
229             }, 
230
231             null,
232
233             // handle streamed clear_shelf progress updates
234             function(resp) {
235                 if (resp.maximum) 
236                     $scope.clear_progress.max = resp.maximum;
237                 if (resp.progress)
238                     $scope.clear_progress.value = resp.progress;
239             }
240
241         );
242     }
243
244     function map_prefix_to_subhash (h,pf) {
245         var newhash = {};
246         angular.forEach(Object.keys(h), function (k) {
247             if (k.startsWith(pf)) {
248                 var nk = k.substr(pf.length);
249                 newhash[nk] = h[k];
250             }
251         });
252         return newhash;
253     }
254
255     $scope.print_shelf_list = function() {
256         var print_holds = [];
257         angular.forEach(holds, function(hold_data) {
258             var phold = {};
259             print_holds.push(phold);
260
261             phold.status_string = hold_data.status_string;
262
263             phold.patron_first = hold_data.hold.usr_first_given_name;
264             phold.patron_last = hold_data.hold.usr_family_name;
265             phold.patron_alias = hold_data.hold.usr_alias;
266             phold.patron_barcode = hold_data.hold.ucard_barcode;
267
268             phold.title = hold_data.hold.title;
269             phold.author = hold_data.hold.author;
270
271             phold.hold = hold_data.hold;
272             phold.copy = map_prefix_to_subhash(hold_data.hold, 'cp_');
273             phold.volume = map_prefix_to_subhash(hold_data.hold, 'cn_');
274             phold.part = map_prefix_to_subhash(hold_data.hold, 'p_');
275         });
276
277         console.log(print_holds);
278
279         return egCore.print.print({
280             context : 'default', 
281             template : 'hold_shelf_list', 
282             scope : {holds : print_holds}
283         });
284     }
285
286     refresh_page();
287
288 }])
289
290 .controller('HoldsPullListCtrl',
291        ['$scope','$q','$routeParams','$window','$location','egCore',
292         'egHolds','egCirc','egHoldGridActions','egProgressDialog',
293 function($scope , $q , $routeParams , $window , $location , egCore , 
294          egHolds , egCirc , egHoldGridActions , egProgressDialog) {
295
296     $scope.detail_hold_id = $routeParams.hold_id;
297
298     var cached_details = {};
299     var details_needed = {};
300
301     $scope.gridControls = {
302         setQuery : function() {
303             return {'copy_circ_lib_id' : egCore.auth.user().ws_ou()}
304         },
305         setSort : function() {
306             return ['copy_location_order_position','call_number_sort_key']
307         },
308         collectStarted : function(offset) {
309             // Launch an indeterminate -> semi-determinate progress
310             // modal.  Using a determinate modal that starts counting
311             // on the post-grid holds data retrieval results in a modal
312             // that's stuck at 0% for most of its life, which is aggravating.
313             egProgressDialog.open();
314         },
315         itemRetrieved : function(item) {
316             egProgressDialog.increment();
317             if (!cached_details[item.id]) {
318                 details_needed[item.id] = item;
319             }
320         },
321         allItemsRetrieved : function() {
322             flesh_holds().finally(egProgressDialog.close);
323         }
324     }
325
326
327     // Fetches hold detail data for each hold in the grid and links
328     // the detail data to the related grid item so egHoldGridActions 
329     // and friends have access to holds data they understand.
330     // Only fetch not-yet-cached data.
331     function flesh_holds() {
332         egProgressDialog.increment();
333
334         // Start by fleshing hold details from our cached data.
335         var items = $scope.gridControls.allItems();
336         angular.forEach(items, function(item) {
337             if (!cached_details[item.id]) return $q.when();
338             angular.forEach(cached_details[item.id], 
339                 function(val, key) { item[key] = val })
340         });
341
342         // Exit if all needed details were already cached
343         if (Object.keys(details_needed).length == 0) return $q.when();
344
345         return egCore.net.request(
346             'open-ils.circ',
347             'open-ils.circ.hold.details.batch.retrieve.authoritative',
348             egCore.auth.token(), Object.keys(details_needed), {
349                 include_usr : true
350             }
351
352         ).then(null, null, function(hold_info) {
353             egProgressDialog.increment();
354
355             // check if this is a staff-created hold
356             // i.e., requestor is not the same as the user
357             hold_info['_is_staff_hold'] = hold_info.hold.requestor() != hold_info.hold.usr().id();
358
359             var hold_id = hold_info.hold.id();
360             cached_details[hold_id] = hold_info;
361             var item = details_needed[hold_id];
362             delete details_needed[hold_id];
363
364             // flesh the grid item from the blob of hold data.
365             angular.forEach(hold_info, 
366                 function(val, key) { item[key] = val });
367
368         });
369     }
370
371     $scope.grid_actions = egHoldGridActions;
372     $scope.grid_actions.refresh = function() {
373         cached_details = {}; // un-cache details after edit actions.
374         $scope.gridControls.refresh();
375     }
376
377     $scope.detail_view = function(action, user_data, items) {
378         if (h = items[0]) {
379             $location.path('/circ/holds/pull/' + h.hold.id());
380         }
381     }
382
383     $scope.list_view = function(items) {
384         $location.path('/circ/holds/pull');
385     }
386
387     // when the detail hold is fetched (and updated), update the bib
388     // record summary display record id.
389     $scope.set_hold = function(hold_data) {
390         $scope.detail_hold_record_id = hold_data.mvr.doc_id();
391     }
392
393     // By default, this action is hidded from the UI, but leaving it
394     // here in case it's needed in the future
395     $scope.print_list_alt = function() {
396         var url = '/opac/extras/circ/alt_holds_print.html';
397         var win = $window.open(url, '_blank');
398         win.ses = function() {return egCore.auth.token()};
399         win.open();
400         win.focus();
401     }
402
403     $scope.print_full_list = function() {
404         var print_holds = [];
405         egProgressDialog.open({value : 0});
406
407         // collect the full list of holds
408         egCore.net.request(
409             'open-ils.circ',
410             'open-ils.circ.hold_pull_list.fleshed.stream',
411             egCore.auth.token(), 10000, 0
412         ).then(
413             function() {
414                 console.debug('printing ' + print_holds.length + ' holds');
415
416                 // holds fetched, send to print
417                 egCore.print.print({
418                     context : 'default', 
419                     template : 'hold_pull_list', 
420                     scope : {holds : print_holds}
421                 });
422             },
423             null, 
424             function(hold_data) {
425                 egProgressDialog.increment();
426                 egHolds.local_flesh(hold_data);
427                 print_holds.push(hold_data);
428                 hold_data.title = hold_data.mvr.title();
429                 hold_data.author = hold_data.mvr.author();
430                 hold_data.hold = egCore.idl.toHash(hold_data.hold);
431                 hold_data.copy = egCore.idl.toHash(hold_data.copy);
432                 hold_data.volume = egCore.idl.toHash(hold_data.volume);
433                 hold_data.part = egCore.idl.toHash(hold_data.part);
434             }
435         ).finally(egProgressDialog.close);
436     }
437
438 }])
439