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