Bug 16851: Move HasOverdues to Koha::Patron->has_overdues
[koha.git] / C4 / Members.pm
1 package C4::Members;
2
3 # Copyright 2000-2003 Katipo Communications
4 # Copyright 2010 BibLibre
5 # Parts Copyright 2010 Catalyst IT
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22
23 use strict;
24 #use warnings; FIXME - Bug 2505
25 use C4::Context;
26 use String::Random qw( random_string );
27 use Scalar::Util qw( looks_like_number );
28 use Date::Calc qw/Today check_date Date_to_Days/;
29 use C4::Log; # logaction
30 use C4::Overdues;
31 use C4::Reserves;
32 use C4::Accounts;
33 use C4::Biblio;
34 use C4::Letters;
35 use C4::Members::Attributes qw(SearchIdMatchingAttribute UpdateBorrowerAttribute);
36 use C4::NewsChannels; #get slip news
37 use DateTime;
38 use Koha::Database;
39 use Koha::DateUtils;
40 use Text::Unaccent qw( unac_string );
41 use Koha::AuthUtils qw(hash_password);
42 use Koha::Database;
43 use Koha::Holds;
44 use Koha::List::Patron;
45 use Koha::Patrons;
46 use Koha::Patron::Categories;
47
48 our (@ISA,@EXPORT,@EXPORT_OK,$debug);
49
50 use Module::Load::Conditional qw( can_load );
51 if ( ! can_load( modules => { 'Koha::NorwegianPatronDB' => undef } ) ) {
52    $debug && warn "Unable to load Koha::NorwegianPatronDB";
53 }
54
55
56 BEGIN {
57     $debug = $ENV{DEBUG} || 0;
58     require Exporter;
59     @ISA = qw(Exporter);
60     #Get data
61     push @EXPORT, qw(
62         &Search
63         &GetMemberDetails
64         &GetMember
65
66         &GetMemberIssuesAndFines
67         &GetPendingIssues
68         &GetAllIssues
69
70         &GetFirstValidEmailAddress
71         &GetNoticeEmailAddress
72
73         &GetAge
74         &GetSortDetails
75
76         &GetHideLostItemsPreference
77
78         &IsMemberBlocked
79         &GetMemberAccountRecords
80         &GetBorNotifyAcctRecord
81
82         GetBorrowerCategorycode
83
84         &GetBorrowersToExpunge
85         &GetBorrowersWhoHaveNeverBorrowed
86         &GetBorrowersWithIssuesHistoryOlderThan
87
88         &GetUpcomingMembershipExpires
89
90         &IssueSlip
91         GetBorrowersWithEmail
92
93         GetOverduesForPatron
94     );
95
96     #Modify data
97     push @EXPORT, qw(
98         &ModMember
99         &changepassword
100     );
101
102     #Delete data
103     push @EXPORT, qw(
104         &DelMember
105     );
106
107     #Insert data
108     push @EXPORT, qw(
109         &AddMember
110         &AddMember_Opac
111         &MoveMemberToDeleted
112     );
113
114     #Check data
115     push @EXPORT, qw(
116         &checkuniquemember
117         &checkuserpassword
118         &Check_Userid
119         &Generate_Userid
120         &fixup_cardnumber
121         &checkcardnumber
122     );
123 }
124
125 =head1 NAME
126
127 C4::Members - Perl Module containing convenience functions for member handling
128
129 =head1 SYNOPSIS
130
131 use C4::Members;
132
133 =head1 DESCRIPTION
134
135 This module contains routines for adding, modifying and deleting members/patrons/borrowers 
136
137 =head1 FUNCTIONS
138
139 =head2 GetMemberDetails
140
141 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
142
143 Looks up a patron and returns information about him or her. If
144 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
145 up the borrower by number; otherwise, it looks up the borrower by card
146 number.
147
148 C<$borrower> is a reference-to-hash whose keys are the fields of the
149 borrowers table in the Koha database. In addition,
150 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
151 about the patron. Its keys act as flags :
152
153     if $borrower->{flags}->{LOST} {
154         # Patron's card was reported lost
155     }
156
157 If the state of a flag means that the patron should not be
158 allowed to borrow any more books, then it will have a C<noissues> key
159 with a true value.
160
161 See patronflags for more details.
162
163 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
164 about the top-level permissions flags set for the borrower.  For example,
165 if a user has the "editcatalogue" permission,
166 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
167 the value "1".
168
169 =cut
170
171 sub GetMemberDetails {
172     my ( $borrowernumber, $cardnumber ) = @_;
173     my $dbh = C4::Context->dbh;
174     my $query;
175     my $sth;
176     if ($borrowernumber) {
177         $sth = $dbh->prepare("
178             SELECT borrowers.*,
179                    category_type,
180                    categories.description,
181                    categories.BlockExpiredPatronOpacActions,
182                    reservefee,
183                    enrolmentperiod
184             FROM borrowers
185             LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
186             WHERE borrowernumber = ?
187         ");
188         $sth->execute($borrowernumber);
189     }
190     elsif ($cardnumber) {
191         $sth = $dbh->prepare("
192             SELECT borrowers.*,
193                    category_type,
194                    categories.description,
195                    categories.BlockExpiredPatronOpacActions,
196                    reservefee,
197                    enrolmentperiod
198             FROM borrowers
199             LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
200             WHERE cardnumber = ?
201         ");
202         $sth->execute($cardnumber);
203     }
204     else {
205         return;
206     }
207     my $borrower = $sth->fetchrow_hashref;
208     return unless $borrower;
209     my ($amount) = GetMemberAccountRecords($borrower->{borrowernumber});
210     $borrower->{'amountoutstanding'} = $amount;
211     # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
212     my $flags = patronflags( $borrower);
213     my $accessflagshash;
214
215     $sth = $dbh->prepare("select bit,flag from userflags");
216     $sth->execute;
217     while ( my ( $bit, $flag ) = $sth->fetchrow ) {
218         if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
219             $accessflagshash->{$flag} = 1;
220         }
221     }
222     $borrower->{'flags'}     = $flags;
223     $borrower->{'authflags'} = $accessflagshash;
224
225     # Handle setting the true behavior for BlockExpiredPatronOpacActions
226     $borrower->{'BlockExpiredPatronOpacActions'} =
227       C4::Context->preference('BlockExpiredPatronOpacActions')
228       if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
229
230     $borrower->{'is_expired'} = 0;
231     $borrower->{'is_expired'} = 1 if
232       defined($borrower->{dateexpiry}) &&
233       $borrower->{'dateexpiry'} ne '0000-00-00' &&
234       Date_to_Days( Today() ) >
235       Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
236
237     return ($borrower);    #, $flags, $accessflagshash);
238 }
239
240 =head2 patronflags
241
242  $flags = &patronflags($patron);
243
244 This function is not exported.
245
246 The following will be set where applicable:
247  $flags->{CHARGES}->{amount}        Amount of debt
248  $flags->{CHARGES}->{noissues}      Set if debt amount >$5.00 (or syspref noissuescharge)
249  $flags->{CHARGES}->{message}       Message -- deprecated
250
251  $flags->{CREDITS}->{amount}        Amount of credit
252  $flags->{CREDITS}->{message}       Message -- deprecated
253
254  $flags->{  GNA  }                  Patron has no valid address
255  $flags->{  GNA  }->{noissues}      Set for each GNA
256  $flags->{  GNA  }->{message}       "Borrower has no valid address" -- deprecated
257
258  $flags->{ LOST  }                  Patron's card reported lost
259  $flags->{ LOST  }->{noissues}      Set for each LOST
260  $flags->{ LOST  }->{message}       Message -- deprecated
261
262  $flags->{DBARRED}                  Set if patron debarred, no access
263  $flags->{DBARRED}->{noissues}      Set for each DBARRED
264  $flags->{DBARRED}->{message}       Message -- deprecated
265
266  $flags->{ NOTES }
267  $flags->{ NOTES }->{message}       The note itself.  NOT deprecated
268
269  $flags->{ ODUES }                  Set if patron has overdue books.
270  $flags->{ ODUES }->{message}       "Yes"  -- deprecated
271  $flags->{ ODUES }->{itemlist}      ref-to-array: list of overdue books
272  $flags->{ ODUES }->{itemlisttext}  Text list of overdue items -- deprecated
273
274  $flags->{WAITING}                  Set if any of patron's reserves are available
275  $flags->{WAITING}->{message}       Message -- deprecated
276  $flags->{WAITING}->{itemlist}      ref-to-array: list of available items
277
278 =over 
279
280 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
281 overdue items. Its elements are references-to-hash, each describing an
282 overdue item. The keys are selected fields from the issues, biblio,
283 biblioitems, and items tables of the Koha database.
284
285 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
286 the overdue items, one per line.  Deprecated.
287
288 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
289 available items. Each element is a reference-to-hash whose keys are
290 fields from the reserves table of the Koha database.
291
292 =back
293
294 All the "message" fields that include language generated in this function are deprecated, 
295 because such strings belong properly in the display layer.
296
297 The "message" field that comes from the DB is OK.
298
299 =cut
300
301 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
302 # FIXME rename this function.
303 sub patronflags {
304     my %flags;
305     my ( $patroninformation) = @_;
306     my $dbh=C4::Context->dbh;
307     my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
308     if ( $owing > 0 ) {
309         my %flaginfo;
310         my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
311         $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
312         $flaginfo{'amount'}  = sprintf "%.02f", $owing;
313         if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
314             $flaginfo{'noissues'} = 1;
315         }
316         $flags{'CHARGES'} = \%flaginfo;
317     }
318     elsif ( $balance < 0 ) {
319         my %flaginfo;
320         $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
321         $flaginfo{'amount'}  = sprintf "%.02f", $balance;
322         $flags{'CREDITS'} = \%flaginfo;
323     }
324
325     # Check the debt of the guarntees of this patron
326     my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
327     $no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
328     if ( defined $no_issues_charge_guarantees ) {
329         my $p = Koha::Patrons->find( $patroninformation->{borrowernumber} );
330         my @guarantees = $p->guarantees();
331         my $guarantees_non_issues_charges;
332         foreach my $g ( @guarantees ) {
333             my ( $b, $n, $o ) = C4::Members::GetMemberAccountBalance( $g->id );
334             $guarantees_non_issues_charges += $n;
335         }
336
337         if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
338             my %flaginfo;
339             $flaginfo{'message'} = sprintf 'patron guarantees owe %.02f', $guarantees_non_issues_charges;
340             $flaginfo{'amount'}  = $guarantees_non_issues_charges;
341             $flaginfo{'noissues'} = 1 unless C4::Context->preference("allowfineoverride");
342             $flags{'CHARGES_GUARANTEES'} = \%flaginfo;
343         }
344     }
345
346     if (   $patroninformation->{'gonenoaddress'}
347         && $patroninformation->{'gonenoaddress'} == 1 )
348     {
349         my %flaginfo;
350         $flaginfo{'message'}  = 'Borrower has no valid address.';
351         $flaginfo{'noissues'} = 1;
352         $flags{'GNA'}         = \%flaginfo;
353     }
354     if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
355         my %flaginfo;
356         $flaginfo{'message'}  = 'Borrower\'s card reported lost.';
357         $flaginfo{'noissues'} = 1;
358         $flags{'LOST'}        = \%flaginfo;
359     }
360     if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
361         if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
362             my %flaginfo;
363             $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
364             $flaginfo{'message'}         = $patroninformation->{'debarredcomment'};
365             $flaginfo{'noissues'}        = 1;
366             $flaginfo{'dateend'}         = $patroninformation->{'debarred'};
367             $flags{'DBARRED'}           = \%flaginfo;
368         }
369     }
370     if (   $patroninformation->{'borrowernotes'}
371         && $patroninformation->{'borrowernotes'} )
372     {
373         my %flaginfo;
374         $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
375         $flags{'NOTES'}      = \%flaginfo;
376     }
377     my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
378     if ( $odues && $odues > 0 ) {
379         my %flaginfo;
380         $flaginfo{'message'}  = "Yes";
381         $flaginfo{'itemlist'} = $itemsoverdue;
382         foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
383             @$itemsoverdue )
384         {
385             $flaginfo{'itemlisttext'} .=
386               "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";  # newline is display layer
387         }
388         $flags{'ODUES'} = \%flaginfo;
389     }
390     my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
391     my $nowaiting = scalar @itemswaiting;
392     if ( $nowaiting > 0 ) {
393         my %flaginfo;
394         $flaginfo{'message'}  = "Reserved items available";
395         $flaginfo{'itemlist'} = \@itemswaiting;
396         $flags{'WAITING'}     = \%flaginfo;
397     }
398     return ( \%flags );
399 }
400
401
402 =head2 GetMember
403
404   $borrower = &GetMember(%information);
405
406 Retrieve the first patron record meeting on criteria listed in the
407 C<%information> hash, which should contain one or more
408 pairs of borrowers column names and values, e.g.,
409
410    $borrower = GetMember(borrowernumber => id);
411
412 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
413 the C<borrowers> table in the Koha database.
414
415 FIXME: GetMember() is used throughout the code as a lookup
416 on a unique key such as the borrowernumber, but this meaning is not
417 enforced in the routine itself.
418
419 =cut
420
421 #'
422 sub GetMember {
423     my ( %information ) = @_;
424     if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
425         #passing mysql's kohaadmin?? Makes no sense as a query
426         return;
427     }
428     my $dbh = C4::Context->dbh;
429     my $select =
430     q{SELECT borrowers.*, categories.category_type, categories.description
431     FROM borrowers 
432     LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
433     my $more_p = 0;
434     my @values = ();
435     for (keys %information ) {
436         if ($more_p) {
437             $select .= ' AND ';
438         }
439         else {
440             $more_p++;
441         }
442
443         if (defined $information{$_}) {
444             $select .= "$_ = ?";
445             push @values, $information{$_};
446         }
447         else {
448             $select .= "$_ IS NULL";
449         }
450     }
451     $debug && warn $select, " ",values %information;
452     my $sth = $dbh->prepare("$select");
453     $sth->execute(@values);
454     my $data = $sth->fetchall_arrayref({});
455     #FIXME interface to this routine now allows generation of a result set
456     #so whole array should be returned but bowhere in the current code expects this
457     if (@{$data} ) {
458         return $data->[0];
459     }
460
461     return;
462 }
463
464 =head2 IsMemberBlocked
465
466   my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
467
468 Returns whether a patron is restricted or has overdue items that may result
469 in a block of circulation privileges.
470
471 C<$block_status> can have the following values:
472
473 1 if the patron is currently restricted, in which case
474 C<$count> is the expiration date (9999-12-31 for indefinite)
475
476 -1 if the patron has overdue items, in which case C<$count> is the number of them
477
478 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
479
480 Existing active restrictions are checked before current overdue items.
481
482 =cut
483
484 sub IsMemberBlocked {
485     my $borrowernumber = shift;
486     my $dbh            = C4::Context->dbh;
487
488     my $blockeddate = Koha::Patrons->find( $borrowernumber )->is_debarred;
489
490     return ( 1, $blockeddate ) if $blockeddate;
491
492     # if he have late issues
493     my $sth = $dbh->prepare(
494         "SELECT COUNT(*) as latedocs
495          FROM issues
496          WHERE borrowernumber = ?
497          AND date_due < now()"
498     );
499     $sth->execute($borrowernumber);
500     my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
501
502     return ( -1, $latedocs ) if $latedocs > 0;
503
504     return ( 0, 0 );
505 }
506
507 =head2 GetMemberIssuesAndFines
508
509   ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
510
511 Returns aggregate data about items borrowed by the patron with the
512 given borrowernumber.
513
514 C<&GetMemberIssuesAndFines> returns a three-element array.  C<$overdue_count> is the
515 number of overdue items the patron currently has borrowed. C<$issue_count> is the
516 number of books the patron currently has borrowed.  C<$total_fines> is
517 the total fine currently due by the borrower.
518
519 =cut
520
521 #'
522 sub GetMemberIssuesAndFines {
523     my ( $borrowernumber ) = @_;
524     my $dbh   = C4::Context->dbh;
525     my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
526
527     $debug and warn $query."\n";
528     my $sth = $dbh->prepare($query);
529     $sth->execute($borrowernumber);
530     my $issue_count = $sth->fetchrow_arrayref->[0];
531
532     $sth = $dbh->prepare(
533         "SELECT COUNT(*) FROM issues 
534          WHERE borrowernumber = ? 
535          AND date_due < now()"
536     );
537     $sth->execute($borrowernumber);
538     my $overdue_count = $sth->fetchrow_arrayref->[0];
539
540     $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
541     $sth->execute($borrowernumber);
542     my $total_fines = $sth->fetchrow_arrayref->[0];
543
544     return ($overdue_count, $issue_count, $total_fines);
545 }
546
547
548 =head2 ModMember
549
550   my $success = ModMember(borrowernumber => $borrowernumber,
551                                             [ field => value ]... );
552
553 Modify borrower's data.  All date fields should ALREADY be in ISO format.
554
555 return :
556 true on success, or false on failure
557
558 =cut
559
560 sub ModMember {
561     my (%data) = @_;
562     # test to know if you must update or not the borrower password
563     if (exists $data{password}) {
564         if ($data{password} eq '****' or $data{password} eq '') {
565             delete $data{password};
566         } else {
567             if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
568                 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
569                 Koha::NorwegianPatronDB::NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
570             }
571             $data{password} = hash_password($data{password});
572         }
573     }
574
575     my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
576
577     # get only the columns of a borrower
578     my $schema = Koha::Database->new()->schema;
579     my @columns = $schema->source('Borrower')->columns;
580     my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
581     delete $new_borrower->{flags};
582
583     $new_borrower->{dateofbirth}     ||= undef if exists $new_borrower->{dateofbirth};
584     $new_borrower->{dateenrolled}    ||= undef if exists $new_borrower->{dateenrolled};
585     $new_borrower->{dateexpiry}      ||= undef if exists $new_borrower->{dateexpiry};
586     $new_borrower->{debarred}        ||= undef if exists $new_borrower->{debarred};
587     $new_borrower->{sms_provider_id} ||= undef if exists $new_borrower->{sms_provider_id};
588
589     my $rs = $schema->resultset('Borrower')->search({
590         borrowernumber => $new_borrower->{borrowernumber},
591      });
592
593     delete $new_borrower->{userid} if exists $new_borrower->{userid} and not $new_borrower->{userid};
594
595     my $execute_success = $rs->update($new_borrower);
596     if ($execute_success ne '0E0') { # only proceed if the update was a success
597         # If the patron changes to a category with enrollment fee, we add a fee
598         if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
599             if ( C4::Context->preference('FeeOnChangePatronCategory') ) {
600                 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
601             }
602         }
603
604         # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
605         # cronjob will use for syncing with NL
606         if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
607             my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
608                 'synctype'       => 'norwegianpatrondb',
609                 'borrowernumber' => $data{'borrowernumber'}
610             });
611             # Do not set to "edited" if syncstatus is "new". We need to sync as new before
612             # we can sync as changed. And the "new sync" will pick up all changes since
613             # the patron was created anyway.
614             if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
615                 $borrowersync->update( { 'syncstatus' => 'edited' } );
616             }
617             # Set the value of 'sync'
618             $borrowersync->update( { 'sync' => $data{'sync'} } );
619             # Try to do the live sync
620             Koha::NorwegianPatronDB::NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
621         }
622
623         logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
624     }
625     return $execute_success;
626 }
627
628 =head2 AddMember
629
630   $borrowernumber = &AddMember(%borrower);
631
632 insert new borrower into table
633
634 (%borrower keys are database columns. Database columns could be
635 different in different versions. Please look into database for correct
636 column names.)
637
638 Returns the borrowernumber upon success
639
640 Returns as undef upon any db error without further processing
641
642 =cut
643
644 #'
645 sub AddMember {
646     my (%data) = @_;
647     my $dbh = C4::Context->dbh;
648     my $schema = Koha::Database->new()->schema;
649
650     # generate a proper login if none provided
651     $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
652       if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
653
654     # add expiration date if it isn't already there
655     $data{dateexpiry} ||= Koha::Patron::Categories->find( $data{categorycode} )->get_expiry_date;
656
657     # add enrollment date if it isn't already there
658     unless ( $data{'dateenrolled'} ) {
659         $data{'dateenrolled'} = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
660     }
661
662     my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
663     $data{'privacy'} =
664         $patron_category->default_privacy() eq 'default' ? 1
665       : $patron_category->default_privacy() eq 'never'   ? 2
666       : $patron_category->default_privacy() eq 'forever' ? 0
667       :                                                    undef;
668
669     $data{'privacy_guarantor_checkouts'} = 0 unless defined( $data{'privacy_guarantor_checkouts'} );
670
671     # Make a copy of the plain text password for later use
672     my $plain_text_password = $data{'password'};
673
674     # create a disabled account if no password provided
675     $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
676
677     # we don't want invalid dates in the db (mysql has a bad habit of inserting 0000-00-00
678     $data{'dateofbirth'}     = undef if ( not $data{'dateofbirth'} );
679     $data{'debarred'}        = undef if ( not $data{'debarred'} );
680     $data{'sms_provider_id'} = undef if ( not $data{'sms_provider_id'} );
681
682     # get only the columns of Borrower
683     my @columns = $schema->source('Borrower')->columns;
684     my $new_member = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $data{$_} )  : () } keys(%data) } ;
685     $new_member->{checkprevcheckout} ||= 'inherit';
686     delete $new_member->{borrowernumber};
687
688     my $rs = $schema->resultset('Borrower');
689     $data{borrowernumber} = $rs->create($new_member)->id;
690
691     # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
692     # cronjob will use for syncing with NL
693     if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
694         Koha::Database->new->schema->resultset('BorrowerSync')->create({
695             'borrowernumber' => $data{'borrowernumber'},
696             'synctype'       => 'norwegianpatrondb',
697             'sync'           => 1,
698             'syncstatus'     => 'new',
699             'hashed_pin'     => Koha::NorwegianPatronDB::NLEncryptPIN( $plain_text_password ),
700         });
701     }
702
703     # mysql_insertid is probably bad.  not necessarily accurate and mysql-specific at best.
704     logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
705
706     AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
707
708     return $data{borrowernumber};
709 }
710
711 =head2 Check_Userid
712
713     my $uniqueness = Check_Userid($userid,$borrowernumber);
714
715     $borrowernumber is optional (i.e. it can contain a blank value). If $userid is passed with a blank $borrowernumber variable, the database will be checked for all instances of that userid (i.e. userid=? AND borrowernumber != '').
716
717     If $borrowernumber is provided, the database will be checked for every instance of that userid coupled with a different borrower(number) than the one provided.
718
719     return :
720         0 for not unique (i.e. this $userid already exists)
721         1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
722
723 =cut
724
725 sub Check_Userid {
726     my ( $uid, $borrowernumber ) = @_;
727
728     return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
729
730     return 0 if ( $uid eq C4::Context->config('user') );
731
732     my $rs = Koha::Database->new()->schema()->resultset('Borrower');
733
734     my $params;
735     $params->{userid} = $uid;
736     $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
737
738     my $count = $rs->count( $params );
739
740     return $count ? 0 : 1;
741 }
742
743 =head2 Generate_Userid
744
745     my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
746
747     Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
748
749     $borrowernumber is optional (i.e. it can contain a blank value). A value is passed when generating a new userid for an existing borrower. When a new userid is created for a new borrower, a blank value is passed to this sub.
750
751     return :
752         new userid ($firstname.$surname if there is a $firstname, or $surname if there is no value in $firstname) plus offset (0 if the $newuid is unique, or a higher numeric value if Check_Userid finds an existing match for the $newuid in the database).
753
754 =cut
755
756 sub Generate_Userid {
757   my ($borrowernumber, $firstname, $surname) = @_;
758   my $newuid;
759   my $offset = 0;
760   #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
761   do {
762     $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
763     $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
764     $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
765     $newuid = unac_string('utf-8',$newuid);
766     $newuid .= $offset unless $offset == 0;
767     $offset++;
768
769    } while (!Check_Userid($newuid,$borrowernumber));
770
771    return $newuid;
772 }
773
774 =head2 fixup_cardnumber
775
776 Warning: The caller is responsible for locking the members table in write
777 mode, to avoid database corruption.
778
779 =cut
780
781 use vars qw( @weightings );
782 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
783
784 sub fixup_cardnumber {
785     my ($cardnumber) = @_;
786     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
787
788     # Find out whether member numbers should be generated
789     # automatically. Should be either "1" or something else.
790     # Defaults to "0", which is interpreted as "no".
791
792     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
793     ($autonumber_members) or return $cardnumber;
794     my $checkdigit = C4::Context->preference('checkdigit');
795     my $dbh = C4::Context->dbh;
796     if ( $checkdigit and $checkdigit eq 'katipo' ) {
797
798         # if checkdigit is selected, calculate katipo-style cardnumber.
799         # otherwise, just use the max()
800         # purpose: generate checksum'd member numbers.
801         # We'll assume we just got the max value of digits 2-8 of member #'s
802         # from the database and our job is to increment that by one,
803         # determine the 1st and 9th digits and return the full string.
804         my $sth = $dbh->prepare(
805             "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
806         );
807         $sth->execute;
808         my $data = $sth->fetchrow_hashref;
809         $cardnumber = $data->{new_num};
810         if ( !$cardnumber ) {    # If DB has no values,
811             $cardnumber = 1000000;    # start at 1000000
812         } else {
813             $cardnumber += 1;
814         }
815
816         my $sum = 0;
817         for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
818             # read weightings, left to right, 1 char at a time
819             my $temp1 = $weightings[$i];
820
821             # sequence left to right, 1 char at a time
822             my $temp2 = substr( $cardnumber, $i, 1 );
823
824             # mult each char 1-7 by its corresponding weighting
825             $sum += $temp1 * $temp2;
826         }
827
828         my $rem = ( $sum % 11 );
829         $rem = 'X' if $rem == 10;
830
831         return "V$cardnumber$rem";
832      } else {
833
834         my $sth = $dbh->prepare(
835             'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
836         );
837         $sth->execute;
838         my ($result) = $sth->fetchrow;
839         return $result + 1;
840     }
841     return $cardnumber;     # just here as a fallback/reminder 
842 }
843
844 =head2 GetPendingIssues
845
846   my $issues = &GetPendingIssues(@borrowernumber);
847
848 Looks up what the patron with the given borrowernumber has borrowed.
849
850 C<&GetPendingIssues> returns a
851 reference-to-array where each element is a reference-to-hash; the
852 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
853 The keys include C<biblioitems> fields except marc and marcxml.
854
855 =cut
856
857 sub GetPendingIssues {
858     my @borrowernumbers = @_;
859
860     unless (@borrowernumbers ) { # return a ref_to_array
861         return \@borrowernumbers; # to not cause surprise to caller
862     }
863
864     # Borrowers part of the query
865     my $bquery = '';
866     for (my $i = 0; $i < @borrowernumbers; $i++) {
867         $bquery .= ' issues.borrowernumber = ?';
868         if ($i < $#borrowernumbers ) {
869             $bquery .= ' OR';
870         }
871     }
872
873     # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
874     # FIXME: namespace collision: each table has "timestamp" fields.  Which one is "timestamp" ?
875     # FIXME: circ/ciculation.pl tries to sort by timestamp!
876     # FIXME: namespace collision: other collisions possible.
877     # FIXME: most of this data isn't really being used by callers.
878     my $query =
879    "SELECT issues.*,
880             items.*,
881            biblio.*,
882            biblioitems.volume,
883            biblioitems.number,
884            biblioitems.itemtype,
885            biblioitems.isbn,
886            biblioitems.issn,
887            biblioitems.publicationyear,
888            biblioitems.publishercode,
889            biblioitems.volumedate,
890            biblioitems.volumedesc,
891            biblioitems.lccn,
892            biblioitems.url,
893            borrowers.firstname,
894            borrowers.surname,
895            borrowers.cardnumber,
896            issues.timestamp AS timestamp,
897            issues.renewals  AS renewals,
898            issues.borrowernumber AS borrowernumber,
899             items.renewals  AS totalrenewals
900     FROM   issues
901     LEFT JOIN items       ON items.itemnumber       =      issues.itemnumber
902     LEFT JOIN biblio      ON items.biblionumber     =      biblio.biblionumber
903     LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
904     LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
905     WHERE
906       $bquery
907     ORDER BY issues.issuedate"
908     ;
909
910     my $sth = C4::Context->dbh->prepare($query);
911     $sth->execute(@borrowernumbers);
912     my $data = $sth->fetchall_arrayref({});
913     my $today = dt_from_string;
914     foreach (@{$data}) {
915         if ($_->{issuedate}) {
916             $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
917         }
918         $_->{date_due_sql} = $_->{date_due};
919         # FIXME no need to have this value
920         $_->{date_due} or next;
921         $_->{date_due_sql} = $_->{date_due};
922         # FIXME no need to have this value
923         $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
924         if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
925             $_->{overdue} = 1;
926         }
927     }
928     return $data;
929 }
930
931 =head2 GetAllIssues
932
933   $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
934
935 Looks up what the patron with the given borrowernumber has borrowed,
936 and sorts the results.
937
938 C<$sortkey> is the name of a field on which to sort the results. This
939 should be the name of a field in the C<issues>, C<biblio>,
940 C<biblioitems>, or C<items> table in the Koha database.
941
942 C<$limit> is the maximum number of results to return.
943
944 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
945 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
946 C<items> tables of the Koha database.
947
948 =cut
949
950 #'
951 sub GetAllIssues {
952     my ( $borrowernumber, $order, $limit ) = @_;
953
954     return unless $borrowernumber;
955     $order = 'date_due desc' unless $order;
956
957     my $dbh = C4::Context->dbh;
958     my $query =
959 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
960   FROM issues 
961   LEFT JOIN items on items.itemnumber=issues.itemnumber
962   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
963   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
964   WHERE borrowernumber=? 
965   UNION ALL
966   SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp 
967   FROM old_issues 
968   LEFT JOIN items on items.itemnumber=old_issues.itemnumber
969   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
970   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
971   WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
972   order by ' . $order;
973     if ($limit) {
974         $query .= " limit $limit";
975     }
976
977     my $sth = $dbh->prepare($query);
978     $sth->execute( $borrowernumber, $borrowernumber );
979     return $sth->fetchall_arrayref( {} );
980 }
981
982
983 =head2 GetMemberAccountRecords
984
985   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
986
987 Looks up accounting data for the patron with the given borrowernumber.
988
989 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
990 reference-to-array, where each element is a reference-to-hash; the
991 keys are the fields of the C<accountlines> table in the Koha database.
992 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
993 total amount outstanding for all of the account lines.
994
995 =cut
996
997 sub GetMemberAccountRecords {
998     my ($borrowernumber) = @_;
999     my $dbh = C4::Context->dbh;
1000     my @acctlines;
1001     my $numlines = 0;
1002     my $strsth      = qq(
1003                         SELECT * 
1004                         FROM accountlines 
1005                         WHERE borrowernumber=?);
1006     $strsth.=" ORDER BY accountlines_id desc";
1007     my $sth= $dbh->prepare( $strsth );
1008     $sth->execute( $borrowernumber );
1009
1010     my $total = 0;
1011     while ( my $data = $sth->fetchrow_hashref ) {
1012         if ( $data->{itemnumber} ) {
1013             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1014             $data->{biblionumber} = $biblio->{biblionumber};
1015             $data->{title}        = $biblio->{title};
1016         }
1017         $acctlines[$numlines] = $data;
1018         $numlines++;
1019         $total += sprintf "%.0f", 1000*$data->{amountoutstanding}; # convert float to integer to avoid round-off errors
1020     }
1021     $total /= 1000;
1022     return ( $total, \@acctlines,$numlines);
1023 }
1024
1025 =head2 GetMemberAccountBalance
1026
1027   ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1028
1029 Calculates amount immediately owing by the patron - non-issue charges.
1030 Based on GetMemberAccountRecords.
1031 Charges exempt from non-issue are:
1032 * Res (reserves)
1033 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1034 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1035
1036 =cut
1037
1038 sub GetMemberAccountBalance {
1039     my ($borrowernumber) = @_;
1040
1041     my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1042
1043     my @not_fines;
1044     push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1045     push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1046     unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1047         my $dbh = C4::Context->dbh;
1048         my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1049         push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1050     }
1051     my %not_fine = map {$_ => 1} @not_fines;
1052
1053     my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1054     my $other_charges = 0;
1055     foreach (@$acctlines) {
1056         $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1057     }
1058
1059     return ( $total, $total - $other_charges, $other_charges);
1060 }
1061
1062 =head2 GetBorNotifyAcctRecord
1063
1064   ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1065
1066 Looks up accounting data for the patron with the given borrowernumber per file number.
1067
1068 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1069 reference-to-array, where each element is a reference-to-hash; the
1070 keys are the fields of the C<accountlines> table in the Koha database.
1071 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1072 total amount outstanding for all of the account lines.
1073
1074 =cut
1075
1076 sub GetBorNotifyAcctRecord {
1077     my ( $borrowernumber, $notifyid ) = @_;
1078     my $dbh = C4::Context->dbh;
1079     my @acctlines;
1080     my $numlines = 0;
1081     my $sth = $dbh->prepare(
1082             "SELECT * 
1083                 FROM accountlines 
1084                 WHERE borrowernumber=? 
1085                     AND notify_id=? 
1086                     AND amountoutstanding != '0' 
1087                 ORDER BY notify_id,accounttype
1088                 ");
1089
1090     $sth->execute( $borrowernumber, $notifyid );
1091     my $total = 0;
1092     while ( my $data = $sth->fetchrow_hashref ) {
1093         if ( $data->{itemnumber} ) {
1094             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1095             $data->{biblionumber} = $biblio->{biblionumber};
1096             $data->{title}        = $biblio->{title};
1097         }
1098         $acctlines[$numlines] = $data;
1099         $numlines++;
1100         $total += int(100 * $data->{'amountoutstanding'});
1101     }
1102     $total /= 100;
1103     return ( $total, \@acctlines, $numlines );
1104 }
1105
1106 sub checkcardnumber {
1107     my ( $cardnumber, $borrowernumber ) = @_;
1108
1109     # If cardnumber is null, we assume they're allowed.
1110     return 0 unless defined $cardnumber;
1111
1112     my $dbh = C4::Context->dbh;
1113     my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1114     $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1115     my $sth = $dbh->prepare($query);
1116     $sth->execute(
1117         $cardnumber,
1118         ( $borrowernumber ? $borrowernumber : () )
1119     );
1120
1121     return 1 if $sth->fetchrow_hashref;
1122
1123     my ( $min_length, $max_length ) = get_cardnumber_length();
1124     return 2
1125         if length $cardnumber > $max_length
1126         or length $cardnumber < $min_length;
1127
1128     return 0;
1129 }
1130
1131 =head2 get_cardnumber_length
1132
1133     my ($min, $max) = C4::Members::get_cardnumber_length()
1134
1135 Returns the minimum and maximum length for patron cardnumbers as
1136 determined by the CardnumberLength system preference, the
1137 BorrowerMandatoryField system preference, and the width of the
1138 database column.
1139
1140 =cut
1141
1142 sub get_cardnumber_length {
1143     my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1144     $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1145     if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1146         # Is integer and length match
1147         if ( $cardnumber_length =~ m|^\d+$| ) {
1148             $min = $max = $cardnumber_length
1149                 if $cardnumber_length >= $min
1150                     and $cardnumber_length <= $max;
1151         }
1152         # Else assuming it is a range
1153         elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1154             $min = $1 if $1 and $min < $1;
1155             $max = $2 if $2 and $max > $2;
1156         }
1157
1158     }
1159     return ( $min, $max );
1160 }
1161
1162 =head2 GetFirstValidEmailAddress
1163
1164   $email = GetFirstValidEmailAddress($borrowernumber);
1165
1166 Return the first valid email address for a borrower, given the borrowernumber.  For now, the order 
1167 is defined as email, emailpro, B_email.  Returns the empty string if the borrower has no email 
1168 addresses.
1169
1170 =cut
1171
1172 sub GetFirstValidEmailAddress {
1173     my $borrowernumber = shift;
1174     my $dbh = C4::Context->dbh;
1175     my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1176     $sth->execute( $borrowernumber );
1177     my $data = $sth->fetchrow_hashref;
1178
1179     if ($data->{'email'}) {
1180        return $data->{'email'};
1181     } elsif ($data->{'emailpro'}) {
1182        return $data->{'emailpro'};
1183     } elsif ($data->{'B_email'}) {
1184        return $data->{'B_email'};
1185     } else {
1186        return '';
1187     }
1188 }
1189
1190 =head2 GetNoticeEmailAddress
1191
1192   $email = GetNoticeEmailAddress($borrowernumber);
1193
1194 Return the email address of borrower used for notices, given the borrowernumber.
1195 Returns the empty string if no email address.
1196
1197 =cut
1198
1199 sub GetNoticeEmailAddress {
1200     my $borrowernumber = shift;
1201
1202     my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1203     # if syspref is set to 'first valid' (value == OFF), look up email address
1204     if ( $which_address eq 'OFF' ) {
1205         return GetFirstValidEmailAddress($borrowernumber);
1206     }
1207     # specified email address field
1208     my $dbh = C4::Context->dbh;
1209     my $sth = $dbh->prepare( qq{
1210         SELECT $which_address AS primaryemail
1211         FROM borrowers
1212         WHERE borrowernumber=?
1213     } );
1214     $sth->execute($borrowernumber);
1215     my $data = $sth->fetchrow_hashref;
1216     return $data->{'primaryemail'} || '';
1217 }
1218
1219 =head2 GetUpcomingMembershipExpires
1220
1221     my $expires = GetUpcomingMembershipExpires({
1222         branch => $branch, before => $before, after => $after,
1223     });
1224
1225     $branch is an optional branch code.
1226     $before/$after is an optional number of days before/after the date that
1227     is set by the preference MembershipExpiryDaysNotice.
1228     If the pref would be 14, before 2 and after 3, you will get all expires
1229     from 12 to 17 days.
1230
1231 =cut
1232
1233 sub GetUpcomingMembershipExpires {
1234     my ( $params ) = @_;
1235     my $before = $params->{before} || 0;
1236     my $after  = $params->{after} || 0;
1237     my $branch = $params->{branch};
1238
1239     my $dbh = C4::Context->dbh;
1240     my $days = C4::Context->preference("MembershipExpiryDaysNotice") || 0;
1241     my $date1 = dt_from_string->add( days => $days - $before );
1242     my $date2 = dt_from_string->add( days => $days + $after );
1243     $date1= output_pref({ dt => $date1, dateformat => 'iso', dateonly => 1 });
1244     $date2= output_pref({ dt => $date2, dateformat => 'iso', dateonly => 1 });
1245
1246     my $query = q|
1247         SELECT borrowers.*, categories.description,
1248         branches.branchname, branches.branchemail FROM borrowers
1249         LEFT JOIN branches USING (branchcode)
1250         LEFT JOIN categories USING (categorycode)
1251     |;
1252     if( $branch ) {
1253         $query.= 'WHERE branchcode=? AND dateexpiry BETWEEN ? AND ?';
1254     } else {
1255         $query.= 'WHERE dateexpiry BETWEEN ? AND ?';
1256     }
1257
1258     my $sth = $dbh->prepare( $query );
1259     my @pars = $branch? ( $branch ): ();
1260     push @pars, $date1, $date2;
1261     $sth->execute( @pars );
1262     my $results = $sth->fetchall_arrayref( {} );
1263     return $results;
1264 }
1265
1266 =head2 GetBorrowerCategorycode
1267
1268     $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1269
1270 Given the borrowernumber, the function returns the corresponding categorycode
1271
1272 =cut
1273
1274 sub GetBorrowerCategorycode {
1275     my ( $borrowernumber ) = @_;
1276     my $dbh = C4::Context->dbh;
1277     my $sth = $dbh->prepare( qq{
1278         SELECT categorycode
1279         FROM borrowers
1280         WHERE borrowernumber = ?
1281     } );
1282     $sth->execute( $borrowernumber );
1283     return $sth->fetchrow;
1284 }
1285
1286 =head2 GetAge
1287
1288   $dateofbirth,$date = &GetAge($date);
1289
1290 this function return the borrowers age with the value of dateofbirth
1291
1292 =cut
1293
1294 #'
1295 sub GetAge{
1296     my ( $date, $date_ref ) = @_;
1297
1298     if ( not defined $date_ref ) {
1299         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1300     }
1301
1302     my ( $year1, $month1, $day1 ) = split /-/, $date;
1303     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1304
1305     my $age = $year2 - $year1;
1306     if ( $month1 . $day1 > $month2 . $day2 ) {
1307         $age--;
1308     }
1309
1310     return $age;
1311 }    # sub get_age
1312
1313 =head2 SetAge
1314
1315   $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1316   $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1317   $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1318
1319   eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1320   if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1321
1322 This function sets the borrower's dateofbirth to match the given age.
1323 Optionally relative to the given $datetime_reference.
1324
1325 @PARAM1 koha.borrowers-object
1326 @PARAM2 DateTime::Duration-object as the desired age
1327         OR a ISO 8601 Date. (To make the API more pleasant)
1328 @PARAM3 DateTime-object as the relative date, defaults to now().
1329 RETURNS The given borrower reference @PARAM1.
1330 DIES    If there was an error with the ISO Date handling.
1331
1332 =cut
1333
1334 #'
1335 sub SetAge{
1336     my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1337     $datetime_ref = DateTime->now() unless $datetime_ref;
1338
1339     if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1340         if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1341             $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1342         }
1343         else {
1344             die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1345         }
1346     }
1347
1348     my $new_datetime_ref = $datetime_ref->clone();
1349     $new_datetime_ref->subtract_duration( $datetimeduration );
1350
1351     $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1352
1353     return $borrower;
1354 }    # sub SetAge
1355
1356 =head2 GetSortDetails (OUEST-PROVENCE)
1357
1358   ($lib) = &GetSortDetails($category,$sortvalue);
1359
1360 Returns the authorized value  details
1361 C<&$lib>return value of authorized value details
1362 C<&$sortvalue>this is the value of authorized value 
1363 C<&$category>this is the value of authorized value category
1364
1365 =cut
1366
1367 sub GetSortDetails {
1368     my ( $category, $sortvalue ) = @_;
1369     my $dbh   = C4::Context->dbh;
1370     my $query = qq|SELECT lib 
1371         FROM authorised_values 
1372         WHERE category=?
1373         AND authorised_value=? |;
1374     my $sth = $dbh->prepare($query);
1375     $sth->execute( $category, $sortvalue );
1376     my $lib = $sth->fetchrow;
1377     return ($lib) if ($lib);
1378     return ($sortvalue) unless ($lib);
1379 }
1380
1381 =head2 MoveMemberToDeleted
1382
1383   $result = &MoveMemberToDeleted($borrowernumber);
1384
1385 Copy the record from borrowers to deletedborrowers table.
1386 The routine returns 1 for success, undef for failure.
1387
1388 =cut
1389
1390 sub MoveMemberToDeleted {
1391     my ($member) = shift or return;
1392
1393     my $schema       = Koha::Database->new()->schema();
1394     my $borrowers_rs = $schema->resultset('Borrower');
1395     $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1396     my $borrower = $borrowers_rs->find($member);
1397     return unless $borrower;
1398
1399     my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1400
1401     return $deleted ? 1 : undef;
1402 }
1403
1404 =head2 DelMember
1405
1406     DelMember($borrowernumber);
1407
1408 This function remove directly a borrower whitout writing it on deleteborrower.
1409 + Deletes reserves for the borrower
1410
1411 =cut
1412
1413 sub DelMember {
1414     my $dbh            = C4::Context->dbh;
1415     my $borrowernumber = shift;
1416     #warn "in delmember with $borrowernumber";
1417     return unless $borrowernumber;    # borrowernumber is mandatory.
1418     # Delete Patron's holds
1419     my @holds = Koha::Holds->search({ borrowernumber => $borrowernumber });
1420     $_->delete for @holds;
1421
1422     my $query = "
1423        DELETE
1424        FROM borrowers
1425        WHERE borrowernumber = ?
1426    ";
1427     my $sth = $dbh->prepare($query);
1428     $sth->execute($borrowernumber);
1429     logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1430     return $sth->rows;
1431 }
1432
1433 =head2 HandleDelBorrower
1434
1435      HandleDelBorrower($borrower);
1436
1437 When a member is deleted (DelMember in Members.pm), you should call me first.
1438 This routine deletes/moves lists and entries for the deleted member/borrower.
1439 Lists owned by the borrower are deleted, but entries from the borrower to
1440 other lists are kept.
1441
1442 =cut
1443
1444 sub HandleDelBorrower {
1445     my ($borrower)= @_;
1446     my $query;
1447     my $dbh = C4::Context->dbh;
1448
1449     #Delete all lists and all shares of this borrower
1450     #Consistent with the approach Koha uses on deleting individual lists
1451     #Note that entries in virtualshelfcontents added by this borrower to
1452     #lists of others will be handled by a table constraint: the borrower
1453     #is set to NULL in those entries.
1454     $query="DELETE FROM virtualshelves WHERE owner=?";
1455     $dbh->do($query,undef,($borrower));
1456
1457     #NOTE:
1458     #We could handle the above deletes via a constraint too.
1459     #But a new BZ report 11889 has been opened to discuss another approach.
1460     #Instead of deleting we could also disown lists (based on a pref).
1461     #In that way we could save shared and public lists.
1462     #The current table constraints support that idea now.
1463     #This pref should then govern the results of other routines/methods such as
1464     #Koha::Virtualshelf->new->delete too.
1465 }
1466
1467 =head2 GetHideLostItemsPreference
1468
1469   $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1470
1471 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1472 C<&$hidelostitemspref>return value of function, 0 or 1
1473
1474 =cut
1475
1476 sub GetHideLostItemsPreference {
1477     my ($borrowernumber) = @_;
1478     my $dbh = C4::Context->dbh;
1479     my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1480     my $sth = $dbh->prepare($query);
1481     $sth->execute($borrowernumber);
1482     my $hidelostitems = $sth->fetchrow;    
1483     return $hidelostitems;    
1484 }
1485
1486 =head2 GetBorrowersToExpunge
1487
1488   $borrowers = &GetBorrowersToExpunge(
1489       not_borrowed_since => $not_borrowed_since,
1490       expired_before       => $expired_before,
1491       category_code        => $category_code,
1492       patron_list_id       => $patron_list_id,
1493       branchcode           => $branchcode
1494   );
1495
1496   This function get all borrowers based on the given criteria.
1497
1498 =cut
1499
1500 sub GetBorrowersToExpunge {
1501
1502     my $params = shift;
1503     my $filterdate       = $params->{'not_borrowed_since'};
1504     my $filterexpiry     = $params->{'expired_before'};
1505     my $filtercategory   = $params->{'category_code'};
1506     my $filterbranch     = $params->{'branchcode'} ||
1507                         ((C4::Context->preference('IndependentBranches')
1508                              && C4::Context->userenv 
1509                              && !C4::Context->IsSuperLibrarian()
1510                              && C4::Context->userenv->{branch})
1511                          ? C4::Context->userenv->{branch}
1512                          : "");  
1513     my $filterpatronlist = $params->{'patron_list_id'};
1514
1515     my $dbh   = C4::Context->dbh;
1516     my $query = q|
1517         SELECT borrowers.borrowernumber,
1518                MAX(old_issues.timestamp) AS latestissue,
1519                MAX(issues.timestamp) AS currentissue
1520         FROM   borrowers
1521         JOIN   categories USING (categorycode)
1522         LEFT JOIN (
1523             SELECT guarantorid
1524             FROM borrowers
1525             WHERE guarantorid IS NOT NULL
1526                 AND guarantorid <> 0
1527         ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
1528         LEFT JOIN old_issues USING (borrowernumber)
1529         LEFT JOIN issues USING (borrowernumber)|;
1530     if ( $filterpatronlist  ){
1531         $query .= q| LEFT JOIN patron_list_patrons USING (borrowernumber)|;
1532     }
1533     $query .= q| WHERE  category_type <> 'S'
1534         AND tmp.guarantorid IS NULL
1535    |;
1536     my @query_params;
1537     if ( $filterbranch && $filterbranch ne "" ) {
1538         $query.= " AND borrowers.branchcode = ? ";
1539         push( @query_params, $filterbranch );
1540     }
1541     if ( $filterexpiry ) {
1542         $query .= " AND dateexpiry < ? ";
1543         push( @query_params, $filterexpiry );
1544     }
1545     if ( $filtercategory ) {
1546         $query .= " AND categorycode = ? ";
1547         push( @query_params, $filtercategory );
1548     }
1549     if ( $filterpatronlist ){
1550         $query.=" AND patron_list_id = ? ";
1551         push( @query_params, $filterpatronlist );
1552     }
1553     $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
1554     if ( $filterdate ) {
1555         $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
1556         push @query_params,$filterdate;
1557     }
1558     warn $query if $debug;
1559
1560     my $sth = $dbh->prepare($query);
1561     if (scalar(@query_params)>0){  
1562         $sth->execute(@query_params);
1563     }
1564     else {
1565         $sth->execute;
1566     }
1567     
1568     my @results;
1569     while ( my $data = $sth->fetchrow_hashref ) {
1570         push @results, $data;
1571     }
1572     return \@results;
1573 }
1574
1575 =head2 GetBorrowersWhoHaveNeverBorrowed
1576
1577   $results = &GetBorrowersWhoHaveNeverBorrowed
1578
1579 This function get all borrowers who have never borrowed.
1580
1581 I<$result> is a ref to an array which all elements are a hasref.
1582
1583 =cut
1584
1585 sub GetBorrowersWhoHaveNeverBorrowed {
1586     my $filterbranch = shift || 
1587                         ((C4::Context->preference('IndependentBranches')
1588                              && C4::Context->userenv 
1589                              && !C4::Context->IsSuperLibrarian()
1590                              && C4::Context->userenv->{branch})
1591                          ? C4::Context->userenv->{branch}
1592                          : "");  
1593     my $dbh   = C4::Context->dbh;
1594     my $query = "
1595         SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1596         FROM   borrowers
1597           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1598         WHERE issues.borrowernumber IS NULL
1599    ";
1600     my @query_params;
1601     if ($filterbranch && $filterbranch ne ""){ 
1602         $query.=" AND borrowers.branchcode= ?";
1603         push @query_params,$filterbranch;
1604     }
1605     warn $query if $debug;
1606   
1607     my $sth = $dbh->prepare($query);
1608     if (scalar(@query_params)>0){  
1609         $sth->execute(@query_params);
1610     } 
1611     else {
1612         $sth->execute;
1613     }      
1614     
1615     my @results;
1616     while ( my $data = $sth->fetchrow_hashref ) {
1617         push @results, $data;
1618     }
1619     return \@results;
1620 }
1621
1622 =head2 GetBorrowersWithIssuesHistoryOlderThan
1623
1624   $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1625
1626 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1627
1628 I<$result> is a ref to an array which all elements are a hashref.
1629 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1630
1631 =cut
1632
1633 sub GetBorrowersWithIssuesHistoryOlderThan {
1634     my $dbh  = C4::Context->dbh;
1635     my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1636     my $filterbranch = shift || 
1637                         ((C4::Context->preference('IndependentBranches')
1638                              && C4::Context->userenv 
1639                              && !C4::Context->IsSuperLibrarian()
1640                              && C4::Context->userenv->{branch})
1641                          ? C4::Context->userenv->{branch}
1642                          : "");  
1643     my $query = "
1644        SELECT count(borrowernumber) as n,borrowernumber
1645        FROM old_issues
1646        WHERE returndate < ?
1647          AND borrowernumber IS NOT NULL 
1648     "; 
1649     my @query_params;
1650     push @query_params, $date;
1651     if ($filterbranch){
1652         $query.="   AND branchcode = ?";
1653         push @query_params, $filterbranch;
1654     }    
1655     $query.=" GROUP BY borrowernumber ";
1656     warn $query if $debug;
1657     my $sth = $dbh->prepare($query);
1658     $sth->execute(@query_params);
1659     my @results;
1660
1661     while ( my $data = $sth->fetchrow_hashref ) {
1662         push @results, $data;
1663     }
1664     return \@results;
1665 }
1666
1667 =head2 IssueSlip
1668
1669   IssueSlip($branchcode, $borrowernumber, $quickslip)
1670
1671   Returns letter hash ( see C4::Letters::GetPreparedLetter )
1672
1673   $quickslip is boolean, to indicate whether we want a quick slip
1674
1675   IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
1676
1677   Both slips:
1678
1679       <<branches.*>>
1680       <<borrowers.*>>
1681
1682   ISSUESLIP:
1683
1684       <checkedout>
1685          <<biblio.*>>
1686          <<items.*>>
1687          <<biblioitems.*>>
1688          <<issues.*>>
1689       </checkedout>
1690
1691       <overdue>
1692          <<biblio.*>>
1693          <<items.*>>
1694          <<biblioitems.*>>
1695          <<issues.*>>
1696       </overdue>
1697
1698       <news>
1699          <<opac_news.*>>
1700       </news>
1701
1702   ISSUEQSLIP:
1703
1704       <checkedout>
1705          <<biblio.*>>
1706          <<items.*>>
1707          <<biblioitems.*>>
1708          <<issues.*>>
1709       </checkedout>
1710
1711   NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
1712
1713 =cut
1714
1715 sub IssueSlip {
1716     my ($branch, $borrowernumber, $quickslip) = @_;
1717
1718     # FIXME Check callers before removing this statement
1719     #return unless $borrowernumber;
1720
1721     my @issues = @{ GetPendingIssues($borrowernumber) };
1722
1723     for my $issue (@issues) {
1724         $issue->{date_due} = $issue->{date_due_sql};
1725         if ($quickslip) {
1726             my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
1727             if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
1728                 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
1729                   $issue->{now} = 1;
1730             };
1731         }
1732     }
1733
1734     # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
1735     @issues = sort {
1736         my $s = $b->{timestamp} <=> $a->{timestamp};
1737         $s == 0 ?
1738              $b->{issuedate} <=> $a->{issuedate} : $s;
1739     } @issues;
1740
1741     my ($letter_code, %repeat);
1742     if ( $quickslip ) {
1743         $letter_code = 'ISSUEQSLIP';
1744         %repeat =  (
1745             'checkedout' => [ map {
1746                 'biblio'       => $_,
1747                 'items'        => $_,
1748                 'biblioitems'  => $_,
1749                 'issues'       => $_,
1750             }, grep { $_->{'now'} } @issues ],
1751         );
1752     }
1753     else {
1754         $letter_code = 'ISSUESLIP';
1755         %repeat =  (
1756             'checkedout' => [ map {
1757                 'biblio'       => $_,
1758                 'items'        => $_,
1759                 'biblioitems'  => $_,
1760                 'issues'       => $_,
1761             }, grep { !$_->{'overdue'} } @issues ],
1762
1763             'overdue' => [ map {
1764                 'biblio'       => $_,
1765                 'items'        => $_,
1766                 'biblioitems'  => $_,
1767                 'issues'       => $_,
1768             }, grep { $_->{'overdue'} } @issues ],
1769
1770             'news' => [ map {
1771                 $_->{'timestamp'} = $_->{'newdate'};
1772                 { opac_news => $_ }
1773             } @{ GetNewsToDisplay("slip",$branch) } ],
1774         );
1775     }
1776
1777     return  C4::Letters::GetPreparedLetter (
1778         module => 'circulation',
1779         letter_code => $letter_code,
1780         branchcode => $branch,
1781         tables => {
1782             'branches'    => $branch,
1783             'borrowers'   => $borrowernumber,
1784         },
1785         repeat => \%repeat,
1786     );
1787 }
1788
1789 =head2 GetBorrowersWithEmail
1790
1791     ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
1792
1793 This gets a list of users and their basic details from their email address.
1794 As it's possible for multiple user to have the same email address, it provides
1795 you with all of them. If there is no userid for the user, there will be an
1796 C<undef> there. An empty list will be returned if there are no matches.
1797
1798 =cut
1799
1800 sub GetBorrowersWithEmail {
1801     my $email = shift;
1802
1803     my $dbh = C4::Context->dbh;
1804
1805     my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
1806     my $sth=$dbh->prepare($query);
1807     $sth->execute($email);
1808     my @result = ();
1809     while (my $ref = $sth->fetch) {
1810         push @result, $ref;
1811     }
1812     die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
1813     return @result;
1814 }
1815
1816 =head2 AddMember_Opac
1817
1818 =cut
1819
1820 sub AddMember_Opac {
1821     my ( %borrower ) = @_;
1822
1823     $borrower{'categorycode'} //= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
1824     if (not defined $borrower{'password'}){
1825         my $sr = new String::Random;
1826         $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
1827         my $password = $sr->randpattern("AAAAAAAAAA");
1828         $borrower{'password'} = $password;
1829     }
1830
1831     $borrower{'cardnumber'} = fixup_cardnumber( $borrower{'cardnumber'} );
1832
1833     my $borrowernumber = AddMember(%borrower);
1834
1835     return ( $borrowernumber, $borrower{'password'} );
1836 }
1837
1838 =head2 AddEnrolmentFeeIfNeeded
1839
1840     AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1841
1842 Add enrolment fee for a patron if needed.
1843
1844 =cut
1845
1846 sub AddEnrolmentFeeIfNeeded {
1847     my ( $categorycode, $borrowernumber ) = @_;
1848     # check for enrollment fee & add it if needed
1849     my $dbh = C4::Context->dbh;
1850     my $sth = $dbh->prepare(q{
1851         SELECT enrolmentfee
1852         FROM categories
1853         WHERE categorycode=?
1854     });
1855     $sth->execute( $categorycode );
1856     if ( $sth->err ) {
1857         warn sprintf('Database returned the following error: %s', $sth->errstr);
1858         return;
1859     }
1860     my ($enrolmentfee) = $sth->fetchrow;
1861     if ($enrolmentfee && $enrolmentfee > 0) {
1862         # insert fee in patron debts
1863         C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
1864     }
1865 }
1866
1867 =head2 DeleteExpiredOpacRegistrations
1868
1869     Delete accounts that haven't been upgraded from the 'temporary' category
1870     Returns the number of removed patrons
1871
1872 =cut
1873
1874 sub DeleteExpiredOpacRegistrations {
1875
1876     my $delay = C4::Context->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
1877     my $category_code = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
1878
1879     return 0 if not $category_code or not defined $delay or $delay eq q||;
1880
1881     my $query = qq|
1882 SELECT borrowernumber
1883 FROM borrowers
1884 WHERE categorycode = ? AND DATEDIFF( NOW(), dateenrolled ) > ? |;
1885
1886     my $dbh = C4::Context->dbh;
1887     my $sth = $dbh->prepare($query);
1888     $sth->execute( $category_code, $delay );
1889     my $cnt=0;
1890     while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
1891         DelMember($borrowernumber);
1892         $cnt++;
1893     }
1894     return $cnt;
1895 }
1896
1897 =head2 DeleteUnverifiedOpacRegistrations
1898
1899     Delete all unverified self registrations in borrower_modifications,
1900     older than the specified number of days.
1901
1902 =cut
1903
1904 sub DeleteUnverifiedOpacRegistrations {
1905     my ( $days ) = @_;
1906     my $dbh = C4::Context->dbh;
1907     my $sql=qq|
1908 DELETE FROM borrower_modifications
1909 WHERE borrowernumber = 0 AND DATEDIFF( NOW(), timestamp ) > ?|;
1910     my $cnt=$dbh->do($sql, undef, ($days) );
1911     return $cnt eq '0E0'? 0: $cnt;
1912 }
1913
1914 sub GetOverduesForPatron {
1915     my ( $borrowernumber ) = @_;
1916
1917     my $sql = "
1918         SELECT *
1919         FROM issues, items, biblio, biblioitems
1920         WHERE items.itemnumber=issues.itemnumber
1921           AND biblio.biblionumber   = items.biblionumber
1922           AND biblio.biblionumber   = biblioitems.biblionumber
1923           AND issues.borrowernumber = ?
1924           AND date_due < NOW()
1925     ";
1926
1927     my $sth = C4::Context->dbh->prepare( $sql );
1928     $sth->execute( $borrowernumber );
1929
1930     return $sth->fetchall_arrayref({});
1931 }
1932
1933 END { }    # module clean-up code here (global destructor)
1934
1935 1;
1936
1937 __END__
1938
1939 =head1 AUTHOR
1940
1941 Koha Team
1942
1943 =cut