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