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