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