]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/SIP/Patron.pm
lp1846354 additional tweaks and fixes
[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->first_given_name || ''),
253                    ($u->second_given_name || ''),
254                    ($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 __volume_to_title($e, 
725         $e->retrieve_asset_call_number($hold->target))
726         if $hold->hold_type eq 'V';
727
728     return __record_to_title(
729         $e, $hold->target) if $hold->hold_type eq 'T';
730
731     return __metarecord_to_title(
732         $e, $hold->target) if $hold->hold_type eq 'M';
733 }
734
735 sub __copy_to_title {
736     my( $e, $copy ) = @_;
737     #syslog('LOG_DEBUG', "OILS: copy_to_title(%s)", $copy->id);
738     return $copy->dummy_title if $copy->call_number == -1;    
739
740     my $vol = (ref $copy->call_number) ?
741         $copy->call_number :
742         $e->retrieve_asset_call_number($copy->call_number);
743
744     return __volume_to_title($e, $vol);
745 }
746
747
748 sub __volume_to_title {
749     my( $e, $volume ) = @_;
750     #syslog('LOG_DEBUG', "OILS: volume_to_title(%s)", $volume->id);
751     return __record_to_title($e, $volume->record);
752 }
753
754
755 sub __record_to_title {
756     my( $e, $title_id ) = @_;
757     #syslog('LOG_DEBUG', "OILS: record_to_title($title_id)");
758     my $mods = $U->simplereq(
759         'open-ils.search',
760         'open-ils.search.biblio.record.mods_slim.retrieve', $title_id );
761     return ($mods) ? $mods->title : "";
762 }
763
764 sub __metarecord_to_title {
765     my( $e, $m_id ) = @_;
766     #syslog('LOG_DEBUG', "OILS: metarecord_to_title($m_id)");
767     my $mods = $U->simplereq(
768         'open-ils.search',
769         'open-ils.search.biblio.metarecord.mods_slim.retrieve', $m_id);
770     return ($U->event_code($mods)) ? "<unknown>" : $mods->title;
771 }
772
773
774 #
775 # remove the hold on item item_id from my hold queue.
776 # return true if I was holding the item, false otherwise.
777
778 sub drop_hold {
779     my ($self, $item_id) = @_;
780     return 0;
781 }
782
783 sub __patron_items_info {
784     my $self = shift;
785     return if $self->{item_info};
786     $self->{item_info} = 
787         OpenILS::Application::Actor::_checked_out(
788             0, $self->{editor}, $self->{user}->id);;
789 }
790
791
792
793 sub overdue_items {
794     my ($self, $start, $end, $ids_only) = @_;
795
796     $self->__patron_items_info();
797     my @overdues = @{$self->{item_info}->{overdue}};
798     #$overdues[$_] = __circ_to_title($self->{editor}, $overdues[$_]) for @overdues;
799
800     return \@overdues if $ids_only;
801
802     my @o;
803     syslog('LOG_DEBUG', "OILS: overdue_items() fleshing circs @overdues");
804
805     my $return_datatype = OpenILS::SIP->get_option_value('msg64_summary_datatype') || '';
806     
807     for my $circid (@overdues) {
808         next unless $circid;
809         if($return_datatype eq 'barcode') {
810             push( @o, __circ_to_barcode($self->{editor}, $circid));
811         } else {
812             push( @o, __circ_to_title($self->{editor}, $circid));
813         }
814     }
815     @overdues = @o;
816
817     return (defined $start and defined $end) ? 
818         [ @overdues[($start-1)..($end-1)] ] : \@overdues;
819 }
820
821 sub __circ_to_barcode {
822     my ($e, $circ) = @_;
823     return unless $circ;
824     $circ = $e->retrieve_action_circulation($circ);
825     my $copy = $e->retrieve_asset_copy($circ->target_copy);
826     return $copy->barcode;
827 }
828
829 sub __circ_to_title {
830     my( $e, $circ ) = @_;
831     return unless $circ;
832     $circ = $e->retrieve_action_circulation($circ);
833     return __copy_to_title( $e, 
834         $e->retrieve_asset_copy($circ->target_copy) );
835 }
836
837 sub charged_items {
838     my ($self, $start, $end, $ids_only) = shift;
839     return $self->charged_items_impl($start, $end, undef, $ids_only);
840 }
841
842 # implementation method
843 # force_bc -- return barcode data regardless of msg64_summary_datatype;
844 #             this is used by the renew-all code
845 sub charged_items_impl {
846     my ($self, $start, $end, $force_bc, $ids_only) = shift;
847
848     $self->__patron_items_info();
849
850     my @charges = (
851         @{$self->{item_info}->{out}},
852         @{$self->{item_info}->{overdue}}
853         );
854
855     #$charges[$_] = __circ_to_title($self->{editor}, $charges[$_]) for @charges;
856
857     return \@charges if $ids_only;
858
859     my @c;
860     syslog('LOG_DEBUG', "OILS: charged_items() fleshing circs @charges");
861
862     my $return_datatype = OpenILS::SIP->get_option_value('msg64_summary_datatype') || '';
863
864     for my $circid (@charges) {
865         next unless $circid;
866         if($return_datatype eq 'barcode' or $force_bc) {
867             push( @c, __circ_to_barcode($self->{editor}, $circid));
868         } else {
869             push( @c, __circ_to_title($self->{editor}, $circid));
870         }
871     }
872
873     @charges = @c;
874
875     return (defined $start and defined $end) ? 
876         [ @charges[($start-1)..($end-1)] ] :
877         \@charges;
878 }
879
880 sub fine_items {
881     my ($self, $start, $end, $ids_only) = @_;
882     my @fines;
883
884     my $login = OpenILS::SIP->login_account();
885     my $AV_format = lc($login->{av_format}) || 'eg_legacy';
886
887     # Do a prescan for validity and default to eg_legacy
888     if ($AV_format ne "swyer_a" &&
889         $AV_format ne "swyer_b" &&
890         $AV_format ne "eg_legacy" &&
891         $AV_format ne "3m") {
892
893         syslog('LOG_WARNING',
894             "OILS: Unknown value for AV_format: ". $login->{av_format});
895         $AV_format = "eg_legacy";
896     }
897
898     my $xacts = $U->simplereq('open-ils.actor',
899         'open-ils.actor.user.transactions.history.have_balance',
900         $self->{authtoken}, $self->{user}->id);
901
902     my $line;
903     foreach my $xact (@{$xacts}) {
904
905         if ($ids_only) {
906             push @fines, $xact->id;
907             next;
908         }
909
910         # fine item details requested
911
912         my $title;
913         my $author;
914         my $line;
915
916         my $fee_type;
917
918         if ($xact->last_billing_type =~ /^Lost/) {
919             $fee_type = 'LOST';
920         } elsif ($xact->last_billing_type =~ /^Overdue/) {
921             $fee_type = 'FINE';
922         } else {
923             $fee_type = 'FEE';
924         }
925
926         if ($xact->xact_type eq 'circulation') {
927             my $e = OpenILS::SIP->editor();
928             my $circ = $e->retrieve_action_circulation([
929                 $xact->id, {
930                     flesh => 2,
931                     flesh_fields => {
932                         circ => ['target_copy'],
933                         acp => ['call_number']
934                     }
935                 }
936             ]);
937
938             my $displays = $e->search_metabib_flat_display_entry({
939                 source => $circ->target_copy->call_number->record,
940                 name => ['title', 'author']
941             });
942
943             ($title) = map {$_->value} grep {$_->name eq 'title'} @$displays;
944             ($author) = map {$_->value} grep {$_->name eq 'author'} @$displays;
945
946             # Scrub "/" chars since they are used in some cases 
947             # to delineate title/author.
948             if ($title) {
949                 $title =~ s/\///g;
950             } else {
951                 $title = '';
952             }
953
954             if ($author) {
955                 $author =~ s/\///g;
956             } else {
957                 $author = '';
958             }
959         }
960
961         if ($AV_format eq "eg_legacy") {
962
963             $line = $xact->balance_owed . " " . $xact->last_billing_type . " ";
964
965             if ($xact->xact_type eq 'circulation') {
966                 $line .= "$title / $author";
967             } else {
968                 $line .= $xact->last_billing_note;
969             }
970
971         } elsif ($AV_format eq "3m" or $AV_format eq "swyer_a") {
972
973             $line = $xact->id . ' $' . $xact->balance_owed . " \"$fee_type\" ";
974
975             if ($xact->xact_type eq 'circulation') {
976                 $line .= "$title";
977             } else {
978                 $line .= $xact->last_billing_note;
979             }
980
981         } elsif ($AV_format eq "swyer_b") {
982
983             $line =   "Charge-Number: " . $xact->id;
984             $line .=  ", Amount-Due: "  . $xact->balance_owed;
985             $line .=  ", Fine-Type: $fee_type";
986
987             if ($xact->xact_type eq 'circulation') {
988                 $line .= ", Title: $title";
989             } else {
990                 $line .= ", Title: " . $xact->last_billing_note;
991             }
992         }
993
994         push @fines, $line;
995     }
996
997     my $log_status = $@ ? 'ERROR: ' . $@ : 'OK';
998     syslog('LOG_DEBUG', 'OILS: Patron->fine_items() ' . $log_status);
999     return (defined $start and defined $end) ? 
1000         [ @fines[($start-1)..($end-1)] ] : \@fines;
1001 }
1002
1003 # not currently supported
1004 sub recall_items {
1005     my ($self, $start, $end, $ids_only) = @_;
1006     return [];
1007 }
1008
1009 sub block {
1010     my ($self, $card_retained, $blocked_card_msg) = @_;
1011     $blocked_card_msg ||= '';
1012
1013     my $e = $self->{editor};
1014     my $u = $self->{user};
1015
1016     syslog('LOG_INFO', "OILS: Blocking user %s", $u->card->barcode );
1017
1018     return $self if $u->card->active eq 'f'; # TODO: don't think this will ever be true
1019
1020     $e->xact_begin;    # connect and start a new transaction
1021
1022     $u->card->active('f');
1023     if( ! $e->update_actor_card($u->card) ) {
1024         syslog('LOG_ERR', "OILS: Block card update failed: %s", $e->event->{textcode});
1025         $e->rollback; # rollback + disconnect
1026         return $self;
1027     }
1028
1029     # Use the ws_ou or home_ou of the authsession user, if any, as a
1030     # context org_unit for the created penalty
1031     my $here;
1032     if ($e->authtoken()) {
1033         my $auth_usr = $e->checkauth();
1034         if ($auth_usr) {
1035             $here = $auth_usr->ws_ou() || $auth_usr->home_ou();
1036         }
1037     }
1038
1039     my $penalty = Fieldmapper::actor::user_standing_penalty->new;
1040     $penalty->usr( $u->id );
1041     $penalty->org_unit( $here );
1042     $penalty->set_date('now');
1043     $penalty->staff( $e->checkauth()->id() );
1044     $penalty->standing_penalty(20); # ALERT_NOTE
1045
1046     my $note = "<sip> CARD BLOCKED BY SELF-CHECK MACHINE. $blocked_card_msg</sip>\n"; # XXX Config option
1047     my $msg = {
1048       title => 'SIP',
1049       message => $note
1050     };
1051     my $penalty_result = $U->simplereq(
1052       'open-ils.actor',
1053       'open-ils.actor.user.penalty.apply', $e->authtoken, $penalty, $msg);
1054     if( my $result_code = $U->event_code($penalty_result) ) {
1055         my $textcode = $penalty_result->{textcode};
1056         syslog('LOG_ERR', "OILS: Block: patron penalty failed: %s", $textcode);
1057         $e->rollback; # rollback + disconnect
1058         return $self;
1059     }
1060
1061     $e->commit;
1062     return $self;
1063 }
1064
1065 # Testing purposes only
1066 sub enable {
1067     # TODO: we never actually enter this sub if the patron's card is not active
1068     # For now, to test the removal of the SIP penalties, manually activate the card first
1069     my ($self, $card_retained) = @_;
1070     $self->{screen_msg} = "All privileges restored.";
1071
1072     # Un-mark card as inactive, grep out the patron alert
1073     my $e = $self->{editor};
1074     my $u = $self->{user};
1075
1076     syslog('LOG_INFO', "OILS: Unblocking user %s", $u->card->barcode );
1077
1078     $e->xact_begin;    # connect and start a new transaction
1079
1080     if ($u->card->active eq 'f') {
1081         $u->card->active('t');
1082         if( ! $e->update_actor_card($u->card) ) {
1083             syslog('LOG_ERR', "OILS: Unblock card update failed: %s", $e->event->{textcode});
1084             $e->rollback; # rollback + disconnect
1085             return $self;
1086         }
1087     }
1088
1089     # look for sip related penalties
1090     my $sip_penalties = $e->search_actor_usr_message_penalty({ usr => $u->id, title => 'SIP', stop_date => undef });
1091
1092     if (scalar(@{ $sip_penalties }) == 0) {
1093         syslog('LOG_INFO', 'OILS: Unblock: no SIP penalties to archive');
1094     }
1095
1096     foreach my $aump (@{ $sip_penalties }) {
1097         my $penalty = $e->retrieve_actor_user_standing_penalty( $aump->ausp_id() );
1098         $penalty->stop_date('now');
1099         if ( ! $e->update_actor_user_standing_penalty($penalty) ) {
1100             syslog('LOG_ERR', "OILS: Unblock: patron alert update failed: %s", $e->event->{textcode});
1101             $e->rollback; # rollback + disconnect
1102             return $self;
1103         }
1104     }
1105
1106     $e->commit; # commits and disconnects
1107     return $self;
1108 }
1109
1110 #
1111 # Messages
1112 #
1113
1114 sub invalid_patron {
1115     return "Please contact library staff";
1116 }
1117
1118 sub charge_denied {
1119     return "Please contact library staff";
1120 }
1121
1122 sub inet_privileges {
1123     my( $self ) = @_;
1124     my $e = OpenILS::SIP->editor();
1125     $INET_PRIVS = $e->retrieve_all_config_net_access_level() unless $INET_PRIVS;
1126     my ($level) = grep { $_->id eq $self->{user}->net_access_level } @$INET_PRIVS;
1127     my $name = $level->name;
1128     syslog('LOG_DEBUG', "OILS: Patron inet_privs = $name");
1129     return $name;
1130 }
1131
1132 sub extra_fields {
1133     my( $self ) = @_;
1134     my $extra_fields = {};
1135     my $u = $self->{user};
1136     foreach my $stat_cat_entry (@{$u->stat_cat_entries}) {
1137         my $stat_cat = $stat_cat_entry->stat_cat;
1138         next unless ($stat_cat->sip_field);
1139         my $value = $stat_cat_entry->stat_cat_entry;
1140         if(defined $stat_cat->sip_format && length($stat_cat->sip_format) > 0) { # Has a format string?
1141             if($stat_cat->sip_format =~ /^\|(.*)\|$/) { # Regex match?
1142                 if($value =~ /($1)/) { # If we have a match
1143                     if(defined $2) { # Check to see if they embedded a capture group
1144                         $value = $2; # If so, use it
1145                     }
1146                     else { # No embedded capture group?
1147                         $value = $1; # Use our outer one
1148                     }
1149                 }
1150                 else { # No match?
1151                     $value = ''; # Empty string. Will be checked for below.
1152                 }
1153             }
1154             else { # Not a regex match - Try sprintf match (looking for a %s, if any)
1155                 $value = sprintf($stat_cat->sip_format, $value);
1156             }
1157         }
1158         next unless length($value) > 0; # No value = no export
1159         $value =~ s/\|//g; # Remove all lingering pipe chars for sane output purposes
1160         $extra_fields->{ $stat_cat->sip_field } = [] unless (defined $extra_fields->{$stat_cat->sip_field});
1161         push(@{$extra_fields->{ $stat_cat->sip_field}}, $value);
1162     }
1163     return $extra_fields;
1164 }
1165
1166 1;