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