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