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