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