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