]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/services/circ.js
3c16f42de4311f90c0cbdee17f971ce63b839cc6
[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             controller: 
710                 ['$scope', '$uibModalInstance', 
711                 function($scope, $uibModalInstance) {
712                 $scope.events = evt;
713                 $scope.auto_override =
714                     evt.filter(function(e){
715                         return service.checkout_auto_override_after_first.indexOf(evt.textcode) > -1;
716                     }).length > 0;
717                 $scope.copy_barcode = params.copy_barcode; // may be null
718                 $scope.ok = function() { $uibModalInstance.close() }
719                 $scope.cancel = function ($event) { 
720                     $uibModalInstance.dismiss();
721                     $event.preventDefault();
722                 }
723             }]
724         }).result.then(
725             function() {
726                 options.override = true;
727
728                 if (action == 'checkin') {
729                     return service.checkin(params, options);
730                 }
731
732                 // checkout/renew support override-after-first
733                 angular.forEach(evt, function(e){
734                     if (service.checkout_auto_override_after_first.indexOf(e.textcode) > -1)
735                         service.auto_override_checkout_events[e.textcode] = true;
736                 });
737
738                 return service[action](params, options);
739             }
740         );
741     }
742
743     service.copy_not_avail_dialog = function(evt, params, options) {
744         if (angular.isArray(evt)) evt = evt[0];
745         return $uibModal.open({
746             templateUrl: './circ/share/t_copy_not_avail_dialog',
747             controller: 
748                        ['$scope','$uibModalInstance','copyStatus',
749                 function($scope , $uibModalInstance , copyStatus) {
750                 $scope.copyStatus = copyStatus;
751                 $scope.ok = function() {$uibModalInstance.close()}
752                 $scope.cancel = function() {$uibModalInstance.dismiss()}
753             }],
754             resolve : {
755                 copyStatus : function() {
756                     return egCore.pcrud.retrieve(
757                         'ccs', evt.payload.status());
758                 }
759             }
760         }).result.then(
761             function() {
762                 options.override = true;
763                 return service.checkout(params, options);
764             }
765         );
766     }
767
768     // Opens a dialog allowing the user to fill in the desired non-cat count.
769     // Unlike other dialogs, which kickoff circ actions internally
770     // as a result of events, this dialog does not kick off any circ
771     // actions. It just collects the count and and resolves the promise.
772     //
773     // This assumes the caller has already handled the noncat-type
774     // selection and just needs to collect the count info.
775     service.noncat_dialog = function(params, options) {
776         var noncatMax = 99; // hard-coded max
777         
778         // the caller should presumably have fetched the noncat_types via
779         // our API already, but fetch them again (from cache) to be safe.
780         return service.get_noncat_types().then(function() {
781
782             params.noncat = true;
783             var type = egCore.env.cnct.map[params.noncat_type];
784
785             return $uibModal.open({
786                 templateUrl: './circ/share/t_noncat_dialog',
787                 controller: 
788                     ['$scope', '$uibModalInstance',
789                     function($scope, $uibModalInstance) {
790                     $scope.focusMe = true;
791                     $scope.type = type;
792                     $scope.count = 1;
793                     $scope.noncatMax = noncatMax;
794                     $scope.ok = function(count) { $uibModalInstance.close(count) }
795                     $scope.cancel = function ($event) { 
796                         $uibModalInstance.dismiss() 
797                         $event.preventDefault();
798                     }
799                 }],
800             }).result.then(
801                 function(count) {
802                     if (count && count > 0 && count <= noncatMax) { 
803                         // NOTE: in Chrome, form validation ensure a valid number
804                         params.noncat_count = count;
805                         return $q.when(params);
806                     } else {
807                         return $q.reject();
808                     }
809                 }
810             );
811         });
812     }
813
814     // Opens a dialog allowing the user to fill in pre-cat copy info.
815     service.precat_dialog = function(params, options) {
816
817         return $uibModal.open({
818             templateUrl: './circ/share/t_precat_dialog',
819             controller: 
820                 ['$scope', '$uibModalInstance', 'circMods',
821                 function($scope, $uibModalInstance, circMods) {
822                 $scope.focusMe = true;
823                 $scope.precatArgs = {
824                     copy_barcode : params.copy_barcode
825                 };
826                 $scope.circModifiers = circMods;
827                 $scope.ok = function(args) { $uibModalInstance.close(args) }
828                 $scope.cancel = function () { $uibModalInstance.dismiss() }
829
830                 // use this function as a keydown handler on form
831                 // elements that should not submit the form on enter.
832                 $scope.preventSubmit = function($event) {
833                     if ($event.keyCode == 13)
834                         $event.preventDefault();
835                 }
836             }],
837             resolve : {
838                 circMods : function() { 
839                     return service.get_circ_mods();
840                 }
841             }
842         }).result.then(
843             function(args) {
844                 if (!args || !args.dummy_title) return $q.reject();
845                 if(args.circ_modifier == "") args.circ_modifier = null;
846                 angular.forEach(args, function(val, key) {params[key] = val});
847                 params.precat = true;
848                 return service.checkout(params, options);
849             }
850         );
851     }
852
853     // find the open transit for the given copy barcode; flesh the org
854     // units locally.
855     service.find_copy_transit = function(evt, params, options) {
856         if (angular.isArray(evt)) evt = evt[0];
857
858         if (evt && evt.payload && evt.payload.transit)
859             return $q.when(evt.payload.transit);
860
861          return egCore.pcrud.search('atc',
862             {   dest_recv_time : null},
863             {   flesh : 1, 
864                 flesh_fields : {atc : ['target_copy']},
865                 join : {
866                     acp : {
867                         filter : {
868                             barcode : params.copy_barcode,
869                             deleted : 'f'
870                         }
871                     }
872                 },
873                 limit : 1,
874                 order_by : {atc : 'source_send_time desc'}, 
875             }
876         ).then(function(transit) {
877             transit.source(egCore.org.get(transit.source()));
878             transit.dest(egCore.org.get(transit.dest()));
879             return transit;
880         });
881     }
882
883     service.copy_in_transit_dialog = function(evt, params, options) {
884         if (angular.isArray(evt)) evt = evt[0];
885         return $uibModal.open({
886             templateUrl: './circ/share/t_copy_in_transit_dialog',
887             controller: 
888                        ['$scope','$uibModalInstance','transit',
889                 function($scope , $uibModalInstance , transit) {
890                 $scope.transit = transit;
891                 $scope.ok = function() { $uibModalInstance.close(transit) }
892                 $scope.cancel = function() { $uibModalInstance.dismiss() }
893             }],
894             resolve : {
895                 // fetch the conflicting open transit w/ fleshed copy
896                 transit : function() {
897                     return service.find_copy_transit(evt, params, options);
898                 }
899             }
900         }).result.then(
901             function(transit) {
902                 // user chose to abort the transit then checkout
903                 return service.abort_transit(transit.id())
904                 .then(function() {
905                     return service.checkout(params, options);
906                 });
907             }
908         );
909     }
910
911     service.abort_transit = function(transit_id) {
912         return egCore.net.request(
913             'open-ils.circ',
914             'open-ils.circ.transit.abort',
915             egCore.auth.token(), {transitid : transit_id}
916         ).then(function(resp) {
917             if (evt = egCore.evt.parse(resp)) {
918                 alert(evt);
919                 return $q.reject();
920             }
921             return $q.when();
922         });
923     }
924
925     service.last_copy_circ = function(copy_id) {
926         return egCore.pcrud.search('circ', 
927             {target_copy : copy_id},
928             {order_by : {circ : 'xact_start desc' }, limit : 1}
929         );
930     }
931
932     service.circ_exists_dialog = function(evt, params, options) {
933         if (angular.isArray(evt)) evt = evt[0];
934
935         if (!evt.payload.old_circ) {
936             return egCore.pcrud.search('circ',
937                 {target_copy : evt.payload.copy.id(), checkin_time : null},
938                 {limit : 1} // should only ever be 1
939             ).then(function(old_circ) {
940                 evt.payload.old_circ = old_circ;
941                return service.circ_exists_dialog_impl(evt, params, options);
942             });
943         } else {
944             return service.circ_exists_dialog_impl( evt, params, options );
945         }
946     },
947
948     service.circ_exists_dialog_impl = function (evt, params, options) {
949
950         var openCirc = evt.payload.old_circ;
951         var sameUser = openCirc.usr() == params.patron_id;
952         
953         return $uibModal.open({
954             templateUrl: './circ/share/t_circ_exists_dialog',
955             controller: 
956                        ['$scope','$uibModalInstance',
957                 function($scope , $uibModalInstance) {
958                 $scope.args = {forgive_fines : false};
959                 $scope.circDate = openCirc.xact_start();
960                 $scope.sameUser = sameUser;
961                 $scope.ok = function() { $uibModalInstance.close($scope.args) }
962                 $scope.cancel = function($event) { 
963                     $uibModalInstance.dismiss();
964                     $event.preventDefault(); // form, avoid calling ok();
965                 }
966             }]
967         }).result.then(
968             function(args) {
969                 if (sameUser) {
970                     params.void_overdues = args.forgive_fines;
971                     options.override = true;
972                     return service.renew(params, options);
973                 }
974
975                 return service.checkin({
976                     barcode : params.copy_barcode,
977                     noop : true,
978                     override : true,
979                     void_overdues : args.forgive_fines
980                 }).then(function(checkin_resp) {
981                     if (checkin_resp.evt[0].textcode == 'SUCCESS') {
982                         return service.checkout(params, options);
983                     } else {
984                         alert(egCore.evt.parse(checkin_resp.evt[0]));
985                         return $q.reject();
986                     }
987                 });
988             }
989         );
990     }
991
992     service.batch_backdate = function(circ_ids, backdate) {
993         return egCore.net.request(
994             'open-ils.circ',
995             'open-ils.circ.post_checkin_backdate.batch',
996             egCore.auth.token(), circ_ids, backdate);
997     }
998
999     service.backdate_dialog = function(circ_ids) {
1000         return $uibModal.open({
1001             templateUrl: './circ/share/t_backdate_dialog',
1002             controller: 
1003                        ['$scope','$uibModalInstance',
1004                 function($scope , $uibModalInstance) {
1005
1006                 var today = new Date();
1007                 $scope.dialog = {
1008                     num_circs : circ_ids.length,
1009                     num_processed : 0,
1010                     backdate : today
1011                 }
1012
1013                 $scope.$watch('dialog.backdate', function(newval) {
1014                     if (newval && newval > today) 
1015                         $scope.dialog.backdate = today;
1016                 });
1017
1018
1019                 $scope.cancel = function() { 
1020                     $uibModalInstance.dismiss();
1021                 }
1022
1023                 $scope.ok = function() { 
1024
1025                     var bd = $scope.dialog.backdate.toISOString().replace(/T.*/,'');
1026                     service.batch_backdate(circ_ids, bd)
1027                     .then(
1028                         function() { // on complete
1029                             $uibModalInstance.close({backdate : bd});
1030                         },
1031                         null,
1032                         function(resp) { // on response
1033                             console.debug('backdate returned ' + resp);
1034                             if (resp == '1') {
1035                                 $scope.num_processed++;
1036                             } else {
1037                                 console.error(egCore.evt.parse(resp));
1038                             }
1039                         }
1040                     );
1041                 }
1042             }]
1043         }).result;
1044     }
1045
1046     service.mark_claims_returned = function(barcode, date, override) {
1047
1048         var method = 'open-ils.circ.circulation.set_claims_returned';
1049         if (override) method += '.override';
1050
1051         console.debug('claims returned ' + method);
1052
1053         return egCore.net.request(
1054             'open-ils.circ', method, egCore.auth.token(),
1055             {barcode : barcode, backdate : date})
1056
1057         .then(function(resp) {
1058
1059             if (resp == 1) { // success
1060                 console.debug('claims returned succeeded for ' + barcode);
1061                 return barcode;
1062
1063             } else if (evt = egCore.evt.parse(resp)) {
1064                 console.debug('claims returned failed: ' + evt.toString());
1065
1066                 if (evt.textcode == 'PATRON_EXCEEDS_CLAIMS_RETURN_COUNT') {
1067                     // TODO check perms before offering override option?
1068
1069                     if (override) return;// just to be safe
1070
1071                     return egConfirmDialog.open(
1072                         egCore.strings.TOO_MANY_CLAIMS_RETURNED, '', {}
1073                     ).result.then(function() {
1074                         return service.mark_claims_returned(barcode, date, true);
1075                     });
1076                 }
1077
1078                 if (evt.textcode == 'PERM_FAILURE') {
1079                     console.error('claims returned permission denied')
1080                     // TODO: auth override dialog?
1081                 }
1082             }
1083         });
1084     }
1085
1086     service.mark_claims_returned_dialog = function(copy_barcodes) {
1087         if (!copy_barcodes.length) return;
1088
1089         return $uibModal.open({
1090             templateUrl: './circ/share/t_mark_claims_returned_dialog',
1091             controller: 
1092                        ['$scope','$uibModalInstance',
1093                 function($scope , $uibModalInstance) {
1094
1095                 var today = new Date();
1096                 $scope.args = {
1097                     barcodes : copy_barcodes,
1098                     date : today
1099                 };
1100
1101                 $scope.$watch('args.date', function(newval) {
1102                     if (newval && newval > today) 
1103                         $scope.args.backdate = today;
1104                 });
1105
1106                 $scope.cancel = function() {$uibModalInstance.dismiss()}
1107                 $scope.ok = function() { 
1108
1109                     var date = $scope.args.date.toISOString().replace(/T.*/,'');
1110
1111                     var deferred = $q.defer();
1112
1113                     // serialize the action on each barcode so that the 
1114                     // caller will never see multiple alerts at the same time.
1115                     function mark_one() {
1116                         var bc = copy_barcodes.pop();
1117                         if (!bc) {
1118                             deferred.resolve();
1119                             $uibModalInstance.close();
1120                             return;
1121                         }
1122
1123                         // finally -> continue even when one fails
1124                         service.mark_claims_returned(bc, date)
1125                         .finally(function(barcode) {
1126                             if (barcode) deferred.notify(barcode);
1127                             mark_one();
1128                         });
1129                     }
1130                     mark_one(); // kick it off
1131                     return deferred.promise;
1132                 }
1133             }]
1134         }).result;
1135     }
1136
1137     // serially checks in each barcode with claims_never_checked_out set
1138     // returns promise, notified on each barcode, resolved after all
1139     // checkins are complete.
1140     service.mark_claims_never_checked_out = function(barcodes) {
1141         if (!barcodes.length) return;
1142
1143         var deferred = $q.defer();
1144         egConfirmDialog.open(
1145             egCore.strings.MARK_NEVER_CHECKED_OUT, '', {barcodes : barcodes}
1146
1147         ).result.then(function() {
1148             function mark_one() {
1149                 var bc = barcodes.pop();
1150
1151                 if (!bc) { // all done
1152                     deferred.resolve();
1153                     return;
1154                 }
1155
1156                 service.checkin(
1157                     {claims_never_checked_out : true, copy_barcode : bc})
1158                 .finally(function() { 
1159                     deferred.notify(bc);
1160                     mark_one();
1161                 })
1162             }
1163             mark_one();
1164         });
1165
1166         return deferred.promise;
1167     }
1168
1169     service.mark_damaged = function(copy_ids) {
1170         return egConfirmDialog.open(
1171             egCore.strings.MARK_DAMAGED_CONFIRM, '',
1172             {   num_items : copy_ids.length,
1173                 ok : function() {},
1174                 cancel : function() {}
1175             }
1176
1177         ).result.then(function() {
1178             var promises = [];
1179             angular.forEach(copy_ids, function(copy_id) {
1180                 promises.push(
1181                     egCore.net.request(
1182                         'open-ils.circ',
1183                         'open-ils.circ.mark_item_damaged',
1184                         egCore.auth.token(), copy_id
1185                     ).then(function(resp) {
1186                         if (evt = egCore.evt.parse(resp)) {
1187                             console.error('mark damaged failed: ' + evt);
1188                         }
1189                     })
1190                 );
1191             });
1192
1193             return $q.all(promises);
1194         });
1195     }
1196
1197     service.mark_missing = function(copy_ids) {
1198         return egConfirmDialog.open(
1199             egCore.strings.MARK_MISSING_CONFIRM, '',
1200             {   num_items : copy_ids.length,
1201                 ok : function() {},
1202                 cancel : function() {}
1203             }
1204         ).result.then(function() {
1205             var promises = [];
1206             angular.forEach(copy_ids, function(copy_id) {
1207                 promises.push(
1208                     egCore.net.request(
1209                         'open-ils.circ',
1210                         'open-ils.circ.mark_item_missing',
1211                         egCore.auth.token(), copy_id
1212                     ).then(function(resp) {
1213                         if (evt = egCore.evt.parse(resp)) {
1214                             console.error('mark missing failed: ' + evt);
1215                         }
1216                     })
1217                 );
1218             });
1219
1220             return $q.all(promises);
1221         });
1222     }
1223
1224
1225
1226     // Mark circulations as lost via copy barcode.  As each item is 
1227     // processed, the returned promise is notified of the barcode.
1228     // No confirmation dialog is presented.
1229     service.mark_lost = function(copy_barcodes) {
1230         var deferred = $q.defer();
1231         var promises = [];
1232
1233         angular.forEach(copy_barcodes, function(barcode) {
1234             promises.push(
1235                 egCore.net.request(
1236                     'open-ils.circ',
1237                     'open-ils.circ.circulation.set_lost',
1238                     egCore.auth.token(), {barcode : barcode}
1239                 ).then(function(resp) {
1240                     if (evt = egCore.evt.parse(resp)) {
1241                         console.error("Mark lost failed: " + evt.toString());
1242                         return;
1243                     }
1244                     // inform the caller as each item is processed
1245                     deferred.notify(barcode);
1246                 })
1247             );
1248         });
1249
1250         $q.all(promises).then(function() {deferred.resolve()});
1251         return deferred.promise;
1252     }
1253
1254     service.abort_transits = function(transit_ids) {
1255         return egConfirmDialog.open(
1256             egCore.strings.ABORT_TRANSIT_CONFIRM, '',
1257             {   num_transits : transit_ids.length,
1258                 ok : function() {},
1259                 cancel : function() {}
1260             }
1261
1262         ).result.then(function() {
1263             var promises = [];
1264             angular.forEach(transit_ids, function(transit_id) {
1265                 promises.push(
1266                     egCore.net.request(
1267                         'open-ils.circ',
1268                         'open-ils.circ.transit.abort',
1269                         egCore.auth.token(), {transitid : transit_id}
1270                     ).then(function(resp) {
1271                         if (evt = egCore.evt.parse(resp)) {
1272                             console.error('abort transit failed: ' + evt);
1273                         }
1274                     })
1275                 );
1276             });
1277
1278             return $q.all(promises);
1279         });
1280     }
1281
1282
1283
1284     // alert when copy location alert_message is set.
1285     // This does not affect processing, it only produces a click-through
1286     service.handle_checkin_loc_alert = function(evt, params, options) {
1287         if (angular.isArray(evt)) evt = evt[0];
1288
1289         var copy = evt && evt.payload ? evt.payload.copy : null;
1290
1291         if (copy && !options.suppress_checkin_popups
1292             && copy.location().checkin_alert() == 't') {
1293
1294             return egAlertDialog.open(
1295                 egCore.strings.LOCATION_ALERT_MSG, {copy : copy}).result;
1296         }
1297
1298         return $q.when();
1299     }
1300
1301     service.handle_checkin_resp = function(evt, params, options) {
1302         if (!angular.isArray(evt)) evt = [evt];
1303
1304         var final_resp = {evt : evt, params : params, options : options};
1305
1306         var copy, hold, transit;
1307         if (evt[0].payload) {
1308             copy = evt[0].payload.copy;
1309             hold = evt[0].payload.hold;
1310             transit = evt[0].payload.transit;
1311         }
1312
1313         // track the barcode regardless of whether it's valid
1314         angular.forEach(evt, function(e){ e.copy_barcode = params.copy_barcode; });
1315
1316         angular.forEach(evt, function(e){ console.debug('checkin event ' + e.textcode); });
1317
1318         if (evt.filter(function(e){return service.checkin_overridable_events.indexOf(e.textcode) > -1;}).length > 0)
1319             return service.handle_overridable_checkin_event(evt, params, options);
1320
1321         switch (evt[0].textcode) {
1322
1323             case 'SUCCESS':
1324             case 'NO_CHANGE':
1325
1326                 switch(Number(copy.status().id())) {
1327
1328                     case 0: /* AVAILABLE */                                        
1329                     case 4: /* MISSING */                                          
1330                     case 7: /* RESHELVING */ 
1331
1332                         egCore.audio.play('success.checkin');
1333
1334                         // see if the copy location requires an alert
1335                         return service.handle_checkin_loc_alert(evt, params, options)
1336                         .then(function() {return final_resp});
1337
1338                     case 8: /* ON HOLDS SHELF */
1339                         egCore.audio.play('info.checkin.holds_shelf');
1340                         
1341                         if (hold) {
1342
1343                             if (hold.pickup_lib() == egCore.auth.user().ws_ou()) {
1344                                 // inform user if the item is on the local holds shelf
1345                             
1346                                 evt[0].route_to = egCore.strings.ROUTE_TO_HOLDS_SHELF;
1347                                 return service.route_dialog(
1348                                     './circ/share/t_hold_shelf_dialog', 
1349                                     evt[0], params, options
1350                                 ).then(function() { return final_resp });
1351
1352                             } else {
1353                                 // normally, if the hold was on the shelf at a 
1354                                 // different location, it would be put into 
1355                                 // transit, resulting in a ROUTE_ITEM event.
1356                                 egCore.audio.play('warning.checkin.wrong_shelf');
1357                                 return $q.when(final_resp);
1358                             }
1359                         } else {
1360
1361                             console.error('checkin: item on holds shelf, '
1362                                 + 'but hold info not returned from checkin');
1363                             return $q.when(final_resp);
1364                         }
1365
1366                     case 11: /* CATALOGING */
1367                         egCore.audio.play('info.checkin.cataloging');
1368                         evt[0].route_to = egCore.strings.ROUTE_TO_CATALOGING;
1369                         return $q.when(final_resp);
1370
1371                     case 15: /* ON_RESERVATION_SHELF */
1372                         egCore.audio.play('info.checkin.reservation');
1373                         // TODO: show booking reservation dialog
1374                         return $q.when(final_resp);
1375
1376                     default:
1377                         egCore.audio.play('error.checkin.unknown');
1378                         console.error('Unhandled checkin copy status: ' 
1379                             + copy.status().id() + ' : ' + copy.status().name());
1380                         return $q.when(final_resp);
1381                 }
1382                 
1383             case 'ROUTE_ITEM':
1384                 return service.route_dialog(
1385                     './circ/share/t_transit_dialog', 
1386                     evt[0], params, options
1387                 ).then(function() { return final_resp });
1388
1389             case 'ASSET_COPY_NOT_FOUND':
1390                 egCore.audio.play('error.checkin.not_found');
1391                 return egAlertDialog.open(
1392                     egCore.strings.UNCAT_ALERT_DIALOG, params)
1393                     .result.then(function() {return final_resp});
1394
1395             case 'ITEM_NOT_CATALOGED':
1396                 egCore.audio.play('error.checkin.not_cataloged');
1397                 evt[0].route_to = egCore.strings.ROUTE_TO_CATALOGING;
1398                 if (options.no_precat_alert) 
1399                     return $q.when(final_resp);
1400                 return egAlertDialog.open(
1401                     egCore.strings.PRECAT_CHECKIN_MSG, params)
1402                     .result.then(function() {return final_resp});
1403
1404             default:
1405                 egCore.audio.play('error.checkin.unknown');
1406                 console.warn('unhandled checkin response : ' + evt[0].textcode);
1407                 return $q.when(final_resp);
1408         }
1409     }
1410
1411     // collect transit, address, and hold info that's not already
1412     // included in responses.
1413     service.collect_route_data = function(tmpl, evt, params, options) {
1414         if (angular.isArray(evt)) evt = evt[0];
1415         var promises = [];
1416         var data = {};
1417
1418         if (evt.org && !tmpl.match(/hold_shelf/)) {
1419             promises.push(
1420                 service.get_org_addr(evt.org, 'holds_address')
1421                 .then(function(addr) { data.address = addr })
1422             );
1423         }
1424
1425         if (evt.payload.hold) {
1426             promises.push(
1427                 egCore.pcrud.retrieve('au', 
1428                     evt.payload.hold.usr(), {
1429                         flesh : 1,
1430                         flesh_fields : {'au' : ['card']}
1431                     }
1432                 ).then(function(patron) {data.patron = patron})
1433             );
1434         }
1435
1436
1437         if (!tmpl.match(/hold_shelf/)) {
1438             var courier_deferred = $q.defer();
1439             promises.push(courier_deferred.promise);
1440             promises.push(
1441                 service.find_copy_transit(evt, params, options)
1442                 .then(function(trans) {
1443                     data.transit = trans;
1444                     egCore.org.settings('lib.courier_code', trans.dest().id())
1445                     .then(function(s) {
1446                         data.dest_courier_code = s['lib.courier_code'];
1447                         courier_deferred.resolve();
1448                     });
1449                 })
1450             );
1451         }
1452
1453         return $q.all(promises).then(function() { return data });
1454     }
1455
1456     service.route_dialog = function(tmpl, evt, params, options) {
1457         if (angular.isArray(evt)) evt = evt[0];
1458
1459         return service.collect_route_data(tmpl, evt, params, options)
1460         .then(function(data) {
1461
1462             var template = data.transit ?
1463                 (data.patron ? 'hold_transit_slip' : 'transit_slip') :
1464                 'hold_shelf_slip';
1465             if (service.never_auto_print[template]) {
1466                 // do not show the dialog or print if the
1467                 // disabled automatic print attempt type list includes
1468                 // the specified template
1469                 return;
1470             }
1471
1472             // All actions flow from the print data
1473
1474             var print_context = {
1475                 copy : egCore.idl.toHash(evt.payload.copy),
1476                 title : evt.title,
1477                 author : evt.author,
1478                 call_number : egCore.idl.toHash(evt.payload.volume)
1479             };
1480
1481             var acn = print_context.call_number; // fix up pre/suffixes
1482             if (acn.prefix == -1) acn.prefix = "";
1483             if (acn.suffix == -1) acn.suffix = "";
1484
1485             if (data.transit) {
1486                 // route_dialog includes the "route to holds shelf" 
1487                 // dialog, which has no transit
1488                 print_context.transit = egCore.idl.toHash(data.transit);
1489                 print_context.dest_courier_code = data.dest_courier_code;
1490                 if (data.address) {
1491                     print_context.dest_address = egCore.idl.toHash(data.address);
1492                 }
1493                 print_context.dest_location =
1494                     egCore.idl.toHash(egCore.org.get(data.transit.dest()));
1495             }
1496
1497             if (data.patron) {
1498                 print_context.hold = egCore.idl.toHash(evt.payload.hold);
1499                 print_context.patron = egCore.idl.toHash(data.patron);
1500             }
1501
1502             var sound = 'info.checkin.transit';
1503             if (evt.payload.hold) sound += '.hold';
1504             egCore.audio.play(sound);
1505
1506             function print_transit(template) {
1507                 return egCore.print.print({
1508                     context : 'default', 
1509                     template : template, 
1510                     scope : print_context
1511                 });
1512             }
1513
1514             // when auto-print is on, skip the dialog and go straight
1515             // to printing.
1516             if (options.auto_print_holds_transits) 
1517                 return print_transit(template);
1518
1519             return $uibModal.open({
1520                 templateUrl: tmpl,
1521                 controller: [
1522                             '$scope','$uibModalInstance',
1523                     function($scope , $uibModalInstance) {
1524
1525                     $scope.today = new Date();
1526
1527                     // copy the print scope into the dialog scope
1528                     angular.forEach(print_context, function(val, key) {
1529                         $scope[key] = val;
1530                     });
1531
1532                     $scope.ok = function() {$uibModalInstance.close()}
1533
1534                     $scope.print = function() { 
1535                         $uibModalInstance.close();
1536                         print_transit(template);
1537                     }
1538                 }]
1539
1540             }).result;
1541         });
1542     }
1543
1544     // action == what action to take if the user confirms the alert
1545     service.copy_alert_dialog = function(evt, params, options, action) {
1546         if (angular.isArray(evt)) evt = evt[0];
1547         return egConfirmDialog.open(
1548             egCore.strings.COPY_ALERT_MSG_DIALOG_TITLE, 
1549             evt.payload,  // payload == alert message text
1550             {   copy_barcode : params.copy_barcode,
1551                 ok : function() {},
1552                 cancel : function() {}
1553             }
1554         ).result.then(function() {
1555             options.override = true;
1556             return service[action](params, options);
1557         });
1558     }
1559
1560     // action == what action to take if the user confirms the alert
1561     service.hold_capture_delay_dialog = function(evt, params, options, action) {
1562         if (angular.isArray(evt)) evt = evt[0];
1563         return $uibModal.open({
1564             templateUrl: './circ/checkin/t_hold_verify',
1565             controller:
1566                        ['$scope','$uibModalInstance','params',
1567                 function($scope , $uibModalInstance , params) {
1568                 $scope.copy_barcode = params.copy_barcode;
1569                 $scope.capture = function() {
1570                     params.capture = 'capture';
1571                     $uibModalInstance.close();
1572                 };
1573                 $scope.nocapture = function() {
1574                     params.capture = 'nocapture';
1575                     $uibModalInstance.close();
1576                 };
1577                 $scope.cancel = function() { $uibModalInstance.dismiss(); };
1578             }],
1579             resolve : {
1580                 params : function() {
1581                     return params;
1582                 }
1583             }
1584         }).result.then(
1585             function(r) {
1586                 return service[action](params, options);
1587             }
1588         );
1589     }
1590
1591     // check the barcode.  If it's no good, show the warning dialog
1592     // Resolves on success, rejected on error
1593     service.test_barcode = function(bc) {
1594
1595         var ok = service.check_barcode(bc);
1596         if (ok) return $q.when();
1597
1598         egCore.audio.play('warning.circ.bad_barcode');
1599         return $uibModal.open({
1600             templateUrl: './circ/share/t_bad_barcode_dialog',
1601             controller: 
1602                 ['$scope', '$uibModalInstance', 
1603                 function($scope, $uibModalInstance) {
1604                 $scope.barcode = bc;
1605                 $scope.ok = function() { $uibModalInstance.close() }
1606                 $scope.cancel = function() { $uibModalInstance.dismiss() }
1607             }]
1608         }).result;
1609     }
1610
1611     // check() and checkdigit() copied directly 
1612     // from chrome/content/util/barcode.js
1613
1614     service.check_barcode = function(bc) {
1615         if (bc != Number(bc)) return false;
1616         bc = bc.toString();
1617         // "16.00" == Number("16.00"), but the . is bad.
1618         // Throw out any barcode that isn't just digits
1619         if (bc.search(/\D/) != -1) return false;
1620         var last_digit = bc.substr(bc.length-1);
1621         var stripped_barcode = bc.substr(0,bc.length-1);
1622         return service.barcode_checkdigit(stripped_barcode).toString() == last_digit;
1623     }
1624
1625     service.barcode_checkdigit = function(bc) {
1626         var reverse_barcode = bc.toString().split('').reverse();
1627         var check_sum = 0; var multiplier = 2;
1628         for (var i = 0; i < reverse_barcode.length; i++) {
1629             var digit = reverse_barcode[i];
1630             var product = digit * multiplier; product = product.toString();
1631             var temp_sum = 0;
1632             for (var j = 0; j < product.length; j++) {
1633                 temp_sum += Number( product[j] );
1634             }
1635             check_sum += Number( temp_sum );
1636             multiplier = ( multiplier == 2 ? 1 : 2 );
1637         }
1638         check_sum = check_sum.toString();
1639         var next_multiple_of_10 = (check_sum.match(/(\d*)\d$/)[1] * 10) + 10;
1640         var check_digit = next_multiple_of_10 - Number(check_sum);
1641         if (check_digit == 10) check_digit = 0;
1642         return check_digit;
1643     }
1644
1645     service.handle_barcode_completion = function(barcode) {
1646         return egCore.net.request(
1647             'open-ils.actor',
1648             'open-ils.actor.get_barcodes',
1649             egCore.auth.token(), egCore.auth.user().ws_ou(), 
1650             'asset', barcode)
1651
1652         .then(function(resp) {
1653             // TODO: handle event during barcode lookup
1654             if (evt = egCore.evt.parse(resp)) {
1655                 console.error(evt.toString());
1656                 return $q.reject();
1657             }
1658
1659             // no matching barcodes: return the barcode as entered
1660             // by the user (so that, e.g., checkout can fall back to
1661             // precat/noncat handling)
1662             if (!resp || !resp[0]) {
1663                 return barcode;
1664             }
1665
1666             // exactly one matching barcode: return it
1667             if (resp.length == 1) {
1668                 return resp[0].barcode;
1669             }
1670
1671             // multiple matching barcodes: let the user pick one 
1672             console.debug('multiple matching barcodes');
1673             var matches = [];
1674             var promises = [];
1675             var final_barcode;
1676             angular.forEach(resp, function(cp) {
1677                 promises.push(
1678                     egCore.net.request(
1679                         'open-ils.circ',
1680                         'open-ils.circ.copy_details.retrieve',
1681                         egCore.auth.token(), cp.id
1682                     ).then(function(r) {
1683                         matches.push({
1684                             barcode: r.copy.barcode(),
1685                             title: r.mvr.title(),
1686                             org_name: egCore.org.get(r.copy.circ_lib()).name(),
1687                             org_shortname: egCore.org.get(r.copy.circ_lib()).shortname()
1688                         });
1689                     })
1690                 );
1691             });
1692             return $q.all(promises)
1693             .then(function() {
1694                 return $uibModal.open({
1695                     templateUrl: './circ/share/t_barcode_choice_dialog',
1696                     controller:
1697                         ['$scope', '$uibModalInstance',
1698                         function($scope, $uibModalInstance) {
1699                         $scope.matches = matches;
1700                         $scope.ok = function(barcode) {
1701                             $uibModalInstance.close();
1702                             final_barcode = barcode;
1703                         }
1704                         $scope.cancel = function() {$uibModalInstance.dismiss()}
1705                     }],
1706                 }).result.then(function() { return final_barcode });
1707             })
1708         });
1709     }
1710
1711     service.create_penalty = function(user_id) {
1712         return $uibModal.open({
1713             templateUrl: './circ/share/t_new_message_dialog',
1714             controller: 
1715                    ['$scope','$uibModalInstance','staffPenalties',
1716             function($scope , $uibModalInstance , staffPenalties) {
1717                 $scope.focusNote = true;
1718                 $scope.penalties = staffPenalties;
1719                 $scope.require_initials = service.require_initials;
1720                 $scope.args = {penalty : 21}; // default to Note
1721                 $scope.setPenalty = function(id) {
1722                     args.penalty = id;
1723                 }
1724                 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
1725                 $scope.cancel = function($event) { 
1726                     $uibModalInstance.dismiss();
1727                     $event.preventDefault();
1728                 }
1729             }],
1730             resolve : { staffPenalties : service.get_staff_penalty_types }
1731         }).result.then(
1732             function(args) {
1733                 var pen = new egCore.idl.ausp();
1734                 pen.usr(user_id);
1735                 pen.org_unit(egCore.auth.user().ws_ou());
1736                 pen.note(args.note);
1737                 if (args.initials) pen.note(args.note + ' [' + args.initials + ']');
1738                 if (args.custom_penalty) {
1739                     pen.standing_penalty(args.custom_penalty);
1740                 } else {
1741                     pen.standing_penalty(args.penalty);
1742                 }
1743                 pen.staff(egCore.auth.user().id());
1744                 pen.set_date('now');
1745                 return egCore.pcrud.create(pen);
1746             }
1747         );
1748     }
1749
1750     // assumes, for now anyway,  penalty type is fleshed onto usr_penalty.
1751     service.edit_penalty = function(usr_penalty) {
1752         return $uibModal.open({
1753             templateUrl: './circ/share/t_new_message_dialog',
1754             controller: 
1755                    ['$scope','$uibModalInstance','staffPenalties',
1756             function($scope , $uibModalInstance , staffPenalties) {
1757                 $scope.focusNote = true;
1758                 $scope.penalties = staffPenalties;
1759                 $scope.require_initials = service.require_initials;
1760                 $scope.args = {
1761                     penalty : usr_penalty.standing_penalty().id(),
1762                     note : usr_penalty.note()
1763                 }
1764                 $scope.setPenalty = function(id) { args.penalty = id; }
1765                 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
1766                 $scope.cancel = function($event) { 
1767                     $uibModalInstance.dismiss();
1768                     $event.preventDefault();
1769                 }
1770             }],
1771             resolve : { staffPenalties : service.get_staff_penalty_types }
1772         }).result.then(
1773             function(args) {
1774                 usr_penalty.note(args.note);
1775                 if (args.initials) usr_penalty.note(args.note + ' [' + args.initials + ']');
1776                 usr_penalty.standing_penalty(args.penalty);
1777                 return egCore.pcrud.update(usr_penalty);
1778             }
1779         );
1780     }
1781
1782     return service;
1783
1784 }]);
1785
1786