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