Bug 16908: Koha::Patrons - Remove GetSortDetails
[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         &GetTitles
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 MoveMemberToDeleted
1357
1358   $result = &MoveMemberToDeleted($borrowernumber);
1359
1360 Copy the record from borrowers to deletedborrowers table.
1361 The routine returns 1 for success, undef for failure.
1362
1363 =cut
1364
1365 sub MoveMemberToDeleted {
1366     my ($member) = shift or return;
1367
1368     my $schema       = Koha::Database->new()->schema();
1369     my $borrowers_rs = $schema->resultset('Borrower');
1370     $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1371     my $borrower = $borrowers_rs->find($member);
1372     return unless $borrower;
1373
1374     my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1375
1376     return $deleted ? 1 : undef;
1377 }
1378
1379 =head2 DelMember
1380
1381     DelMember($borrowernumber);
1382
1383 This function remove directly a borrower whitout writing it on deleteborrower.
1384 + Deletes reserves for the borrower
1385
1386 =cut
1387
1388 sub DelMember {
1389     my $dbh            = C4::Context->dbh;
1390     my $borrowernumber = shift;
1391     #warn "in delmember with $borrowernumber";
1392     return unless $borrowernumber;    # borrowernumber is mandatory.
1393     # Delete Patron's holds
1394     my @holds = Koha::Holds->search({ borrowernumber => $borrowernumber });
1395     $_->delete for @holds;
1396
1397     my $query = "
1398        DELETE
1399        FROM borrowers
1400        WHERE borrowernumber = ?
1401    ";
1402     my $sth = $dbh->prepare($query);
1403     $sth->execute($borrowernumber);
1404     logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1405     return $sth->rows;
1406 }
1407
1408 =head2 HandleDelBorrower
1409
1410      HandleDelBorrower($borrower);
1411
1412 When a member is deleted (DelMember in Members.pm), you should call me first.
1413 This routine deletes/moves lists and entries for the deleted member/borrower.
1414 Lists owned by the borrower are deleted, but entries from the borrower to
1415 other lists are kept.
1416
1417 =cut
1418
1419 sub HandleDelBorrower {
1420     my ($borrower)= @_;
1421     my $query;
1422     my $dbh = C4::Context->dbh;
1423
1424     #Delete all lists and all shares of this borrower
1425     #Consistent with the approach Koha uses on deleting individual lists
1426     #Note that entries in virtualshelfcontents added by this borrower to
1427     #lists of others will be handled by a table constraint: the borrower
1428     #is set to NULL in those entries.
1429     $query="DELETE FROM virtualshelves WHERE owner=?";
1430     $dbh->do($query,undef,($borrower));
1431
1432     #NOTE:
1433     #We could handle the above deletes via a constraint too.
1434     #But a new BZ report 11889 has been opened to discuss another approach.
1435     #Instead of deleting we could also disown lists (based on a pref).
1436     #In that way we could save shared and public lists.
1437     #The current table constraints support that idea now.
1438     #This pref should then govern the results of other routines/methods such as
1439     #Koha::Virtualshelf->new->delete too.
1440 }
1441
1442 =head2 GetHideLostItemsPreference
1443
1444   $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1445
1446 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1447 C<&$hidelostitemspref>return value of function, 0 or 1
1448
1449 =cut
1450
1451 sub GetHideLostItemsPreference {
1452     my ($borrowernumber) = @_;
1453     my $dbh = C4::Context->dbh;
1454     my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1455     my $sth = $dbh->prepare($query);
1456     $sth->execute($borrowernumber);
1457     my $hidelostitems = $sth->fetchrow;    
1458     return $hidelostitems;    
1459 }
1460
1461 =head2 GetBorrowersToExpunge
1462
1463   $borrowers = &GetBorrowersToExpunge(
1464       not_borrowed_since => $not_borrowed_since,
1465       expired_before       => $expired_before,
1466       category_code        => $category_code,
1467       patron_list_id       => $patron_list_id,
1468       branchcode           => $branchcode
1469   );
1470
1471   This function get all borrowers based on the given criteria.
1472
1473 =cut
1474
1475 sub GetBorrowersToExpunge {
1476
1477     my $params = shift;
1478     my $filterdate       = $params->{'not_borrowed_since'};
1479     my $filterexpiry     = $params->{'expired_before'};
1480     my $filtercategory   = $params->{'category_code'};
1481     my $filterbranch     = $params->{'branchcode'} ||
1482                         ((C4::Context->preference('IndependentBranches')
1483                              && C4::Context->userenv 
1484                              && !C4::Context->IsSuperLibrarian()
1485                              && C4::Context->userenv->{branch})
1486                          ? C4::Context->userenv->{branch}
1487                          : "");  
1488     my $filterpatronlist = $params->{'patron_list_id'};
1489
1490     my $dbh   = C4::Context->dbh;
1491     my $query = q|
1492         SELECT borrowers.borrowernumber,
1493                MAX(old_issues.timestamp) AS latestissue,
1494                MAX(issues.timestamp) AS currentissue
1495         FROM   borrowers
1496         JOIN   categories USING (categorycode)
1497         LEFT JOIN (
1498             SELECT guarantorid
1499             FROM borrowers
1500             WHERE guarantorid IS NOT NULL
1501                 AND guarantorid <> 0
1502         ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
1503         LEFT JOIN old_issues USING (borrowernumber)
1504         LEFT JOIN issues USING (borrowernumber)|;
1505     if ( $filterpatronlist  ){
1506         $query .= q| LEFT JOIN patron_list_patrons USING (borrowernumber)|;
1507     }
1508     $query .= q| WHERE  category_type <> 'S'
1509         AND tmp.guarantorid IS NULL
1510    |;
1511     my @query_params;
1512     if ( $filterbranch && $filterbranch ne "" ) {
1513         $query.= " AND borrowers.branchcode = ? ";
1514         push( @query_params, $filterbranch );
1515     }
1516     if ( $filterexpiry ) {
1517         $query .= " AND dateexpiry < ? ";
1518         push( @query_params, $filterexpiry );
1519     }
1520     if ( $filtercategory ) {
1521         $query .= " AND categorycode = ? ";
1522         push( @query_params, $filtercategory );
1523     }
1524     if ( $filterpatronlist ){
1525         $query.=" AND patron_list_id = ? ";
1526         push( @query_params, $filterpatronlist );
1527     }
1528     $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
1529     if ( $filterdate ) {
1530         $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
1531         push @query_params,$filterdate;
1532     }
1533     warn $query if $debug;
1534
1535     my $sth = $dbh->prepare($query);
1536     if (scalar(@query_params)>0){  
1537         $sth->execute(@query_params);
1538     }
1539     else {
1540         $sth->execute;
1541     }
1542     
1543     my @results;
1544     while ( my $data = $sth->fetchrow_hashref ) {
1545         push @results, $data;
1546     }
1547     return \@results;
1548 }
1549
1550 =head2 GetBorrowersWhoHaveNeverBorrowed
1551
1552   $results = &GetBorrowersWhoHaveNeverBorrowed
1553
1554 This function get all borrowers who have never borrowed.
1555
1556 I<$result> is a ref to an array which all elements are a hasref.
1557
1558 =cut
1559
1560 sub GetBorrowersWhoHaveNeverBorrowed {
1561     my $filterbranch = shift || 
1562                         ((C4::Context->preference('IndependentBranches')
1563                              && C4::Context->userenv 
1564                              && !C4::Context->IsSuperLibrarian()
1565                              && C4::Context->userenv->{branch})
1566                          ? C4::Context->userenv->{branch}
1567                          : "");  
1568     my $dbh   = C4::Context->dbh;
1569     my $query = "
1570         SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1571         FROM   borrowers
1572           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1573         WHERE issues.borrowernumber IS NULL
1574    ";
1575     my @query_params;
1576     if ($filterbranch && $filterbranch ne ""){ 
1577         $query.=" AND borrowers.branchcode= ?";
1578         push @query_params,$filterbranch;
1579     }
1580     warn $query if $debug;
1581   
1582     my $sth = $dbh->prepare($query);
1583     if (scalar(@query_params)>0){  
1584         $sth->execute(@query_params);
1585     } 
1586     else {
1587         $sth->execute;
1588     }      
1589     
1590     my @results;
1591     while ( my $data = $sth->fetchrow_hashref ) {
1592         push @results, $data;
1593     }
1594     return \@results;
1595 }
1596
1597 =head2 GetBorrowersWithIssuesHistoryOlderThan
1598
1599   $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1600
1601 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1602
1603 I<$result> is a ref to an array which all elements are a hashref.
1604 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1605
1606 =cut
1607
1608 sub GetBorrowersWithIssuesHistoryOlderThan {
1609     my $dbh  = C4::Context->dbh;
1610     my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1611     my $filterbranch = shift || 
1612                         ((C4::Context->preference('IndependentBranches')
1613                              && C4::Context->userenv 
1614                              && !C4::Context->IsSuperLibrarian()
1615                              && C4::Context->userenv->{branch})
1616                          ? C4::Context->userenv->{branch}
1617                          : "");  
1618     my $query = "
1619        SELECT count(borrowernumber) as n,borrowernumber
1620        FROM old_issues
1621        WHERE returndate < ?
1622          AND borrowernumber IS NOT NULL 
1623     "; 
1624     my @query_params;
1625     push @query_params, $date;
1626     if ($filterbranch){
1627         $query.="   AND branchcode = ?";
1628         push @query_params, $filterbranch;
1629     }    
1630     $query.=" GROUP BY borrowernumber ";
1631     warn $query if $debug;
1632     my $sth = $dbh->prepare($query);
1633     $sth->execute(@query_params);
1634     my @results;
1635
1636     while ( my $data = $sth->fetchrow_hashref ) {
1637         push @results, $data;
1638     }
1639     return \@results;
1640 }
1641
1642 =head2 IssueSlip
1643
1644   IssueSlip($branchcode, $borrowernumber, $quickslip)
1645
1646   Returns letter hash ( see C4::Letters::GetPreparedLetter )
1647
1648   $quickslip is boolean, to indicate whether we want a quick slip
1649
1650   IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
1651
1652   Both slips:
1653
1654       <<branches.*>>
1655       <<borrowers.*>>
1656
1657   ISSUESLIP:
1658
1659       <checkedout>
1660          <<biblio.*>>
1661          <<items.*>>
1662          <<biblioitems.*>>
1663          <<issues.*>>
1664       </checkedout>
1665
1666       <overdue>
1667          <<biblio.*>>
1668          <<items.*>>
1669          <<biblioitems.*>>
1670          <<issues.*>>
1671       </overdue>
1672
1673       <news>
1674          <<opac_news.*>>
1675       </news>
1676
1677   ISSUEQSLIP:
1678
1679       <checkedout>
1680          <<biblio.*>>
1681          <<items.*>>
1682          <<biblioitems.*>>
1683          <<issues.*>>
1684       </checkedout>
1685
1686   NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
1687
1688 =cut
1689
1690 sub IssueSlip {
1691     my ($branch, $borrowernumber, $quickslip) = @_;
1692
1693     # FIXME Check callers before removing this statement
1694     #return unless $borrowernumber;
1695
1696     my @issues = @{ GetPendingIssues($borrowernumber) };
1697
1698     for my $issue (@issues) {
1699         $issue->{date_due} = $issue->{date_due_sql};
1700         if ($quickslip) {
1701             my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
1702             if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
1703                 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
1704                   $issue->{now} = 1;
1705             };
1706         }
1707     }
1708
1709     # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
1710     @issues = sort {
1711         my $s = $b->{timestamp} <=> $a->{timestamp};
1712         $s == 0 ?
1713              $b->{issuedate} <=> $a->{issuedate} : $s;
1714     } @issues;
1715
1716     my ($letter_code, %repeat);
1717     if ( $quickslip ) {
1718         $letter_code = 'ISSUEQSLIP';
1719         %repeat =  (
1720             'checkedout' => [ map {
1721                 'biblio'       => $_,
1722                 'items'        => $_,
1723                 'biblioitems'  => $_,
1724                 'issues'       => $_,
1725             }, grep { $_->{'now'} } @issues ],
1726         );
1727     }
1728     else {
1729         $letter_code = 'ISSUESLIP';
1730         %repeat =  (
1731             'checkedout' => [ map {
1732                 'biblio'       => $_,
1733                 'items'        => $_,
1734                 'biblioitems'  => $_,
1735                 'issues'       => $_,
1736             }, grep { !$_->{'overdue'} } @issues ],
1737
1738             'overdue' => [ map {
1739                 'biblio'       => $_,
1740                 'items'        => $_,
1741                 'biblioitems'  => $_,
1742                 'issues'       => $_,
1743             }, grep { $_->{'overdue'} } @issues ],
1744
1745             'news' => [ map {
1746                 $_->{'timestamp'} = $_->{'newdate'};
1747                 { opac_news => $_ }
1748             } @{ GetNewsToDisplay("slip",$branch) } ],
1749         );
1750     }
1751
1752     return  C4::Letters::GetPreparedLetter (
1753         module => 'circulation',
1754         letter_code => $letter_code,
1755         branchcode => $branch,
1756         tables => {
1757             'branches'    => $branch,
1758             'borrowers'   => $borrowernumber,
1759         },
1760         repeat => \%repeat,
1761     );
1762 }
1763
1764 =head2 GetBorrowersWithEmail
1765
1766     ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
1767
1768 This gets a list of users and their basic details from their email address.
1769 As it's possible for multiple user to have the same email address, it provides
1770 you with all of them. If there is no userid for the user, there will be an
1771 C<undef> there. An empty list will be returned if there are no matches.
1772
1773 =cut
1774
1775 sub GetBorrowersWithEmail {
1776     my $email = shift;
1777
1778     my $dbh = C4::Context->dbh;
1779
1780     my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
1781     my $sth=$dbh->prepare($query);
1782     $sth->execute($email);
1783     my @result = ();
1784     while (my $ref = $sth->fetch) {
1785         push @result, $ref;
1786     }
1787     die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
1788     return @result;
1789 }
1790
1791 =head2 AddMember_Opac
1792
1793 =cut
1794
1795 sub AddMember_Opac {
1796     my ( %borrower ) = @_;
1797
1798     $borrower{'categorycode'} //= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
1799     if (not defined $borrower{'password'}){
1800         my $sr = new String::Random;
1801         $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
1802         my $password = $sr->randpattern("AAAAAAAAAA");
1803         $borrower{'password'} = $password;
1804     }
1805
1806     $borrower{'cardnumber'} = fixup_cardnumber( $borrower{'cardnumber'} );
1807
1808     my $borrowernumber = AddMember(%borrower);
1809
1810     return ( $borrowernumber, $borrower{'password'} );
1811 }
1812
1813 =head2 AddEnrolmentFeeIfNeeded
1814
1815     AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1816
1817 Add enrolment fee for a patron if needed.
1818
1819 =cut
1820
1821 sub AddEnrolmentFeeIfNeeded {
1822     my ( $categorycode, $borrowernumber ) = @_;
1823     # check for enrollment fee & add it if needed
1824     my $dbh = C4::Context->dbh;
1825     my $sth = $dbh->prepare(q{
1826         SELECT enrolmentfee
1827         FROM categories
1828         WHERE categorycode=?
1829     });
1830     $sth->execute( $categorycode );
1831     if ( $sth->err ) {
1832         warn sprintf('Database returned the following error: %s', $sth->errstr);
1833         return;
1834     }
1835     my ($enrolmentfee) = $sth->fetchrow;
1836     if ($enrolmentfee && $enrolmentfee > 0) {
1837         # insert fee in patron debts
1838         C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
1839     }
1840 }
1841
1842 =head2 DeleteExpiredOpacRegistrations
1843
1844     Delete accounts that haven't been upgraded from the 'temporary' category
1845     Returns the number of removed patrons
1846
1847 =cut
1848
1849 sub DeleteExpiredOpacRegistrations {
1850
1851     my $delay = C4::Context->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
1852     my $category_code = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
1853
1854     return 0 if not $category_code or not defined $delay or $delay eq q||;
1855
1856     my $query = qq|
1857 SELECT borrowernumber
1858 FROM borrowers
1859 WHERE categorycode = ? AND DATEDIFF( NOW(), dateenrolled ) > ? |;
1860
1861     my $dbh = C4::Context->dbh;
1862     my $sth = $dbh->prepare($query);
1863     $sth->execute( $category_code, $delay );
1864     my $cnt=0;
1865     while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
1866         DelMember($borrowernumber);
1867         $cnt++;
1868     }
1869     return $cnt;
1870 }
1871
1872 =head2 DeleteUnverifiedOpacRegistrations
1873
1874     Delete all unverified self registrations in borrower_modifications,
1875     older than the specified number of days.
1876
1877 =cut
1878
1879 sub DeleteUnverifiedOpacRegistrations {
1880     my ( $days ) = @_;
1881     my $dbh = C4::Context->dbh;
1882     my $sql=qq|
1883 DELETE FROM borrower_modifications
1884 WHERE borrowernumber = 0 AND DATEDIFF( NOW(), timestamp ) > ?|;
1885     my $cnt=$dbh->do($sql, undef, ($days) );
1886     return $cnt eq '0E0'? 0: $cnt;
1887 }
1888
1889 sub GetOverduesForPatron {
1890     my ( $borrowernumber ) = @_;
1891
1892     my $sql = "
1893         SELECT *
1894         FROM issues, items, biblio, biblioitems
1895         WHERE items.itemnumber=issues.itemnumber
1896           AND biblio.biblionumber   = items.biblionumber
1897           AND biblio.biblionumber   = biblioitems.biblionumber
1898           AND issues.borrowernumber = ?
1899           AND date_due < NOW()
1900     ";
1901
1902     my $sth = C4::Context->dbh->prepare( $sql );
1903     $sth->execute( $borrowernumber );
1904
1905     return $sth->fetchall_arrayref({});
1906 }
1907
1908 END { }    # module clean-up code here (global destructor)
1909
1910 1;
1911
1912 __END__
1913
1914 =head1 AUTHOR
1915
1916 Koha Team
1917
1918 =cut