3 # Copyright ByWater Solutions 2014
4 # Copyright PTFS Europe 2016
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 3 of the License, or (at your option) any later
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 use List
::MoreUtils
qw( uniq );
32 use Koha
::Old
::Checkouts
;
33 use Koha
::Patron
::Categories
;
34 use Koha
::Patron
::HouseboundProfile
;
35 use Koha
::Patron
::HouseboundRole
;
36 use Koha
::Patron
::Images
;
38 use Koha
::Virtualshelves
;
39 use Koha
::Club
::Enrollments
;
42 use base
qw(Koha::Object);
46 Koha::Patron - Koha Patron Object class
58 Delete patron's holds, lists and finally the patron.
60 Lists owned by the borrower are deleted, but entries from the borrower to
69 $self->_result->result_source->schema->txn_do(
71 # Delete Patron's holds
74 # Delete all lists and all shares of this borrower
75 # Consistent with the approach Koha uses on deleting individual lists
76 # Note that entries in virtualshelfcontents added by this borrower to
77 # lists of others will be handled by a table constraint: the borrower
78 # is set to NULL in those entries.
80 # We could handle the above deletes via a constraint too.
81 # But a new BZ report 11889 has been opened to discuss another approach.
82 # Instead of deleting we could also disown lists (based on a pref).
83 # In that way we could save shared and public lists.
84 # The current table constraints support that idea now.
85 # This pref should then govern the results of other routines/methods such as
86 # Koha::Virtualshelf->new->delete too.
87 # FIXME Could be $patron->get_lists
88 $_->delete for Koha
::Virtualshelves
->search( { owner
=> $self->borrowernumber } );
90 $deleted = $self->SUPER::delete;
92 logaction
( "MEMBERS", "DELETE", $self->borrowernumber, "" ) if C4
::Context
->preference("BorrowersLog");
101 my $patron_category = $patron->category
103 Return the patron category for this patron
109 return Koha
::Patron
::Category
->_new_from_dbic( $self->_result->categorycode );
114 Returns a Koha::Patron object for this patron's guarantor
121 return unless $self->guarantorid();
123 return Koha
::Patrons
->find( $self->guarantorid() );
129 return scalar Koha
::Patron
::Images
->find( $self->borrowernumber );
134 return Koha
::Library
->_new_from_dbic($self->_result->branchcode);
139 Returns the guarantees (list of Koha::Patron) of this patron
146 return Koha
::Patrons
->search( { guarantorid
=> $self->borrowernumber } );
149 =head3 housebound_profile
151 Returns the HouseboundProfile associated with this patron.
155 sub housebound_profile
{
157 my $profile = $self->_result->housebound_profile;
158 return Koha
::Patron
::HouseboundProfile
->_new_from_dbic($profile)
163 =head3 housebound_role
165 Returns the HouseboundRole associated with this patron.
169 sub housebound_role
{
172 my $role = $self->_result->housebound_role;
173 return Koha
::Patron
::HouseboundRole
->_new_from_dbic($role) if ( $role );
179 Returns the siblings of this patron.
186 my $guarantor = $self->guarantor;
188 return unless $guarantor;
190 return Koha
::Patrons
->search(
194 '=' => $guarantor->id,
197 '!=' => $self->borrowernumber,
203 =head3 wants_check_for_previous_checkout
205 $wants_check = $patron->wants_check_for_previous_checkout;
207 Return 1 if Koha needs to perform PrevIssue checking, else 0.
211 sub wants_check_for_previous_checkout
{
213 my $syspref = C4
::Context
->preference("checkPrevCheckout");
216 ## Hard syspref trumps all
217 return 1 if ($syspref eq 'hardyes');
218 return 0 if ($syspref eq 'hardno');
219 ## Now, patron pref trumps all
220 return 1 if ($self->checkprevcheckout eq 'yes');
221 return 0 if ($self->checkprevcheckout eq 'no');
223 # More complex: patron inherits -> determine category preference
224 my $checkPrevCheckoutByCat = $self->category->checkprevcheckout;
225 return 1 if ($checkPrevCheckoutByCat eq 'yes');
226 return 0 if ($checkPrevCheckoutByCat eq 'no');
228 # Finally: category preference is inherit, default to 0
229 if ($syspref eq 'softyes') {
236 =head3 do_check_for_previous_checkout
238 $do_check = $patron->do_check_for_previous_checkout($item);
240 Return 1 if the bib associated with $ITEM has previously been checked out to
241 $PATRON, 0 otherwise.
245 sub do_check_for_previous_checkout
{
246 my ( $self, $item ) = @_;
248 # Find all items for bib and extract item numbers.
249 my @items = Koha
::Items
->search({biblionumber
=> $item->{biblionumber
}});
251 foreach my $item (@items) {
252 push @item_nos, $item->itemnumber;
255 # Create (old)issues search criteria
257 borrowernumber
=> $self->borrowernumber,
258 itemnumber
=> \
@item_nos,
261 # Check current issues table
262 my $issues = Koha
::Checkouts
->search($criteria);
263 return 1 if $issues->count; # 0 || N
265 # Check old issues table
266 my $old_issues = Koha
::Old
::Checkouts
->search($criteria);
267 return $old_issues->count; # 0 || N
272 my $debarment_expiration = $patron->is_debarred;
274 Returns the date a patron debarment will expire, or undef if the patron is not
282 return unless $self->debarred;
283 return $self->debarred
284 if $self->debarred =~ '^9999'
285 or dt_from_string
( $self->debarred ) > dt_from_string
;
291 my $is_expired = $patron->is_expired;
293 Returns 1 if the patron is expired or 0;
299 return 0 unless $self->dateexpiry;
300 return 0 if $self->dateexpiry =~ '^9999';
301 return 1 if dt_from_string
( $self->dateexpiry ) < dt_from_string
->truncate( to
=> 'day' );
305 =head3 is_going_to_expire
307 my $is_going_to_expire = $patron->is_going_to_expire;
309 Returns 1 if the patron is going to expired, depending on the NotifyBorrowerDeparture pref or 0
313 sub is_going_to_expire
{
316 my $delay = C4
::Context
->preference('NotifyBorrowerDeparture') || 0;
318 return 0 unless $delay;
319 return 0 unless $self->dateexpiry;
320 return 0 if $self->dateexpiry =~ '^9999';
321 return 1 if dt_from_string
( $self->dateexpiry )->subtract( days
=> $delay ) < dt_from_string
->truncate( to
=> 'day' );
325 =head3 update_password
327 my $updated = $patron->update_password( $userid, $password );
329 Update the userid and the password of a patron.
330 If the userid already exists, returns and let DBIx::Class warns
331 This will add an entry to action_logs if BorrowersLog is set.
335 sub update_password
{
336 my ( $self, $userid, $password ) = @_;
337 eval { $self->userid($userid)->store; };
338 return if $@
; # Make sure the userid is not already in used by another patron
341 password
=> $password,
345 logaction
( "MEMBERS", "CHANGE PASS", $self->borrowernumber, "" ) if C4
::Context
->preference("BorrowersLog");
351 my $new_expiry_date = $patron->renew_account
353 Extending the subscription to the expiry date.
360 if ( C4
::Context
->preference('BorrowerRenewalPeriodBase') eq 'combination' ) {
361 $date = ( dt_from_string
gt dt_from_string
( $self->dateexpiry ) ) ? dt_from_string
: dt_from_string
( $self->dateexpiry );
364 C4
::Context
->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry'
365 ? dt_from_string
( $self->dateexpiry )
368 my $expiry_date = $self->category->get_expiry_date($date);
370 $self->dateexpiry($expiry_date);
371 $self->date_renewed( dt_from_string
() );
374 $self->add_enrolment_fee_if_needed;
376 logaction
( "MEMBERS", "RENEW", $self->borrowernumber, "Membership renewed" ) if C4
::Context
->preference("BorrowersLog");
377 return dt_from_string
( $expiry_date )->truncate( to
=> 'day' );
382 my $has_overdues = $patron->has_overdues;
384 Returns the number of patron's overdues
390 my $dtf = Koha
::Database
->new->schema->storage->datetime_parser;
391 return $self->_result->issues->search({ date_due
=> { '<' => $dtf->format_datetime( dt_from_string
() ) } })->count;
396 $patron->track_login;
397 $patron->track_login({ force => 1 });
399 Tracks a (successful) login attempt.
400 The preference TrackLastPatronActivity must be enabled. Or you
401 should pass the force parameter.
406 my ( $self, $params ) = @_;
409 !C4
::Context
->preference('TrackLastPatronActivity');
410 $self->lastseen( dt_from_string
() )->store;
413 =head3 move_to_deleted
415 my $is_moved = $patron->move_to_deleted;
417 Move a patron to the deletedborrowers table.
418 This can be done before deleting a patron, to make sure the data are not completely deleted.
422 sub move_to_deleted
{
424 my $patron_infos = $self->unblessed;
425 delete $patron_infos->{updated_on
}; #This ensures the updated_on date in deletedborrowers will be set to the current timestamp
426 return Koha
::Database
->new->schema->resultset('Deletedborrower')->create($patron_infos);
429 =head3 article_requests
431 my @requests = $borrower->article_requests();
432 my $requests = $borrower->article_requests();
434 Returns either a list of ArticleRequests objects,
435 or an ArtitleRequests object, depending on the
440 sub article_requests
{
443 $self->{_article_requests
} ||= Koha
::ArticleRequests
->search({ borrowernumber
=> $self->borrowernumber() });
445 return $self->{_article_requests
};
448 =head3 article_requests_current
450 my @requests = $patron->article_requests_current
452 Returns the article requests associated with this patron that are incomplete
456 sub article_requests_current
{
459 $self->{_article_requests_current
} ||= Koha
::ArticleRequests
->search(
461 borrowernumber
=> $self->id(),
463 { status
=> Koha
::ArticleRequest
::Status
::Pending
},
464 { status
=> Koha
::ArticleRequest
::Status
::Processing
}
469 return $self->{_article_requests_current
};
472 =head3 article_requests_finished
474 my @requests = $biblio->article_requests_finished
476 Returns the article requests associated with this patron that are completed
480 sub article_requests_finished
{
481 my ( $self, $borrower ) = @_;
483 $self->{_article_requests_finished
} ||= Koha
::ArticleRequests
->search(
485 borrowernumber
=> $self->id(),
487 { status
=> Koha
::ArticleRequest
::Status
::Completed
},
488 { status
=> Koha
::ArticleRequest
::Status
::Canceled
}
493 return $self->{_article_requests_finished
};
496 =head3 add_enrolment_fee_if_needed
498 my $enrolment_fee = $patron->add_enrolment_fee_if_needed;
500 Add enrolment fee for a patron if needed.
504 sub add_enrolment_fee_if_needed
{
506 my $enrolment_fee = $self->category->enrolmentfee;
507 if ( $enrolment_fee && $enrolment_fee > 0 ) {
508 # insert fee in patron debts
509 C4
::Accounts
::manualinvoice
( $self->borrowernumber, '', '', 'A', $enrolment_fee );
511 return $enrolment_fee || 0;
516 my $checkouts = $patron->checkouts
522 my $checkouts = $self->_result->issues;
523 return Koha
::Checkouts
->_new_from_dbic( $checkouts );
526 =head3 pending_checkouts
528 my $pending_checkouts = $patron->pending_checkouts
530 This method will return the same as $self->checkouts, but with a prefetch on
531 items, biblio and biblioitems.
533 It has been introduced to replaced the C4::Members::GetPendingIssues subroutine
535 It should not be used directly, prefer to access fields you need instead of
536 retrieving all these fields in one go.
541 sub pending_checkouts
{
543 my $checkouts = $self->_result->issues->search(
547 { -desc
=> 'me.timestamp' },
548 { -desc
=> 'issuedate' },
549 { -desc
=> 'issue_id' }, # Sort by issue_id should be enough
551 prefetch
=> { item
=> { biblio
=> 'biblioitems' } },
554 return Koha
::Checkouts
->_new_from_dbic( $checkouts );
559 my $old_checkouts = $patron->old_checkouts
565 my $old_checkouts = $self->_result->old_issues;
566 return Koha
::Old
::Checkouts
->_new_from_dbic( $old_checkouts );
571 my $overdue_items = $patron->get_overdues
573 Return the overdued items
579 my $dtf = Koha
::Database
->new->schema->storage->datetime_parser;
580 return $self->checkouts->search(
582 'me.date_due' => { '<' => $dtf->format_datetime(dt_from_string
) },
585 prefetch
=> { item
=> { biblio
=> 'biblioitems' } },
592 my $age = $patron->get_age
594 Return the age of the patron
600 my $today_str = dt_from_string
->strftime("%Y-%m-%d");
601 return unless $self->dateofbirth;
602 my $dob_str = dt_from_string
( $self->dateofbirth )->strftime("%Y-%m-%d");
604 my ( $dob_y, $dob_m, $dob_d ) = split /-/, $dob_str;
605 my ( $today_y, $today_m, $today_d ) = split /-/, $today_str;
607 my $age = $today_y - $dob_y;
608 if ( $dob_m . $dob_d > $today_m . $today_d ) {
617 my $account = $patron->account
623 return Koha
::Account
->new( { patron_id
=> $self->borrowernumber } );
628 my $holds = $patron->holds
630 Return all the holds placed by this patron
636 my $holds_rs = $self->_result->reserves->search( {}, { order_by
=> 'reservedate' } );
637 return Koha
::Holds
->_new_from_dbic($holds_rs);
642 my $old_holds = $patron->old_holds
644 Return all the historical holds for this patron
650 my $old_holds_rs = $self->_result->old_reserves->search( {}, { order_by
=> 'reservedate' } );
651 return Koha
::Old
::Holds
->_new_from_dbic($old_holds_rs);
654 =head3 notice_email_address
656 my $email = $patron->notice_email_address;
658 Return the email address of patron used for notices.
659 Returns the empty string if no email address.
663 sub notice_email_address
{
666 my $which_address = C4
::Context
->preference("AutoEmailPrimaryAddress");
667 # if syspref is set to 'first valid' (value == OFF), look up email address
668 if ( $which_address eq 'OFF' ) {
669 return $self->first_valid_email_address;
672 return $self->$which_address || '';
675 =head3 first_valid_email_address
677 my $first_valid_email_address = $patron->first_valid_email_address
679 Return the first valid email address for a patron.
680 For now, the order is defined as email, emailpro, B_email.
681 Returns the empty string if the borrower has no email addresses.
685 sub first_valid_email_address
{
688 return $self->email() || $self->emailpro() || $self->B_email() || q{};
691 =head3 get_club_enrollments
695 sub get_club_enrollments
{
696 my ( $self, $return_scalar ) = @_;
698 my $e = Koha
::Club
::Enrollments
->search( { borrowernumber
=> $self->borrowernumber(), date_canceled
=> undef } );
700 return $e if $return_scalar;
702 return wantarray ?
$e->as_list : $e;
705 =head3 get_enrollable_clubs
709 sub get_enrollable_clubs
{
710 my ( $self, $is_enrollable_from_opac, $return_scalar ) = @_;
713 $params->{is_enrollable_from_opac
} = $is_enrollable_from_opac
714 if $is_enrollable_from_opac;
715 $params->{is_email_required
} = 0 unless $self->first_valid_email_address();
717 $params->{borrower
} = $self;
719 my $e = Koha
::Clubs
->get_enrollable($params);
721 return $e if $return_scalar;
723 return wantarray ?
$e->as_list : $e;
726 =head3 account_locked
728 my $is_locked = $patron->account_locked
730 Return true if the patron has reach the maximum number of login attempts (see pref FailedLoginAttempts).
731 Otherwise return false.
732 If the pref is not set (empty string, null or 0), the feature is considered as disabled.
738 my $FailedLoginAttempts = C4
::Context
->preference('FailedLoginAttempts');
739 return ( $FailedLoginAttempts
740 and $self->login_attempts
741 and $self->login_attempts >= $FailedLoginAttempts )?
1 : 0;
744 =head3 can_see_patron_infos
746 my $can_see = $patron->can_see_patron_infos( $patron );
748 Return true if the patron (usually the logged in user) can see the patron's infos for a given patron
752 sub can_see_patron_infos
{
753 my ( $self, $patron ) = @_;
754 return $self->can_see_patrons_from( $patron->library->branchcode );
757 =head3 can_see_patrons_from
759 my $can_see = $patron->can_see_patrons_from( $branchcode );
761 Return true if the patron (usually the logged in user) can see the patron's infos from a given library
765 sub can_see_patrons_from
{
766 my ( $self, $branchcode ) = @_;
768 if ( $self->branchcode eq $branchcode ) {
770 } elsif ( $self->has_permission( { borrowers
=> 'view_borrower_infos_from_any_libraries' } ) ) {
772 } elsif ( my $library_groups = $self->library->library_groups ) {
773 while ( my $library_group = $library_groups->next ) {
774 if ( $library_group->parent->has_child( $branchcode ) ) {
783 =head3 libraries_where_can_see_patrons
785 my $libraries = $patron-libraries_where_can_see_patrons;
787 Return the list of branchcodes(!) of libraries the patron is allowed to see other patron's infos.
788 The branchcodes are arbitrarily returned sorted.
789 We are supposing here that the object is related to the logged in patron (use of C4::Context::only_my_library)
791 An empty array means no restriction, the patron can see patron's infos from any libraries.
795 sub libraries_where_can_see_patrons
{
797 my $userenv = C4
::Context
->userenv;
799 return () unless $userenv; # For tests, but userenv should be defined in tests...
801 my @restricted_branchcodes;
802 if (C4
::Context
::only_my_library
) {
803 push @restricted_branchcodes, $self->branchcode;
807 $self->has_permission(
808 { borrowers
=> 'view_borrower_infos_from_any_libraries' }
812 my $library_groups = $self->library->library_groups({ ft_hide_patron_info
=> 1 });
813 if ( $library_groups->count )
815 while ( my $library_group = $library_groups->next ) {
816 my $parent = $library_group->parent;
817 if ( $parent->has_child( $self->branchcode ) ) {
818 push @restricted_branchcodes, $parent->children->get_column('branchcode');
823 @restricted_branchcodes = ( $self->branchcode ) unless @restricted_branchcodes;
827 @restricted_branchcodes = grep { defined $_ } @restricted_branchcodes;
828 @restricted_branchcodes = uniq
(@restricted_branchcodes);
829 @restricted_branchcodes = sort(@restricted_branchcodes);
830 return @restricted_branchcodes;
834 my ( $self, $flagsrequired ) = @_;
835 return unless $self->userid;
836 # TODO code from haspermission needs to be moved here!
837 return C4
::Auth
::haspermission
( $self->userid, $flagsrequired );
842 my $is_adult = $patron->is_adult
844 Return true if the patron has a category with a type Adult (A) or Organization (I)
850 return $self->category->category_type =~ /^(A|I)$/ ?
1 : 0;
855 my $is_child = $patron->is_child
857 Return true if the patron has a category with a type Child (C)
862 return $self->category->category_type eq 'C' ?
1 : 0;
865 =head3 has_valid_userid
867 my $patron = Koha::Patrons->find(42);
868 $patron->userid( $new_userid );
869 my $has_a_valid_userid = $patron->has_valid_userid
871 my $patron = Koha::Patron->new( $params );
872 my $has_a_valid_userid = $patron->has_valid_userid
874 Return true if the current userid of this patron is valid/unique, otherwise false.
876 Note that this should be done in $self->store instead and raise an exception if needed.
880 sub has_valid_userid
{
883 return 0 unless $self->userid;
885 return 0 if ( $self->userid eq C4
::Context
->config('user') ); # DB user
887 my $already_exists = Koha
::Patrons
->search(
889 userid
=> $self->userid,
892 ?
( borrowernumber
=> { '!=' => $self->borrowernumber } )
897 return $already_exists ?
0 : 1;
900 =head2 Internal methods
912 Kyle M Hall <kyle@bywatersolutions.com>
913 Alex Sassmannshausen <alex.sassmannshausen@ptfs-europe.com>