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