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