]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/SIP/Patron.pm
Merge remote branch 'working/user/shadowspar/ttopac-altcleanup' into template-toolkit...
[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 OpenSRF::Utils qw/:datetime/;
21 use DateTime::Format::ISO8601;
22 my $U = 'OpenILS::Application::AppUtils';
23
24 our (@ISA, @EXPORT_OK);
25
26 @ISA = qw(Exporter);
27
28 @EXPORT_OK = qw(invalid_patron);
29
30 my $INET_PRIVS;
31
32 #
33 # OpenILS::SIP::Patron->new($barcode);
34 # OpenILS::SIP::Patron->new(barcode => $barcode);   # same as above
35 # OpenILS::SIP::Patron->new(    usr => $id);       
36
37 sub new {
38     my $class = shift;
39     my $key   = (@_ > 1) ? shift : 'barcode';  # if we have multiple args, the first is the key index (default barcode)
40     my $patron_id = shift;
41     my %args = @_;
42
43     if ($key ne 'usr' and $key ne 'barcode') {
44         syslog("LOG_ERROR", "Patron (card) lookup requested by illegeal key '$key'");
45         return undef;
46     }
47
48     unless(defined $patron_id) {
49         syslog("LOG_WARNING", "No patron ID provided to ILS::Patron->new");
50         return undef;
51     }
52
53     my $type = ref($class) || $class;
54     my $self = bless({}, $type);
55
56     syslog("LOG_DEBUG", "OILS: new OpenILS Patron(%s => %s): searching...", $key, $patron_id);
57
58     my $e = OpenILS::SIP->editor();
59
60     my $usr_flesh = {
61         flesh => 2,
62         flesh_fields => {
63             au => [
64                 "card",
65                 "addresses",
66                 "billing_address",
67                 "mailing_address",
68                 'profile',
69                 "stat_cat_entries",
70             ],
71             actscecm => [
72                 "stat_cat",
73             ],
74         }
75     };
76
77     # in some cases, we don't need all of this data.  Only fetch the user + barcode
78     $usr_flesh = {flesh => 1, flesh_fields => {au => ['card']}} if $args{slim_user};
79     
80     my $user;
81     if($key eq 'barcode') { # retrieve user by barcode
82
83         $$usr_flesh{flesh} += 1;
84         $$usr_flesh{flesh_fields}{ac} = ['usr'];
85
86         my $card = $e->search_actor_card([{barcode => $patron_id}, $usr_flesh])->[0];
87
88         if(!$card or !$U->is_true($card->active)) {
89             syslog("LOG_WARNING", "No such patron barcode: $patron_id");
90             return undef;
91         }
92
93         $user = $card->usr;
94
95     } else {
96             $user = $e->retrieve_actor_user([$patron_id, $usr_flesh]);
97     }
98
99     if(!$user or $U->is_true($user->deleted)) {
100         syslog("LOG_WARNING", "OILS: Unable to find patron %s => %s", $key, $patron_id);
101         return undef;
102     }
103
104     if(!$U->is_true($user->active)) {
105         syslog("LOG_WARNING", "OILS: Patron is inactive %s => %s", $key, $patron_id);
106         return undef;
107     }
108
109     # now grab the user's penalties
110
111     $self->flesh_user_penalties($user, $e) unless $args{slim_user};
112
113     $self->{editor} = $e;
114     $self->{user}   = $user;
115     $self->{id}     = ($key eq 'barcode') ? $patron_id : $user->card->barcode;   # The barcode IS the ID to SIP.  
116     # We give back the passed barcode if the key was indeed a barcode, just to be safe.  Otherwise pull it from the card.
117
118     syslog("LOG_DEBUG", "OILS: new OpenILS Patron(%s => %s): found patron : barred=%s, card:active=%s", 
119         $key, $patron_id, $user->barred, $user->card->active );
120
121     return $self;
122 }
123
124 # grab patron penalties.  Only grab non-archived penalties that are for fines,
125 # excessive overdues, or otherwise block circluation activity
126 sub flesh_user_penalties {
127     my ($self, $user, $e) = @_;
128
129     $user->standing_penalties(
130         $e->search_actor_user_standing_penalty([
131             {   
132                 usr => $user->id,
133                 '-or' => [
134
135                     # ignore "archived" penalties
136                     {stop_date => undef},
137                     {stop_date => {'>' => 'now'}}
138                 ],
139
140                 org_unit => {
141                     in  => {
142                         select => {
143                             aou => [{
144                                 column => 'id', 
145                                 transform => 'actor.org_unit_ancestors', 
146                                 result_field => 'id'
147                             }]
148                         },
149                         from => 'aou',
150
151                         # at this point, there is no concept of "here", so fetch penalties 
152                         # for the patron's home lib plus ancestors
153                         where => {id => $user->home_ou}, 
154                         distinct => 1
155                     }
156                 },
157
158                 # in addition to fines and excessive overdue penalties, 
159                 # we only care about penalties that result in blocks
160                 standing_penalty => {
161                     in => {
162                         select => {csp => ['id']},
163                         from => 'csp',
164                         where => {
165                             '-or' => [
166                                 {id => [1,2]}, # fines / overdues
167                                 {block_list => {'!=' => undef}}
168                             ]
169                         },
170                     }
171                 }
172             },
173         ])
174     );
175 }
176
177 sub id {
178     my $self = shift;
179     return $self->{id};
180 }
181
182 sub name {
183     my $self = shift;
184     return format_name($self->{user});
185 }
186
187 sub format_name {
188     my $u = shift;
189     return OpenILS::SIP::clean_text(
190         sprintf('%s %s %s', 
191             ($u->first_given_name || ''),
192             ($u->second_given_name || ''),
193             ($u->family_name || '')));
194 }
195
196 sub home_library {
197     my $self = shift;
198     my $lib = OpenILS::SIP::shortname_from_id($self->{user}->home_ou);
199         syslog('LOG_DEBUG', "OILS: Patron->home_library() = $lib");
200     return $lib;
201 }
202
203 sub __addr_string {
204     my $addr = shift;
205     return "" unless $addr;
206     my $return = OpenILS::SIP::clean_text(
207         join( ' ', map {$_ || ''} (
208             $addr->street1,
209             $addr->street2,
210             $addr->city . ',',
211             $addr->county,
212             $addr->state,
213             $addr->country,
214             $addr->post_code
215             )
216         )
217     );
218     $return =~ s/\s+/ /sg;     # Compress any run of of whitespace to one space
219     return $return;
220 }
221
222 sub internal_id {
223     my $self = shift;
224     return $self->{user}->id;
225 }
226
227 sub address {
228         my $self = shift;
229         my $u    = $self->{user};
230         my $str  = __addr_string($u->billing_address || $u->mailing_address);
231         syslog('LOG_DEBUG', "OILS: Patron address: $str");
232         return $str;
233 }
234
235 sub email_addr {
236     my $self = shift;
237     return OpenILS::SIP::clean_text($self->{user}->email);
238 }
239
240 sub home_phone {
241     my $self = shift;
242     return $self->{user}->day_phone;
243 }
244
245 sub sip_birthdate {
246         my $self = shift;
247         my $dob = OpenILS::SIP->format_date($self->{user}->dob);
248         syslog('LOG_DEBUG', "OILS: Patron DOB = $dob");
249         return $dob;
250 }
251
252 sub sip_expire {
253     my $self = shift;
254     my $expire = OpenILS::SIP->format_date($self->{user}->expire_date);
255     syslog('LOG_DEBUG', "OILS: Patron Expire = $expire");
256     return $expire;
257 }
258
259 sub ptype {
260     my $self = shift;
261
262         my $use_code = OpenILS::SIP->get_option_value('patron_type_uses_code') || '';
263
264     # should we use the no_i18n version of patron profile name (as a 'code')?
265     return $self->{editor}->retrieve_permission_grp_tree(
266         [$self->{user}->profile->id, {no_i18n => 1}])->name
267         if $use_code =~ /true/io;
268
269     return OpenILS::SIP::clean_text($self->{user}->profile->name);
270 }
271
272 sub language {
273     my $self = shift;
274     return '000'; # Unspecified
275 }
276
277 # How much more detail do we need to check here?
278 sub charge_ok {
279     my $self = shift;
280     my $u = $self->{user};
281     return 
282         $u->barred eq 'f' and 
283         $u->active eq 't' and
284         $u->card->active eq 't';
285 }
286
287 # How much more detail do we need to check here?
288 sub renew_ok {
289     my $self = shift;
290     return $self->charge_ok;
291 }
292
293 sub recall_ok {
294     my $self = shift;
295     return 0;
296 }
297
298 sub hold_ok {
299     my $self = shift;
300     return $self->charge_ok;
301 }
302
303 # return true if the card provided is marked as lost
304 sub card_lost {
305     my $self = shift;
306     return $self->{user}->card->active eq 'f';
307 }
308
309 sub recall_overdue {        # not implemented
310     my $self = shift;
311     return 0;
312 }
313
314 sub check_password {
315         my ($self, $pwd) = @_;
316         syslog('LOG_DEBUG', 'OILS: Patron->check_password()');
317     return 0 unless (defined $pwd and $self->{user});
318         return md5_hex($pwd) eq $self->{user}->passwd;
319 }
320
321 sub currency {              # not really implemented
322         my $self = shift;
323         syslog('LOG_DEBUG', 'OILS: Patron->currency()');
324         return 'USD';
325 }
326
327 sub fee_amount {
328         my $self = shift;
329         syslog('LOG_DEBUG', 'OILS: Patron->fee_amount()');
330     my $user_id = $self->{user}->id;
331
332     my $e = $self->{editor};
333     $e->xact_begin;
334     my $summary = $e->retrieve_money_open_user_summary($user_id);
335     $e->rollback; # xact_rollback + disconnect
336
337     my $total = ($summary) ? $summary->balance_owed : 0;
338         syslog('LOG_INFO', "User ".$self->{id} .":$user_id has a fee amount of \$$total");
339         return $total;
340 }
341
342 sub screen_msg {
343         my $self = shift;
344         my $u = $self->{user};
345
346         return 'barred' if $u->barred eq 't';
347
348         my $b = 'blocked';
349
350         return $b if $u->active eq 'f';
351         return $b if $u->card->active eq 'f';
352
353     # if we have any penalties at this point, they are blocking penalties
354     return $b if $u->standing_penalties and @{$u->standing_penalties};
355
356     # has the patron account expired?
357         my $expire = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($u->expire_date));
358         return $b if CORE::time > $expire->epoch;
359
360         return 'OK';
361 }
362
363 sub print_line {            # not implemented
364     my $self = shift;
365         return '';
366 }
367
368 sub too_many_charged {      # not implemented
369     my $self = shift;
370         return 0;
371 }
372
373 sub too_many_overdue { 
374         my $self = shift;
375     return scalar( # PATRON_EXCEEDS_OVERDUE_COUNT
376         grep { $_->standing_penalty == 2 } @{$self->{user}->standing_penalties}
377     );
378 }
379
380 # not completely sure what this means
381 sub too_many_renewal {
382     my $self = shift;
383     return 0;
384 }
385
386 # not relevant, handled by fines/fees
387 sub too_many_claim_return {
388     my $self = shift;
389     return 0;
390 }
391
392 # not relevant, handled by fines/fees
393 sub too_many_lost {
394     my $self = shift;
395     return 0;
396 }
397
398 sub excessive_fines { 
399     my $self = shift;
400     return scalar( # PATRON_EXCEEDS_FINES
401         grep { $_->standing_penalty == 1 } @{$self->{user}->standing_penalties}
402     );
403 }
404
405 # Until someone suggests otherwise, fees and fines are the same
406
407 sub excessive_fees {
408         my $self = shift;
409     return $self->excessive_fines;
410 }
411
412 # not relevant, handled by fines/fees
413 sub too_many_billed {
414     my $self = shift;
415         return 0;
416 }
417
418
419
420 #
421 # List of outstanding holds placed
422 #
423 sub hold_items {
424     my ($self, $start, $end) = @_;
425         syslog('LOG_DEBUG', 'OILS: Patron->hold_items()');
426
427          my $holds = $self->{editor}->search_action_hold_request(
428                 { usr => $self->{user}->id, fulfillment_time => undef, cancel_time => undef }
429          );
430
431         my @holds;
432         push( @holds, OpenILS::SIP::clean_text($self->__hold_to_title($_)) ) for @$holds;
433
434         return (defined $start and defined $end) ? 
435                 [ $holds[($start-1)..($end-1)] ] : 
436                 \@holds;
437 }
438
439 sub __hold_to_title {
440         my $self = shift;
441         my $hold = shift;
442         my $e = $self->{editor};
443
444         my( $id, $mods, $title, $volume, $copy );
445
446         return __copy_to_title($e, 
447                 $e->retrieve_asset_copy($hold->target)) 
448                 if $hold->hold_type eq 'C';
449
450         return __volume_to_title($e, 
451                 $e->retrieve_asset_call_number($hold->target))
452                 if $hold->hold_type eq 'V';
453
454         return __record_to_title(
455                 $e, $hold->target) if $hold->hold_type eq 'T';
456
457         return __metarecord_to_title(
458                 $e, $hold->target) if $hold->hold_type eq 'M';
459 }
460
461 sub __copy_to_title {
462         my( $e, $copy ) = @_;
463         #syslog('LOG_DEBUG', "OILS: copy_to_title(%s)", $copy->id);
464         return $copy->dummy_title if $copy->call_number == -1;  
465
466         my $vol = (ref $copy->call_number) ?
467                 $copy->call_number :
468                 $e->retrieve_asset_call_number($copy->call_number);
469
470         return __volume_to_title($e, $vol);
471 }
472
473
474 sub __volume_to_title {
475         my( $e, $volume ) = @_;
476         #syslog('LOG_DEBUG', "OILS: volume_to_title(%s)", $volume->id);
477         return __record_to_title($e, $volume->record);
478 }
479
480
481 sub __record_to_title {
482         my( $e, $title_id ) = @_;
483         #syslog('LOG_DEBUG', "OILS: record_to_title($title_id)");
484         my $mods = $U->simplereq(
485                 'open-ils.search',
486                 'open-ils.search.biblio.record.mods_slim.retrieve', $title_id );
487         return ($mods) ? $mods->title : "";
488 }
489
490 sub __metarecord_to_title {
491         my( $e, $m_id ) = @_;
492         #syslog('LOG_DEBUG', "OILS: metarecord_to_title($m_id)");
493         my $mods = $U->simplereq(
494                 'open-ils.search',
495                 'open-ils.search.biblio.metarecord.mods_slim.retrieve', $m_id);
496         return ($U->event_code($mods)) ? "<unknown>" : $mods->title;
497 }
498
499
500 #
501 # remove the hold on item item_id from my hold queue.
502 # return true if I was holding the item, false otherwise.
503
504 sub drop_hold {
505     my ($self, $item_id) = @_;
506     return 0;
507 }
508
509 sub __patron_items_info {
510         my $self = shift;
511         return if $self->{item_info};
512         $self->{item_info} = 
513                 OpenILS::Application::Actor::_checked_out(
514                         0, $self->{editor}, $self->{user}->id);;
515 }
516
517
518
519 sub overdue_items {
520         my ($self, $start, $end) = @_;
521
522         $self->__patron_items_info();
523         my @overdues = @{$self->{item_info}->{overdue}};
524         #$overdues[$_] = __circ_to_title($self->{editor}, $overdues[$_]) for @overdues;
525
526         my @o;
527         syslog('LOG_DEBUG', "OILS: overdue_items() fleshing circs @overdues");
528
529         my $return_datatype = OpenILS::SIP->get_option_value('msg64_summary_datatype') || '';
530         
531         for my $circid (@overdues) {
532                 next unless $circid;
533                 if($return_datatype eq 'barcode') {
534                         push( @o, __circ_to_barcode($self->{editor}, $circid));
535                 } else {
536                         push( @o, OpenILS::SIP::clean_text(__circ_to_title($self->{editor}, $circid)));
537                 }
538         }
539         @overdues = @o;
540
541         return (defined $start and defined $end) ? 
542                 [ $overdues[($start-1)..($end-1)] ] : \@overdues;
543 }
544
545 sub __circ_to_barcode {
546         my ($e, $circ) = @_;
547         return unless $circ;
548         $circ = $e->retrieve_action_circulation($circ);
549         my $copy = $e->retrieve_asset_copy($circ->target_copy);
550         return $copy->barcode;
551 }
552
553 sub __circ_to_title {
554         my( $e, $circ ) = @_;
555         return unless $circ;
556         $circ = $e->retrieve_action_circulation($circ);
557         return __copy_to_title( $e, 
558                 $e->retrieve_asset_copy($circ->target_copy) );
559 }
560
561 sub charged_items {
562         my ($self, $start, $end) = shift;
563
564         $self->__patron_items_info();
565
566         my @charges = (
567                 @{$self->{item_info}->{out}},
568                 @{$self->{item_info}->{overdue}}
569                 );
570
571         #$charges[$_] = __circ_to_title($self->{editor}, $charges[$_]) for @charges;
572
573         my @c;
574         syslog('LOG_DEBUG', "OILS: charged_items() fleshing circs @charges");
575
576         my $return_datatype = OpenILS::SIP->get_option_value('msg64_summary_datatype') || '';
577
578         for my $circid (@charges) {
579                 next unless $circid;
580                 if($return_datatype eq 'barcode') {
581                         push( @c, __circ_to_barcode($self->{editor}, $circid));
582                 } else {
583                         push( @c, OpenILS::SIP::clean_text(__circ_to_title($self->{editor}, $circid)));
584                 }
585         }
586
587         @charges = @c;
588
589         return (defined $start and defined $end) ? 
590                 [ $charges[($start-1)..($end-1)] ] : 
591                 \@charges;
592 }
593
594 sub fine_items {
595         my ($self, $start, $end) = @_;
596         my @fines;
597         syslog('LOG_DEBUG', 'OILS: Patron->fine_items()');
598         return (defined $start and defined $end) ? 
599                 [ $fines[($start-1)..($end-1)] ] : \@fines;
600 }
601
602 # not currently supported
603 sub recall_items {
604     my ($self, $start, $end) = @_;
605     return [];
606 }
607
608 sub unavail_holds {
609      my ($self, $start, $end) = @_;
610      syslog('LOG_DEBUG', 'OILS: Patron->unavail_holds()');
611  
612      my @holds_sip_output = map {
613         OpenILS::SIP::clean_text($self->__hold_to_title($_))
614      } @{
615         $self->{editor}->search_action_hold_request({
616             usr              => $self->{user}->id,
617             fulfillment_time => undef,
618             cancel_time      => undef,
619             shelf_time       => undef
620         })
621      };
622  
623      return (defined $start and defined $end) ?
624          [ @holds_sip_output[($start-1)..($end-1)] ] :
625          \@holds_sip_output;
626 }
627
628 sub block {
629         my ($self, $card_retained, $blocked_card_msg) = @_;
630     $blocked_card_msg ||= '';
631
632     my $e = $self->{editor};
633         my $u = $self->{user};
634
635         syslog('LOG_INFO', "OILS: Blocking user %s", $u->card->barcode );
636
637         return $self if $u->card->active eq 'f';
638
639     $e->xact_begin;    # connect and start a new transaction
640
641         $u->card->active('f');
642         if( ! $e->update_actor_card($u->card) ) {
643                 syslog('LOG_ERR', "OILS: Block card update failed: %s", $e->event->{textcode});
644                 $e->rollback; # rollback + disconnect
645                 return $self;
646         }
647
648         # retrieve the un-fleshed user object for update
649         $u = $e->retrieve_actor_user($u->id);
650         my $note = OpenILS::SIP::clean_text($u->alert_message) || "";
651         $note = "<sip> CARD BLOCKED BY SELF-CHECK MACHINE. $blocked_card_msg</sip>\n$note"; # XXX Config option
652     $note =~ s/\s*$//;  # kill trailng whitespace
653         $u->alert_message($note);
654
655         if( ! $e->update_actor_user($u) ) {
656                 syslog('LOG_ERR', "OILS: Block: patron alert update failed: %s", $e->event->{textcode});
657                 $e->rollback; # rollback + disconnect
658                 return $self;
659         }
660
661         # stay in synch
662         $self->{user}->alert_message( $note );
663
664         $e->commit; # commits and disconnects
665         return $self;
666 }
667
668 # Testing purposes only
669 sub enable {
670     my ($self, $card_retained) = @_;
671     $self->{screen_msg} = "All privileges restored.";
672
673     # Un-mark card as inactive, grep out the patron alert
674     my $e = $self->{editor};
675     my $u = $self->{user};
676
677     syslog('LOG_INFO', "OILS: Unblocking user %s", $u->card->barcode );
678
679     return $self if $u->card->active eq 't';
680
681     $e->xact_begin;    # connect and start a new transaction
682
683     $u->card->active('t');
684     if( ! $e->update_actor_card($u->card) ) {
685         syslog('LOG_ERR', "OILS: Unblock card update failed: %s", $e->event->{textcode});
686         $e->rollback; # rollback + disconnect
687         return $self;
688     }
689
690     # retrieve the un-fleshed user object for update
691     $u = $e->retrieve_actor_user($u->id);
692     my $note = OpenILS::SIP::clean_text($u->alert_message) || "";
693     $note =~ s#<sip>.*</sip>##;
694     $note =~ s/^\s*//;  # kill leading whitespace
695     $note =~ s/\s*$//;  # kill trailng whitespace
696     $u->alert_message($note);
697
698     if( ! $e->update_actor_user($u) ) {
699         syslog('LOG_ERR', "OILS: Unblock: patron alert update failed: %s", $e->event->{textcode});
700         $e->rollback; # rollback + disconnect
701         return $self;
702     }
703
704     # stay in synch
705     $self->{user}->alert_message( $note );
706
707     $e->commit; # commits and disconnects
708     return $self;
709 }
710
711 #
712 # Messages
713 #
714
715 sub invalid_patron {
716     return "Please contact library staff";
717 }
718
719 sub charge_denied {
720     return "Please contact library staff";
721 }
722
723 sub inet_privileges {
724     my( $self ) = @_;
725     my $e = OpenILS::SIP->editor();
726     $INET_PRIVS = $e->retrieve_all_config_net_access_level() unless $INET_PRIVS;
727     my ($level) = grep { $_->id eq $self->{user}->net_access_level } @$INET_PRIVS;
728     my $name = OpenILS::SIP::clean_text($level->name);
729     syslog('LOG_DEBUG', "OILS: Patron inet_privs = $name");
730     return $name;
731 }
732
733 sub extra_fields {
734     my( $self ) = @_;
735     my $extra_fields = {};
736         my $u = $self->{user};
737     foreach my $stat_cat_entry (@{$u->stat_cat_entries}) {
738         my $stat_cat = $stat_cat_entry->stat_cat;
739         next unless ($stat_cat->sip_field);
740         my $value = $stat_cat_entry->stat_cat_entry;
741         if(defined $stat_cat->sip_format && length($stat_cat->sip_format) > 0) { # Has a format string?
742             if($stat_cat->sip_format =~ /^\|(.*)\|$/) { # Regex match?
743                 if($value =~ /($1)/) { # If we have a match
744                     if(defined $2) { # Check to see if they embedded a capture group
745                         $value = $2; # If so, use it
746                     }
747                     else { # No embedded capture group?
748                         $value = $1; # Use our outer one
749                     }
750                 }
751                 else { # No match?
752                     $value = ''; # Empty string. Will be checked for below.
753                 }
754             }
755             else { # Not a regex match - Try sprintf match (looking for a %s, if any)
756                 $value = sprintf($stat_cat->sip_format, $value);
757             }
758         }
759         next unless length($value) > 0; # No value = no export
760         $value =~ s/\|//g; # Remove all lingering pipe chars for sane output purposes
761         $extra_fields->{ $stat_cat->sip_field } = [] unless (defined $extra_fields->{$stat_cat->sip_field});
762         push(@{$extra_fields->{ $stat_cat->sip_field}}, $value);
763     }
764     return $extra_fields;
765 }
766
767 1;