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