]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/services/circ.js
LP#1350042 Browser client templates/scripts (phase 1)
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / circ / services / circ.js
1 /**
2  * Checkin, checkout, and renew
3  */
4
5 angular.module('egCoreMod')
6
7 .factory('egCirc',
8
9        ['$modal','$q','egCore','egAlertDialog','egConfirmDialog',
10 function($modal , $q , egCore , egAlertDialog , egConfirmDialog) {
11
12     var service = {
13         // auto-override these events after the first override
14         auto_override_checkout_events : {},
15     };
16
17     service.reset = function() {
18         service.auto_override_checkout_events = {};
19     }
20
21     // these events can be overridden by staff during checkout
22     service.checkout_overridable_events = [
23         'PATRON_EXCEEDS_OVERDUE_COUNT',
24         'PATRON_EXCEEDS_CHECKOUT_COUNT',
25         'PATRON_EXCEEDS_FINES',
26         'PATRON_BARRED',
27         'CIRC_EXCEEDS_COPY_RANGE',
28         'ITEM_DEPOSIT_REQUIRED',
29         'ITEM_RENTAL_FEE_REQUIRED',
30         'PATRON_EXCEEDS_LOST_COUNT',
31         'COPY_CIRC_NOT_ALLOWED',
32         'COPY_NOT_AVAILABLE',
33         'COPY_IS_REFERENCE',
34         'COPY_ALERT_MESSAGE',
35         'ITEM_ON_HOLDS_SHELF'                 
36     ]
37
38     // after the first override of any of these events, 
39     // auto-override them in subsequent calls.
40     service.checkout_auto_override_after_first = [
41         'PATRON_EXCEEDS_OVERDUE_COUNT',
42         'PATRON_BARRED',
43         'PATRON_EXCEEDS_LOST_COUNT',
44         'PATRON_EXCEEDS_CHECKOUT_COUNT',
45         'PATRON_EXCEEDS_FINES'
46     ]
47
48
49     // overridable during renewal
50     service.renew_overridable_events = [
51         'PATRON_EXCEEDS_OVERDUE_COUNT',
52         'PATRON_EXCEEDS_LOST_COUNT',
53         'PATRON_EXCEEDS_CHECKOUT_COUNT',
54         'PATRON_EXCEEDS_FINES',
55         'CIRC_EXCEEDS_COPY_RANGE',
56         'ITEM_DEPOSIT_REQUIRED',
57         'ITEM_RENTAL_FEE_REQUIRED',
58         'ITEM_DEPOSIT_PAID',
59         'COPY_CIRC_NOT_ALLOWED',
60         'COPY_IS_REFERENCE',
61         'COPY_ALERT_MESSAGE',
62         'COPY_NEEDED_FOR_HOLD',
63         'MAX_RENEWALS_REACHED',
64         'CIRC_CLAIMS_RETURNED'
65     ];
66
67     // these checkin events do not produce alerts when 
68     // options.suppress_alerts is in effect.
69     service.checkin_suppress_overrides = [
70         'COPY_BAD_STATUS',
71         'PATRON_BARRED',
72         'PATRON_INACTIVE',
73         'PATRON_ACCOUNT_EXPIRED',
74         'ITEM_DEPOSIT_PAID',
75         'CIRC_CLAIMS_RETURNED',
76         'COPY_ALERT_MESSAGE',
77         'COPY_STATUS_LOST',
78         'COPY_STATUS_LONG_OVERDUE',
79         'COPY_STATUS_MISSING',
80         'PATRON_EXCEEDS_FINES'
81     ]
82
83     // these events can be overridden by staff during checkin
84     service.checkin_overridable_events = 
85         service.checkin_suppress_overrides.concat([
86         'TRANSIT_CHECKIN_INTERVAL_BLOCK'
87     ])
88
89     // Performs a checkout.
90     // Returns a promise resolved with the original params and options
91     // and the final checkout event (e.g. in the case of override).
92     // Rejected if the checkout cannot be completed.
93     //
94     // params : passed directly as arguments to the server API 
95     // options : non-parameter controls.  e.g. "override", "check_barcode"
96     service.checkout = function(params, options) {
97         if (!options) options = {};
98
99         console.debug('egCirc.checkout() : ' 
100             + js2JSON(params) + ' : ' + js2JSON(options));
101
102         var promise = options.check_barcode ? 
103             service.test_barcode(params.copy_barcode) : $q.when();
104
105         // avoid re-check on override, etc.
106         delete options.check_barcode;
107
108         return promise.then(function() {
109
110             var method = 'open-ils.circ.checkout.full';
111             if (options.override) method += '.override';
112
113             return egCore.net.request(
114                 'open-ils.circ', method, egCore.auth.token(), params
115
116             ).then(function(evt) {
117
118                 if (angular.isArray(evt)) evt = evt[0];
119
120                 return service.flesh_response_data('checkout', evt, params, options)
121                 .then(function() {
122                     return service.handle_checkout_resp(evt, params, options);
123                 })
124                 .then(function(final_resp) {
125                     return service.munge_resp_data(final_resp)
126                 })
127             });
128         });
129     }
130
131     // Performs a renewal.
132     // Returns a promise resolved with the original params and options
133     // and the final checkout event (e.g. in the case of override)
134     // Rejected if the renewal cannot be completed.
135     service.renew = function(params, options) {
136         if (!options) options = {};
137
138         console.debug('egCirc.renew() : ' 
139             + js2JSON(params) + ' : ' + js2JSON(options));
140
141         var promise = options.check_barcode ? 
142             service.test_barcode(params.copy_barcode) : $q.when();
143
144         // avoid re-check on override, etc.
145         delete options.check_barcode;
146
147         return promise.then(function() {
148
149             var method = 'open-ils.circ.renew';
150             if (options.override) method += '.override';
151
152             return egCore.net.request(
153                 'open-ils.circ', method, egCore.auth.token(), params
154
155             ).then(function(evt) {
156
157                 if (angular.isArray(evt)) evt = evt[0];
158
159                 return service.flesh_response_data(
160                     'renew', evt, params, options)
161                 .then(function() {
162                     return service.handle_renew_resp(evt, params, options);
163                 })
164                 .then(function(final_resp) {
165                     return service.munge_resp_data(final_resp)
166                 })
167             });
168         });
169     }
170
171     // Performs a checkin
172     // Returns a promise resolved with the original params and options,
173     // plus the final checkin event (e.g. in the case of override).
174     // Rejected if the checkin cannot be completed.
175     service.checkin = function(params, options) {
176         if (!options) options = {};
177
178         console.debug('egCirc.checkin() : ' 
179             + js2JSON(params) + ' : ' + js2JSON(options));
180
181         var promise = options.check_barcode ? 
182             service.test_barcode(params.copy_barcode) : $q.when();
183
184         // avoid re-check on override, etc.
185         delete options.check_barcode;
186
187         return promise.then(function() {
188
189             var method = 'open-ils.circ.checkin';
190             if (options.override) method += '.override';
191
192             return egCore.net.request(
193                 'open-ils.circ', method, egCore.auth.token(), params
194
195             ).then(function(evt) {
196
197                 if (angular.isArray(evt)) evt = evt[0];
198                 return service.flesh_response_data(
199                     'checkin', evt, params, options)
200                 .then(function() {
201                     return service.handle_checkin_resp(evt, params, options);
202                 })
203                 .then(function(final_resp) {
204                     return service.munge_resp_data(final_resp)
205                 })
206             });
207         });
208     }
209
210     // provide consistent formatting of the final response data
211     service.munge_resp_data = function(final_resp) {
212         var data = final_resp.data = {};
213
214         if (!final_resp.evt) return;
215
216         var payload = final_resp.evt.payload;
217         if (!payload) return;
218
219         data.circ = payload.circ;
220         data.parent_circ = payload.parent_circ;
221         data.hold = payload.hold;
222         data.record = payload.record;
223         data.acp = payload.copy;
224         data.acn = payload.volume ?  payload.volume : payload.copy.call_number();
225         data.au = payload.patron;
226         data.transit = payload.transit;
227         data.status = payload.status;
228         data.message = payload.message;
229         data.title = final_resp.evt.title;
230         data.author = final_resp.evt.author;
231         data.isbn = final_resp.evt.isbn;
232         data.route_to = final_resp.evt.route_to;
233
234         // for checkin, the mbts lives on the main circ
235         if (payload.circ && payload.circ.billable_transaction())
236             data.mbts = payload.circ.billable_transaction().summary();
237
238         // on renewals, the mbts lives on the parent circ
239         if (payload.parent_circ && payload.parent_circ.billable_transaction())
240             data.mbts = payload.parent_circ.billable_transaction().summary();
241
242         if (!data.route_to) {
243             if (data.transit) {
244                 data.route_to = data.transit.dest().shortname();
245             } else if (data.acp) {
246                 data.route_to = data.acp.location().name();
247             }
248         }
249
250         return final_resp;
251     }
252
253     service.handle_overridable_checkout_event = function(evt, params, options) {
254
255         if (options.override) {
256             // override attempt already made and failed.
257             // NOTE: I don't think we'll ever get here, since the
258             // override attempt should produce a perm failure...
259             console.debug('override failed: ' + evt.textcode);
260             return $q.reject();
261
262         } 
263
264         if (service.auto_override_checkout_events[evt.textcode]) {
265             // user has already opted to override this type
266             // of event.  Re-run the checkout w/ override.
267             options.override = true;
268             return service.checkout(params, options);
269         } 
270
271         // Ask the user if they would like to override this event.
272         // Some events offer a stock override dialog, while others
273         // require additional context.
274
275         switch(evt.textcode) {
276             case 'COPY_NOT_AVAILABLE':
277                 return service.copy_not_avail_dialog(evt, params, options);
278             case 'COPY_ALERT_MESSAGE':
279                 return service.copy_alert_dialog(evt, params, options, 'checkout');
280             default: 
281                 return service.override_dialog(evt, params, options, 'checkout');
282         }
283     }
284
285     service.handle_overridable_renew_event = function(evt, params, options) {
286
287         if (options.override) {
288             // override attempt already made and failed.
289             // NOTE: I don't think we'll ever get here, since the
290             // override attempt should produce a perm failure...
291             console.debug('override failed: ' + evt.textcode);
292             return $q.reject();
293
294         } 
295
296         // renewal auto-overrides are the same as checkout
297         if (service.auto_override_checkout_events[evt.textcode]) {
298             // user has already opted to override this type
299             // of event.  Re-run the renew w/ override.
300             options.override = true;
301             return service.renew(params, options);
302         } 
303
304         // Ask the user if they would like to override this event.
305         // Some events offer a stock override dialog, while others
306         // require additional context.
307
308         switch(evt.textcode) {
309             case 'COPY_ALERT_MESSAGE':
310                 return service.copy_alert_dialog(evt, params, options, 'renew');
311             default: 
312                 return service.override_dialog(evt, params, options, 'renew');
313         }
314     }
315
316
317     service.handle_overridable_checkin_event = function(evt, params, options) {
318
319         if (options.override) {
320             // override attempt already made and failed.
321             // NOTE: I don't think we'll ever get here, since the
322             // override attempt should produce a perm failure...
323             console.debug('override failed: ' + evt.textcode);
324             return $q.reject();
325
326         } 
327
328         if (options.suppress_checkin_popups
329             && service.checkin_suppress_overrides.indexOf(evt.textcode) > -1) {
330             // Event is suppressed.  Re-run the checkin w/ override.
331             options.override = true;
332             return service.checkin(params, options);
333         } 
334
335         // Ask the user if they would like to override this event.
336         // Some events offer a stock override dialog, while others
337         // require additional context.
338
339         switch(evt.textcode) {
340             case 'COPY_ALERT_MESSAGE':
341                 return service.copy_alert_dialog(evt, params, options, 'checkin');
342             default: 
343                 return service.override_dialog(evt, params, options, 'checkin');
344         }
345     }
346
347
348     service.handle_renew_resp = function(evt, params, options) {
349
350         var final_resp = {evt : evt, params : params, options : options};
351
352         // track the barcode regardless of whether it refers to a copy
353         evt.copy_barcode = params.copy_barcode;
354
355         // Overridable Events
356         if (service.renew_overridable_events.indexOf(evt.textcode) > -1) 
357             return service.handle_overridable_renew_event(evt, params, options);
358
359         // Other events
360         switch (evt.textcode) {
361             case 'SUCCESS':
362                 return $q.when(final_resp);
363
364             case 'COPY_IN_TRANSIT':
365             case 'PATRON_CARD_INACTIVE':
366             case 'PATRON_INACTIVE':
367             case 'PATRON_ACCOUNT_EXPIRED':
368             case 'CIRC_CLAIMS_RETURNED':
369                 return service.exit_alert(
370                     egCore.strings[evt.textcode],
371                     {barcode : params.copy_barcode}
372                 );
373
374             case 'PERM_FAILURE':
375                 return service.exit_alert(
376                     egCore.strings[evt.textcode],
377                     {permission : evt.ilsperm}
378                 );
379
380             default:
381                 return service.exit_alert(
382                     egCore.strings.CHECKOUT_FAILED_GENERIC, {
383                         barcode : params.copy_barcode,
384                         textcode : evt.textcode,
385                         desc : evt.desc
386                     }
387                 );
388         }
389     }
390
391
392     service.handle_checkout_resp = function(evt, params, options) {
393
394         var final_resp = {evt : evt, params : params, options : options};
395
396         // track the barcode regardless of whether it refers to a copy
397         evt.copy_barcode = params.copy_barcode;
398
399         // Overridable Events
400         if (service.checkout_overridable_events.indexOf(evt.textcode) > -1) 
401             return service.handle_overridable_checkout_event(evt, params, options);
402
403         // Other events
404         switch (evt.textcode) {
405             case 'SUCCESS':
406                 return $q.when(final_resp);
407
408             case 'ITEM_NOT_CATALOGED':
409                 return service.precat_dialog(params, options);
410
411             case 'OPEN_CIRCULATION_EXISTS':
412                 return service.circ_exists_dialog(evt, params, options);
413
414             case 'COPY_IN_TRANSIT':
415                 return service.copy_in_transit_dialog(evt, params, options);
416
417             case 'PATRON_CARD_INACTIVE':
418             case 'PATRON_INACTIVE':
419             case 'PATRON_ACCOUNT_EXPIRED':
420             case 'CIRC_CLAIMS_RETURNED':
421                 return service.exit_alert(
422                     egCore.strings[evt.textcode],
423                     {barcode : params.copy_barcode}
424                 );
425
426             case 'PERM_FAILURE':
427                 return service.exit_alert(
428                     egCore.strings[evt.textcode],
429                     {permission : evt.ilsperm}
430                 );
431
432             default:
433                 return service.exit_alert(
434                     egCore.strings.CHECKOUT_FAILED_GENERIC, {
435                         barcode : params.copy_barcode,
436                         textcode : evt.textcode,
437                         desc : evt.desc
438                     }
439                 );
440         }
441     }
442
443     // returns a promise resolved with the list of circ mods
444     service.get_circ_mods = function() {
445         if (egCore.env.ccm) 
446             return $q.when(egCore.env.ccm.list);
447
448         return egCore.pcrud.retrieveAll('ccm', null, {atomic : true})
449         .then(function(list) { 
450             egCore.env.absorbList(list, 'ccm');
451             return list;
452         });
453     };
454
455     // returns a promise resolved with the list of noncat types
456     service.get_noncat_types = function() {
457         if (egCore.env.cnct) 
458             return $q.when(egCore.env.cnct.list);
459
460         return egCore.pcrud.search('cnct', 
461             {owning_lib : 
462                 egCore.org.fullPath(egCore.auth.user().ws_ou(), true)}, 
463             null, {atomic : true}
464         ).then(function(list) { 
465             egCore.env.absorbList(list, 'cnct');
466             return list;
467         });
468     }
469
470     service.get_staff_penalty_types = function() {
471         if (egCore.env.csp) 
472             return $q.when(egCore.env.csp.list);
473         return egCore.pcrud.search(
474             // id <= 100 are reserved for system use
475             'csp', {id : {'>': 100}}, {}, {atomic : true})
476         .then(function(penalties) {
477             return egCore.env.absorbList(penalties, 'csp').list;
478         });
479     }
480
481     // ideally all of these data should be returned with the response,
482     // but until then, grab what we need.
483     service.flesh_response_data = function(action, evt, params, options) {
484         var promises = [];
485         var payload;
486         if (!evt || !(payload = evt.payload)) return $q.when();
487
488         promises.push(service.flesh_copy_location(payload.copy));
489         if (payload.copy) {
490             promises.push(
491                 service.flesh_copy_status(payload.copy)
492
493                 .then(function() {
494                     // copy is in transit, but no transit was delivered
495                     // in the payload.  Do this here instead of below to
496                     // ensure consistent copy status fleshiness
497                     if (!payload.transit && payload.copy.status().id() == 6) { // in-transit
498                         return service.find_copy_transit(evt, params, options)
499                         .then(function(trans) {
500                             if (trans) {
501                                 trans.source(egCore.org.get(trans.source()));
502                                 trans.dest(egCore.org.get(trans.dest()));
503                                 payload.transit = trans;
504                             }
505                         })
506                     }
507                 })
508             );
509         }
510
511         // local flesh transit
512         if (transit = payload.transit) {
513             transit.source(egCore.org.get(transit.source()));
514             transit.dest(egCore.org.get(transit.dest()));
515         } 
516
517         // TODO: renewal responses should include the patron
518         if (!payload.patron && payload.circ) {
519             promises.push(
520                 egCore.pcrud.retrieve('au', payload.circ.usr())
521                 .then(function(user) {payload.patron = user})
522             );
523         }
524
525         // extract precat values
526         evt.title = payload.record ? payload.record.title() : 
527             (payload.copy ? payload.copy.dummy_title() : null);
528
529         evt.author = payload.record ? payload.record.author() : 
530             (payload.copy ? payload.copy.dummy_author() : null);
531
532         evt.isbn = payload.record ? payload.record.isbn() : 
533             (payload.copy ? payload.copy.dummy_isbn() : null);
534
535         return $q.all(promises);
536     }
537
538     // fetches the full list of copy statuses
539     service.flesh_copy_status = function(copy) {
540         if (!copy) return $q.when();
541         if (egCore.env.ccs) 
542             return $q.when(copy.status(egCore.env.ccs.map[copy.status()]));
543         return egCore.pcrud.retrieveAll('ccs', {}, {atomic : true}).then(
544             function(list) {
545                 egCore.env.absorbList(list, 'ccs');
546                 copy.status(egCore.env.ccs.map[copy.status()]);
547             }
548         );
549     }
550
551     // there may be *many* copy locations and we may be handling items
552     // for other locations.  Fetch copy locations as-needed and cache.
553     service.flesh_copy_location = function(copy) {
554         if (!copy) return $q.when();
555         if (angular.isObject(copy.location())) return $q.when(copy);
556         if (egCore.env.acpl) {
557             if (egCore.env.acpl.map[copy.location()]) {
558                 copy.location(egCore.env.acpl.map[copy.location()]);
559                 return $q.when(copy);
560             }
561         } 
562         return egCore.pcrud.retrieve('acpl', copy.location())
563         .then(function(loc) {
564             egCore.env.absorbList([loc], 'acpl'); // append to cache
565             copy.location(loc);
566             return copy;
567         });
568     }
569
570
571     // fetch org unit addresses as needed.
572     service.get_org_addr = function(org_id, addr_type) {
573         var org = egCore.org.get(org_id);
574         var addr_id = org[addr_type]();
575
576         if (egCore.env.aoa && egCore.env.aoa.map[addr_id]) 
577             return $q.when(egCore.env.aoa.map[addr_id]); 
578
579         return egCore.pcrud.retrieve('aoa', addr_id).then(function(addr) {
580             egCore.env.absorbList([addr], 'aoa');
581             return egCore.env.aoa.map[addr_id]; 
582         });
583     }
584
585     service.exit_alert = function(msg, scope) {
586         return egAlertDialog.open(msg, scope).result.then(
587             function() {return $q.reject()});
588     }
589
590     // opens a dialog asking the user if they would like to override
591     // the returned event.
592     service.override_dialog = function(evt, params, options, action) {
593         return $modal.open({
594             templateUrl: './circ/share/t_event_override_dialog',
595             controller: 
596                 ['$scope', '$modalInstance', 
597                 function($scope, $modalInstance) {
598                 $scope.evt = evt;
599                 $scope.auto_override = 
600                     service.checkout_auto_override_after_first.indexOf(evt.textcode) > -1;
601                 $scope.copy_barcode = params.copy_barcode; // may be null
602                 $scope.ok = function() { $modalInstance.close() }
603                 $scope.cancel = function ($event) { 
604                     $modalInstance.dismiss();
605                     $event.preventDefault();
606                 }
607             }]
608         }).result.then(
609             function() {
610                 options.override = true;
611
612                 if (action == 'checkin') {
613                     return service.checkin(params, options);
614                 }
615
616                 // checkout/renew support override-after-first
617                 if (service.checkout_auto_override_after_first.indexOf(evt.textcode) > -1)
618                     service.auto_override_checkout_events[evt.textcode] = true;
619
620                 return service[action](params, options);
621             }
622         );
623     }
624
625     service.copy_not_avail_dialog = function(evt, params, options) {
626         return $modal.open({
627             templateUrl: './circ/share/t_copy_not_avail_dialog',
628             controller: 
629                        ['$scope','$modalInstance','copyStatus',
630                 function($scope , $modalInstance , copyStatus) {
631                 $scope.copyStatus = copyStatus;
632                 $scope.ok = function() {$modalInstance.close()}
633                 $scope.cancel = function() {$modalInstance.dismiss()}
634             }],
635             resolve : {
636                 copyStatus : function() {
637                     return egCore.pcrud.retrieve(
638                         'ccs', evt.payload.status());
639                 }
640             }
641         }).result.then(
642             function() {
643                 options.override = true;
644                 return service.checkout(params, options);
645             }
646         );
647     }
648
649     // Opens a dialog allowing the user to fill in the desired non-cat count.
650     // Unlike other dialogs, which kickoff circ actions internally
651     // as a result of events, this dialog does not kick off any circ
652     // actions. It just collects the count and and resolves the promise.
653     //
654     // This assumes the caller has already handled the noncat-type
655     // selection and just needs to collect the count info.
656     service.noncat_dialog = function(params, options) {
657         var noncatMax = 99; // hard-coded max
658         
659         // the caller should presumably have fetched the noncat_types via
660         // our API already, but fetch them again (from cache) to be safe.
661         return service.get_noncat_types().then(function() {
662
663             params.noncat = true;
664             var type = egCore.env.cnct.map[params.noncat_type];
665
666             return $modal.open({
667                 templateUrl: './circ/share/t_noncat_dialog',
668                 controller: 
669                     ['$scope', '$modalInstance',
670                     function($scope, $modalInstance) {
671                     $scope.focusMe = true;
672                     $scope.type = type;
673                     $scope.count = 1;
674                     $scope.noncatMax = noncatMax;
675                     $scope.ok = function(count) { $modalInstance.close(count) }
676                     $scope.cancel = function ($event) { 
677                         $modalInstance.dismiss() 
678                         $event.preventDefault();
679                     }
680                 }],
681             }).result.then(
682                 function(count) {
683                     if (count && count > 0 && count <= noncatMax) { 
684                         // NOTE: in Chrome, form validation ensure a valid number
685                         params.noncat_count = count;
686                         return $q.when(params);
687                     } else {
688                         return $q.reject();
689                     }
690                 }
691             );
692         });
693     }
694
695     // Opens a dialog allowing the user to fill in pre-cat copy info.
696     service.precat_dialog = function(params, options) {
697
698         return $modal.open({
699             templateUrl: './circ/share/t_precat_dialog',
700             controller: 
701                 ['$scope', '$modalInstance', 'circMods',
702                 function($scope, $modalInstance, circMods) {
703                 $scope.focusMe = true;
704                 $scope.precatArgs = {
705                     copy_barcode : params.copy_barcode,
706                     circ_modifier : circMods.length ? circMods[0].code() : null
707                 };
708                 $scope.circModifiers = circMods;
709                 $scope.ok = function(args) { $modalInstance.close(args) }
710                 $scope.cancel = function () { $modalInstance.dismiss() }
711             }],
712             resolve : {
713                 circMods : function() { 
714                     return service.get_circ_mods();
715                 }
716             }
717         }).result.then(
718             function(args) {
719                 if (!args || !args.dummy_title) return $q.reject();
720                 angular.forEach(args, function(val, key) {params[key] = val});
721                 params.precat = true;
722                 return service.checkout(params, options);
723             }
724         );
725     }
726
727     // find the open transit for the given copy barcode; flesh the org
728     // units locally.
729     service.find_copy_transit = function(evt, params, options) {
730
731         if (evt && evt.payload && evt.payload.transit)
732             return $q.when(evt.payload.transit);
733
734          return egCore.pcrud.search('atc',
735             {   dest_recv_time : null},
736             {   flesh : 1, 
737                 flesh_fields : {atc : ['target_copy']},
738                 join : {
739                     acp : {
740                         filter : {
741                             barcode : params.copy_barcode,
742                             deleted : 'f'
743                         }
744                     }
745                 },
746                 limit : 1,
747                 order_by : {atc : 'source_send_time desc'}, 
748             }
749         ).then(function(transit) {
750             transit.source(egCore.org.get(transit.source()));
751             transit.dest(egCore.org.get(transit.dest()));
752             return transit;
753         });
754     }
755
756     service.copy_in_transit_dialog = function(evt, params, options) {
757         return $modal.open({
758             templateUrl: './circ/share/t_copy_in_transit_dialog',
759             controller: 
760                        ['$scope','$modalInstance','transit',
761                 function($scope , $modalInstance , transit) {
762                 $scope.transit = transit;
763                 $scope.ok = function() { $modalInstance.close(transit) }
764                 $scope.cancel = function() { $modalInstance.dismiss() }
765             }],
766             resolve : {
767                 // fetch the conflicting open transit w/ fleshed copy
768                 transit : function() {
769                     return service.find_copy_transit(evt, params, options);
770                 }
771             }
772         }).result.then(
773             function(transit) {
774                 // user chose to abort the transit then checkout
775                 return service.abort_transit(transit.id())
776                 .then(function() {
777                     return service.checkout(params, options);
778                 });
779             }
780         );
781     }
782
783     service.abort_transit = function(transit_id) {
784         return egCore.net.request(
785             'open-ils.circ',
786             'open-ils.circ.transit.abort',
787             egCore.auth.token(), {transitid : transit_id}
788         ).then(function(resp) {
789             if (evt = egCore.evt.parse(resp)) {
790                 alert(evt);
791                 return $q.reject();
792             }
793             return $q.when();
794         });
795     }
796
797     service.last_copy_circ = function(copy_id) {
798         return egCore.pcrud.search('circ', 
799             {target_copy : copy_id},
800             {order_by : {circ : 'xact_start desc' }, limit : 1}
801         );
802     }
803
804     service.circ_exists_dialog = function(evt, params, options) {
805
806         var openCirc = evt.payload.old_circ;
807         var sameUser = openCirc.usr() == params.patron_id;
808         
809         return $modal.open({
810             templateUrl: './circ/share/t_circ_exists_dialog',
811             controller: 
812                        ['$scope','$modalInstance',
813                 function($scope , $modalInstance) {
814                 $scope.circDate = openCirc.xact_start();
815                 $scope.sameUser = sameUser;
816                 $scope.ok = function() { $modalInstance.close() }
817                 $scope.cancel = function($event) { 
818                     $modalInstance.dismiss();
819                     $event.preventDefault(); // form, avoid calling ok();
820                 }
821             }]
822         }).result.then(
823             function() {
824                 
825                 return service.checkin(
826                     {barcode : params.copy_barcode, noop : true}
827                 ).then(function(checkin_resp) {
828                     if (checkin_resp.evt.textcode == 'SUCCESS') {
829                         return service.checkout(params, options);
830                     } else {
831                         alert(egCore.evt.parse(evt));
832                         return $q.reject();
833                     }
834                 });
835             }
836         );
837     }
838
839     service.batch_backdate = function(circ_ids, backdate) {
840         return egCore.net.request(
841             'open-ils.circ',
842             'open-ils.circ.post_checkin_backdate.batch',
843             egCore.auth.token(), circ_ids, backdate);
844     }
845
846     service.backdate_dialog = function(circ_ids) {
847         return $modal.open({
848             templateUrl: './circ/share/t_backdate_dialog',
849             controller: 
850                        ['$scope','$modalInstance',
851                 function($scope , $modalInstance) {
852
853                 var today = new Date();
854                 $scope.dialog = {
855                     num_circs : circ_ids.length,
856                     num_processed : 0,
857                     backdate : today
858                 }
859
860                 $scope.$watch('dialog.backdate', function(newval) {
861                     if (newval && newval > today) 
862                         $scope.dialog.backdate = today;
863                 });
864
865
866                 $scope.cancel = function() { 
867                     $modalInstance.dismiss();
868                 }
869
870                 $scope.ok = function() { 
871
872                     var bd = $scope.dialog.backdate.toISOString().replace(/T.*/,'');
873                     service.batch_backdate(circ_ids, bd)
874                     .then(
875                         function() { // on complete
876                             $modalInstance.close({backdate : bd});
877                         },
878                         null,
879                         function(resp) { // on response
880                             console.debug('backdate returned ' + resp);
881                             if (resp == '1') {
882                                 $scope.num_processed++;
883                             } else {
884                                 console.error(egCore.evt.parse(resp));
885                             }
886                         }
887                     );
888                 }
889             }]
890         }).result;
891     }
892
893     service.mark_claims_returned = function(barcode, date, override) {
894
895         var method = 'open-ils.circ.circulation.set_claims_returned';
896         if (override) method += '.override';
897
898         console.debug('claims returned ' + method);
899
900         return egCore.net.request(
901             'open-ils.circ', method, egCore.auth.token(),
902             {barcode : barcode, backdate : date})
903
904         .then(function(resp) {
905
906             if (resp == 1) { // success
907                 console.debug('claims returned succeeded for ' + barcode);
908                 return barcode;
909
910             } else if (evt = egCore.evt.parse(resp)) {
911                 console.debug('claims returned failed: ' + evt.toString());
912
913                 if (evt.textcode == 'PATRON_EXCEEDS_CLAIMS_RETURN_COUNT') {
914                     // TODO check perms before offering override option?
915
916                     if (override) return;// just to be safe
917
918                     return egConfirmDialog.open(
919                         egCore.strings.TOO_MANY_CLAIMS_RETURNED, '', {}
920                     ).result.then(function() {
921                         return service.mark_claims_returned(barcode, date, true);
922                     });
923                 }
924
925                 if (evt.textcode == 'PERM_FAILURE') {
926                     console.error('claims returned permission denied')
927                     // TODO: auth override dialog?
928                 }
929             }
930         });
931     }
932
933     service.mark_claims_returned_dialog = function(copy_barcodes) {
934         if (!copy_barcodes.length) return;
935
936         return $modal.open({
937             templateUrl: './circ/share/t_mark_claims_returned_dialog',
938             controller: 
939                        ['$scope','$modalInstance',
940                 function($scope , $modalInstance) {
941
942                 var today = new Date();
943                 $scope.args = {
944                     barcodes : copy_barcodes,
945                     date : today
946                 };
947
948                 $scope.$watch('args.date', function(newval) {
949                     if (newval && newval > today) 
950                         $scope.args.backdate = today;
951                 });
952
953                 $scope.cancel = function() {$modalInstance.dismiss()}
954                 $scope.ok = function() { 
955
956                     var date = $scope.args.date.toISOString().replace(/T.*/,'');
957
958                     var deferred = $q.defer();
959
960                     // serialize the action on each barcode so that the 
961                     // caller will never see multiple alerts at the same time.
962                     function mark_one() {
963                         var bc = copy_barcodes.pop();
964                         if (!bc) {
965                             deferred.resolve();
966                             $modalInstance.close();
967                             return;
968                         }
969
970                         // finally -> continue even when one fails
971                         service.mark_claims_returned(bc, date)
972                         .finally(function(barcode) {
973                             if (barcode) deferred.notify(barcode);
974                             mark_one();
975                         });
976                     }
977                     mark_one(); // kick it off
978                     return deferred.promise;
979                 }
980             }]
981         }).result;
982     }
983
984     // serially checks in each barcode with claims_never_checked_out set
985     // returns promise, notified on each barcode, resolved after all
986     // checkins are complete.
987     service.mark_claims_never_checked_out = function(barcodes) {
988         if (!barcodes.length) return;
989
990         var deferred = $q.defer();
991         egConfirmDialog.open(
992             egCore.strings.MARK_NEVER_CHECKED_OUT, '', {barcodes : barcodes}
993
994         ).result.then(function() {
995             function mark_one() {
996                 var bc = barcodes.pop();
997
998                 if (!bc) { // all done
999                     deferred.resolve();
1000                     return;
1001                 }
1002
1003                 service.checkin(
1004                     {claims_never_checked_out : true, copy_barcode : bc})
1005                 .finally(function() { 
1006                     deferred.notify(bc);
1007                     mark_one();
1008                 })
1009             }
1010             mark_one();
1011         });
1012
1013         return deferred.promise;
1014     }
1015
1016     service.mark_damaged = function(copy_ids) {
1017         return egConfirmDialog.open(
1018             egCore.strings.MARK_DAMAGED_CONFIRM, '',
1019             {   num_items : copy_ids.length,
1020                 ok : function() {},
1021                 cancel : function() {}
1022             }
1023
1024         ).result.then(function() {
1025             var promises = [];
1026             angular.forEach(copy_ids, function(copy_id) {
1027                 promises.push(
1028                     egCore.net.request(
1029                         'open-ils.circ',
1030                         'open-ils.circ.mark_item_damaged',
1031                         egCore.auth.token(), copy_id
1032                     ).then(function(resp) {
1033                         if (evt = egCore.evt.parse(resp)) {
1034                             console.error('mark damaged failed: ' + evt);
1035                         }
1036                     })
1037                 );
1038             });
1039
1040             return $q.all(promises);
1041         });
1042     }
1043
1044     service.mark_missing = function(copy_ids) {
1045         return egConfirmDialog.open(
1046             egCore.strings.MARK_MISSING_CONFIRM, '',
1047             {   num_items : copy_ids.length,
1048                 ok : function() {},
1049                 cancel : function() {}
1050             }
1051         ).result.then(function() {
1052             var promises = [];
1053             angular.forEach(copy_ids, function(copy_id) {
1054                 promises.push(
1055                     egCore.net.request(
1056                         'open-ils.circ',
1057                         'open-ils.circ.mark_item_missing',
1058                         egCore.auth.token(), copy_id
1059                     ).then(function(resp) {
1060                         if (evt = egCore.evt.parse(resp)) {
1061                             console.error('mark missing failed: ' + evt);
1062                         }
1063                     })
1064                 );
1065             });
1066
1067             return $q.all(promises);
1068         });
1069     }
1070
1071
1072
1073     // Mark circulations as lost via copy barcode.  As each item is 
1074     // processed, the returned promise is notified of the barcode.
1075     // No confirmation dialog is presented.
1076     service.mark_lost = function(copy_barcodes) {
1077         var deferred = $q.defer();
1078         var promises = [];
1079
1080         angular.forEach(copy_barcodes, function(barcode) {
1081             promises.push(
1082                 egCore.net.request(
1083                     'open-ils.circ',
1084                     'open-ils.circ.circulation.set_lost',
1085                     egCore.auth.token(), {barcode : barcode}
1086                 ).then(function(resp) {
1087                     if (evt = egCore.evt.parse(resp)) {
1088                         console.error("Mark lost failed: " + evt.toString());
1089                         return;
1090                     }
1091                     // inform the caller as each item is processed
1092                     deferred.notify(barcode);
1093                 })
1094             );
1095         });
1096
1097         $q.all(promises).then(function() {deferred.resolve()});
1098         return deferred.promise;
1099     }
1100
1101     service.abort_transits = function(transit_ids) {
1102         return egConfirmDialog.open(
1103             egCore.strings.ABORT_TRANSIT_CONFIRM, '',
1104             {   num_transits : transit_ids.length,
1105                 ok : function() {},
1106                 cancel : function() {}
1107             }
1108
1109         ).result.then(function() {
1110             var promises = [];
1111             angular.forEach(transit_ids, function(transit_id) {
1112                 promises.push(
1113                     egCore.net.request(
1114                         'open-ils.circ',
1115                         'open-ils.circ.transit.abort',
1116                         egCore.auth.token(), {transitid : transit_id}
1117                     ).then(function(resp) {
1118                         if (evt = egCore.evt.parse(resp)) {
1119                             console.error('abort transit failed: ' + evt);
1120                         }
1121                     })
1122                 );
1123             });
1124
1125             return $q.all(promises);
1126         });
1127     }
1128
1129
1130
1131     // alert when copy location alert_message is set.
1132     // This does not affect processing, it only produces a click-through
1133     service.handle_checkin_loc_alert = function(evt, params, options) {
1134
1135         var copy = evt && evt.payload ? evt.payload.copy : null;
1136
1137         if (copy && !options.suppress_checkin_popups
1138             && copy.location().checkin_alert() == 't') {
1139
1140             return egAlertDialog.open(
1141                 egCore.strings.LOCATION_ALERT_MSG, {copy : copy}).result;
1142         }
1143
1144         return $q.when();
1145     }
1146
1147     service.handle_checkin_resp = function(evt, params, options) {
1148
1149         var final_resp = {evt : evt, params : params, options : options};
1150
1151         var copy, hold, transit;
1152         if (evt.payload) {
1153             copy = evt.payload.copy;
1154             hold = evt.payload.hold;
1155             transit = evt.payload.transit;
1156         }
1157
1158         // track the barcode regardless of whether it's valid
1159         evt.copy_barcode = params.copy_barcode;
1160
1161         console.debug('checkin event ' + evt.textcode);
1162
1163         if (service.checkin_overridable_events.indexOf(evt.textcode) > -1) 
1164             return service.handle_overridable_checkin_event(evt, params, options);
1165
1166         switch (evt.textcode) {
1167
1168             case 'SUCCESS':
1169             case 'NO_CHANGE':
1170
1171                 switch(Number(copy.status().id())) {
1172
1173                     case 0: /* AVAILABLE */                                        
1174                     case 4: /* MISSING */                                          
1175                     case 7: /* RESHELVING */ 
1176
1177                         // see if the copy location requires an alert
1178                         return service.handle_checkin_loc_alert(evt, params, options)
1179                         .then(function() {return final_resp});
1180
1181                     case 8: /* ON HOLDS SHELF */
1182
1183                         
1184                         if (hold) {
1185
1186                             if (hold.pickup_lib() == egCore.auth.user().ws_ou()) {
1187                                 // inform user if the item is on the local holds shelf
1188                             
1189                                 evt.route_to = egCore.strings.ROUTE_TO_HOLDS_SHELF;
1190                                 return service.route_dialog(
1191                                     './circ/share/t_hold_shelf_dialog', 
1192                                     evt, params, options
1193                                 ).then(function() { return final_resp });
1194
1195                             } else {
1196                                 // normally, if the hold was on the shelf at a 
1197                                 // different location, it would be put into 
1198                                 // transit, resulting in a ROUTE_ITEM event.
1199                                 return $q.when(final_resp);
1200                             }
1201                         } else {
1202
1203                             console.error('checkin: item on holds shelf, '
1204                                 + 'but hold info not returned from checkin');
1205                             return $q.when(final_resp);
1206                         }
1207
1208                     case 11: /* CATALOGING */
1209                         evt.route_to = egCore.strings.ROUTE_TO_CATALOGING;
1210                         return $q.when(final_resp);
1211
1212                     case 15: /* ON_RESERVATION_SHELF */
1213                         // TODO: show booking reservation dialog
1214                         return $q.when(final_resp);
1215
1216                     default:
1217                         console.error('Unhandled checkin copy status: ' 
1218                             + copy.status().id() + ' : ' + copy.status().name());
1219                         return $q.when(final_resp);
1220                 }
1221                 
1222             case 'ROUTE_ITEM':
1223                 return service.route_dialog(
1224                     './circ/share/t_transit_dialog', 
1225                     evt, params, options
1226                 ).then(function() { return final_resp });
1227
1228             case 'ASSET_COPY_NOT_FOUND':
1229                 return egAlertDialog.open(
1230                     egCore.strings.UNCAT_ALERT_DIALOG, params)
1231                     .result.then(function() {return final_resp});
1232
1233             case 'ITEM_NOT_CATALOGED':
1234                 evt.route_to = egCore.strings.ROUTE_TO_CATALOGING;
1235                 if (options.no_precat_alert) 
1236                     return $q.when(final_resp);
1237                 return egAlertDialog.open(
1238                     egCore.strings.PRECAT_CHECKIN_MSG, params)
1239                     .result.then(function() {return final_resp});
1240
1241             default:
1242                 console.warn('unhandled checkin response : ' + evt.textcode);
1243                 return $q.when(final_resp);
1244         }
1245     }
1246
1247     // collect transit, address, and hold info that's not already
1248     // included in responses.
1249     service.collect_route_data = function(tmpl, evt, params, options) {
1250         var promises = [];
1251         var data = {};
1252
1253         if (evt.org && !tmpl.match(/hold_shelf/)) {
1254             promises.push(
1255                 service.get_org_addr(evt.org, 'holds_address')
1256                 .then(function(addr) { data.address = addr })
1257             );
1258         }
1259
1260         if (evt.payload.hold) {
1261             promises.push(
1262                 egCore.pcrud.retrieve('au', 
1263                     evt.payload.hold.usr(), {
1264                         flesh : 1,
1265                         flesh_fields : {'au' : ['card']}
1266                     }
1267                 ).then(function(patron) {data.patron = patron})
1268             );
1269         }
1270
1271         if (!tmpl.match(/hold_shelf/)) {
1272             promises.push(
1273                 service.find_copy_transit(evt, params, options)
1274                 .then(function(trans) {data.transit = trans})
1275             );
1276         }
1277
1278         return $q.all(promises).then(function() { return data });
1279     }
1280
1281     service.route_dialog = function(tmpl, evt, params, options) {
1282
1283         return service.collect_route_data(tmpl, evt, params, options)
1284         .then(function(data) {
1285             
1286             // All actions flow from the print data
1287
1288             var print_context = {
1289                 copy : egCore.idl.toHash(evt.payload.copy),
1290                 title : evt.title,
1291                 author : evt.author
1292             }
1293
1294             if (data.transit) {
1295                 // route_dialog includes the "route to holds shelf" 
1296                 // dialog, which has no transit
1297                 print_context.transit = egCore.idl.toHash(data.transit);
1298                 print_context.dest_address = egCore.idl.toHash(data.address);
1299                 print_context.dest_location =
1300                     egCore.idl.toHash(egCore.org.get(data.transit.dest()));
1301             }
1302
1303             if (data.patron) {
1304                 print_context.hold = egCore.idl.toHash(evt.payload.hold);
1305                 print_context.patron = egCore.idl.toHash(data.patron);
1306             }
1307
1308             function print_transit() {
1309                 var template = data.transit ? 
1310                     (data.patron ? 'hold_transit_slip' : 'transit_slip') :
1311                     'hold_shelf_slip';
1312
1313                 return egCore.print.print({
1314                     context : 'default', 
1315                     template : template, 
1316                     scope : print_context
1317                 });
1318             }
1319
1320             // when auto-print is on, skip the dialog and go straight
1321             // to printing.
1322             if (options.auto_print_holds_transits) 
1323                 return print_transit();
1324
1325             return $modal.open({
1326                 templateUrl: tmpl,
1327                 controller: [
1328                             '$scope','$modalInstance',
1329                     function($scope , $modalInstance) {
1330
1331                     $scope.today = new Date();
1332
1333                     // copy the print scope into the dialog scope
1334                     angular.forEach(print_context, function(val, key) {
1335                         $scope[key] = val;
1336                     });
1337
1338                     $scope.ok = function() {$modalInstance.close()}
1339
1340                     $scope.print = function() { 
1341                         $modalInstance.close();
1342                         print_transit();
1343                     }
1344                 }]
1345
1346             }).result;
1347         });
1348     }
1349
1350     // action == what action to take if the user confirms the alert
1351     service.copy_alert_dialog = function(evt, params, options, action) {
1352         return egConfirmDialog.open(
1353             egCore.strings.COPY_ALERT_MSG_DIALOG_TITLE, 
1354             evt.payload,  // payload == alert message text
1355             {   copy_barcode : params.copy_barcode,
1356                 ok : function() {},
1357                 cancel : function() {}
1358             }
1359         ).result.then(function() {
1360             options.override = true;
1361             return service[action](params, options);
1362         });
1363     }
1364
1365     // check the barcode.  If it's no good, show the warning dialog
1366     // Resolves on success, rejected on error
1367     service.test_barcode = function(bc) {
1368
1369         var ok = service.check_barcode(bc);
1370         if (ok) return $q.when();
1371
1372         return $modal.open({
1373             templateUrl: './circ/share/t_bad_barcode_dialog',
1374             controller: 
1375                 ['$scope', '$modalInstance', 
1376                 function($scope, $modalInstance) {
1377                 $scope.barcode = bc;
1378                 $scope.ok = function() { $modalInstance.close() }
1379                 $scope.cancel = function() { $modalInstance.dismiss() }
1380             }]
1381         }).result;
1382     }
1383
1384     // check() and checkdigit() copied directly 
1385     // from chrome/content/util/barcode.js
1386
1387     service.check_barcode = function(bc) {
1388         if (bc != Number(bc)) return false;
1389         bc = bc.toString();
1390         // "16.00" == Number("16.00"), but the . is bad.
1391         // Throw out any barcode that isn't just digits
1392         if (bc.search(/\D/) != -1) return false;
1393         var last_digit = bc.substr(bc.length-1);
1394         var stripped_barcode = bc.substr(0,bc.length-1);
1395         return service.barcode_checkdigit(stripped_barcode).toString() == last_digit;
1396     }
1397
1398     service.barcode_checkdigit = function(bc) {
1399         var reverse_barcode = bc.toString().split('').reverse();
1400         var check_sum = 0; var multiplier = 2;
1401         for (var i = 0; i < reverse_barcode.length; i++) {
1402             var digit = reverse_barcode[i];
1403             var product = digit * multiplier; product = product.toString();
1404             var temp_sum = 0;
1405             for (var j = 0; j < product.length; j++) {
1406                 temp_sum += Number( product[j] );
1407             }
1408             check_sum += Number( temp_sum );
1409             multiplier = ( multiplier == 2 ? 1 : 2 );
1410         }
1411         check_sum = check_sum.toString();
1412         var next_multiple_of_10 = (check_sum.match(/(\d*)\d$/)[1] * 10) + 10;
1413         var check_digit = next_multiple_of_10 - Number(check_sum);
1414         if (check_digit == 10) check_digit = 0;
1415         return check_digit;
1416     }
1417
1418     service.create_penalty = function(user_id) {
1419         return $modal.open({
1420             templateUrl: './circ/share/t_new_message_dialog',
1421             controller: 
1422                    ['$scope','$modalInstance','staffPenalties',
1423             function($scope , $modalInstance , staffPenalties) {
1424                 $scope.focusNote = true;
1425                 $scope.penalties = staffPenalties;
1426                 $scope.args = {penalty : 21}; // default to Note
1427                 $scope.setPenalty = function(id) {
1428                     args.penalty = id;
1429                 }
1430                 $scope.ok = function(count) { $modalInstance.close($scope.args) }
1431                 $scope.cancel = function($event) { 
1432                     $modalInstance.dismiss();
1433                     $event.preventDefault();
1434                 }
1435             }],
1436             resolve : { staffPenalties : service.get_staff_penalty_types }
1437         }).result.then(
1438             function(args) {
1439                 var pen = new egCore.idl.ausp();
1440                 pen.usr(user_id);
1441                 pen.org_unit(egCore.auth.user().ws_ou());
1442                 pen.note(args.note);
1443                 pen.standing_penalty(args.penalty);
1444                 pen.staff(egCore.auth.user().id());
1445                 pen.set_date('now');
1446                 return egCore.pcrud.create(pen);
1447             }
1448         );
1449     }
1450
1451     // assumes, for now anyway,  penalty type is fleshed onto usr_penalty.
1452     service.edit_penalty = function(usr_penalty) {
1453         return $modal.open({
1454             templateUrl: './circ/share/t_new_message_dialog',
1455             controller: 
1456                    ['$scope','$modalInstance','staffPenalties',
1457             function($scope , $modalInstance , staffPenalties) {
1458                 $scope.focusNote = true;
1459                 $scope.penalties = staffPenalties;
1460                 $scope.args = {
1461                     penalty : usr_penalty.standing_penalty().id(),
1462                     note : usr_penalty.note()
1463                 }
1464                 $scope.setPenalty = function(id) { args.penalty = id; }
1465                 $scope.ok = function(count) { $modalInstance.close($scope.args) }
1466                 $scope.cancel = function($event) { 
1467                     $modalInstance.dismiss();
1468                     $event.preventDefault();
1469                 }
1470             }],
1471             resolve : { staffPenalties : service.get_staff_penalty_types }
1472         }).result.then(
1473             function(args) {
1474                 usr_penalty.note(args.note);
1475                 usr_penalty.standing_penalty(args.penalty);
1476                 return egCore.pcrud.update(usr_penalty);
1477             }
1478         );
1479     }
1480
1481     return service;
1482
1483 }]);
1484
1485