]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/SIP/Patron.pm
Merge branch 'master' of git+ssh://yeti.esilibrary.com/home/evergreen/evergreen-equin...
[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             ],
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 ptype {
244     my $self = shift;
245
246         my $use_code = OpenILS::SIP->get_option_value('patron_type_uses_code') || '';
247
248     # should we use the no_i18n version of patron profile name (as a 'code')?
249     return $self->{editor}->retrieve_permission_grp_tree(
250         [$self->{user}->profile->id, {no_i18n => 1}])->name
251         if $use_code =~ /true/io;
252
253     return OpenILS::SIP::clean_text($self->{user}->profile->name);
254 }
255
256 sub language {
257     my $self = shift;
258     return '000'; # Unspecified
259 }
260
261 # How much more detail do we need to check here?
262 sub charge_ok {
263     my $self = shift;
264     my $u = $self->{user};
265     return (($u->barred eq 'f') and ($u->card->active eq 't'));
266 }
267
268 # How much more detail do we need to check here?
269 sub renew_ok {
270     my $self = shift;
271     return $self->charge_ok;
272 }
273
274 sub recall_ok {
275     my $self = shift;
276     return 0;
277 }
278
279 sub hold_ok {
280     my $self = shift;
281     return $self->charge_ok;
282 }
283
284 # return true if the card provided is marked as lost
285 sub card_lost {
286     my $self = shift;
287     return $self->{user}->card->active eq 'f';
288 }
289
290 sub recall_overdue {        # not implemented
291     my $self = shift;
292     return 0;
293 }
294
295 sub check_password {
296         my ($self, $pwd) = @_;
297         syslog('LOG_DEBUG', 'OILS: Patron->check_password()');
298     return 0 unless (defined $pwd and $self->{user});
299         return md5_hex($pwd) eq $self->{user}->passwd;
300 }
301
302 sub currency {              # not really implemented
303         my $self = shift;
304         syslog('LOG_DEBUG', 'OILS: Patron->currency()');
305         return 'USD';
306 }
307
308 sub fee_amount {
309         my $self = shift;
310         syslog('LOG_DEBUG', 'OILS: Patron->fee_amount()');
311     my $user_id = $self->{user}->id;
312
313     my $e = $self->{editor};
314     $e->xact_begin;
315     my $summary = $e->retrieve_money_open_user_summary($user_id);
316     $e->rollback; # xact_rollback + disconnect
317
318     my $total = ($summary) ? $summary->balance_owed : 0;
319         syslog('LOG_INFO', "User ".$self->{id} .":$user_id has a fee amount of \$$total");
320         return $total;
321 }
322
323 sub screen_msg {
324         my $self = shift;
325         my $u = $self->{user};
326
327         return 'barred' if $u->barred eq 't';
328
329         my $b = 'blocked';
330
331         return $b if $u->active eq 'f';
332         return $b if $u->card->active eq 'f';
333
334     # if we have any penalties at this point, they are blocking penalties
335     return $b if $u->standing_penalties and @{$u->standing_penalties};
336
337     # has the patron account expired?
338         my $expire = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($u->expire_date));
339         return $b if CORE::time > $expire->epoch;
340
341         return 'OK';
342 }
343
344 sub print_line {            # not implemented
345     my $self = shift;
346         return '';
347 }
348
349 sub too_many_charged {      # not implemented
350     my $self = shift;
351         return 0;
352 }
353
354 sub too_many_overdue { 
355         my $self = shift;
356     return scalar( # PATRON_EXCEEDS_OVERDUE_COUNT
357         grep { $_->standing_penalty == 2 } @{$self->{user}->standing_penalties}
358     );
359 }
360
361 # not completely sure what this means
362 sub too_many_renewal {
363     my $self = shift;
364     return 0;
365 }
366
367 # not relevant, handled by fines/fees
368 sub too_many_claim_return {
369     my $self = shift;
370     return 0;
371 }
372
373 # not relevant, handled by fines/fees
374 sub too_many_lost {
375     my $self = shift;
376     return 0;
377 }
378
379 sub excessive_fines { 
380     my $self = shift;
381     return scalar( # PATRON_EXCEEDS_FINES
382         grep { $_->standing_penalty == 1 } @{$self->{user}->standing_penalties}
383     );
384 }
385
386 # Until someone suggests otherwise, fees and fines are the same
387
388 sub excessive_fees {
389         my $self = shift;
390     return $self->excessive_fines;
391 }
392
393 # not relevant, handled by fines/fees
394 sub too_many_billed {
395     my $self = shift;
396         return 0;
397 }
398
399
400
401 #
402 # List of outstanding holds placed
403 #
404 sub hold_items {
405     my ($self, $start, $end) = @_;
406         syslog('LOG_DEBUG', 'OILS: Patron->hold_items()');
407
408          my $holds = $self->{editor}->search_action_hold_request(
409                 { usr => $self->{user}->id, fulfillment_time => undef, cancel_time => undef }
410          );
411
412         my @holds;
413         push( @holds, OpenILS::SIP::clean_text($self->__hold_to_title($_)) ) for @$holds;
414
415         return (defined $start and defined $end) ? 
416                 [ $holds[($start-1)..($end-1)] ] : 
417                 \@holds;
418 }
419
420 sub __hold_to_title {
421         my $self = shift;
422         my $hold = shift;
423         my $e = $self->{editor};
424
425         my( $id, $mods, $title, $volume, $copy );
426
427         return __copy_to_title($e, 
428                 $e->retrieve_asset_copy($hold->target)) 
429                 if $hold->hold_type eq 'C';
430
431         return __volume_to_title($e, 
432                 $e->retrieve_asset_call_number($hold->target))
433                 if $hold->hold_type eq 'V';
434
435         return __record_to_title(
436                 $e, $hold->target) if $hold->hold_type eq 'T';
437
438         return __metarecord_to_title(
439                 $e, $hold->target) if $hold->hold_type eq 'M';
440 }
441
442 sub __copy_to_title {
443         my( $e, $copy ) = @_;
444         #syslog('LOG_DEBUG', "OILS: copy_to_title(%s)", $copy->id);
445         return $copy->dummy_title if $copy->call_number == -1;  
446
447         my $vol = (ref $copy->call_number) ?
448                 $copy->call_number :
449                 $e->retrieve_asset_call_number($copy->call_number);
450
451         return __volume_to_title($e, $vol);
452 }
453
454
455 sub __volume_to_title {
456         my( $e, $volume ) = @_;
457         #syslog('LOG_DEBUG', "OILS: volume_to_title(%s)", $volume->id);
458         return __record_to_title($e, $volume->record);
459 }
460
461
462 sub __record_to_title {
463         my( $e, $title_id ) = @_;
464         #syslog('LOG_DEBUG', "OILS: record_to_title($title_id)");
465         my $mods = $U->simplereq(
466                 'open-ils.search',
467                 'open-ils.search.biblio.record.mods_slim.retrieve', $title_id );
468         return ($mods) ? $mods->title : "";
469 }
470
471 sub __metarecord_to_title {
472         my( $e, $m_id ) = @_;
473         #syslog('LOG_DEBUG', "OILS: metarecord_to_title($m_id)");
474         my $mods = $U->simplereq(
475                 'open-ils.search',
476                 'open-ils.search.biblio.metarecord.mods_slim.retrieve', $m_id);
477         return ($U->event_code($mods)) ? "<unknown>" : $mods->title;
478 }
479
480
481 #
482 # remove the hold on item item_id from my hold queue.
483 # return true if I was holding the item, false otherwise.
484
485 sub drop_hold {
486     my ($self, $item_id) = @_;
487     return 0;
488 }
489
490 sub __patron_items_info {
491         my $self = shift;
492         return if $self->{item_info};
493         $self->{item_info} = 
494                 OpenILS::Application::Actor::_checked_out(
495                         0, $self->{editor}, $self->{user}->id);;
496 }
497
498
499
500 sub overdue_items {
501         my ($self, $start, $end) = @_;
502
503         $self->__patron_items_info();
504         my @overdues = @{$self->{item_info}->{overdue}};
505         #$overdues[$_] = __circ_to_title($self->{editor}, $overdues[$_]) for @overdues;
506
507         my @o;
508         syslog('LOG_DEBUG', "OILS: overdue_items() fleshing circs @overdues");
509
510         my $return_datatype = OpenILS::SIP->get_option_value('msg64_summary_datatype') || '';
511         
512         for my $circid (@overdues) {
513                 next unless $circid;
514                 if($return_datatype eq 'barcode') {
515                         push( @o, __circ_to_barcode($self->{editor}, $circid));
516                 } else {
517                         push( @o, OpenILS::SIP::clean_text(__circ_to_title($self->{editor}, $circid)));
518                 }
519         }
520         @overdues = @o;
521
522         return (defined $start and defined $end) ? 
523                 [ $overdues[($start-1)..($end-1)] ] : \@overdues;
524 }
525
526 sub __circ_to_barcode {
527         my ($e, $circ) = @_;
528         return unless $circ;
529         $circ = $e->retrieve_action_circulation($circ);
530         my $copy = $e->retrieve_asset_copy($circ->target_copy);
531         return $copy->barcode;
532 }
533
534 sub __circ_to_title {
535         my( $e, $circ ) = @_;
536         return unless $circ;
537         $circ = $e->retrieve_action_circulation($circ);
538         return __copy_to_title( $e, 
539                 $e->retrieve_asset_copy($circ->target_copy) );
540 }
541
542 sub charged_items {
543         my ($self, $start, $end) = shift;
544
545         $self->__patron_items_info();
546
547         my @charges = (
548                 @{$self->{item_info}->{out}},
549                 @{$self->{item_info}->{overdue}}
550                 );
551
552         #$charges[$_] = __circ_to_title($self->{editor}, $charges[$_]) for @charges;
553
554         my @c;
555         syslog('LOG_DEBUG', "OILS: charged_items() fleshing circs @charges");
556
557         my $return_datatype = OpenILS::SIP->get_option_value('msg64_summary_datatype') || '';
558
559         for my $circid (@charges) {
560                 next unless $circid;
561                 if($return_datatype eq 'barcode') {
562                         push( @c, __circ_to_barcode($self->{editor}, $circid));
563                 } else {
564                         push( @c, OpenILS::SIP::clean_text(__circ_to_title($self->{editor}, $circid)));
565                 }
566         }
567
568         @charges = @c;
569
570         return (defined $start and defined $end) ? 
571                 [ $charges[($start-1)..($end-1)] ] : 
572                 \@charges;
573 }
574
575 sub fine_items {
576         my ($self, $start, $end) = @_;
577         my @fines;
578         syslog('LOG_DEBUG', 'OILS: Patron->fine_items()');
579         return (defined $start and defined $end) ? 
580                 [ $fines[($start-1)..($end-1)] ] : \@fines;
581 }
582
583 # not currently supported
584 sub recall_items {
585     my ($self, $start, $end) = @_;
586     return [];
587 }
588
589 sub unavail_holds {
590         my ($self, $start, $end) = @_;
591         my @holds;
592         syslog('LOG_DEBUG', 'OILS: Patron->unavail_holds()');
593         return (defined $start and defined $end) ? 
594                 [ $holds[($start-1)..($end-1)] ] : \@holds;
595 }
596
597 sub block {
598         my ($self, $card_retained, $blocked_card_msg) = @_;
599     $blocked_card_msg ||= '';
600
601     my $e = $self->{editor};
602         my $u = $self->{user};
603
604         syslog('LOG_INFO', "OILS: Blocking user %s", $u->card->barcode );
605
606         return $self if $u->card->active eq 'f';
607
608     $e->xact_begin;    # connect and start a new transaction
609
610         $u->card->active('f');
611         if( ! $e->update_actor_card($u->card) ) {
612                 syslog('LOG_ERR', "OILS: Block card update failed: %s", $e->event->{textcode});
613                 $e->rollback; # rollback + disconnect
614                 return $self;
615         }
616
617         # retrieve the un-fleshed user object for update
618         $u = $e->retrieve_actor_user($u->id);
619         my $note = OpenILS::SIP::clean_text($u->alert_message) || "";
620         $note = "<sip> CARD BLOCKED BY SELF-CHECK MACHINE. $blocked_card_msg</sip>\n$note"; # XXX Config option
621     $note =~ s/\s*$//;  # kill trailng whitespace
622         $u->alert_message($note);
623
624         if( ! $e->update_actor_user($u) ) {
625                 syslog('LOG_ERR', "OILS: Block: patron alert update failed: %s", $e->event->{textcode});
626                 $e->rollback; # rollback + disconnect
627                 return $self;
628         }
629
630         # stay in synch
631         $self->{user}->alert_message( $note );
632
633         $e->commit; # commits and disconnects
634         return $self;
635 }
636
637 # Testing purposes only
638 sub enable {
639     my ($self, $card_retained) = @_;
640     $self->{screen_msg} = "All privileges restored.";
641
642     # Un-mark card as inactive, grep out the patron alert
643     my $e = $self->{editor};
644     my $u = $self->{user};
645
646     syslog('LOG_INFO', "OILS: Unblocking user %s", $u->card->barcode );
647
648     return $self if $u->card->active eq 't';
649
650     $e->xact_begin;    # connect and start a new transaction
651
652     $u->card->active('t');
653     if( ! $e->update_actor_card($u->card) ) {
654         syslog('LOG_ERR', "OILS: Unblock card update failed: %s", $e->event->{textcode});
655         $e->rollback; # rollback + disconnect
656         return $self;
657     }
658
659     # retrieve the un-fleshed user object for update
660     $u = $e->retrieve_actor_user($u->id);
661     my $note = OpenILS::SIP::clean_text($u->alert_message) || "";
662     $note =~ s#<sip>.*</sip>##;
663     $note =~ s/^\s*//;  # kill leading whitespace
664     $note =~ s/\s*$//;  # kill trailng whitespace
665     $u->alert_message($note);
666
667     if( ! $e->update_actor_user($u) ) {
668         syslog('LOG_ERR', "OILS: Unblock: patron alert update failed: %s", $e->event->{textcode});
669         $e->rollback; # rollback + disconnect
670         return $self;
671     }
672
673     # stay in synch
674     $self->{user}->alert_message( $note );
675
676     $e->commit; # commits and disconnects
677     return $self;
678 }
679
680 #
681 # Messages
682 #
683
684 sub invalid_patron {
685     return "Please contact library staff";
686 }
687
688 sub charge_denied {
689     return "Please contact library staff";
690 }
691
692 sub inet_privileges {
693     my( $self ) = @_;
694     my $e = OpenILS::SIP->editor();
695     $INET_PRIVS = $e->retrieve_all_config_net_access_level() unless $INET_PRIVS;
696     my ($level) = grep { $_->id eq $self->{user}->net_access_level } @$INET_PRIVS;
697     my $name = OpenILS::SIP::clean_text($level->name);
698     syslog('LOG_DEBUG', "OILS: Patron inet_privs = $name");
699     return $name;
700 }
701
702
703 1;