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