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