]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/SIP/Patron.pm
98a594da84df643319e3554492593e87a6fff4b4
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / SIP / Patron.pm
1 #
2
3 # A Class for hiding the ILS's concept of the patron from the OpenSIP
4 # system
5 #
6
7 package OpenILS::SIP::Patron;
8
9 use strict;
10 use warnings;
11 use Exporter;
12
13 use Sys::Syslog qw(syslog);
14 use Data::Dumper;
15 use Digest::MD5 qw(md5_hex);
16
17 use OpenILS::SIP;
18 use OpenILS::Application::AppUtils;
19 use OpenILS::Application::Actor;
20 use OpenILS::Const qw/:const/;
21 use OpenILS::Utils::DateTime qw/:datetime/;
22 use DateTime::Format::ISO8601;
23 my $U = 'OpenILS::Application::AppUtils';
24
25 our (@ISA, @EXPORT_OK);
26
27 @ISA = qw(Exporter);
28
29 @EXPORT_OK = qw(invalid_patron);
30
31 my $INET_PRIVS;
32
33 sub new {
34     my $class = shift;
35     my $key   = shift;
36     my $patron_id = shift;
37     my %args = @_;
38
39     if ($key ne 'usr' and $key ne 'barcode') {
40         syslog("LOG_ERROR", "Patron (card) lookup requested by illegeal key '$key'");
41         return undef;
42     }
43
44     unless(defined $patron_id) {
45         syslog("LOG_WARNING", "No patron ID provided to ILS::Patron->new");
46         return undef;
47     }
48
49     my $type = ref($class) || $class;
50     my $self = bless({}, $type);
51
52     syslog("LOG_DEBUG", "OILS: new OpenILS Patron(%s => %s): searching...", $key, $patron_id);
53
54     my $e = OpenILS::SIP->editor();
55     # Pass the authtoken, if any, to the editor so that we can use it
56     # to fake a context org_unit for the csp.ignore_proximity in
57     # flesh_user_penalties, below.
58     unless ($e->authtoken()) {
59         $e->authtoken($args{authtoken}) if ($args{authtoken});
60     }
61
62     my $usr_flesh = {
63         flesh => 2,
64         flesh_fields => {
65             au => [
66                 "card",
67                 "addresses",
68                 "billing_address",
69                 "mailing_address",
70                 'profile',
71                 "stat_cat_entries",
72             ],
73             actscecm => [
74                 "stat_cat",
75             ],
76         }
77     };
78
79     # in some cases, we don't need all of this data.  Only fetch the user + barcode
80     $usr_flesh = {flesh => 1, flesh_fields => {au => ['card']}} if $args{slim_user};
81     
82     my $user;
83     if($key eq 'barcode') { # retrieve user by barcode
84
85         $$usr_flesh{flesh} += 1;
86         $$usr_flesh{flesh_fields}{ac} = ['usr'];
87
88         my $card = $e->search_actor_card([{barcode => $patron_id}, $usr_flesh])->[0];
89
90         if(!$card or !$U->is_true($card->active)) {
91             syslog("LOG_WARNING", "No such patron barcode: $patron_id");
92             return undef;
93         }
94
95         $user = $card->usr;
96
97     } else {
98         $user = $e->retrieve_actor_user([$patron_id, $usr_flesh]);
99     }
100
101     if(!$user or $U->is_true($user->deleted)) {
102         syslog("LOG_WARNING", "OILS: Unable to find patron %s => %s", $key, $patron_id);
103         return undef;
104     }
105
106     if(!$U->is_true($user->active)) {
107         syslog("LOG_WARNING", "OILS: Patron is inactive %s => %s", $key, $patron_id);
108         return undef;
109     }
110
111     # now grab the user's penalties
112
113     $self->flesh_user_penalties($user, $e) unless $args{slim_user};
114
115     $self->{authtoken} = $args{authtoken} if $args{authtoken};
116     $self->{editor} = $e;
117     $self->{user}   = $user;
118     $self->{id}     = ($key eq 'barcode') ? $patron_id : $user->card->barcode;   # The barcode IS the ID to SIP.  
119     # We give back the passed barcode if the key was indeed a barcode, just to be safe.  Otherwise pull it from the card.
120
121     syslog("LOG_DEBUG", "OILS: new OpenILS Patron(%s => %s): found patron : barred=%s, card:active=%s", 
122         $key, $patron_id, $user->barred, $user->card->active );
123
124     $U->log_user_activity($user->id, $self->get_act_who, 'verify');
125
126     return $self;
127 }
128
129 sub get_act_who {
130     my $self = shift;
131     my $config = OpenILS::SIP->config();
132     my $login = OpenILS::SIP->login_account();
133
134     my $act_who = $config->{implementation_config}->{default_activity_who};
135     my $force_who = $config->{implementation_config}->{force_activity_who};
136
137     # 1. future: test sip extension for caller-provided ewho and !$force_who
138
139     # 2. See if the login is tagged with an ewho
140     return $login->{activity_who} if $login->{activity_who};
141
142     # 3. if all else fails, see if there is an institution-wide ewho
143     return $config->{activity_who} if $config->{activity_who};
144
145     return undef;
146 }
147
148 # grab patron penalties.  Only grab non-archived penalties that are for fines,
149 # excessive overdues, or otherwise block circluation activity
150 sub flesh_user_penalties {
151     my ($self, $user, $e) = @_;
152
153     # Use the ws_ou or home_ou of the authsession user, if any, as a
154     # context org_unit for the penalties and the csp.ignore_proximity.
155     my $here;
156     if ($e->authtoken()) {
157         my $auth_usr = $e->checkauth();
158         if ($auth_usr) {
159             $here = $auth_usr->ws_ou() || $auth_usr->home_ou();
160         }
161     }
162
163     # Get the "raw" list of user's penalties and flesh the
164     # standing_penalty field, so we can filter them based on
165     # csp.ignore_proximity.
166     my $raw_penalties =
167         $e->search_actor_user_standing_penalty([
168             {
169                 usr => $user->id,
170                 '-or' => [
171
172                     # ignore "archived" penalties
173                     {stop_date => undef},
174                     {stop_date => {'>' => 'now'}}
175                 ],
176
177                 org_unit => {
178                     in  => {
179                         select => {
180                             aou => [{
181                                 column => 'id',
182                                 transform => 'actor.org_unit_ancestors',
183                                 result_field => 'id'
184                             }]
185                         },
186                         from => 'aou',
187
188                         # Use "here" or user's home_ou.
189                         where => {id => ($here) ? $here : $user->home_ou},
190                         distinct => 1
191                     }
192                 },
193
194                 # in addition to fines and excessive overdue penalties,
195                 # we only care about penalties that result in blocks
196                 standing_penalty => {
197                     in => {
198                         select => {csp => ['id']},
199                         from => 'csp',
200                         where => {
201                             '-or' => [
202                                 {id => [1,2]}, # fines / overdues
203                                 {block_list => {'!=' => undef}}
204                             ]
205                         },
206                     }
207                 }
208             },
209             {
210                 flesh => 1,
211                 flesh_fields => {ausp => ['standing_penalty']}
212             }
213         ]);
214     # We filter the raw penalties that apply into this array.
215     my $applied_penalties = [];
216     if (ref($raw_penalties) eq 'ARRAY' && @$raw_penalties) {
217         my $here_prox = ($here) ? $U->get_org_unit_proximity($e, $here, $user->home_ou())
218             : undef;
219         # Filter out those that do not apply
220         $applied_penalties = [map
221             { $_->standing_penalty }
222                 grep {
223                     !defined($_->standing_penalty->ignore_proximity())
224                     || ((defined($here_prox))
225                         ? $_->standing_penalty->ignore_proximity() < $here_prox
226                         : $_->standing_penalty->ignore_proximity() <
227                             $U->get_org_unit_proximity($e, $_->org_unit(), $user->home_ou()))
228                 } @$raw_penalties];
229     }
230     $user->standing_penalties($applied_penalties);
231 }
232
233 sub id {
234     my $self = shift;
235     return $self->{id};
236 }
237
238 sub name {
239     my $self = shift;
240     return format_name($self->{user});
241 }
242
243 sub format_name {
244     my $u = shift;
245     return sprintf('%s %s %s',
246                    ($u->first_given_name || ''),
247                    ($u->second_given_name || ''),
248                    ($u->family_name || ''));
249 }
250
251 sub home_library {
252     my $self = shift;
253     my $lib = OpenILS::SIP::shortname_from_id($self->{user}->home_ou);
254     syslog('LOG_DEBUG', "OILS: Patron->home_library() = $lib");
255     return $lib;
256 }
257
258 sub __addr_string {
259     my $addr = shift;
260     return "" unless $addr;
261     my $return = join( ' ', map {$_ || ''}
262                            (
263                                $addr->street1,
264                                $addr->street2,
265                                $addr->city . ',',
266                                $addr->county,
267                                $addr->state,
268                                $addr->country,
269                                $addr->post_code
270                            )
271                        );
272     $return =~ s/\s+/ /sg; # Compress any run of of whitespace to one space
273     return $return;
274 }
275
276 sub internal_id {
277     my $self = shift;
278     return $self->{user}->id;
279 }
280
281 sub address {
282     my $self = shift;
283     my $u    = $self->{user};
284     my $str  = __addr_string($u->billing_address || $u->mailing_address);
285     syslog('LOG_DEBUG', "OILS: Patron address: $str");
286     return $str;
287 }
288
289 sub email_addr {
290     my $self = shift;
291     return $self->{user}->email;
292 }
293
294 sub home_phone {
295     my $self = shift;
296     return $self->{user}->day_phone;
297 }
298
299 sub sip_birthdate {
300     my $self = shift;
301     my $dob = OpenILS::SIP->format_date($self->{user}->dob, 'dob');
302     syslog('LOG_DEBUG', "OILS: Patron DOB = $dob");
303     return $dob;
304 }
305
306 sub sip_expire {
307     my $self = shift;
308     my $expire = OpenILS::SIP->format_date($self->{user}->expire_date);
309     syslog('LOG_DEBUG', "OILS: Patron Expire = $expire");
310     return $expire;
311 }
312
313 sub ptype {
314     my $self = shift;
315
316     my $use_code = OpenILS::SIP->get_option_value('patron_type_uses_code') || '';
317
318     # should we use the no_i18n version of patron profile name (as a 'code')?
319     return $self->{editor}->retrieve_permission_grp_tree(
320         [$self->{user}->profile->id, {no_i18n => 1}])->name
321         if $use_code =~ /true/io;
322
323     return $self->{user}->profile->name;
324 }
325
326 sub language {
327     my $self = shift;
328     return '000'; # Unspecified
329 }
330
331 # How much more detail do we need to check here?
332 # sec: adding logic to return false if user is barred, has a circulation block
333 # or an expired card
334 sub charge_ok {
335     my $self = shift;
336     my $u = $self->{user};
337     my $circ_is_blocked = 0;
338
339     # compute expiration date for borrowing privileges
340     my $expire = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($u->expire_date));
341
342     $circ_is_blocked =
343         (($u->barred eq 't') or
344           (@{$u->standing_penalties} and grep { ( $_->block_list // '') =~ /CIRC/ } @{$u->standing_penalties}) or
345           (CORE::time > $expire->epoch));
346
347     return
348         !$circ_is_blocked &&
349         $u->active eq 't' &&
350         $u->card->active eq 't';
351 }
352
353 sub renew_ok {
354     my $self = shift;
355     my $u = $self->{user};
356     my $renew_is_blocked = 0;
357
358     # compute expiration date for borrowing privileges
359     my $expire = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($u->expire_date));
360
361     $renew_is_blocked =
362         (($u->barred eq 't') or
363          (@{$u->standing_penalties} and grep { ( $_->block_list // '') =~ /RENEW/ } @{$u->standing_penalties}) or
364          (CORE::time > $expire->epoch));
365
366     return
367         !$renew_is_blocked &&
368         $u->active eq 't' &&
369         $u->card->active eq 't';
370 }
371
372 sub recall_ok {
373     my $self = shift;
374     return $self->charge_ok if 
375         OpenILS::SIP->get_option_value('patron_calculate_recal_ok');
376     return 0;
377 }
378
379 sub hold_ok {
380     my $self = shift;
381     my $u = $self->{user};
382     my $hold_is_blocked = 0;
383
384     # compute expiration date for borrowing privileges
385     my $expire = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($u->expire_date));
386
387     $hold_is_blocked =
388         (($u->barred eq 't') or
389          (@{$u->standing_penalties} and grep { ( $_->block_list // '') =~ /HOLD/ } @{$u->standing_penalties}) or
390          (CORE::time > $expire->epoch));
391
392     return
393         !$hold_is_blocked &&
394         $u->active eq 't' &&
395         $u->card->active eq 't';
396 }
397
398 # return true if the card provided is marked as lost
399 sub card_lost {
400     my $self = shift;
401     return $self->{user}->card->active eq 'f';
402 }
403
404 sub recall_overdue {        # not implemented
405     my $self = shift;
406     return 0;
407 }
408
409 sub check_password {
410     my ($self, $pwd) = @_;
411     syslog('LOG_DEBUG', 'OILS: Patron->check_password()');
412     return 0 unless (defined $pwd and $self->{user});
413     return $U->verify_migrated_user_password(
414         $self->{editor},$self->{user}->id, $pwd);
415 }
416
417 sub currency {
418     my $self = shift;
419     syslog('LOG_DEBUG', 'OILS: Patron->currency()');
420     return OpenILS::SIP->config()->{implementation_config}->{currency} || 'USD';
421 }
422
423 sub fee_amount {
424     my $self = shift;
425     syslog('LOG_DEBUG', 'OILS: Patron->fee_amount()');
426     my $user_id = $self->{user}->id;
427
428     my $e = $self->{editor};
429     $e->xact_begin;
430     my $summary = $e->retrieve_money_open_user_summary($user_id);
431     $e->rollback; # xact_rollback + disconnect
432
433     my $total = ($summary) ? $summary->balance_owed : 0;
434     syslog('LOG_INFO', "User ".$self->{id} .":$user_id has a fee amount of \$$total");
435     return $total;
436 }
437
438 sub screen_msg {
439     my $self = shift;
440     my $u = $self->{user};
441
442     return 'barred' if $u->barred eq 't';
443
444     my $b = 'blocked';
445
446     return $b if $u->active eq 'f';
447     return $b if $u->card->active eq 'f';
448
449     # if we have any penalties at this point, they are blocking penalties
450     return $b if $u->standing_penalties and @{$u->standing_penalties};
451
452     # has the patron account expired?
453     my $expire = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($u->expire_date));
454     return $b if CORE::time > $expire->epoch;
455
456     return '';
457 }
458
459 sub print_line {            # not implemented
460     my $self = shift;
461     return '';
462 }
463
464 sub too_many_charged {      # not implemented
465     my $self = shift;
466     return 0;
467 }
468
469 sub too_many_overdue { 
470     my $self = shift;
471     return scalar( # PATRON_EXCEEDS_OVERDUE_COUNT
472         grep { $_->id == OILS_PENALTY_PATRON_EXCEEDS_OVERDUE_COUNT } @{$self->{user}->standing_penalties}
473     );
474 }
475
476 # not completely sure what this means
477 sub too_many_renewal {
478     my $self = shift;
479     return 0;
480 }
481
482 # not relevant, handled by fines/fees
483 sub too_many_claim_return {
484     my $self = shift;
485     return 0;
486 }
487
488 # not relevant, handled by fines/fees
489 sub too_many_lost {
490     my $self = shift;
491     return 0;
492 }
493
494 sub excessive_fines { 
495     my $self = shift;
496     return scalar( # PATRON_EXCEEDS_FINES
497         grep { $_->id == OILS_PENALTY_PATRON_EXCEEDS_FINES } @{$self->{user}->standing_penalties}
498     );
499 }
500
501 # Until someone suggests otherwise, fees and fines are the same
502
503 sub excessive_fees {
504     my $self = shift;
505     return $self->excessive_fines;
506 }
507
508 # not relevant, handled by fines/fees
509 sub too_many_billed {
510     my $self = shift;
511     return 0;
512 }
513
514
515
516 #
517 # List of outstanding holds placed
518 #
519 sub hold_items {
520     my ($self, $start, $end, $ids_only) = @_;
521     syslog('LOG_DEBUG', 'OILS: Patron->hold_items()');
522
523     # all of my open holds
524     my $holds_query = {
525         usr => $self->{user}->id,
526         fulfillment_time => undef,
527         cancel_time => undef
528     };
529     if (OpenILS::SIP->get_option_value('msg64_hold_items_available')) {
530         # Limit to available holds.
531         $holds_query->{current_shelf_lib} = {'=' => {'+ahr' => 'pickup_lib'}};
532     }
533     my $holds = $self->{editor}->search_action_hold_request($holds_query);
534
535     return $holds if $ids_only;
536     return $self->__format_holds($holds, $start, $end);
537 }
538
539 sub unavail_holds {
540      my ($self, $start, $end, $ids_only) = @_;
541      syslog('LOG_DEBUG', 'OILS: Patron->unavail_holds()');
542
543      my $holds = $self->{editor}->search_action_hold_request({
544         usr => $self->{user}->id,
545         fulfillment_time => undef,
546         cancel_time => undef,
547         '-or' => [
548             {current_shelf_lib => undef},
549             {current_shelf_lib => {'!=' => {'+ahr' => 'pickup_lib'}}}
550         ]
551     });
552
553     return $holds if $ids_only;
554     return $self->__format_holds($holds, $start, $end);
555 }
556
557
558
559 sub __format_holds {
560     my ($self, $holds, $start, $end) = @_;
561
562     return [] unless @$holds;
563
564     my $return_datatype = 
565         OpenILS::SIP->get_option_value('msg64_hold_datatype') || '';
566
567     my @response;
568
569     for my $hold (@$holds) {
570
571         if ($return_datatype eq 'barcode') {
572
573             if (my $copy = $self->find_copy_for_hold($hold)) {
574                 push(@response, $copy->barcode);
575
576             } else {
577                 syslog('LOG_WARNING', 
578                     'OILS: No representative copy found for hold ' . $hold->id);
579             }
580
581         } else {
582             push(@response, 
583                 $self->__hold_to_title($hold));
584         }
585     }
586
587     return (defined $start and defined $end) ? 
588         [ @response[($start-1)..($end-1)] ] :
589         \@response;
590 }
591
592 # Finds a representative copy for the given hold.
593 # If no copy exists at all, undef is returned.
594 # The only limit placed on what constitutes a 
595 # "representative" copy is that it cannot be deleted.
596 # Otherwise, any copy that allows us to find the hold
597 # later is good enough.
598 sub find_copy_for_hold {
599     my ($self, $hold) = @_;
600     my $e = $self->{editor};
601
602     return $e->retrieve_asset_copy($hold->current_copy)
603         if $hold->current_copy; 
604
605     return $e->retrieve_asset_copy($hold->target)
606         if $hold->hold_type =~ /C|R|F/;
607
608     return $e->search_asset_copy([
609         {call_number => $hold->target, deleted => 'f'}, 
610         {limit => 1}])->[0] if $hold->hold_type eq 'V';
611
612     my $bre_ids = [$hold->target];
613
614     if ($hold->hold_type eq 'M') {
615         # find all of the bibs that link to the target metarecord
616         my $maps = $e->search_metabib_metarecord_source_map(
617             {metarecord => $hold->target});
618         $bre_ids = [map {$_->record} @$maps];
619     }
620
621     my $vol_ids = $e->search_asset_call_number( 
622         {record => $bre_ids, deleted => 'f'}, 
623         {idlist => 1}
624     );
625
626     return $e->search_asset_copy([
627         {call_number => $vol_ids, deleted => 'f'}, 
628         {limit => 1}
629     ])->[0];
630 }
631
632 # Given a "representative" copy, finds a matching hold
633 sub find_hold_from_copy {
634     my ($self, $barcode) = @_;
635     my $e = $self->{editor};
636     my $hold;
637
638     my $copy = $e->search_asset_copy([
639         {barcode => $barcode, deleted => 'f'},
640         {flesh => 1, flesh_fields => {acp => ['call_number']}}
641     ])->[0];
642
643     return undef unless $copy;
644
645     my $run_hold_query = sub {
646         my %filter = @_;
647         return $e->search_action_hold_request([
648             {   usr => $self->{user}->id,
649                 cancel_time => undef,
650                 fulfillment_time => undef,
651                 %filter
652             }, {
653                 limit => 1,
654                 order_by => {ahr => 'request_time DESC'}
655             }
656         ])->[0];
657     };
658
659     # first see if there is a match on current_copy
660     return $hold if $hold = 
661         $run_hold_query->(current_copy => $copy->id);
662
663     # next, assume bib-level holds are the most common
664     return $hold if $hold = $run_hold_query->(
665         target => $copy->call_number->record, hold_type => 'T');
666
667     # next try metarecord holds
668     my $map = $e->search_metabib_metarecord_source_map(
669         {source => $copy->call_number->record})->[0];
670
671     return $hold if $hold = $run_hold_query->(
672         target => $map->metarecord, hold_type => 'M');
673
674     # volume holds
675     return $hold if $hold = $run_hold_query->(
676         target => $copy->call_number->id, hold_type => 'V');
677
678     # copy holds
679     return $run_hold_query->(
680         target => $copy->id, hold_type => ['C', 'F', 'R']);
681 }
682
683 sub __hold_to_title {
684     my $self = shift;
685     my $hold = shift;
686     my $e = $self->{editor};
687
688     my( $id, $mods, $title, $volume, $copy );
689
690     return __copy_to_title($e, 
691         $e->retrieve_asset_copy($hold->target)) 
692         if $hold->hold_type eq 'C' or $hold->hold_type eq 'F' or $hold->hold_type eq 'R';
693
694     return __volume_to_title($e, 
695         $e->retrieve_asset_call_number($hold->target))
696         if $hold->hold_type eq 'V';
697
698     return __record_to_title(
699         $e, $hold->target) if $hold->hold_type eq 'T';
700
701     return __metarecord_to_title(
702         $e, $hold->target) if $hold->hold_type eq 'M';
703 }
704
705 sub __copy_to_title {
706     my( $e, $copy ) = @_;
707     #syslog('LOG_DEBUG', "OILS: copy_to_title(%s)", $copy->id);
708     return $copy->dummy_title if $copy->call_number == -1;    
709
710     my $vol = (ref $copy->call_number) ?
711         $copy->call_number :
712         $e->retrieve_asset_call_number($copy->call_number);
713
714     return __volume_to_title($e, $vol);
715 }
716
717
718 sub __volume_to_title {
719     my( $e, $volume ) = @_;
720     #syslog('LOG_DEBUG', "OILS: volume_to_title(%s)", $volume->id);
721     return __record_to_title($e, $volume->record);
722 }
723
724
725 sub __record_to_title {
726     my( $e, $title_id ) = @_;
727     #syslog('LOG_DEBUG', "OILS: record_to_title($title_id)");
728     my $mods = $U->simplereq(
729         'open-ils.search',
730         'open-ils.search.biblio.record.mods_slim.retrieve', $title_id );
731     return ($mods) ? $mods->title : "";
732 }
733
734 sub __metarecord_to_title {
735     my( $e, $m_id ) = @_;
736     #syslog('LOG_DEBUG', "OILS: metarecord_to_title($m_id)");
737     my $mods = $U->simplereq(
738         'open-ils.search',
739         'open-ils.search.biblio.metarecord.mods_slim.retrieve', $m_id);
740     return ($U->event_code($mods)) ? "<unknown>" : $mods->title;
741 }
742
743
744 #
745 # remove the hold on item item_id from my hold queue.
746 # return true if I was holding the item, false otherwise.
747
748 sub drop_hold {
749     my ($self, $item_id) = @_;
750     return 0;
751 }
752
753 sub __patron_items_info {
754     my $self = shift;
755     return if $self->{item_info};
756     $self->{item_info} = 
757         OpenILS::Application::Actor::_checked_out(
758             0, $self->{editor}, $self->{user}->id);;
759 }
760
761
762
763 sub overdue_items {
764     my ($self, $start, $end, $ids_only) = @_;
765
766     $self->__patron_items_info();
767     my @overdues = @{$self->{item_info}->{overdue}};
768     #$overdues[$_] = __circ_to_title($self->{editor}, $overdues[$_]) for @overdues;
769
770     return \@overdues if $ids_only;
771
772     my @o;
773     syslog('LOG_DEBUG', "OILS: overdue_items() fleshing circs @overdues");
774
775     my $return_datatype = OpenILS::SIP->get_option_value('msg64_summary_datatype') || '';
776     
777     for my $circid (@overdues) {
778         next unless $circid;
779         if($return_datatype eq 'barcode') {
780             push( @o, __circ_to_barcode($self->{editor}, $circid));
781         } else {
782             push( @o, __circ_to_title($self->{editor}, $circid));
783         }
784     }
785     @overdues = @o;
786
787     return (defined $start and defined $end) ? 
788         [ @overdues[($start-1)..($end-1)] ] : \@overdues;
789 }
790
791 sub __circ_to_barcode {
792     my ($e, $circ) = @_;
793     return unless $circ;
794     $circ = $e->retrieve_action_circulation($circ);
795     my $copy = $e->retrieve_asset_copy($circ->target_copy);
796     return $copy->barcode;
797 }
798
799 sub __circ_to_title {
800     my( $e, $circ ) = @_;
801     return unless $circ;
802     $circ = $e->retrieve_action_circulation($circ);
803     return __copy_to_title( $e, 
804         $e->retrieve_asset_copy($circ->target_copy) );
805 }
806
807 sub charged_items {
808     my ($self, $start, $end, $ids_only) = shift;
809     return $self->charged_items_impl($start, $end, undef, $ids_only);
810 }
811
812 # implementation method
813 # force_bc -- return barcode data regardless of msg64_summary_datatype;
814 #             this is used by the renew-all code
815 sub charged_items_impl {
816     my ($self, $start, $end, $force_bc, $ids_only) = shift;
817
818     $self->__patron_items_info();
819
820     my @charges = (
821         @{$self->{item_info}->{out}},
822         @{$self->{item_info}->{overdue}}
823         );
824
825     #$charges[$_] = __circ_to_title($self->{editor}, $charges[$_]) for @charges;
826
827     return \@charges if $ids_only;
828
829     my @c;
830     syslog('LOG_DEBUG', "OILS: charged_items() fleshing circs @charges");
831
832     my $return_datatype = OpenILS::SIP->get_option_value('msg64_summary_datatype') || '';
833
834     for my $circid (@charges) {
835         next unless $circid;
836         if($return_datatype eq 'barcode' or $force_bc) {
837             push( @c, __circ_to_barcode($self->{editor}, $circid));
838         } else {
839             push( @c, __circ_to_title($self->{editor}, $circid));
840         }
841     }
842
843     @charges = @c;
844
845     return (defined $start and defined $end) ? 
846         [ @charges[($start-1)..($end-1)] ] :
847         \@charges;
848 }
849
850 sub fine_items {
851     my ($self, $start, $end, $ids_only) = @_;
852     my @fines;
853
854     my $login = OpenILS::SIP->login_account();
855     my $AV_format = lc($login->{av_format}) || 'eg_legacy';
856
857     # Do a prescan for validity and default to eg_legacy
858     if ($AV_format ne "swyer_a" &&
859         $AV_format ne "swyer_b" &&
860         $AV_format ne "eg_legacy" &&
861         $AV_format ne "3m") {
862
863         syslog('LOG_WARNING',
864             "OILS: Unknown value for AV_format: ". $login->{av_format});
865         $AV_format = "eg_legacy";
866     }
867
868     my $xacts = $U->simplereq('open-ils.actor',
869         'open-ils.actor.user.transactions.history.have_balance',
870         $self->{authtoken}, $self->{user}->id);
871
872     my $line;
873     foreach my $xact (@{$xacts}) {
874
875         if ($ids_only) {
876             push @fines, $xact->id;
877             next;
878         }
879
880         # fine item details requested
881
882         my $title;
883         my $author;
884         my $line;
885
886         my $fee_type;
887
888         if ($xact->last_billing_type =~ /^Lost/) {
889             $fee_type = 'LOST';
890         } elsif ($xact->last_billing_type =~ /^Overdue/) {
891             $fee_type = 'FINE';
892         } else {
893             $fee_type = 'FEE';
894         }
895
896         if ($xact->xact_type eq 'circulation') {
897             my $e = OpenILS::SIP->editor();
898             my $circ = $e->retrieve_action_circulation([
899                 $xact->id, {
900                     flesh => 2,
901                     flesh_fields => {
902                         circ => ['target_copy'],
903                         acp => ['call_number']
904                     }
905                 }
906             ]);
907
908             my $displays = $e->search_metabib_flat_display_entry({
909                 source => $circ->target_copy->call_number->record,
910                 name => ['title', 'author']
911             });
912
913             ($title) = map {$_->value} grep {$_->name eq 'title'} @$displays;
914             ($author) = map {$_->value} grep {$_->name eq 'author'} @$displays;
915
916             # Scrub "/" chars since they are used in some cases 
917             # to delineate title/author.
918             if ($title) {
919                 $title =~ s/\///g;
920             } else {
921                 $title = '';
922             }
923
924             if ($author) {
925                 $author =~ s/\///g;
926             } else {
927                 $author = '';
928             }
929         }
930
931         if ($AV_format eq "eg_legacy") {
932
933             $line = $xact->balance_owed . " " . $xact->last_billing_type . " ";
934
935             if ($xact->xact_type eq 'circulation') {
936                 $line .= "$title / $author";
937             } else {
938                 $line .= $xact->last_billing_note;
939             }
940
941         } elsif ($AV_format eq "3m" or $AV_format eq "swyer_a") {
942
943             $line = $xact->id . ' $' . $xact->balance_owed . " \"$fee_type\" ";
944
945             if ($xact->xact_type eq 'circulation') {
946                 $line .= "$title";
947             } else {
948                 $line .= $xact->last_billing_note;
949             }
950
951         } elsif ($AV_format eq "swyer_b") {
952
953             $line =   "Charge-Number: " . $xact->id;
954             $line .=  ", Amount-Due: "  . $xact->balance_owed;
955             $line .=  ", Fine-Type: $fee_type";
956
957             if ($xact->xact_type eq 'circulation') {
958                 $line .= ", Title: $title";
959             } else {
960                 $line .= ", Title: " . $xact->last_billing_note;
961             }
962         }
963
964         push @fines, $line;
965     }
966
967     my $log_status = $@ ? 'ERROR: ' . $@ : 'OK';
968     syslog('LOG_DEBUG', 'OILS: Patron->fine_items() ' . $log_status);
969     return (defined $start and defined $end) ? 
970         [ @fines[($start-1)..($end-1)] ] : \@fines;
971 }
972
973 # not currently supported
974 sub recall_items {
975     my ($self, $start, $end, $ids_only) = @_;
976     return [];
977 }
978
979 sub block {
980     my ($self, $card_retained, $blocked_card_msg) = @_;
981     $blocked_card_msg ||= '';
982
983     my $e = $self->{editor};
984     my $u = $self->{user};
985
986     syslog('LOG_INFO', "OILS: Blocking user %s", $u->card->barcode );
987
988     return $self if $u->card->active eq 'f';
989
990     $e->xact_begin;    # connect and start a new transaction
991
992     $u->card->active('f');
993     if( ! $e->update_actor_card($u->card) ) {
994         syslog('LOG_ERR', "OILS: Block card update failed: %s", $e->event->{textcode});
995         $e->rollback; # rollback + disconnect
996         return $self;
997     }
998
999     # retrieve the un-fleshed user object for update
1000     $u = $e->retrieve_actor_user($u->id);
1001     my $note = $u->alert_message || "";
1002     $note = "<sip> CARD BLOCKED BY SELF-CHECK MACHINE. $blocked_card_msg</sip>\n$note"; # XXX Config option
1003     $note =~ s/\s*$//;  # kill trailng whitespace
1004     $u->alert_message($note);
1005
1006     if( ! $e->update_actor_user($u) ) {
1007         syslog('LOG_ERR', "OILS: Block: patron alert update failed: %s", $e->event->{textcode});
1008         $e->rollback; # rollback + disconnect
1009         return $self;
1010     }
1011
1012     # stay in synch
1013     $self->{user}->alert_message( $note );
1014
1015     $e->commit; # commits and disconnects
1016     return $self;
1017 }
1018
1019 # Testing purposes only
1020 sub enable {
1021     my ($self, $card_retained) = @_;
1022     $self->{screen_msg} = "All privileges restored.";
1023
1024     # Un-mark card as inactive, grep out the patron alert
1025     my $e = $self->{editor};
1026     my $u = $self->{user};
1027
1028     syslog('LOG_INFO', "OILS: Unblocking user %s", $u->card->barcode );
1029
1030     return $self if $u->card->active eq 't';
1031
1032     $e->xact_begin;    # connect and start a new transaction
1033
1034     $u->card->active('t');
1035     if( ! $e->update_actor_card($u->card) ) {
1036         syslog('LOG_ERR', "OILS: Unblock card update failed: %s", $e->event->{textcode});
1037         $e->rollback; # rollback + disconnect
1038         return $self;
1039     }
1040
1041     # retrieve the un-fleshed user object for update
1042     $u = $e->retrieve_actor_user($u->id);
1043     my $note = $u->alert_message || "";
1044     $note =~ s#<sip>.*</sip>##;
1045     $note =~ s/^\s*//;  # kill leading whitespace
1046     $note =~ s/\s*$//;  # kill trailng whitespace
1047     $u->alert_message($note);
1048
1049     if( ! $e->update_actor_user($u) ) {
1050         syslog('LOG_ERR', "OILS: Unblock: patron alert update failed: %s", $e->event->{textcode});
1051         $e->rollback; # rollback + disconnect
1052         return $self;
1053     }
1054
1055     # stay in synch
1056     $self->{user}->alert_message( $note );
1057
1058     $e->commit; # commits and disconnects
1059     return $self;
1060 }
1061
1062 #
1063 # Messages
1064 #
1065
1066 sub invalid_patron {
1067     return "Please contact library staff";
1068 }
1069
1070 sub charge_denied {
1071     return "Please contact library staff";
1072 }
1073
1074 sub inet_privileges {
1075     my( $self ) = @_;
1076     my $e = OpenILS::SIP->editor();
1077     $INET_PRIVS = $e->retrieve_all_config_net_access_level() unless $INET_PRIVS;
1078     my ($level) = grep { $_->id eq $self->{user}->net_access_level } @$INET_PRIVS;
1079     my $name = $level->name;
1080     syslog('LOG_DEBUG', "OILS: Patron inet_privs = $name");
1081     return $name;
1082 }
1083
1084 sub extra_fields {
1085     my( $self ) = @_;
1086     my $extra_fields = {};
1087     my $u = $self->{user};
1088     foreach my $stat_cat_entry (@{$u->stat_cat_entries}) {
1089         my $stat_cat = $stat_cat_entry->stat_cat;
1090         next unless ($stat_cat->sip_field);
1091         my $value = $stat_cat_entry->stat_cat_entry;
1092         if(defined $stat_cat->sip_format && length($stat_cat->sip_format) > 0) { # Has a format string?
1093             if($stat_cat->sip_format =~ /^\|(.*)\|$/) { # Regex match?
1094                 if($value =~ /($1)/) { # If we have a match
1095                     if(defined $2) { # Check to see if they embedded a capture group
1096                         $value = $2; # If so, use it
1097                     }
1098                     else { # No embedded capture group?
1099                         $value = $1; # Use our outer one
1100                     }
1101                 }
1102                 else { # No match?
1103                     $value = ''; # Empty string. Will be checked for below.
1104                 }
1105             }
1106             else { # Not a regex match - Try sprintf match (looking for a %s, if any)
1107                 $value = sprintf($stat_cat->sip_format, $value);
1108             }
1109         }
1110         next unless length($value) > 0; # No value = no export
1111         $value =~ s/\|//g; # Remove all lingering pipe chars for sane output purposes
1112         $extra_fields->{ $stat_cat->sip_field } = [] unless (defined $extra_fields->{$stat_cat->sip_field});
1113         push(@{$extra_fields->{ $stat_cat->sip_field}}, $value);
1114     }
1115     return $extra_fields;
1116 }
1117
1118 1;