Bug 34587: Move period total calculations to the backend to improve performance
[koha.git] / Koha / Patron.pm
1 package Koha::Patron;
2
3 # Copyright ByWater Solutions 2014
4 # Copyright PTFS Europe 2016
5 #
6 # This file is part of Koha.
7 #
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.
12 #
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.
17 #
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>.
20
21 use Modern::Perl;
22
23 use List::MoreUtils qw( any uniq );
24 use JSON qw( to_json );
25 use Unicode::Normalize qw( NFKD );
26 use Try::Tiny;
27 use DateTime ();
28
29 use C4::Auth qw( checkpw_hash );
30 use C4::Context;
31 use C4::Letters qw( GetPreparedLetter EnqueueLetter SendQueuedMessages );
32 use C4::Log qw( logaction );
33 use Koha::Account;
34 use Koha::ArticleRequests;
35 use Koha::AuthUtils;
36 use Koha::Caches;
37 use Koha::Checkouts;
38 use Koha::CirculationRules;
39 use Koha::Club::Enrollments;
40 use Koha::CurbsidePickups;
41 use Koha::Database;
42 use Koha::DateUtils qw( dt_from_string );
43 use Koha::Encryption;
44 use Koha::Exceptions;
45 use Koha::Exceptions::Password;
46 use Koha::Holds;
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;
61 use Koha::Patrons;
62 use Koha::Plugins;
63 use Koha::Recalls;
64 use Koha::Result::Boolean;
65 use Koha::Subscription::Routinglists;
66 use Koha::Token;
67 use Koha::Virtualshelves;
68
69 use base qw(Koha::Object);
70
71 use constant ADMINISTRATIVE_LOCKOUT => -1;
72
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',
100 };
101
102 =head1 NAME
103
104 Koha::Patron - Koha Patron Object class
105
106 =head1 API
107
108 =head2 Class Methods
109
110 =head3 new
111
112 =cut
113
114 sub new {
115     my ( $class, $params ) = @_;
116
117     return $class->SUPER::new($params);
118 }
119
120 =head3 fixup_cardnumber
121
122 Autogenerate next cardnumber from highest value found in database
123
124 =cut
125
126 sub fixup_cardnumber {
127     my ( $self ) = @_;
128
129     my $max = $self->cardnumber;
130     Koha::Plugins->call( 'patron_barcode_transform', \$max );
131
132     $max ||= Koha::Patrons->search({
133         cardnumber => {-regexp => '^-?[0-9]+$'}
134     }, {
135         select => \'CAST(cardnumber AS SIGNED)',
136         as => ['cast_cardnumber']
137     })->_resultset->get_column('cast_cardnumber')->max;
138     $self->cardnumber(($max || 0) +1);
139 }
140
141 =head3 trim_whitespace
142
143 trim whitespace from data which has some non-whitespace in it.
144 Could be moved to Koha::Object if need to be reused
145
146 =cut
147
148 sub trim_whitespaces {
149     my( $self ) = @_;
150
151     my $schema  = Koha::Database->new->schema;
152     my @columns = $schema->source($self->_type)->columns;
153
154     for my $column( @columns ) {
155         my $value = $self->$column;
156         if ( defined $value ) {
157             $value =~ s/^\s*|\s*$//g;
158             $self->$column($value);
159         }
160     }
161     return $self;
162 }
163
164 =head3 plain_text_password
165
166 $patron->plain_text_password( $password );
167
168 stores a copy of the unencrypted password in the object
169 for use in code before encrypting for db
170
171 =cut
172
173 sub plain_text_password {
174     my ( $self, $password ) = @_;
175     if ( $password ) {
176         $self->{_plain_text_password} = $password;
177         return $self;
178     }
179     return $self->{_plain_text_password}
180         if $self->{_plain_text_password};
181
182     return;
183 }
184
185 =head3 store
186
187 Patron specific store method to cleanup record
188 and do other necessary things before saving
189 to db
190
191 =cut
192
193 sub store {
194     my ($self) = @_;
195
196     $self->_result->result_source->schema->txn_do(
197         sub {
198             if (
199                 C4::Context->preference("autoMemberNum")
200                 and ( not defined $self->cardnumber
201                     or $self->cardnumber eq '' )
202               )
203             {
204                 # Warning: The caller is responsible for locking the members table in write
205                 # mode, to avoid database corruption.
206                 # We are in a transaction but the table is not locked
207                 $self->fixup_cardnumber;
208             }
209
210             unless( $self->category->in_storage ) {
211                 Koha::Exceptions::Object::FKConstraint->throw(
212                     broken_fk => 'categorycode',
213                     value     => $self->categorycode,
214                 );
215             }
216
217             $self->trim_whitespaces;
218
219             my $new_cardnumber = $self->cardnumber;
220             Koha::Plugins->call( 'patron_barcode_transform', \$new_cardnumber );
221             $self->cardnumber( $new_cardnumber );
222
223             # Set surname to uppercase if uppercasesurname is true
224             $self->surname( uc($self->surname) )
225                 if C4::Context->preference("uppercasesurnames");
226
227             $self->relationship(undef) # We do not want to store an empty string in this field
228               if defined $self->relationship
229                      and $self->relationship eq "";
230
231             unless ( $self->in_storage ) {    #AddMember
232
233                 # Generate a valid userid/login if needed
234                 $self->generate_userid unless $self->userid;
235                 Koha::Exceptions::Patron::InvalidUserid->throw( userid => $self->userid )
236                     unless $self->has_valid_userid;
237
238                 # Add expiration date if it isn't already there
239                 unless ( $self->dateexpiry ) {
240                     $self->dateexpiry( $self->category->get_expiry_date );
241                 }
242
243                 # Add enrollment date if it isn't already there
244                 unless ( $self->dateenrolled ) {
245                     $self->dateenrolled(dt_from_string);
246                 }
247
248                 # Set the privacy depending on the patron's category
249                 my $default_privacy = $self->category->default_privacy || q{};
250                 $default_privacy =
251                     $default_privacy eq 'default' ? 1
252                   : $default_privacy eq 'never'   ? 2
253                   : $default_privacy eq 'forever' ? 0
254                   :                                                   undef;
255                 $self->privacy($default_privacy);
256
257                 # Call any check_password plugins if password is passed
258                 if ( C4::Context->config("enable_plugins") && $self->password ) {
259                     my @plugins = Koha::Plugins->new()->GetPlugins({
260                         method => 'check_password',
261                     });
262                     foreach my $plugin ( @plugins ) {
263                         # This plugin hook will also be used by a plugin for the Norwegian national
264                         # patron database. This is why we need to pass both the password and the
265                         # borrowernumber to the plugin.
266                         my $ret = $plugin->check_password(
267                             {
268                                 password       => $self->password,
269                                 borrowernumber => $self->borrowernumber
270                             }
271                         );
272                         if ( $ret->{'error'} == 1 ) {
273                             Koha::Exceptions::Password::Plugin->throw();
274                         }
275                     }
276                 }
277
278                 # Make a copy of the plain text password for later use
279                 $self->plain_text_password( $self->password );
280
281                 $self->password_expiration_date( $self->password
282                     ? $self->category->get_password_expiry_date || undef
283                     : undef );
284                 # Create a disabled account if no password provided
285                 $self->password( $self->password
286                     ? Koha::AuthUtils::hash_password( $self->password )
287                     : '!' );
288
289                 $self->borrowernumber(undef);
290
291                 $self = $self->SUPER::store;
292
293                 $self->add_enrolment_fee_if_needed(0);
294
295                 logaction( "MEMBERS", "CREATE", $self->borrowernumber, "" )
296                   if C4::Context->preference("BorrowersLog");
297             }
298             else {    #ModMember
299
300                 my $self_from_storage = $self->get_from_storage;
301
302                 # Do not accept invalid userid here
303                 $self->generate_userid unless $self->userid;
304                 Koha::Exceptions::Patron::InvalidUserid->throw( userid => $self->userid )
305                       unless $self->has_valid_userid;
306
307                 # If a borrower has set their privacy to never we should immediately anonymize
308                 # their checkouts
309                 if( $self->privacy() == 2 && $self_from_storage->privacy() != 2 ){
310                     try{
311                         $self->old_checkouts->anonymize;
312                     }
313                     catch {
314                         Koha::Exceptions::Patron::FailedAnonymizing->throw(
315                             error => @_
316                         );
317                     };
318                 }
319
320                 # Password must be updated using $self->set_password
321                 $self->password($self_from_storage->password);
322
323                 if ( $self->category->categorycode ne
324                     $self_from_storage->category->categorycode )
325                 {
326                     # Add enrolement fee on category change if required
327                     $self->add_enrolment_fee_if_needed(1)
328                       if C4::Context->preference('FeeOnChangePatronCategory');
329
330                     # Clean up guarantors on category change if required
331                     $self->guarantor_relationships->delete
332                       unless ( $self->category->can_be_guarantee );
333
334                 }
335
336                 # Actionlogs
337                 if ( C4::Context->preference("BorrowersLog") ) {
338                     my $info;
339                     my $from_storage = $self_from_storage->unblessed;
340                     my $from_object  = $self->unblessed;
341                     my @skip_fields  = (qw/lastseen updated_on/);
342                     for my $key ( keys %{$from_storage} ) {
343                         next if any { /$key/ } @skip_fields;
344                         if (
345                             (
346                                   !defined( $from_storage->{$key} )
347                                 && defined( $from_object->{$key} )
348                             )
349                             || ( defined( $from_storage->{$key} )
350                                 && !defined( $from_object->{$key} ) )
351                             || (
352                                    defined( $from_storage->{$key} )
353                                 && defined( $from_object->{$key} )
354                                 && ( $from_storage->{$key} ne
355                                     $from_object->{$key} )
356                             )
357                           )
358                         {
359                             $info->{$key} = {
360                                 before => $from_storage->{$key},
361                                 after  => $from_object->{$key}
362                             };
363                         }
364                     }
365
366                     if ( defined($info) ) {
367                         logaction(
368                             "MEMBERS",
369                             "MODIFY",
370                             $self->borrowernumber,
371                             to_json(
372                                 $info,
373                                 { utf8 => 1, pretty => 1, canonical => 1 }
374                             )
375                         );
376                     }
377                 }
378
379                 # Final store
380                 $self = $self->SUPER::store;
381             }
382         }
383     );
384     return $self;
385 }
386
387 =head3 delete
388
389 $patron->delete
390
391 Delete patron's holds, lists and finally the patron.
392
393 Lists owned by the borrower are deleted or ownership is transferred depending on the
394 ListOwnershipUponPatronDeletion pref, but entries from the borrower to other lists are kept.
395
396 =cut
397
398 sub delete {
399     my ($self) = @_;
400
401     my $anonymous_patron = C4::Context->preference("AnonymousPatron");
402     Koha::Exceptions::Patron::FailedDeleteAnonymousPatron->throw() if $anonymous_patron && $self->id eq $anonymous_patron;
403
404     $self->_result->result_source->schema->txn_do(
405         sub {
406             # Cancel Patron's holds
407             my $holds = $self->holds;
408             while( my $hold = $holds->next ){
409                 $hold->cancel;
410             }
411
412             # Handle lists (virtualshelves)
413             $self->virtualshelves->disown_or_delete;
414
415             # We cannot have a FK on borrower_modifications.borrowernumber, the table is also used
416             # for patron selfreg
417             $_->delete for Koha::Patron::Modifications->search( { borrowernumber => $self->borrowernumber } )->as_list;
418
419             $self->SUPER::delete;
420
421             logaction( "MEMBERS", "DELETE", $self->borrowernumber, "" ) if C4::Context->preference("BorrowersLog");
422         }
423     );
424     return $self;
425 }
426
427 =head3 category
428
429 my $patron_category = $patron->category
430
431 Return the patron category for this patron
432
433 =cut
434
435 sub category {
436     my ( $self ) = @_;
437     return Koha::Patron::Category->_new_from_dbic( $self->_result->categorycode );
438 }
439
440 =head3 image
441
442 =cut
443
444 sub image {
445     my ( $self ) = @_;
446
447     return Koha::Patron::Images->find( $self->borrowernumber );
448 }
449
450 =head3 library
451
452 Returns a Koha::Library object representing the patron's home library.
453
454 =cut
455
456 sub library {
457     my ( $self ) = @_;
458     return Koha::Library->_new_from_dbic($self->_result->branchcode);
459 }
460
461 =head3 sms_provider
462
463 Returns a Koha::SMS::Provider object representing the patron's SMS provider.
464
465 =cut
466
467 sub sms_provider {
468     my ( $self ) = @_;
469     my $sms_provider_rs = $self->_result->sms_provider;
470     return unless $sms_provider_rs;
471     return Koha::SMS::Provider->_new_from_dbic($sms_provider_rs);
472 }
473
474 =head3 guarantor_relationships
475
476 Returns Koha::Patron::Relationships object for this patron's guarantors
477
478 Returns the set of relationships for the patrons that are guarantors for this patron.
479
480 Note that a guarantor should exist as a patron in Koha; it was not possible
481 to add them without a guarantor_id in the interface for some time. Bug 30472
482 restricts it on db level.
483
484 =cut
485
486 sub guarantor_relationships {
487     my ($self) = @_;
488
489     return Koha::Patron::Relationships->search( { guarantee_id => $self->id } );
490 }
491
492 =head3 guarantee_relationships
493
494 Returns Koha::Patron::Relationships object for this patron's guarantors
495
496 Returns the set of relationships for the patrons that are guarantees for this patron.
497
498 The method returns Koha::Patron::Relationship objects for the sake
499 of consistency with the guantors method.
500 A guarantee by definition must exist as a patron in Koha.
501
502 =cut
503
504 sub guarantee_relationships {
505     my ($self) = @_;
506
507     return Koha::Patron::Relationships->search(
508         { guarantor_id => $self->id },
509         {
510             prefetch => 'guarantee',
511             order_by => { -asc => [ 'guarantee.surname', 'guarantee.firstname' ] },
512         }
513     );
514 }
515
516 =head3 relationships_debt
517
518 Returns the amount owed by the patron's guarantors *and* the other guarantees of those guarantors
519
520 =cut
521
522 sub relationships_debt {
523     my ($self, $params) = @_;
524
525     my $include_guarantors  = $params->{include_guarantors};
526     my $only_this_guarantor = $params->{only_this_guarantor};
527     my $include_this_patron = $params->{include_this_patron};
528
529     my @guarantors;
530     if ( $only_this_guarantor ) {
531         @guarantors = $self->guarantee_relationships->count ? ( $self ) : ();
532         Koha::Exceptions::BadParameter->throw( { parameter => 'only_this_guarantor' } ) unless @guarantors;
533     } elsif ( $self->guarantor_relationships->count ) {
534         # I am a guarantee, just get all my guarantors
535         @guarantors = $self->guarantor_relationships->guarantors->as_list;
536     } else {
537         # I am a guarantor, I need to get all the guarantors of all my guarantees
538         @guarantors = map { $_->guarantor_relationships->guarantors->as_list } $self->guarantee_relationships->guarantees->as_list;
539     }
540
541     my $non_issues_charges = 0;
542     my $seen = $include_this_patron ? {} : { $self->id => 1 }; # For tracking members already added to the total
543     foreach my $guarantor (@guarantors) {
544         $non_issues_charges += $guarantor->account->non_issues_charges if $include_guarantors && !$seen->{ $guarantor->id };
545
546         # We've added what the guarantor owes, not added in that guarantor's guarantees as well
547         my @guarantees = map { $_->guarantee } $guarantor->guarantee_relationships->as_list;
548         my $guarantees_non_issues_charges = 0;
549         foreach my $guarantee (@guarantees) {
550             next if $seen->{ $guarantee->id };
551             $guarantees_non_issues_charges += $guarantee->account->non_issues_charges;
552             # Mark this guarantee as seen so we don't double count a guarantee linked to multiple guarantors
553             $seen->{ $guarantee->id } = 1;
554         }
555
556         $non_issues_charges += $guarantees_non_issues_charges;
557         $seen->{ $guarantor->id } = 1;
558     }
559
560     return $non_issues_charges;
561 }
562
563 =head3 housebound_profile
564
565 Returns the HouseboundProfile associated with this patron.
566
567 =cut
568
569 sub housebound_profile {
570     my ( $self ) = @_;
571     my $profile = $self->_result->housebound_profile;
572     return Koha::Patron::HouseboundProfile->_new_from_dbic($profile)
573         if ( $profile );
574     return;
575 }
576
577 =head3 housebound_role
578
579 Returns the HouseboundRole associated with this patron.
580
581 =cut
582
583 sub housebound_role {
584     my ( $self ) = @_;
585
586     my $role = $self->_result->housebound_role;
587     return Koha::Patron::HouseboundRole->_new_from_dbic($role) if ( $role );
588     return;
589 }
590
591 =head3 siblings
592
593 Returns the siblings of this patron.
594
595 =cut
596
597 sub siblings {
598     my ($self) = @_;
599
600     my @guarantors = $self->guarantor_relationships()->guarantors()->as_list;
601
602     return unless @guarantors;
603
604     my @siblings =
605       map { $_->guarantee_relationships()->guarantees()->as_list } @guarantors;
606
607     return unless @siblings;
608
609     my %seen;
610     @siblings =
611       grep { !$seen{ $_->id }++ && ( $_->id != $self->id ) } @siblings;
612
613     return Koha::Patrons->search( { borrowernumber => { -in => [ map { $_->id } @siblings ] } } );
614 }
615
616 =head3 merge_with
617
618     my $patron = Koha::Patrons->find($id);
619     $patron->merge_with( \@patron_ids );
620
621     This subroutine merges a list of patrons into the patron record. This is accomplished by finding
622     all related patron ids for the patrons to be merged in other tables and changing the ids to be that
623     of the keeper patron.
624
625 =cut
626
627 sub merge_with {
628     my ( $self, $patron_ids ) = @_;
629
630     my $anonymous_patron = C4::Context->preference("AnonymousPatron");
631     return if $anonymous_patron && $self->id eq $anonymous_patron;
632
633     my @patron_ids = @{ $patron_ids };
634
635     # Ensure the keeper isn't in the list of patrons to merge
636     @patron_ids = grep { $_ ne $self->id } @patron_ids;
637
638     my $schema = Koha::Database->new()->schema();
639
640     my $results;
641
642     $self->_result->result_source->schema->txn_do( sub {
643         foreach my $patron_id (@patron_ids) {
644
645             next if $patron_id eq $anonymous_patron;
646
647             my $patron = Koha::Patrons->find( $patron_id );
648
649             next unless $patron;
650
651             # Unbless for safety, the patron will end up being deleted
652             $results->{merged}->{$patron_id}->{patron} = $patron->unblessed;
653
654             my $attributes = $patron->extended_attributes;
655             my $new_attributes = [
656                 map { { code => $_->code, attribute => $_->attribute } }
657                     $attributes->as_list
658             ];
659             $attributes->delete; # We need to delete before trying to merge them to prevent exception on unique and repeatable
660             for my $attribute ( @$new_attributes ) {
661                 try {
662                     $self->add_extended_attribute($attribute);
663                 } catch {
664                     # Don't block the merge if there is a non-repeatable attribute that cannot be added to the current patron.
665                     unless ( $_->isa('Koha::Exceptions::Patron::Attribute::NonRepeatable') ) {
666                         $_->rethrow;
667                     }
668                 };
669             }
670
671             while (my ($r, $field) = each(%$RESULTSET_PATRON_ID_MAPPING)) {
672                 my $rs = $schema->resultset($r)->search({ $field => $patron_id });
673                 $results->{merged}->{ $patron_id }->{updated}->{$r} = $rs->count();
674                 $rs->update({ $field => $self->id });
675                 if ( $r eq 'BorrowerDebarment' ) {
676                     Koha::Patron::Debarments::UpdateBorrowerDebarmentFlags($self->id);
677                 }
678             }
679
680             $patron->move_to_deleted();
681             $patron->delete();
682         }
683     });
684
685     return $results;
686 }
687
688
689 =head3 messaging_preferences
690
691     my $patron = Koha::Patrons->find($id);
692     $patron->messaging_preferences();
693
694 =cut
695
696 sub messaging_preferences {
697     my ( $self ) = @_;
698
699     return Koha::Patron::MessagePreferences->search({
700         borrowernumber => $self->borrowernumber,
701     });
702 }
703
704 =head3 wants_check_for_previous_checkout
705
706     $wants_check = $patron->wants_check_for_previous_checkout;
707
708 Return 1 if Koha needs to perform PrevIssue checking, else 0.
709
710 =cut
711
712 sub wants_check_for_previous_checkout {
713     my ( $self ) = @_;
714     my $syspref = C4::Context->preference("checkPrevCheckout");
715
716     # Simple cases
717     ## Hard syspref trumps all
718     return 1 if ($syspref eq 'hardyes');
719     return 0 if ($syspref eq 'hardno');
720     ## Now, patron pref trumps all
721     return 1 if ($self->checkprevcheckout eq 'yes');
722     return 0 if ($self->checkprevcheckout eq 'no');
723
724     # More complex: patron inherits -> determine category preference
725     my $checkPrevCheckoutByCat = $self->category->checkprevcheckout;
726     return 1 if ($checkPrevCheckoutByCat eq 'yes');
727     return 0 if ($checkPrevCheckoutByCat eq 'no');
728
729     # Finally: category preference is inherit, default to 0
730     if ($syspref eq 'softyes') {
731         return 1;
732     } else {
733         return 0;
734     }
735 }
736
737 =head3 do_check_for_previous_checkout
738
739     $do_check = $patron->do_check_for_previous_checkout($item);
740
741 Return 1 if the bib associated with $ITEM has previously been checked out to
742 $PATRON, 0 otherwise.
743
744 =cut
745
746 sub do_check_for_previous_checkout {
747     my ( $self, $item ) = @_;
748
749     my @item_nos;
750     my $biblio = Koha::Biblios->find( $item->{biblionumber} );
751     if ( $biblio->is_serial ) {
752         push @item_nos, $item->{itemnumber};
753     } else {
754         # Get all itemnumbers for given bibliographic record.
755         @item_nos = $biblio->items->get_column( 'itemnumber' );
756     }
757
758     # Create (old)issues search criteria
759     my $criteria = {
760         borrowernumber => $self->borrowernumber,
761         itemnumber => \@item_nos,
762     };
763
764     my $delay = C4::Context->preference('CheckPrevCheckoutDelay') || 0;
765     if ($delay) {
766         my $dtf = Koha::Database->new->schema->storage->datetime_parser;
767         my $newer_than = dt_from_string()->subtract( days => $delay );
768         $criteria->{'returndate'} = { '>'   =>  $dtf->format_datetime($newer_than), };
769     }
770
771     # Check current issues table
772     my $issues = Koha::Checkouts->search($criteria);
773     return 1 if $issues->count; # 0 || N
774
775     # Check old issues table
776     my $old_issues = Koha::Old::Checkouts->search($criteria);
777     return $old_issues->count;  # 0 || N
778 }
779
780 =head3 is_debarred
781
782 my $debarment_expiration = $patron->is_debarred;
783
784 Returns the date a patron debarment will expire, or undef if the patron is not
785 debarred
786
787 =cut
788
789 sub is_debarred {
790     my ($self) = @_;
791
792     return unless $self->debarred;
793     return $self->debarred
794       if $self->debarred =~ '^9999'
795       or dt_from_string( $self->debarred ) > dt_from_string;
796     return;
797 }
798
799 =head3 is_expired
800
801 my $is_expired = $patron->is_expired;
802
803 Returns 1 if the patron is expired or 0;
804
805 =cut
806
807 sub is_expired {
808     my ($self) = @_;
809     return 0 unless $self->dateexpiry;
810     return 0 if $self->dateexpiry =~ '^9999';
811     return 1 if dt_from_string( $self->dateexpiry ) < dt_from_string->truncate( to => 'day' );
812     return 0;
813 }
814
815 =head3 is_active
816
817 $patron->is_active({ [ since => $date ], [ days|weeks|months|years => $value ] })
818
819 A patron is considered 'active' if the following conditions hold:
820
821     - account did not expire
822     - account has not been anonymized
823     - enrollment or lastseen within period specified
824
825 Note: lastseen is updated for triggers defined in preference
826 TrackLastPatronActivityTriggers. This includes logins, issues, holds, etc.
827
828 The period to check is defined by $date or $value in days, weeks or months. You should
829 pass one of those; otherwise an exception is thrown.
830
831 =cut
832
833 sub is_active {
834     my ( $self, $params ) = @_;
835     return 0 if $self->is_expired or $self->anonymized;
836
837     my $dt;
838     if ( $params->{since} ) {
839         $dt = dt_from_string( $params->{since}, 'iso' );
840     } elsif ( grep { $params->{$_} } qw(days weeks months years) ) {
841         $dt = dt_from_string();
842         foreach my $duration (qw(days weeks months years)) {
843             $dt = $dt->subtract( $duration => $params->{$duration} ) if $params->{$duration};
844         }
845     } else {
846         Koha::Exceptions::MissingParameter->throw('is_active needs date or period');
847     }
848
849     # Enrollment within this period?
850     return 1 if DateTime->compare( dt_from_string( $self->dateenrolled ), $dt ) > -1;
851
852     # We look at lastseen regardless of TrackLastPatronActivityTriggers. If lastseen is set
853     # recently, the triggers may have been removed after that, etc.
854     return 1 if $self->lastseen && DateTime->compare( dt_from_string( $self->lastseen ), $dt ) > -1;
855
856     return 0;
857 }
858
859 =head3 password_expired
860
861 my $password_expired = $patron->password_expired;
862
863 Returns 1 if the patron's password is expired or 0;
864
865 =cut
866
867 sub password_expired {
868     my ($self) = @_;
869     return 0 unless $self->password_expiration_date;
870     return 1 if dt_from_string( $self->password_expiration_date ) <= dt_from_string->truncate( to => 'day' );
871     return 0;
872 }
873
874 =head3 is_going_to_expire
875
876 my $is_going_to_expire = $patron->is_going_to_expire;
877
878 Returns 1 if the patron is going to expired, depending on the NotifyBorrowerDeparture pref or 0
879
880 =cut
881
882 sub is_going_to_expire {
883     my ($self) = @_;
884
885     my $delay = C4::Context->preference('NotifyBorrowerDeparture') || 0;
886
887     return 0 unless $delay;
888     return 0 unless $self->dateexpiry;
889     return 0 if $self->dateexpiry =~ '^9999';
890     return 1 if dt_from_string( $self->dateexpiry, undef, 'floating' )->subtract( days => $delay ) < dt_from_string(undef, undef, 'floating')->truncate( to => 'day' );
891     return 0;
892 }
893
894 =head3 set_password
895
896     $patron->set_password({ password => $plain_text_password [, skip_validation => 1 ] });
897
898 Set the patron's password.
899
900 =head4 Exceptions
901
902 The passed string is validated against the current password enforcement policy.
903 Validation can be skipped by passing the I<skip_validation> parameter.
904
905 Exceptions are thrown if the password is not good enough.
906
907 =over 4
908
909 =item Koha::Exceptions::Password::TooShort
910
911 =item Koha::Exceptions::Password::WhitespaceCharacters
912
913 =item Koha::Exceptions::Password::TooWeak
914
915 =item Koha::Exceptions::Password::Plugin (if a "check password" plugin is enabled)
916
917 =back
918
919 =cut
920
921 sub set_password {
922     my ( $self, $args ) = @_;
923
924     my $password = $args->{password};
925
926     unless ( $args->{skip_validation} ) {
927         my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, $self->category );
928
929         if ( !$is_valid ) {
930             if ( $error eq 'too_short' ) {
931                 my $min_length = $self->category->effective_min_password_length;
932                 $min_length = 3 if not $min_length or $min_length < 3;
933
934                 my $password_length = length($password);
935                 Koha::Exceptions::Password::TooShort->throw(
936                     length => $password_length, min_length => $min_length );
937             }
938             elsif ( $error eq 'has_whitespaces' ) {
939                 Koha::Exceptions::Password::WhitespaceCharacters->throw();
940             }
941             elsif ( $error eq 'too_weak' ) {
942                 Koha::Exceptions::Password::TooWeak->throw();
943             }
944         }
945     }
946
947     if ( C4::Context->config("enable_plugins") ) {
948         # Call any check_password plugins
949         my @plugins = Koha::Plugins->new()->GetPlugins({
950             method => 'check_password',
951         });
952         foreach my $plugin ( @plugins ) {
953             # This plugin hook will also be used by a plugin for the Norwegian national
954             # patron database. This is why we need to pass both the password and the
955             # borrowernumber to the plugin.
956             my $ret = $plugin->check_password(
957                 {
958                     password       => $password,
959                     borrowernumber => $self->borrowernumber
960                 }
961             );
962             # This plugin hook will also be used by a plugin for the Norwegian national
963             # patron database. This is why we need to call the actual plugins and then
964             # check skip_validation afterwards.
965             if ( $ret->{'error'} == 1 && !$args->{skip_validation} ) {
966                 Koha::Exceptions::Password::Plugin->throw();
967             }
968         }
969     }
970
971     if ( C4::Context->preference('NotifyPasswordChange') ) {
972         my $self_from_storage = $self->get_from_storage;
973         if ( !C4::Auth::checkpw_hash( $password, $self_from_storage->password ) ) {
974             my $emailaddr = $self_from_storage->notice_email_address;
975
976             # if we manage to find a valid email address, send notice
977             if ($emailaddr) {
978                 my $letter = C4::Letters::GetPreparedLetter(
979                     module      => 'members',
980                     letter_code => 'PASSWORD_CHANGE',
981                     branchcode  => $self_from_storage->branchcode,
982                     ,
983                     lang   => $self_from_storage->lang || 'default',
984                     tables => {
985                         'branches'  => $self_from_storage->branchcode,
986                         'borrowers' => $self_from_storage->borrowernumber,
987                     },
988                     want_librarian => 1,
989                 ) or return;
990
991                 my $message_id = C4::Letters::EnqueueLetter(
992                     {
993                         letter                 => $letter,
994                         borrowernumber         => $self_from_storage->id,
995                         to_address             => $emailaddr,
996                         message_transport_type => 'email'
997                     }
998                 );
999                 C4::Letters::SendQueuedMessages( { message_id => $message_id } ) if $message_id;
1000             }
1001         }
1002     }
1003
1004     my $digest = Koha::AuthUtils::hash_password($password);
1005
1006     $self->password_expiration_date( $self->category->get_password_expiry_date || undef );
1007
1008     # We do not want to call $self->store and retrieve password from DB
1009     $self->password($digest);
1010     $self->login_attempts(0);
1011     $self->SUPER::store;
1012
1013     logaction( "MEMBERS", "CHANGE PASS", $self->borrowernumber, "" )
1014         if C4::Context->preference("BorrowersLog");
1015
1016     return $self;
1017 }
1018
1019
1020 =head3 renew_account
1021
1022 my $new_expiry_date = $patron->renew_account
1023
1024 Extending the subscription to the expiry date.
1025
1026 =cut
1027
1028 sub renew_account {
1029     my ($self) = @_;
1030     my $date;
1031     if ( C4::Context->preference('BorrowerRenewalPeriodBase') eq 'combination' ) {
1032         $date = ( dt_from_string gt dt_from_string( $self->dateexpiry ) ) ? dt_from_string : dt_from_string( $self->dateexpiry );
1033     } else {
1034         $date =
1035             C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry'
1036             ? dt_from_string( $self->dateexpiry )
1037             : dt_from_string;
1038     }
1039     my $expiry_date = $self->category->get_expiry_date($date);
1040
1041     $self->dateexpiry($expiry_date);
1042     $self->date_renewed( dt_from_string() );
1043     $self->store();
1044
1045     $self->add_enrolment_fee_if_needed(1);
1046
1047     logaction( "MEMBERS", "RENEW", $self->borrowernumber, "Membership renewed" ) if C4::Context->preference("BorrowersLog");
1048     return dt_from_string( $expiry_date )->truncate( to => 'day' );
1049 }
1050
1051 =head3 has_overdues
1052
1053 my $has_overdues = $patron->has_overdues;
1054
1055 Returns the number of patron's overdues
1056
1057 =cut
1058
1059 sub has_overdues {
1060     my ($self) = @_;
1061     my $date = dt_from_string();
1062     my $dtf = Koha::Database->new->schema->storage->datetime_parser;
1063     return $self->_result->issues->search({ date_due => { '<' => $dtf->format_datetime($date) } })->count;
1064 }
1065
1066
1067
1068 =head3 has_restricting_overdues
1069
1070 my $has_restricting_overdues = $patron->has_restricting_overdues({ issue_branchcode => $branchcode });
1071
1072 Returns true if patron has overdues that would result in debarment.
1073
1074 =cut
1075
1076 sub has_restricting_overdues {
1077     my ( $self, $params ) = @_;
1078     $params //= {};
1079     my $date = dt_from_string()->truncate( to => 'day' );
1080
1081     # If ignoring unrestricted overdues, calculate which delay value for
1082     # overdue messages is set with restrictions. Then only include overdue
1083     # issues older than that date when counting.
1084     #TODO: bail out/throw exception if $params->{issue_branchcode} not set?
1085     my $debarred_delay = _get_overdue_debarred_delay( $params->{issue_branchcode}, $self->categorycode() );
1086     return 0 unless defined $debarred_delay;
1087
1088     # Emulate the conditions in overdue_notices.pl.
1089     # The overdue_notices-script effectively truncates both issues.date_due and current date
1090     # to days when selecting overdue issues.
1091     # Hours and minutes for issues.date_due is usually set to 23 and 59 respectively, though can theoretically
1092     # be set to any other value (truncated to minutes, except if CalcDateDue gets a $startdate)
1093     #
1094     # No matter what time of day date_due is set to, overdue_notices.pl will select all issues that are due
1095     # the current date or later. We can emulate this query by instead of truncating both to days in the SQL-query,
1096     # using the condition that date_due must be less then the current date truncated to days (time set to 00:00:00)
1097     # offset by one day in the future.
1098
1099     $date->add( days => 1 );
1100
1101     my $calendar;
1102     if ( C4::Context->preference('OverdueNoticeCalendar') ) {
1103         $calendar = Koha::Calendar->new( branchcode => $params->{issue_branchcode} );
1104     }
1105
1106     my $dtf    = Koha::Database->new->schema->storage->datetime_parser;
1107     my $issues = $self->_result->issues->search( { date_due => { '<' => $dtf->format_datetime($date) } } );
1108     my $now    = dt_from_string();
1109
1110     while ( my $issue = $issues->next ) {
1111         my $days_between =
1112             C4::Context->preference('OverdueNoticeCalendar')
1113             ? $calendar->days_between( dt_from_string( $issue->date_due ), $now )->in_units('days')
1114             : $now->delta_days( dt_from_string( $issue->date_due ) )->in_units('days');
1115         if ( $days_between >= $debarred_delay ) {
1116             return 1;
1117         }
1118     }
1119     return 0;
1120 }
1121
1122 # Fetch first delayX value from overduerules where debarredX is set, or 0 for no delay
1123 sub _get_overdue_debarred_delay {
1124     my ( $branchcode, $categorycode ) = @_;
1125     my $dbh = C4::Context->dbh();
1126
1127     # We get default rules if there is no rule for this branch
1128     my $rule = Koha::OverdueRules->find(
1129         {
1130             branchcode   => $branchcode,
1131             categorycode => $categorycode
1132         }
1133         )
1134         || Koha::OverdueRules->find(
1135         {
1136             branchcode   => q{},
1137             categorycode => $categorycode
1138         }
1139         );
1140
1141     if ($rule) {
1142         return $rule->delay1 if $rule->debarred1;
1143         return $rule->delay2 if $rule->debarred2;
1144         return $rule->delay3 if $rule->debarred3;
1145     }
1146 }
1147
1148 =head3 update_lastseen
1149
1150   $patron->update_lastseen('activity');
1151
1152 Updates the lastseen field, limited to one update per day, whenever the activity passed is
1153 listed in TrackLastPatronActivityTriggers.
1154
1155 The method should be called upon successful completion of the activity.
1156
1157 =cut
1158
1159 sub update_lastseen {
1160     my ( $self, $activity ) = @_;
1161     my $tracked_activities = {
1162         map { ( lc $_, 1 ); } split /\s*\,\s*/,
1163         C4::Context->preference('TrackLastPatronActivityTriggers')
1164     };
1165     return $self unless $tracked_activities->{$activity};
1166
1167     my $cache     = Koha::Caches->get_instance();
1168     my $cache_key = "track_activity_" . $self->borrowernumber;
1169     my $cached    = $cache->get_from_cache($cache_key);
1170     my $now       = dt_from_string();
1171     return $self if $cached && $cached eq $now->ymd;
1172
1173     $self->lastseen($now)->store;
1174     $cache->set_in_cache( $cache_key, $now->ymd );
1175     return $self;
1176 }
1177
1178 =head3 move_to_deleted
1179
1180 my $is_moved = $patron->move_to_deleted;
1181
1182 Move a patron to the deletedborrowers table.
1183 This can be done before deleting a patron, to make sure the data are not completely deleted.
1184
1185 =cut
1186
1187 sub move_to_deleted {
1188     my ($self) = @_;
1189     my $patron_infos = $self->unblessed;
1190     delete $patron_infos->{updated_on}; #This ensures the updated_on date in deletedborrowers will be set to the current timestamp
1191     return Koha::Database->new->schema->resultset('Deletedborrower')->create($patron_infos);
1192 }
1193
1194 =head3 can_request_article
1195
1196     if ( $patron->can_request_article( $library->id ) ) { ... }
1197
1198 Returns true if the patron can request articles. As limits apply for the patron
1199 on the same day, those completed the same day are considered as current.
1200
1201 A I<library_id> can be passed as parameter, falling back to userenv if absent.
1202
1203 =cut
1204
1205 sub can_request_article {
1206     my ($self, $library_id) = @_;
1207
1208     $library_id //= C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
1209
1210     my $rule = Koha::CirculationRules->get_effective_rule(
1211         {
1212             branchcode   => $library_id,
1213             categorycode => $self->categorycode,
1214             rule_name    => 'open_article_requests_limit'
1215         }
1216     );
1217
1218     my $limit = ($rule) ? $rule->rule_value : undef;
1219
1220     return 1 unless defined $limit;
1221
1222     my $count = Koha::ArticleRequests->search(
1223         [   { borrowernumber => $self->borrowernumber, status => [ 'REQUESTED', 'PENDING', 'PROCESSING' ] },
1224             { borrowernumber => $self->borrowernumber, status => 'COMPLETED', updated_on => { '>=' => \'CAST(NOW() AS DATE)' } },
1225         ]
1226     )->count;
1227     return $count < $limit ? 1 : 0;
1228 }
1229
1230 =head3 article_request_fee
1231
1232     my $fee = $patron->article_request_fee(
1233         {
1234           [ library_id => $library->id, ]
1235         }
1236     );
1237
1238 Returns the fee to be charged to the patron when it places an article request.
1239
1240 A I<library_id> can be passed as parameter, falling back to userenv if absent.
1241
1242 =cut
1243
1244 sub article_request_fee {
1245     my ($self, $params) = @_;
1246
1247     my $library_id = $params->{library_id};
1248
1249     $library_id //= C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
1250
1251     my $rule = Koha::CirculationRules->get_effective_rule(
1252         {
1253             branchcode   => $library_id,
1254             categorycode => $self->categorycode,
1255             rule_name    => 'article_request_fee'
1256         }
1257     );
1258
1259     my $fee = ($rule) ? $rule->rule_value + 0 : 0;
1260
1261     return $fee;
1262 }
1263
1264 =head3 add_article_request_fee_if_needed
1265
1266     my $fee = $patron->add_article_request_fee_if_needed(
1267         {
1268           [ item_id    => $item->id,
1269             library_id => $library->id, ]
1270         }
1271     );
1272
1273 If an article request fee needs to be charged, it adds a debit to the patron's
1274 account.
1275
1276 Returns the fee line.
1277
1278 A I<library_id> can be passed as parameter, falling back to userenv if absent.
1279
1280 =cut
1281
1282 sub add_article_request_fee_if_needed {
1283     my ($self, $params) = @_;
1284
1285     my $library_id = $params->{library_id};
1286     my $item_id    = $params->{item_id};
1287
1288     $library_id //= C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
1289
1290     my $amount = $self->article_request_fee(
1291         {
1292             library_id => $library_id,
1293         }
1294     );
1295
1296     my $debit_line;
1297
1298     if ( $amount > 0 ) {
1299         $debit_line = $self->account->add_debit(
1300             {
1301                 amount     => $amount,
1302                 user_id    => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
1303                 interface  => C4::Context->interface,
1304                 library_id => $library_id,
1305                 type       => 'ARTICLE_REQUEST',
1306                 item_id    => $item_id,
1307             }
1308         );
1309     }
1310
1311     return $debit_line;
1312 }
1313
1314 =head3 article_requests
1315
1316     my $article_requests = $patron->article_requests;
1317
1318 Returns the patron article requests.
1319
1320 =cut
1321
1322 sub article_requests {
1323     my ($self) = @_;
1324
1325     return Koha::ArticleRequests->_new_from_dbic( scalar $self->_result->article_requests );
1326 }
1327
1328 =head3 add_enrolment_fee_if_needed
1329
1330 my $enrolment_fee = $patron->add_enrolment_fee_if_needed($renewal);
1331
1332 Add enrolment fee for a patron if needed.
1333
1334 $renewal - boolean denoting whether this is an account renewal or not
1335
1336 =cut
1337
1338 sub add_enrolment_fee_if_needed {
1339     my ($self, $renewal) = @_;
1340     my $enrolment_fee = $self->category->enrolmentfee;
1341     if ( $enrolment_fee && $enrolment_fee > 0 ) {
1342         my $type = $renewal ? 'ACCOUNT_RENEW' : 'ACCOUNT';
1343         $self->account->add_debit(
1344             {
1345                 amount     => $enrolment_fee,
1346                 user_id    => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
1347                 interface  => C4::Context->interface,
1348                 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
1349                 type       => $type
1350             }
1351         );
1352     }
1353     return $enrolment_fee || 0;
1354 }
1355
1356 =head3 checkouts
1357
1358 my $checkouts = $patron->checkouts
1359
1360 =cut
1361
1362 sub checkouts {
1363     my ($self) = @_;
1364     my $checkouts = $self->_result->issues;
1365     return Koha::Checkouts->_new_from_dbic( $checkouts );
1366 }
1367
1368 =head3 pending_checkouts
1369
1370 my $pending_checkouts = $patron->pending_checkouts
1371
1372 This method will return the same as $self->checkouts, but with a prefetch on
1373 items, biblio and biblioitems.
1374
1375 It has been introduced to replaced the C4::Members::GetPendingIssues subroutine
1376
1377 It should not be used directly, prefer to access fields you need instead of
1378 retrieving all these fields in one go.
1379
1380 =cut
1381
1382 sub pending_checkouts {
1383     my( $self ) = @_;
1384     my $checkouts = $self->_result->issues->search(
1385         {},
1386         {
1387             order_by => [
1388                 { -desc => 'me.timestamp' },
1389                 { -desc => 'issuedate' },
1390                 { -desc => 'issue_id' }, # Sort by issue_id should be enough
1391             ],
1392             prefetch => { item => { biblio => 'biblioitems' } },
1393         }
1394     );
1395     return Koha::Checkouts->_new_from_dbic( $checkouts );
1396 }
1397
1398 =head3 old_checkouts
1399
1400 my $old_checkouts = $patron->old_checkouts
1401
1402 =cut
1403
1404 sub old_checkouts {
1405     my ($self) = @_;
1406     my $old_checkouts = $self->_result->old_issues;
1407     return Koha::Old::Checkouts->_new_from_dbic( $old_checkouts );
1408 }
1409
1410 =head3 overdues
1411
1412 my $overdue_items = $patron->overdues
1413
1414 Return the overdue items
1415
1416 =cut
1417
1418 sub overdues {
1419     my ($self) = @_;
1420     my $dtf = Koha::Database->new->schema->storage->datetime_parser;
1421     return $self->checkouts->search(
1422         {
1423             'me.date_due' => { '<' => $dtf->format_datetime(dt_from_string) },
1424         },
1425         {
1426             prefetch => { item => { biblio => 'biblioitems' } },
1427         }
1428     );
1429 }
1430
1431
1432 =head3 restrictions
1433
1434   my $restrictions = $patron->restrictions;
1435
1436 Returns the patron restrictions.
1437
1438 =cut
1439
1440 sub restrictions {
1441     my ($self) = @_;
1442     my $restrictions_rs = $self->_result->restrictions;
1443     return Koha::Patron::Restrictions->_new_from_dbic($restrictions_rs);
1444 }
1445
1446 =head3 get_routing_lists
1447
1448 my $routinglists = $patron->get_routing_lists
1449
1450 Returns the routing lists a patron is subscribed to.
1451
1452 =cut
1453
1454 sub get_routing_lists {
1455     my ($self) = @_;
1456     my $routing_list_rs = $self->_result->subscriptionroutinglists;
1457     return Koha::Subscription::Routinglists->_new_from_dbic($routing_list_rs);
1458 }
1459
1460 =head3 get_age
1461
1462     my $age = $patron->get_age
1463
1464 Return the age of the patron
1465
1466 =cut
1467
1468 sub get_age {
1469     my ($self)    = @_;
1470
1471     return unless $self->dateofbirth;
1472
1473     #Set timezone to floating to avoid any datetime math issues caused by DST
1474     my $date_of_birth = dt_from_string( $self->dateofbirth, undef, 'floating' );
1475     my $today         = dt_from_string(undef, undef, 'floating')->truncate( to => 'day' );
1476
1477     return $today->subtract_datetime( $date_of_birth )->years;
1478 }
1479
1480 =head3 is_valid_age
1481
1482 my $is_valid = $patron->is_valid_age
1483
1484 Return 1 if patron's age is between allowed limits, returns 0 if it's not.
1485
1486 =cut
1487
1488 sub is_valid_age {
1489     my ($self) = @_;
1490     my $age = $self->get_age;
1491
1492     my $patroncategory = $self->category;
1493     my ($low,$high) = ($patroncategory->dateofbirthrequired, $patroncategory->upperagelimit);
1494
1495     return (defined($age) && (($high && ($age > $high)) or ($low && ($age < $low)))) ? 0 : 1;
1496 }
1497
1498 =head3 account
1499
1500 my $account = $patron->account
1501
1502 =cut
1503
1504 sub account {
1505     my ($self) = @_;
1506     return Koha::Account->new( { patron_id => $self->borrowernumber } );
1507 }
1508
1509 =head3 holds
1510
1511 my $holds = $patron->holds
1512
1513 Return all the holds placed by this patron
1514
1515 =cut
1516
1517 sub holds {
1518     my ($self) = @_;
1519     my $holds_rs = $self->_result->reserves->search( {}, { order_by => 'reservedate' } );
1520     return Koha::Holds->_new_from_dbic($holds_rs);
1521 }
1522
1523 =head3 old_holds
1524
1525 my $old_holds = $patron->old_holds
1526
1527 Return all the historical holds for this patron
1528
1529 =cut
1530
1531 sub old_holds {
1532     my ($self) = @_;
1533     my $old_holds_rs = $self->_result->old_reserves->search( {}, { order_by => 'reservedate' } );
1534     return Koha::Old::Holds->_new_from_dbic($old_holds_rs);
1535 }
1536
1537 =head3 curbside_pickups
1538
1539 my $curbside_pickups = $patron->curbside_pickups;
1540
1541 Return all the curbside pickups for this patron
1542
1543 =cut
1544
1545 sub curbside_pickups {
1546     my ($self) = @_;
1547     my $curbside_pickups_rs = $self->_result->curbside_pickups_borrowernumbers->search;
1548     return Koha::CurbsidePickups->_new_from_dbic($curbside_pickups_rs);
1549 }
1550
1551 =head3 return_claims
1552
1553 my $return_claims = $patron->return_claims
1554
1555 =cut
1556
1557 sub return_claims {
1558     my ($self) = @_;
1559     my $return_claims = $self->_result->return_claims_borrowernumbers;
1560     return Koha::Checkouts::ReturnClaims->_new_from_dbic( $return_claims );
1561 }
1562
1563 =head3 notice_email_address
1564
1565   my $email = $patron->notice_email_address;
1566
1567 Return the email address of patron used for notices.
1568 Returns the empty string if no email address.
1569
1570 =cut
1571
1572 sub notice_email_address{
1573     my ( $self ) = @_;
1574
1575     my $which_address = C4::Context->preference("EmailFieldPrimary");
1576     # if syspref is set to 'first valid' (value == OFF), look up email address
1577     if ( $which_address eq 'OFF' ) {
1578         return $self->first_valid_email_address;
1579     }
1580
1581     return $self->$which_address || '';
1582 }
1583
1584 =head3 first_valid_email_address
1585
1586 my $first_valid_email_address = $patron->first_valid_email_address
1587
1588 Return the first valid email address for a patron.
1589 For now, the order  is defined as email, emailpro, B_email.
1590 Returns the empty string if the borrower has no email addresses.
1591
1592 =cut
1593
1594 sub first_valid_email_address {
1595     my ($self) = @_;
1596
1597     my $email = q{};
1598
1599     my @fields = split /\s*\|\s*/,
1600       C4::Context->preference('EmailFieldPrecedence');
1601     for my $field (@fields) {
1602         $email = $self->$field;
1603         last if ($email);
1604     }
1605
1606     return $email;
1607 }
1608
1609 =head3 get_club_enrollments
1610
1611 =cut
1612
1613 sub get_club_enrollments {
1614     my ( $self ) = @_;
1615
1616     return Koha::Club::Enrollments->search( { borrowernumber => $self->borrowernumber(), date_canceled => undef } );
1617 }
1618
1619 =head3 get_enrollable_clubs
1620
1621 =cut
1622
1623 sub get_enrollable_clubs {
1624     my ( $self, $is_enrollable_from_opac ) = @_;
1625
1626     my $params;
1627     $params->{is_enrollable_from_opac} = $is_enrollable_from_opac
1628       if $is_enrollable_from_opac;
1629     $params->{is_email_required} = 0 unless $self->first_valid_email_address();
1630
1631     $params->{borrower} = $self;
1632
1633     return Koha::Clubs->get_enrollable($params);
1634 }
1635
1636 =head3 account_locked
1637
1638 my $is_locked = $patron->account_locked
1639
1640 Return true if the patron has reached the maximum number of login attempts
1641 (see pref FailedLoginAttempts). If login_attempts is < 0, this is interpreted
1642 as an administrative lockout (independent of FailedLoginAttempts; see also
1643 Koha::Patron->lock).
1644 Otherwise return false.
1645 If the pref is not set (empty string, null or 0), the feature is considered as
1646 disabled.
1647
1648 =cut
1649
1650 sub account_locked {
1651     my ($self) = @_;
1652     my $FailedLoginAttempts = C4::Context->preference('FailedLoginAttempts');
1653     return 1 if $FailedLoginAttempts
1654           and $self->login_attempts
1655           and $self->login_attempts >= $FailedLoginAttempts;
1656     return 1 if ($self->login_attempts || 0) < 0; # administrative lockout
1657     return 0;
1658 }
1659
1660 =head3 can_see_patron_infos
1661
1662 my $can_see = $patron->can_see_patron_infos( $patron );
1663
1664 Return true if the patron (usually the logged in user) can see the patron's infos for a given patron
1665
1666 =cut
1667
1668 sub can_see_patron_infos {
1669     my ( $self, $patron ) = @_;
1670     return unless $patron;
1671     return $self->can_see_patrons_from( $patron->branchcode );
1672 }
1673
1674 =head3 can_see_patrons_from
1675
1676 my $can_see = $patron->can_see_patrons_from( $branchcode );
1677
1678 Return true if the patron (usually the logged in user) can see the patron's infos from a given library
1679
1680 =cut
1681
1682 sub can_see_patrons_from {
1683     my ( $self, $branchcode ) = @_;
1684
1685     return $self->can_see_things_from(
1686         {
1687             branchcode => $branchcode,
1688             permission => 'borrowers',
1689             subpermission => 'view_borrower_infos_from_any_libraries',
1690         }
1691     );
1692 }
1693
1694 =head3 can_edit_items_from
1695
1696     my $can_edit = $patron->can_edit_items_from( $branchcode );
1697
1698 Return true if the I<Koha::Patron> can edit items from the given branchcode
1699
1700 =cut
1701
1702 sub can_edit_items_from {
1703     my ( $self, $branchcode ) = @_;
1704
1705     return 1 if C4::Context->IsSuperLibrarian();
1706
1707     my $userenv = C4::Context->userenv();
1708     if ( $userenv && C4::Context->preference('IndependentBranches') ) {
1709         return $userenv->{branch} eq $branchcode;
1710     }
1711
1712     return $self->can_see_things_from(
1713         {
1714             branchcode    => $branchcode,
1715             permission    => 'editcatalogue',
1716             subpermission => 'edit_any_item',
1717         }
1718     );
1719 }
1720
1721 =head3 libraries_where_can_edit_items
1722
1723     my $libraries = $patron->libraries_where_can_edit_items;
1724
1725 Return the list of branchcodes(!) of libraries the patron is allowed to items for.
1726 The branchcodes are arbitrarily returned sorted.
1727 We are supposing here that the object is related to the logged in patron (use of C4::Context::only_my_library)
1728
1729 An empty array means no restriction, the user can edit any item.
1730
1731 =cut
1732
1733 sub libraries_where_can_edit_items {
1734     my ($self) = @_;
1735
1736     return $self->libraries_where_can_see_things(
1737         {
1738             permission    => 'editcatalogue',
1739             subpermission => 'edit_any_item',
1740             group_feature => 'ft_limit_item_editing',
1741         }
1742     );
1743 }
1744
1745 =head3 libraries_where_can_see_patrons
1746
1747 my $libraries = $patron->libraries_where_can_see_patrons;
1748
1749 Return the list of branchcodes(!) of libraries the patron is allowed to see other patron's infos.
1750 The branchcodes are arbitrarily returned sorted.
1751 We are supposing here that the object is related to the logged in patron (use of C4::Context::only_my_library)
1752
1753 An empty array means no restriction, the patron can see patron's infos from any libraries.
1754
1755 =cut
1756
1757 sub libraries_where_can_see_patrons {
1758     my ($self) = @_;
1759
1760     return $self->libraries_where_can_see_things(
1761         {
1762             permission    => 'borrowers',
1763             subpermission => 'view_borrower_infos_from_any_libraries',
1764             group_feature => 'ft_hide_patron_info',
1765         }
1766     );
1767 }
1768
1769 =head3 can_see_things_from
1770
1771 my $can_see = $patron->can_see_things_from( $branchcode );
1772
1773 Return true if the I<Koha::Patron> can perform some action on the given thing
1774
1775 =cut
1776
1777 sub can_see_things_from {
1778     my ( $self, $params ) = @_;
1779
1780     my $branchcode    = $params->{branchcode};
1781     my $permission    = $params->{permission};
1782     my $subpermission = $params->{subpermission};
1783
1784     return 1 if C4::Context->IsSuperLibrarian();
1785
1786     my $can = 0;
1787     if ( $self->branchcode eq $branchcode ) {
1788         $can = 1;
1789     } elsif ( $self->has_permission( { $permission => $subpermission } ) ) {
1790         $can = 1;
1791     } elsif ( my @branches = $self->libraries_where_can_see_patrons ) {
1792         $can = ( any { $_ eq $branchcode } @branches ) ? 1 : 0;
1793     }
1794     return $can;
1795 }
1796
1797 =head3 can_log_into
1798
1799 my $can_log_into = $patron->can_log_into( $library );
1800
1801 Given a I<Koha::Library> object, it returns a boolean representing
1802 the fact the patron can log into a the library.
1803
1804 =cut
1805
1806 sub can_log_into {
1807     my ( $self, $library ) = @_;
1808
1809     my $can = 0;
1810
1811     if ( C4::Context->preference('IndependentBranches') ) {
1812         $can = 1
1813           if $self->is_superlibrarian
1814           or $self->branchcode eq $library->id;
1815     }
1816     else {
1817         # no restrictions
1818         $can = 1;
1819     }
1820
1821    return $can;
1822 }
1823
1824 =head3 libraries_where_can_see_things
1825
1826     my $libraries = $patron->libraries_where_can_see_things;
1827
1828 Returns a list of libraries where an aribitarary action is allowed to be taken by the logged in librarian
1829 against an object based on some branchcode related to the object ( patron branchcode, item homebranch, etc ).
1830
1831 We are supposing here that the object is related to the logged in librarian (use of C4::Context::only_my_library)
1832
1833 An empty array means no restriction, the thing can see thing's infos from any libraries.
1834
1835 =cut
1836
1837 sub libraries_where_can_see_things {
1838     my ( $self, $params ) = @_;
1839     my $permission    = $params->{permission};
1840     my $subpermission = $params->{subpermission};
1841     my $group_feature = $params->{group_feature};
1842
1843     return $self->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"}
1844         if exists( $self->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} );
1845
1846     my $userenv = C4::Context->userenv;
1847
1848     return () unless $userenv; # For tests, but userenv should be defined in tests...
1849
1850     my @restricted_branchcodes;
1851     if (C4::Context::only_my_library) {
1852         push @restricted_branchcodes, $self->branchcode;
1853     }
1854     else {
1855         unless (
1856             $self->has_permission(
1857                 { $permission => $subpermission }
1858             )
1859           )
1860         {
1861             my $library_groups = $self->library->library_groups({ $group_feature => 1 });
1862             if ( $library_groups->count )
1863             {
1864                 while ( my $library_group = $library_groups->next ) {
1865                     my $parent = $library_group->parent;
1866                     if ( $parent->has_child( $self->branchcode ) ) {
1867                         push @restricted_branchcodes, $parent->children->get_column('branchcode');
1868                     }
1869                 }
1870             }
1871
1872             @restricted_branchcodes = ( $self->branchcode ) unless @restricted_branchcodes;
1873         }
1874     }
1875
1876     @restricted_branchcodes = grep { defined $_ } @restricted_branchcodes;
1877     @restricted_branchcodes = uniq(@restricted_branchcodes);
1878     @restricted_branchcodes = sort(@restricted_branchcodes);
1879
1880     $self->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} = \@restricted_branchcodes;
1881     return @{ $self->{"_restricted_branchcodes:$permission:$subpermission:$group_feature"} };
1882 }
1883
1884 =head3 has_permission
1885
1886 my $permission = $patron->has_permission($required);
1887
1888 See C4::Auth::haspermission for details of syntax for $required
1889
1890 =cut
1891
1892 sub has_permission {
1893     my ( $self, $flagsrequired ) = @_;
1894     return unless $self->userid;
1895     # TODO code from haspermission needs to be moved here!
1896     return C4::Auth::haspermission( $self->userid, $flagsrequired );
1897 }
1898
1899 =head3 is_superlibrarian
1900
1901   my $is_superlibrarian = $patron->is_superlibrarian;
1902
1903 Return true if the patron is a superlibrarian.
1904
1905 =cut
1906
1907 sub is_superlibrarian {
1908     my ($self) = @_;
1909     return $self->has_permission( { superlibrarian => 1 } ) ? 1 : 0;
1910 }
1911
1912 =head3 is_adult
1913
1914 my $is_adult = $patron->is_adult
1915
1916 Return true if the patron has a category with a type Adult (A) or Organization (I)
1917
1918 =cut
1919
1920 sub is_adult {
1921     my ( $self ) = @_;
1922     return $self->category->category_type =~ /^(A|I)$/ ? 1 : 0;
1923 }
1924
1925 =head3 is_child
1926
1927 my $is_child = $patron->is_child
1928
1929 Return true if the patron has a category with a type Child (C)
1930
1931 =cut
1932
1933 sub is_child {
1934     my( $self ) = @_;
1935     return $self->category->category_type eq 'C' ? 1 : 0;
1936 }
1937
1938 =head3 has_valid_userid
1939
1940 my $patron = Koha::Patrons->find(42);
1941 $patron->userid( $new_userid );
1942 my $has_a_valid_userid = $patron->has_valid_userid
1943
1944 my $patron = Koha::Patron->new( $params );
1945 my $has_a_valid_userid = $patron->has_valid_userid
1946
1947 Return true if the current userid of this patron is valid/unique, otherwise false.
1948
1949 Note that this should be done in $self->store instead and raise an exception if needed.
1950
1951 =cut
1952
1953 sub has_valid_userid {
1954     my ($self) = @_;
1955
1956     return 0 unless $self->userid;
1957
1958     return 0 if ( $self->userid eq C4::Context->config('user') );    # DB user
1959
1960     my $already_exists = Koha::Patrons->search(
1961         {
1962             userid => $self->userid,
1963             (
1964                 $self->in_storage
1965                 ? ( borrowernumber => { '!=' => $self->borrowernumber } )
1966                 : ()
1967             ),
1968         }
1969     )->count;
1970     return $already_exists ? 0 : 1;
1971 }
1972
1973 =head3 generate_userid
1974
1975     $patron->generate_userid;
1976
1977     If you do not have a plugin for generating a userid, we will call
1978     the internal method here that returns firstname.surname[.number],
1979     where number is an optional suffix to make the userid unique.
1980     (Its behavior has not been changed on bug 32426.)
1981
1982     If you have plugin(s), the first valid response will be used.
1983     A plugin is assumed to return a valid userid as suggestion, but not
1984     assumed to save it already.
1985     Does not fallback to internal (you could arrange for that in your plugin).
1986     Clears userid when there are no valid plugin responses.
1987
1988 =cut
1989
1990 sub generate_userid {
1991     my ( $self ) = @_;
1992     my @responses = Koha::Plugins->call(
1993         'patron_generate_userid', { patron => $self },
1994     );
1995     unless( @responses ) {
1996         # Empty list only possible when there are NO enabled plugins for this method.
1997         # In that case we provide internal response.
1998         return $self->_generate_userid_internal;
1999     }
2000     # If a plugin returned false value or invalid value, we do however not return
2001     # internal response. The plugins should deal with that themselves. So we prevent
2002     # unexpected/unwelcome internal codes for plugin failures.
2003     foreach my $response ( grep { $_ } @responses ) {
2004         $self->userid( $response );
2005         return $self if $self->has_valid_userid;
2006     }
2007     $self->userid(undef);
2008     return $self;
2009 }
2010
2011 sub _generate_userid_internal { # as we always did
2012     my ($self) = @_;
2013     my $offset = 0;
2014     my $firstname = $self->firstname // q{};
2015     my $surname = $self->surname // q{};
2016     #The script will "do" the following code and increment the $offset until the generated userid is unique
2017     do {
2018       $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
2019       $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
2020       my $userid = lc(($firstname)? "$firstname.$surname" : $surname);
2021       $userid = NFKD( $userid );
2022       $userid =~ s/\p{NonspacingMark}//g;
2023       $userid .= $offset unless $offset == 0;
2024       $self->userid( $userid );
2025       $offset++;
2026      } while (! $self->has_valid_userid );
2027
2028      return $self;
2029 }
2030
2031 =head3 add_extended_attribute
2032
2033 =cut
2034
2035 sub add_extended_attribute {
2036     my ($self, $attribute) = @_;
2037
2038     return Koha::Patron::Attribute->new(
2039         {
2040             %$attribute,
2041             ( borrowernumber => $self->borrowernumber ),
2042         }
2043     )->store;
2044
2045 }
2046
2047 =head3 extended_attributes
2048
2049 Return object of Koha::Patron::Attributes type with all attributes set for this patron
2050
2051 Or setter FIXME
2052
2053 =cut
2054
2055 sub extended_attributes {
2056     my ( $self, $attributes ) = @_;
2057     if ($attributes) {    # setter
2058         my $schema = $self->_result->result_source->schema;
2059         $schema->txn_do(
2060             sub {
2061                 # Remove the existing one
2062                 $self->extended_attributes->filter_by_branch_limitations->delete;
2063
2064                 # Insert the new ones
2065                 my $new_types = {};
2066                 for my $attribute (@$attributes) {
2067                     $self->add_extended_attribute($attribute);
2068                     $new_types->{$attribute->{code}} = 1;
2069                 }
2070
2071                 # Check globally mandatory types
2072                 my @required_attribute_types =
2073                     Koha::Patron::Attribute::Types->search(
2074                         {
2075                             mandatory => 1,
2076                             category_code => [ undef, $self->categorycode ],
2077                             'borrower_attribute_types_branches.b_branchcode' =>
2078                               undef,
2079                         },
2080                         { join => 'borrower_attribute_types_branches' }
2081                     )->get_column('code');
2082                 for my $type ( @required_attribute_types ) {
2083                     Koha::Exceptions::Patron::MissingMandatoryExtendedAttribute->throw(
2084                         type => $type,
2085                     ) if !$new_types->{$type};
2086                 }
2087             }
2088         );
2089     }
2090
2091     my $rs = $self->_result->borrower_attributes;
2092     # We call search to use the filters in Koha::Patron::Attributes->search
2093     return Koha::Patron::Attributes->_new_from_dbic($rs)->search;
2094 }
2095
2096 =head3 messages
2097
2098     my $messages = $patron->messages;
2099
2100 Return the message attached to the patron.
2101
2102 =cut
2103
2104 sub messages {
2105     my ( $self ) = @_;
2106     my $messages_rs = $self->_result->messages_borrowernumbers->search;
2107     return Koha::Patron::Messages->_new_from_dbic($messages_rs);
2108 }
2109
2110 =head3 lock
2111
2112     Koha::Patrons->find($id)->lock({ expire => 1, remove => 1 });
2113
2114     Lock and optionally expire a patron account.
2115     Remove holds and article requests if remove flag set.
2116     In order to distinguish from locking by entering a wrong password, let's
2117     call this an administrative lockout.
2118
2119 =cut
2120
2121 sub lock {
2122     my ( $self, $params ) = @_;
2123     $self->login_attempts( ADMINISTRATIVE_LOCKOUT );
2124     if( $params->{expire} ) {
2125         $self->dateexpiry( dt_from_string->subtract(days => 1) );
2126     }
2127     $self->store;
2128     if( $params->{remove} ) {
2129         $self->holds->delete;
2130         $self->article_requests->delete;
2131     }
2132     return $self;
2133 }
2134
2135 =head3 anonymize
2136
2137     Koha::Patrons->find($id)->anonymize;
2138
2139     Anonymize or clear borrower fields. Fields in BorrowerMandatoryField
2140     are randomized, other personal data is cleared too.
2141     Patrons with issues are skipped.
2142
2143 =cut
2144
2145 sub anonymize {
2146     my ( $self ) = @_;
2147     if( $self->_result->issues->count ) {
2148         warn "Exiting anonymize: patron ".$self->borrowernumber." still has issues";
2149         return;
2150     }
2151     # Mandatory fields come from the corresponding pref, but email fields
2152     # are removed since scrambled email addresses only generate errors
2153     my $mandatory = { map { (lc $_, 1); } grep { !/email/ }
2154         split /\s*\|\s*/, C4::Context->preference('BorrowerMandatoryField') };
2155     $mandatory->{userid} = 1; # needed since sub store does not clear field
2156     my @columns = $self->_result->result_source->columns;
2157     @columns = grep { !/borrowernumber|branchcode|categorycode|^date|password|flags|updated_on|lastseen|lang|login_attempts|anonymized|auth_method/ } @columns;
2158     push @columns, 'dateofbirth'; # add this date back in
2159     foreach my $col (@columns) {
2160         $self->_anonymize_column($col, $mandatory->{lc $col} );
2161     }
2162     $self->anonymized(1)->store;
2163 }
2164
2165 sub _anonymize_column {
2166     my ( $self, $col, $mandatory ) = @_;
2167     my $col_info = $self->_result->result_source->column_info($col);
2168     my $type = $col_info->{data_type};
2169     my $nullable = $col_info->{is_nullable};
2170     my $val;
2171     if( $type =~ /char|text/ ) {
2172         $val = $mandatory
2173             ? Koha::Token->new->generate({ pattern => '\w{10}' })
2174             : $nullable
2175             ? undef
2176             : q{};
2177     } elsif( $type =~ /integer|int$|float|dec|double/ ) {
2178         $val = $nullable ? undef : 0;
2179     } elsif( $type =~ /date|time/ ) {
2180         $val = $nullable ? undef : dt_from_string;
2181     }
2182     $self->$col($val);
2183 }
2184
2185 =head3 add_guarantor
2186
2187     my $relationship = $patron->add_guarantor(
2188         {
2189             borrowernumber => $borrowernumber,
2190             relationships  => $relationship,
2191         }
2192     );
2193
2194     Adds a new guarantor to a patron.
2195
2196 =cut
2197
2198 sub add_guarantor {
2199     my ( $self, $params ) = @_;
2200
2201     my $guarantor_id = $params->{guarantor_id};
2202     my $relationship = $params->{relationship};
2203
2204     return Koha::Patron::Relationship->new(
2205         {
2206             guarantee_id => $self->id,
2207             guarantor_id => $guarantor_id,
2208             relationship => $relationship
2209         }
2210     )->store();
2211 }
2212
2213 =head3 get_extended_attribute
2214
2215 my $attribute_value = $patron->get_extended_attribute( $code );
2216
2217 Return the attribute for the code passed in parameter.
2218
2219 It not exist it returns undef
2220
2221 Note that this will not work for repeatable attribute types.
2222
2223 Maybe you certainly not want to use this method, it is actually only used for SHOW_BARCODE
2224 (which should be a real patron's attribute (not extended)
2225
2226 =cut
2227
2228 sub get_extended_attribute {
2229     my ( $self, $code, $value ) = @_;
2230     my $rs = $self->_result->borrower_attributes;
2231     return unless $rs;
2232     my $attribute = $rs->search({ code => $code, ( $value ? ( attribute => $value ) : () ) });
2233     return unless $attribute->count;
2234     return $attribute->next;
2235 }
2236
2237 =head3 set_default_messaging_preferences
2238
2239     $patron->set_default_messaging_preferences
2240
2241 Sets default messaging preferences on patron.
2242
2243 See Koha::Patron::MessagePreference(s) for more documentation, especially on
2244 thrown exceptions.
2245
2246 =cut
2247
2248 sub set_default_messaging_preferences {
2249     my ($self, $categorycode) = @_;
2250
2251     my $options = Koha::Patron::MessagePreferences->get_options;
2252
2253     foreach my $option (@$options) {
2254         # Check that this option has preference configuration for this category
2255         unless (Koha::Patron::MessagePreferences->search({
2256             message_attribute_id => $option->{message_attribute_id},
2257             categorycode         => $categorycode || $self->categorycode,
2258         })->count) {
2259             next;
2260         }
2261
2262         # Delete current setting
2263         Koha::Patron::MessagePreferences->search({
2264              borrowernumber => $self->borrowernumber,
2265              message_attribute_id => $option->{message_attribute_id},
2266         })->delete;
2267
2268         Koha::Patron::MessagePreference->new_from_default({
2269             borrowernumber => $self->borrowernumber,
2270             categorycode   => $categorycode || $self->categorycode,
2271             message_attribute_id => $option->{message_attribute_id},
2272         });
2273     }
2274
2275     return $self;
2276 }
2277
2278 =head3 is_accessible
2279
2280     if ( $patron->is_accessible({ user => $logged_in_user }) ) { ... }
2281
2282 This overloaded method validates whether the current I<Koha::Patron> object can be accessed
2283 by the logged in user.
2284
2285 Returns 0 if the I<user> parameter is missing.
2286
2287 =cut
2288
2289 sub is_accessible {
2290     my ( $self, $params ) = @_;
2291
2292     unless ( defined( $params->{user} ) ) {
2293         Koha::Exceptions::MissingParameter->throw( error => "The `user` parameter is mandatory" );
2294     }
2295
2296     my $consumer = $params->{user};
2297     return $consumer->can_see_patron_infos($self);
2298 }
2299
2300 =head3 unredact_list
2301
2302 This method returns the list of database fields that should be visible, even for restricted users,
2303 for both API and UI output purposes
2304
2305 =cut
2306
2307 sub unredact_list {
2308     return ['branchcode'];
2309 }
2310
2311 =head3 to_api
2312
2313     my $json = $patron->to_api;
2314
2315 Overloaded method that returns a JSON representation of the Koha::Patron object,
2316 suitable for API output.
2317
2318 =cut
2319
2320 sub to_api {
2321     my ( $self, $params ) = @_;
2322
2323     my $json_patron = $self->SUPER::to_api( $params );
2324
2325     return unless $json_patron;
2326
2327     $json_patron->{restricted} = ( $self->is_debarred )
2328                                     ? Mojo::JSON->true
2329                                     : Mojo::JSON->false;
2330
2331     return $json_patron;
2332 }
2333
2334 =head3 to_api_mapping
2335
2336 This method returns the mapping for representing a Koha::Patron object
2337 on the API.
2338
2339 =cut
2340
2341 sub to_api_mapping {
2342     return {
2343         borrowernotes       => 'staff_notes',
2344         borrowernumber      => 'patron_id',
2345         branchcode          => 'library_id',
2346         categorycode        => 'category_id',
2347         checkprevcheckout   => 'check_previous_checkout',
2348         contactfirstname    => undef,                     # Unused
2349         contactname         => undef,                     # Unused
2350         contactnote         => 'altaddress_notes',
2351         contacttitle        => undef,                     # Unused
2352         dateenrolled        => 'date_enrolled',
2353         dateexpiry          => 'expiry_date',
2354         dateofbirth         => 'date_of_birth',
2355         debarred            => undef,                     # replaced by 'restricted'
2356         debarredcomment     => undef,    # calculated, API consumers will use /restrictions instead
2357         emailpro            => 'secondary_email',
2358         flags               => undef,    # permissions manipulation handled in /permissions
2359         gonenoaddress       => 'incorrect_address',
2360         lastseen            => 'last_seen',
2361         lost                => 'patron_card_lost',
2362         opacnote            => 'opac_notes',
2363         othernames          => 'other_name',
2364         password            => undef,            # password manipulation handled in /password
2365         phonepro            => 'secondary_phone',
2366         relationship        => 'relationship_type',
2367         sex                 => 'gender',
2368         smsalertnumber      => 'sms_number',
2369         sort1               => 'statistics_1',
2370         sort2               => 'statistics_2',
2371         autorenew_checkouts => 'autorenew_checkouts',
2372         streetnumber        => 'street_number',
2373         streettype          => 'street_type',
2374         zipcode             => 'postal_code',
2375         B_address           => 'altaddress_address',
2376         B_address2          => 'altaddress_address2',
2377         B_city              => 'altaddress_city',
2378         B_country           => 'altaddress_country',
2379         B_email             => 'altaddress_email',
2380         B_phone             => 'altaddress_phone',
2381         B_state             => 'altaddress_state',
2382         B_streetnumber      => 'altaddress_street_number',
2383         B_streettype        => 'altaddress_street_type',
2384         B_zipcode           => 'altaddress_postal_code',
2385         altcontactaddress1  => 'altcontact_address',
2386         altcontactaddress2  => 'altcontact_address2',
2387         altcontactaddress3  => 'altcontact_city',
2388         altcontactcountry   => 'altcontact_country',
2389         altcontactfirstname => 'altcontact_firstname',
2390         altcontactphone     => 'altcontact_phone',
2391         altcontactsurname   => 'altcontact_surname',
2392         altcontactstate     => 'altcontact_state',
2393         altcontactzipcode   => 'altcontact_postal_code',
2394         password_expiration_date => undef,
2395         primary_contact_method => undef,
2396         secret              => undef,
2397         auth_method         => undef,
2398     };
2399 }
2400
2401 =head3 queue_notice
2402
2403     Koha::Patrons->queue_notice({ letter_params => $letter_params, message_name => 'DUE'});
2404     Koha::Patrons->queue_notice({ letter_params => $letter_params, message_transports => \@message_transports });
2405     Koha::Patrons->queue_notice({ letter_params => $letter_params, message_transports => \@message_transports, test_mode => 1 });
2406
2407     Queue messages to a patron. Can pass a message that is part of the message_attributes
2408     table or supply the transport to use.
2409
2410     If passed a message name we retrieve the patrons preferences for transports
2411     Otherwise we use the supplied transport. In the case of email or sms we fall back to print if
2412     we have no address/number for sending
2413
2414     $letter_params is a hashref of the values to be passed to GetPreparedLetter
2415
2416     test_mode will only report which notices would be sent, but nothing will be queued
2417
2418 =cut
2419
2420 sub queue_notice {
2421     my ( $self, $params ) = @_;
2422     my $letter_params = $params->{letter_params};
2423     my $test_mode = $params->{test_mode};
2424
2425     return unless $letter_params;
2426     return unless exists $params->{message_name} xor $params->{message_transports}; # We only want one of these
2427
2428     my $library = Koha::Libraries->find( $letter_params->{branchcode} );
2429     my $from_email_address = $library->from_email_address;
2430
2431     my @message_transports;
2432     my $letter_code;
2433     $letter_code = $letter_params->{letter_code};
2434     if( $params->{message_name} ){
2435         my $messaging_prefs = C4::Members::Messaging::GetMessagingPreferences( {
2436                 borrowernumber => $letter_params->{borrowernumber},
2437                 message_name => $params->{message_name}
2438         } );
2439         @message_transports = ( keys %{ $messaging_prefs->{transports} } );
2440         $letter_code = $messaging_prefs->{transports}->{$message_transports[0]} unless $letter_code;
2441     } else {
2442         @message_transports = @{$params->{message_transports}};
2443     }
2444     return unless defined $letter_code;
2445     $letter_params->{letter_code} = $letter_code;
2446     my $print_sent = 0;
2447     my %return;
2448     foreach my $mtt (@message_transports){
2449         next if ($mtt eq 'itiva' and C4::Context->preference('TalkingTechItivaPhoneNotification') );
2450         # Notice is handled by TalkingTech_itiva_outbound.pl
2451         if (   ( $mtt eq 'email' and not $self->notice_email_address )
2452             or ( $mtt eq 'sms'   and not $self->smsalertnumber )
2453             or ( $mtt eq 'phone' and not $self->phone ) )
2454         {
2455             push @{ $return{fallback} }, $mtt;
2456             $mtt = 'print';
2457         }
2458         next if $mtt eq 'print' && $print_sent;
2459         $letter_params->{message_transport_type} = $mtt;
2460         my $letter = C4::Letters::GetPreparedLetter( %$letter_params );
2461         C4::Letters::EnqueueLetter({
2462             letter => $letter,
2463             borrowernumber => $self->borrowernumber,
2464             from_address   => $from_email_address,
2465             message_transport_type => $mtt
2466         }) unless $test_mode;
2467         push @{$return{sent}}, $mtt;
2468         $print_sent = 1 if $mtt eq 'print';
2469     }
2470     return \%return;
2471 }
2472
2473 =head3 safe_to_delete
2474
2475     my $result = $patron->safe_to_delete;
2476     if ( $result eq 'has_guarantees' ) { ... }
2477     elsif ( $result ) { ... }
2478     else { # cannot delete }
2479
2480 This method tells if the Koha:Patron object can be deleted. Possible return values
2481
2482 =over 4
2483
2484 =item 'ok'
2485
2486 =item 'has_checkouts'
2487
2488 =item 'has_debt'
2489
2490 =item 'has_guarantees'
2491
2492 =item 'is_anonymous_patron'
2493
2494 =back
2495
2496 =cut
2497
2498 sub safe_to_delete {
2499     my ($self) = @_;
2500
2501     my $anonymous_patron = C4::Context->preference('AnonymousPatron');
2502
2503     my $error;
2504
2505     if ( $anonymous_patron && $self->id eq $anonymous_patron ) {
2506         $error = 'is_anonymous_patron';
2507     }
2508     elsif ( $self->checkouts->count ) {
2509         $error = 'has_checkouts';
2510     }
2511     elsif ( $self->account->outstanding_debits->total_outstanding > 0 ) {
2512         $error = 'has_debt';
2513     }
2514     elsif ( $self->guarantee_relationships->count ) {
2515         $error = 'has_guarantees';
2516     }
2517
2518     if ( $error ) {
2519         return Koha::Result::Boolean->new(0)->add_message({ message => $error });
2520     }
2521
2522     return Koha::Result::Boolean->new(1);
2523 }
2524
2525 =head3 recalls
2526
2527     my $recalls = $patron->recalls;
2528
2529 Return the patron's recalls.
2530
2531 =cut
2532
2533 sub recalls {
2534     my ( $self ) = @_;
2535
2536     return Koha::Recalls->search({ patron_id => $self->borrowernumber });
2537 }
2538
2539 =head3 account_balance
2540
2541     my $balance = $patron->account_balance
2542
2543 Return the patron's account balance
2544
2545 =cut
2546
2547 sub account_balance {
2548     my ($self) = @_;
2549     return $self->account->balance;
2550 }
2551
2552 =head3 notify_library_of_registration
2553
2554 $patron->notify_library_of_registration( $email_patron_registrations );
2555
2556 Send patron registration email to library if EmailPatronRegistrations system preference is enabled.
2557
2558 =cut
2559
2560 sub notify_library_of_registration {
2561     my ( $self, $email_patron_registrations ) = @_;
2562
2563     if (
2564         my $letter = C4::Letters::GetPreparedLetter(
2565             module      => 'members',
2566             letter_code => 'OPAC_REG',
2567             branchcode  => $self->branchcode,
2568             lang        => $self->lang || 'default',
2569             tables      => {
2570                 'borrowers' => $self->borrowernumber
2571             },
2572         )
2573     ) {
2574         my $to_address;
2575         if ( $email_patron_registrations eq "BranchEmailAddress" ) {
2576             my $library = Koha::Libraries->find( $self->branchcode );
2577             $to_address = $library->inbound_email_address;
2578         }
2579         elsif ( $email_patron_registrations eq "KohaAdminEmailAddress" ) {
2580             $to_address = C4::Context->preference('ReplytoDefault')
2581             || C4::Context->preference('KohaAdminEmailAddress');
2582         }
2583         else {
2584             $to_address =
2585                 C4::Context->preference('EmailAddressForPatronRegistrations')
2586                 || C4::Context->preference('ReplytoDefault')
2587                 || C4::Context->preference('KohaAdminEmailAddress');
2588         }
2589
2590         my $message_id = C4::Letters::EnqueueLetter(
2591             {
2592                 letter                 => $letter,
2593                 borrowernumber         => $self->borrowernumber,
2594                 to_address             => $to_address,
2595                 message_transport_type => 'email'
2596             }
2597         ) or warn "can't enqueue letter $letter";
2598         if ( $message_id ) {
2599             return 1;
2600         }
2601     }
2602 }
2603
2604 =head3 has_messaging_preference
2605
2606 my $bool = $patron->has_messaging_preference({
2607     message_name => $message_name, # A value from message_attributes.message_name
2608     message_transport_type => $message_transport_type, # email, sms, phone, itiva, etc...
2609     wants_digest => $wants_digest, # 1 if you are looking for the digest version, don't pass if you just want either
2610 });
2611
2612 =cut
2613
2614 sub has_messaging_preference {
2615     my ( $self, $params ) = @_;
2616
2617     my $message_name           = $params->{message_name};
2618     my $message_transport_type = $params->{message_transport_type};
2619     my $wants_digest           = $params->{wants_digest};
2620
2621     return $self->_result->search_related_rs(
2622         'borrower_message_preferences',
2623         $params,
2624         {
2625             prefetch =>
2626               [ 'borrower_message_transport_preferences', 'message_attribute' ]
2627         }
2628     )->count;
2629 }
2630
2631 =head3 can_patron_change_staff_only_lists
2632
2633 $patron->can_patron_change_staff_only_lists;
2634
2635 Return 1 if a patron has 'Superlibrarian' or 'Catalogue' permission.
2636 Otherwise, return 0.
2637
2638 =cut
2639
2640 sub can_patron_change_staff_only_lists {
2641     my ( $self, $params ) = @_;
2642     return 1 if C4::Auth::haspermission( $self->userid, { 'catalogue' => 1 });
2643     return 0;
2644 }
2645
2646 =head3 can_patron_change_permitted_staff_lists
2647
2648 $patron->can_patron_change_permitted_staff_lists;
2649
2650 Return 1 if a patron has 'Superlibrarian' or 'Catalogue' and 'edit_public_list_contents' permissions.
2651 Otherwise, return 0.
2652
2653 =cut
2654
2655 sub can_patron_change_permitted_staff_lists {
2656     my ( $self, $params ) = @_;
2657     return 1 if C4::Auth::haspermission( $self->userid, { 'catalogue' => 1, lists => 'edit_public_list_contents' } );
2658     return 0;
2659 }
2660
2661 =head3 encode_secret
2662
2663   $patron->encode_secret($secret32);
2664
2665 Secret (TwoFactorAuth expects it in base32 format) is encrypted.
2666 You still need to call ->store.
2667
2668 =cut
2669
2670 sub encode_secret {
2671     my ( $self, $secret ) = @_;
2672     if( $secret ) {
2673         return $self->secret( Koha::Encryption->new->encrypt_hex($secret) );
2674     }
2675     return $self->secret($secret);
2676 }
2677
2678 =head3 decoded_secret
2679
2680   my $secret32 = $patron->decoded_secret;
2681
2682 Decode the patron secret. We expect to get back a base32 string, but this
2683 is not checked here. Caller of encode_secret is responsible for that.
2684
2685 =cut
2686
2687 sub decoded_secret {
2688     my ( $self ) = @_;
2689     if( $self->secret ) {
2690         return Koha::Encryption->new->decrypt_hex( $self->secret );
2691     }
2692     return $self->secret;
2693 }
2694
2695 =head3 virtualshelves
2696
2697     my $shelves = $patron->virtualshelves;
2698
2699 =cut
2700
2701 sub virtualshelves {
2702     my $self = shift;
2703     return Koha::Virtualshelves->_new_from_dbic( scalar $self->_result->virtualshelves );
2704 }
2705
2706 =head3 get_savings
2707
2708     my $savings = $patron->get_savings;
2709
2710 Use the replacement price of patron's old and current issues to calculate how much they have 'saved' by using the library.
2711
2712 =cut
2713
2714 sub get_savings {
2715     my ($self) = @_;
2716
2717     my @itemnumbers = grep { defined $_ } ( $self->old_checkouts->get_column('itemnumber'), $self->checkouts->get_column('itemnumber') );
2718
2719     return Koha::Items->search(
2720         { itemnumber => { -in => \@itemnumbers } },
2721         {   select => [ { sum => 'me.replacementprice' } ],
2722             as     => ['total_savings']
2723         }
2724     )->next->get_column('total_savings') // 0;
2725 }
2726
2727 =head3 alert_subscriptions
2728
2729     my $subscriptions = $patron->alert_subscriptions;
2730
2731 Return a Koha::Subscriptions object containing subscriptions for which the patron has subscribed to email alerts.
2732
2733 =cut
2734
2735 sub alert_subscriptions {
2736     my ($self) = @_;
2737
2738     my @alerts           = $self->_result->alerts;
2739     my @subscription_ids = map { $_->externalid } @alerts;
2740
2741     return Koha::Subscriptions->search( { subscriptionid => \@subscription_ids } );
2742 }
2743
2744 =head3 consent
2745
2746     my $consent = $patron->consent(TYPE);
2747
2748     Returns the first consent of type TYPE (there should be only one) or a new instance
2749     of Koha::Patron::Consent.
2750
2751 =cut
2752
2753 sub consent {
2754     my ( $self, $type ) = @_;
2755     Koha::Exceptions::MissingParameter->throw('Missing consent type') if !$type;
2756     my $consents = Koha::Patron::Consents->search(
2757         {
2758             borrowernumber => $self->borrowernumber,
2759             type           => $type,
2760         }
2761     );
2762     return $consents && $consents->count
2763         ? $consents->next
2764         : Koha::Patron::Consent->new( { borrowernumber => $self->borrowernumber, type => $type } );
2765 }
2766
2767 =head2 Internal methods
2768
2769 =head3 _type
2770
2771 =cut
2772
2773 sub _type {
2774     return 'Borrower';
2775 }
2776
2777 =head1 AUTHORS
2778
2779 Kyle M Hall <kyle@bywatersolutions.com>
2780 Alex Sassmannshausen <alex.sassmannshausen@ptfs-europe.com>
2781 Martin Renvoize <martin.renvoize@ptfs-europe.com>
2782
2783 =cut
2784
2785 1;