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