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