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