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