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