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