Bug 17935: Adjust some POD lines, fix a few typos
[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
25 use C4::Context;
26 use C4::Log;
27 use Koha::Checkouts;
28 use Koha::Database;
29 use Koha::DateUtils;
30 use Koha::Holds;
31 use Koha::Old::Checkouts;
32 use Koha::Patron::Categories;
33 use Koha::Patron::HouseboundProfile;
34 use Koha::Patron::HouseboundRole;
35 use Koha::Patron::Images;
36 use Koha::Patrons;
37 use Koha::Virtualshelves;
38
39 use base qw(Koha::Object);
40
41 =head1 NAME
42
43 Koha::Patron - Koha Patron Object class
44
45 =head1 API
46
47 =head2 Class Methods
48
49 =cut
50
51 =head3 delete
52
53 $patron->delete
54
55 Delete patron's holds, lists and finally the patron.
56
57 Lists owned by the borrower are deleted, but entries from the borrower to
58 other lists are kept.
59
60 =cut
61
62 sub delete {
63     my ($self) = @_;
64
65     my $deleted;
66     $self->_result->result_source->schema->txn_do(
67         sub {
68             # Delete Patron's holds
69             $self->holds->delete;
70
71             # Delete all lists and all shares of this borrower
72             # Consistent with the approach Koha uses on deleting individual lists
73             # Note that entries in virtualshelfcontents added by this borrower to
74             # lists of others will be handled by a table constraint: the borrower
75             # is set to NULL in those entries.
76             # NOTE:
77             # We could handle the above deletes via a constraint too.
78             # But a new BZ report 11889 has been opened to discuss another approach.
79             # Instead of deleting we could also disown lists (based on a pref).
80             # In that way we could save shared and public lists.
81             # The current table constraints support that idea now.
82             # This pref should then govern the results of other routines/methods such as
83             # Koha::Virtualshelf->new->delete too.
84             # FIXME Could be $patron->get_lists
85             $_->delete for Koha::Virtualshelves->search( { owner => $self->borrowernumber } );
86
87             $deleted = $self->SUPER::delete;
88
89             logaction( "MEMBERS", "DELETE", $self->borrowernumber, "" ) if C4::Context->preference("BorrowersLog");
90         }
91     );
92     return $deleted;
93 }
94
95
96 =head3 category
97
98 my $patron_category = $patron->category
99
100 Return the patron category for this patron
101
102 =cut
103
104 sub category {
105     my ( $self ) = @_;
106     return Koha::Patron::Category->_new_from_dbic( $self->_result->categorycode );
107 }
108
109 =head3 guarantor
110
111 Returns a Koha::Patron object for this patron's guarantor
112
113 =cut
114
115 sub guarantor {
116     my ( $self ) = @_;
117
118     return unless $self->guarantorid();
119
120     return Koha::Patrons->find( $self->guarantorid() );
121 }
122
123 sub image {
124     my ( $self ) = @_;
125
126     return Koha::Patron::Images->find( $self->borrowernumber );
127 }
128
129 sub library {
130     my ( $self ) = @_;
131     return Koha::Library->_new_from_dbic($self->_result->branchcode);
132 }
133
134 =head3 guarantees
135
136 Returns the guarantees (list of Koha::Patron) of this patron
137
138 =cut
139
140 sub guarantees {
141     my ( $self ) = @_;
142
143     return Koha::Patrons->search( { guarantorid => $self->borrowernumber } );
144 }
145
146 =head3 housebound_profile
147
148 Returns the HouseboundProfile associated with this patron.
149
150 =cut
151
152 sub housebound_profile {
153     my ( $self ) = @_;
154     my $profile = $self->_result->housebound_profile;
155     return Koha::Patron::HouseboundProfile->_new_from_dbic($profile)
156         if ( $profile );
157     return;
158 }
159
160 =head3 housebound_role
161
162 Returns the HouseboundRole associated with this patron.
163
164 =cut
165
166 sub housebound_role {
167     my ( $self ) = @_;
168
169     my $role = $self->_result->housebound_role;
170     return Koha::Patron::HouseboundRole->_new_from_dbic($role) if ( $role );
171     return;
172 }
173
174 =head3 siblings
175
176 Returns the siblings of this patron.
177
178 =cut
179
180 sub siblings {
181     my ( $self ) = @_;
182
183     my $guarantor = $self->guarantor;
184
185     return unless $guarantor;
186
187     return Koha::Patrons->search(
188         {
189             guarantorid => {
190                 '!=' => undef,
191                 '=' => $guarantor->id,
192             },
193             borrowernumber => {
194                 '!=' => $self->borrowernumber,
195             }
196         }
197     );
198 }
199
200 =head3 wants_check_for_previous_checkout
201
202     $wants_check = $patron->wants_check_for_previous_checkout;
203
204 Return 1 if Koha needs to perform PrevIssue checking, else 0.
205
206 =cut
207
208 sub wants_check_for_previous_checkout {
209     my ( $self ) = @_;
210     my $syspref = C4::Context->preference("checkPrevCheckout");
211
212     # Simple cases
213     ## Hard syspref trumps all
214     return 1 if ($syspref eq 'hardyes');
215     return 0 if ($syspref eq 'hardno');
216     ## Now, patron pref trumps all
217     return 1 if ($self->checkprevcheckout eq 'yes');
218     return 0 if ($self->checkprevcheckout eq 'no');
219
220     # More complex: patron inherits -> determine category preference
221     my $checkPrevCheckoutByCat = $self->category->checkprevcheckout;
222     return 1 if ($checkPrevCheckoutByCat eq 'yes');
223     return 0 if ($checkPrevCheckoutByCat eq 'no');
224
225     # Finally: category preference is inherit, default to 0
226     if ($syspref eq 'softyes') {
227         return 1;
228     } else {
229         return 0;
230     }
231 }
232
233 =head3 do_check_for_previous_checkout
234
235     $do_check = $patron->do_check_for_previous_checkout($item);
236
237 Return 1 if the bib associated with $ITEM has previously been checked out to
238 $PATRON, 0 otherwise.
239
240 =cut
241
242 sub do_check_for_previous_checkout {
243     my ( $self, $item ) = @_;
244
245     # Find all items for bib and extract item numbers.
246     my @items = Koha::Items->search({biblionumber => $item->{biblionumber}});
247     my @item_nos;
248     foreach my $item (@items) {
249         push @item_nos, $item->itemnumber;
250     }
251
252     # Create (old)issues search criteria
253     my $criteria = {
254         borrowernumber => $self->borrowernumber,
255         itemnumber => \@item_nos,
256     };
257
258     # Check current issues table
259     my $issues = Koha::Checkouts->search($criteria);
260     return 1 if $issues->count; # 0 || N
261
262     # Check old issues table
263     my $old_issues = Koha::Old::Checkouts->search($criteria);
264     return $old_issues->count;  # 0 || N
265 }
266
267 =head3 is_debarred
268
269 my $debarment_expiration = $patron->is_debarred;
270
271 Returns the date a patron debarment will expire, or undef if the patron is not
272 debarred
273
274 =cut
275
276 sub is_debarred {
277     my ($self) = @_;
278
279     return unless $self->debarred;
280     return $self->debarred
281       if $self->debarred =~ '^9999'
282       or dt_from_string( $self->debarred ) > dt_from_string;
283     return;
284 }
285
286 =head3 is_expired
287
288 my $is_expired = $patron->is_expired;
289
290 Returns 1 if the patron is expired or 0;
291
292 =cut
293
294 sub is_expired {
295     my ($self) = @_;
296     return 0 unless $self->dateexpiry;
297     return 0 if $self->dateexpiry eq '0000-00-00';
298     return 1 if dt_from_string( $self->dateexpiry ) < dt_from_string->truncate( to => 'day' );
299     return 0;
300 }
301
302 =head3 is_going_to_expire
303
304 my $is_going_to_expire = $patron->is_going_to_expire;
305
306 Returns 1 if the patron is going to expired, depending on the NotifyBorrowerDeparture pref or 0
307
308 =cut
309
310 sub is_going_to_expire {
311     my ($self) = @_;
312
313     my $delay = C4::Context->preference('NotifyBorrowerDeparture') || 0;
314
315     return 0 unless $delay;
316     return 0 unless $self->dateexpiry;
317     return 0 if $self->dateexpiry eq '0000-00-00';
318     return 1 if dt_from_string( $self->dateexpiry )->subtract( days => $delay ) < dt_from_string->truncate( to => 'day' );
319     return 0;
320 }
321
322 =head3 update_password
323
324 my $updated = $patron->update_password( $userid, $password );
325
326 Update the userid and the password of a patron.
327 If the userid already exists, returns and let DBIx::Class warns
328 This will add an entry to action_logs if BorrowersLog is set.
329
330 =cut
331
332 sub update_password {
333     my ( $self, $userid, $password ) = @_;
334     eval { $self->userid($userid)->store; };
335     return if $@; # Make sure the userid is not already in used by another patron
336     $self->password($password)->store;
337     logaction( "MEMBERS", "CHANGE PASS", $self->borrowernumber, "" ) if C4::Context->preference("BorrowersLog");
338     return 1;
339 }
340
341 =head3 renew_account
342
343 my $new_expiry_date = $patron->renew_account
344
345 Extending the subscription to the expiry date.
346
347 =cut
348
349 sub renew_account {
350     my ($self) = @_;
351     my $date;
352     if ( C4::Context->preference('BorrowerRenewalPeriodBase') eq 'combination' ) {
353         $date = ( dt_from_string gt dt_from_string( $self->dateexpiry ) ) ? dt_from_string : dt_from_string( $self->dateexpiry );
354     } else {
355         $date =
356             C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry'
357             ? dt_from_string( $self->dateexpiry )
358             : dt_from_string;
359     }
360     my $expiry_date = $self->category->get_expiry_date($date);
361
362     $self->dateexpiry($expiry_date)->store;
363
364     $self->add_enrolment_fee_if_needed;
365
366     logaction( "MEMBERS", "RENEW", $self->borrowernumber, "Membership renewed" ) if C4::Context->preference("BorrowersLog");
367     return dt_from_string( $expiry_date )->truncate( to => 'day' );
368 }
369
370 =head3 has_overdues
371
372 my $has_overdues = $patron->has_overdues;
373
374 Returns the number of patron's overdues
375
376 =cut
377
378 sub has_overdues {
379     my ($self) = @_;
380     my $dtf = Koha::Database->new->schema->storage->datetime_parser;
381     return $self->_result->issues->search({ date_due => { '<' => $dtf->format_datetime( dt_from_string() ) } })->count;
382 }
383
384 =head3 track_login
385
386     $patron->track_login;
387     $patron->track_login({ force => 1 });
388
389     Tracks a (successful) login attempt.
390     The preference TrackLastPatronActivity must be enabled. Or you
391     should pass the force parameter.
392
393 =cut
394
395 sub track_login {
396     my ( $self, $params ) = @_;
397     return if
398         !$params->{force} &&
399         !C4::Context->preference('TrackLastPatronActivity');
400     $self->lastseen( dt_from_string() )->store;
401 }
402
403 =head3 move_to_deleted
404
405 my $is_moved = $patron->move_to_deleted;
406
407 Move a patron to the deletedborrowers table.
408 This can be done before deleting a patron, to make sure the data are not completely deleted.
409
410 =cut
411
412 sub move_to_deleted {
413     my ($self) = @_;
414     my $patron_infos = $self->unblessed;
415     delete $patron_infos->{updated_on}; #This ensures the updated_on date in deletedborrowers will be set to the current timestamp
416     return Koha::Database->new->schema->resultset('Deletedborrower')->create($patron_infos);
417 }
418
419 =head3 article_requests
420
421 my @requests = $borrower->article_requests();
422 my $requests = $borrower->article_requests();
423
424 Returns either a list of ArticleRequests objects,
425 or an ArtitleRequests object, depending on the
426 calling context.
427
428 =cut
429
430 sub article_requests {
431     my ( $self ) = @_;
432
433     $self->{_article_requests} ||= Koha::ArticleRequests->search({ borrowernumber => $self->borrowernumber() });
434
435     return $self->{_article_requests};
436 }
437
438 =head3 article_requests_current
439
440 my @requests = $patron->article_requests_current
441
442 Returns the article requests associated with this patron that are incomplete
443
444 =cut
445
446 sub article_requests_current {
447     my ( $self ) = @_;
448
449     $self->{_article_requests_current} ||= Koha::ArticleRequests->search(
450         {
451             borrowernumber => $self->id(),
452             -or          => [
453                 { status => Koha::ArticleRequest::Status::Pending },
454                 { status => Koha::ArticleRequest::Status::Processing }
455             ]
456         }
457     );
458
459     return $self->{_article_requests_current};
460 }
461
462 =head3 article_requests_finished
463
464 my @requests = $biblio->article_requests_finished
465
466 Returns the article requests associated with this patron that are completed
467
468 =cut
469
470 sub article_requests_finished {
471     my ( $self, $borrower ) = @_;
472
473     $self->{_article_requests_finished} ||= Koha::ArticleRequests->search(
474         {
475             borrowernumber => $self->id(),
476             -or          => [
477                 { status => Koha::ArticleRequest::Status::Completed },
478                 { status => Koha::ArticleRequest::Status::Canceled }
479             ]
480         }
481     );
482
483     return $self->{_article_requests_finished};
484 }
485
486 =head3 add_enrolment_fee_if_needed
487
488 my $enrolment_fee = $patron->add_enrolment_fee_if_needed;
489
490 Add enrolment fee for a patron if needed.
491
492 =cut
493
494 sub add_enrolment_fee_if_needed {
495     my ($self) = @_;
496     my $enrolment_fee = $self->category->enrolmentfee;
497     if ( $enrolment_fee && $enrolment_fee > 0 ) {
498         # insert fee in patron debts
499         C4::Accounts::manualinvoice( $self->borrowernumber, '', '', 'A', $enrolment_fee );
500     }
501     return $enrolment_fee || 0;
502 }
503
504 =head3 checkouts
505
506 my $issues = $patron->checkouts
507
508 =cut
509
510 sub checkouts {
511     my ($self) = @_;
512     my $issues = $self->_result->issues;
513     return Koha::Checkouts->_new_from_dbic( $issues );
514 }
515
516 =head3 get_overdues
517
518 my $overdue_items = $patron->get_overdues
519
520 Return the overdued items
521
522 =cut
523
524 sub get_overdues {
525     my ($self) = @_;
526     my $dtf = Koha::Database->new->schema->storage->datetime_parser;
527     return $self->checkouts->search(
528         {
529             'me.date_due' => { '<' => $dtf->format_datetime(dt_from_string) },
530         },
531         {
532             prefetch => { item => { biblio => 'biblioitems' } },
533         }
534     );
535 }
536
537 =head3 get_age
538
539 my $age = $patron->get_age
540
541 Return the age of the patron
542
543 =cut
544
545 sub get_age {
546     my ($self)    = @_;
547     my $today_str = dt_from_string->strftime("%Y-%m-%d");
548     my $dob_str   = dt_from_string( $self->dateofbirth )->strftime("%Y-%m-%d");
549
550     my ( $dob_y,   $dob_m,   $dob_d )   = split /-/, $dob_str;
551     my ( $today_y, $today_m, $today_d ) = split /-/, $today_str;
552
553     my $age = $today_y - $dob_y;
554     if ( $dob_m . $dob_d > $today_m . $today_d ) {
555         $age--;
556     }
557
558     return $age;
559 }
560
561 =head3 account
562
563 my $account = $patron->account
564
565 =cut
566
567 sub account {
568     my ($self) = @_;
569     return Koha::Account->new( { patron_id => $self->borrowernumber } );
570 }
571
572 =head3 holds
573
574 my $holds = $patron->holds
575
576 Return all the holds placed by this patron
577
578 =cut
579
580 sub holds {
581     my ($self) = @_;
582     my $holds_rs = $self->_result->reserves->search( {}, { order_by => 'reservedate' } );
583     return Koha::Holds->_new_from_dbic($holds_rs);
584 }
585
586 =head3 type
587
588 =cut
589
590 sub _type {
591     return 'Borrower';
592 }
593
594 =head1 AUTHOR
595
596 Kyle M Hall <kyle@bywatersolutions.com>
597 Alex Sassmannshausen <alex.sassmannshausen@ptfs-europe.com>
598
599 =cut
600
601 1;