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(
264 method => 'check_password',
267 foreach my $plugin (@plugins) {
269 # This plugin hook will also be used by a plugin for the Norwegian national
270 # patron database. This is why we need to pass both the password and the
271 # borrowernumber to the plugin.
272 my $ret = $plugin->check_password(
274 password => $self->password,
275 borrowernumber => $self->borrowernumber
278 if ( $ret->{'error'} == 1 ) {
279 Koha::Exceptions::Password::Plugin->throw();
284 # Make a copy of the plain text password for later use
285 $self->plain_text_password( $self->password );
287 $self->password_expiration_date(
289 ? $self->category->get_password_expiry_date || undef
293 # Create a disabled account if no password provided
296 ? Koha::AuthUtils::hash_password( $self->password )
300 $self->borrowernumber(undef);
302 if ( C4::Context->preference('ChildNeedsGuarantor')
303 and ( $self->is_child or $self->category->can_be_guarantee )
304 and $self->contactname eq ""
307 Koha::Exceptions::Patron::Relationship::NoGuarantor->throw();
310 foreach my $guarantor (@$guarantors) {
311 if ( $guarantor->is_child or $guarantor->category->can_be_guarantee ) {
312 Koha::Exceptions::Patron::Relationship::InvalidRelationship->throw( invalid_guarantor => 1 );
316 $self = $self->SUPER::store;
318 $self->add_enrolment_fee_if_needed(0);
320 logaction( "MEMBERS", "CREATE", $self->borrowernumber, "" )
321 if C4::Context->preference("BorrowersLog");
324 my $self_from_storage = $self->get_from_storage;
326 # Do not accept invalid userid here
327 $self->generate_userid unless $self->userid;
328 Koha::Exceptions::Patron::InvalidUserid->throw( userid => $self->userid )
329 unless $self->has_valid_userid;
331 # If a borrower has set their privacy to never we should immediately anonymize
333 if ( $self->privacy() == 2 && $self_from_storage->privacy() != 2 ) {
335 $self->old_checkouts->anonymize;
337 Koha::Exceptions::Patron::FailedAnonymizing->throw( error => @_ );
341 # Password must be updated using $self->set_password
342 $self->password( $self_from_storage->password );
344 if ( $self->category->categorycode ne $self_from_storage->category->categorycode ) {
346 # Add enrolement fee on category change if required
347 $self->add_enrolment_fee_if_needed(1)
348 if C4::Context->preference('FeeOnChangePatronCategory');
350 # Clean up guarantors on category change if required
351 $self->guarantor_relationships->delete
352 unless ( $self->category->can_be_guarantee );
356 my @existing_guarantors = $self->guarantor_relationships()->guarantors->as_list;
357 push @$guarantors, @existing_guarantors;
359 if ( C4::Context->preference('ChildNeedsGuarantor')
360 and ( $self->is_child or $self->category->can_be_guarantee )
361 and $self->contactname eq ""
364 Koha::Exceptions::Patron::Relationship::NoGuarantor->throw();
367 foreach my $guarantor (@$guarantors) {
368 if ( $guarantor->is_child or $guarantor->category->can_be_guarantee ) {
369 Koha::Exceptions::Patron::Relationship::InvalidRelationship->throw( invalid_guarantor => 1 );
374 if ( C4::Context->preference("BorrowersLog") ) {
376 my $from_storage = $self_from_storage->unblessed;
377 my $from_object = $self->unblessed;
378 my @skip_fields = (qw/lastseen updated_on/);
379 for my $key ( keys %{$from_storage} ) {
380 next if any { /$key/ } @skip_fields;
382 ( !defined( $from_storage->{$key} ) && defined( $from_object->{$key} ) )
383 || ( defined( $from_storage->{$key} )
384 && !defined( $from_object->{$key} ) )
385 || ( defined( $from_storage->{$key} )
386 && defined( $from_object->{$key} )
387 && ( $from_storage->{$key} ne $from_object->{$key} ) )
391 before => $from_storage->{$key},
392 after => $from_object->{$key}
397 if ( defined($info) ) {
401 $self->borrowernumber,
404 { utf8 => 1, pretty => 1, canonical => 1 }
411 $self = $self->SUPER::store;
422 Delete patron's holds, lists and finally the patron.
424 Lists owned by the borrower are deleted or ownership is transferred depending on the
425 ListOwnershipUponPatronDeletion pref, but entries from the borrower to other lists are kept.
432 my $anonymous_patron = C4::Context->preference("AnonymousPatron");
433 Koha::Exceptions::Patron::FailedDeleteAnonymousPatron->throw() if $anonymous_patron && $self->id eq $anonymous_patron;
435 # Check if patron is protected
436 Koha::Exceptions::Patron::FailedDeleteProtectedPatron->throw() if $self->protected == 1;
438 $self->_result->result_source->schema->txn_do(
440 # Cancel Patron's holds
441 my $holds = $self->holds;
442 while( my $hold = $holds->next ){
446 # Handle lists (virtualshelves)
447 $self->virtualshelves->disown_or_delete;
449 # We cannot have a FK on borrower_modifications.borrowernumber, the table is also used
451 $_->delete for Koha::Patron::Modifications->search( { borrowernumber => $self->borrowernumber } )->as_list;
453 $self->SUPER::delete;
455 logaction( "MEMBERS", "DELETE", $self->borrowernumber, "" ) if C4::Context->preference("BorrowersLog");
463 my $patron_category = $patron->category
465 Return the patron category for this patron
471 return Koha::Patron::Category->_new_from_dbic( $self->_result->categorycode );
481 return Koha::Patron::Images->find( $self->borrowernumber );
486 Returns a Koha::Library object representing the patron's home library.
492 return Koha::Library->_new_from_dbic($self->_result->branchcode);
497 Returns a Koha::SMS::Provider object representing the patron's SMS provider.
503 my $sms_provider_rs = $self->_result->sms_provider;
504 return unless $sms_provider_rs;
505 return Koha::SMS::Provider->_new_from_dbic($sms_provider_rs);
508 =head3 guarantor_relationships
510 Returns Koha::Patron::Relationships object for this patron's guarantors
512 Returns the set of relationships for the patrons that are guarantors for this patron.
514 Note that a guarantor should exist as a patron in Koha; it was not possible
515 to add them without a guarantor_id in the interface for some time. Bug 30472
516 restricts it on db level.
520 sub guarantor_relationships {
523 return Koha::Patron::Relationships->search( { guarantee_id => $self->id } );
526 =head3 guarantee_relationships
528 Returns Koha::Patron::Relationships object for this patron's guarantors
530 Returns the set of relationships for the patrons that are guarantees for this patron.
532 The method returns Koha::Patron::Relationship objects for the sake
533 of consistency with the guantors method.
534 A guarantee by definition must exist as a patron in Koha.
538 sub guarantee_relationships {
541 return Koha::Patron::Relationships->search(
542 { guarantor_id => $self->id },
544 prefetch => 'guarantee',
545 order_by => { -asc => [ 'guarantee.surname', 'guarantee.firstname' ] },
550 =head3 relationships_debt
552 Returns the amount owed by the patron's guarantors *and* the other guarantees of those guarantors
556 sub relationships_debt {
557 my ($self, $params) = @_;
559 my $include_guarantors = $params->{include_guarantors};
560 my $only_this_guarantor = $params->{only_this_guarantor};
561 my $include_this_patron = $params->{include_this_patron};
564 if ( $only_this_guarantor ) {
565 @guarantors = $self->guarantee_relationships->count ? ( $self ) : ();
566 Koha::Exceptions::BadParameter->throw( { parameter => 'only_this_guarantor' } ) unless @guarantors;
567 } elsif ( $self->guarantor_relationships->count ) {
568 # I am a guarantee, just get all my guarantors
569 @guarantors = $self->guarantor_relationships->guarantors->as_list;
571 # I am a guarantor, I need to get all the guarantors of all my guarantees
572 @guarantors = map { $_->guarantor_relationships->guarantors->as_list } $self->guarantee_relationships->guarantees->as_list;
575 my $non_issues_charges = 0;
576 my $seen = $include_this_patron ? {} : { $self->id => 1 }; # For tracking members already added to the total
577 foreach my $guarantor (@guarantors) {
578 $non_issues_charges += $guarantor->account->non_issues_charges if $include_guarantors && !$seen->{ $guarantor->id };
580 # We've added what the guarantor owes, not added in that guarantor's guarantees as well
581 my @guarantees = map { $_->guarantee } $guarantor->guarantee_relationships->as_list;
582 my $guarantees_non_issues_charges = 0;
583 foreach my $guarantee (@guarantees) {
584 next if $seen->{ $guarantee->id };
585 $guarantees_non_issues_charges += $guarantee->account->non_issues_charges;
586 # Mark this guarantee as seen so we don't double count a guarantee linked to multiple guarantors
587 $seen->{ $guarantee->id } = 1;
590 $non_issues_charges += $guarantees_non_issues_charges;
591 $seen->{ $guarantor->id } = 1;
594 return $non_issues_charges;
597 =head3 housebound_profile
599 Returns the HouseboundProfile associated with this patron.
603 sub housebound_profile {
605 my $profile = $self->_result->housebound_profile;
606 return Koha::Patron::HouseboundProfile->_new_from_dbic($profile)
611 =head3 housebound_role
613 Returns the HouseboundRole associated with this patron.
617 sub housebound_role {
620 my $role = $self->_result->housebound_role;
621 return Koha::Patron::HouseboundRole->_new_from_dbic($role) if ( $role );
627 Returns the siblings of this patron.
634 my @guarantors = $self->guarantor_relationships()->guarantors()->as_list;
636 return unless @guarantors;
639 map { $_->guarantee_relationships()->guarantees()->as_list } @guarantors;
641 return unless @siblings;
645 grep { !$seen{ $_->id }++ && ( $_->id != $self->id ) } @siblings;
647 return Koha::Patrons->search( { borrowernumber => { -in => [ map { $_->id } @siblings ] } } );
652 my $patron = Koha::Patrons->find($id);
653 $patron->merge_with( \@patron_ids );
655 This subroutine merges a list of patrons into the patron record. This is accomplished by finding
656 all related patron ids for the patrons to be merged in other tables and changing the ids to be that
657 of the keeper patron.
662 my ( $self, $patron_ids ) = @_;
664 my $anonymous_patron = C4::Context->preference("AnonymousPatron");
665 return if $anonymous_patron && $self->id eq $anonymous_patron;
667 # Do not merge other patrons into a protected patron
668 return if $self->protected;
670 my @patron_ids = @{ $patron_ids };
672 # Ensure the keeper isn't in the list of patrons to merge
673 @patron_ids = grep { $_ ne $self->id } @patron_ids;
675 my $schema = Koha::Database->new()->schema();
679 $self->_result->result_source->schema->txn_do( sub {
680 foreach my $patron_id (@patron_ids) {
682 next if $patron_id eq $anonymous_patron;
684 my $patron = Koha::Patrons->find( $patron_id );
688 # Do not merge protected patrons into other patrons
689 next if $patron->protected;
691 # Unbless for safety, the patron will end up being deleted
692 $results->{merged}->{$patron_id}->{patron} = $patron->unblessed;
694 my $attributes = $patron->extended_attributes;
695 my $new_attributes = [
696 map { { code => $_->code, attribute => $_->attribute } }
699 $attributes->delete; # We need to delete before trying to merge them to prevent exception on unique and repeatable
700 for my $attribute ( @$new_attributes ) {
702 $self->add_extended_attribute($attribute);
704 # Don't block the merge if there is a non-repeatable attribute that cannot be added to the current patron.
705 unless ( $_->isa('Koha::Exceptions::Patron::Attribute::NonRepeatable') ) {
711 while (my ($r, $field) = each(%$RESULTSET_PATRON_ID_MAPPING)) {
712 my $rs = $schema->resultset($r)->search({ $field => $patron_id });
713 $results->{merged}->{ $patron_id }->{updated}->{$r} = $rs->count();
714 $rs->update({ $field => $self->id });
715 if ( $r eq 'BorrowerDebarment' ) {
716 Koha::Patron::Debarments::UpdateBorrowerDebarmentFlags($self->id);
720 $patron->move_to_deleted();
729 =head3 messaging_preferences
731 my $patron = Koha::Patrons->find($id);
732 $patron->messaging_preferences();
736 sub messaging_preferences {
739 return Koha::Patron::MessagePreferences->search({
740 borrowernumber => $self->borrowernumber,
744 =head3 wants_check_for_previous_checkout
746 $wants_check = $patron->wants_check_for_previous_checkout;
748 Return 1 if Koha needs to perform PrevIssue checking, else 0.
752 sub wants_check_for_previous_checkout {
754 my $syspref = C4::Context->preference("checkPrevCheckout");
757 ## Hard syspref trumps all
758 return 1 if ($syspref eq 'hardyes');
759 return 0 if ($syspref eq 'hardno');
760 ## Now, patron pref trumps all
761 return 1 if ($self->checkprevcheckout eq 'yes');
762 return 0 if ($self->checkprevcheckout eq 'no');
764 # More complex: patron inherits -> determine category preference
765 my $checkPrevCheckoutByCat = $self->category->checkprevcheckout;
766 return 1 if ($checkPrevCheckoutByCat eq 'yes');
767 return 0 if ($checkPrevCheckoutByCat eq 'no');
769 # Finally: category preference is inherit, default to 0
770 if ($syspref eq 'softyes') {
777 =head3 do_check_for_previous_checkout
779 $do_check = $patron->do_check_for_previous_checkout($item);
781 Return 1 if the bib associated with $ITEM has previously been checked out to
782 $PATRON, 0 otherwise.
786 sub do_check_for_previous_checkout {
787 my ( $self, $item ) = @_;
790 my $biblio = Koha::Biblios->find( $item->{biblionumber} );
791 if ( $biblio->is_serial ) {
792 push @item_nos, $item->{itemnumber};
794 # Get all itemnumbers for given bibliographic record.
795 @item_nos = $biblio->items->get_column( 'itemnumber' );
798 # Create (old)issues search criteria
800 borrowernumber => $self->borrowernumber,
801 itemnumber => \@item_nos,
804 my $delay = C4::Context->preference('CheckPrevCheckoutDelay') || 0;
806 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
807 my $newer_than = dt_from_string()->subtract( days => $delay );
808 $criteria->{'returndate'} = { '>' => $dtf->format_datetime($newer_than), };
811 # Check current issues table
812 my $issues = Koha::Checkouts->search($criteria);
813 return 1 if $issues->count; # 0 || N
815 # Check old issues table
816 my $old_issues = Koha::Old::Checkouts->search($criteria);
817 return $old_issues->count; # 0 || N
822 my $debarment_expiration = $patron->is_debarred;
824 Returns the date a patron debarment will expire, or undef if the patron is not
832 return unless $self->debarred;
833 return $self->debarred
834 if $self->debarred =~ '^9999'
835 or dt_from_string( $self->debarred ) > dt_from_string;
841 my $is_expired = $patron->is_expired;
843 Returns 1 if the patron is expired or 0;
849 return 0 unless $self->dateexpiry;
850 return 0 if $self->dateexpiry =~ '^9999';
851 return 1 if dt_from_string( $self->dateexpiry ) < dt_from_string->truncate( to => 'day' );
857 $patron->is_active({ [ since => $date ], [ days|weeks|months|years => $value ] })
859 A patron is considered 'active' if the following conditions hold:
861 - account did not expire
862 - account has not been anonymized
863 - enrollment or lastseen within period specified
865 Note: lastseen is updated for triggers defined in preference
866 TrackLastPatronActivityTriggers. This includes logins, issues, holds, etc.
868 The period to check is defined by $date or $value in days, weeks or months. You should
869 pass one of those; otherwise an exception is thrown.
874 my ( $self, $params ) = @_;
875 return 0 if $self->is_expired or $self->anonymized;
878 if ( $params->{since} ) {
879 $dt = dt_from_string( $params->{since}, 'iso' );
880 } elsif ( grep { $params->{$_} } qw(days weeks months years) ) {
881 $dt = dt_from_string();
882 foreach my $duration (qw(days weeks months years)) {
883 $dt = $dt->subtract( $duration => $params->{$duration} ) if $params->{$duration};
886 Koha::Exceptions::MissingParameter->throw('is_active needs date or period');
889 # Enrollment within this period?
890 return 1 if DateTime->compare( dt_from_string( $self->dateenrolled ), $dt ) > -1;
892 # We look at lastseen regardless of TrackLastPatronActivityTriggers. If lastseen is set
893 # recently, the triggers may have been removed after that, etc.
894 return 1 if $self->lastseen && DateTime->compare( dt_from_string( $self->lastseen ), $dt ) > -1;
899 =head3 password_expired
901 my $password_expired = $patron->password_expired;
903 Returns 1 if the patron's password is expired or 0;
907 sub password_expired {
909 return 0 unless $self->password_expiration_date;
910 return 1 if dt_from_string( $self->password_expiration_date ) <= dt_from_string->truncate( to => 'day' );
914 =head3 is_going_to_expire
916 my $is_going_to_expire = $patron->is_going_to_expire;
918 Returns 1 if the patron is going to expired, depending on the NotifyBorrowerDeparture pref or 0
922 sub is_going_to_expire {
925 my $delay = C4::Context->preference('NotifyBorrowerDeparture') || 0;
927 return 0 unless $delay;
928 return 0 unless $self->dateexpiry;
929 return 0 if $self->dateexpiry =~ '^9999';
930 return 1 if dt_from_string( $self->dateexpiry, undef, 'floating' )->subtract( days => $delay ) < dt_from_string(undef, undef, 'floating')->truncate( to => 'day' );
936 $patron->set_password({ password => $plain_text_password [, skip_validation => 1, action => NAME ] });
938 Set the patron's password.
940 Allows optional action parameter to change name of action logged (when enabled). Used for reset password.
944 The passed string is validated against the current password enforcement policy.
945 Validation can be skipped by passing the I<skip_validation> parameter.
947 Exceptions are thrown if the password is not good enough.
951 =item Koha::Exceptions::Password::TooShort
953 =item Koha::Exceptions::Password::WhitespaceCharacters
955 =item Koha::Exceptions::Password::TooWeak
957 =item Koha::Exceptions::Password::Plugin (if a "check password" plugin is enabled)
964 my ( $self, $args ) = @_;
966 my $password = $args->{password};
967 my $action = $args->{action} || "CHANGE PASS";
969 unless ( $args->{skip_validation} ) {
970 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, $self->category );
973 if ( $error eq 'too_short' ) {
974 my $min_length = $self->category->effective_min_password_length;
975 $min_length = 3 if not $min_length or $min_length < 3;
977 my $password_length = length($password);
978 Koha::Exceptions::Password::TooShort->throw(
979 length => $password_length, min_length => $min_length );
981 elsif ( $error eq 'has_whitespaces' ) {
982 Koha::Exceptions::Password::WhitespaceCharacters->throw();
984 elsif ( $error eq 'too_weak' ) {
985 Koha::Exceptions::Password::TooWeak->throw();
990 if ( C4::Context->config("enable_plugins") ) {
991 # Call any check_password plugins
992 my @plugins = Koha::Plugins->new()->GetPlugins({
993 method => 'check_password',
995 foreach my $plugin ( @plugins ) {
996 # This plugin hook will also be used by a plugin for the Norwegian national
997 # patron database. This is why we need to pass both the password and the
998 # borrowernumber to the plugin.
999 my $ret = $plugin->check_password(
1001 password => $password,
1002 borrowernumber => $self->borrowernumber
1005 # This plugin hook will also be used by a plugin for the Norwegian national
1006 # patron database. This is why we need to call the actual plugins and then
1007 # check skip_validation afterwards.
1008 if ( $ret->{'error'} == 1 && !$args->{skip_validation} ) {
1009 Koha::Exceptions::Password::Plugin->throw();
1014 if ( C4::Context->preference('NotifyPasswordChange') ) {
1015 my $self_from_storage = $self->get_from_storage;
1016 if ( !C4::Auth::checkpw_hash( $password, $self_from_storage->password ) ) {
1017 my $emailaddr = $self_from_storage->notice_email_address;
1019 # if we manage to find a valid email address, send notice
1021 my $letter = C4::Letters::GetPreparedLetter(
1022 module => 'members',
1023 letter_code => 'PASSWORD_CHANGE',
1024 branchcode => $self_from_storage->branchcode,
1026 lang => $self_from_storage->lang || 'default',
1028 'branches' => $self_from_storage->branchcode,
1029 'borrowers' => $self_from_storage->borrowernumber,
1031 want_librarian => 1,
1034 my $message_id = C4::Letters::EnqueueLetter(
1037 borrowernumber => $self_from_storage->id,
1038 to_address => $emailaddr,
1039 message_transport_type => 'email'
1042 C4::Letters::SendQueuedMessages( { message_id => $message_id } ) if $message_id;
1047 my $digest = Koha::AuthUtils::hash_password($password);
1049 $self->password_expiration_date( $self->category->get_password_expiry_date || undef );
1051 # We do not want to call $self->store and retrieve password from DB
1052 $self->password($digest);
1053 $self->login_attempts(0);
1054 $self->SUPER::store;
1056 logaction( "MEMBERS", $action, $self->borrowernumber, "" )
1057 if C4::Context->preference("BorrowersLog");
1063 =head3 renew_account
1065 my $new_expiry_date = $patron->renew_account
1067 Extending the subscription to the expiry date.
1074 if ( C4::Context->preference('BorrowerRenewalPeriodBase') eq 'combination' ) {
1075 $date = ( dt_from_string gt dt_from_string( $self->dateexpiry ) ) ? dt_from_string : dt_from_string( $self->dateexpiry );
1078 C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry'
1079 ? dt_from_string( $self->dateexpiry )
1082 my $expiry_date = $self->category->get_expiry_date($date);
1084 $self->dateexpiry($expiry_date);
1085 $self->date_renewed( dt_from_string() );
1088 $self->add_enrolment_fee_if_needed(1);
1090 logaction( "MEMBERS", "RENEW", $self->borrowernumber, "Membership renewed" ) if C4::Context->preference("BorrowersLog");
1091 return dt_from_string( $expiry_date )->truncate( to => 'day' );
1096 my $has_overdues = $patron->has_overdues;
1098 Returns the number of patron's overdues
1104 my $date = dt_from_string();
1105 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
1106 return $self->_result->issues->search({ date_due => { '<' => $dtf->format_datetime($date) } })->count;
1111 =head3 has_restricting_overdues
1113 my $has_restricting_overdues = $patron->has_restricting_overdues({ issue_branchcode => $branchcode });
1115 Returns true if patron has overdues that would result in debarment.
1119 sub has_restricting_overdues {
1120 my ( $self, $params ) = @_;
1122 my $date = dt_from_string()->truncate( to => 'day' );
1124 # If ignoring unrestricted overdues, calculate which delay value for
1125 # overdue messages is set with restrictions. Then only include overdue
1126 # issues older than that date when counting.
1127 #TODO: bail out/throw exception if $params->{issue_branchcode} not set?
1128 my $debarred_delay = _get_overdue_debarred_delay( $params->{issue_branchcode}, $self->categorycode() );
1129 return 0 unless defined $debarred_delay;
1131 # Emulate the conditions in overdue_notices.pl.
1132 # The overdue_notices-script effectively truncates both issues.date_due and current date
1133 # to days when selecting overdue issues.
1134 # Hours and minutes for issues.date_due is usually set to 23 and 59 respectively, though can theoretically
1135 # be set to any other value (truncated to minutes, except if CalcDateDue gets a $startdate)
1137 # No matter what time of day date_due is set to, overdue_notices.pl will select all issues that are due
1138 # the current date or later. We can emulate this query by instead of truncating both to days in the SQL-query,
1139 # using the condition that date_due must be less then the current date truncated to days (time set to 00:00:00)
1140 # offset by one day in the future.
1142 $date->add( days => 1 );
1145 if ( C4::Context->preference('OverdueNoticeCalendar') ) {
1146 $calendar = Koha::Calendar->new( branchcode => $params->{issue_branchcode} );
1149 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
1150 my $issues = $self->_result->issues->search( { date_due => { '<' => $dtf->format_datetime($date) } } );
1151 my $now = dt_from_string();
1153 while ( my $issue = $issues->next ) {
1155 C4::Context->preference('OverdueNoticeCalendar')
1156 ? $calendar->days_between( dt_from_string( $issue->date_due ), $now )->in_units('days')
1157 : $now->delta_days( dt_from_string( $issue->date_due ) )->in_units('days');
1158 if ( $days_between >= $debarred_delay ) {
1165 # Fetch first delayX value from overduerules where debarredX is set, or 0 for no delay
1166 sub _get_overdue_debarred_delay {
1167 my ( $branchcode, $categorycode ) = @_;
1168 my $dbh = C4::Context->dbh();
1170 # We get default rules if there is no rule for this branch
1171 my $rule = Koha::OverdueRules->find(
1173 branchcode => $branchcode,
1174 categorycode => $categorycode
1177 || Koha::OverdueRules->find(
1180 categorycode => $categorycode
1185 return $rule->delay1 if $rule->debarred1;
1186 return $rule->delay2 if $rule->debarred2;
1187 return $rule->delay3 if $rule->debarred3;
1191 =head3 update_lastseen
1193 $patron->update_lastseen('activity');
1195 Updates the lastseen field, limited to one update per day, whenever the activity passed is
1196 listed in TrackLastPatronActivityTriggers.
1198 The method should be called upon successful completion of the activity.
1202 sub update_lastseen {
1203 my ( $self, $activity ) = @_;
1204 my $tracked_activities = {
1205 map { ( lc $_, 1 ); } split /\s*\,\s*/,
1206 C4::Context->preference('TrackLastPatronActivityTriggers')
1208 return $self unless $tracked_activities->{$activity};
1210 my $cache = Koha::Caches->get_instance();
1211 my $cache_key = "track_activity_" . $self->borrowernumber;
1212 my $cached = $cache->get_from_cache($cache_key);
1213 my $now = dt_from_string();
1214 return $self if $cached && $cached eq $now->ymd;
1216 $self->lastseen($now)->store;
1217 $cache->set_in_cache( $cache_key, $now->ymd );
1221 =head3 move_to_deleted
1223 my $is_moved = $patron->move_to_deleted;
1225 Move a patron to the deletedborrowers table.
1226 This can be done before deleting a patron, to make sure the data are not completely deleted.
1230 sub move_to_deleted {
1232 my $patron_infos = $self->unblessed;
1233 delete $patron_infos->{updated_on}; #This ensures the updated_on date in deletedborrowers will be set to the current timestamp
1234 return Koha::Database->new->schema->resultset('Deletedborrower')->create($patron_infos);
1237 =head3 can_request_article
1239 if ( $patron->can_request_article( $library->id ) ) { ... }
1241 Returns true if the patron can request articles. As limits apply for the patron
1242 on the same day, those completed the same day are considered as current.
1244 A I<library_id> can be passed as parameter, falling back to userenv if absent.
1248 sub can_request_article {
1249 my ($self, $library_id) = @_;
1251 $library_id //= C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
1253 my $rule = Koha::CirculationRules->get_effective_rule(
1255 branchcode => $library_id,
1256 categorycode => $self->categorycode,
1257 rule_name => 'open_article_requests_limit'
1261 my $limit = ($rule) ? $rule->rule_value : undef;
1263 return 1 unless defined $limit;
1265 my $count = Koha::ArticleRequests->search(
1266 [ { borrowernumber => $self->borrowernumber, status => [ 'REQUESTED', 'PENDING', 'PROCESSING' ] },
1267 { borrowernumber => $self->borrowernumber, status => 'COMPLETED', updated_on => { '>=' => \'CAST(NOW() AS DATE)' } },
1270 return $count < $limit ? 1 : 0;
1273 =head3 article_request_fee
1275 my $fee = $patron->article_request_fee(
1277 [ library_id => $library->id, ]
1281 Returns the fee to be charged to the patron when it places an article request.
1283 A I<library_id> can be passed as parameter, falling back to userenv if absent.
1287 sub article_request_fee {
1288 my ($self, $params) = @_;
1290 my $library_id = $params->{library_id};
1292 $library_id //= C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
1294 my $rule = Koha::CirculationRules->get_effective_rule(
1296 branchcode => $library_id,
1297 categorycode => $self->categorycode,
1298 rule_name => 'article_request_fee'
1302 my $fee = ($rule) ? $rule->rule_value + 0 : 0;
1307 =head3 add_article_request_fee_if_needed
1309 my $fee = $patron->add_article_request_fee_if_needed(
1311 [ item_id => $item->id,
1312 library_id => $library->id, ]
1316 If an article request fee needs to be charged, it adds a debit to the patron's
1319 Returns the fee line.
1321 A I<library_id> can be passed as parameter, falling back to userenv if absent.
1325 sub add_article_request_fee_if_needed {
1326 my ($self, $params) = @_;
1328 my $library_id = $params->{library_id};
1329 my $item_id = $params->{item_id};
1331 $library_id //= C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
1333 my $amount = $self->article_request_fee(
1335 library_id => $library_id,
1341 if ( $amount > 0 ) {
1342 $debit_line = $self->account->add_debit(
1345 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
1346 interface => C4::Context->interface,
1347 library_id => $library_id,
1348 type => 'ARTICLE_REQUEST',
1349 item_id => $item_id,
1357 =head3 article_requests
1359 my $article_requests = $patron->article_requests;
1361 Returns the patron article requests.
1365 sub article_requests {
1368 return Koha::ArticleRequests->_new_from_dbic( scalar $self->_result->article_requests );
1371 =head3 add_enrolment_fee_if_needed
1373 my $enrolment_fee = $patron->add_enrolment_fee_if_needed($renewal);
1375 Add enrolment fee for a patron if needed.
1377 $renewal - boolean denoting whether this is an account renewal or not
1381 sub add_enrolment_fee_if_needed {
1382 my ($self, $renewal) = @_;
1383 my $enrolment_fee = $self->category->enrolmentfee;
1384 if ( $enrolment_fee && $enrolment_fee > 0 ) {
1385 my $type = $renewal ? 'ACCOUNT_RENEW' : 'ACCOUNT';
1386 $self->account->add_debit(
1388 amount => $enrolment_fee,
1389 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
1390 interface => C4::Context->interface,
1391 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
1396 return $enrolment_fee || 0;
1401 my $checkouts = $patron->checkouts
1407 my $checkouts = $self->_result->issues;
1408 return Koha::Checkouts->_new_from_dbic( $checkouts );
1411 =head3 pending_checkouts
1413 my $pending_checkouts = $patron->pending_checkouts
1415 This method will return the same as $self->checkouts, but with a prefetch on
1416 items, biblio and biblioitems.
1418 It has been introduced to replaced the C4::Members::GetPendingIssues subroutine
1420 It should not be used directly, prefer to access fields you need instead of
1421 retrieving all these fields in one go.
1425 sub pending_checkouts {
1427 my $checkouts = $self->_result->issues->search(
1431 { -desc => 'me.timestamp' },
1432 { -desc => 'issuedate' },
1433 { -desc => 'issue_id' }, # Sort by issue_id should be enough
1435 prefetch => { item => { biblio => 'biblioitems' } },
1438 return Koha::Checkouts->_new_from_dbic( $checkouts );
1441 =head3 old_checkouts
1443 my $old_checkouts = $patron->old_checkouts
1449 my $old_checkouts = $self->_result->old_issues;
1450 return Koha::Old::Checkouts->_new_from_dbic( $old_checkouts );
1455 my $overdue_items = $patron->overdues
1457 Return the overdue items
1463 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
1464 return $self->checkouts->search(
1466 'me.date_due' => { '<' => $dtf->format_datetime(dt_from_string) },
1469 prefetch => { item => { biblio => 'biblioitems' } },
1477 my $restrictions = $patron->restrictions;
1479 Returns the patron restrictions.
1485 my $restrictions_rs = $self->_result->restrictions;
1486 return Koha::Patron::Restrictions->_new_from_dbic($restrictions_rs);
1489 =head3 get_routing_lists
1491 my $routinglists = $patron->get_routing_lists
1493 Returns the routing lists a patron is subscribed to.
1497 sub get_routing_lists {
1499 my $routing_list_rs = $self->_result->subscriptionroutinglists;
1500 return Koha::Subscription::Routinglists->_new_from_dbic($routing_list_rs);
1505 my $age = $patron->get_age
1507 Return the age of the patron
1514 return unless $self->dateofbirth;
1516 #Set timezone to floating to avoid any datetime math issues caused by DST
1517 my $date_of_birth = dt_from_string( $self->dateofbirth, undef, 'floating' );
1518 my $today = dt_from_string(undef, undef, 'floating')->truncate( to => 'day' );
1520 return $today->subtract_datetime( $date_of_birth )->years;
1525 my $is_valid = $patron->is_valid_age
1527 Return 1 if patron's age is between allowed limits, returns 0 if it's not.
1533 my $age = $self->get_age;
1535 my $patroncategory = $self->category;
1536 my ($low,$high) = ($patroncategory->dateofbirthrequired, $patroncategory->upperagelimit);
1538 return (defined($age) && (($high && ($age > $high)) or ($low && ($age < $low)))) ? 0 : 1;
1543 my $account = $patron->account
1549 return Koha::Account->new( { patron_id => $self->borrowernumber } );
1554 my $holds = $patron->holds
1556 Return all the holds placed by this patron
1562 my $holds_rs = $self->_result->reserves->search( {}, { order_by => 'reservedate' } );
1563 return Koha::Holds->_new_from_dbic($holds_rs);
1568 my $old_holds = $patron->old_holds
1570 Return all the historical holds for this patron
1576 my $old_holds_rs = $self->_result->old_reserves->search( {}, { order_by => 'reservedate' } );
1577 return Koha::Old::Holds->_new_from_dbic($old_holds_rs);
1580 =head3 curbside_pickups
1582 my $curbside_pickups = $patron->curbside_pickups;
1584 Return all the curbside pickups for this patron
1588 sub curbside_pickups {
1590 my $curbside_pickups_rs = $self->_result->curbside_pickups_borrowernumbers->search;
1591 return Koha::CurbsidePickups->_new_from_dbic($curbside_pickups_rs);
1594 =head3 return_claims
1596 my $return_claims = $patron->return_claims
1602 my $return_claims = $self->_result->return_claims_borrowernumbers;
1603 return Koha::Checkouts::ReturnClaims->_new_from_dbic( $return_claims );
1606 =head3 notice_email_address
1608 my $email = $patron->notice_email_address;
1610 Return the email address of patron used for notices.
1611 Returns the empty string if no email address.
1615 sub notice_email_address{
1618 my $which_address = C4::Context->preference("EmailFieldPrimary");
1619 # if syspref is set to 'first valid' (value == OFF), look up email address
1620 if ( $which_address eq 'OFF' ) {
1621 return $self->first_valid_email_address;
1624 return $self->$which_address || '';
1627 =head3 first_valid_email_address
1629 my $first_valid_email_address = $patron->first_valid_email_address
1631 Return the first valid email address for a patron.
1632 For now, the order is defined as email, emailpro, B_email.
1633 Returns the empty string if the borrower has no email addresses.
1637 sub first_valid_email_address {
1642 my @fields = split /\s*\|\s*/,
1643 C4::Context->preference('EmailFieldPrecedence');
1644 for my $field (@fields) {
1645 $email = $self->$field;
1652 =head3 get_club_enrollments
1656 sub get_club_enrollments {
1659 return Koha::Club::Enrollments->search( { borrowernumber => $self->borrowernumber(), date_canceled => undef } );
1662 =head3 get_enrollable_clubs
1666 sub get_enrollable_clubs {
1667 my ( $self, $is_enrollable_from_opac ) = @_;
1670 $params->{is_enrollable_from_opac} = $is_enrollable_from_opac
1671 if $is_enrollable_from_opac;
1672 $params->{is_email_required} = 0 unless $self->first_valid_email_address();
1674 $params->{borrower} = $self;
1676 return Koha::Clubs->get_enrollable($params);
1680 =head3 get_lists_with_patron
1682 my @lists = $patron->get_lists_with_patron;
1684 FIXME: This method returns a DBIC resultset instead of a Koha::Objects-based
1689 sub get_lists_with_patron {
1691 my $borrowernumber = $self->borrowernumber;
1693 return Koha::Database->new()->schema()->resultset('PatronList')->search(
1695 'patron_list_patrons.borrowernumber' => $borrowernumber,
1698 join => 'patron_list_patrons',
1705 =head3 account_locked
1707 my $is_locked = $patron->account_locked
1709 Return true if the patron has reached the maximum number of login attempts
1710 (see pref FailedLoginAttempts). If login_attempts is < 0, this is interpreted
1711 as an administrative lockout (independent of FailedLoginAttempts; see also
1712 Koha::Patron->lock).
1713 Otherwise return false.
1714 If the pref is not set (empty string, null or 0), the feature is considered as
1719 sub account_locked {
1721 my $FailedLoginAttempts = C4::Context->preference('FailedLoginAttempts');
1722 return 1 if $FailedLoginAttempts
1723 and $self->login_attempts
1724 and $self->login_attempts >= $FailedLoginAttempts;
1725 return 1 if ($self->login_attempts || 0) < 0; # administrative lockout
1729 =head3 can_see_patron_infos
1731 my $can_see = $patron->can_see_patron_infos( $patron );
1733 Return true if the patron (usually the logged in user) can see the patron's infos for a given patron
1737 sub can_see_patron_infos {
1738 my ( $self, $patron ) = @_;
1739 return unless $patron;
1740 return $self->can_see_patrons_from( $patron->branchcode );
1743 =head3 can_see_patrons_from
1745 my $can_see = $patron->can_see_patrons_from( $branchcode );
1747 Return true if the patron (usually the logged in user) can see the patron's infos from a given library
1751 sub can_see_patrons_from {
1752 my ( $self, $branchcode ) = @_;
1754 return $self->can_see_things_from(
1756 branchcode => $branchcode,
1757 permission => 'borrowers',
1758 subpermission => 'view_borrower_infos_from_any_libraries',
1763 =head3 can_edit_items_from
1765 my $can_edit = $patron->can_edit_items_from( $branchcode );
1767 Return true if the I<Koha::Patron> can edit items from the given branchcode
1771 sub can_edit_items_from {
1772 my ( $self, $branchcode ) = @_;
1774 return 1 if C4::Context->IsSuperLibrarian();
1776 my $userenv = C4::Context->userenv();
1777 if ( $userenv && C4::Context->preference('IndependentBranches') ) {
1778 return $userenv->{branch} eq $branchcode;
1781 return $self->can_see_things_from(
1783 branchcode => $branchcode,
1784 permission => 'editcatalogue',
1785 subpermission => 'edit_any_item',
1790 =head3 libraries_where_can_edit_items
1792 my $libraries = $patron->libraries_where_can_edit_items;
1794 Return the list of branchcodes(!) of libraries the patron is allowed to items for.
1795 The branchcodes are arbitrarily returned sorted.
1796 We are supposing here that the object is related to the logged in patron (use of C4::Context::only_my_library)
1798 An empty array means no restriction, the user can edit any item.
1802 sub libraries_where_can_edit_items {
1805 return $self->libraries_where_can_see_things(
1807 permission => 'editcatalogue',
1808 subpermission => 'edit_any_item',
1809 group_feature => 'ft_limit_item_editing',
1814 =head3 libraries_where_can_see_patrons
1816 my $libraries = $patron->libraries_where_can_see_patrons;
1818 Return the list of branchcodes(!) of libraries the patron is allowed to see other patron's infos.
1819 The branchcodes are arbitrarily returned sorted.
1820 We are supposing here that the object is related to the logged in patron (use of C4::Context::only_my_library)
1822 An empty array means no restriction, the patron can see patron's infos from any libraries.
1826 sub libraries_where_can_see_patrons {
1829 return $self->libraries_where_can_see_things(
1831 permission => 'borrowers',
1832 subpermission => 'view_borrower_infos_from_any_libraries',
1833 group_feature => 'ft_hide_patron_info',
1838 =head3 can_see_things_from
1840 my $can_see = $patron->can_see_things_from( $branchcode );
1842 Return true if the I<Koha::Patron> can perform some action on the given thing
1846 sub can_see_things_from {
1847 my ( $self, $params ) = @_;
1849 my $branchcode = $params->{branchcode};
1850 my $permission = $params->{permission};
1851 my $subpermission = $params->{subpermission};
1853 return 1 if C4::Context->IsSuperLibrarian();
1856 if ( $self->branchcode eq $branchcode ) {
1858 } elsif ( $self->has_permission( { $permission => $subpermission } ) ) {
1860 } elsif ( my @branches = $self->libraries_where_can_see_patrons ) {
1861 $can = ( any { $_ eq $branchcode } @branches ) ? 1 : 0;
1868 my $can_log_into = $patron->can_log_into( $library );
1870 Given a I<Koha::Library> object, it returns a boolean representing
1871 the fact the patron can log into a the library.
1876 my ( $self, $library ) = @_;
1880 if ( C4::Context->preference('IndependentBranches') ) {
1882 if $self->is_superlibrarian
1883 or $self->branchcode eq $library->id;
1893 =head3 libraries_where_can_see_things
1895 my $libraries = $patron->libraries_where_can_see_things;
1897 Returns a list of libraries where an aribitarary action is allowed to be taken by the logged in librarian
1898 against an object based on some branchcode related to the object ( patron branchcode, item homebranch, etc ).
1900 We are supposing here that the object is related to the logged in librarian (use of C4::Context::only_my_library)
1902 An empty array means no restriction, the thing can see thing's infos from any libraries.
1906 sub libraries_where_can_see_things {
1907 my ( $self, $params ) = @_;
1908 my $permission = $params->{permission};
1909 my $subpermission = $params->{subpermission};
1910 my $group_feature = $params->{group_feature};
1912 return $self->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"}
1913 if exists( $self->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} );
1915 my $userenv = C4::Context->userenv;
1917 return () unless $userenv; # For tests, but userenv should be defined in tests...
1919 my @restricted_branchcodes;
1920 if (C4::Context::only_my_library) {
1921 push @restricted_branchcodes, $self->branchcode;
1925 $self->has_permission(
1926 { $permission => $subpermission }
1930 my $library_groups = $self->library->library_groups({ $group_feature => 1 });
1931 if ( $library_groups->count )
1933 while ( my $library_group = $library_groups->next ) {
1934 my $parent = $library_group->parent;
1935 if ( $parent->has_child( $self->branchcode ) ) {
1936 push @restricted_branchcodes, $parent->children->get_column('branchcode');
1941 @restricted_branchcodes = ( $self->branchcode ) unless @restricted_branchcodes;
1945 @restricted_branchcodes = grep { defined $_ } @restricted_branchcodes;
1946 @restricted_branchcodes = uniq(@restricted_branchcodes);
1947 @restricted_branchcodes = sort(@restricted_branchcodes);
1949 $self->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} = \@restricted_branchcodes;
1950 return @{ $self->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} };
1953 =head3 has_permission
1955 my $permission = $patron->has_permission($required);
1957 See C4::Auth::haspermission for details of syntax for $required
1961 sub has_permission {
1962 my ( $self, $flagsrequired ) = @_;
1963 return unless $self->userid;
1964 # TODO code from haspermission needs to be moved here!
1965 return C4::Auth::haspermission( $self->userid, $flagsrequired );
1968 =head3 is_superlibrarian
1970 my $is_superlibrarian = $patron->is_superlibrarian;
1972 Return true if the patron is a superlibrarian.
1976 sub is_superlibrarian {
1978 return $self->has_permission( { superlibrarian => 1 } ) ? 1 : 0;
1983 my $is_adult = $patron->is_adult
1985 Return true if the patron has a category with a type Adult (A) or Organization (I)
1991 return $self->category->category_type =~ /^(A|I)$/ ? 1 : 0;
1996 my $is_child = $patron->is_child
1998 Return true if the patron has a category with a type Child (C)
2004 return $self->category->category_type eq 'C' ? 1 : 0;
2007 =head3 has_valid_userid
2009 my $patron = Koha::Patrons->find(42);
2010 $patron->userid( $new_userid );
2011 my $has_a_valid_userid = $patron->has_valid_userid
2013 my $patron = Koha::Patron->new( $params );
2014 my $has_a_valid_userid = $patron->has_valid_userid
2016 Return true if the current userid of this patron is valid/unique, otherwise false.
2018 Note that this should be done in $self->store instead and raise an exception if needed.
2022 sub has_valid_userid {
2025 return 0 unless $self->userid;
2027 return 0 if ( $self->userid eq C4::Context->config('user') ); # DB user
2029 my $already_exists = Koha::Patrons->search(
2031 userid => $self->userid,
2034 ? ( borrowernumber => { '!=' => $self->borrowernumber } )
2039 return $already_exists ? 0 : 1;
2042 =head3 generate_userid
2044 $patron->generate_userid;
2046 If you do not have a plugin for generating a userid, we will call
2047 the internal method here that returns firstname.surname[.number],
2048 where number is an optional suffix to make the userid unique.
2049 (Its behavior has not been changed on bug 32426.)
2051 If you have plugin(s), the first valid response will be used.
2052 A plugin is assumed to return a valid userid as suggestion, but not
2053 assumed to save it already.
2054 Does not fallback to internal (you could arrange for that in your plugin).
2055 Clears userid when there are no valid plugin responses.
2059 sub generate_userid {
2061 my @responses = Koha::Plugins->call(
2062 'patron_generate_userid', { patron => $self },
2064 unless( @responses ) {
2065 # Empty list only possible when there are NO enabled plugins for this method.
2066 # In that case we provide internal response.
2067 return $self->_generate_userid_internal;
2069 # If a plugin returned false value or invalid value, we do however not return
2070 # internal response. The plugins should deal with that themselves. So we prevent
2071 # unexpected/unwelcome internal codes for plugin failures.
2072 foreach my $response ( grep { $_ } @responses ) {
2073 $self->userid( $response );
2074 return $self if $self->has_valid_userid;
2076 $self->userid(undef);
2080 sub _generate_userid_internal { # as we always did
2083 my $firstname = $self->firstname // q{};
2084 my $surname = $self->surname // q{};
2085 #The script will "do" the following code and increment the $offset until the generated userid is unique
2087 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
2088 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
2089 my $userid = lc(($firstname)? "$firstname.$surname" : $surname);
2090 $userid = NFKD( $userid );
2091 $userid =~ s/\p{NonspacingMark}//g;
2092 $userid .= $offset unless $offset == 0;
2093 $self->userid( $userid );
2095 } while (! $self->has_valid_userid );
2100 =head3 add_extended_attribute
2104 sub add_extended_attribute {
2105 my ($self, $attribute) = @_;
2107 return Koha::Patron::Attribute->new(
2110 ( borrowernumber => $self->borrowernumber ),
2116 =head3 extended_attributes
2118 Return object of Koha::Patron::Attributes type with all attributes set for this patron
2124 sub extended_attributes {
2125 my ( $self, $attributes ) = @_;
2126 if ($attributes) { # setter
2127 my $schema = $self->_result->result_source->schema;
2130 # Remove the existing one
2131 $self->extended_attributes->filter_by_branch_limitations->delete;
2133 # Insert the new ones
2135 for my $attribute (@$attributes) {
2136 $self->add_extended_attribute($attribute);
2137 $new_types->{$attribute->{code}} = 1;
2140 # Check globally mandatory types
2141 my @required_attribute_types =
2142 Koha::Patron::Attribute::Types->search(
2145 category_code => [ undef, $self->categorycode ],
2146 'borrower_attribute_types_branches.b_branchcode' =>
2149 { join => 'borrower_attribute_types_branches' }
2150 )->get_column('code');
2151 for my $type ( @required_attribute_types ) {
2152 Koha::Exceptions::Patron::MissingMandatoryExtendedAttribute->throw(
2154 ) if !$new_types->{$type};
2160 my $rs = $self->_result->borrower_attributes;
2161 # We call search to use the filters in Koha::Patron::Attributes->search
2162 return Koha::Patron::Attributes->_new_from_dbic($rs)->search;
2167 my $messages = $patron->messages;
2169 Return the message attached to the patron.
2175 my $messages_rs = $self->_result->messages_borrowernumbers->search;
2176 return Koha::Patron::Messages->_new_from_dbic($messages_rs);
2181 Koha::Patrons->find($id)->lock({ expire => 1, remove => 1 });
2183 Lock and optionally expire a patron account.
2184 Remove holds and article requests if remove flag set.
2185 In order to distinguish from locking by entering a wrong password, let's
2186 call this an administrative lockout.
2191 my ( $self, $params ) = @_;
2192 $self->login_attempts( ADMINISTRATIVE_LOCKOUT );
2193 if( $params->{expire} ) {
2194 $self->dateexpiry( dt_from_string->subtract(days => 1) );
2197 if( $params->{remove} ) {
2198 $self->holds->delete;
2199 $self->article_requests->delete;
2206 Koha::Patrons->find($id)->anonymize;
2208 Anonymize or clear borrower fields. Fields in BorrowerMandatoryField
2209 are randomized, other personal data is cleared too.
2210 Patrons with issues are skipped.
2216 if( $self->_result->issues->count ) {
2217 warn "Exiting anonymize: patron ".$self->borrowernumber." still has issues";
2220 # Mandatory fields come from the corresponding pref, but email fields
2221 # are removed since scrambled email addresses only generate errors
2222 my $mandatory = { map { (lc $_, 1); } grep { !/email/ }
2223 split /\s*\|\s*/, C4::Context->preference('BorrowerMandatoryField') };
2224 $mandatory->{userid} = 1; # needed since sub store does not clear field
2225 my @columns = $self->_result->result_source->columns;
2226 @columns = grep { !/borrowernumber|branchcode|categorycode|^date|password|flags|updated_on|lastseen|lang|login_attempts|anonymized|auth_method/ } @columns;
2227 push @columns, 'dateofbirth'; # add this date back in
2228 foreach my $col (@columns) {
2229 $self->_anonymize_column($col, $mandatory->{lc $col} );
2231 $self->anonymized(1)->store;
2234 sub _anonymize_column {
2235 my ( $self, $col, $mandatory ) = @_;
2236 my $col_info = $self->_result->result_source->column_info($col);
2237 my $type = $col_info->{data_type};
2238 my $nullable = $col_info->{is_nullable};
2240 if( $type =~ /char|text/ ) {
2242 ? Koha::Token->new->generate({ pattern => '\w{10}' })
2246 } elsif( $type =~ /integer|int$|float|dec|double/ ) {
2247 $val = $nullable ? undef : 0;
2248 } elsif( $type =~ /date|time/ ) {
2249 $val = $nullable ? undef : dt_from_string;
2254 =head3 add_guarantor
2256 my $relationship = $patron->add_guarantor(
2258 borrowernumber => $borrowernumber,
2259 relationships => $relationship,
2263 Adds a new guarantor to a patron.
2268 my ( $self, $params ) = @_;
2270 my $guarantor_id = $params->{guarantor_id};
2271 my $relationship = $params->{relationship};
2273 return Koha::Patron::Relationship->new(
2275 guarantee_id => $self->id,
2276 guarantor_id => $guarantor_id,
2277 relationship => $relationship
2282 =head3 get_extended_attribute
2284 my $attribute_value = $patron->get_extended_attribute( $code );
2286 Return the attribute for the code passed in parameter.
2288 It not exist it returns undef
2290 Note that this will not work for repeatable attribute types.
2292 Maybe you certainly not want to use this method, it is actually only used for SHOW_BARCODE
2293 (which should be a real patron's attribute (not extended)
2297 sub get_extended_attribute {
2298 my ( $self, $code, $value ) = @_;
2299 my $rs = $self->_result->borrower_attributes;
2301 my $attribute = $rs->search({ code => $code, ( $value ? ( attribute => $value ) : () ) });
2302 return unless $attribute->count;
2303 return $attribute->next;
2306 =head3 set_default_messaging_preferences
2308 $patron->set_default_messaging_preferences
2310 Sets default messaging preferences on patron.
2312 See Koha::Patron::MessagePreference(s) for more documentation, especially on
2317 sub set_default_messaging_preferences {
2318 my ($self, $categorycode) = @_;
2320 my $options = Koha::Patron::MessagePreferences->get_options;
2322 foreach my $option (@$options) {
2323 # Check that this option has preference configuration for this category
2324 unless (Koha::Patron::MessagePreferences->search({
2325 message_attribute_id => $option->{message_attribute_id},
2326 categorycode => $categorycode || $self->categorycode,
2331 # Delete current setting
2332 Koha::Patron::MessagePreferences->search({
2333 borrowernumber => $self->borrowernumber,
2334 message_attribute_id => $option->{message_attribute_id},
2337 Koha::Patron::MessagePreference->new_from_default({
2338 borrowernumber => $self->borrowernumber,
2339 categorycode => $categorycode || $self->categorycode,
2340 message_attribute_id => $option->{message_attribute_id},
2347 =head3 is_accessible
2349 if ( $patron->is_accessible({ user => $logged_in_user }) ) { ... }
2351 This overloaded method validates whether the current I<Koha::Patron> object can be accessed
2352 by the logged in user.
2354 Returns 0 if the I<user> parameter is missing.
2359 my ( $self, $params ) = @_;
2361 unless ( defined( $params->{user} ) ) {
2362 Koha::Exceptions::MissingParameter->throw( error => "The `user` parameter is mandatory" );
2365 my $consumer = $params->{user};
2366 return $consumer->can_see_patron_infos($self);
2369 =head3 unredact_list
2371 This method returns the list of database fields that should be visible, even for restricted users,
2372 for both API and UI output purposes
2377 return ['branchcode'];
2382 my $json = $patron->to_api;
2384 Overloaded method that returns a JSON representation of the Koha::Patron object,
2385 suitable for API output.
2390 my ( $self, $params ) = @_;
2392 my $json_patron = $self->SUPER::to_api( $params );
2394 return unless $json_patron;
2396 $json_patron->{restricted} = ( $self->is_debarred )
2398 : Mojo::JSON->false;
2400 return $json_patron;
2403 =head3 to_api_mapping
2405 This method returns the mapping for representing a Koha::Patron object
2410 sub to_api_mapping {
2412 borrowernotes => 'staff_notes',
2413 borrowernumber => 'patron_id',
2414 branchcode => 'library_id',
2415 categorycode => 'category_id',
2416 checkprevcheckout => 'check_previous_checkout',
2417 contactfirstname => undef, # Unused
2418 contactname => undef, # Unused
2419 contactnote => 'altaddress_notes',
2420 contacttitle => undef, # Unused
2421 dateenrolled => 'date_enrolled',
2422 dateexpiry => 'expiry_date',
2423 dateofbirth => 'date_of_birth',
2424 debarred => undef, # replaced by 'restricted'
2425 debarredcomment => undef, # calculated, API consumers will use /restrictions instead
2426 emailpro => 'secondary_email',
2427 flags => undef, # permissions manipulation handled in /permissions
2428 gonenoaddress => 'incorrect_address',
2429 lastseen => 'last_seen',
2430 lost => 'patron_card_lost',
2431 opacnote => 'opac_notes',
2432 othernames => 'other_name',
2433 password => undef, # password manipulation handled in /password
2434 phonepro => 'secondary_phone',
2435 relationship => 'relationship_type',
2437 smsalertnumber => 'sms_number',
2438 sort1 => 'statistics_1',
2439 sort2 => 'statistics_2',
2440 autorenew_checkouts => 'autorenew_checkouts',
2441 streetnumber => 'street_number',
2442 streettype => 'street_type',
2443 zipcode => 'postal_code',
2444 B_address => 'altaddress_address',
2445 B_address2 => 'altaddress_address2',
2446 B_city => 'altaddress_city',
2447 B_country => 'altaddress_country',
2448 B_email => 'altaddress_email',
2449 B_phone => 'altaddress_phone',
2450 B_state => 'altaddress_state',
2451 B_streetnumber => 'altaddress_street_number',
2452 B_streettype => 'altaddress_street_type',
2453 B_zipcode => 'altaddress_postal_code',
2454 altcontactaddress1 => 'altcontact_address',
2455 altcontactaddress2 => 'altcontact_address2',
2456 altcontactaddress3 => 'altcontact_city',
2457 altcontactcountry => 'altcontact_country',
2458 altcontactfirstname => 'altcontact_firstname',
2459 altcontactphone => 'altcontact_phone',
2460 altcontactsurname => 'altcontact_surname',
2461 altcontactstate => 'altcontact_state',
2462 altcontactzipcode => 'altcontact_postal_code',
2463 password_expiration_date => undef,
2464 primary_contact_method => undef,
2466 auth_method => undef,
2472 Returns a map of column name to string representations including the string.
2477 my ( $self, $params ) = @_;
2481 str => $self->library->branchname,
2485 str => $self->category->description,
2486 type => 'patron_category',
2493 Koha::Patrons->queue_notice({ letter_params => $letter_params, message_name => 'DUE'});
2494 Koha::Patrons->queue_notice({ letter_params => $letter_params, message_transports => \@message_transports });
2495 Koha::Patrons->queue_notice({ letter_params => $letter_params, message_transports => \@message_transports, test_mode => 1 });
2497 Queue messages to a patron. Can pass a message that is part of the message_attributes
2498 table or supply the transport to use.
2500 If passed a message name we retrieve the patrons preferences for transports
2501 Otherwise we use the supplied transport. In the case of email or sms we fall back to print if
2502 we have no address/number for sending
2504 $letter_params is a hashref of the values to be passed to GetPreparedLetter
2506 test_mode will only report which notices would be sent, but nothing will be queued
2511 my ( $self, $params ) = @_;
2512 my $letter_params = $params->{letter_params};
2513 my $test_mode = $params->{test_mode};
2515 return unless $letter_params;
2516 return unless exists $params->{message_name} xor $params->{message_transports}; # We only want one of these
2518 my $library = Koha::Libraries->find( $letter_params->{branchcode} );
2519 my $from_email_address = $library->from_email_address;
2521 my @message_transports;
2523 $letter_code = $letter_params->{letter_code};
2524 if( $params->{message_name} ){
2525 my $messaging_prefs = C4::Members::Messaging::GetMessagingPreferences( {
2526 borrowernumber => $letter_params->{borrowernumber},
2527 message_name => $params->{message_name}
2529 @message_transports = ( keys %{ $messaging_prefs->{transports} } );
2530 $letter_code = $messaging_prefs->{transports}->{$message_transports[0]} unless $letter_code;
2532 @message_transports = @{$params->{message_transports}};
2534 return unless defined $letter_code;
2535 $letter_params->{letter_code} = $letter_code;
2538 foreach my $mtt (@message_transports){
2539 next if ($mtt eq 'itiva' and C4::Context->preference('TalkingTechItivaPhoneNotification') );
2540 # Notice is handled by TalkingTech_itiva_outbound.pl
2541 if ( ( $mtt eq 'email' and not $self->notice_email_address )
2542 or ( $mtt eq 'sms' and not $self->smsalertnumber )
2543 or ( $mtt eq 'phone' and not $self->phone ) )
2545 push @{ $return{fallback} }, $mtt;
2548 next if $mtt eq 'print' && $print_sent;
2549 $letter_params->{message_transport_type} = $mtt;
2550 my $letter = C4::Letters::GetPreparedLetter( %$letter_params );
2551 C4::Letters::EnqueueLetter({
2553 borrowernumber => $self->borrowernumber,
2554 from_address => $from_email_address,
2555 message_transport_type => $mtt
2556 }) unless $test_mode;
2557 push @{$return{sent}}, $mtt;
2558 $print_sent = 1 if $mtt eq 'print';
2563 =head3 safe_to_delete
2565 my $result = $patron->safe_to_delete;
2566 if ( $result eq 'has_guarantees' ) { ... }
2567 elsif ( $result ) { ... }
2568 else { # cannot delete }
2570 This method tells if the Koha:Patron object can be deleted. Possible return values
2576 =item 'has_checkouts'
2580 =item 'has_guarantees'
2582 =item 'is_anonymous_patron'
2584 =item 'is_protected'
2590 sub safe_to_delete {
2593 my $anonymous_patron = C4::Context->preference('AnonymousPatron');
2597 if ( $anonymous_patron && $self->id eq $anonymous_patron ) {
2598 $error = 'is_anonymous_patron';
2600 elsif ( $self->checkouts->count ) {
2601 $error = 'has_checkouts';
2603 elsif ( $self->account->outstanding_debits->total_outstanding > 0 ) {
2604 $error = 'has_debt';
2606 elsif ( $self->guarantee_relationships->count ) {
2607 $error = 'has_guarantees';
2609 elsif ( $self->protected ) {
2610 $error = 'is_protected';
2614 return Koha::Result::Boolean->new(0)->add_message({ message => $error });
2617 return Koha::Result::Boolean->new(1);
2622 my $recalls = $patron->recalls;
2624 Return the patron's recalls.
2631 return Koha::Recalls->search({ patron_id => $self->borrowernumber });
2634 =head3 account_balance
2636 my $balance = $patron->account_balance
2638 Return the patron's account balance
2642 sub account_balance {
2644 return $self->account->balance;
2647 =head3 notify_library_of_registration
2649 $patron->notify_library_of_registration( $email_patron_registrations );
2651 Send patron registration email to library if EmailPatronRegistrations system preference is enabled.
2655 sub notify_library_of_registration {
2656 my ( $self, $email_patron_registrations ) = @_;
2659 my $letter = C4::Letters::GetPreparedLetter(
2660 module => 'members',
2661 letter_code => 'OPAC_REG',
2662 branchcode => $self->branchcode,
2663 lang => $self->lang || 'default',
2665 'borrowers' => $self->borrowernumber
2670 if ( $email_patron_registrations eq "BranchEmailAddress" ) {
2671 my $library = Koha::Libraries->find( $self->branchcode );
2672 $to_address = $library->inbound_email_address;
2674 elsif ( $email_patron_registrations eq "KohaAdminEmailAddress" ) {
2675 $to_address = C4::Context->preference('ReplytoDefault')
2676 || C4::Context->preference('KohaAdminEmailAddress');
2680 C4::Context->preference('EmailAddressForPatronRegistrations')
2681 || C4::Context->preference('ReplytoDefault')
2682 || C4::Context->preference('KohaAdminEmailAddress');
2685 my $message_id = C4::Letters::EnqueueLetter(
2688 borrowernumber => $self->borrowernumber,
2689 to_address => $to_address,
2690 message_transport_type => 'email'
2692 ) or warn "can't enqueue letter $letter";
2693 if ( $message_id ) {
2699 =head3 has_messaging_preference
2701 my $bool = $patron->has_messaging_preference({
2702 message_name => $message_name, # A value from message_attributes.message_name
2703 message_transport_type => $message_transport_type, # email, sms, phone, itiva, etc...
2704 wants_digest => $wants_digest, # 1 if you are looking for the digest version, don't pass if you just want either
2709 sub has_messaging_preference {
2710 my ( $self, $params ) = @_;
2712 my $message_name = $params->{message_name};
2713 my $message_transport_type = $params->{message_transport_type};
2714 my $wants_digest = $params->{wants_digest};
2716 return $self->_result->search_related_rs(
2717 'borrower_message_preferences',
2721 [ 'borrower_message_transport_preferences', 'message_attribute' ]
2726 =head3 can_patron_change_staff_only_lists
2728 $patron->can_patron_change_staff_only_lists;
2730 Return 1 if a patron has 'Superlibrarian' or 'Catalogue' permission.
2731 Otherwise, return 0.
2735 sub can_patron_change_staff_only_lists {
2736 my ( $self, $params ) = @_;
2737 return 1 if C4::Auth::haspermission( $self->userid, { 'catalogue' => 1 });
2741 =head3 can_patron_change_permitted_staff_lists
2743 $patron->can_patron_change_permitted_staff_lists;
2745 Return 1 if a patron has 'Superlibrarian' or 'Catalogue' and 'edit_public_list_contents' permissions.
2746 Otherwise, return 0.
2750 sub can_patron_change_permitted_staff_lists {
2751 my ( $self, $params ) = @_;
2752 return 1 if C4::Auth::haspermission( $self->userid, { 'catalogue' => 1, lists => 'edit_public_list_contents' } );
2756 =head3 encode_secret
2758 $patron->encode_secret($secret32);
2760 Secret (TwoFactorAuth expects it in base32 format) is encrypted.
2761 You still need to call ->store.
2766 my ( $self, $secret ) = @_;
2768 return $self->secret( Koha::Encryption->new->encrypt_hex($secret) );
2770 return $self->secret($secret);
2773 =head3 decoded_secret
2775 my $secret32 = $patron->decoded_secret;
2777 Decode the patron secret. We expect to get back a base32 string, but this
2778 is not checked here. Caller of encode_secret is responsible for that.
2782 sub decoded_secret {
2784 if( $self->secret ) {
2785 return Koha::Encryption->new->decrypt_hex( $self->secret );
2787 return $self->secret;
2790 =head3 virtualshelves
2792 my $shelves = $patron->virtualshelves;
2796 sub virtualshelves {
2798 return Koha::Virtualshelves->_new_from_dbic( scalar $self->_result->virtualshelves );
2803 my $savings = $patron->get_savings;
2805 Use the replacement price of patron's old and current issues to calculate how much they have 'saved' by using the library.
2812 my @itemnumbers = grep { defined $_ } ( $self->old_checkouts->get_column('itemnumber'), $self->checkouts->get_column('itemnumber') );
2814 return Koha::Items->search(
2815 { itemnumber => { -in => \@itemnumbers } },
2816 { select => [ { sum => 'me.replacementprice' } ],
2817 as => ['total_savings']
2819 )->next->get_column('total_savings') // 0;
2822 =head3 alert_subscriptions
2824 my $subscriptions = $patron->alert_subscriptions;
2826 Return a Koha::Subscriptions object containing subscriptions for which the patron has subscribed to email alerts.
2830 sub alert_subscriptions {
2833 my @alerts = $self->_result->alerts;
2834 my @subscription_ids = map { $_->externalid } @alerts;
2836 return Koha::Subscriptions->search( { subscriptionid => \@subscription_ids } );
2841 my $consent = $patron->consent(TYPE);
2843 Returns the first consent of type TYPE (there should be only one) or a new instance
2844 of Koha::Patron::Consent.
2849 my ( $self, $type ) = @_;
2850 Koha::Exceptions::MissingParameter->throw('Missing consent type') if !$type;
2851 my $consents = Koha::Patron::Consents->search(
2853 borrowernumber => $self->borrowernumber,
2857 return $consents && $consents->count
2859 : Koha::Patron::Consent->new( { borrowernumber => $self->borrowernumber, type => $type } );
2862 =head2 Internal methods
2874 Kyle M Hall <kyle@bywatersolutions.com>
2875 Alex Sassmannshausen <alex.sassmannshausen@ptfs-europe.com>
2876 Martin Renvoize <martin.renvoize@ptfs-europe.com>