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