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