]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/SIP/Patron.pm
LP1615805 No inputs after submit in patron search (AngularJS)
[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 # method to check to see if charge_ok, renew_ok, and
332 # lost_card should be coerced to return a status indicating
333 # that the patron should be allowed to circulate; this
334 # implements a workaround further described in
335 # https://bugs.launchpad.net/evergreen/+bug/1853363
336 sub patron_status_always_permit_loans_set {
337     my $self = shift;
338
339     my $login = OpenILS::SIP->login_account();
340
341     return (
342                 OpenILS::SIP::to_bool($login->{patron_status_always_permit_loans}) //
343                 OpenILS::SIP::to_bool(OpenILS::SIP->get_option_value('patron_status_always_permit_loans'))
344            ) ||
345            0;
346 }
347
348 # How much more detail do we need to check here?
349 # sec: adding logic to return false if user is barred, has a circulation block
350 # or an expired card
351 sub charge_ok {
352     my $self = shift;
353     my $u = $self->{user};
354     my $circ_is_blocked = 0;
355
356     return 1 if $self->patron_status_always_permit_loans_set();
357
358     # compute expiration date for borrowing privileges
359     my $expire = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($u->expire_date));
360
361     $circ_is_blocked =
362         (($u->barred eq 't') or
363           (@{$u->standing_penalties} and grep { ( $_->block_list // '') =~ /CIRC/ } @{$u->standing_penalties}) or
364           (CORE::time > $expire->epoch));
365
366     return
367         !$circ_is_blocked &&
368         $u->active eq 't' &&
369         $u->card->active eq 't';
370 }
371
372 sub renew_ok {
373     my $self = shift;
374     my $u = $self->{user};
375     my $renew_is_blocked = 0;
376
377     return 1 if $self->patron_status_always_permit_loans_set();
378
379     # compute expiration date for borrowing privileges
380     my $expire = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($u->expire_date));
381
382     $renew_is_blocked =
383         (($u->barred eq 't') or
384          (@{$u->standing_penalties} and grep { ( $_->block_list // '') =~ /RENEW/ } @{$u->standing_penalties}) or
385          (CORE::time > $expire->epoch));
386
387     return
388         !$renew_is_blocked &&
389         $u->active eq 't' &&
390         $u->card->active eq 't';
391 }
392
393 sub recall_ok {
394     my $self = shift;
395     return $self->charge_ok if 
396         OpenILS::SIP->get_option_value('patron_calculate_recal_ok');
397     return 0;
398 }
399
400 sub hold_ok {
401     my $self = shift;
402     my $u = $self->{user};
403     my $hold_is_blocked = 0;
404
405     # compute expiration date for borrowing privileges
406     my $expire = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($u->expire_date));
407
408     $hold_is_blocked =
409         (($u->barred eq 't') or
410          (@{$u->standing_penalties} and grep { ( $_->block_list // '') =~ /HOLD/ } @{$u->standing_penalties}) or
411          (CORE::time > $expire->epoch));
412
413     return
414         !$hold_is_blocked &&
415         $u->active eq 't' &&
416         $u->card->active eq 't';
417 }
418
419 # return true if the card provided is marked as lost
420 sub card_lost {
421     my $self = shift;
422
423     return 0 if $self->patron_status_always_permit_loans_set();
424
425     return $self->{user}->card->active eq 'f';
426 }
427
428 sub recall_overdue {        # not implemented
429     my $self = shift;
430     return 0;
431 }
432
433 sub check_password {
434     my ($self, $pwd) = @_;
435     syslog('LOG_DEBUG', 'OILS: Patron->check_password()');
436     return 0 unless (defined $pwd and $self->{user});
437     return $U->verify_migrated_user_password(
438         $self->{editor},$self->{user}->id, $pwd);
439 }
440
441 sub currency {
442     my $self = shift;
443     syslog('LOG_DEBUG', 'OILS: Patron->currency()');
444     return OpenILS::SIP->config()->{implementation_config}->{currency} || 'USD';
445 }
446
447 sub fee_amount {
448     my $self = shift;
449     syslog('LOG_DEBUG', 'OILS: Patron->fee_amount()');
450     my $user_id = $self->{user}->id;
451
452     my $e = $self->{editor};
453     $e->xact_begin;
454     my $summary = $e->retrieve_money_open_user_summary($user_id);
455     $e->rollback; # xact_rollback + disconnect
456
457     my $total = ($summary) ? $summary->balance_owed : 0;
458     syslog('LOG_INFO', "User ".$self->{id} .":$user_id has a fee amount of \$$total");
459     return $total;
460 }
461
462 sub screen_msg {
463     my $self = shift;
464     my $u = $self->{user};
465
466     return 'barred' if $u->barred eq 't';
467
468     my $b = 'blocked';
469
470     return $b if $u->active eq 'f';
471     return $b if $u->card->active eq 'f';
472
473     # if we have any penalties at this point, they are blocking penalties
474     return $b if $u->standing_penalties and @{$u->standing_penalties};
475
476     # has the patron account expired?
477     my $expire = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($u->expire_date));
478     return $b if CORE::time > $expire->epoch;
479
480     return '';
481 }
482
483 sub print_line {            # not implemented
484     my $self = shift;
485     return '';
486 }
487
488 sub too_many_charged {      # not implemented
489     my $self = shift;
490     return 0;
491 }
492
493 sub too_many_overdue { 
494     my $self = shift;
495     return scalar( # PATRON_EXCEEDS_OVERDUE_COUNT
496         grep { $_->id == OILS_PENALTY_PATRON_EXCEEDS_OVERDUE_COUNT } @{$self->{user}->standing_penalties}
497     );
498 }
499
500 # not completely sure what this means
501 sub too_many_renewal {
502     my $self = shift;
503     return 0;
504 }
505
506 # not relevant, handled by fines/fees
507 sub too_many_claim_return {
508     my $self = shift;
509     return 0;
510 }
511
512 # not relevant, handled by fines/fees
513 sub too_many_lost {
514     my $self = shift;
515     return 0;
516 }
517
518 sub excessive_fines { 
519     my $self = shift;
520     return scalar( # PATRON_EXCEEDS_FINES
521         grep { $_->id == OILS_PENALTY_PATRON_EXCEEDS_FINES } @{$self->{user}->standing_penalties}
522     );
523 }
524
525 # Until someone suggests otherwise, fees and fines are the same
526
527 sub excessive_fees {
528     my $self = shift;
529     return $self->excessive_fines;
530 }
531
532 # not relevant, handled by fines/fees
533 sub too_many_billed {
534     my $self = shift;
535     return 0;
536 }
537
538
539
540 #
541 # List of outstanding holds placed
542 #
543 sub hold_items {
544     my ($self, $start, $end, $ids_only) = @_;
545     syslog('LOG_DEBUG', 'OILS: Patron->hold_items()');
546
547     # all of my open holds
548     my $holds_query = {
549         usr => $self->{user}->id,
550         fulfillment_time => undef,
551         cancel_time => undef
552     };
553     if (OpenILS::SIP->get_option_value('msg64_hold_items_available')) {
554         # Limit to available holds.
555         $holds_query->{current_shelf_lib} = {'=' => {'+ahr' => 'pickup_lib'}};
556     }
557     my $holds = $self->{editor}->search_action_hold_request($holds_query);
558
559     return $holds if $ids_only;
560     return $self->__format_holds($holds, $start, $end);
561 }
562
563 sub unavail_holds {
564      my ($self, $start, $end, $ids_only) = @_;
565      syslog('LOG_DEBUG', 'OILS: Patron->unavail_holds()');
566
567      my $holds = $self->{editor}->search_action_hold_request({
568         usr => $self->{user}->id,
569         fulfillment_time => undef,
570         cancel_time => undef,
571         '-or' => [
572             {current_shelf_lib => undef},
573             {current_shelf_lib => {'!=' => {'+ahr' => 'pickup_lib'}}}
574         ]
575     });
576
577     return $holds if $ids_only;
578     return $self->__format_holds($holds, $start, $end);
579 }
580
581
582
583 sub __format_holds {
584     my ($self, $holds, $start, $end) = @_;
585
586     return [] unless @$holds;
587
588     my $return_datatype = 
589         OpenILS::SIP->get_option_value('msg64_hold_datatype') || '';
590
591     my @response;
592
593     for my $hold (@$holds) {
594
595         if ($return_datatype eq 'barcode') {
596
597             if (my $copy = $self->find_copy_for_hold($hold)) {
598                 push(@response, $copy->barcode);
599
600             } else {
601                 syslog('LOG_WARNING', 
602                     'OILS: No representative copy found for hold ' . $hold->id);
603             }
604
605         } else {
606             push(@response, 
607                 $self->__hold_to_title($hold));
608         }
609     }
610
611     return (defined $start and defined $end) ? 
612         [ @response[($start-1)..($end-1)] ] :
613         \@response;
614 }
615
616 # Finds a representative copy for the given hold.
617 # If no copy exists at all, undef is returned.
618 # The only limit placed on what constitutes a 
619 # "representative" copy is that it cannot be deleted.
620 # Otherwise, any copy that allows us to find the hold
621 # later is good enough.
622 sub find_copy_for_hold {
623     my ($self, $hold) = @_;
624     my $e = $self->{editor};
625
626     return $e->retrieve_asset_copy($hold->current_copy)
627         if $hold->current_copy; 
628
629     return $e->retrieve_asset_copy($hold->target)
630         if $hold->hold_type =~ /C|R|F/;
631
632     return $e->search_asset_copy([
633         {call_number => $hold->target, deleted => 'f'}, 
634         {limit => 1}])->[0] if $hold->hold_type eq 'V';
635
636     my $bre_ids = [$hold->target];
637
638     if ($hold->hold_type eq 'M') {
639         # find all of the bibs that link to the target metarecord
640         my $maps = $e->search_metabib_metarecord_source_map(
641             {metarecord => $hold->target});
642         $bre_ids = [map {$_->record} @$maps];
643     }
644
645     my $vol_ids = $e->search_asset_call_number( 
646         {record => $bre_ids, deleted => 'f'}, 
647         {idlist => 1}
648     );
649
650     return $e->search_asset_copy([
651         {call_number => $vol_ids, deleted => 'f'}, 
652         {limit => 1}
653     ])->[0];
654 }
655
656 # Given a "representative" copy, finds a matching hold
657 sub find_hold_from_copy {
658     my ($self, $barcode) = @_;
659     my $e = $self->{editor};
660     my $hold;
661
662     my $copy = $e->search_asset_copy([
663         {barcode => $barcode, deleted => 'f'},
664         {flesh => 1, flesh_fields => {acp => ['call_number']}}
665     ])->[0];
666
667     return undef unless $copy;
668
669     my $run_hold_query = sub {
670         my %filter = @_;
671         return $e->search_action_hold_request([
672             {   usr => $self->{user}->id,
673                 cancel_time => undef,
674                 fulfillment_time => undef,
675                 %filter
676             }, {
677                 limit => 1,
678                 order_by => {ahr => 'request_time DESC'}
679             }
680         ])->[0];
681     };
682
683     # first see if there is a match on current_copy
684     return $hold if $hold = 
685         $run_hold_query->(current_copy => $copy->id);
686
687     # next, assume bib-level holds are the most common
688     return $hold if $hold = $run_hold_query->(
689         target => $copy->call_number->record, hold_type => 'T');
690
691     # next try metarecord holds
692     my $map = $e->search_metabib_metarecord_source_map(
693         {source => $copy->call_number->record})->[0];
694
695     return $hold if $hold = $run_hold_query->(
696         target => $map->metarecord, hold_type => 'M');
697
698     # volume holds
699     return $hold if $hold = $run_hold_query->(
700         target => $copy->call_number->id, hold_type => 'V');
701
702     # copy holds
703     return $run_hold_query->(
704         target => $copy->id, hold_type => ['C', 'F', 'R']);
705 }
706
707 sub __hold_to_title {
708     my $self = shift;
709     my $hold = shift;
710     my $e = $self->{editor};
711
712     my( $id, $mods, $title, $volume, $copy );
713
714     return __copy_to_title($e, 
715         $e->retrieve_asset_copy($hold->target)) 
716         if $hold->hold_type eq 'C' or $hold->hold_type eq 'F' or $hold->hold_type eq 'R';
717
718     return __volume_to_title($e, 
719         $e->retrieve_asset_call_number($hold->target))
720         if $hold->hold_type eq 'V';
721
722     return __record_to_title(
723         $e, $hold->target) if $hold->hold_type eq 'T';
724
725     return __metarecord_to_title(
726         $e, $hold->target) if $hold->hold_type eq 'M';
727 }
728
729 sub __copy_to_title {
730     my( $e, $copy ) = @_;
731     #syslog('LOG_DEBUG', "OILS: copy_to_title(%s)", $copy->id);
732     return $copy->dummy_title if $copy->call_number == -1;    
733
734     my $vol = (ref $copy->call_number) ?
735         $copy->call_number :
736         $e->retrieve_asset_call_number($copy->call_number);
737
738     return __volume_to_title($e, $vol);
739 }
740
741
742 sub __volume_to_title {
743     my( $e, $volume ) = @_;
744     #syslog('LOG_DEBUG', "OILS: volume_to_title(%s)", $volume->id);
745     return __record_to_title($e, $volume->record);
746 }
747
748
749 sub __record_to_title {
750     my( $e, $title_id ) = @_;
751     #syslog('LOG_DEBUG', "OILS: record_to_title($title_id)");
752     my $mods = $U->simplereq(
753         'open-ils.search',
754         'open-ils.search.biblio.record.mods_slim.retrieve', $title_id );
755     return ($mods) ? $mods->title : "";
756 }
757
758 sub __metarecord_to_title {
759     my( $e, $m_id ) = @_;
760     #syslog('LOG_DEBUG', "OILS: metarecord_to_title($m_id)");
761     my $mods = $U->simplereq(
762         'open-ils.search',
763         'open-ils.search.biblio.metarecord.mods_slim.retrieve', $m_id);
764     return ($U->event_code($mods)) ? "<unknown>" : $mods->title;
765 }
766
767
768 #
769 # remove the hold on item item_id from my hold queue.
770 # return true if I was holding the item, false otherwise.
771
772 sub drop_hold {
773     my ($self, $item_id) = @_;
774     return 0;
775 }
776
777 sub __patron_items_info {
778     my $self = shift;
779     return if $self->{item_info};
780     $self->{item_info} = 
781         OpenILS::Application::Actor::_checked_out(
782             0, $self->{editor}, $self->{user}->id);;
783 }
784
785
786
787 sub overdue_items {
788     my ($self, $start, $end, $ids_only) = @_;
789
790     $self->__patron_items_info();
791     my @overdues = @{$self->{item_info}->{overdue}};
792     #$overdues[$_] = __circ_to_title($self->{editor}, $overdues[$_]) for @overdues;
793
794     return \@overdues if $ids_only;
795
796     my @o;
797     syslog('LOG_DEBUG', "OILS: overdue_items() fleshing circs @overdues");
798
799     my $return_datatype = OpenILS::SIP->get_option_value('msg64_summary_datatype') || '';
800     
801     for my $circid (@overdues) {
802         next unless $circid;
803         if($return_datatype eq 'barcode') {
804             push( @o, __circ_to_barcode($self->{editor}, $circid));
805         } else {
806             push( @o, __circ_to_title($self->{editor}, $circid));
807         }
808     }
809     @overdues = @o;
810
811     return (defined $start and defined $end) ? 
812         [ @overdues[($start-1)..($end-1)] ] : \@overdues;
813 }
814
815 sub __circ_to_barcode {
816     my ($e, $circ) = @_;
817     return unless $circ;
818     $circ = $e->retrieve_action_circulation($circ);
819     my $copy = $e->retrieve_asset_copy($circ->target_copy);
820     return $copy->barcode;
821 }
822
823 sub __circ_to_title {
824     my( $e, $circ ) = @_;
825     return unless $circ;
826     $circ = $e->retrieve_action_circulation($circ);
827     return __copy_to_title( $e, 
828         $e->retrieve_asset_copy($circ->target_copy) );
829 }
830
831 sub charged_items {
832     my ($self, $start, $end, $ids_only) = shift;
833     return $self->charged_items_impl($start, $end, undef, $ids_only);
834 }
835
836 # implementation method
837 # force_bc -- return barcode data regardless of msg64_summary_datatype;
838 #             this is used by the renew-all code
839 sub charged_items_impl {
840     my ($self, $start, $end, $force_bc, $ids_only) = shift;
841
842     $self->__patron_items_info();
843
844     my @charges = (
845         @{$self->{item_info}->{out}},
846         @{$self->{item_info}->{overdue}}
847         );
848
849     #$charges[$_] = __circ_to_title($self->{editor}, $charges[$_]) for @charges;
850
851     return \@charges if $ids_only;
852
853     my @c;
854     syslog('LOG_DEBUG', "OILS: charged_items() fleshing circs @charges");
855
856     my $return_datatype = OpenILS::SIP->get_option_value('msg64_summary_datatype') || '';
857
858     for my $circid (@charges) {
859         next unless $circid;
860         if($return_datatype eq 'barcode' or $force_bc) {
861             push( @c, __circ_to_barcode($self->{editor}, $circid));
862         } else {
863             push( @c, __circ_to_title($self->{editor}, $circid));
864         }
865     }
866
867     @charges = @c;
868
869     return (defined $start and defined $end) ? 
870         [ @charges[($start-1)..($end-1)] ] :
871         \@charges;
872 }
873
874 sub fine_items {
875     my ($self, $start, $end, $ids_only) = @_;
876     my @fines;
877
878     my $login = OpenILS::SIP->login_account();
879     my $AV_format = lc($login->{av_format}) || 'eg_legacy';
880
881     # Do a prescan for validity and default to eg_legacy
882     if ($AV_format ne "swyer_a" &&
883         $AV_format ne "swyer_b" &&
884         $AV_format ne "eg_legacy" &&
885         $AV_format ne "3m") {
886
887         syslog('LOG_WARNING',
888             "OILS: Unknown value for AV_format: ". $login->{av_format});
889         $AV_format = "eg_legacy";
890     }
891
892     my $xacts = $U->simplereq('open-ils.actor',
893         'open-ils.actor.user.transactions.history.have_balance',
894         $self->{authtoken}, $self->{user}->id);
895
896     my $line;
897     foreach my $xact (@{$xacts}) {
898
899         if ($ids_only) {
900             push @fines, $xact->id;
901             next;
902         }
903
904         # fine item details requested
905
906         my $title;
907         my $author;
908         my $line;
909
910         my $fee_type;
911
912         if ($xact->last_billing_type =~ /^Lost/) {
913             $fee_type = 'LOST';
914         } elsif ($xact->last_billing_type =~ /^Overdue/) {
915             $fee_type = 'FINE';
916         } else {
917             $fee_type = 'FEE';
918         }
919
920         if ($xact->xact_type eq 'circulation') {
921             my $e = OpenILS::SIP->editor();
922             my $circ = $e->retrieve_action_circulation([
923                 $xact->id, {
924                     flesh => 2,
925                     flesh_fields => {
926                         circ => ['target_copy'],
927                         acp => ['call_number']
928                     }
929                 }
930             ]);
931
932             my $displays = $e->search_metabib_flat_display_entry({
933                 source => $circ->target_copy->call_number->record,
934                 name => ['title', 'author']
935             });
936
937             ($title) = map {$_->value} grep {$_->name eq 'title'} @$displays;
938             ($author) = map {$_->value} grep {$_->name eq 'author'} @$displays;
939
940             # Scrub "/" chars since they are used in some cases 
941             # to delineate title/author.
942             if ($title) {
943                 $title =~ s/\///g;
944             } else {
945                 $title = '';
946             }
947
948             if ($author) {
949                 $author =~ s/\///g;
950             } else {
951                 $author = '';
952             }
953         }
954
955         if ($AV_format eq "eg_legacy") {
956
957             $line = $xact->balance_owed . " " . $xact->last_billing_type . " ";
958
959             if ($xact->xact_type eq 'circulation') {
960                 $line .= "$title / $author";
961             } else {
962                 $line .= $xact->last_billing_note;
963             }
964
965         } elsif ($AV_format eq "3m" or $AV_format eq "swyer_a") {
966
967             $line = $xact->id . ' $' . $xact->balance_owed . " \"$fee_type\" ";
968
969             if ($xact->xact_type eq 'circulation') {
970                 $line .= "$title";
971             } else {
972                 $line .= $xact->last_billing_note;
973             }
974
975         } elsif ($AV_format eq "swyer_b") {
976
977             $line =   "Charge-Number: " . $xact->id;
978             $line .=  ", Amount-Due: "  . $xact->balance_owed;
979             $line .=  ", Fine-Type: $fee_type";
980
981             if ($xact->xact_type eq 'circulation') {
982                 $line .= ", Title: $title";
983             } else {
984                 $line .= ", Title: " . $xact->last_billing_note;
985             }
986         }
987
988         push @fines, $line;
989     }
990
991     my $log_status = $@ ? 'ERROR: ' . $@ : 'OK';
992     syslog('LOG_DEBUG', 'OILS: Patron->fine_items() ' . $log_status);
993     return (defined $start and defined $end) ? 
994         [ @fines[($start-1)..($end-1)] ] : \@fines;
995 }
996
997 # not currently supported
998 sub recall_items {
999     my ($self, $start, $end, $ids_only) = @_;
1000     return [];
1001 }
1002
1003 sub block {
1004     my ($self, $card_retained, $blocked_card_msg) = @_;
1005     $blocked_card_msg ||= '';
1006
1007     my $e = $self->{editor};
1008     my $u = $self->{user};
1009
1010     syslog('LOG_INFO', "OILS: Blocking user %s", $u->card->barcode );
1011
1012     return $self if $u->card->active eq 'f';
1013
1014     $e->xact_begin;    # connect and start a new transaction
1015
1016     $u->card->active('f');
1017     if( ! $e->update_actor_card($u->card) ) {
1018         syslog('LOG_ERR', "OILS: Block card update failed: %s", $e->event->{textcode});
1019         $e->rollback; # rollback + disconnect
1020         return $self;
1021     }
1022
1023     # retrieve the un-fleshed user object for update
1024     $u = $e->retrieve_actor_user($u->id);
1025     my $note = $u->alert_message || "";
1026     $note = "<sip> CARD BLOCKED BY SELF-CHECK MACHINE. $blocked_card_msg</sip>\n$note"; # XXX Config option
1027     $note =~ s/\s*$//;  # kill trailng whitespace
1028     $u->alert_message($note);
1029
1030     if( ! $e->update_actor_user($u) ) {
1031         syslog('LOG_ERR', "OILS: Block: patron alert update failed: %s", $e->event->{textcode});
1032         $e->rollback; # rollback + disconnect
1033         return $self;
1034     }
1035
1036     # stay in synch
1037     $self->{user}->alert_message( $note );
1038
1039     $e->commit; # commits and disconnects
1040     return $self;
1041 }
1042
1043 # Testing purposes only
1044 sub enable {
1045     my ($self, $card_retained) = @_;
1046     $self->{screen_msg} = "All privileges restored.";
1047
1048     # Un-mark card as inactive, grep out the patron alert
1049     my $e = $self->{editor};
1050     my $u = $self->{user};
1051
1052     syslog('LOG_INFO', "OILS: Unblocking user %s", $u->card->barcode );
1053
1054     return $self if $u->card->active eq 't';
1055
1056     $e->xact_begin;    # connect and start a new transaction
1057
1058     $u->card->active('t');
1059     if( ! $e->update_actor_card($u->card) ) {
1060         syslog('LOG_ERR', "OILS: Unblock card update failed: %s", $e->event->{textcode});
1061         $e->rollback; # rollback + disconnect
1062         return $self;
1063     }
1064
1065     # retrieve the un-fleshed user object for update
1066     $u = $e->retrieve_actor_user($u->id);
1067     my $note = $u->alert_message || "";
1068     $note =~ s#<sip>.*</sip>##;
1069     $note =~ s/^\s*//;  # kill leading whitespace
1070     $note =~ s/\s*$//;  # kill trailng whitespace
1071     $u->alert_message($note);
1072
1073     if( ! $e->update_actor_user($u) ) {
1074         syslog('LOG_ERR', "OILS: Unblock: patron alert update failed: %s", $e->event->{textcode});
1075         $e->rollback; # rollback + disconnect
1076         return $self;
1077     }
1078
1079     # stay in synch
1080     $self->{user}->alert_message( $note );
1081
1082     $e->commit; # commits and disconnects
1083     return $self;
1084 }
1085
1086 #
1087 # Messages
1088 #
1089
1090 sub invalid_patron {
1091     return "Please contact library staff";
1092 }
1093
1094 sub charge_denied {
1095     return "Please contact library staff";
1096 }
1097
1098 sub inet_privileges {
1099     my( $self ) = @_;
1100     my $e = OpenILS::SIP->editor();
1101     $INET_PRIVS = $e->retrieve_all_config_net_access_level() unless $INET_PRIVS;
1102     my ($level) = grep { $_->id eq $self->{user}->net_access_level } @$INET_PRIVS;
1103     my $name = $level->name;
1104     syslog('LOG_DEBUG', "OILS: Patron inet_privs = $name");
1105     return $name;
1106 }
1107
1108 sub extra_fields {
1109     my( $self ) = @_;
1110     my $extra_fields = {};
1111     my $u = $self->{user};
1112     foreach my $stat_cat_entry (@{$u->stat_cat_entries}) {
1113         my $stat_cat = $stat_cat_entry->stat_cat;
1114         next unless ($stat_cat->sip_field);
1115         my $value = $stat_cat_entry->stat_cat_entry;
1116         if(defined $stat_cat->sip_format && length($stat_cat->sip_format) > 0) { # Has a format string?
1117             if($stat_cat->sip_format =~ /^\|(.*)\|$/) { # Regex match?
1118                 if($value =~ /($1)/) { # If we have a match
1119                     if(defined $2) { # Check to see if they embedded a capture group
1120                         $value = $2; # If so, use it
1121                     }
1122                     else { # No embedded capture group?
1123                         $value = $1; # Use our outer one
1124                     }
1125                 }
1126                 else { # No match?
1127                     $value = ''; # Empty string. Will be checked for below.
1128                 }
1129             }
1130             else { # Not a regex match - Try sprintf match (looking for a %s, if any)
1131                 $value = sprintf($stat_cat->sip_format, $value);
1132             }
1133         }
1134         next unless length($value) > 0; # No value = no export
1135         $value =~ s/\|//g; # Remove all lingering pipe chars for sane output purposes
1136         $extra_fields->{ $stat_cat->sip_field } = [] unless (defined $extra_fields->{$stat_cat->sip_field});
1137         push(@{$extra_fields->{ $stat_cat->sip_field}}, $value);
1138     }
1139     return $extra_fields;
1140 }
1141
1142 1;