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