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