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