]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/SIP/Patron.pm
LP2045292 Color contrast for AngularJS patron bills
[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     return $e->json_query(
643         {
644             select => { acp => ['id'] },
645             from => {
646                 acp => {
647                     acpm => {
648                         field => 'target_copy',
649                         fkey => 'id',
650                         filter => { part => $hold->target }
651                     }
652                 }
653            },
654            where => { '+acp' => { deleted => 'f' } },
655            limit => 1
656        })->[0]->{id} if $hold->hold_type eq 'P';
657
658
659     return $e->json_query(
660         {
661             select => { acp => ['id'] },
662             from => {
663                 acp => {
664                     sitem => {
665                         field => 'unit',
666                         fkey => 'id',
667                         filter => { issuance => $hold->target }
668                     }
669                 }
670            },
671            where => { '+acp' => { deleted => 'f' } },
672            limit => 1
673        })->[0]->{id} if $hold->hold_type eq 'I';
674
675
676     my $bre_ids = [$hold->target];
677
678     if ($hold->hold_type eq 'M') {
679         # find all of the bibs that link to the target metarecord
680         my $maps = $e->search_metabib_metarecord_source_map(
681             {metarecord => $hold->target});
682         $bre_ids = [map {$_->record} @$maps];
683     }
684
685     my $vol_ids = $e->search_asset_call_number( 
686         {record => $bre_ids, deleted => 'f'}, 
687         {idlist => 1}
688     );
689
690     return $e->search_asset_copy([
691         {call_number => $vol_ids, deleted => 'f'}, 
692         {limit => 1}
693     ])->[0];
694 }
695
696 # Given a "representative" copy, finds a matching hold
697 sub find_hold_from_copy {
698     my ($self, $barcode) = @_;
699     my $e = $self->{editor};
700     my $hold;
701
702     my $copy = $e->search_asset_copy([
703         {barcode => $barcode, deleted => 'f'},
704         {flesh => 1, flesh_fields => {acp => ['call_number']}}
705     ])->[0];
706
707     return undef unless $copy;
708
709     my $run_hold_query = sub {
710         my %filter = @_;
711         return $e->search_action_hold_request([
712             {   usr => $self->{user}->id,
713                 cancel_time => undef,
714                 fulfillment_time => undef,
715                 %filter
716             }, {
717                 limit => 1,
718                 order_by => {ahr => 'request_time DESC'}
719             }
720         ])->[0];
721     };
722
723     # first see if there is a match on current_copy
724     return $hold if $hold = 
725         $run_hold_query->(current_copy => $copy->id);
726
727     # next, assume bib-level holds are the most common
728     return $hold if $hold = $run_hold_query->(
729         target => $copy->call_number->record, hold_type => 'T');
730
731     # next try metarecord holds
732     my $map = $e->search_metabib_metarecord_source_map(
733         {source => $copy->call_number->record})->[0];
734
735     return $hold if $hold = $run_hold_query->(
736         target => $map->metarecord, hold_type => 'M');
737
738
739     # part holds
740     my $part = $e->search_asset_copy_part_map(
741         { target_copy => $copy->id })->[0];
742
743     if ($part) {
744         return $hold if $hold = $run_hold_query->(
745             target => $part->id, hold_type => 'P');
746     }
747
748     # issuance holds
749     my $iss = $e->search_serial_item(
750         { unit => $copy->id })->[0];
751
752     if ($iss) {
753         return $hold if $hold = $run_hold_query->(
754             target => $iss->id, hold_type => 'I');
755     }
756
757     # volume holds
758     return $hold if $hold = $run_hold_query->(
759         target => $copy->call_number->id, hold_type => 'V');
760
761     # copy holds
762     return $run_hold_query->(
763         target => $copy->id, hold_type => ['C', 'F', 'R']);
764 }
765
766 sub __hold_to_title {
767     my $self = shift;
768     my $hold = shift;
769     my $e = $self->{editor};
770
771     my( $id, $mods, $title, $volume, $copy );
772
773     return __copy_to_title($e, 
774         $e->retrieve_asset_copy($hold->target)) 
775         if $hold->hold_type eq 'C' or $hold->hold_type eq 'F' or $hold->hold_type eq 'R';
776
777     return __part_to_title($e,
778         $e->retrieve_biblio_monograph_part($hold->target))
779         if $hold->hold_type eq 'P';
780
781     return __volume_to_title($e, 
782         $e->retrieve_asset_call_number($hold->target))
783         if $hold->hold_type eq 'V';
784
785     return __issuance_to_title(
786         $e, $hold->target) # starts with the issuance id because there's more involved for I holds.
787         if $hold->hold_type eq 'I';
788
789     return __record_to_title(
790         $e, $hold->target) if $hold->hold_type eq 'T';
791
792     return __metarecord_to_title(
793         $e, $hold->target) if $hold->hold_type eq 'M';
794 }
795
796 sub __copy_to_title {
797     my( $e, $copy ) = @_;
798     #syslog('LOG_DEBUG', "OILS: copy_to_title(%s)", $copy->id);
799     return $copy->dummy_title if $copy->call_number == -1;    
800
801     my $vol = (ref $copy->call_number) ?
802         $copy->call_number :
803         $e->retrieve_asset_call_number($copy->call_number);
804
805     return __volume_to_title($e, $vol);
806 }
807
808 sub __part_to_title {
809     my( $e, $part ) = @_;
810     #syslog('LOG_DEBUG', "OILS: part_to_title(%s)", $part->id);
811
812     return __record_to_title($e, $part->record);
813 }
814
815 sub __volume_to_title {
816     my( $e, $volume ) = @_;
817     #syslog('LOG_DEBUG', "OILS: volume_to_title(%s)", $volume->id);
818     return __record_to_title($e, $volume->record);
819 }
820
821 sub __issuance_to_title {
822     my( $e, $issuance_id ) = @_;
823     my $bre_id = $e->json_query(
824     {
825         select => { ssub => ['record_entry'] },
826         from => {
827             ssub => {
828                 siss => {
829                     field => 'subscription',
830                     fkey => 'id',
831                     filter => { id => $issuance_id }
832                 }
833             }
834         }
835     })->[0]->{record_entry};
836
837     return __record_to_title($e, $bre_id);
838 }
839
840
841 sub __record_to_title {
842     my( $e, $title_id ) = @_;
843     #syslog('LOG_DEBUG', "OILS: record_to_title($title_id)");
844     my $mods = $U->simplereq(
845         'open-ils.search',
846         'open-ils.search.biblio.record.mods_slim.retrieve', $title_id );
847     return ($mods) ? $mods->title : "";
848 }
849
850 sub __metarecord_to_title {
851     my( $e, $m_id ) = @_;
852     #syslog('LOG_DEBUG', "OILS: metarecord_to_title($m_id)");
853     my $mods = $U->simplereq(
854         'open-ils.search',
855         'open-ils.search.biblio.metarecord.mods_slim.retrieve', $m_id);
856     return ($U->event_code($mods)) ? "<unknown>" : $mods->title;
857 }
858
859
860 #
861 # remove the hold on item item_id from my hold queue.
862 # return true if I was holding the item, false otherwise.
863
864 sub drop_hold {
865     my ($self, $item_id) = @_;
866     return 0;
867 }
868
869 sub __patron_items_info {
870     my $self = shift;
871     return if $self->{item_info};
872     $self->{item_info} = 
873         OpenILS::Application::Actor::_checked_out(
874             0, $self->{editor}, $self->{user}->id);;
875 }
876
877
878
879 sub overdue_items {
880     my ($self, $start, $end, $ids_only) = @_;
881
882     $self->__patron_items_info();
883     my @overdues = @{$self->{item_info}->{overdue}};
884     #$overdues[$_] = __circ_to_title($self->{editor}, $overdues[$_]) for @overdues;
885
886     return \@overdues if $ids_only;
887
888     my @o;
889     syslog('LOG_DEBUG', "OILS: overdue_items() fleshing circs @overdues");
890
891     my $return_datatype = OpenILS::SIP->get_option_value('msg64_summary_datatype') || '';
892     
893     for my $circid (@overdues) {
894         next unless $circid;
895         if($return_datatype eq 'barcode') {
896             push( @o, __circ_to_barcode($self->{editor}, $circid));
897         } else {
898             push( @o, __circ_to_title($self->{editor}, $circid));
899         }
900     }
901     @overdues = @o;
902
903     return (defined $start and defined $end) ? 
904         [ @overdues[($start-1)..($end-1)] ] : \@overdues;
905 }
906
907 sub __circ_to_barcode {
908     my ($e, $circ) = @_;
909     return unless $circ;
910     $circ = $e->retrieve_action_circulation($circ);
911     my $copy = $e->retrieve_asset_copy($circ->target_copy);
912     return $copy->barcode;
913 }
914
915 sub __circ_to_title {
916     my( $e, $circ ) = @_;
917     return unless $circ;
918     $circ = $e->retrieve_action_circulation($circ);
919     return __copy_to_title( $e, 
920         $e->retrieve_asset_copy($circ->target_copy) );
921 }
922
923 sub charged_items {
924     my ($self, $start, $end, $ids_only) = shift;
925     return $self->charged_items_impl($start, $end, undef, $ids_only);
926 }
927
928 # implementation method
929 # force_bc -- return barcode data regardless of msg64_summary_datatype;
930 #             this is used by the renew-all code
931 sub charged_items_impl {
932     my ($self, $start, $end, $force_bc, $ids_only) = shift;
933
934     $self->__patron_items_info();
935
936     my @charges = (
937         @{$self->{item_info}->{out}},
938         @{$self->{item_info}->{overdue}}
939         );
940
941     #$charges[$_] = __circ_to_title($self->{editor}, $charges[$_]) for @charges;
942
943     return \@charges if $ids_only;
944
945     my @c;
946     syslog('LOG_DEBUG', "OILS: charged_items() fleshing circs @charges");
947
948     my $return_datatype = OpenILS::SIP->get_option_value('msg64_summary_datatype') || '';
949
950     for my $circid (@charges) {
951         next unless $circid;
952         if($return_datatype eq 'barcode' or $force_bc) {
953             push( @c, __circ_to_barcode($self->{editor}, $circid));
954         } else {
955             push( @c, __circ_to_title($self->{editor}, $circid));
956         }
957     }
958
959     @charges = @c;
960
961     return (defined $start and defined $end) ? 
962         [ @charges[($start-1)..($end-1)] ] :
963         \@charges;
964 }
965
966 sub fine_items {
967     my ($self, $start, $end, $ids_only) = @_;
968     my @fines;
969
970     my $login = OpenILS::SIP->login_account();
971     my $AV_format = lc($login->{av_format}) || 'eg_legacy';
972
973     # Do a prescan for validity and default to eg_legacy
974     if ($AV_format ne "swyer_a" &&
975         $AV_format ne "swyer_b" &&
976         $AV_format ne "eg_legacy" &&
977         $AV_format ne "3m") {
978
979         syslog('LOG_WARNING',
980             "OILS: Unknown value for AV_format: ". $login->{av_format});
981         $AV_format = "eg_legacy";
982     }
983
984     my $xacts = $U->simplereq('open-ils.actor',
985         'open-ils.actor.user.transactions.history.have_balance',
986         $self->{authtoken}, $self->{user}->id);
987
988     my $line;
989     foreach my $xact (@{$xacts}) {
990
991         if ($ids_only) {
992             push @fines, $xact->id;
993             next;
994         }
995
996         # fine item details requested
997
998         my $title;
999         my $author;
1000         my $line;
1001
1002         my $fee_type;
1003
1004         if ($xact->last_billing_type =~ /^Lost/) {
1005             $fee_type = 'LOST';
1006         } elsif ($xact->last_billing_type =~ /^Overdue/) {
1007             $fee_type = 'FINE';
1008         } else {
1009             $fee_type = 'FEE';
1010         }
1011
1012         if ($xact->xact_type eq 'circulation') {
1013             my $e = OpenILS::SIP->editor();
1014             my $circ = $e->retrieve_action_circulation([
1015                 $xact->id, {
1016                     flesh => 2,
1017                     flesh_fields => {
1018                         circ => ['target_copy'],
1019                         acp => ['call_number']
1020                     }
1021                 }
1022             ]);
1023
1024             my $displays = $e->search_metabib_flat_display_entry({
1025                 source => $circ->target_copy->call_number->record,
1026                 name => ['title', 'author']
1027             });
1028
1029             ($title) = map {$_->value} grep {$_->name eq 'title'} @$displays;
1030             ($author) = map {$_->value} grep {$_->name eq 'author'} @$displays;
1031
1032             # Scrub "/" chars since they are used in some cases 
1033             # to delineate title/author.
1034             if ($title) {
1035                 $title =~ s/\///g;
1036             } else {
1037                 $title = '';
1038             }
1039
1040             if ($author) {
1041                 $author =~ s/\///g;
1042             } else {
1043                 $author = '';
1044             }
1045         }
1046
1047         if ($AV_format eq "eg_legacy") {
1048
1049             $line = $xact->balance_owed . " " . $xact->last_billing_type . " ";
1050
1051             if ($xact->xact_type eq 'circulation') {
1052                 $line .= "$title / $author";
1053             } else {
1054                 $line .= $xact->last_billing_note;
1055             }
1056
1057         } elsif ($AV_format eq "3m" or $AV_format eq "swyer_a") {
1058
1059             $line = $xact->id . ' $' . $xact->balance_owed . " \"$fee_type\" ";
1060
1061             if ($xact->xact_type eq 'circulation') {
1062                 $line .= "$title";
1063             } else {
1064                 $line .= $xact->last_billing_note;
1065             }
1066
1067         } elsif ($AV_format eq "swyer_b") {
1068
1069             $line =   "Charge-Number: " . $xact->id;
1070             $line .=  ", Amount-Due: "  . $xact->balance_owed;
1071             $line .=  ", Fine-Type: $fee_type";
1072
1073             if ($xact->xact_type eq 'circulation') {
1074                 $line .= ", Title: $title";
1075             } else {
1076                 $line .= ", Title: " . $xact->last_billing_note;
1077             }
1078         }
1079
1080         push @fines, $line;
1081     }
1082
1083     my $log_status = $@ ? 'ERROR: ' . $@ : 'OK';
1084     syslog('LOG_DEBUG', 'OILS: Patron->fine_items() ' . $log_status);
1085     return (defined $start and defined $end) ? 
1086         [ @fines[($start-1)..($end-1)] ] : \@fines;
1087 }
1088
1089 # not currently supported
1090 sub recall_items {
1091     my ($self, $start, $end, $ids_only) = @_;
1092     return [];
1093 }
1094
1095 sub block {
1096     my ($self, $card_retained, $blocked_card_msg) = @_;
1097     $blocked_card_msg ||= '';
1098
1099     my $e = $self->{editor};
1100     my $u = $self->{user};
1101
1102     syslog('LOG_INFO', "OILS: Blocking user %s", $u->card->barcode );
1103
1104     return $self if $u->card->active eq 'f'; # TODO: don't think this will ever be true
1105
1106     $e->xact_begin;    # connect and start a new transaction
1107
1108     $u->card->active('f');
1109     if( ! $e->update_actor_card($u->card) ) {
1110         syslog('LOG_ERR', "OILS: Block card update failed: %s", $e->event->{textcode});
1111         $e->rollback; # rollback + disconnect
1112         return $self;
1113     }
1114
1115     # Use the ws_ou or home_ou of the authsession user, if any, as a
1116     # context org_unit for the created penalty
1117     my $here;
1118     if ($e->authtoken()) {
1119         my $auth_usr = $e->checkauth();
1120         if ($auth_usr) {
1121             $here = $auth_usr->ws_ou() || $auth_usr->home_ou();
1122         }
1123     }
1124
1125     my $penalty = Fieldmapper::actor::user_standing_penalty->new;
1126     $penalty->usr( $u->id );
1127     $penalty->org_unit( $here );
1128     $penalty->set_date('now');
1129     $penalty->staff( $e->checkauth()->id() );
1130     $penalty->standing_penalty(20); # ALERT_NOTE
1131
1132     my $note = "<sip> CARD BLOCKED BY SELF-CHECK MACHINE. $blocked_card_msg</sip>\n"; # XXX Config option
1133     my $msg = {
1134       title => 'SIP',
1135       message => $note
1136     };
1137     my $penalty_result = $U->simplereq(
1138       'open-ils.actor',
1139       'open-ils.actor.user.penalty.apply', $e->authtoken, $penalty, $msg);
1140     if( my $result_code = $U->event_code($penalty_result) ) {
1141         my $textcode = $penalty_result->{textcode};
1142         syslog('LOG_ERR', "OILS: Block: patron penalty failed: %s", $textcode);
1143         $e->rollback; # rollback + disconnect
1144         return $self;
1145     }
1146
1147     $e->commit;
1148     return $self;
1149 }
1150
1151 # Testing purposes only
1152 sub enable {
1153     # TODO: we never actually enter this sub if the patron's card is not active
1154     # For now, to test the removal of the SIP penalties, manually activate the card first
1155     my ($self, $card_retained) = @_;
1156     $self->{screen_msg} = "All privileges restored.";
1157
1158     # Un-mark card as inactive, grep out the patron alert
1159     my $e = $self->{editor};
1160     my $u = $self->{user};
1161
1162     syslog('LOG_INFO', "OILS: Unblocking user %s", $u->card->barcode );
1163
1164     $e->xact_begin;    # connect and start a new transaction
1165
1166     if ($u->card->active eq 'f') {
1167         $u->card->active('t');
1168         if( ! $e->update_actor_card($u->card) ) {
1169             syslog('LOG_ERR', "OILS: Unblock card update failed: %s", $e->event->{textcode});
1170             $e->rollback; # rollback + disconnect
1171             return $self;
1172         }
1173     }
1174
1175     # look for sip related penalties
1176     my $sip_penalties = $e->search_actor_usr_message_penalty({ usr => $u->id, title => 'SIP', stop_date => undef });
1177
1178     if (scalar(@{ $sip_penalties }) == 0) {
1179         syslog('LOG_INFO', 'OILS: Unblock: no SIP penalties to archive');
1180     }
1181
1182     foreach my $aump (@{ $sip_penalties }) {
1183         my $penalty = $e->retrieve_actor_user_standing_penalty( $aump->ausp_id() );
1184         $penalty->stop_date('now');
1185         if ( ! $e->update_actor_user_standing_penalty($penalty) ) {
1186             syslog('LOG_ERR', "OILS: Unblock: patron alert update failed: %s", $e->event->{textcode});
1187             $e->rollback; # rollback + disconnect
1188             return $self;
1189         }
1190     }
1191
1192     $e->commit; # commits and disconnects
1193     return $self;
1194 }
1195
1196 #
1197 # Messages
1198 #
1199
1200 sub invalid_patron {
1201     return "Please contact library staff";
1202 }
1203
1204 sub charge_denied {
1205     return "Please contact library staff";
1206 }
1207
1208 sub inet_privileges {
1209     my( $self ) = @_;
1210     my $e = OpenILS::SIP->editor();
1211     $INET_PRIVS = $e->retrieve_all_config_net_access_level() unless $INET_PRIVS;
1212     my ($level) = grep { $_->id eq $self->{user}->net_access_level } @$INET_PRIVS;
1213     my $name = $level->name;
1214     syslog('LOG_DEBUG', "OILS: Patron inet_privs = $name");
1215     return $name;
1216 }
1217
1218 sub extra_fields {
1219     my( $self ) = @_;
1220     my $extra_fields = {};
1221     my $u = $self->{user};
1222     foreach my $stat_cat_entry (@{$u->stat_cat_entries}) {
1223         my $stat_cat = $stat_cat_entry->stat_cat;
1224         next unless ($stat_cat->sip_field);
1225         my $value = $stat_cat_entry->stat_cat_entry;
1226         if(defined $stat_cat->sip_format && length($stat_cat->sip_format) > 0) { # Has a format string?
1227             if($stat_cat->sip_format =~ /^\|(.*)\|$/) { # Regex match?
1228                 if($value =~ /($1)/) { # If we have a match
1229                     if(defined $2) { # Check to see if they embedded a capture group
1230                         $value = $2; # If so, use it
1231                     }
1232                     else { # No embedded capture group?
1233                         $value = $1; # Use our outer one
1234                     }
1235                 }
1236                 else { # No match?
1237                     $value = ''; # Empty string. Will be checked for below.
1238                 }
1239             }
1240             else { # Not a regex match - Try sprintf match (looking for a %s, if any)
1241                 $value = sprintf($stat_cat->sip_format, $value);
1242             }
1243         }
1244         next unless length($value) > 0; # No value = no export
1245         $value =~ s/\|//g; # Remove all lingering pipe chars for sane output purposes
1246         $extra_fields->{ $stat_cat->sip_field } = [] unless (defined $extra_fields->{$stat_cat->sip_field});
1247         push(@{$extra_fields->{ $stat_cat->sip_field}}, $value);
1248     }
1249     return $extra_fields;
1250 }
1251
1252 1;