]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/services/circ.js
6bed816ee37e7ffd2bee985f1a18e05b860cd7c4
[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             backdrop: 'static',
1317             templateUrl: './circ/share/t_mark_damaged',
1318             controller:
1319                 ['$scope', '$uibModalInstance', 'egCore', 'egBilling', 'egItem',
1320                 function($scope, $uibModalInstance, egCore, egBilling, egItem) {
1321                     var doRefresh = params.refresh;
1322                     
1323                     $scope.showBill = params.charge != null && params.circ;
1324                     $scope.billArgs = {charge: params.charge};
1325                     $scope.mode = 'charge';
1326                     $scope.barcode = params.barcode;
1327                     if (params.circ) {
1328                         $scope.circ = params.circ;
1329                         $scope.circ_checkin_time = params.circ.checkin_time();
1330                         $scope.circ_patron_name = params.circ.usr().family_name() + ", "
1331                             + params.circ.usr().first_given_name() + " "
1332                             + params.circ.usr().second_given_name();
1333                     }
1334                     egBilling.fetchBillingTypes().then(function(res) {
1335                         $scope.billingTypes = res;
1336                     });
1337
1338                     $scope.btnChargeFees = function() {
1339                         $scope.mode = 'charge';
1340                         $scope.billArgs.charge = params.charge;
1341                     }
1342                     $scope.btnWaiveFees = function() {
1343                         $scope.mode = 'waive';
1344                         $scope.billArgs.charge = 0;
1345                     }
1346
1347                     $scope.cancel = function ($event) { 
1348                         $uibModalInstance.dismiss();
1349                     }
1350                     $scope.ok = function() {
1351                         handle_mark_item_damaged();
1352                     }
1353
1354                     var handle_mark_item_damaged = function() {
1355                         var applyFines;
1356                         if ($scope.showBill)
1357                             applyFines = $scope.billArgs.charge ? 'apply' : 'noapply';
1358
1359                         egCore.net.request(
1360                             'open-ils.circ',
1361                             'open-ils.circ.mark_item_damaged',
1362                             egCore.auth.token(), params.id, {
1363                                 apply_fines: applyFines,
1364                                 override_amount: $scope.billArgs.charge,
1365                                 override_btype: $scope.billArgs.type,
1366                                 override_note: $scope.billArgs.note,
1367                                 handle_checkin: !applyFines
1368                         }).then(function(resp) {
1369                             if (evt = egCore.evt.parse(resp)) {
1370                                 doRefresh = false;
1371                                 console.debug("mark damaged more information required. Pushing back.");
1372                                 service.mark_damaged({
1373                                     id: params.id,
1374                                     barcode: params.barcode,
1375                                     charge: evt.payload.charge,
1376                                     circ: evt.payload.circ,
1377                                     refresh: params.refresh
1378                                 });
1379                                 console.error('mark damaged failed: ' + evt);
1380                             }
1381                         }).then(function() {
1382                             if (doRefresh) egItem.add_barcode_to_list(params.barcode);
1383                         });
1384                         $uibModalInstance.close();
1385                     }
1386                 }]
1387         }).result;
1388     }
1389
1390     service.handle_mark_item_event = function(copy, status, args, event) {
1391         var dlogTitle, dlogMessage;
1392         switch (event.textcode) {
1393         case 'ITEM_TO_MARK_CHECKED_OUT':
1394             dlogTitle = egCore.strings.MARK_ITEM_CHECKED_OUT;
1395             dlogMessage = egCore.strings.MARK_ITEM_CHECKIN_CONTINUE;
1396             args.handle_checkin = 1;
1397             break;
1398         case 'ITEM_TO_MARK_IN_TRANSIT':
1399             dlogTitle = egCore.strings.MARK_ITEM_IN_TRANSIT;
1400             dlogMessage = egCore.strings.MARK_ITEM_ABORT_CONTINUE;
1401             args.handle_transit = 1;
1402             break;
1403         case 'ITEM_TO_MARK_LAST_HOLD_COPY':
1404             dlogTitle = egCore.strings.MARK_ITEM_LAST_HOLD_COPY;
1405             dlogMessage = egCore.strings.MARK_ITEM_CONTINUE;
1406             args.handle_last_hold_copy = 1;
1407             break;
1408         case 'COPY_DELETE_WARNING':
1409             dlogTitle = egCore.strings.MARK_ITEM_RESTRICT_DELETE;
1410             dlogMessage = egCore.strings.MARK_ITEM_CONTINUE;
1411             args.handle_copy_delete_warning = 1;
1412             break;
1413         case 'PERM_FAILURE':
1414             console.error('Mark item ' + status.name() + ' for ' + copy.barcode + ' failed: ' +
1415                           event);
1416             return service.exit_alert(egCore.strings.PERMISSION_DENIED,
1417                                       {permission : event.ilsperm});
1418             break;
1419         default:
1420             console.error('Mark item ' + status.name() + ' for ' + copy.barcode + ' failed: ' +
1421                           event);
1422             return service.exit_alert(egCore.strings.MARK_ITEM_FAILURE,
1423                                       {status : status.name(), barcode : copy.barcode,
1424                                        textcode : event.textcode});
1425             break;
1426         }
1427         return egConfirmDialog.open(
1428             dlogTitle, dlogMessage,
1429             {
1430                 barcode : copy.barcode,
1431                 status : status.name(),
1432                 ok : function () {},
1433                 cancel : function () {}
1434             }
1435         ).result.then(function() {
1436             return service.mark_item(copy, status, args);
1437         });
1438     }
1439
1440     service.mark_item = function(copy, markstatus, args) {
1441         if (!copy) return $q.when();
1442
1443         // If any new back end mark_item calls are added, also add
1444         // them here to use them from the staff client.
1445         // TODO: I didn't find any JS constants for copy status.
1446         var req;
1447         switch (markstatus.id()) {
1448         case 2:
1449             // Not implemented in the staff client, yet.
1450             // req = "open-ils.circ.mark_item_bindery";
1451             break;
1452         case 4:
1453             req = "open-ils.circ.mark_item_missing";
1454             break;
1455         case 9:
1456             // Not implemented in the staff client, yet.
1457             // req = "open-ils.circ.mark_item_on_order";
1458             break;
1459         case 10:
1460             // Not implemented in the staff client, yet.
1461             // req = "open-ils.circ.mark_item_ill";
1462             break;
1463         case 11:
1464             // Not implemented in the staff client, yet.
1465             // req = "open-ils.circ.mark_item_cataloging";
1466             break;
1467         case 12:
1468             // Not implemented in the staff client, yet.
1469             // req = "open-ils.circ.mark_item_reserves";
1470             break;
1471         case 13:
1472             req = "open-ils.circ.mark_item_discard";
1473             break;
1474         case 14:
1475             // Damaged is for handling of events. It's main handler is elsewhere.
1476             req = "open-ils.circ.mark_item_damaged";
1477             break;
1478         }
1479
1480         return egCore.net.request(
1481             'open-ils.circ',
1482             req,
1483             egCore.auth.token(),
1484             copy.id,
1485             args
1486         ).then(function(resp) {
1487             if (evt = egCore.evt.parse(resp)) {
1488                 return service.handle_mark_item_event(copy, markstatus, args, evt);
1489             }
1490         });
1491     }
1492
1493     service.mark_discard = function(copies) {
1494         return egConfirmDialog.open(
1495             egCore.strings.MARK_DISCARD_CONFIRM, '',
1496             {
1497                 num_items : copies.length,
1498                 ok : function() {},
1499                 cancel : function() {}
1500             }
1501         ).result.then(function() {
1502             return egCore.pcrud.retrieve('ccs', 13)
1503                 .then(function(resp) {
1504                     var promises = [];
1505                     angular.forEach(copies, function(copy) {
1506                         promises.push(service.mark_item(copy, resp, {}))
1507                     });
1508                     return $q.all(promises);
1509                 });
1510         });
1511     }
1512
1513     service.mark_missing = function(copies) {
1514         return egConfirmDialog.open(
1515             egCore.strings.MARK_MISSING_CONFIRM, '',
1516             {
1517                 num_items : copies.length,
1518                 ok : function() {},
1519                 cancel : function() {}
1520             }
1521         ).result.then(function() {
1522             return egCore.pcrud.retrieve('ccs', 4)
1523                 .then(function(resp) {
1524                     var promises = [];
1525                     angular.forEach(copies, function(copy) {
1526                         promises.push(service.mark_item(copy, resp, {}))
1527                     });
1528                     return $q.all(promises);
1529                 });
1530         });
1531     }
1532
1533
1534
1535     // Mark circulations as lost via copy barcode.  As each item is 
1536     // processed, the returned promise is notified of the barcode.
1537     // No confirmation dialog is presented.
1538     service.mark_lost = function(copy_barcodes) {
1539         var deferred = $q.defer();
1540         var promises = [];
1541
1542         angular.forEach(copy_barcodes, function(barcode) {
1543             promises.push(
1544                 egCore.net.request(
1545                     'open-ils.circ',
1546                     'open-ils.circ.circulation.set_lost',
1547                     egCore.auth.token(), {barcode : barcode}
1548                 ).then(function(resp) {
1549                     if (evt = egCore.evt.parse(resp)) {
1550                         console.error("Mark lost failed: " + evt.toString());
1551                         return;
1552                     }
1553                     // inform the caller as each item is processed
1554                     deferred.notify(barcode);
1555                 })
1556             );
1557         });
1558
1559         $q.all(promises).then(function() {deferred.resolve()});
1560         return deferred.promise;
1561     }
1562
1563     service.abort_transits = function(transit_ids) {
1564         return egConfirmDialog.open(
1565             egCore.strings.ABORT_TRANSIT_CONFIRM, '',
1566             {   num_transits : transit_ids.length,
1567                 ok : function() {},
1568                 cancel : function() {}
1569             }
1570
1571         ).result.then(function() {
1572             var promises = [];
1573             angular.forEach(transit_ids, function(transit_id) {
1574                 promises.push(
1575                     egCore.net.request(
1576                         'open-ils.circ',
1577                         'open-ils.circ.transit.abort',
1578                         egCore.auth.token(), {transitid : transit_id}
1579                     ).then(function(resp) {
1580                         if (evt = egCore.evt.parse(resp)) {
1581                             console.error('abort transit failed: ' + evt);
1582                         }
1583                     })
1584                 );
1585             });
1586
1587             return $q.all(promises);
1588         });
1589     }
1590
1591     service.add_copy_alerts = function(item_ids) {
1592         return egAddCopyAlertDialog.open({
1593             copy_ids : item_ids,
1594             ok : function() { },
1595             cancel : function() {}
1596         }).result.then(function() { });
1597     }
1598
1599     service.manage_copy_alerts = function(item_ids) {
1600         return egCopyAlertEditorDialog.open({
1601             copy_id : item_ids[0],
1602             ok : function() { },
1603             cancel : function() {}
1604         }).result.then(function() { });
1605     }
1606
1607     // alert when copy location alert_message is set.
1608     // This does not affect processing, it only produces a click-through
1609     service.handle_checkin_loc_alert = function(evt, params, options) {
1610         if (angular.isArray(evt)) evt = evt[0];
1611
1612         var copy = evt && evt.payload ? evt.payload.copy : null;
1613
1614         if (copy && !options.suppress_popups
1615             && copy.location().checkin_alert() == 't') {
1616
1617             return egAlertDialog.open(
1618                 egCore.strings.LOCATION_ALERT_MSG, {copy : copy}).result;
1619         }
1620
1621         return $q.when();
1622     }
1623
1624     service.handle_checkin_resp = function(evt, params, options) {
1625         if (!angular.isArray(evt)) evt = [evt];
1626
1627         var final_resp = {evt : evt, params : params, options : options};
1628
1629         var copy, hold, transit, latest_inventory;
1630         if (evt[0].payload) {
1631             copy = evt[0].payload.copy;
1632             hold = evt[0].payload.hold;
1633             transit = evt[0].payload.transit;
1634             latest_inventory = evt[0].payload.latest_inventory;
1635         }
1636
1637         // track the barcode regardless of whether it's valid
1638         angular.forEach(evt, function(e){ e.copy_barcode = params.copy_barcode; });
1639
1640         angular.forEach(evt, function(e){ console.debug('checkin event ' + e.textcode); });
1641
1642         if (evt.filter(function(e){return service.checkin_overridable_events.indexOf(e.textcode) > -1;}).length > 0)
1643             return service.handle_overridable_checkin_event(evt, params, options);
1644
1645         switch (evt[0].textcode) {
1646
1647             case 'SUCCESS':
1648             case 'NO_CHANGE':
1649
1650                 switch(Number(copy.status().id())) {
1651
1652                     case 0: /* AVAILABLE */                                        
1653                     case 4: /* MISSING */                                          
1654                     case 7: /* RESHELVING */ 
1655
1656                         egCore.audio.play('success.checkin');
1657
1658                         // see if the copy location requires an alert
1659                         return service.handle_checkin_loc_alert(evt, params, options)
1660                         .then(function() {return final_resp});
1661
1662                     case 8: /* ON HOLDS SHELF */
1663                         egCore.audio.play('info.checkin.holds_shelf');
1664                         
1665                         if (hold) {
1666
1667                             if (hold.pickup_lib() == egCore.auth.user().ws_ou()) {
1668                                 // inform user if the item is on the local holds shelf
1669                             
1670                                 evt[0].route_to = egCore.strings.ROUTE_TO_HOLDS_SHELF;
1671                                 return service.route_dialog(
1672                                     './circ/share/t_hold_shelf_dialog', 
1673                                     evt[0], params, options
1674                                 ).then(function() { return final_resp });
1675
1676                             } else {
1677                                 // normally, if the hold was on the shelf at a 
1678                                 // different location, it would be put into 
1679                                 // transit, resulting in a ROUTE_ITEM event.
1680                                 egCore.audio.play('warning.checkin.wrong_shelf');
1681                                 return $q.when(final_resp);
1682                             }
1683                         } else {
1684
1685                             console.error('checkin: item on holds shelf, '
1686                                 + 'but hold info not returned from checkin');
1687                             return $q.when(final_resp);
1688                         }
1689
1690                     case 11: /* CATALOGING */
1691                         egCore.audio.play('info.checkin.cataloging');
1692                         evt[0].route_to = egCore.strings.ROUTE_TO_CATALOGING;
1693                         if (options.no_precat_alert || options.suppress_popups)
1694                             return $q.when(final_resp);
1695                         return egAlertDialog.open(
1696                             egCore.strings.PRECAT_CHECKIN_MSG, params)
1697                             .result.then(function() {return final_resp});
1698
1699
1700                     case 15: /* ON_RESERVATION_SHELF */
1701                         egCore.audio.play('info.checkin.reservation');
1702                         // TODO: show booking reservation dialog
1703                         return $q.when(final_resp);
1704
1705                     default:
1706                         egCore.audio.play('success.checkin');
1707                         console.debug('Unusual checkin copy status (may have been set via copy alert): '
1708                             + copy.status().id() + ' : ' + copy.status().name());
1709                         return $q.when(final_resp);
1710                 }
1711                 
1712             case 'ROUTE_ITEM':
1713                 return service.route_dialog(
1714                     './circ/share/t_transit_dialog', 
1715                     evt[0], params, options
1716                 ).then(function(data) {
1717                     if (transit && data.transit && transit.dest().id() != data.transit.dest().id())
1718                         final_resp.evt[0].route_to = data.transit.dest().shortname();
1719                     return final_resp;
1720                 });
1721
1722             case 'ASSET_COPY_NOT_FOUND':
1723                 egCore.audio.play('error.checkin.not_found');
1724                 if (options.suppress_popups) return $q.when(final_resp);
1725                 return egAlertDialog.open(
1726                     egCore.strings.UNCAT_ALERT_DIALOG, params)
1727                     .result.then(function() {return final_resp});
1728
1729             case 'ITEM_NOT_CATALOGED':
1730                 egCore.audio.play('error.checkin.not_cataloged');
1731                 evt[0].route_to = egCore.strings.ROUTE_TO_CATALOGING;
1732                 if (options.no_precat_alert || options.suppress_popups)
1733                     return $q.when(final_resp);
1734                 return egAlertDialog.open(
1735                     egCore.strings.PRECAT_CHECKIN_MSG, params)
1736                     .result.then(function() {return final_resp});
1737
1738             default:
1739                 egCore.audio.play('error.checkin.unknown');
1740                 console.warn('unhandled checkin response : ' + evt[0].textcode);
1741                 return $q.when(final_resp);
1742         }
1743     }
1744
1745     // collect transit, address, and hold info that's not already
1746     // included in responses.
1747     service.collect_route_data = function(tmpl, evt, params, options) {
1748         if (angular.isArray(evt)) evt = evt[0];
1749         var promises = [];
1750         var data = {};
1751
1752         if (evt.org && !tmpl.match(/hold_shelf/)) {
1753             promises.push(
1754                 service.get_org_addr(evt.org, 'holds_address')
1755                 .then(function(addr) { data.address = addr })
1756             );
1757         }
1758
1759         if (evt.payload.hold) {
1760             promises.push(
1761                 egCore.pcrud.retrieve('au', 
1762                     evt.payload.hold.usr(), {
1763                         flesh : 1,
1764                         flesh_fields : {'au' : ['card']}
1765                     }
1766                 ).then(function(patron) {data.patron = patron})
1767             );
1768         }
1769
1770
1771         if (!tmpl.match(/hold_shelf/)) {
1772             var courier_deferred = $q.defer();
1773             promises.push(courier_deferred.promise);
1774             promises.push(
1775                 service.find_copy_transit(evt, params, options)
1776                 .then(function(trans) {
1777                     data.transit = trans;
1778                     egCore.org.settings('lib.courier_code', trans.dest().id())
1779                     .then(function(s) {
1780                         data.dest_courier_code = s['lib.courier_code'];
1781                         courier_deferred.resolve();
1782                     });
1783                 })
1784             );
1785         }
1786
1787         return $q.all(promises).then(function() { return data });
1788     }
1789
1790     service.route_dialog = function(tmpl, evt, params, options) {
1791         if (angular.isArray(evt)) evt = evt[0];
1792
1793         return service.collect_route_data(tmpl, evt, params, options)
1794         .then(function(data) {
1795
1796             var template = data.transit ?
1797                 (data.patron ? 'hold_transit_slip' : 'transit_slip') :
1798                 'hold_shelf_slip';
1799             if (service.never_auto_print[template]) {
1800                 // do not show the dialog or print if the
1801                 // disabled automatic print attempt type list includes
1802                 // the specified template
1803                 return data;
1804             }
1805
1806             // All actions flow from the print data
1807
1808             var print_context = {
1809                 copy : egCore.idl.toHash(evt.payload.copy),
1810                 title : evt.title,
1811                 author : evt.author,
1812                 call_number : egCore.idl.toHash(evt.payload.volume)
1813             };
1814
1815             var acn = print_context.call_number; // fix up pre/suffixes
1816             if (acn.prefix == -1) acn.prefix = "";
1817             if (acn.suffix == -1) acn.suffix = "";
1818
1819             if (data.transit) {
1820                 // route_dialog includes the "route to holds shelf" 
1821                 // dialog, which has no transit
1822                 print_context.transit = egCore.idl.toHash(data.transit);
1823                 print_context.dest_courier_code = data.dest_courier_code;
1824                 if (data.address) {
1825                     print_context.dest_address = egCore.idl.toHash(data.address);
1826                 }
1827                 print_context.dest_location =
1828                     egCore.idl.toHash(egCore.org.get(data.transit.dest()));
1829                 print_context.copy.status = egCore.idl.toHash(print_context.copy.status);
1830             }
1831
1832             if (data.patron) {
1833                 print_context.hold = egCore.idl.toHash(evt.payload.hold);
1834                 var notes = print_context.hold.notes;
1835                 if(notes.length > 0){
1836                     print_context.hold_notes = [];
1837                     angular.forEach(notes, function(n){
1838                         print_context.hold_notes.push(n);
1839                     });
1840                 }
1841                 print_context.patron = egCore.idl.toHash(data.patron);
1842             }
1843
1844             var sound = 'info.checkin.transit';
1845             if (evt.payload.hold) sound += '.hold';
1846             egCore.audio.play(sound);
1847
1848             function print_transit(template) {
1849                 return egCore.print.print({
1850                     context : 'default', 
1851                     template : template, 
1852                     scope : print_context
1853                 }).then(function() { return data });
1854             }
1855
1856             // when auto-print is on, skip the dialog and go straight
1857             // to printing.
1858             if (options.auto_print_holds_transits || options.suppress_popups) 
1859                 return print_transit(template);
1860
1861             return $uibModal.open({
1862                 templateUrl: tmpl,
1863                 backdrop: 'static',
1864                 controller: [
1865                             '$scope','$uibModalInstance',
1866                     function($scope , $uibModalInstance) {
1867
1868                     $scope.today = new Date();
1869
1870                     // copy the print scope into the dialog scope
1871                     angular.forEach(print_context, function(val, key) {
1872                         $scope[key] = val;
1873                     });
1874
1875                     $scope.ok = function() {$uibModalInstance.close()}
1876
1877                     $scope.print = function() { 
1878                         $uibModalInstance.close();
1879                         print_transit(template);
1880                     }
1881                 }]
1882
1883             }).result.then(function() { return data });
1884         });
1885     }
1886
1887     // action == what action to take if the user confirms the alert
1888     service.copy_alert_dialog = function(evt, params, options, action) {
1889         if (angular.isArray(evt)) evt = evt[0];
1890         if (!angular.isArray(evt.payload)) {
1891             return egConfirmDialog.open(
1892                 egCore.strings.COPY_ALERT_MSG_DIALOG_TITLE, 
1893                 evt.payload,  // payload == alert message text
1894                 {   copy_barcode : params.copy_barcode,
1895                     ok : function() {},
1896                     cancel : function() {}
1897                 }
1898             ).result.then(function() {
1899                 options.override = true;
1900                 return service[action](params, options);
1901             });
1902         } else { // we got a list of copy alert objects ...
1903             return egCopyAlertManagerDialog.open({
1904                 alerts : evt.payload,
1905                 mode : action,
1906                 ok : function(the_next_status) {
1907                         if (the_next_status !== null) {
1908                             params.next_copy_status = [ the_next_status ];
1909                             params.capture = 'nocapture';
1910                         }
1911                      },
1912                 cancel : function() {}
1913             }).result.then(function() {
1914                 options.override = true;
1915                 return service[action](params, options);
1916             });
1917         }
1918     }
1919
1920     // action == what action to take if the user confirms the alert
1921     service.hold_capture_delay_dialog = function(evt, params, options, action) {
1922         if (angular.isArray(evt)) evt = evt[0];
1923         return $uibModal.open({
1924             templateUrl: './circ/checkin/t_hold_verify',
1925             backdrop: 'static',
1926             controller:
1927                        ['$scope','$uibModalInstance','params',
1928                 function($scope , $uibModalInstance , params) {
1929                 $scope.copy_barcode = params.copy_barcode;
1930                 $scope.capture = function() {
1931                     params.capture = 'capture';
1932                     $uibModalInstance.close();
1933                 };
1934                 $scope.nocapture = function() {
1935                     params.capture = 'nocapture';
1936                     $uibModalInstance.close();
1937                 };
1938                 $scope.cancel = function() { $uibModalInstance.dismiss(); };
1939             }],
1940             resolve : {
1941                 params : function() {
1942                     return params;
1943                 }
1944             }
1945         }).result.then(
1946             function(r) {
1947                 return service[action](params, options);
1948             }
1949         );
1950     }
1951
1952     // check the barcode.  If it's no good, show the warning dialog
1953     // Resolves on success, rejected on error
1954     service.test_barcode = function(bc) {
1955
1956         var ok = service.check_barcode(bc);
1957         if (ok) return $q.when();
1958
1959         egCore.audio.play('warning.circ.bad_barcode');
1960         return $uibModal.open({
1961             templateUrl: './circ/share/t_bad_barcode_dialog',
1962             backdrop: 'static',
1963             controller: 
1964                 ['$scope', '$uibModalInstance', 
1965                 function($scope, $uibModalInstance) {
1966                 $scope.barcode = bc;
1967                 $scope.ok = function() { $uibModalInstance.close() }
1968                 $scope.cancel = function() { $uibModalInstance.dismiss() }
1969             }]
1970         }).result;
1971     }
1972
1973     // check() and checkdigit() copied directly 
1974     // from chrome/content/util/barcode.js
1975
1976     service.check_barcode = function(bc) {
1977         if (bc != Number(bc)) return false;
1978         bc = bc.toString();
1979         // "16.00" == Number("16.00"), but the . is bad.
1980         // Throw out any barcode that isn't just digits
1981         if (bc.search(/\D/) != -1) return false;
1982         var last_digit = bc.substr(bc.length-1);
1983         var stripped_barcode = bc.substr(0,bc.length-1);
1984         return service.barcode_checkdigit(stripped_barcode).toString() == last_digit;
1985     }
1986
1987     service.barcode_checkdigit = function(bc) {
1988         var reverse_barcode = bc.toString().split('').reverse();
1989         var check_sum = 0; var multiplier = 2;
1990         for (var i = 0; i < reverse_barcode.length; i++) {
1991             var digit = reverse_barcode[i];
1992             var product = digit * multiplier; product = product.toString();
1993             var temp_sum = 0;
1994             for (var j = 0; j < product.length; j++) {
1995                 temp_sum += Number( product[j] );
1996             }
1997             check_sum += Number( temp_sum );
1998             multiplier = ( multiplier == 2 ? 1 : 2 );
1999         }
2000         check_sum = check_sum.toString();
2001         var next_multiple_of_10 = (check_sum.match(/(\d*)\d$/)[1] * 10) + 10;
2002         var check_digit = next_multiple_of_10 - Number(check_sum);
2003         if (check_digit == 10) check_digit = 0;
2004         return check_digit;
2005     }
2006
2007     service.handle_barcode_completion = function(barcode) {
2008         return egCore.net.request(
2009             'open-ils.actor',
2010             'open-ils.actor.get_barcodes',
2011             egCore.auth.token(), egCore.auth.user().ws_ou(), 
2012             'asset', barcode)
2013
2014         .then(function(resp) {
2015             // TODO: handle event during barcode lookup
2016             if (evt = egCore.evt.parse(resp)) {
2017                 console.error(evt.toString());
2018                 return $q.reject();
2019             }
2020
2021             // no matching barcodes: return the barcode as entered
2022             // by the user (so that, e.g., checkout can fall back to
2023             // precat/noncat handling)
2024             if (!resp || !resp[0]) {
2025                 return barcode;
2026             }
2027
2028             // exactly one matching barcode: return it
2029             if (resp.length == 1) {
2030                 return resp[0].barcode;
2031             }
2032
2033             // multiple matching barcodes: let the user pick one 
2034             console.debug('multiple matching barcodes');
2035             var matches = [];
2036             var promises = [];
2037             var final_barcode;
2038             angular.forEach(resp, function(cp) {
2039                 promises.push(
2040                     egCore.net.request(
2041                         'open-ils.circ',
2042                         'open-ils.circ.copy_details.retrieve',
2043                         egCore.auth.token(), cp.id
2044                     ).then(function(r) {
2045                         matches.push({
2046                             barcode: r.copy.barcode(),
2047                             title: r.mvr.title(),
2048                             org_name: egCore.org.get(r.copy.circ_lib()).name(),
2049                             org_shortname: egCore.org.get(r.copy.circ_lib()).shortname()
2050                         });
2051                     })
2052                 );
2053             });
2054             return $q.all(promises)
2055             .then(function() {
2056                 return $uibModal.open({
2057                     templateUrl: './circ/share/t_barcode_choice_dialog',
2058                     backdrop: 'static',
2059                     controller:
2060                         ['$scope', '$uibModalInstance',
2061                         function($scope, $uibModalInstance) {
2062                         $scope.matches = matches;
2063                         $scope.ok = function(barcode) {
2064                             $uibModalInstance.close();
2065                             final_barcode = barcode;
2066                         }
2067                         $scope.cancel = function() {$uibModalInstance.dismiss()}
2068                     }],
2069                 }).result.then(function() { return final_barcode });
2070             })
2071         });
2072     }
2073
2074     service.create_penalty = function(user_id) {
2075         return $uibModal.open({
2076             templateUrl: './circ/share/t_new_message_dialog',
2077             backdrop: 'static',
2078             controller: 
2079                    ['$scope','$uibModalInstance','staffPenalties',
2080             function($scope , $uibModalInstance , staffPenalties) {
2081                 $scope.focusNote = true;
2082                 $scope.penalties = staffPenalties;
2083                 $scope.require_initials = service.require_initials;
2084                 $scope.args = {penalty : 21}; // default to Note
2085                 $scope.setPenalty = function(id) {
2086                     args.penalty = id;
2087                 }
2088                 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
2089                 $scope.cancel = function($event) { 
2090                     $uibModalInstance.dismiss();
2091                     $event.preventDefault();
2092                 }
2093             }],
2094             resolve : { staffPenalties : service.get_staff_penalty_types }
2095         }).result.then(
2096             function(args) {
2097                 var pen = new egCore.idl.ausp();
2098                 pen.usr(user_id);
2099                 pen.org_unit(egCore.auth.user().ws_ou());
2100                 pen.note(args.note);
2101                 if (args.initials) pen.note(args.note + ' [' + args.initials + ']');
2102                 if (args.custom_penalty) {
2103                     pen.standing_penalty(args.custom_penalty);
2104                 } else {
2105                     pen.standing_penalty(args.penalty);
2106                 }
2107                 pen.staff(egCore.auth.user().id());
2108                 pen.set_date('now');
2109
2110                 return egCore.net.request(
2111                     'open-ils.actor',
2112                     'open-ils.actor.user.penalty.apply',
2113                     egCore.auth.token(), pen
2114                 );
2115             }
2116         );
2117     }
2118
2119     // assumes, for now anyway,  penalty type is fleshed onto usr_penalty.
2120     service.edit_penalty = function(usr_penalty) {
2121         return $uibModal.open({
2122             templateUrl: './circ/share/t_new_message_dialog',
2123             backdrop: 'static',
2124             controller: 
2125                    ['$scope','$uibModalInstance','staffPenalties',
2126             function($scope , $uibModalInstance , staffPenalties) {
2127                 $scope.focusNote = true;
2128                 $scope.penalties = staffPenalties;
2129                 $scope.require_initials = service.require_initials;
2130                 $scope.args = {
2131                     penalty : usr_penalty.standing_penalty().id(),
2132                     note : usr_penalty.note()
2133                 }
2134                 $scope.setPenalty = function(id) { args.penalty = id; }
2135                 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
2136                 $scope.cancel = function($event) { 
2137                     $uibModalInstance.dismiss();
2138                     $event.preventDefault();
2139                 }
2140             }],
2141             resolve : { staffPenalties : service.get_staff_penalty_types }
2142         }).result.then(
2143             function(args) {
2144                 usr_penalty.note(args.note);
2145                 if (args.initials) usr_penalty.note(args.note + ' [' + args.initials + ']');
2146                 usr_penalty.standing_penalty(args.penalty);
2147                 return egCore.pcrud.update(usr_penalty);
2148             }
2149         );
2150     }
2151
2152     return service;
2153
2154 }]);
2155
2156