Bug 18403: Fix perlcritic on Koha::Patron
[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 under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 3 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 use Modern::Perl;
22
23 use Carp;
24 use List::MoreUtils qw( uniq );
25
26 use C4::Context;
27 use C4::Log;
28 use Koha::Checkouts;
29 use Koha::Database;
30 use Koha::DateUtils;
31 use Koha::Holds;
32 use Koha::Old::Checkouts;
33 use Koha::Patron::Categories;
34 use Koha::Patron::HouseboundProfile;
35 use Koha::Patron::HouseboundRole;
36 use Koha::Patron::Images;
37 use Koha::Patrons;
38 use Koha::Virtualshelves;
39 use Koha::Club::Enrollments;
40 use Koha::Account;
41
42 use base qw(Koha::Object);
43
44 =head1 NAME
45
46 Koha::Patron - Koha Patron Object class
47
48 =head1 API
49
50 =head2 Class Methods
51
52 =cut
53
54 =head3 delete
55
56 $patron->delete
57
58 Delete patron's holds, lists and finally the patron.
59
60 Lists owned by the borrower are deleted, but entries from the borrower to
61 other lists are kept.
62
63 =cut
64
65 sub delete {
66     my ($self) = @_;
67
68     my $deleted;
69     $self->_result->result_source->schema->txn_do(
70         sub {
71             # Delete Patron's holds
72             $self->holds->delete;
73
74             # Delete all lists and all shares of this borrower
75             # Consistent with the approach Koha uses on deleting individual lists
76             # Note that entries in virtualshelfcontents added by this borrower to
77             # lists of others will be handled by a table constraint: the borrower
78             # is set to NULL in those entries.
79             # NOTE:
80             # We could handle the above deletes via a constraint too.
81             # But a new BZ report 11889 has been opened to discuss another approach.
82             # Instead of deleting we could also disown lists (based on a pref).
83             # In that way we could save shared and public lists.
84             # The current table constraints support that idea now.
85             # This pref should then govern the results of other routines/methods such as
86             # Koha::Virtualshelf->new->delete too.
87             # FIXME Could be $patron->get_lists
88             $_->delete for Koha::Virtualshelves->search( { owner => $self->borrowernumber } );
89
90             $deleted = $self->SUPER::delete;
91
92             logaction( "MEMBERS", "DELETE", $self->borrowernumber, "" ) if C4::Context->preference("BorrowersLog");
93         }
94     );
95     return $deleted;
96 }
97
98
99 =head3 category
100
101 my $patron_category = $patron->category
102
103 Return the patron category for this patron
104
105 =cut
106
107 sub category {
108     my ( $self ) = @_;
109     return Koha::Patron::Category->_new_from_dbic( $self->_result->categorycode );
110 }
111
112 =head3 guarantor
113
114 Returns a Koha::Patron object for this patron's guarantor
115
116 =cut
117
118 sub guarantor {
119     my ( $self ) = @_;
120
121     return unless $self->guarantorid();
122
123     return Koha::Patrons->find( $self->guarantorid() );
124 }
125
126 sub image {
127     my ( $self ) = @_;
128
129     return Koha::Patron::Images->find( $self->borrowernumber );
130 }
131
132 sub library {
133     my ( $self ) = @_;
134     return Koha::Library->_new_from_dbic($self->_result->branchcode);
135 }
136
137 =head3 guarantees
138
139 Returns the guarantees (list of Koha::Patron) of this patron
140
141 =cut
142
143 sub guarantees {
144     my ( $self ) = @_;
145
146     return Koha::Patrons->search( { guarantorid => $self->borrowernumber } );
147 }
148
149 =head3 housebound_profile
150
151 Returns the HouseboundProfile associated with this patron.
152
153 =cut
154
155 sub housebound_profile {
156     my ( $self ) = @_;
157     my $profile = $self->_result->housebound_profile;
158     return Koha::Patron::HouseboundProfile->_new_from_dbic($profile)
159         if ( $profile );
160     return;
161 }
162
163 =head3 housebound_role
164
165 Returns the HouseboundRole associated with this patron.
166
167 =cut
168
169 sub housebound_role {
170     my ( $self ) = @_;
171
172     my $role = $self->_result->housebound_role;
173     return Koha::Patron::HouseboundRole->_new_from_dbic($role) if ( $role );
174     return;
175 }
176
177 =head3 siblings
178
179 Returns the siblings of this patron.
180
181 =cut
182
183 sub siblings {
184     my ( $self ) = @_;
185
186     my $guarantor = $self->guarantor;
187
188     return unless $guarantor;
189
190     return Koha::Patrons->search(
191         {
192             guarantorid => {
193                 '!=' => undef,
194                 '=' => $guarantor->id,
195             },
196             borrowernumber => {
197                 '!=' => $self->borrowernumber,
198             }
199         }
200     );
201 }
202
203 =head3 wants_check_for_previous_checkout
204
205     $wants_check = $patron->wants_check_for_previous_checkout;
206
207 Return 1 if Koha needs to perform PrevIssue checking, else 0.
208
209 =cut
210
211 sub wants_check_for_previous_checkout {
212     my ( $self ) = @_;
213     my $syspref = C4::Context->preference("checkPrevCheckout");
214
215     # Simple cases
216     ## Hard syspref trumps all
217     return 1 if ($syspref eq 'hardyes');
218     return 0 if ($syspref eq 'hardno');
219     ## Now, patron pref trumps all
220     return 1 if ($self->checkprevcheckout eq 'yes');
221     return 0 if ($self->checkprevcheckout eq 'no');
222
223     # More complex: patron inherits -> determine category preference
224     my $checkPrevCheckoutByCat = $self->category->checkprevcheckout;
225     return 1 if ($checkPrevCheckoutByCat eq 'yes');
226     return 0 if ($checkPrevCheckoutByCat eq 'no');
227
228     # Finally: category preference is inherit, default to 0
229     if ($syspref eq 'softyes') {
230         return 1;
231     } else {
232         return 0;
233     }
234 }
235
236 =head3 do_check_for_previous_checkout
237
238     $do_check = $patron->do_check_for_previous_checkout($item);
239
240 Return 1 if the bib associated with $ITEM has previously been checked out to
241 $PATRON, 0 otherwise.
242
243 =cut
244
245 sub do_check_for_previous_checkout {
246     my ( $self, $item ) = @_;
247
248     # Find all items for bib and extract item numbers.
249     my @items = Koha::Items->search({biblionumber => $item->{biblionumber}});
250     my @item_nos;
251     foreach my $item (@items) {
252         push @item_nos, $item->itemnumber;
253     }
254
255     # Create (old)issues search criteria
256     my $criteria = {
257         borrowernumber => $self->borrowernumber,
258         itemnumber => \@item_nos,
259     };
260
261     # Check current issues table
262     my $issues = Koha::Checkouts->search($criteria);
263     return 1 if $issues->count; # 0 || N
264
265     # Check old issues table
266     my $old_issues = Koha::Old::Checkouts->search($criteria);
267     return $old_issues->count;  # 0 || N
268 }
269
270 =head3 is_debarred
271
272 my $debarment_expiration = $patron->is_debarred;
273
274 Returns the date a patron debarment will expire, or undef if the patron is not
275 debarred
276
277 =cut
278
279 sub is_debarred {
280     my ($self) = @_;
281
282     return unless $self->debarred;
283     return $self->debarred
284       if $self->debarred =~ '^9999'
285       or dt_from_string( $self->debarred ) > dt_from_string;
286     return;
287 }
288
289 =head3 is_expired
290
291 my $is_expired = $patron->is_expired;
292
293 Returns 1 if the patron is expired or 0;
294
295 =cut
296
297 sub is_expired {
298     my ($self) = @_;
299     return 0 unless $self->dateexpiry;
300     return 0 if $self->dateexpiry eq '0000-00-00';
301     return 1 if dt_from_string( $self->dateexpiry ) < dt_from_string->truncate( to => 'day' );
302     return 0;
303 }
304
305 =head3 is_going_to_expire
306
307 my $is_going_to_expire = $patron->is_going_to_expire;
308
309 Returns 1 if the patron is going to expired, depending on the NotifyBorrowerDeparture pref or 0
310
311 =cut
312
313 sub is_going_to_expire {
314     my ($self) = @_;
315
316     my $delay = C4::Context->preference('NotifyBorrowerDeparture') || 0;
317
318     return 0 unless $delay;
319     return 0 unless $self->dateexpiry;
320     return 0 if $self->dateexpiry eq '0000-00-00';
321     return 1 if dt_from_string( $self->dateexpiry )->subtract( days => $delay ) < dt_from_string->truncate( to => 'day' );
322     return 0;
323 }
324
325 =head3 update_password
326
327 my $updated = $patron->update_password( $userid, $password );
328
329 Update the userid and the password of a patron.
330 If the userid already exists, returns and let DBIx::Class warns
331 This will add an entry to action_logs if BorrowersLog is set.
332
333 =cut
334
335 sub update_password {
336     my ( $self, $userid, $password ) = @_;
337     eval { $self->userid($userid)->store; };
338     return if $@; # Make sure the userid is not already in used by another patron
339     $self->update(
340         {
341             password       => $password,
342             login_attempts => 0,
343         }
344     );
345     logaction( "MEMBERS", "CHANGE PASS", $self->borrowernumber, "" ) if C4::Context->preference("BorrowersLog");
346     return 1;
347 }
348
349 =head3 renew_account
350
351 my $new_expiry_date = $patron->renew_account
352
353 Extending the subscription to the expiry date.
354
355 =cut
356
357 sub renew_account {
358     my ($self) = @_;
359     my $date;
360     if ( C4::Context->preference('BorrowerRenewalPeriodBase') eq 'combination' ) {
361         $date = ( dt_from_string gt dt_from_string( $self->dateexpiry ) ) ? dt_from_string : dt_from_string( $self->dateexpiry );
362     } else {
363         $date =
364             C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry'
365             ? dt_from_string( $self->dateexpiry )
366             : dt_from_string;
367     }
368     my $expiry_date = $self->category->get_expiry_date($date);
369
370     $self->dateexpiry($expiry_date);
371     $self->date_renewed( dt_from_string() );
372     $self->store();
373
374     $self->add_enrolment_fee_if_needed;
375
376     logaction( "MEMBERS", "RENEW", $self->borrowernumber, "Membership renewed" ) if C4::Context->preference("BorrowersLog");
377     return dt_from_string( $expiry_date )->truncate( to => 'day' );
378 }
379
380 =head3 has_overdues
381
382 my $has_overdues = $patron->has_overdues;
383
384 Returns the number of patron's overdues
385
386 =cut
387
388 sub has_overdues {
389     my ($self) = @_;
390     my $dtf = Koha::Database->new->schema->storage->datetime_parser;
391     return $self->_result->issues->search({ date_due => { '<' => $dtf->format_datetime( dt_from_string() ) } })->count;
392 }
393
394 =head3 track_login
395
396     $patron->track_login;
397     $patron->track_login({ force => 1 });
398
399     Tracks a (successful) login attempt.
400     The preference TrackLastPatronActivity must be enabled. Or you
401     should pass the force parameter.
402
403 =cut
404
405 sub track_login {
406     my ( $self, $params ) = @_;
407     return if
408         !$params->{force} &&
409         !C4::Context->preference('TrackLastPatronActivity');
410     $self->lastseen( dt_from_string() )->store;
411 }
412
413 =head3 move_to_deleted
414
415 my $is_moved = $patron->move_to_deleted;
416
417 Move a patron to the deletedborrowers table.
418 This can be done before deleting a patron, to make sure the data are not completely deleted.
419
420 =cut
421
422 sub move_to_deleted {
423     my ($self) = @_;
424     my $patron_infos = $self->unblessed;
425     delete $patron_infos->{updated_on}; #This ensures the updated_on date in deletedborrowers will be set to the current timestamp
426     return Koha::Database->new->schema->resultset('Deletedborrower')->create($patron_infos);
427 }
428
429 =head3 article_requests
430
431 my @requests = $borrower->article_requests();
432 my $requests = $borrower->article_requests();
433
434 Returns either a list of ArticleRequests objects,
435 or an ArtitleRequests object, depending on the
436 calling context.
437
438 =cut
439
440 sub article_requests {
441     my ( $self ) = @_;
442
443     $self->{_article_requests} ||= Koha::ArticleRequests->search({ borrowernumber => $self->borrowernumber() });
444
445     return $self->{_article_requests};
446 }
447
448 =head3 article_requests_current
449
450 my @requests = $patron->article_requests_current
451
452 Returns the article requests associated with this patron that are incomplete
453
454 =cut
455
456 sub article_requests_current {
457     my ( $self ) = @_;
458
459     $self->{_article_requests_current} ||= Koha::ArticleRequests->search(
460         {
461             borrowernumber => $self->id(),
462             -or          => [
463                 { status => Koha::ArticleRequest::Status::Pending },
464                 { status => Koha::ArticleRequest::Status::Processing }
465             ]
466         }
467     );
468
469     return $self->{_article_requests_current};
470 }
471
472 =head3 article_requests_finished
473
474 my @requests = $biblio->article_requests_finished
475
476 Returns the article requests associated with this patron that are completed
477
478 =cut
479
480 sub article_requests_finished {
481     my ( $self, $borrower ) = @_;
482
483     $self->{_article_requests_finished} ||= Koha::ArticleRequests->search(
484         {
485             borrowernumber => $self->id(),
486             -or          => [
487                 { status => Koha::ArticleRequest::Status::Completed },
488                 { status => Koha::ArticleRequest::Status::Canceled }
489             ]
490         }
491     );
492
493     return $self->{_article_requests_finished};
494 }
495
496 =head3 add_enrolment_fee_if_needed
497
498 my $enrolment_fee = $patron->add_enrolment_fee_if_needed;
499
500 Add enrolment fee for a patron if needed.
501
502 =cut
503
504 sub add_enrolment_fee_if_needed {
505     my ($self) = @_;
506     my $enrolment_fee = $self->category->enrolmentfee;
507     if ( $enrolment_fee && $enrolment_fee > 0 ) {
508         # insert fee in patron debts
509         C4::Accounts::manualinvoice( $self->borrowernumber, '', '', 'A', $enrolment_fee );
510     }
511     return $enrolment_fee || 0;
512 }
513
514 =head3 checkouts
515
516 my $checkouts = $patron->checkouts
517
518 =cut
519
520 sub checkouts {
521     my ($self) = @_;
522     my $checkouts = $self->_result->issues;
523     return Koha::Checkouts->_new_from_dbic( $checkouts );
524 }
525
526 =head3 old_checkouts
527
528 my $old_checkouts = $patron->old_checkouts
529
530 =cut
531
532 sub old_checkouts {
533     my ($self) = @_;
534     my $old_checkouts = $self->_result->old_issues;
535     return Koha::Old::Checkouts->_new_from_dbic( $old_checkouts );
536 }
537
538 =head3 get_overdues
539
540 my $overdue_items = $patron->get_overdues
541
542 Return the overdued items
543
544 =cut
545
546 sub get_overdues {
547     my ($self) = @_;
548     my $dtf = Koha::Database->new->schema->storage->datetime_parser;
549     return $self->checkouts->search(
550         {
551             'me.date_due' => { '<' => $dtf->format_datetime(dt_from_string) },
552         },
553         {
554             prefetch => { item => { biblio => 'biblioitems' } },
555         }
556     );
557 }
558
559 =head3 get_age
560
561 my $age = $patron->get_age
562
563 Return the age of the patron
564
565 =cut
566
567 sub get_age {
568     my ($self)    = @_;
569     my $today_str = dt_from_string->strftime("%Y-%m-%d");
570     return unless $self->dateofbirth;
571     my $dob_str   = dt_from_string( $self->dateofbirth )->strftime("%Y-%m-%d");
572
573     my ( $dob_y,   $dob_m,   $dob_d )   = split /-/, $dob_str;
574     my ( $today_y, $today_m, $today_d ) = split /-/, $today_str;
575
576     my $age = $today_y - $dob_y;
577     if ( $dob_m . $dob_d > $today_m . $today_d ) {
578         $age--;
579     }
580
581     return $age;
582 }
583
584 =head3 account
585
586 my $account = $patron->account
587
588 =cut
589
590 sub account {
591     my ($self) = @_;
592     return Koha::Account->new( { patron_id => $self->borrowernumber } );
593 }
594
595 =head3 holds
596
597 my $holds = $patron->holds
598
599 Return all the holds placed by this patron
600
601 =cut
602
603 sub holds {
604     my ($self) = @_;
605     my $holds_rs = $self->_result->reserves->search( {}, { order_by => 'reservedate' } );
606     return Koha::Holds->_new_from_dbic($holds_rs);
607 }
608
609 =head3 old_holds
610
611 my $old_holds = $patron->old_holds
612
613 Return all the historical holds for this patron
614
615 =cut
616
617 sub old_holds {
618     my ($self) = @_;
619     my $old_holds_rs = $self->_result->old_reserves->search( {}, { order_by => 'reservedate' } );
620     return Koha::Old::Holds->_new_from_dbic($old_holds_rs);
621 }
622
623 =head3 notice_email_address
624
625   my $email = $patron->notice_email_address;
626
627 Return the email address of patron used for notices.
628 Returns the empty string if no email address.
629
630 =cut
631
632 sub notice_email_address{
633     my ( $self ) = @_;
634
635     my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
636     # if syspref is set to 'first valid' (value == OFF), look up email address
637     if ( $which_address eq 'OFF' ) {
638         return $self->first_valid_email_address;
639     }
640
641     return $self->$which_address || '';
642 }
643
644 =head3 first_valid_email_address
645
646 my $first_valid_email_address = $patron->first_valid_email_address
647
648 Return the first valid email address for a patron.
649 For now, the order  is defined as email, emailpro, B_email.
650 Returns the empty string if the borrower has no email addresses.
651
652 =cut
653
654 sub first_valid_email_address {
655     my ($self) = @_;
656
657     return $self->email() || $self->emailpro() || $self->B_email() || q{};
658 }
659
660 =head3 get_club_enrollments
661
662 =cut
663
664 sub get_club_enrollments {
665     my ( $self, $return_scalar ) = @_;
666
667     my $e = Koha::Club::Enrollments->search( { borrowernumber => $self->borrowernumber(), date_canceled => undef } );
668
669     return $e if $return_scalar;
670
671     return wantarray ? $e->as_list : $e;
672 }
673
674 =head3 get_enrollable_clubs
675
676 =cut
677
678 sub get_enrollable_clubs {
679     my ( $self, $is_enrollable_from_opac, $return_scalar ) = @_;
680
681     my $params;
682     $params->{is_enrollable_from_opac} = $is_enrollable_from_opac
683       if $is_enrollable_from_opac;
684     $params->{is_email_required} = 0 unless $self->first_valid_email_address();
685
686     $params->{borrower} = $self;
687
688     my $e = Koha::Clubs->get_enrollable($params);
689
690     return $e if $return_scalar;
691
692     return wantarray ? $e->as_list : $e;
693 }
694
695 =head3 account_locked
696
697 my $is_locked = $patron->account_locked
698
699 Return true if the patron has reach the maximum number of login attempts (see pref FailedLoginAttempts).
700 Otherwise return false.
701 If the pref is not set (empty string, null or 0), the feature is considered as disabled.
702
703 =cut
704
705 sub account_locked {
706     my ($self) = @_;
707     my $FailedLoginAttempts = C4::Context->preference('FailedLoginAttempts');
708     return ( $FailedLoginAttempts
709           and $self->login_attempts
710           and $self->login_attempts >= $FailedLoginAttempts )? 1 : 0;
711 }
712
713 =head3 can_see_patron_infos
714
715 my $can_see = $patron->can_see_patron_infos( $patron );
716
717 Return true if the patron (usually the logged in user) can see the patron's infos for a given patron
718
719 =cut
720
721 sub can_see_patron_infos {
722     my ( $self, $patron ) = @_;
723     return $self->can_see_patrons_from( $patron->library->branchcode );
724 }
725
726 =head3 can_see_patrons_from
727
728 my $can_see = $patron->can_see_patrons_from( $branchcode );
729
730 Return true if the patron (usually the logged in user) can see the patron's infos from a given library
731
732 =cut
733
734 sub can_see_patrons_from {
735     my ( $self, $branchcode ) = @_;
736     my $can = 0;
737     if ( $self->branchcode eq $branchcode ) {
738         $can = 1;
739     } elsif ( $self->has_permission( { borrowers => 'view_borrower_infos_from_any_libraries' } ) ) {
740         $can = 1;
741     } elsif ( my $library_groups = $self->library->library_groups ) {
742         while ( my $library_group = $library_groups->next ) {
743             if ( $library_group->parent->has_child( $branchcode ) ) {
744                 $can = 1;
745                 last;
746             }
747         }
748     }
749     return $can;
750 }
751
752 =head3 libraries_where_can_see_patrons
753
754 my $libraries = $patron-libraries_where_can_see_patrons;
755
756 Return the list of branchcodes(!) of libraries the patron is allowed to see other patron's infos.
757 The branchcodes are arbitrarily returned sorted.
758 We are supposing here that the object is related to the logged in patron (use of C4::Context::only_my_library)
759
760 An empty array means no restriction, the patron can see patron's infos from any libraries.
761
762 =cut
763
764 sub libraries_where_can_see_patrons {
765     my ( $self ) = @_;
766     my $userenv = C4::Context->userenv;
767
768     return () unless $userenv; # For tests, but userenv should be defined in tests...
769
770     my @restricted_branchcodes;
771     if (C4::Context::only_my_library) {
772         push @restricted_branchcodes, $self->branchcode;
773     }
774     else {
775         unless (
776             $self->has_permission(
777                 { borrowers => 'view_borrower_infos_from_any_libraries' }
778             )
779           )
780         {
781             my $library_groups = $self->library->library_groups({ ft_hide_patron_info => 1 });
782             if ( $library_groups->count )
783             {
784                 while ( my $library_group = $library_groups->next ) {
785                     my $parent = $library_group->parent;
786                     if ( $parent->has_child( $self->branchcode ) ) {
787                         push @restricted_branchcodes, $parent->children->get_column('branchcode');
788                     }
789                 }
790             }
791
792             @restricted_branchcodes = ( $self->branchcode ) unless @restricted_branchcodes;
793         }
794     }
795
796     @restricted_branchcodes = grep { defined $_ } @restricted_branchcodes;
797     @restricted_branchcodes = uniq(@restricted_branchcodes);
798     @restricted_branchcodes = sort(@restricted_branchcodes);
799     return @restricted_branchcodes;
800 }
801
802 sub has_permission {
803     my ( $self, $flagsrequired ) = @_;
804     return unless $self->userid;
805     # TODO code from haspermission needs to be moved here!
806     return C4::Auth::haspermission( $self->userid, $flagsrequired );
807 }
808
809 =head3 type
810
811 =cut
812
813 sub _type {
814     return 'Borrower';
815 }
816
817 =head1 AUTHOR
818
819 Kyle M Hall <kyle@bywatersolutions.com>
820 Alex Sassmannshausen <alex.sassmannshausen@ptfs-europe.com>
821
822 =cut
823
824 1;