3 # A Class for hiding the ILS's concept of the patron from the OpenSIP
7 package OpenILS::SIP::Patron;
13 use Sys::Syslog qw(syslog);
15 use Digest::MD5 qw(md5_hex);
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';
24 our (@ISA, @EXPORT_OK);
28 @EXPORT_OK = qw(invalid_patron);
35 my $patron_id = shift;
38 if ($key ne 'usr' and $key ne 'barcode') {
39 syslog("LOG_ERROR", "Patron (card) lookup requested by illegeal key '$key'");
43 unless(defined $patron_id) {
44 syslog("LOG_WARNING", "No patron ID provided to ILS::Patron->new");
48 my $type = ref($class) || $class;
49 my $self = bless({}, $type);
51 syslog("LOG_DEBUG", "OILS: new OpenILS Patron(%s => %s): searching...", $key, $patron_id);
53 my $e = OpenILS::SIP->editor();
72 # in some cases, we don't need all of this data. Only fetch the user + barcode
73 $usr_flesh = {flesh => 1, flesh_fields => {au => ['card']}} if $args{slim_user};
76 if($key eq 'barcode') { # retrieve user by barcode
78 $$usr_flesh{flesh} += 1;
79 $$usr_flesh{flesh_fields}{ac} = ['usr'];
81 my $card = $e->search_actor_card([{barcode => $patron_id}, $usr_flesh])->[0];
83 if(!$card or !$U->is_true($card->active)) {
84 syslog("LOG_WARNING", "No such patron barcode: $patron_id");
91 $user = $e->retrieve_actor_user([$patron_id, $usr_flesh]);
94 if(!$user or $U->is_true($user->deleted)) {
95 syslog("LOG_WARNING", "OILS: Unable to find patron %s => %s", $key, $patron_id);
99 if(!$U->is_true($user->active)) {
100 syslog("LOG_WARNING", "OILS: Patron is inactive %s => %s", $key, $patron_id);
104 # now grab the user's penalties
106 $self->flesh_user_penalties($user, $e) unless $args{slim_user};
108 $self->{authtoken} = $args{authtoken} if $args{authtoken};
109 $self->{editor} = $e;
110 $self->{user} = $user;
111 $self->{id} = ($key eq 'barcode') ? $patron_id : $user->card->barcode; # The barcode IS the ID to SIP.
112 # We give back the passed barcode if the key was indeed a barcode, just to be safe. Otherwise pull it from the card.
114 syslog("LOG_DEBUG", "OILS: new OpenILS Patron(%s => %s): found patron : barred=%s, card:active=%s",
115 $key, $patron_id, $user->barred, $user->card->active );
117 $U->log_user_activity($user->id, $self->get_act_who, 'verify');
124 my $config = OpenILS::SIP->config();
125 my $login = OpenILS::SIP->login_account();
127 my $act_who = $config->{implementation_config}->{default_activity_who};
128 my $force_who = $config->{implementation_config}->{force_activity_who};
130 # 1. future: test sip extension for caller-provided ewho and !$force_who
132 # 2. See if the login is tagged with an ewho
133 return $login->{activity_who} if $login->{activity_who};
135 # 3. if all else fails, see if there is an institution-wide ewho
136 return $config->{activity_who} if $config->{activity_who};
141 # grab patron penalties. Only grab non-archived penalties that are for fines,
142 # excessive overdues, or otherwise block circluation activity
143 sub flesh_user_penalties {
144 my ($self, $user, $e) = @_;
146 $user->standing_penalties(
147 $e->search_actor_user_standing_penalty([
152 # ignore "archived" penalties
153 {stop_date => undef},
154 {stop_date => {'>' => 'now'}}
162 transform => 'actor.org_unit_ancestors',
168 # at this point, there is no concept of "here", so fetch penalties
169 # for the patron's home lib plus ancestors
170 where => {id => $user->home_ou},
175 # in addition to fines and excessive overdue penalties,
176 # we only care about penalties that result in blocks
177 standing_penalty => {
179 select => {csp => ['id']},
183 {id => [1,2]}, # fines / overdues
184 {block_list => {'!=' => undef}}
201 return format_name($self->{user});
206 return OpenILS::SIP::clean_text(
208 ($u->first_given_name || ''),
209 ($u->second_given_name || ''),
210 ($u->family_name || '')));
215 my $lib = OpenILS::SIP::shortname_from_id($self->{user}->home_ou);
216 syslog('LOG_DEBUG', "OILS: Patron->home_library() = $lib");
222 return "" unless $addr;
223 my $return = OpenILS::SIP::clean_text(
224 join( ' ', map {$_ || ''} (
235 $return =~ s/\s+/ /sg; # Compress any run of of whitespace to one space
241 return $self->{user}->id;
246 my $u = $self->{user};
247 my $str = __addr_string($u->billing_address || $u->mailing_address);
248 syslog('LOG_DEBUG', "OILS: Patron address: $str");
254 return OpenILS::SIP::clean_text($self->{user}->email);
259 return $self->{user}->day_phone;
264 my $dob = OpenILS::SIP->format_date($self->{user}->dob);
265 syslog('LOG_DEBUG', "OILS: Patron DOB = $dob");
271 my $expire = OpenILS::SIP->format_date($self->{user}->expire_date);
272 syslog('LOG_DEBUG', "OILS: Patron Expire = $expire");
279 my $use_code = OpenILS::SIP->get_option_value('patron_type_uses_code') || '';
281 # should we use the no_i18n version of patron profile name (as a 'code')?
282 return $self->{editor}->retrieve_permission_grp_tree(
283 [$self->{user}->profile->id, {no_i18n => 1}])->name
284 if $use_code =~ /true/io;
286 return OpenILS::SIP::clean_text($self->{user}->profile->name);
291 return '000'; # Unspecified
294 # How much more detail do we need to check here?
295 # sec: adding logic to return false if user is barred, has a circulation block
299 my $u = $self->{user};
301 # compute expiration date for borrowing privileges
302 my $expire = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($u->expire_date));
304 # determine whether patron should be allowed to circulate materials:
305 # not barred, doesn't owe too much wrt fines/fees, privileges haven't
307 my $circ_is_blocked =
308 (($u->barred eq 't') or
309 ($u->standing_penalties and @{$u->standing_penalties}) or
310 (CORE::time > $expire->epoch));
313 !$circ_is_blocked and
314 $u->active eq 't' and
315 $u->card->active eq 't';
320 # How much more detail do we need to check here?
323 return $self->charge_ok;
328 return $self->charge_ok if
329 OpenILS::SIP->get_option_value('patron_calculate_recal_ok');
335 return $self->charge_ok;
338 # return true if the card provided is marked as lost
341 return $self->{user}->card->active eq 'f';
344 sub recall_overdue { # not implemented
350 my ($self, $pwd) = @_;
351 syslog('LOG_DEBUG', 'OILS: Patron->check_password()');
352 return 0 unless (defined $pwd and $self->{user});
353 return md5_hex($pwd) eq $self->{user}->passwd;
356 sub currency { # not really implemented
358 syslog('LOG_DEBUG', 'OILS: Patron->currency()');
364 syslog('LOG_DEBUG', 'OILS: Patron->fee_amount()');
365 my $user_id = $self->{user}->id;
367 my $e = $self->{editor};
369 my $summary = $e->retrieve_money_open_user_summary($user_id);
370 $e->rollback; # xact_rollback + disconnect
372 my $total = ($summary) ? $summary->balance_owed : 0;
373 syslog('LOG_INFO', "User ".$self->{id} .":$user_id has a fee amount of \$$total");
379 my $u = $self->{user};
381 return 'barred' if $u->barred eq 't';
385 return $b if $u->active eq 'f';
386 return $b if $u->card->active eq 'f';
388 # if we have any penalties at this point, they are blocking penalties
389 return $b if $u->standing_penalties and @{$u->standing_penalties};
391 # has the patron account expired?
392 my $expire = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($u->expire_date));
393 return $b if CORE::time > $expire->epoch;
398 sub print_line { # not implemented
403 sub too_many_charged { # not implemented
408 sub too_many_overdue {
410 return scalar( # PATRON_EXCEEDS_OVERDUE_COUNT
411 grep { $_->standing_penalty == 2 } @{$self->{user}->standing_penalties}
415 # not completely sure what this means
416 sub too_many_renewal {
421 # not relevant, handled by fines/fees
422 sub too_many_claim_return {
427 # not relevant, handled by fines/fees
433 sub excessive_fines {
435 return scalar( # PATRON_EXCEEDS_FINES
436 grep { $_->standing_penalty == 1 } @{$self->{user}->standing_penalties}
440 # Until someone suggests otherwise, fees and fines are the same
444 return $self->excessive_fines;
447 # not relevant, handled by fines/fees
448 sub too_many_billed {
456 # List of outstanding holds placed
459 my ($self, $start, $end, $ids_only) = @_;
460 syslog('LOG_DEBUG', 'OILS: Patron->hold_items()');
463 # all of my open holds
464 my $holds = $self->{editor}->search_action_hold_request({
465 usr => $self->{user}->id,
466 fulfillment_time => undef,
470 return $holds if $ids_only;
471 return $self->__format_holds($holds, $start, $end);
475 my ($self, $start, $end, $ids_only) = @_;
476 syslog('LOG_DEBUG', 'OILS: Patron->unavail_holds()');
478 my $holds = $self->{editor}->search_action_hold_request({
479 usr => $self->{user}->id,
480 fulfillment_time => undef,
481 cancel_time => undef,
483 {current_shelf_lib => undef},
484 {current_shelf_lib => {'!=' => {'+ahr' => 'pickup_lib'}}}
488 return $holds if $ids_only;
489 return $self->__format_holds($holds, $start, $end);
495 my ($self, $holds, $start, $end) = @_;
497 return [] unless @$holds;
499 my $return_datatype =
500 OpenILS::SIP->get_option_value('msg64_hold_datatype') || '';
504 for my $hold (@$holds) {
506 if ($return_datatype eq 'barcode') {
508 if (my $copy = $self->find_copy_for_hold($hold)) {
509 push(@response, $copy->barcode);
512 syslog('LOG_WARNING',
513 'OILS: No representative copy found for hold ' . $hold->id);
518 OpenILS::SIP::clean_text($self->__hold_to_title($hold)));
522 return (defined $start and defined $end) ?
523 [ @response[($start-1)..($end-1)] ] :
527 # Finds a representative copy for the given hold.
528 # If no copy exists at all, undef is returned.
529 # The only limit placed on what constitutes a
530 # "representative" copy is that it cannot be deleted.
531 # Otherwise, any copy that allows us to find the hold
532 # later is good enough.
533 sub find_copy_for_hold {
534 my ($self, $hold) = @_;
535 my $e = $self->{editor};
537 return $e->retrieve_asset_copy($hold->current_copy)
538 if $hold->current_copy;
540 return $e->retrieve_asset_copy($hold->target)
541 if $hold->hold_type =~ /C|R|F/;
543 return $e->search_asset_copy([
544 {call_number => $hold->target, deleted => 'f'},
545 {limit => 1}])->[0] if $hold->hold_type eq 'V';
547 my $bre_ids = [$hold->target];
549 if ($hold->hold_type eq 'M') {
550 # find all of the bibs that link to the target metarecord
551 my $maps = $e->search_metabib_metarecord_source_map(
552 {metarecord => $hold->target});
553 $bre_ids = [map {$_->record} @$maps];
556 my $vol_ids = $e->search_asset_call_number(
557 {record => $bre_ids, deleted => 'f'},
561 return $e->search_asset_copy([
562 {call_number => $vol_ids, deleted => 'f'},
567 # Given a "representative" copy, finds a matching hold
568 sub find_hold_from_copy {
569 my ($self, $barcode) = @_;
570 my $e = $self->{editor};
573 my $copy = $e->search_asset_copy([
574 {barcode => $barcode, deleted => 'f'},
575 {flesh => 1, flesh_fields => {acp => ['call_number']}}
578 return undef unless $copy;
580 my $run_hold_query = sub {
582 return $e->search_action_hold_request([
583 { usr => $self->{user}->id,
584 cancel_time => undef,
585 fulfillment_time => undef,
589 order_by => {ahr => 'request_time DESC'}
594 # first see if there is a match on current_copy
595 return $hold if $hold =
596 $run_hold_query->(current_copy => $copy->id);
598 # next, assume bib-level holds are the most common
599 return $hold if $hold = $run_hold_query->(
600 target => $copy->call_number->record, hold_type => 'T');
602 # next try metarecord holds
603 my $map = $e->search_metabib_metarecord_source_map(
604 {source => $copy->call_number->record})->[0];
606 return $hold if $hold = $run_hold_query->(
607 target => $map->metarecord, hold_type => 'M');
610 return $hold if $hold = $run_hold_query->(
611 target => $copy->call_number->id, hold_type => 'V');
614 return $run_hold_query->(
615 target => $copy->id, hold_type => ['C', 'F', 'R']);
618 sub __hold_to_title {
621 my $e = $self->{editor};
623 my( $id, $mods, $title, $volume, $copy );
625 return __copy_to_title($e,
626 $e->retrieve_asset_copy($hold->target))
627 if $hold->hold_type eq 'C' or $hold->hold_type eq 'F' or $hold->hold_type eq 'R';
629 return __volume_to_title($e,
630 $e->retrieve_asset_call_number($hold->target))
631 if $hold->hold_type eq 'V';
633 return __record_to_title(
634 $e, $hold->target) if $hold->hold_type eq 'T';
636 return __metarecord_to_title(
637 $e, $hold->target) if $hold->hold_type eq 'M';
640 sub __copy_to_title {
641 my( $e, $copy ) = @_;
642 #syslog('LOG_DEBUG', "OILS: copy_to_title(%s)", $copy->id);
643 return $copy->dummy_title if $copy->call_number == -1;
645 my $vol = (ref $copy->call_number) ?
647 $e->retrieve_asset_call_number($copy->call_number);
649 return __volume_to_title($e, $vol);
653 sub __volume_to_title {
654 my( $e, $volume ) = @_;
655 #syslog('LOG_DEBUG', "OILS: volume_to_title(%s)", $volume->id);
656 return __record_to_title($e, $volume->record);
660 sub __record_to_title {
661 my( $e, $title_id ) = @_;
662 #syslog('LOG_DEBUG', "OILS: record_to_title($title_id)");
663 my $mods = $U->simplereq(
665 'open-ils.search.biblio.record.mods_slim.retrieve', $title_id );
666 return ($mods) ? $mods->title : "";
669 sub __metarecord_to_title {
670 my( $e, $m_id ) = @_;
671 #syslog('LOG_DEBUG', "OILS: metarecord_to_title($m_id)");
672 my $mods = $U->simplereq(
674 'open-ils.search.biblio.metarecord.mods_slim.retrieve', $m_id);
675 return ($U->event_code($mods)) ? "<unknown>" : $mods->title;
680 # remove the hold on item item_id from my hold queue.
681 # return true if I was holding the item, false otherwise.
684 my ($self, $item_id) = @_;
688 sub __patron_items_info {
690 return if $self->{item_info};
692 OpenILS::Application::Actor::_checked_out(
693 0, $self->{editor}, $self->{user}->id);;
699 my ($self, $start, $end, $ids_only) = @_;
701 $self->__patron_items_info();
702 my @overdues = @{$self->{item_info}->{overdue}};
703 #$overdues[$_] = __circ_to_title($self->{editor}, $overdues[$_]) for @overdues;
705 return \@overdues if $ids_only;
708 syslog('LOG_DEBUG', "OILS: overdue_items() fleshing circs @overdues");
710 my $return_datatype = OpenILS::SIP->get_option_value('msg64_summary_datatype') || '';
712 for my $circid (@overdues) {
714 if($return_datatype eq 'barcode') {
715 push( @o, __circ_to_barcode($self->{editor}, $circid));
717 push( @o, OpenILS::SIP::clean_text(__circ_to_title($self->{editor}, $circid)));
722 return (defined $start and defined $end) ?
723 [ @overdues[($start-1)..($end-1)] ] : \@overdues;
726 sub __circ_to_barcode {
729 $circ = $e->retrieve_action_circulation($circ);
730 my $copy = $e->retrieve_asset_copy($circ->target_copy);
731 return $copy->barcode;
734 sub __circ_to_title {
735 my( $e, $circ ) = @_;
737 $circ = $e->retrieve_action_circulation($circ);
738 return __copy_to_title( $e,
739 $e->retrieve_asset_copy($circ->target_copy) );
743 my ($self, $start, $end, $ids_only) = shift;
744 return $self->charged_items_impl($start, $end, undef, $ids_only);
747 # implementation method
748 # force_bc -- return barcode data regardless of msg64_summary_datatype;
749 # this is used by the renew-all code
750 sub charged_items_impl {
751 my ($self, $start, $end, $force_bc, $ids_only) = shift;
753 $self->__patron_items_info();
756 @{$self->{item_info}->{out}},
757 @{$self->{item_info}->{overdue}}
760 #$charges[$_] = __circ_to_title($self->{editor}, $charges[$_]) for @charges;
762 return \@charges if $ids_only;
765 syslog('LOG_DEBUG', "OILS: charged_items() fleshing circs @charges");
767 my $return_datatype = OpenILS::SIP->get_option_value('msg64_summary_datatype') || '';
769 for my $circid (@charges) {
771 if($return_datatype eq 'barcode' or $force_bc) {
772 push( @c, __circ_to_barcode($self->{editor}, $circid));
774 push( @c, OpenILS::SIP::clean_text(__circ_to_title($self->{editor}, $circid)));
780 return (defined $start and defined $end) ?
781 [ @charges[($start-1)..($end-1)] ] :
786 my ($self, $start, $end, $ids_only) = @_;
789 my $xacts = $U->simplereq('open-ils.actor', 'open-ils.actor.user.transactions.history.have_balance', $self->{authtoken}, $self->{user}->id);
790 foreach my $xact (@{$xacts}) {
795 my $line = $xact->balance_owed . " " . $xact->last_billing_type . " ";
796 if ($xact->xact_type eq 'circulation') {
797 my $mods = $U->simplereq('open-ils.circ', 'open-ils.circ.circ_transaction.find_title', $self->{authtoken}, $xact->id);
798 $line .= $mods->title . ' / ' . $mods->author;
800 $line .= $xact->last_billing_note;
802 push @fines, OpenILS::SIP::clean_text($line);
805 my $log_status = $@ ? 'ERROR: ' . $@ : 'OK';
806 syslog('LOG_DEBUG', 'OILS: Patron->fine_items() ' . $log_status);
807 return (defined $start and defined $end) ?
808 [ @fines[($start-1)..($end-1)] ] : \@fines;
811 # not currently supported
813 my ($self, $start, $end, $ids_only) = @_;
818 my ($self, $card_retained, $blocked_card_msg) = @_;
819 $blocked_card_msg ||= '';
821 my $e = $self->{editor};
822 my $u = $self->{user};
824 syslog('LOG_INFO', "OILS: Blocking user %s", $u->card->barcode );
826 return $self if $u->card->active eq 'f';
828 $e->xact_begin; # connect and start a new transaction
830 $u->card->active('f');
831 if( ! $e->update_actor_card($u->card) ) {
832 syslog('LOG_ERR', "OILS: Block card update failed: %s", $e->event->{textcode});
833 $e->rollback; # rollback + disconnect
837 # retrieve the un-fleshed user object for update
838 $u = $e->retrieve_actor_user($u->id);
839 my $note = OpenILS::SIP::clean_text($u->alert_message) || "";
840 $note = "<sip> CARD BLOCKED BY SELF-CHECK MACHINE. $blocked_card_msg</sip>\n$note"; # XXX Config option
841 $note =~ s/\s*$//; # kill trailng whitespace
842 $u->alert_message($note);
844 if( ! $e->update_actor_user($u) ) {
845 syslog('LOG_ERR', "OILS: Block: patron alert update failed: %s", $e->event->{textcode});
846 $e->rollback; # rollback + disconnect
851 $self->{user}->alert_message( $note );
853 $e->commit; # commits and disconnects
857 # Testing purposes only
859 my ($self, $card_retained) = @_;
860 $self->{screen_msg} = "All privileges restored.";
862 # Un-mark card as inactive, grep out the patron alert
863 my $e = $self->{editor};
864 my $u = $self->{user};
866 syslog('LOG_INFO', "OILS: Unblocking user %s", $u->card->barcode );
868 return $self if $u->card->active eq 't';
870 $e->xact_begin; # connect and start a new transaction
872 $u->card->active('t');
873 if( ! $e->update_actor_card($u->card) ) {
874 syslog('LOG_ERR', "OILS: Unblock card update failed: %s", $e->event->{textcode});
875 $e->rollback; # rollback + disconnect
879 # retrieve the un-fleshed user object for update
880 $u = $e->retrieve_actor_user($u->id);
881 my $note = OpenILS::SIP::clean_text($u->alert_message) || "";
882 $note =~ s#<sip>.*</sip>##;
883 $note =~ s/^\s*//; # kill leading whitespace
884 $note =~ s/\s*$//; # kill trailng whitespace
885 $u->alert_message($note);
887 if( ! $e->update_actor_user($u) ) {
888 syslog('LOG_ERR', "OILS: Unblock: patron alert update failed: %s", $e->event->{textcode});
889 $e->rollback; # rollback + disconnect
894 $self->{user}->alert_message( $note );
896 $e->commit; # commits and disconnects
905 return "Please contact library staff";
909 return "Please contact library staff";
912 sub inet_privileges {
914 my $e = OpenILS::SIP->editor();
915 $INET_PRIVS = $e->retrieve_all_config_net_access_level() unless $INET_PRIVS;
916 my ($level) = grep { $_->id eq $self->{user}->net_access_level } @$INET_PRIVS;
917 my $name = OpenILS::SIP::clean_text($level->name);
918 syslog('LOG_DEBUG', "OILS: Patron inet_privs = $name");
924 my $extra_fields = {};
925 my $u = $self->{user};
926 foreach my $stat_cat_entry (@{$u->stat_cat_entries}) {
927 my $stat_cat = $stat_cat_entry->stat_cat;
928 next unless ($stat_cat->sip_field);
929 my $value = $stat_cat_entry->stat_cat_entry;
930 if(defined $stat_cat->sip_format && length($stat_cat->sip_format) > 0) { # Has a format string?
931 if($stat_cat->sip_format =~ /^\|(.*)\|$/) { # Regex match?
932 if($value =~ /($1)/) { # If we have a match
933 if(defined $2) { # Check to see if they embedded a capture group
934 $value = $2; # If so, use it
936 else { # No embedded capture group?
937 $value = $1; # Use our outer one
941 $value = ''; # Empty string. Will be checked for below.
944 else { # Not a regex match - Try sprintf match (looking for a %s, if any)
945 $value = sprintf($stat_cat->sip_format, $value);
948 next unless length($value) > 0; # No value = no export
949 $value =~ s/\|//g; # Remove all lingering pipe chars for sane output purposes
950 $extra_fields->{ $stat_cat->sip_field } = [] unless (defined $extra_fields->{$stat_cat->sip_field});
951 push(@{$extra_fields->{ $stat_cat->sip_field}}, $value);
953 return $extra_fields;