]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/services/circ.js
ecbf03af24221e429a8fa40d379d6eacf744558a
[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', 'has_precat_perm',
948                 function($scope, $uibModalInstance, circMods, has_precat_perm) {
949                 $scope.focusMe = true;
950                 $scope.precatArgs = {
951                     copy_barcode : params.copy_barcode
952                 };
953
954                 $scope.can_create_precats = has_precat_perm;
955                 $scope.circModifiers = circMods;
956                 $scope.ok = function(args) { $uibModalInstance.close(args) }
957                 $scope.cancel = function () { $uibModalInstance.dismiss() }
958
959                 // use this function as a keydown handler on form
960                 // elements that should not submit the form on enter.
961                 $scope.preventSubmit = function($event) {
962                     if ($event.keyCode == 13)
963                         $event.preventDefault();
964                 }
965             }],
966             resolve : {
967                 circMods : function() { return service.get_circ_mods(); },
968                 has_precat_perm : function(){ return egCore.perm.hasPermHere('CREATE_PRECAT'); }
969             }
970         }).result.then(
971             function(args) {
972                 if (!args || !args.dummy_title) return $q.reject();
973                 if(args.circ_modifier == "") args.circ_modifier = null;
974                 angular.forEach(args, function(val, key) {params[key] = val});
975                 params.precat = true;
976                 return service.checkout(params, options);
977             }
978         );
979     }
980
981     // find the open transit for the given copy barcode; flesh the org
982     // units locally.
983     service.find_copy_transit = function(evt, params, options) {
984         if (angular.isArray(evt)) evt = evt[0];
985
986         // NOTE: evt.payload.transit may exist, but it's not necessarily
987         // the transit we want, since a transit close + open in the API
988         // returns the closed transit.
989
990          return egCore.pcrud.search('atc',
991             {   dest_recv_time : null, cancel_time : null},
992             {   flesh : 1, 
993                 flesh_fields : {atc : ['target_copy']},
994                 join : {
995                     acp : {
996                         filter : {
997                             barcode : params.copy_barcode,
998                             deleted : 'f'
999                         }
1000                     }
1001                 },
1002                 limit : 1,
1003                 order_by : {atc : 'source_send_time desc'}, 
1004             }, {authoritative : true}
1005         ).then(function(transit) {
1006             transit.source(egCore.org.get(transit.source()));
1007             transit.dest(egCore.org.get(transit.dest()));
1008             return transit;
1009         });
1010     }
1011
1012     service.copy_in_transit_dialog = function(evt, params, options) {
1013         if (angular.isArray(evt)) evt = evt[0];
1014         return $uibModal.open({
1015             templateUrl: './circ/share/t_copy_in_transit_dialog',
1016             backdrop: 'static',
1017             controller: 
1018                        ['$scope','$uibModalInstance','transit',
1019                 function($scope , $uibModalInstance , transit) {
1020                 $scope.transit = transit;
1021                 $scope.ok = function() { $uibModalInstance.close(transit) }
1022                 $scope.cancel = function() { $uibModalInstance.dismiss() }
1023             }],
1024             resolve : {
1025                 // fetch the conflicting open transit w/ fleshed copy
1026                 transit : function() {
1027                     return service.find_copy_transit(evt, params, options);
1028                 }
1029             }
1030         }).result.then(
1031             function(transit) {
1032                 // user chose to abort the transit then checkout
1033                 return service.abort_transit(transit.id())
1034                 .then(function() {
1035                     return service.checkout(params, options);
1036                 });
1037             }
1038         );
1039     }
1040
1041     service.abort_transit = function(transit_id) {
1042         return egCore.net.request(
1043             'open-ils.circ',
1044             'open-ils.circ.transit.abort',
1045             egCore.auth.token(), {transitid : transit_id}
1046         ).then(function(resp) {
1047             if (evt = egCore.evt.parse(resp)) {
1048                 alert(evt);
1049                 return $q.reject();
1050             }
1051             return $q.when();
1052         });
1053     }
1054
1055     service.last_copy_circ = function(copy_id) {
1056         return egCore.pcrud.search('circ', 
1057             {target_copy : copy_id},
1058             {order_by : {circ : 'xact_start desc' }, limit : 1}
1059         );
1060     }
1061
1062     service.circ_exists_dialog = function(evt, params, options) {
1063         if (angular.isArray(evt)) evt = evt[0];
1064
1065         if (!evt.payload.old_circ) {
1066             return egCore.net.request(
1067                 'open-ils.search',
1068                 'open-ils.search.asset.copy.fleshed2.find_by_barcode',
1069                 params.copy_barcode
1070             ).then(function(resp){
1071                 console.log(resp);
1072                 if (egCore.evt.parse(resp)) {
1073                     console.error(egCore.evt.parse(resp));
1074                 } else {
1075                     return egCore.net.request(
1076                          'open-ils.circ',
1077                          'open-ils.circ.copy_checkout_history.retrieve',
1078                          egCore.auth.token(), resp.id(), 1
1079                     ).then( function (circs) {
1080                         evt.payload.old_circ = circs[0];
1081                         return service.circ_exists_dialog_impl( evt, params, options );
1082                     });
1083                 }
1084             });
1085         } else {
1086             return service.circ_exists_dialog_impl( evt, params, options );
1087         }
1088     },
1089
1090     service.circ_exists_dialog_impl = function (evt, params, options) {
1091
1092         var openCirc = evt.payload.old_circ;
1093         var sameUser = openCirc.usr() == params.patron_id;
1094         
1095         return $uibModal.open({
1096             templateUrl: './circ/share/t_circ_exists_dialog',
1097             backdrop: 'static',
1098             controller: 
1099                        ['$scope','$uibModalInstance',
1100                 function($scope , $uibModalInstance) {
1101                 $scope.args = {forgive_fines : false};
1102                 $scope.circDate = openCirc.xact_start();
1103                 $scope.sameUser = sameUser;
1104                 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1105                 $scope.cancel = function($event) { 
1106                     $uibModalInstance.dismiss();
1107                     $event.preventDefault(); // form, avoid calling ok();
1108                 }
1109             }]
1110         }).result.then(
1111             function(args) {
1112                 if (sameUser) {
1113                     params.void_overdues = args.forgive_fines;
1114                     options.sameCopyCheckout = true;
1115                     return service.renew(params, options);
1116                 }
1117
1118                 return service.checkin({
1119                     barcode : params.copy_barcode,
1120                     noop : true,
1121                     void_overdues : args.forgive_fines
1122                 }).then(function(checkin_resp) {
1123                     if (checkin_resp.evt[0].textcode == 'SUCCESS') {
1124                         return service.checkout(params, options);
1125                     } else {
1126                         alert(egCore.evt.parse(checkin_resp.evt[0]));
1127                         return $q.reject();
1128                     }
1129                 });
1130             }
1131         );
1132     }
1133
1134     service.batch_backdate = function(circ_ids, backdate) {
1135         return egCore.net.request(
1136             'open-ils.circ',
1137             'open-ils.circ.post_checkin_backdate.batch',
1138             egCore.auth.token(), circ_ids, backdate);
1139     }
1140
1141     service.backdate_dialog = function(circ_ids) {
1142         return $uibModal.open({
1143             templateUrl: './circ/share/t_backdate_dialog',
1144             backdrop: 'static',
1145             controller: 
1146                        ['$scope','$uibModalInstance',
1147                 function($scope , $uibModalInstance) {
1148
1149                 var today = new Date();
1150                 $scope.dialog = {
1151                     num_circs : circ_ids.length,
1152                     num_processed : 0,
1153                     backdate : today
1154                 }
1155
1156                 $scope.$watch('dialog.backdate', function(newval) {
1157                     if (newval && newval > today) 
1158                         $scope.dialog.backdate = today;
1159                 });
1160
1161
1162                 $scope.cancel = function() { 
1163                     $uibModalInstance.dismiss();
1164                 }
1165
1166                 $scope.ok = function() { 
1167
1168                     var bd = $scope.dialog.backdate.toISOString().replace(/T.*/,'');
1169                     service.batch_backdate(circ_ids, bd)
1170                     .then(
1171                         function() { // on complete
1172                             $uibModalInstance.close({backdate : bd});
1173                         },
1174                         null,
1175                         function(resp) { // on response
1176                             console.debug('backdate returned ' + resp);
1177                             if (resp == '1') {
1178                                 $scope.num_processed++;
1179                             } else {
1180                                 console.error(egCore.evt.parse(resp));
1181                             }
1182                         }
1183                     );
1184                 }
1185             }]
1186         }).result;
1187     }
1188
1189     service.mark_claims_returned = function(barcode, date, override) {
1190
1191         var method = 'open-ils.circ.circulation.set_claims_returned';
1192         if (override) method += '.override';
1193
1194         console.debug('claims returned ' + method);
1195
1196         return egCore.net.request(
1197             'open-ils.circ', method, egCore.auth.token(),
1198             {barcode : barcode, backdate : date})
1199
1200         .then(function(resp) {
1201
1202             if (resp == 1) { // success
1203                 console.debug('claims returned succeeded for ' + barcode);
1204                 return barcode;
1205
1206             } else if (evt = egCore.evt.parse(resp)) {
1207                 console.debug('claims returned failed: ' + evt.toString());
1208
1209                 if (evt.textcode == 'PATRON_EXCEEDS_CLAIMS_RETURN_COUNT') {
1210                     // TODO check perms before offering override option?
1211
1212                     if (override) return;// just to be safe
1213
1214                     return egConfirmDialog.open(
1215                         egCore.strings.TOO_MANY_CLAIMS_RETURNED, '', {}
1216                     ).result.then(function() {
1217                         return service.mark_claims_returned(barcode, date, true);
1218                     });
1219                 }
1220
1221                 if (evt.textcode == 'PERM_FAILURE') {
1222                     console.error('claims returned permission denied')
1223                     // TODO: auth override dialog?
1224                 }
1225             }
1226         });
1227     }
1228
1229     service.mark_claims_returned_dialog = function(copy_barcodes) {
1230         if (!copy_barcodes.length) return;
1231
1232         return $uibModal.open({
1233             templateUrl: './circ/share/t_mark_claims_returned_dialog',
1234             backdrop: 'static',
1235             controller: 
1236                        ['$scope','$uibModalInstance',
1237                 function($scope , $uibModalInstance) {
1238
1239                 var today = new Date();
1240                 $scope.args = {
1241                     barcodes : copy_barcodes,
1242                     date : today
1243                 };
1244
1245                 $scope.$watch('args.date', function(newval) {
1246                     if (newval && newval > today) 
1247                         $scope.args.backdate = today;
1248                 });
1249
1250                 $scope.cancel = function() {$uibModalInstance.dismiss()}
1251                 $scope.ok = function() { 
1252
1253                     var date = $scope.args.date.toISOString().replace(/T.*/,'');
1254
1255                     var deferred = $q.defer();
1256
1257                     // serialize the action on each barcode so that the 
1258                     // caller will never see multiple alerts at the same time.
1259                     function mark_one() {
1260                         var bc = copy_barcodes.pop();
1261                         if (!bc) {
1262                             deferred.resolve();
1263                             $uibModalInstance.close();
1264                             return;
1265                         }
1266
1267                         // finally -> continue even when one fails
1268                         service.mark_claims_returned(bc, date)
1269                         .finally(function(barcode) {
1270                             if (barcode) deferred.notify(barcode);
1271                             mark_one();
1272                         });
1273                     }
1274                     mark_one(); // kick it off
1275                     return deferred.promise;
1276                 }
1277             }]
1278         }).result;
1279     }
1280
1281     // serially checks in each barcode with claims_never_checked_out set
1282     // returns promise, notified on each barcode, resolved after all
1283     // checkins are complete.
1284     service.mark_claims_never_checked_out = function(barcodes) {
1285         if (!barcodes.length) return;
1286
1287         var deferred = $q.defer();
1288         egConfirmDialog.open(
1289             egCore.strings.MARK_NEVER_CHECKED_OUT, '', {barcodes : barcodes}
1290
1291         ).result.then(function() {
1292             function mark_one() {
1293                 var bc = barcodes.pop();
1294
1295                 if (!bc) { // all done
1296                     deferred.resolve();
1297                     return;
1298                 }
1299
1300                 service.checkin(
1301                     {claims_never_checked_out : true, copy_barcode : bc})
1302                 .finally(function() { 
1303                     deferred.notify(bc);
1304                     mark_one();
1305                 })
1306             }
1307             mark_one();
1308         });
1309
1310         return deferred.promise;
1311     }
1312
1313     service.mark_damaged = function(params) {
1314         if (!params) return $q.when();
1315         return $uibModal.open({
1316             templateUrl: './circ/share/t_mark_damaged',
1317             controller:
1318                 ['$scope', '$uibModalInstance', 'egCore', 'egBilling', 'egItem',
1319                 function($scope, $uibModalInstance, egCore, egBilling, egItem) {
1320                     var doRefresh = params.refresh;
1321                     
1322                     $scope.billArgs = {charge: params.charge};
1323                     $scope.mode = 'charge';
1324                     $scope.barcode = params.barcode;
1325                     if (params.charge && params.charge > 0) {
1326                         $scope.applyFine = "apply";
1327                     }
1328                     if (params.circ) {
1329                         $scope.circ = params.circ;
1330                         $scope.circ_checkin_time = params.circ.checkin_time();
1331                         $scope.circ_patron_name = params.circ.usr().family_name() + ", "
1332                             + params.circ.usr().first_given_name() + " "
1333                             + params.circ.usr().second_given_name();
1334                     }
1335                     egBilling.fetchBillingTypes().then(function(res) {
1336                         $scope.billingTypes = res;
1337                     });
1338
1339                     $scope.btnChargeFees = function() {
1340                         $scope.mode = 'charge';
1341                         $scope.billArgs.charge = params.charge;
1342                         $scope.applyFine = "apply";
1343                     }
1344                     $scope.btnWaiveFees = function() {
1345                         $scope.mode = 'waive';
1346                         $scope.billArgs.charge = 0;
1347                         $scope.applyFine = "noapply";
1348                     }
1349
1350                     $scope.cancel = function ($event) { 
1351                         $uibModalInstance.dismiss();
1352                     }
1353                     $scope.ok = function() {
1354                         handle_mark_item_damaged();
1355                     }
1356
1357                     var handle_mark_item_damaged = function() {
1358                         egCore.net.request(
1359                             'open-ils.circ',
1360                             'open-ils.circ.mark_item_damaged',
1361                             egCore.auth.token(), params.id, {
1362                                 apply_fines: $scope.applyFine,
1363                                 override_amount: $scope.billArgs.charge,
1364                                 override_btype: $scope.billArgs.type,
1365                                 override_note: $scope.billArgs.note,
1366                                 handle_checkin: !$scope.applyFine
1367                         }).then(function(resp) {
1368                             if (evt = egCore.evt.parse(resp)) {
1369                                 doRefresh = false;
1370                                 console.debug("mark damaged more information required. Pushing back.");
1371                                 service.mark_damaged({
1372                                     id: params.id,
1373                                     barcode: params.barcode,
1374                                     charge: evt.payload.charge,
1375                                     circ: evt.payload.circ,
1376                                     refresh: params.refresh
1377                                 });
1378                                 console.error('mark damaged failed: ' + evt);
1379                             }
1380                         }).then(function() {
1381                             if (doRefresh) egItem.add_barcode_to_list(params.barcode);
1382                         });
1383                         $uibModalInstance.close();
1384                     }
1385                 }]
1386         }).result;
1387     }
1388
1389     service.handle_mark_item_event = function(copy, status, args, event) {
1390         var dlogTitle, dlogMessage;
1391         switch (event.textcode) {
1392         case 'ITEM_TO_MARK_CHECKED_OUT':
1393             dlogTitle = egCore.strings.MARK_ITEM_CHECKED_OUT;
1394             dlogMessage = egCore.strings.MARK_ITEM_CHECKIN_CONTINUE;
1395             args.handle_checkin = 1;
1396             break;
1397         case 'ITEM_TO_MARK_IN_TRANSIT':
1398             dlogTitle = egCore.strings.MARK_ITEM_IN_TRANSIT;
1399             dlogMessage = egCore.strings.MARK_ITEM_ABORT_CONTINUE;
1400             args.handle_transit = 1;
1401             break;
1402         case 'ITEM_TO_MARK_LAST_HOLD_COPY':
1403             dlogTitle = egCore.strings.MARK_ITEM_LAST_HOLD_COPY;
1404             dlogMessage = egCore.strings.MARK_ITEM_CONTINUE;
1405             args.handle_last_hold_copy = 1;
1406             break;
1407         case 'COPY_DELETE_WARNING':
1408             dlogTitle = egCore.strings.MARK_ITEM_RESTRICT_DELETE;
1409             dlogMessage = egCore.strings.MARK_ITEM_CONTINUE;
1410             args.handle_copy_delete_warning = 1;
1411             break;
1412         case 'PERM_FAILURE':
1413             console.error('Mark item ' + status.name() + ' for ' + copy.barcode + ' failed: ' +
1414                           event);
1415             return service.exit_alert(egCore.strings.PERMISSION_DENIED,
1416                                       {permission : event.ilsperm});
1417             break;
1418         default:
1419             console.error('Mark item ' + status.name() + ' for ' + copy.barcode + ' failed: ' +
1420                           event);
1421             return service.exit_alert(egCore.strings.MARK_ITEM_FAILURE,
1422                                       {status : status.name(), barcode : copy.barcode,
1423                                        textcode : event.textcode});
1424             break;
1425         }
1426         return egConfirmDialog.open(
1427             dlogTitle, dlogMessage,
1428             {
1429                 barcode : copy.barcode,
1430                 status : status.name(),
1431                 ok : function () {},
1432                 cancel : function () {}
1433             }
1434         ).result.then(function() {
1435             return service.mark_item(copy, status, args);
1436         });
1437     }
1438
1439     service.mark_item = function(copy, markstatus, args) {
1440         if (!copy) return $q.when();
1441
1442         // If any new back end mark_item calls are added, also add
1443         // them here to use them from the staff client.
1444         // TODO: I didn't find any JS constants for copy status.
1445         var req;
1446         switch (markstatus.id()) {
1447         case 2:
1448             // Not implemented in the staff client, yet.
1449             // req = "open-ils.circ.mark_item_bindery";
1450             break;
1451         case 4:
1452             req = "open-ils.circ.mark_item_missing";
1453             break;
1454         case 9:
1455             // Not implemented in the staff client, yet.
1456             // req = "open-ils.circ.mark_item_on_order";
1457             break;
1458         case 10:
1459             // Not implemented in the staff client, yet.
1460             // req = "open-ils.circ.mark_item_ill";
1461             break;
1462         case 11:
1463             // Not implemented in the staff client, yet.
1464             // req = "open-ils.circ.mark_item_cataloging";
1465             break;
1466         case 12:
1467             // Not implemented in the staff client, yet.
1468             // req = "open-ils.circ.mark_item_reserves";
1469             break;
1470         case 13:
1471             req = "open-ils.circ.mark_item_discard";
1472             break;
1473         case 14:
1474             // Damaged is for handling of events. It's main handler is elsewhere.
1475             req = "open-ils.circ.mark_item_damaged";
1476             break;
1477         }
1478
1479         return egCore.net.request(
1480             'open-ils.circ',
1481             req,
1482             egCore.auth.token(),
1483             copy.id,
1484             args
1485         ).then(function(resp) {
1486             if (evt = egCore.evt.parse(resp)) {
1487                 return service.handle_mark_item_event(copy, markstatus, args, evt);
1488             }
1489         });
1490     }
1491
1492     service.mark_discard = function(copies) {
1493         return egConfirmDialog.open(
1494             egCore.strings.MARK_DISCARD_CONFIRM, '',
1495             {
1496                 num_items : copies.length,
1497                 ok : function() {},
1498                 cancel : function() {}
1499             }
1500         ).result.then(function() {
1501             return egCore.pcrud.retrieve('ccs', 13)
1502                 .then(function(resp) {
1503                     var promises = [];
1504                     angular.forEach(copies, function(copy) {
1505                         promises.push(service.mark_item(copy, resp, {}))
1506                     });
1507                     return $q.all(promises);
1508                 });
1509         });
1510     }
1511
1512     service.mark_missing = function(copies) {
1513         return egConfirmDialog.open(
1514             egCore.strings.MARK_MISSING_CONFIRM, '',
1515             {
1516                 num_items : copies.length,
1517                 ok : function() {},
1518                 cancel : function() {}
1519             }
1520         ).result.then(function() {
1521             return egCore.pcrud.retrieve('ccs', 4)
1522                 .then(function(resp) {
1523                     var promises = [];
1524                     angular.forEach(copies, function(copy) {
1525                         promises.push(service.mark_item(copy, resp, {}))
1526                     });
1527                     return $q.all(promises);
1528                 });
1529         });
1530     }
1531
1532
1533
1534     // Mark circulations as lost via copy barcode.  As each item is 
1535     // processed, the returned promise is notified of the barcode.
1536     // No confirmation dialog is presented.
1537     service.mark_lost = function(copy_barcodes) {
1538         var deferred = $q.defer();
1539         var promises = [];
1540
1541         angular.forEach(copy_barcodes, function(barcode) {
1542             promises.push(
1543                 egCore.net.request(
1544                     'open-ils.circ',
1545                     'open-ils.circ.circulation.set_lost',
1546                     egCore.auth.token(), {barcode : barcode}
1547                 ).then(function(resp) {
1548                     if (evt = egCore.evt.parse(resp)) {
1549                         console.error("Mark lost failed: " + evt.toString());
1550                         return;
1551                     }
1552                     // inform the caller as each item is processed
1553                     deferred.notify(barcode);
1554                 })
1555             );
1556         });
1557
1558         $q.all(promises).then(function() {deferred.resolve()});
1559         return deferred.promise;
1560     }
1561
1562     service.abort_transits = function(transit_ids) {
1563         return egConfirmDialog.open(
1564             egCore.strings.ABORT_TRANSIT_CONFIRM, '',
1565             {   num_transits : transit_ids.length,
1566                 ok : function() {},
1567                 cancel : function() {}
1568             }
1569
1570         ).result.then(function() {
1571             var promises = [];
1572             angular.forEach(transit_ids, function(transit_id) {
1573                 promises.push(
1574                     egCore.net.request(
1575                         'open-ils.circ',
1576                         'open-ils.circ.transit.abort',
1577                         egCore.auth.token(), {transitid : transit_id}
1578                     ).then(function(resp) {
1579                         if (evt = egCore.evt.parse(resp)) {
1580                             console.error('abort transit failed: ' + evt);
1581                         }
1582                     })
1583                 );
1584             });
1585
1586             return $q.all(promises);
1587         });
1588     }
1589
1590     service.add_copy_alerts = function(item_ids) {
1591         return egAddCopyAlertDialog.open({
1592             copy_ids : item_ids,
1593             ok : function() { },
1594             cancel : function() {}
1595         }).result.then(function() { });
1596     }
1597
1598     service.manage_copy_alerts = function(item_ids) {
1599         return egCopyAlertEditorDialog.open({
1600             copy_id : item_ids[0],
1601             ok : function() { },
1602             cancel : function() {}
1603         }).result.then(function() { });
1604     }
1605
1606     // alert when copy location alert_message is set.
1607     // This does not affect processing, it only produces a click-through
1608     service.handle_checkin_loc_alert = function(evt, params, options) {
1609         if (angular.isArray(evt)) evt = evt[0];
1610
1611         var copy = evt && evt.payload ? evt.payload.copy : null;
1612
1613         if (copy && !options.suppress_popups
1614             && copy.location().checkin_alert() == 't') {
1615
1616             return egAlertDialog.open(
1617                 egCore.strings.LOCATION_ALERT_MSG, {copy : copy}).result;
1618         }
1619
1620         return $q.when();
1621     }
1622
1623     service.handle_checkin_resp = function(evt, params, options) {
1624         if (!angular.isArray(evt)) evt = [evt];
1625
1626         var final_resp = {evt : evt, params : params, options : options};
1627
1628         var copy, hold, transit, latest_inventory;
1629         if (evt[0].payload) {
1630             copy = evt[0].payload.copy;
1631             hold = evt[0].payload.hold;
1632             transit = evt[0].payload.transit;
1633             latest_inventory = evt[0].payload.latest_inventory;
1634         }
1635
1636         // track the barcode regardless of whether it's valid
1637         angular.forEach(evt, function(e){ e.copy_barcode = params.copy_barcode; });
1638
1639         angular.forEach(evt, function(e){ console.debug('checkin event ' + e.textcode); });
1640
1641         if (evt.filter(function(e){return service.checkin_overridable_events.indexOf(e.textcode) > -1;}).length > 0)
1642             return service.handle_overridable_checkin_event(evt, params, options);
1643
1644         switch (evt[0].textcode) {
1645
1646             case 'SUCCESS':
1647             case 'NO_CHANGE':
1648
1649                 switch(Number(copy.status().id())) {
1650
1651                     case 0: /* AVAILABLE */                                        
1652                     case 4: /* MISSING */                                          
1653                     case 7: /* RESHELVING */ 
1654
1655                         egCore.audio.play('success.checkin');
1656
1657                         // see if the copy location requires an alert
1658                         return service.handle_checkin_loc_alert(evt, params, options)
1659                         .then(function() {return final_resp});
1660
1661                     case 8: /* ON HOLDS SHELF */
1662                         egCore.audio.play('info.checkin.holds_shelf');
1663                         
1664                         if (hold) {
1665
1666                             if (hold.pickup_lib() == egCore.auth.user().ws_ou()) {
1667                                 // inform user if the item is on the local holds shelf
1668                             
1669                                 evt[0].route_to = egCore.strings.ROUTE_TO_HOLDS_SHELF;
1670                                 return service.route_dialog(
1671                                     './circ/share/t_hold_shelf_dialog', 
1672                                     evt[0], params, options
1673                                 ).then(function() { return final_resp });
1674
1675                             } else {
1676                                 // normally, if the hold was on the shelf at a 
1677                                 // different location, it would be put into 
1678                                 // transit, resulting in a ROUTE_ITEM event.
1679                                 egCore.audio.play('warning.checkin.wrong_shelf');
1680                                 return $q.when(final_resp);
1681                             }
1682                         } else {
1683
1684                             console.error('checkin: item on holds shelf, '
1685                                 + 'but hold info not returned from checkin');
1686                             return $q.when(final_resp);
1687                         }
1688
1689                     case 11: /* CATALOGING */
1690                         egCore.audio.play('info.checkin.cataloging');
1691                         evt[0].route_to = egCore.strings.ROUTE_TO_CATALOGING;
1692                         if (options.no_precat_alert || options.suppress_popups)
1693                             return $q.when(final_resp);
1694                         return egAlertDialog.open(
1695                             egCore.strings.PRECAT_CHECKIN_MSG, params)
1696                             .result.then(function() {return final_resp});
1697
1698
1699                     case 15: /* ON_RESERVATION_SHELF */
1700                         egCore.audio.play('info.checkin.reservation');
1701                         // TODO: show booking reservation dialog
1702                         return $q.when(final_resp);
1703
1704                     default:
1705                         egCore.audio.play('success.checkin');
1706                         console.debug('Unusual checkin copy status (may have been set via copy alert): '
1707                             + copy.status().id() + ' : ' + copy.status().name());
1708                         return $q.when(final_resp);
1709                 }
1710                 
1711             case 'ROUTE_ITEM':
1712                 return service.route_dialog(
1713                     './circ/share/t_transit_dialog', 
1714                     evt[0], params, options
1715                 ).then(function(data) {
1716                     if (transit && data.transit && transit.dest().id() != data.transit.dest().id())
1717                         final_resp.evt[0].route_to = data.transit.dest().shortname();
1718                     return final_resp;
1719                 });
1720
1721             case 'ASSET_COPY_NOT_FOUND':
1722                 egCore.audio.play('error.checkin.not_found');
1723                 if (options.suppress_popups) return $q.when(final_resp);
1724                 return egAlertDialog.open(
1725                     egCore.strings.UNCAT_ALERT_DIALOG, params)
1726                     .result.then(function() {return final_resp});
1727
1728             case 'ITEM_NOT_CATALOGED':
1729                 egCore.audio.play('error.checkin.not_cataloged');
1730                 evt[0].route_to = egCore.strings.ROUTE_TO_CATALOGING;
1731                 if (options.no_precat_alert || options.suppress_popups)
1732                     return $q.when(final_resp);
1733                 return egAlertDialog.open(
1734                     egCore.strings.PRECAT_CHECKIN_MSG, params)
1735                     .result.then(function() {return final_resp});
1736
1737             default:
1738                 egCore.audio.play('error.checkin.unknown');
1739                 console.warn('unhandled checkin response : ' + evt[0].textcode);
1740                 return $q.when(final_resp);
1741         }
1742     }
1743
1744     // collect transit, address, and hold info that's not already
1745     // included in responses.
1746     service.collect_route_data = function(tmpl, evt, params, options) {
1747         if (angular.isArray(evt)) evt = evt[0];
1748         var promises = [];
1749         var data = {};
1750
1751         if (evt.org && !tmpl.match(/hold_shelf/)) {
1752             promises.push(
1753                 service.get_org_addr(evt.org, 'holds_address')
1754                 .then(function(addr) { data.address = addr })
1755             );
1756         }
1757
1758         if (evt.payload.hold) {
1759             promises.push(
1760                 egCore.pcrud.retrieve('au', 
1761                     evt.payload.hold.usr(), {
1762                         flesh : 1,
1763                         flesh_fields : {'au' : ['card']}
1764                     }
1765                 ).then(function(patron) {data.patron = patron})
1766             );
1767         }
1768
1769
1770         if (!tmpl.match(/hold_shelf/)) {
1771             var courier_deferred = $q.defer();
1772             promises.push(courier_deferred.promise);
1773             promises.push(
1774                 service.find_copy_transit(evt, params, options)
1775                 .then(function(trans) {
1776                     data.transit = trans;
1777                     egCore.org.settings('lib.courier_code', trans.dest().id())
1778                     .then(function(s) {
1779                         data.dest_courier_code = s['lib.courier_code'];
1780                         courier_deferred.resolve();
1781                     });
1782                 })
1783             );
1784         }
1785
1786         return $q.all(promises).then(function() { return data });
1787     }
1788
1789     service.route_dialog = function(tmpl, evt, params, options) {
1790         if (angular.isArray(evt)) evt = evt[0];
1791
1792         return service.collect_route_data(tmpl, evt, params, options)
1793         .then(function(data) {
1794
1795             var template = data.transit ?
1796                 (data.patron ? 'hold_transit_slip' : 'transit_slip') :
1797                 'hold_shelf_slip';
1798             if (service.never_auto_print[template]) {
1799                 // do not show the dialog or print if the
1800                 // disabled automatic print attempt type list includes
1801                 // the specified template
1802                 return data;
1803             }
1804
1805             // All actions flow from the print data
1806
1807             var print_context = {
1808                 copy : egCore.idl.toHash(evt.payload.copy),
1809                 title : evt.title,
1810                 author : evt.author,
1811                 call_number : egCore.idl.toHash(evt.payload.volume)
1812             };
1813
1814             var acn = print_context.call_number; // fix up pre/suffixes
1815             if (acn.prefix == -1) acn.prefix = "";
1816             if (acn.suffix == -1) acn.suffix = "";
1817
1818             if (data.transit) {
1819                 // route_dialog includes the "route to holds shelf" 
1820                 // dialog, which has no transit
1821                 print_context.transit = egCore.idl.toHash(data.transit);
1822                 print_context.dest_courier_code = data.dest_courier_code;
1823                 if (data.address) {
1824                     print_context.dest_address = egCore.idl.toHash(data.address);
1825                 }
1826                 print_context.dest_location =
1827                     egCore.idl.toHash(egCore.org.get(data.transit.dest()));
1828             }
1829
1830             if (data.patron) {
1831                 print_context.hold = egCore.idl.toHash(evt.payload.hold);
1832                 var notes = print_context.hold.notes;
1833                 if(notes.length > 0){
1834                     print_context.hold_notes = [];
1835                     angular.forEach(notes, function(n){
1836                         print_context.hold_notes.push(n);
1837                     });
1838                 }
1839                 print_context.patron = egCore.idl.toHash(data.patron);
1840             }
1841
1842             var sound = 'info.checkin.transit';
1843             if (evt.payload.hold) sound += '.hold';
1844             egCore.audio.play(sound);
1845
1846             function print_transit(template) {
1847                 return egCore.print.print({
1848                     context : 'default', 
1849                     template : template, 
1850                     scope : print_context
1851                 }).then(function() { return data });
1852             }
1853
1854             // when auto-print is on, skip the dialog and go straight
1855             // to printing.
1856             if (options.auto_print_holds_transits || options.suppress_popups) 
1857                 return print_transit(template);
1858
1859             return $uibModal.open({
1860                 templateUrl: tmpl,
1861                 backdrop: 'static',
1862                 controller: [
1863                             '$scope','$uibModalInstance',
1864                     function($scope , $uibModalInstance) {
1865
1866                     $scope.today = new Date();
1867
1868                     // copy the print scope into the dialog scope
1869                     angular.forEach(print_context, function(val, key) {
1870                         $scope[key] = val;
1871                     });
1872
1873                     $scope.ok = function() {$uibModalInstance.close()}
1874
1875                     $scope.print = function() { 
1876                         $uibModalInstance.close();
1877                         print_transit(template);
1878                     }
1879                 }]
1880
1881             }).result.then(function() { return data });
1882         });
1883     }
1884
1885     // action == what action to take if the user confirms the alert
1886     service.copy_alert_dialog = function(evt, params, options, action) {
1887         if (angular.isArray(evt)) evt = evt[0];
1888         if (!angular.isArray(evt.payload)) {
1889             return egConfirmDialog.open(
1890                 egCore.strings.COPY_ALERT_MSG_DIALOG_TITLE, 
1891                 evt.payload,  // payload == alert message text
1892                 {   copy_barcode : params.copy_barcode,
1893                     ok : function() {},
1894                     cancel : function() {}
1895                 }
1896             ).result.then(function() {
1897                 options.override = true;
1898                 return service[action](params, options);
1899             });
1900         } else { // we got a list of copy alert objects ...
1901             return egCopyAlertManagerDialog.open({
1902                 alerts : evt.payload,
1903                 mode : action,
1904                 ok : function(the_next_status) {
1905                         if (the_next_status !== null) {
1906                             params.next_copy_status = [ the_next_status ];
1907                             params.capture = 'nocapture';
1908                         }
1909                      },
1910                 cancel : function() {}
1911             }).result.then(function() {
1912                 options.override = true;
1913                 return service[action](params, options);
1914             });
1915         }
1916     }
1917
1918     // action == what action to take if the user confirms the alert
1919     service.hold_capture_delay_dialog = function(evt, params, options, action) {
1920         if (angular.isArray(evt)) evt = evt[0];
1921         return $uibModal.open({
1922             templateUrl: './circ/checkin/t_hold_verify',
1923             backdrop: 'static',
1924             controller:
1925                        ['$scope','$uibModalInstance','params',
1926                 function($scope , $uibModalInstance , params) {
1927                 $scope.copy_barcode = params.copy_barcode;
1928                 $scope.capture = function() {
1929                     params.capture = 'capture';
1930                     $uibModalInstance.close();
1931                 };
1932                 $scope.nocapture = function() {
1933                     params.capture = 'nocapture';
1934                     $uibModalInstance.close();
1935                 };
1936                 $scope.cancel = function() { $uibModalInstance.dismiss(); };
1937             }],
1938             resolve : {
1939                 params : function() {
1940                     return params;
1941                 }
1942             }
1943         }).result.then(
1944             function(r) {
1945                 return service[action](params, options);
1946             }
1947         );
1948     }
1949
1950     // check the barcode.  If it's no good, show the warning dialog
1951     // Resolves on success, rejected on error
1952     service.test_barcode = function(bc) {
1953
1954         var ok = service.check_barcode(bc);
1955         if (ok) return $q.when();
1956
1957         egCore.audio.play('warning.circ.bad_barcode');
1958         return $uibModal.open({
1959             templateUrl: './circ/share/t_bad_barcode_dialog',
1960             backdrop: 'static',
1961             controller: 
1962                 ['$scope', '$uibModalInstance', 
1963                 function($scope, $uibModalInstance) {
1964                 $scope.barcode = bc;
1965                 $scope.ok = function() { $uibModalInstance.close() }
1966                 $scope.cancel = function() { $uibModalInstance.dismiss() }
1967             }]
1968         }).result;
1969     }
1970
1971     // check() and checkdigit() copied directly 
1972     // from chrome/content/util/barcode.js
1973
1974     service.check_barcode = function(bc) {
1975         if (bc != Number(bc)) return false;
1976         bc = bc.toString();
1977         // "16.00" == Number("16.00"), but the . is bad.
1978         // Throw out any barcode that isn't just digits
1979         if (bc.search(/\D/) != -1) return false;
1980         var last_digit = bc.substr(bc.length-1);
1981         var stripped_barcode = bc.substr(0,bc.length-1);
1982         return service.barcode_checkdigit(stripped_barcode).toString() == last_digit;
1983     }
1984
1985     service.barcode_checkdigit = function(bc) {
1986         var reverse_barcode = bc.toString().split('').reverse();
1987         var check_sum = 0; var multiplier = 2;
1988         for (var i = 0; i < reverse_barcode.length; i++) {
1989             var digit = reverse_barcode[i];
1990             var product = digit * multiplier; product = product.toString();
1991             var temp_sum = 0;
1992             for (var j = 0; j < product.length; j++) {
1993                 temp_sum += Number( product[j] );
1994             }
1995             check_sum += Number( temp_sum );
1996             multiplier = ( multiplier == 2 ? 1 : 2 );
1997         }
1998         check_sum = check_sum.toString();
1999         var next_multiple_of_10 = (check_sum.match(/(\d*)\d$/)[1] * 10) + 10;
2000         var check_digit = next_multiple_of_10 - Number(check_sum);
2001         if (check_digit == 10) check_digit = 0;
2002         return check_digit;
2003     }
2004
2005     service.handle_barcode_completion = function(barcode) {
2006         return egCore.net.request(
2007             'open-ils.actor',
2008             'open-ils.actor.get_barcodes',
2009             egCore.auth.token(), egCore.auth.user().ws_ou(), 
2010             'asset', barcode)
2011
2012         .then(function(resp) {
2013             // TODO: handle event during barcode lookup
2014             if (evt = egCore.evt.parse(resp)) {
2015                 console.error(evt.toString());
2016                 return $q.reject();
2017             }
2018
2019             // no matching barcodes: return the barcode as entered
2020             // by the user (so that, e.g., checkout can fall back to
2021             // precat/noncat handling)
2022             if (!resp || !resp[0]) {
2023                 return barcode;
2024             }
2025
2026             // exactly one matching barcode: return it
2027             if (resp.length == 1) {
2028                 return resp[0].barcode;
2029             }
2030
2031             // multiple matching barcodes: let the user pick one 
2032             console.debug('multiple matching barcodes');
2033             var matches = [];
2034             var promises = [];
2035             var final_barcode;
2036             angular.forEach(resp, function(cp) {
2037                 promises.push(
2038                     egCore.net.request(
2039                         'open-ils.circ',
2040                         'open-ils.circ.copy_details.retrieve',
2041                         egCore.auth.token(), cp.id
2042                     ).then(function(r) {
2043                         matches.push({
2044                             barcode: r.copy.barcode(),
2045                             title: r.mvr.title(),
2046                             org_name: egCore.org.get(r.copy.circ_lib()).name(),
2047                             org_shortname: egCore.org.get(r.copy.circ_lib()).shortname()
2048                         });
2049                     })
2050                 );
2051             });
2052             return $q.all(promises)
2053             .then(function() {
2054                 return $uibModal.open({
2055                     templateUrl: './circ/share/t_barcode_choice_dialog',
2056                     backdrop: 'static',
2057                     controller:
2058                         ['$scope', '$uibModalInstance',
2059                         function($scope, $uibModalInstance) {
2060                         $scope.matches = matches;
2061                         $scope.ok = function(barcode) {
2062                             $uibModalInstance.close();
2063                             final_barcode = barcode;
2064                         }
2065                         $scope.cancel = function() {$uibModalInstance.dismiss()}
2066                     }],
2067                 }).result.then(function() { return final_barcode });
2068             })
2069         });
2070     }
2071
2072     service.create_penalty = function(user_id) {
2073         return $uibModal.open({
2074             templateUrl: './circ/share/t_new_message_dialog',
2075             backdrop: 'static',
2076             controller: 
2077                    ['$scope','$uibModalInstance','staffPenalties',
2078             function($scope , $uibModalInstance , staffPenalties) {
2079                 $scope.focusNote = true;
2080                 $scope.penalties = staffPenalties;
2081                 $scope.require_initials = service.require_initials;
2082                 $scope.args = {penalty : 21}; // default to Note
2083                 $scope.setPenalty = function(id) {
2084                     args.penalty = id;
2085                 }
2086                 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
2087                 $scope.cancel = function($event) { 
2088                     $uibModalInstance.dismiss();
2089                     $event.preventDefault();
2090                 }
2091             }],
2092             resolve : { staffPenalties : service.get_staff_penalty_types }
2093         }).result.then(
2094             function(args) {
2095                 var pen = new egCore.idl.ausp();
2096                 pen.usr(user_id);
2097                 pen.org_unit(egCore.auth.user().ws_ou());
2098                 pen.note(args.note);
2099                 if (args.initials) pen.note(args.note + ' [' + args.initials + ']');
2100                 if (args.custom_penalty) {
2101                     pen.standing_penalty(args.custom_penalty);
2102                 } else {
2103                     pen.standing_penalty(args.penalty);
2104                 }
2105                 pen.staff(egCore.auth.user().id());
2106                 pen.set_date('now');
2107
2108                 return egCore.net.request(
2109                     'open-ils.actor',
2110                     'open-ils.actor.user.penalty.apply',
2111                     egCore.auth.token(), pen
2112                 );
2113             }
2114         );
2115     }
2116
2117     // assumes, for now anyway,  penalty type is fleshed onto usr_penalty.
2118     service.edit_penalty = function(usr_penalty) {
2119         return $uibModal.open({
2120             templateUrl: './circ/share/t_new_message_dialog',
2121             backdrop: 'static',
2122             controller: 
2123                    ['$scope','$uibModalInstance','staffPenalties',
2124             function($scope , $uibModalInstance , staffPenalties) {
2125                 $scope.focusNote = true;
2126                 $scope.penalties = staffPenalties;
2127                 $scope.require_initials = service.require_initials;
2128                 $scope.args = {
2129                     penalty : usr_penalty.standing_penalty().id(),
2130                     note : usr_penalty.note()
2131                 }
2132                 $scope.setPenalty = function(id) { args.penalty = id; }
2133                 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
2134                 $scope.cancel = function($event) { 
2135                     $uibModalInstance.dismiss();
2136                     $event.preventDefault();
2137                 }
2138             }],
2139             resolve : { staffPenalties : service.get_staff_penalty_types }
2140         }).result.then(
2141             function(args) {
2142                 usr_penalty.note(args.note);
2143                 if (args.initials) usr_penalty.note(args.note + ' [' + args.initials + ']');
2144                 usr_penalty.standing_penalty(args.penalty);
2145                 return egCore.pcrud.update(usr_penalty);
2146             }
2147         );
2148     }
2149
2150     return service;
2151
2152 }]);
2153
2154