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