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