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