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