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
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23 use List::MoreUtils qw( any uniq );
24 use JSON qw( to_json );
25 use Unicode::Normalize qw( NFKD );
29 use C4::Auth qw( checkpw_hash );
31 use C4::Letters qw( GetPreparedLetter EnqueueLetter SendQueuedMessages );
32 use C4::Log qw( logaction );
34 use Koha::ArticleRequests;
38 use Koha::CirculationRules;
39 use Koha::Club::Enrollments;
40 use Koha::CurbsidePickups;
42 use Koha::DateUtils qw( dt_from_string );
45 use Koha::Exceptions::Password;
47 use Koha::Old::Checkouts;
48 use Koha::OverdueRules;
49 use Koha::Patron::Attributes;
50 use Koha::Patron::Categories;
51 use Koha::Patron::Consents;
52 use Koha::Patron::Debarments;
53 use Koha::Patron::HouseboundProfile;
54 use Koha::Patron::HouseboundRole;
55 use Koha::Patron::Images;
56 use Koha::Patron::Messages;
57 use Koha::Patron::Modifications;
58 use Koha::Patron::MessagePreferences;
59 use Koha::Patron::Relationships;
60 use Koha::Patron::Restrictions;
64 use Koha::Result::Boolean;
65 use Koha::Subscription::Routinglists;
67 use Koha::Virtualshelves;
69 use base qw(Koha::Object);
71 use constant ADMINISTRATIVE_LOCKOUT => -1;
73 our $RESULTSET_PATRON_ID_MAPPING = {
74 Accountline => 'borrowernumber',
75 Aqbasketuser => 'borrowernumber',
76 Aqbudget => 'budget_owner_id',
77 Aqbudgetborrower => 'borrowernumber',
78 ArticleRequest => 'borrowernumber',
79 BorrowerDebarment => 'borrowernumber',
80 BorrowerFile => 'borrowernumber',
81 BorrowerModification => 'borrowernumber',
82 ClubEnrollment => 'borrowernumber',
83 Issue => 'borrowernumber',
84 ItemsLastBorrower => 'borrowernumber',
85 Linktracker => 'borrowernumber',
86 Message => 'borrowernumber',
87 MessageQueue => 'borrowernumber',
88 OldIssue => 'borrowernumber',
89 OldReserve => 'borrowernumber',
90 Rating => 'borrowernumber',
91 Reserve => 'borrowernumber',
92 Review => 'borrowernumber',
93 SearchHistory => 'userid',
94 Statistic => 'borrowernumber',
95 Suggestion => 'suggestedby',
96 TagAll => 'borrowernumber',
97 Virtualshelfcontent => 'borrowernumber',
98 Virtualshelfshare => 'borrowernumber',
99 Virtualshelve => 'owner',
104 Koha::Patron - Koha Patron Object class
115 my ( $class, $params ) = @_;
117 return $class->SUPER::new($params);
120 =head3 fixup_cardnumber
122 Autogenerate next cardnumber from highest value found in database
126 sub fixup_cardnumber {
129 my $max = $self->cardnumber;
130 Koha::Plugins->call( 'patron_barcode_transform', \$max );
132 $max ||= Koha::Patrons->search({
133 cardnumber => {-regexp => '^-?[0-9]+$'}
135 select => \'CAST(cardnumber AS SIGNED)',
136 as => ['cast_cardnumber']
137 })->_resultset->get_column('cast_cardnumber')->max;
138 $self->cardnumber(($max || 0) +1);
141 =head3 trim_whitespace
143 trim whitespace from data which has some non-whitespace in it.
144 Could be moved to Koha::Object if need to be reused
148 sub trim_whitespaces {
151 my $schema = Koha::Database->new->schema;
152 my @columns = $schema->source($self->_type)->columns;
154 for my $column( @columns ) {
155 my $value = $self->$column;
156 if ( defined $value ) {
157 $value =~ s/^\s*|\s*$//g;
158 $self->$column($value);
164 =head3 plain_text_password
166 $patron->plain_text_password( $password );
168 stores a copy of the unencrypted password in the object
169 for use in code before encrypting for db
173 sub plain_text_password {
174 my ( $self, $password ) = @_;
176 $self->{_plain_text_password} = $password;
179 return $self->{_plain_text_password}
180 if $self->{_plain_text_password};
187 Patron specific store method to cleanup record
188 and do other necessary things before saving
195 my $params = @_ ? shift : {};
197 my $guarantors = $params->{guarantors} // [];
199 $self->_result->result_source->schema->txn_do(
202 C4::Context->preference("autoMemberNum")
203 and ( not defined $self->cardnumber
204 or $self->cardnumber eq '' )
207 # Warning: The caller is responsible for locking the members table in write
208 # mode, to avoid database corruption.
209 # We are in a transaction but the table is not locked
210 $self->fixup_cardnumber;
213 unless( $self->category->in_storage ) {
214 Koha::Exceptions::Object::FKConstraint->throw(
215 broken_fk => 'categorycode',
216 value => $self->categorycode,
220 $self->trim_whitespaces;
222 my $new_cardnumber = $self->cardnumber;
223 Koha::Plugins->call( 'patron_barcode_transform', \$new_cardnumber );
224 $self->cardnumber( $new_cardnumber );
226 # Set surname to uppercase if uppercasesurname is true
227 $self->surname( uc($self->surname) )
228 if C4::Context->preference("uppercasesurnames");
230 $self->relationship(undef) # We do not want to store an empty string in this field
231 if defined $self->relationship
232 and $self->relationship eq "";
234 unless ( $self->in_storage ) { #AddMember
236 # Generate a valid userid/login if needed
237 $self->generate_userid unless $self->userid;
238 Koha::Exceptions::Patron::InvalidUserid->throw( userid => $self->userid )
239 unless $self->has_valid_userid;
241 # Add expiration date if it isn't already there
242 unless ( $self->dateexpiry ) {
243 $self->dateexpiry( $self->category->get_expiry_date );
246 # Add enrollment date if it isn't already there
247 unless ( $self->dateenrolled ) {
248 $self->dateenrolled(dt_from_string);
251 # Set the privacy depending on the patron's category
252 my $default_privacy = $self->category->default_privacy || q{};
254 $default_privacy eq 'default' ? 1
255 : $default_privacy eq 'never' ? 2
256 : $default_privacy eq 'forever' ? 0
258 $self->privacy($default_privacy);
260 # Call any check_password plugins if password is passed
261 if ( C4::Context->config("enable_plugins") && $self->password ) {
262 my @plugins = Koha::Plugins->new()->GetPlugins({
263 method => 'check_password',
265 foreach my $plugin ( @plugins ) {
266 # This plugin hook will also be used by a plugin for the Norwegian national
267 # patron database. This is why we need to pass both the password and the
268 # borrowernumber to the plugin.
269 my $ret = $plugin->check_password(
271 password => $self->password,
272 borrowernumber => $self->borrowernumber
275 if ( $ret->{'error'} == 1 ) {
276 Koha::Exceptions::Password::Plugin->throw();
281 # Make a copy of the plain text password for later use
282 $self->plain_text_password( $self->password );
284 $self->password_expiration_date( $self->password
285 ? $self->category->get_password_expiry_date || undef
287 # Create a disabled account if no password provided
288 $self->password( $self->password
289 ? Koha::AuthUtils::hash_password( $self->password )
292 $self->borrowernumber(undef);
294 if ( C4::Context->preference('ChildNeedsGuarantor')
295 and ( $self->is_child or $self->category->can_be_guarantee )
296 and $self->contactname eq ""
299 Koha::Exceptions::Patron::Relationship::NoGuarantor->throw();
302 foreach my $guarantor (@$guarantors) {
303 if ( $guarantor->is_child or $guarantor->category->can_be_guarantee) {
304 Koha::Exceptions::Patron::Relationship::InvalidRelationship
305 ->throw( invalid_guarantor => 1 );
309 $self = $self->SUPER::store;
311 $self->add_enrolment_fee_if_needed(0);
313 logaction( "MEMBERS", "CREATE", $self->borrowernumber, "" )
314 if C4::Context->preference("BorrowersLog");
318 my $self_from_storage = $self->get_from_storage;
320 # Do not accept invalid userid here
321 $self->generate_userid unless $self->userid;
322 Koha::Exceptions::Patron::InvalidUserid->throw( userid => $self->userid )
323 unless $self->has_valid_userid;
325 # If a borrower has set their privacy to never we should immediately anonymize
327 if( $self->privacy() == 2 && $self_from_storage->privacy() != 2 ){
329 $self->old_checkouts->anonymize;
332 Koha::Exceptions::Patron::FailedAnonymizing->throw(
338 # Password must be updated using $self->set_password
339 $self->password($self_from_storage->password);
341 if ( $self->category->categorycode ne
342 $self_from_storage->category->categorycode )
344 # Add enrolement fee on category change if required
345 $self->add_enrolment_fee_if_needed(1)
346 if C4::Context->preference('FeeOnChangePatronCategory');
348 # Clean up guarantors on category change if required
349 $self->guarantor_relationships->delete
350 unless ( $self->category->can_be_guarantee );
354 my @existing_guarantors = $self->guarantor_relationships()->guarantors->as_list;
355 push @$guarantors, @existing_guarantors;
357 if ( C4::Context->preference('ChildNeedsGuarantor')
358 and ( $self->is_child or $self->category->can_be_guarantee )
359 and $self->contactname eq ""
362 Koha::Exceptions::Patron::Relationship::NoGuarantor->throw();
365 foreach my $guarantor (@$guarantors) {
366 if ( $guarantor->is_child or $guarantor->category->can_be_guarantee) {
367 Koha::Exceptions::Patron::Relationship::InvalidRelationship
368 ->throw( invalid_guarantor => 1 );
373 if ( C4::Context->preference("BorrowersLog") ) {
375 my $from_storage = $self_from_storage->unblessed;
376 my $from_object = $self->unblessed;
377 my @skip_fields = (qw/lastseen updated_on/);
378 for my $key ( keys %{$from_storage} ) {
379 next if any { /$key/ } @skip_fields;
382 !defined( $from_storage->{$key} )
383 && defined( $from_object->{$key} )
385 || ( defined( $from_storage->{$key} )
386 && !defined( $from_object->{$key} ) )
388 defined( $from_storage->{$key} )
389 && defined( $from_object->{$key} )
390 && ( $from_storage->{$key} ne
391 $from_object->{$key} )
396 before => $from_storage->{$key},
397 after => $from_object->{$key}
402 if ( defined($info) ) {
406 $self->borrowernumber,
409 { utf8 => 1, pretty => 1, canonical => 1 }
416 $self = $self->SUPER::store;
427 Delete patron's holds, lists and finally the patron.
429 Lists owned by the borrower are deleted or ownership is transferred depending on the
430 ListOwnershipUponPatronDeletion pref, but entries from the borrower to other lists are kept.
437 my $anonymous_patron = C4::Context->preference("AnonymousPatron");
438 Koha::Exceptions::Patron::FailedDeleteAnonymousPatron->throw() if $anonymous_patron && $self->id eq $anonymous_patron;
440 # Check if patron is protected
441 Koha::Exceptions::Patron::FailedDeleteProtectedPatron->throw() if $self->protected == 1;
443 $self->_result->result_source->schema->txn_do(
445 # Cancel Patron's holds
446 my $holds = $self->holds;
447 while( my $hold = $holds->next ){
451 # Handle lists (virtualshelves)
452 $self->virtualshelves->disown_or_delete;
454 # We cannot have a FK on borrower_modifications.borrowernumber, the table is also used
456 $_->delete for Koha::Patron::Modifications->search( { borrowernumber => $self->borrowernumber } )->as_list;
458 $self->SUPER::delete;
460 logaction( "MEMBERS", "DELETE", $self->borrowernumber, "" ) if C4::Context->preference("BorrowersLog");
468 my $patron_category = $patron->category
470 Return the patron category for this patron
476 return Koha::Patron::Category->_new_from_dbic( $self->_result->categorycode );
486 return Koha::Patron::Images->find( $self->borrowernumber );
491 Returns a Koha::Library object representing the patron's home library.
497 return Koha::Library->_new_from_dbic($self->_result->branchcode);
502 Returns a Koha::SMS::Provider object representing the patron's SMS provider.
508 my $sms_provider_rs = $self->_result->sms_provider;
509 return unless $sms_provider_rs;
510 return Koha::SMS::Provider->_new_from_dbic($sms_provider_rs);
513 =head3 guarantor_relationships
515 Returns Koha::Patron::Relationships object for this patron's guarantors
517 Returns the set of relationships for the patrons that are guarantors for this patron.
519 Note that a guarantor should exist as a patron in Koha; it was not possible
520 to add them without a guarantor_id in the interface for some time. Bug 30472
521 restricts it on db level.
525 sub guarantor_relationships {
528 return Koha::Patron::Relationships->search( { guarantee_id => $self->id } );
531 =head3 guarantee_relationships
533 Returns Koha::Patron::Relationships object for this patron's guarantors
535 Returns the set of relationships for the patrons that are guarantees for this patron.
537 The method returns Koha::Patron::Relationship objects for the sake
538 of consistency with the guantors method.
539 A guarantee by definition must exist as a patron in Koha.
543 sub guarantee_relationships {
546 return Koha::Patron::Relationships->search(
547 { guarantor_id => $self->id },
549 prefetch => 'guarantee',
550 order_by => { -asc => [ 'guarantee.surname', 'guarantee.firstname' ] },
555 =head3 relationships_debt
557 Returns the amount owed by the patron's guarantors *and* the other guarantees of those guarantors
561 sub relationships_debt {
562 my ($self, $params) = @_;
564 my $include_guarantors = $params->{include_guarantors};
565 my $only_this_guarantor = $params->{only_this_guarantor};
566 my $include_this_patron = $params->{include_this_patron};
569 if ( $only_this_guarantor ) {
570 @guarantors = $self->guarantee_relationships->count ? ( $self ) : ();
571 Koha::Exceptions::BadParameter->throw( { parameter => 'only_this_guarantor' } ) unless @guarantors;
572 } elsif ( $self->guarantor_relationships->count ) {
573 # I am a guarantee, just get all my guarantors
574 @guarantors = $self->guarantor_relationships->guarantors->as_list;
576 # I am a guarantor, I need to get all the guarantors of all my guarantees
577 @guarantors = map { $_->guarantor_relationships->guarantors->as_list } $self->guarantee_relationships->guarantees->as_list;
580 my $non_issues_charges = 0;
581 my $seen = $include_this_patron ? {} : { $self->id => 1 }; # For tracking members already added to the total
582 foreach my $guarantor (@guarantors) {
583 $non_issues_charges += $guarantor->account->non_issues_charges if $include_guarantors && !$seen->{ $guarantor->id };
585 # We've added what the guarantor owes, not added in that guarantor's guarantees as well
586 my @guarantees = map { $_->guarantee } $guarantor->guarantee_relationships->as_list;
587 my $guarantees_non_issues_charges = 0;
588 foreach my $guarantee (@guarantees) {
589 next if $seen->{ $guarantee->id };
590 $guarantees_non_issues_charges += $guarantee->account->non_issues_charges;
591 # Mark this guarantee as seen so we don't double count a guarantee linked to multiple guarantors
592 $seen->{ $guarantee->id } = 1;
595 $non_issues_charges += $guarantees_non_issues_charges;
596 $seen->{ $guarantor->id } = 1;
599 return $non_issues_charges;
602 =head3 housebound_profile
604 Returns the HouseboundProfile associated with this patron.
608 sub housebound_profile {
610 my $profile = $self->_result->housebound_profile;
611 return Koha::Patron::HouseboundProfile->_new_from_dbic($profile)
616 =head3 housebound_role
618 Returns the HouseboundRole associated with this patron.
622 sub housebound_role {
625 my $role = $self->_result->housebound_role;
626 return Koha::Patron::HouseboundRole->_new_from_dbic($role) if ( $role );
632 Returns the siblings of this patron.
639 my @guarantors = $self->guarantor_relationships()->guarantors()->as_list;
641 return unless @guarantors;
644 map { $_->guarantee_relationships()->guarantees()->as_list } @guarantors;
646 return unless @siblings;
650 grep { !$seen{ $_->id }++ && ( $_->id != $self->id ) } @siblings;
652 return Koha::Patrons->search( { borrowernumber => { -in => [ map { $_->id } @siblings ] } } );
657 my $patron = Koha::Patrons->find($id);
658 $patron->merge_with( \@patron_ids );
660 This subroutine merges a list of patrons into the patron record. This is accomplished by finding
661 all related patron ids for the patrons to be merged in other tables and changing the ids to be that
662 of the keeper patron.
667 my ( $self, $patron_ids ) = @_;
669 my $anonymous_patron = C4::Context->preference("AnonymousPatron");
670 return if $anonymous_patron && $self->id eq $anonymous_patron;
672 # Do not merge other patrons into a protected patron
673 return if $self->protected;
675 my @patron_ids = @{ $patron_ids };
677 # Ensure the keeper isn't in the list of patrons to merge
678 @patron_ids = grep { $_ ne $self->id } @patron_ids;
680 my $schema = Koha::Database->new()->schema();
684 $self->_result->result_source->schema->txn_do( sub {
685 foreach my $patron_id (@patron_ids) {
687 next if $patron_id eq $anonymous_patron;
689 my $patron = Koha::Patrons->find( $patron_id );
693 # Do not merge protected patrons into other patrons
694 next if $patron->protected;
696 # Unbless for safety, the patron will end up being deleted
697 $results->{merged}->{$patron_id}->{patron} = $patron->unblessed;
699 my $attributes = $patron->extended_attributes;
700 my $new_attributes = [
701 map { { code => $_->code, attribute => $_->attribute } }
704 $attributes->delete; # We need to delete before trying to merge them to prevent exception on unique and repeatable
705 for my $attribute ( @$new_attributes ) {
707 $self->add_extended_attribute($attribute);
709 # Don't block the merge if there is a non-repeatable attribute that cannot be added to the current patron.
710 unless ( $_->isa('Koha::Exceptions::Patron::Attribute::NonRepeatable') ) {
716 while (my ($r, $field) = each(%$RESULTSET_PATRON_ID_MAPPING)) {
717 my $rs = $schema->resultset($r)->search({ $field => $patron_id });
718 $results->{merged}->{ $patron_id }->{updated}->{$r} = $rs->count();
719 $rs->update({ $field => $self->id });
720 if ( $r eq 'BorrowerDebarment' ) {
721 Koha::Patron::Debarments::UpdateBorrowerDebarmentFlags($self->id);
725 $patron->move_to_deleted();
734 =head3 messaging_preferences
736 my $patron = Koha::Patrons->find($id);
737 $patron->messaging_preferences();
741 sub messaging_preferences {
744 return Koha::Patron::MessagePreferences->search({
745 borrowernumber => $self->borrowernumber,
749 =head3 wants_check_for_previous_checkout
751 $wants_check = $patron->wants_check_for_previous_checkout;
753 Return 1 if Koha needs to perform PrevIssue checking, else 0.
757 sub wants_check_for_previous_checkout {
759 my $syspref = C4::Context->preference("checkPrevCheckout");
762 ## Hard syspref trumps all
763 return 1 if ($syspref eq 'hardyes');
764 return 0 if ($syspref eq 'hardno');
765 ## Now, patron pref trumps all
766 return 1 if ($self->checkprevcheckout eq 'yes');
767 return 0 if ($self->checkprevcheckout eq 'no');
769 # More complex: patron inherits -> determine category preference
770 my $checkPrevCheckoutByCat = $self->category->checkprevcheckout;
771 return 1 if ($checkPrevCheckoutByCat eq 'yes');
772 return 0 if ($checkPrevCheckoutByCat eq 'no');
774 # Finally: category preference is inherit, default to 0
775 if ($syspref eq 'softyes') {
782 =head3 do_check_for_previous_checkout
784 $do_check = $patron->do_check_for_previous_checkout($item);
786 Return 1 if the bib associated with $ITEM has previously been checked out to
787 $PATRON, 0 otherwise.
791 sub do_check_for_previous_checkout {
792 my ( $self, $item ) = @_;
795 my $biblio = Koha::Biblios->find( $item->{biblionumber} );
796 if ( $biblio->is_serial ) {
797 push @item_nos, $item->{itemnumber};
799 # Get all itemnumbers for given bibliographic record.
800 @item_nos = $biblio->items->get_column( 'itemnumber' );
803 # Create (old)issues search criteria
805 borrowernumber => $self->borrowernumber,
806 itemnumber => \@item_nos,
809 my $delay = C4::Context->preference('CheckPrevCheckoutDelay') || 0;
811 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
812 my $newer_than = dt_from_string()->subtract( days => $delay );
813 $criteria->{'returndate'} = { '>' => $dtf->format_datetime($newer_than), };
816 # Check current issues table
817 my $issues = Koha::Checkouts->search($criteria);
818 return 1 if $issues->count; # 0 || N
820 # Check old issues table
821 my $old_issues = Koha::Old::Checkouts->search($criteria);
822 return $old_issues->count; # 0 || N
827 my $debarment_expiration = $patron->is_debarred;
829 Returns the date a patron debarment will expire, or undef if the patron is not
837 return unless $self->debarred;
838 return $self->debarred
839 if $self->debarred =~ '^9999'
840 or dt_from_string( $self->debarred ) > dt_from_string;
846 my $is_expired = $patron->is_expired;
848 Returns 1 if the patron is expired or 0;
854 return 0 unless $self->dateexpiry;
855 return 0 if $self->dateexpiry =~ '^9999';
856 return 1 if dt_from_string( $self->dateexpiry ) < dt_from_string->truncate( to => 'day' );
862 $patron->is_active({ [ since => $date ], [ days|weeks|months|years => $value ] })
864 A patron is considered 'active' if the following conditions hold:
866 - account did not expire
867 - account has not been anonymized
868 - enrollment or lastseen within period specified
870 Note: lastseen is updated for triggers defined in preference
871 TrackLastPatronActivityTriggers. This includes logins, issues, holds, etc.
873 The period to check is defined by $date or $value in days, weeks or months. You should
874 pass one of those; otherwise an exception is thrown.
879 my ( $self, $params ) = @_;
880 return 0 if $self->is_expired or $self->anonymized;
883 if ( $params->{since} ) {
884 $dt = dt_from_string( $params->{since}, 'iso' );
885 } elsif ( grep { $params->{$_} } qw(days weeks months years) ) {
886 $dt = dt_from_string();
887 foreach my $duration (qw(days weeks months years)) {
888 $dt = $dt->subtract( $duration => $params->{$duration} ) if $params->{$duration};
891 Koha::Exceptions::MissingParameter->throw('is_active needs date or period');
894 # Enrollment within this period?
895 return 1 if DateTime->compare( dt_from_string( $self->dateenrolled ), $dt ) > -1;
897 # We look at lastseen regardless of TrackLastPatronActivityTriggers. If lastseen is set
898 # recently, the triggers may have been removed after that, etc.
899 return 1 if $self->lastseen && DateTime->compare( dt_from_string( $self->lastseen ), $dt ) > -1;
904 =head3 password_expired
906 my $password_expired = $patron->password_expired;
908 Returns 1 if the patron's password is expired or 0;
912 sub password_expired {
914 return 0 unless $self->password_expiration_date;
915 return 1 if dt_from_string( $self->password_expiration_date ) <= dt_from_string->truncate( to => 'day' );
919 =head3 is_going_to_expire
921 my $is_going_to_expire = $patron->is_going_to_expire;
923 Returns 1 if the patron is going to expired, depending on the NotifyBorrowerDeparture pref or 0
927 sub is_going_to_expire {
930 my $delay = C4::Context->preference('NotifyBorrowerDeparture') || 0;
932 return 0 unless $delay;
933 return 0 unless $self->dateexpiry;
934 return 0 if $self->dateexpiry =~ '^9999';
935 return 1 if dt_from_string( $self->dateexpiry, undef, 'floating' )->subtract( days => $delay ) < dt_from_string(undef, undef, 'floating')->truncate( to => 'day' );
941 $patron->set_password({ password => $plain_text_password [, skip_validation => 1, action => NAME ] });
943 Set the patron's password.
945 Allows optional action parameter to change name of action logged (when enabled). Used for reset password.
949 The passed string is validated against the current password enforcement policy.
950 Validation can be skipped by passing the I<skip_validation> parameter.
952 Exceptions are thrown if the password is not good enough.
956 =item Koha::Exceptions::Password::TooShort
958 =item Koha::Exceptions::Password::WhitespaceCharacters
960 =item Koha::Exceptions::Password::TooWeak
962 =item Koha::Exceptions::Password::Plugin (if a "check password" plugin is enabled)
969 my ( $self, $args ) = @_;
971 my $password = $args->{password};
972 my $action = $args->{action} || "CHANGE PASS";
974 unless ( $args->{skip_validation} ) {
975 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, $self->category );
978 if ( $error eq 'too_short' ) {
979 my $min_length = $self->category->effective_min_password_length;
980 $min_length = 3 if not $min_length or $min_length < 3;
982 my $password_length = length($password);
983 Koha::Exceptions::Password::TooShort->throw(
984 length => $password_length, min_length => $min_length );
986 elsif ( $error eq 'has_whitespaces' ) {
987 Koha::Exceptions::Password::WhitespaceCharacters->throw();
989 elsif ( $error eq 'too_weak' ) {
990 Koha::Exceptions::Password::TooWeak->throw();
995 if ( C4::Context->config("enable_plugins") ) {
996 # Call any check_password plugins
997 my @plugins = Koha::Plugins->new()->GetPlugins({
998 method => 'check_password',
1000 foreach my $plugin ( @plugins ) {
1001 # This plugin hook will also be used by a plugin for the Norwegian national
1002 # patron database. This is why we need to pass both the password and the
1003 # borrowernumber to the plugin.
1004 my $ret = $plugin->check_password(
1006 password => $password,
1007 borrowernumber => $self->borrowernumber
1010 # This plugin hook will also be used by a plugin for the Norwegian national
1011 # patron database. This is why we need to call the actual plugins and then
1012 # check skip_validation afterwards.
1013 if ( $ret->{'error'} == 1 && !$args->{skip_validation} ) {
1014 Koha::Exceptions::Password::Plugin->throw();
1019 if ( C4::Context->preference('NotifyPasswordChange') ) {
1020 my $self_from_storage = $self->get_from_storage;
1021 if ( !C4::Auth::checkpw_hash( $password, $self_from_storage->password ) ) {
1022 my $emailaddr = $self_from_storage->notice_email_address;
1024 # if we manage to find a valid email address, send notice
1026 my $letter = C4::Letters::GetPreparedLetter(
1027 module => 'members',
1028 letter_code => 'PASSWORD_CHANGE',
1029 branchcode => $self_from_storage->branchcode,
1031 lang => $self_from_storage->lang || 'default',
1033 'branches' => $self_from_storage->branchcode,
1034 'borrowers' => $self_from_storage->borrowernumber,
1036 want_librarian => 1,
1039 my $message_id = C4::Letters::EnqueueLetter(
1042 borrowernumber => $self_from_storage->id,
1043 to_address => $emailaddr,
1044 message_transport_type => 'email'
1047 C4::Letters::SendQueuedMessages( { message_id => $message_id } ) if $message_id;
1052 my $digest = Koha::AuthUtils::hash_password($password);
1054 $self->password_expiration_date( $self->category->get_password_expiry_date || undef );
1056 # We do not want to call $self->store and retrieve password from DB
1057 $self->password($digest);
1058 $self->login_attempts(0);
1059 $self->SUPER::store;
1061 logaction( "MEMBERS", $action, $self->borrowernumber, "" )
1062 if C4::Context->preference("BorrowersLog");
1068 =head3 renew_account
1070 my $new_expiry_date = $patron->renew_account
1072 Extending the subscription to the expiry date.
1079 if ( C4::Context->preference('BorrowerRenewalPeriodBase') eq 'combination' ) {
1080 $date = ( dt_from_string gt dt_from_string( $self->dateexpiry ) ) ? dt_from_string : dt_from_string( $self->dateexpiry );
1083 C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry'
1084 ? dt_from_string( $self->dateexpiry )
1087 my $expiry_date = $self->category->get_expiry_date($date);
1089 $self->dateexpiry($expiry_date);
1090 $self->date_renewed( dt_from_string() );
1093 $self->add_enrolment_fee_if_needed(1);
1095 logaction( "MEMBERS", "RENEW", $self->borrowernumber, "Membership renewed" ) if C4::Context->preference("BorrowersLog");
1096 return dt_from_string( $expiry_date )->truncate( to => 'day' );
1101 my $has_overdues = $patron->has_overdues;
1103 Returns the number of patron's overdues
1109 my $date = dt_from_string();
1110 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
1111 return $self->_result->issues->search({ date_due => { '<' => $dtf->format_datetime($date) } })->count;
1116 =head3 has_restricting_overdues
1118 my $has_restricting_overdues = $patron->has_restricting_overdues({ issue_branchcode => $branchcode });
1120 Returns true if patron has overdues that would result in debarment.
1124 sub has_restricting_overdues {
1125 my ( $self, $params ) = @_;
1127 my $date = dt_from_string()->truncate( to => 'day' );
1129 # If ignoring unrestricted overdues, calculate which delay value for
1130 # overdue messages is set with restrictions. Then only include overdue
1131 # issues older than that date when counting.
1132 #TODO: bail out/throw exception if $params->{issue_branchcode} not set?
1133 my $debarred_delay = _get_overdue_debarred_delay( $params->{issue_branchcode}, $self->categorycode() );
1134 return 0 unless defined $debarred_delay;
1136 # Emulate the conditions in overdue_notices.pl.
1137 # The overdue_notices-script effectively truncates both issues.date_due and current date
1138 # to days when selecting overdue issues.
1139 # Hours and minutes for issues.date_due is usually set to 23 and 59 respectively, though can theoretically
1140 # be set to any other value (truncated to minutes, except if CalcDateDue gets a $startdate)
1142 # No matter what time of day date_due is set to, overdue_notices.pl will select all issues that are due
1143 # the current date or later. We can emulate this query by instead of truncating both to days in the SQL-query,
1144 # using the condition that date_due must be less then the current date truncated to days (time set to 00:00:00)
1145 # offset by one day in the future.
1147 $date->add( days => 1 );
1150 if ( C4::Context->preference('OverdueNoticeCalendar') ) {
1151 $calendar = Koha::Calendar->new( branchcode => $params->{issue_branchcode} );
1154 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
1155 my $issues = $self->_result->issues->search( { date_due => { '<' => $dtf->format_datetime($date) } } );
1156 my $now = dt_from_string();
1158 while ( my $issue = $issues->next ) {
1160 C4::Context->preference('OverdueNoticeCalendar')
1161 ? $calendar->days_between( dt_from_string( $issue->date_due ), $now )->in_units('days')
1162 : $now->delta_days( dt_from_string( $issue->date_due ) )->in_units('days');
1163 if ( $days_between >= $debarred_delay ) {
1170 # Fetch first delayX value from overduerules where debarredX is set, or 0 for no delay
1171 sub _get_overdue_debarred_delay {
1172 my ( $branchcode, $categorycode ) = @_;
1173 my $dbh = C4::Context->dbh();
1175 # We get default rules if there is no rule for this branch
1176 my $rule = Koha::OverdueRules->find(
1178 branchcode => $branchcode,
1179 categorycode => $categorycode
1182 || Koha::OverdueRules->find(
1185 categorycode => $categorycode
1190 return $rule->delay1 if $rule->debarred1;
1191 return $rule->delay2 if $rule->debarred2;
1192 return $rule->delay3 if $rule->debarred3;
1196 =head3 update_lastseen
1198 $patron->update_lastseen('activity');
1200 Updates the lastseen field, limited to one update per day, whenever the activity passed is
1201 listed in TrackLastPatronActivityTriggers.
1203 The method should be called upon successful completion of the activity.
1207 sub update_lastseen {
1208 my ( $self, $activity ) = @_;
1209 my $tracked_activities = {
1210 map { ( lc $_, 1 ); } split /\s*\,\s*/,
1211 C4::Context->preference('TrackLastPatronActivityTriggers')
1213 return $self unless $tracked_activities->{$activity};
1215 my $cache = Koha::Caches->get_instance();
1216 my $cache_key = "track_activity_" . $self->borrowernumber;
1217 my $cached = $cache->get_from_cache($cache_key);
1218 my $now = dt_from_string();
1219 return $self if $cached && $cached eq $now->ymd;
1221 $self->lastseen($now)->store;
1222 $cache->set_in_cache( $cache_key, $now->ymd );
1226 =head3 move_to_deleted
1228 my $is_moved = $patron->move_to_deleted;
1230 Move a patron to the deletedborrowers table.
1231 This can be done before deleting a patron, to make sure the data are not completely deleted.
1235 sub move_to_deleted {
1237 my $patron_infos = $self->unblessed;
1238 delete $patron_infos->{updated_on}; #This ensures the updated_on date in deletedborrowers will be set to the current timestamp
1239 return Koha::Database->new->schema->resultset('Deletedborrower')->create($patron_infos);
1242 =head3 can_request_article
1244 if ( $patron->can_request_article( $library->id ) ) { ... }
1246 Returns true if the patron can request articles. As limits apply for the patron
1247 on the same day, those completed the same day are considered as current.
1249 A I<library_id> can be passed as parameter, falling back to userenv if absent.
1253 sub can_request_article {
1254 my ($self, $library_id) = @_;
1256 $library_id //= C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
1258 my $rule = Koha::CirculationRules->get_effective_rule(
1260 branchcode => $library_id,
1261 categorycode => $self->categorycode,
1262 rule_name => 'open_article_requests_limit'
1266 my $limit = ($rule) ? $rule->rule_value : undef;
1268 return 1 unless defined $limit;
1270 my $count = Koha::ArticleRequests->search(
1271 [ { borrowernumber => $self->borrowernumber, status => [ 'REQUESTED', 'PENDING', 'PROCESSING' ] },
1272 { borrowernumber => $self->borrowernumber, status => 'COMPLETED', updated_on => { '>=' => \'CAST(NOW() AS DATE)' } },
1275 return $count < $limit ? 1 : 0;
1278 =head3 article_request_fee
1280 my $fee = $patron->article_request_fee(
1282 [ library_id => $library->id, ]
1286 Returns the fee to be charged to the patron when it places an article request.
1288 A I<library_id> can be passed as parameter, falling back to userenv if absent.
1292 sub article_request_fee {
1293 my ($self, $params) = @_;
1295 my $library_id = $params->{library_id};
1297 $library_id //= C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
1299 my $rule = Koha::CirculationRules->get_effective_rule(
1301 branchcode => $library_id,
1302 categorycode => $self->categorycode,
1303 rule_name => 'article_request_fee'
1307 my $fee = ($rule) ? $rule->rule_value + 0 : 0;
1312 =head3 add_article_request_fee_if_needed
1314 my $fee = $patron->add_article_request_fee_if_needed(
1316 [ item_id => $item->id,
1317 library_id => $library->id, ]
1321 If an article request fee needs to be charged, it adds a debit to the patron's
1324 Returns the fee line.
1326 A I<library_id> can be passed as parameter, falling back to userenv if absent.
1330 sub add_article_request_fee_if_needed {
1331 my ($self, $params) = @_;
1333 my $library_id = $params->{library_id};
1334 my $item_id = $params->{item_id};
1336 $library_id //= C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
1338 my $amount = $self->article_request_fee(
1340 library_id => $library_id,
1346 if ( $amount > 0 ) {
1347 $debit_line = $self->account->add_debit(
1350 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
1351 interface => C4::Context->interface,
1352 library_id => $library_id,
1353 type => 'ARTICLE_REQUEST',
1354 item_id => $item_id,
1362 =head3 article_requests
1364 my $article_requests = $patron->article_requests;
1366 Returns the patron article requests.
1370 sub article_requests {
1373 return Koha::ArticleRequests->_new_from_dbic( scalar $self->_result->article_requests );
1376 =head3 add_enrolment_fee_if_needed
1378 my $enrolment_fee = $patron->add_enrolment_fee_if_needed($renewal);
1380 Add enrolment fee for a patron if needed.
1382 $renewal - boolean denoting whether this is an account renewal or not
1386 sub add_enrolment_fee_if_needed {
1387 my ($self, $renewal) = @_;
1388 my $enrolment_fee = $self->category->enrolmentfee;
1389 if ( $enrolment_fee && $enrolment_fee > 0 ) {
1390 my $type = $renewal ? 'ACCOUNT_RENEW' : 'ACCOUNT';
1391 $self->account->add_debit(
1393 amount => $enrolment_fee,
1394 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
1395 interface => C4::Context->interface,
1396 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
1401 return $enrolment_fee || 0;
1406 my $checkouts = $patron->checkouts
1412 my $checkouts = $self->_result->issues;
1413 return Koha::Checkouts->_new_from_dbic( $checkouts );
1416 =head3 pending_checkouts
1418 my $pending_checkouts = $patron->pending_checkouts
1420 This method will return the same as $self->checkouts, but with a prefetch on
1421 items, biblio and biblioitems.
1423 It has been introduced to replaced the C4::Members::GetPendingIssues subroutine
1425 It should not be used directly, prefer to access fields you need instead of
1426 retrieving all these fields in one go.
1430 sub pending_checkouts {
1432 my $checkouts = $self->_result->issues->search(
1436 { -desc => 'me.timestamp' },
1437 { -desc => 'issuedate' },
1438 { -desc => 'issue_id' }, # Sort by issue_id should be enough
1440 prefetch => { item => { biblio => 'biblioitems' } },
1443 return Koha::Checkouts->_new_from_dbic( $checkouts );
1446 =head3 old_checkouts
1448 my $old_checkouts = $patron->old_checkouts
1454 my $old_checkouts = $self->_result->old_issues;
1455 return Koha::Old::Checkouts->_new_from_dbic( $old_checkouts );
1460 my $overdue_items = $patron->overdues
1462 Return the overdue items
1468 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
1469 return $self->checkouts->search(
1471 'me.date_due' => { '<' => $dtf->format_datetime(dt_from_string) },
1474 prefetch => { item => { biblio => 'biblioitems' } },
1482 my $restrictions = $patron->restrictions;
1484 Returns the patron restrictions.
1490 my $restrictions_rs = $self->_result->restrictions;
1491 return Koha::Patron::Restrictions->_new_from_dbic($restrictions_rs);
1494 =head3 get_routing_lists
1496 my $routinglists = $patron->get_routing_lists
1498 Returns the routing lists a patron is subscribed to.
1502 sub get_routing_lists {
1504 my $routing_list_rs = $self->_result->subscriptionroutinglists;
1505 return Koha::Subscription::Routinglists->_new_from_dbic($routing_list_rs);
1510 my $age = $patron->get_age
1512 Return the age of the patron
1519 return unless $self->dateofbirth;
1521 #Set timezone to floating to avoid any datetime math issues caused by DST
1522 my $date_of_birth = dt_from_string( $self->dateofbirth, undef, 'floating' );
1523 my $today = dt_from_string(undef, undef, 'floating')->truncate( to => 'day' );
1525 return $today->subtract_datetime( $date_of_birth )->years;
1530 my $is_valid = $patron->is_valid_age
1532 Return 1 if patron's age is between allowed limits, returns 0 if it's not.
1538 my $age = $self->get_age;
1540 my $patroncategory = $self->category;
1541 my ($low,$high) = ($patroncategory->dateofbirthrequired, $patroncategory->upperagelimit);
1543 return (defined($age) && (($high && ($age > $high)) or ($low && ($age < $low)))) ? 0 : 1;
1548 my $account = $patron->account
1554 return Koha::Account->new( { patron_id => $self->borrowernumber } );
1559 my $holds = $patron->holds
1561 Return all the holds placed by this patron
1567 my $holds_rs = $self->_result->reserves->search( {}, { order_by => 'reservedate' } );
1568 return Koha::Holds->_new_from_dbic($holds_rs);
1573 my $old_holds = $patron->old_holds
1575 Return all the historical holds for this patron
1581 my $old_holds_rs = $self->_result->old_reserves->search( {}, { order_by => 'reservedate' } );
1582 return Koha::Old::Holds->_new_from_dbic($old_holds_rs);
1585 =head3 curbside_pickups
1587 my $curbside_pickups = $patron->curbside_pickups;
1589 Return all the curbside pickups for this patron
1593 sub curbside_pickups {
1595 my $curbside_pickups_rs = $self->_result->curbside_pickups_borrowernumbers->search;
1596 return Koha::CurbsidePickups->_new_from_dbic($curbside_pickups_rs);
1599 =head3 return_claims
1601 my $return_claims = $patron->return_claims
1607 my $return_claims = $self->_result->return_claims_borrowernumbers;
1608 return Koha::Checkouts::ReturnClaims->_new_from_dbic( $return_claims );
1611 =head3 notice_email_address
1613 my $email = $patron->notice_email_address;
1615 Return the email address of patron used for notices.
1616 Returns the empty string if no email address.
1620 sub notice_email_address{
1623 my $which_address = C4::Context->preference("EmailFieldPrimary");
1624 # if syspref is set to 'first valid' (value == OFF), look up email address
1625 if ( $which_address eq 'OFF' ) {
1626 return $self->first_valid_email_address;
1629 return $self->$which_address || '';
1632 =head3 first_valid_email_address
1634 my $first_valid_email_address = $patron->first_valid_email_address
1636 Return the first valid email address for a patron.
1637 For now, the order is defined as email, emailpro, B_email.
1638 Returns the empty string if the borrower has no email addresses.
1642 sub first_valid_email_address {
1647 my @fields = split /\s*\|\s*/,
1648 C4::Context->preference('EmailFieldPrecedence');
1649 for my $field (@fields) {
1650 $email = $self->$field;
1657 =head3 get_club_enrollments
1661 sub get_club_enrollments {
1664 return Koha::Club::Enrollments->search( { borrowernumber => $self->borrowernumber(), date_canceled => undef } );
1667 =head3 get_enrollable_clubs
1671 sub get_enrollable_clubs {
1672 my ( $self, $is_enrollable_from_opac ) = @_;
1675 $params->{is_enrollable_from_opac} = $is_enrollable_from_opac
1676 if $is_enrollable_from_opac;
1677 $params->{is_email_required} = 0 unless $self->first_valid_email_address();
1679 $params->{borrower} = $self;
1681 return Koha::Clubs->get_enrollable($params);
1685 =head3 get_lists_with_patron
1687 my @lists = $patron->get_lists_with_patron;
1689 FIXME: This method returns a DBIC resultset instead of a Koha::Objects-based
1694 sub get_lists_with_patron {
1696 my $borrowernumber = $self->borrowernumber;
1698 return Koha::Database->new()->schema()->resultset('PatronList')->search(
1700 'patron_list_patrons.borrowernumber' => $borrowernumber,
1703 join => 'patron_list_patrons',
1710 =head3 account_locked
1712 my $is_locked = $patron->account_locked
1714 Return true if the patron has reached the maximum number of login attempts
1715 (see pref FailedLoginAttempts). If login_attempts is < 0, this is interpreted
1716 as an administrative lockout (independent of FailedLoginAttempts; see also
1717 Koha::Patron->lock).
1718 Otherwise return false.
1719 If the pref is not set (empty string, null or 0), the feature is considered as
1724 sub account_locked {
1726 my $FailedLoginAttempts = C4::Context->preference('FailedLoginAttempts');
1727 return 1 if $FailedLoginAttempts
1728 and $self->login_attempts
1729 and $self->login_attempts >= $FailedLoginAttempts;
1730 return 1 if ($self->login_attempts || 0) < 0; # administrative lockout
1734 =head3 can_see_patron_infos
1736 my $can_see = $patron->can_see_patron_infos( $patron );
1738 Return true if the patron (usually the logged in user) can see the patron's infos for a given patron
1742 sub can_see_patron_infos {
1743 my ( $self, $patron ) = @_;
1744 return unless $patron;
1745 return $self->can_see_patrons_from( $patron->branchcode );
1748 =head3 can_see_patrons_from
1750 my $can_see = $patron->can_see_patrons_from( $branchcode );
1752 Return true if the patron (usually the logged in user) can see the patron's infos from a given library
1756 sub can_see_patrons_from {
1757 my ( $self, $branchcode ) = @_;
1759 return $self->can_see_things_from(
1761 branchcode => $branchcode,
1762 permission => 'borrowers',
1763 subpermission => 'view_borrower_infos_from_any_libraries',
1768 =head3 can_edit_items_from
1770 my $can_edit = $patron->can_edit_items_from( $branchcode );
1772 Return true if the I<Koha::Patron> can edit items from the given branchcode
1776 sub can_edit_items_from {
1777 my ( $self, $branchcode ) = @_;
1779 return 1 if C4::Context->IsSuperLibrarian();
1781 my $userenv = C4::Context->userenv();
1782 if ( $userenv && C4::Context->preference('IndependentBranches') ) {
1783 return $userenv->{branch} eq $branchcode;
1786 return $self->can_see_things_from(
1788 branchcode => $branchcode,
1789 permission => 'editcatalogue',
1790 subpermission => 'edit_any_item',
1795 =head3 libraries_where_can_edit_items
1797 my $libraries = $patron->libraries_where_can_edit_items;
1799 Return the list of branchcodes(!) of libraries the patron is allowed to items for.
1800 The branchcodes are arbitrarily returned sorted.
1801 We are supposing here that the object is related to the logged in patron (use of C4::Context::only_my_library)
1803 An empty array means no restriction, the user can edit any item.
1807 sub libraries_where_can_edit_items {
1810 return $self->libraries_where_can_see_things(
1812 permission => 'editcatalogue',
1813 subpermission => 'edit_any_item',
1814 group_feature => 'ft_limit_item_editing',
1819 =head3 libraries_where_can_see_patrons
1821 my $libraries = $patron->libraries_where_can_see_patrons;
1823 Return the list of branchcodes(!) of libraries the patron is allowed to see other patron's infos.
1824 The branchcodes are arbitrarily returned sorted.
1825 We are supposing here that the object is related to the logged in patron (use of C4::Context::only_my_library)
1827 An empty array means no restriction, the patron can see patron's infos from any libraries.
1831 sub libraries_where_can_see_patrons {
1834 return $self->libraries_where_can_see_things(
1836 permission => 'borrowers',
1837 subpermission => 'view_borrower_infos_from_any_libraries',
1838 group_feature => 'ft_hide_patron_info',
1843 =head3 can_see_things_from
1845 my $can_see = $patron->can_see_things_from( $branchcode );
1847 Return true if the I<Koha::Patron> can perform some action on the given thing
1851 sub can_see_things_from {
1852 my ( $self, $params ) = @_;
1854 my $branchcode = $params->{branchcode};
1855 my $permission = $params->{permission};
1856 my $subpermission = $params->{subpermission};
1858 return 1 if C4::Context->IsSuperLibrarian();
1861 if ( $self->branchcode eq $branchcode ) {
1863 } elsif ( $self->has_permission( { $permission => $subpermission } ) ) {
1865 } elsif ( my @branches = $self->libraries_where_can_see_patrons ) {
1866 $can = ( any { $_ eq $branchcode } @branches ) ? 1 : 0;
1873 my $can_log_into = $patron->can_log_into( $library );
1875 Given a I<Koha::Library> object, it returns a boolean representing
1876 the fact the patron can log into a the library.
1881 my ( $self, $library ) = @_;
1885 if ( C4::Context->preference('IndependentBranches') ) {
1887 if $self->is_superlibrarian
1888 or $self->branchcode eq $library->id;
1898 =head3 libraries_where_can_see_things
1900 my $libraries = $patron->libraries_where_can_see_things;
1902 Returns a list of libraries where an aribitarary action is allowed to be taken by the logged in librarian
1903 against an object based on some branchcode related to the object ( patron branchcode, item homebranch, etc ).
1905 We are supposing here that the object is related to the logged in librarian (use of C4::Context::only_my_library)
1907 An empty array means no restriction, the thing can see thing's infos from any libraries.
1911 sub libraries_where_can_see_things {
1912 my ( $self, $params ) = @_;
1913 my $permission = $params->{permission};
1914 my $subpermission = $params->{subpermission};
1915 my $group_feature = $params->{group_feature};
1917 return $self->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"}
1918 if exists( $self->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} );
1920 my $userenv = C4::Context->userenv;
1922 return () unless $userenv; # For tests, but userenv should be defined in tests...
1924 my @restricted_branchcodes;
1925 if (C4::Context::only_my_library) {
1926 push @restricted_branchcodes, $self->branchcode;
1930 $self->has_permission(
1931 { $permission => $subpermission }
1935 my $library_groups = $self->library->library_groups({ $group_feature => 1 });
1936 if ( $library_groups->count )
1938 while ( my $library_group = $library_groups->next ) {
1939 my $parent = $library_group->parent;
1940 if ( $parent->has_child( $self->branchcode ) ) {
1941 push @restricted_branchcodes, $parent->children->get_column('branchcode');
1946 @restricted_branchcodes = ( $self->branchcode ) unless @restricted_branchcodes;
1950 @restricted_branchcodes = grep { defined $_ } @restricted_branchcodes;
1951 @restricted_branchcodes = uniq(@restricted_branchcodes);
1952 @restricted_branchcodes = sort(@restricted_branchcodes);
1954 $self->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} = \@restricted_branchcodes;
1955 return @{ $self->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} };
1958 =head3 has_permission
1960 my $permission = $patron->has_permission($required);
1962 See C4::Auth::haspermission for details of syntax for $required
1966 sub has_permission {
1967 my ( $self, $flagsrequired ) = @_;
1968 return unless $self->userid;
1969 # TODO code from haspermission needs to be moved here!
1970 return C4::Auth::haspermission( $self->userid, $flagsrequired );
1973 =head3 is_superlibrarian
1975 my $is_superlibrarian = $patron->is_superlibrarian;
1977 Return true if the patron is a superlibrarian.
1981 sub is_superlibrarian {
1983 return $self->has_permission( { superlibrarian => 1 } ) ? 1 : 0;
1988 my $is_adult = $patron->is_adult
1990 Return true if the patron has a category with a type Adult (A) or Organization (I)
1996 return $self->category->category_type =~ /^(A|I)$/ ? 1 : 0;
2001 my $is_child = $patron->is_child
2003 Return true if the patron has a category with a type Child (C)
2009 return $self->category->category_type eq 'C' ? 1 : 0;
2012 =head3 has_valid_userid
2014 my $patron = Koha::Patrons->find(42);
2015 $patron->userid( $new_userid );
2016 my $has_a_valid_userid = $patron->has_valid_userid
2018 my $patron = Koha::Patron->new( $params );
2019 my $has_a_valid_userid = $patron->has_valid_userid
2021 Return true if the current userid of this patron is valid/unique, otherwise false.
2023 Note that this should be done in $self->store instead and raise an exception if needed.
2027 sub has_valid_userid {
2030 return 0 unless $self->userid;
2032 return 0 if ( $self->userid eq C4::Context->config('user') ); # DB user
2034 my $already_exists = Koha::Patrons->search(
2036 userid => $self->userid,
2039 ? ( borrowernumber => { '!=' => $self->borrowernumber } )
2044 return $already_exists ? 0 : 1;
2047 =head3 generate_userid
2049 $patron->generate_userid;
2051 If you do not have a plugin for generating a userid, we will call
2052 the internal method here that returns firstname.surname[.number],
2053 where number is an optional suffix to make the userid unique.
2054 (Its behavior has not been changed on bug 32426.)
2056 If you have plugin(s), the first valid response will be used.
2057 A plugin is assumed to return a valid userid as suggestion, but not
2058 assumed to save it already.
2059 Does not fallback to internal (you could arrange for that in your plugin).
2060 Clears userid when there are no valid plugin responses.
2064 sub generate_userid {
2066 my @responses = Koha::Plugins->call(
2067 'patron_generate_userid', { patron => $self },
2069 unless( @responses ) {
2070 # Empty list only possible when there are NO enabled plugins for this method.
2071 # In that case we provide internal response.
2072 return $self->_generate_userid_internal;
2074 # If a plugin returned false value or invalid value, we do however not return
2075 # internal response. The plugins should deal with that themselves. So we prevent
2076 # unexpected/unwelcome internal codes for plugin failures.
2077 foreach my $response ( grep { $_ } @responses ) {
2078 $self->userid( $response );
2079 return $self if $self->has_valid_userid;
2081 $self->userid(undef);
2085 sub _generate_userid_internal { # as we always did
2088 my $firstname = $self->firstname // q{};
2089 my $surname = $self->surname // q{};
2090 #The script will "do" the following code and increment the $offset until the generated userid is unique
2092 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
2093 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
2094 my $userid = lc(($firstname)? "$firstname.$surname" : $surname);
2095 $userid = NFKD( $userid );
2096 $userid =~ s/\p{NonspacingMark}//g;
2097 $userid .= $offset unless $offset == 0;
2098 $self->userid( $userid );
2100 } while (! $self->has_valid_userid );
2105 =head3 add_extended_attribute
2109 sub add_extended_attribute {
2110 my ($self, $attribute) = @_;
2112 return Koha::Patron::Attribute->new(
2115 ( borrowernumber => $self->borrowernumber ),
2121 =head3 extended_attributes
2123 Return object of Koha::Patron::Attributes type with all attributes set for this patron
2129 sub extended_attributes {
2130 my ( $self, $attributes ) = @_;
2131 if ($attributes) { # setter
2132 my $schema = $self->_result->result_source->schema;
2135 # Remove the existing one
2136 $self->extended_attributes->filter_by_branch_limitations->delete;
2138 # Insert the new ones
2140 for my $attribute (@$attributes) {
2141 $self->add_extended_attribute($attribute);
2142 $new_types->{$attribute->{code}} = 1;
2145 # Check globally mandatory types
2146 my @required_attribute_types =
2147 Koha::Patron::Attribute::Types->search(
2150 category_code => [ undef, $self->categorycode ],
2151 'borrower_attribute_types_branches.b_branchcode' =>
2154 { join => 'borrower_attribute_types_branches' }
2155 )->get_column('code');
2156 for my $type ( @required_attribute_types ) {
2157 Koha::Exceptions::Patron::MissingMandatoryExtendedAttribute->throw(
2159 ) if !$new_types->{$type};
2165 my $rs = $self->_result->borrower_attributes;
2166 # We call search to use the filters in Koha::Patron::Attributes->search
2167 return Koha::Patron::Attributes->_new_from_dbic($rs)->search;
2172 my $messages = $patron->messages;
2174 Return the message attached to the patron.
2180 my $messages_rs = $self->_result->messages_borrowernumbers->search;
2181 return Koha::Patron::Messages->_new_from_dbic($messages_rs);
2186 Koha::Patrons->find($id)->lock({ expire => 1, remove => 1 });
2188 Lock and optionally expire a patron account.
2189 Remove holds and article requests if remove flag set.
2190 In order to distinguish from locking by entering a wrong password, let's
2191 call this an administrative lockout.
2196 my ( $self, $params ) = @_;
2197 $self->login_attempts( ADMINISTRATIVE_LOCKOUT );
2198 if( $params->{expire} ) {
2199 $self->dateexpiry( dt_from_string->subtract(days => 1) );
2202 if( $params->{remove} ) {
2203 $self->holds->delete;
2204 $self->article_requests->delete;
2211 Koha::Patrons->find($id)->anonymize;
2213 Anonymize or clear borrower fields. Fields in BorrowerMandatoryField
2214 are randomized, other personal data is cleared too.
2215 Patrons with issues are skipped.
2221 if( $self->_result->issues->count ) {
2222 warn "Exiting anonymize: patron ".$self->borrowernumber." still has issues";
2225 # Mandatory fields come from the corresponding pref, but email fields
2226 # are removed since scrambled email addresses only generate errors
2227 my $mandatory = { map { (lc $_, 1); } grep { !/email/ }
2228 split /\s*\|\s*/, C4::Context->preference('BorrowerMandatoryField') };
2229 $mandatory->{userid} = 1; # needed since sub store does not clear field
2230 my @columns = $self->_result->result_source->columns;
2231 @columns = grep { !/borrowernumber|branchcode|categorycode|^date|password|flags|updated_on|lastseen|lang|login_attempts|anonymized|auth_method/ } @columns;
2232 push @columns, 'dateofbirth'; # add this date back in
2233 foreach my $col (@columns) {
2234 $self->_anonymize_column($col, $mandatory->{lc $col} );
2236 $self->anonymized(1)->store;
2239 sub _anonymize_column {
2240 my ( $self, $col, $mandatory ) = @_;
2241 my $col_info = $self->_result->result_source->column_info($col);
2242 my $type = $col_info->{data_type};
2243 my $nullable = $col_info->{is_nullable};
2245 if( $type =~ /char|text/ ) {
2247 ? Koha::Token->new->generate({ pattern => '\w{10}' })
2251 } elsif( $type =~ /integer|int$|float|dec|double/ ) {
2252 $val = $nullable ? undef : 0;
2253 } elsif( $type =~ /date|time/ ) {
2254 $val = $nullable ? undef : dt_from_string;
2259 =head3 add_guarantor
2261 my $relationship = $patron->add_guarantor(
2263 borrowernumber => $borrowernumber,
2264 relationships => $relationship,
2268 Adds a new guarantor to a patron.
2273 my ( $self, $params ) = @_;
2275 my $guarantor_id = $params->{guarantor_id};
2276 my $relationship = $params->{relationship};
2278 return Koha::Patron::Relationship->new(
2280 guarantee_id => $self->id,
2281 guarantor_id => $guarantor_id,
2282 relationship => $relationship
2287 =head3 get_extended_attribute
2289 my $attribute_value = $patron->get_extended_attribute( $code );
2291 Return the attribute for the code passed in parameter.
2293 It not exist it returns undef
2295 Note that this will not work for repeatable attribute types.
2297 Maybe you certainly not want to use this method, it is actually only used for SHOW_BARCODE
2298 (which should be a real patron's attribute (not extended)
2302 sub get_extended_attribute {
2303 my ( $self, $code, $value ) = @_;
2304 my $rs = $self->_result->borrower_attributes;
2306 my $attribute = $rs->search({ code => $code, ( $value ? ( attribute => $value ) : () ) });
2307 return unless $attribute->count;
2308 return $attribute->next;
2311 =head3 set_default_messaging_preferences
2313 $patron->set_default_messaging_preferences
2315 Sets default messaging preferences on patron.
2317 See Koha::Patron::MessagePreference(s) for more documentation, especially on
2322 sub set_default_messaging_preferences {
2323 my ($self, $categorycode) = @_;
2325 my $options = Koha::Patron::MessagePreferences->get_options;
2327 foreach my $option (@$options) {
2328 # Check that this option has preference configuration for this category
2329 unless (Koha::Patron::MessagePreferences->search({
2330 message_attribute_id => $option->{message_attribute_id},
2331 categorycode => $categorycode || $self->categorycode,
2336 # Delete current setting
2337 Koha::Patron::MessagePreferences->search({
2338 borrowernumber => $self->borrowernumber,
2339 message_attribute_id => $option->{message_attribute_id},
2342 Koha::Patron::MessagePreference->new_from_default({
2343 borrowernumber => $self->borrowernumber,
2344 categorycode => $categorycode || $self->categorycode,
2345 message_attribute_id => $option->{message_attribute_id},
2352 =head3 is_accessible
2354 if ( $patron->is_accessible({ user => $logged_in_user }) ) { ... }
2356 This overloaded method validates whether the current I<Koha::Patron> object can be accessed
2357 by the logged in user.
2359 Returns 0 if the I<user> parameter is missing.
2364 my ( $self, $params ) = @_;
2366 unless ( defined( $params->{user} ) ) {
2367 Koha::Exceptions::MissingParameter->throw( error => "The `user` parameter is mandatory" );
2370 my $consumer = $params->{user};
2371 return $consumer->can_see_patron_infos($self);
2374 =head3 unredact_list
2376 This method returns the list of database fields that should be visible, even for restricted users,
2377 for both API and UI output purposes
2382 return ['branchcode'];
2387 my $json = $patron->to_api;
2389 Overloaded method that returns a JSON representation of the Koha::Patron object,
2390 suitable for API output.
2395 my ( $self, $params ) = @_;
2397 my $json_patron = $self->SUPER::to_api( $params );
2399 return unless $json_patron;
2401 $json_patron->{restricted} = ( $self->is_debarred )
2403 : Mojo::JSON->false;
2405 return $json_patron;
2408 =head3 to_api_mapping
2410 This method returns the mapping for representing a Koha::Patron object
2415 sub to_api_mapping {
2417 borrowernotes => 'staff_notes',
2418 borrowernumber => 'patron_id',
2419 branchcode => 'library_id',
2420 categorycode => 'category_id',
2421 checkprevcheckout => 'check_previous_checkout',
2422 contactfirstname => undef, # Unused
2423 contactname => undef, # Unused
2424 contactnote => 'altaddress_notes',
2425 contacttitle => undef, # Unused
2426 dateenrolled => 'date_enrolled',
2427 dateexpiry => 'expiry_date',
2428 dateofbirth => 'date_of_birth',
2429 debarred => undef, # replaced by 'restricted'
2430 debarredcomment => undef, # calculated, API consumers will use /restrictions instead
2431 emailpro => 'secondary_email',
2432 flags => undef, # permissions manipulation handled in /permissions
2433 gonenoaddress => 'incorrect_address',
2434 lastseen => 'last_seen',
2435 lost => 'patron_card_lost',
2436 opacnote => 'opac_notes',
2437 othernames => 'other_name',
2438 password => undef, # password manipulation handled in /password
2439 phonepro => 'secondary_phone',
2440 relationship => 'relationship_type',
2442 smsalertnumber => 'sms_number',
2443 sort1 => 'statistics_1',
2444 sort2 => 'statistics_2',
2445 autorenew_checkouts => 'autorenew_checkouts',
2446 streetnumber => 'street_number',
2447 streettype => 'street_type',
2448 zipcode => 'postal_code',
2449 B_address => 'altaddress_address',
2450 B_address2 => 'altaddress_address2',
2451 B_city => 'altaddress_city',
2452 B_country => 'altaddress_country',
2453 B_email => 'altaddress_email',
2454 B_phone => 'altaddress_phone',
2455 B_state => 'altaddress_state',
2456 B_streetnumber => 'altaddress_street_number',
2457 B_streettype => 'altaddress_street_type',
2458 B_zipcode => 'altaddress_postal_code',
2459 altcontactaddress1 => 'altcontact_address',
2460 altcontactaddress2 => 'altcontact_address2',
2461 altcontactaddress3 => 'altcontact_city',
2462 altcontactcountry => 'altcontact_country',
2463 altcontactfirstname => 'altcontact_firstname',
2464 altcontactphone => 'altcontact_phone',
2465 altcontactsurname => 'altcontact_surname',
2466 altcontactstate => 'altcontact_state',
2467 altcontactzipcode => 'altcontact_postal_code',
2468 password_expiration_date => undef,
2469 primary_contact_method => undef,
2471 auth_method => undef,
2477 Koha::Patrons->queue_notice({ letter_params => $letter_params, message_name => 'DUE'});
2478 Koha::Patrons->queue_notice({ letter_params => $letter_params, message_transports => \@message_transports });
2479 Koha::Patrons->queue_notice({ letter_params => $letter_params, message_transports => \@message_transports, test_mode => 1 });
2481 Queue messages to a patron. Can pass a message that is part of the message_attributes
2482 table or supply the transport to use.
2484 If passed a message name we retrieve the patrons preferences for transports
2485 Otherwise we use the supplied transport. In the case of email or sms we fall back to print if
2486 we have no address/number for sending
2488 $letter_params is a hashref of the values to be passed to GetPreparedLetter
2490 test_mode will only report which notices would be sent, but nothing will be queued
2495 my ( $self, $params ) = @_;
2496 my $letter_params = $params->{letter_params};
2497 my $test_mode = $params->{test_mode};
2499 return unless $letter_params;
2500 return unless exists $params->{message_name} xor $params->{message_transports}; # We only want one of these
2502 my $library = Koha::Libraries->find( $letter_params->{branchcode} );
2503 my $from_email_address = $library->from_email_address;
2505 my @message_transports;
2507 $letter_code = $letter_params->{letter_code};
2508 if( $params->{message_name} ){
2509 my $messaging_prefs = C4::Members::Messaging::GetMessagingPreferences( {
2510 borrowernumber => $letter_params->{borrowernumber},
2511 message_name => $params->{message_name}
2513 @message_transports = ( keys %{ $messaging_prefs->{transports} } );
2514 $letter_code = $messaging_prefs->{transports}->{$message_transports[0]} unless $letter_code;
2516 @message_transports = @{$params->{message_transports}};
2518 return unless defined $letter_code;
2519 $letter_params->{letter_code} = $letter_code;
2522 foreach my $mtt (@message_transports){
2523 next if ($mtt eq 'itiva' and C4::Context->preference('TalkingTechItivaPhoneNotification') );
2524 # Notice is handled by TalkingTech_itiva_outbound.pl
2525 if ( ( $mtt eq 'email' and not $self->notice_email_address )
2526 or ( $mtt eq 'sms' and not $self->smsalertnumber )
2527 or ( $mtt eq 'phone' and not $self->phone ) )
2529 push @{ $return{fallback} }, $mtt;
2532 next if $mtt eq 'print' && $print_sent;
2533 $letter_params->{message_transport_type} = $mtt;
2534 my $letter = C4::Letters::GetPreparedLetter( %$letter_params );
2535 C4::Letters::EnqueueLetter({
2537 borrowernumber => $self->borrowernumber,
2538 from_address => $from_email_address,
2539 message_transport_type => $mtt
2540 }) unless $test_mode;
2541 push @{$return{sent}}, $mtt;
2542 $print_sent = 1 if $mtt eq 'print';
2547 =head3 safe_to_delete
2549 my $result = $patron->safe_to_delete;
2550 if ( $result eq 'has_guarantees' ) { ... }
2551 elsif ( $result ) { ... }
2552 else { # cannot delete }
2554 This method tells if the Koha:Patron object can be deleted. Possible return values
2560 =item 'has_checkouts'
2564 =item 'has_guarantees'
2566 =item 'is_anonymous_patron'
2568 =item 'is_protected'
2574 sub safe_to_delete {
2577 my $anonymous_patron = C4::Context->preference('AnonymousPatron');
2581 if ( $anonymous_patron && $self->id eq $anonymous_patron ) {
2582 $error = 'is_anonymous_patron';
2584 elsif ( $self->checkouts->count ) {
2585 $error = 'has_checkouts';
2587 elsif ( $self->account->outstanding_debits->total_outstanding > 0 ) {
2588 $error = 'has_debt';
2590 elsif ( $self->guarantee_relationships->count ) {
2591 $error = 'has_guarantees';
2593 elsif ( $self->protected ) {
2594 $error = 'is_protected';
2598 return Koha::Result::Boolean->new(0)->add_message({ message => $error });
2601 return Koha::Result::Boolean->new(1);
2606 my $recalls = $patron->recalls;
2608 Return the patron's recalls.
2615 return Koha::Recalls->search({ patron_id => $self->borrowernumber });
2618 =head3 account_balance
2620 my $balance = $patron->account_balance
2622 Return the patron's account balance
2626 sub account_balance {
2628 return $self->account->balance;
2631 =head3 notify_library_of_registration
2633 $patron->notify_library_of_registration( $email_patron_registrations );
2635 Send patron registration email to library if EmailPatronRegistrations system preference is enabled.
2639 sub notify_library_of_registration {
2640 my ( $self, $email_patron_registrations ) = @_;
2643 my $letter = C4::Letters::GetPreparedLetter(
2644 module => 'members',
2645 letter_code => 'OPAC_REG',
2646 branchcode => $self->branchcode,
2647 lang => $self->lang || 'default',
2649 'borrowers' => $self->borrowernumber
2654 if ( $email_patron_registrations eq "BranchEmailAddress" ) {
2655 my $library = Koha::Libraries->find( $self->branchcode );
2656 $to_address = $library->inbound_email_address;
2658 elsif ( $email_patron_registrations eq "KohaAdminEmailAddress" ) {
2659 $to_address = C4::Context->preference('ReplytoDefault')
2660 || C4::Context->preference('KohaAdminEmailAddress');
2664 C4::Context->preference('EmailAddressForPatronRegistrations')
2665 || C4::Context->preference('ReplytoDefault')
2666 || C4::Context->preference('KohaAdminEmailAddress');
2669 my $message_id = C4::Letters::EnqueueLetter(
2672 borrowernumber => $self->borrowernumber,
2673 to_address => $to_address,
2674 message_transport_type => 'email'
2676 ) or warn "can't enqueue letter $letter";
2677 if ( $message_id ) {
2683 =head3 has_messaging_preference
2685 my $bool = $patron->has_messaging_preference({
2686 message_name => $message_name, # A value from message_attributes.message_name
2687 message_transport_type => $message_transport_type, # email, sms, phone, itiva, etc...
2688 wants_digest => $wants_digest, # 1 if you are looking for the digest version, don't pass if you just want either
2693 sub has_messaging_preference {
2694 my ( $self, $params ) = @_;
2696 my $message_name = $params->{message_name};
2697 my $message_transport_type = $params->{message_transport_type};
2698 my $wants_digest = $params->{wants_digest};
2700 return $self->_result->search_related_rs(
2701 'borrower_message_preferences',
2705 [ 'borrower_message_transport_preferences', 'message_attribute' ]
2710 =head3 can_patron_change_staff_only_lists
2712 $patron->can_patron_change_staff_only_lists;
2714 Return 1 if a patron has 'Superlibrarian' or 'Catalogue' permission.
2715 Otherwise, return 0.
2719 sub can_patron_change_staff_only_lists {
2720 my ( $self, $params ) = @_;
2721 return 1 if C4::Auth::haspermission( $self->userid, { 'catalogue' => 1 });
2725 =head3 can_patron_change_permitted_staff_lists
2727 $patron->can_patron_change_permitted_staff_lists;
2729 Return 1 if a patron has 'Superlibrarian' or 'Catalogue' and 'edit_public_list_contents' permissions.
2730 Otherwise, return 0.
2734 sub can_patron_change_permitted_staff_lists {
2735 my ( $self, $params ) = @_;
2736 return 1 if C4::Auth::haspermission( $self->userid, { 'catalogue' => 1, lists => 'edit_public_list_contents' } );
2740 =head3 encode_secret
2742 $patron->encode_secret($secret32);
2744 Secret (TwoFactorAuth expects it in base32 format) is encrypted.
2745 You still need to call ->store.
2750 my ( $self, $secret ) = @_;
2752 return $self->secret( Koha::Encryption->new->encrypt_hex($secret) );
2754 return $self->secret($secret);
2757 =head3 decoded_secret
2759 my $secret32 = $patron->decoded_secret;
2761 Decode the patron secret. We expect to get back a base32 string, but this
2762 is not checked here. Caller of encode_secret is responsible for that.
2766 sub decoded_secret {
2768 if( $self->secret ) {
2769 return Koha::Encryption->new->decrypt_hex( $self->secret );
2771 return $self->secret;
2774 =head3 virtualshelves
2776 my $shelves = $patron->virtualshelves;
2780 sub virtualshelves {
2782 return Koha::Virtualshelves->_new_from_dbic( scalar $self->_result->virtualshelves );
2787 my $savings = $patron->get_savings;
2789 Use the replacement price of patron's old and current issues to calculate how much they have 'saved' by using the library.
2796 my @itemnumbers = grep { defined $_ } ( $self->old_checkouts->get_column('itemnumber'), $self->checkouts->get_column('itemnumber') );
2798 return Koha::Items->search(
2799 { itemnumber => { -in => \@itemnumbers } },
2800 { select => [ { sum => 'me.replacementprice' } ],
2801 as => ['total_savings']
2803 )->next->get_column('total_savings') // 0;
2806 =head3 alert_subscriptions
2808 my $subscriptions = $patron->alert_subscriptions;
2810 Return a Koha::Subscriptions object containing subscriptions for which the patron has subscribed to email alerts.
2814 sub alert_subscriptions {
2817 my @alerts = $self->_result->alerts;
2818 my @subscription_ids = map { $_->externalid } @alerts;
2820 return Koha::Subscriptions->search( { subscriptionid => \@subscription_ids } );
2825 my $consent = $patron->consent(TYPE);
2827 Returns the first consent of type TYPE (there should be only one) or a new instance
2828 of Koha::Patron::Consent.
2833 my ( $self, $type ) = @_;
2834 Koha::Exceptions::MissingParameter->throw('Missing consent type') if !$type;
2835 my $consents = Koha::Patron::Consents->search(
2837 borrowernumber => $self->borrowernumber,
2841 return $consents && $consents->count
2843 : Koha::Patron::Consent->new( { borrowernumber => $self->borrowernumber, type => $type } );
2846 =head2 Internal methods
2858 Kyle M Hall <kyle@bywatersolutions.com>
2859 Alex Sassmannshausen <alex.sassmannshausen@ptfs-europe.com>
2860 Martin Renvoize <martin.renvoize@ptfs-europe.com>