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