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