Bug 10021: Drop columns notify_id and notify_level from accountlines
[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 use Koha::Schema;
48
49 our (@ISA,@EXPORT,@EXPORT_OK,$debug);
50
51 use Module::Load::Conditional qw( can_load );
52 if ( ! can_load( modules => { 'Koha::NorwegianPatronDB' => undef } ) ) {
53    $debug && warn "Unable to load Koha::NorwegianPatronDB";
54 }
55
56
57 BEGIN {
58     $debug = $ENV{DEBUG} || 0;
59     require Exporter;
60     @ISA = qw(Exporter);
61     #Get data
62     push @EXPORT, qw(
63
64         &GetPendingIssues
65         &GetAllIssues
66
67         &GetFirstValidEmailAddress
68         &GetNoticeEmailAddress
69
70         &GetMemberAccountRecords
71
72         &GetBorrowersToExpunge
73
74         &IssueSlip
75
76         GetOverduesForPatron
77     );
78
79     #Modify data
80     push @EXPORT, qw(
81         &ModMember
82         &changepassword
83     );
84
85     #Insert data
86     push @EXPORT, qw(
87         &AddMember
88     &AddMember_Auto
89         &AddMember_Opac
90     );
91
92     #Check data
93     push @EXPORT, qw(
94         &checkuniquemember
95         &checkuserpassword
96         &Check_Userid
97         &Generate_Userid
98         &fixup_cardnumber
99         &checkcardnumber
100     );
101 }
102
103 =head1 NAME
104
105 C4::Members - Perl Module containing convenience functions for member handling
106
107 =head1 SYNOPSIS
108
109 use C4::Members;
110
111 =head1 DESCRIPTION
112
113 This module contains routines for adding, modifying and deleting members/patrons/borrowers 
114
115 =head1 FUNCTIONS
116
117 =head2 patronflags
118
119  $flags = &patronflags($patron);
120
121 This function is not exported.
122
123 The following will be set where applicable:
124  $flags->{CHARGES}->{amount}        Amount of debt
125  $flags->{CHARGES}->{noissues}      Set if debt amount >$5.00 (or syspref noissuescharge)
126  $flags->{CHARGES}->{message}       Message -- deprecated
127
128  $flags->{CREDITS}->{amount}        Amount of credit
129  $flags->{CREDITS}->{message}       Message -- deprecated
130
131  $flags->{  GNA  }                  Patron has no valid address
132  $flags->{  GNA  }->{noissues}      Set for each GNA
133  $flags->{  GNA  }->{message}       "Borrower has no valid address" -- deprecated
134
135  $flags->{ LOST  }                  Patron's card reported lost
136  $flags->{ LOST  }->{noissues}      Set for each LOST
137  $flags->{ LOST  }->{message}       Message -- deprecated
138
139  $flags->{DBARRED}                  Set if patron debarred, no access
140  $flags->{DBARRED}->{noissues}      Set for each DBARRED
141  $flags->{DBARRED}->{message}       Message -- deprecated
142
143  $flags->{ NOTES }
144  $flags->{ NOTES }->{message}       The note itself.  NOT deprecated
145
146  $flags->{ ODUES }                  Set if patron has overdue books.
147  $flags->{ ODUES }->{message}       "Yes"  -- deprecated
148  $flags->{ ODUES }->{itemlist}      ref-to-array: list of overdue books
149  $flags->{ ODUES }->{itemlisttext}  Text list of overdue items -- deprecated
150
151  $flags->{WAITING}                  Set if any of patron's reserves are available
152  $flags->{WAITING}->{message}       Message -- deprecated
153  $flags->{WAITING}->{itemlist}      ref-to-array: list of available items
154
155 =over 
156
157 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
158 overdue items. Its elements are references-to-hash, each describing an
159 overdue item. The keys are selected fields from the issues, biblio,
160 biblioitems, and items tables of the Koha database.
161
162 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
163 the overdue items, one per line.  Deprecated.
164
165 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
166 available items. Each element is a reference-to-hash whose keys are
167 fields from the reserves table of the Koha database.
168
169 =back
170
171 All the "message" fields that include language generated in this function are deprecated, 
172 because such strings belong properly in the display layer.
173
174 The "message" field that comes from the DB is OK.
175
176 =cut
177
178 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
179 # FIXME rename this function.
180 sub patronflags {
181     my %flags;
182     my ( $patroninformation) = @_;
183     my $dbh=C4::Context->dbh;
184     my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
185     if ( $owing > 0 ) {
186         my %flaginfo;
187         my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
188         $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
189         $flaginfo{'amount'}  = sprintf "%.02f", $owing;
190         if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
191             $flaginfo{'noissues'} = 1;
192         }
193         $flags{'CHARGES'} = \%flaginfo;
194     }
195     elsif ( $balance < 0 ) {
196         my %flaginfo;
197         $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
198         $flaginfo{'amount'}  = sprintf "%.02f", $balance;
199         $flags{'CREDITS'} = \%flaginfo;
200     }
201
202     # Check the debt of the guarntees of this patron
203     my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
204     $no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
205     if ( defined $no_issues_charge_guarantees ) {
206         my $p = Koha::Patrons->find( $patroninformation->{borrowernumber} );
207         my @guarantees = $p->guarantees();
208         my $guarantees_non_issues_charges;
209         foreach my $g ( @guarantees ) {
210             my ( $b, $n, $o ) = C4::Members::GetMemberAccountBalance( $g->id );
211             $guarantees_non_issues_charges += $n;
212         }
213
214         if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
215             my %flaginfo;
216             $flaginfo{'message'} = sprintf 'patron guarantees owe %.02f', $guarantees_non_issues_charges;
217             $flaginfo{'amount'}  = $guarantees_non_issues_charges;
218             $flaginfo{'noissues'} = 1 unless C4::Context->preference("allowfineoverride");
219             $flags{'CHARGES_GUARANTEES'} = \%flaginfo;
220         }
221     }
222
223     if (   $patroninformation->{'gonenoaddress'}
224         && $patroninformation->{'gonenoaddress'} == 1 )
225     {
226         my %flaginfo;
227         $flaginfo{'message'}  = 'Borrower has no valid address.';
228         $flaginfo{'noissues'} = 1;
229         $flags{'GNA'}         = \%flaginfo;
230     }
231     if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
232         my %flaginfo;
233         $flaginfo{'message'}  = 'Borrower\'s card reported lost.';
234         $flaginfo{'noissues'} = 1;
235         $flags{'LOST'}        = \%flaginfo;
236     }
237     if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
238         if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
239             my %flaginfo;
240             $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
241             $flaginfo{'message'}         = $patroninformation->{'debarredcomment'};
242             $flaginfo{'noissues'}        = 1;
243             $flaginfo{'dateend'}         = $patroninformation->{'debarred'};
244             $flags{'DBARRED'}           = \%flaginfo;
245         }
246     }
247     if (   $patroninformation->{'borrowernotes'}
248         && $patroninformation->{'borrowernotes'} )
249     {
250         my %flaginfo;
251         $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
252         $flags{'NOTES'}      = \%flaginfo;
253     }
254     my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
255     if ( $odues && $odues > 0 ) {
256         my %flaginfo;
257         $flaginfo{'message'}  = "Yes";
258         $flaginfo{'itemlist'} = $itemsoverdue;
259         foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
260             @$itemsoverdue )
261         {
262             $flaginfo{'itemlisttext'} .=
263               "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";  # newline is display layer
264         }
265         $flags{'ODUES'} = \%flaginfo;
266     }
267
268     my $patron = Koha::Patrons->find( $patroninformation->{borrowernumber} );
269     my $waiting_holds = $patron->holds->search({ found => 'W' });
270     my $nowaiting = $waiting_holds->count;
271     if ( $nowaiting > 0 ) {
272         my %flaginfo;
273         $flaginfo{'message'}  = "Reserved items available";
274         $flaginfo{'itemlist'} = $waiting_holds->unblessed;
275         $flags{'WAITING'}     = \%flaginfo;
276     }
277     return ( \%flags );
278 }
279
280
281 =head2 ModMember
282
283   my $success = ModMember(borrowernumber => $borrowernumber,
284                                             [ field => value ]... );
285
286 Modify borrower's data.  All date fields should ALREADY be in ISO format.
287
288 return :
289 true on success, or false on failure
290
291 =cut
292
293 sub ModMember {
294     my (%data) = @_;
295
296     # trim whitespace from data which has some non-whitespace in it.
297     foreach my $field_name (keys(%data)) {
298         if ( defined $data{$field_name} && $data{$field_name} =~ /\S/ ) {
299             $data{$field_name} =~ s/^\s*|\s*$//g;
300         }
301     }
302
303     # test to know if you must update or not the borrower password
304     if (exists $data{password}) {
305         if ($data{password} eq '****' or $data{password} eq '') {
306             delete $data{password};
307         } else {
308             if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
309                 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
310                 Koha::NorwegianPatronDB::NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
311             }
312             $data{password} = hash_password($data{password});
313         }
314     }
315
316     my $old_categorycode = Koha::Patrons->find( $data{borrowernumber} )->categorycode;
317
318     # get only the columns of a borrower
319     my $schema = Koha::Database->new()->schema;
320     my @columns = $schema->source('Borrower')->columns;
321     my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
322
323     $new_borrower->{dateofbirth}     ||= undef if exists $new_borrower->{dateofbirth};
324     $new_borrower->{dateenrolled}    ||= undef if exists $new_borrower->{dateenrolled};
325     $new_borrower->{dateexpiry}      ||= undef if exists $new_borrower->{dateexpiry};
326     $new_borrower->{debarred}        ||= undef if exists $new_borrower->{debarred};
327     $new_borrower->{sms_provider_id} ||= undef if exists $new_borrower->{sms_provider_id};
328     $new_borrower->{guarantorid}     ||= undef if exists $new_borrower->{guarantorid};
329
330     my $patron = Koha::Patrons->find( $new_borrower->{borrowernumber} );
331
332     delete $new_borrower->{userid} if exists $new_borrower->{userid} and not $new_borrower->{userid};
333
334     my $execute_success = $patron->store if $patron->set($new_borrower);
335
336     if ($execute_success) { # only proceed if the update was a success
337         # If the patron changes to a category with enrollment fee, we add a fee
338         if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
339             if ( C4::Context->preference('FeeOnChangePatronCategory') ) {
340                 $patron->add_enrolment_fee_if_needed;
341             }
342         }
343
344         # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
345         # cronjob will use for syncing with NL
346         if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
347             my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
348                 'synctype'       => 'norwegianpatrondb',
349                 'borrowernumber' => $data{'borrowernumber'}
350             });
351             # Do not set to "edited" if syncstatus is "new". We need to sync as new before
352             # we can sync as changed. And the "new sync" will pick up all changes since
353             # the patron was created anyway.
354             if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
355                 $borrowersync->update( { 'syncstatus' => 'edited' } );
356             }
357             # Set the value of 'sync'
358             $borrowersync->update( { 'sync' => $data{'sync'} } );
359             # Try to do the live sync
360             Koha::NorwegianPatronDB::NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
361         }
362
363         logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
364     }
365     return $execute_success;
366 }
367
368 =head2 AddMember
369
370   $borrowernumber = &AddMember(%borrower);
371
372 insert new borrower into table
373
374 (%borrower keys are database columns. Database columns could be
375 different in different versions. Please look into database for correct
376 column names.)
377
378 Returns the borrowernumber upon success
379
380 Returns as undef upon any db error without further processing
381
382 =cut
383
384 #'
385 sub AddMember {
386     my (%data) = @_;
387     my $dbh = C4::Context->dbh;
388     my $schema = Koha::Database->new()->schema;
389
390     # trim whitespace from data which has some non-whitespace in it.
391     foreach my $field_name (keys(%data)) {
392         if ( defined $data{$field_name} && $data{$field_name} =~ /\S/ ) {
393             $data{$field_name} =~ s/^\s*|\s*$//g;
394         }
395     }
396
397     # generate a proper login if none provided
398     $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
399       if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
400
401     # add expiration date if it isn't already there
402     $data{dateexpiry} ||= Koha::Patron::Categories->find( $data{categorycode} )->get_expiry_date;
403
404     # add enrollment date if it isn't already there
405     unless ( $data{'dateenrolled'} ) {
406         $data{'dateenrolled'} = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
407     }
408
409     if ( C4::Context->preference("autoMemberNum") ) {
410         if ( not exists $data{cardnumber} or not defined $data{cardnumber} or $data{cardnumber} eq '' ) {
411             $data{cardnumber} = fixup_cardnumber( $data{cardnumber} );
412         }
413     }
414
415     my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
416     $data{'privacy'} =
417         $patron_category->default_privacy() eq 'default' ? 1
418       : $patron_category->default_privacy() eq 'never'   ? 2
419       : $patron_category->default_privacy() eq 'forever' ? 0
420       :                                                    undef;
421
422     $data{'privacy_guarantor_checkouts'} = 0 unless defined( $data{'privacy_guarantor_checkouts'} );
423
424     # Make a copy of the plain text password for later use
425     my $plain_text_password = $data{'password'};
426
427     # create a disabled account if no password provided
428     $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
429
430     # we don't want invalid dates in the db (mysql has a bad habit of inserting 0000-00-00
431     $data{'dateofbirth'}     = undef if ( not $data{'dateofbirth'} );
432     $data{'debarred'}        = undef if ( not $data{'debarred'} );
433     $data{'sms_provider_id'} = undef if ( not $data{'sms_provider_id'} );
434     $data{'guarantorid'}     = undef if ( not $data{'guarantorid'} );
435
436     # get only the columns of Borrower
437     # FIXME Do we really need this check?
438     my @columns = $schema->source('Borrower')->columns;
439     my $new_member = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $data{$_} )  : () } keys(%data) } ;
440
441     delete $new_member->{borrowernumber};
442
443     my $patron = Koha::Patron->new( $new_member )->store;
444     $data{borrowernumber} = $patron->borrowernumber;
445
446     # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
447     # cronjob will use for syncing with NL
448     if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
449         Koha::Database->new->schema->resultset('BorrowerSync')->create({
450             'borrowernumber' => $data{'borrowernumber'},
451             'synctype'       => 'norwegianpatrondb',
452             'sync'           => 1,
453             'syncstatus'     => 'new',
454             'hashed_pin'     => Koha::NorwegianPatronDB::NLEncryptPIN( $plain_text_password ),
455         });
456     }
457
458     logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
459
460     $patron->add_enrolment_fee_if_needed;
461
462     return $data{borrowernumber};
463 }
464
465 =head2 Check_Userid
466
467     my $uniqueness = Check_Userid($userid,$borrowernumber);
468
469     $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 != '').
470
471     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.
472
473     return :
474         0 for not unique (i.e. this $userid already exists)
475         1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
476
477 =cut
478
479 sub Check_Userid {
480     my ( $uid, $borrowernumber ) = @_;
481
482     return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
483
484     return 0 if ( $uid eq C4::Context->config('user') );
485
486     my $rs = Koha::Database->new()->schema()->resultset('Borrower');
487
488     my $params;
489     $params->{userid} = $uid;
490     $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
491
492     my $count = $rs->count( $params );
493
494     return $count ? 0 : 1;
495 }
496
497 =head2 Generate_Userid
498
499     my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
500
501     Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
502
503     $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.
504
505     return :
506         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).
507
508 =cut
509
510 sub Generate_Userid {
511   my ($borrowernumber, $firstname, $surname) = @_;
512   my $newuid;
513   my $offset = 0;
514   #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
515   do {
516     $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
517     $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
518     $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
519     $newuid = unac_string('utf-8',$newuid);
520     $newuid .= $offset unless $offset == 0;
521     $offset++;
522
523    } while (!Check_Userid($newuid,$borrowernumber));
524
525    return $newuid;
526 }
527
528 =head2 fixup_cardnumber
529
530 Warning: The caller is responsible for locking the members table in write
531 mode, to avoid database corruption.
532
533 =cut
534
535 use vars qw( @weightings );
536 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
537
538 sub fixup_cardnumber {
539     my ($cardnumber) = @_;
540     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
541
542     # Find out whether member numbers should be generated
543     # automatically. Should be either "1" or something else.
544     # Defaults to "0", which is interpreted as "no".
545
546     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
547     ($autonumber_members) or return $cardnumber;
548     my $checkdigit = C4::Context->preference('checkdigit');
549     my $dbh = C4::Context->dbh;
550     if ( $checkdigit and $checkdigit eq 'katipo' ) {
551
552         # if checkdigit is selected, calculate katipo-style cardnumber.
553         # otherwise, just use the max()
554         # purpose: generate checksum'd member numbers.
555         # We'll assume we just got the max value of digits 2-8 of member #'s
556         # from the database and our job is to increment that by one,
557         # determine the 1st and 9th digits and return the full string.
558         my $sth = $dbh->prepare(
559             "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
560         );
561         $sth->execute;
562         my $data = $sth->fetchrow_hashref;
563         $cardnumber = $data->{new_num};
564         if ( !$cardnumber ) {    # If DB has no values,
565             $cardnumber = 1000000;    # start at 1000000
566         } else {
567             $cardnumber += 1;
568         }
569
570         my $sum = 0;
571         for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
572             # read weightings, left to right, 1 char at a time
573             my $temp1 = $weightings[$i];
574
575             # sequence left to right, 1 char at a time
576             my $temp2 = substr( $cardnumber, $i, 1 );
577
578             # mult each char 1-7 by its corresponding weighting
579             $sum += $temp1 * $temp2;
580         }
581
582         my $rem = ( $sum % 11 );
583         $rem = 'X' if $rem == 10;
584
585         return "V$cardnumber$rem";
586      } else {
587
588         my $sth = $dbh->prepare(
589             'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
590         );
591         $sth->execute;
592         my ($result) = $sth->fetchrow;
593         return $result + 1;
594     }
595     return $cardnumber;     # just here as a fallback/reminder 
596 }
597
598 =head2 GetPendingIssues
599
600   my $issues = &GetPendingIssues(@borrowernumber);
601
602 Looks up what the patron with the given borrowernumber has borrowed.
603
604 C<&GetPendingIssues> returns a
605 reference-to-array where each element is a reference-to-hash; the
606 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
607 The keys include C<biblioitems> fields.
608
609 =cut
610
611 sub GetPendingIssues {
612     my @borrowernumbers = @_;
613
614     unless (@borrowernumbers ) { # return a ref_to_array
615         return \@borrowernumbers; # to not cause surprise to caller
616     }
617
618     # Borrowers part of the query
619     my $bquery = '';
620     for (my $i = 0; $i < @borrowernumbers; $i++) {
621         $bquery .= ' issues.borrowernumber = ?';
622         if ($i < $#borrowernumbers ) {
623             $bquery .= ' OR';
624         }
625     }
626
627     # FIXME: namespace collision: each table has "timestamp" fields.  Which one is "timestamp" ?
628     # FIXME: circ/ciculation.pl tries to sort by timestamp!
629     # FIXME: namespace collision: other collisions possible.
630     # FIXME: most of this data isn't really being used by callers.
631     my $query =
632    "SELECT issues.*,
633             items.*,
634            biblio.*,
635            biblioitems.volume,
636            biblioitems.number,
637            biblioitems.itemtype,
638            biblioitems.isbn,
639            biblioitems.issn,
640            biblioitems.publicationyear,
641            biblioitems.publishercode,
642            biblioitems.volumedate,
643            biblioitems.volumedesc,
644            biblioitems.lccn,
645            biblioitems.url,
646            borrowers.firstname,
647            borrowers.surname,
648            borrowers.cardnumber,
649            issues.timestamp AS timestamp,
650            issues.renewals  AS renewals,
651            issues.borrowernumber AS borrowernumber,
652             items.renewals  AS totalrenewals
653     FROM   issues
654     LEFT JOIN items       ON items.itemnumber       =      issues.itemnumber
655     LEFT JOIN biblio      ON items.biblionumber     =      biblio.biblionumber
656     LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
657     LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
658     WHERE
659       $bquery
660     ORDER BY issues.issuedate"
661     ;
662
663     my $sth = C4::Context->dbh->prepare($query);
664     $sth->execute(@borrowernumbers);
665     my $data = $sth->fetchall_arrayref({});
666     my $today = dt_from_string;
667     foreach (@{$data}) {
668         if ($_->{issuedate}) {
669             $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
670         }
671         $_->{date_due_sql} = $_->{date_due};
672         # FIXME no need to have this value
673         $_->{date_due} or next;
674         $_->{date_due_sql} = $_->{date_due};
675         # FIXME no need to have this value
676         $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
677         if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
678             $_->{overdue} = 1;
679         }
680     }
681     return $data;
682 }
683
684 =head2 GetAllIssues
685
686   $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
687
688 Looks up what the patron with the given borrowernumber has borrowed,
689 and sorts the results.
690
691 C<$sortkey> is the name of a field on which to sort the results. This
692 should be the name of a field in the C<issues>, C<biblio>,
693 C<biblioitems>, or C<items> table in the Koha database.
694
695 C<$limit> is the maximum number of results to return.
696
697 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
698 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
699 C<items> tables of the Koha database.
700
701 =cut
702
703 #'
704 sub GetAllIssues {
705     my ( $borrowernumber, $order, $limit ) = @_;
706
707     return unless $borrowernumber;
708     $order = 'date_due desc' unless $order;
709
710     my $dbh = C4::Context->dbh;
711     my $query =
712 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
713   FROM issues 
714   LEFT JOIN items on items.itemnumber=issues.itemnumber
715   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
716   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
717   WHERE borrowernumber=? 
718   UNION ALL
719   SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp 
720   FROM old_issues 
721   LEFT JOIN items on items.itemnumber=old_issues.itemnumber
722   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
723   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
724   WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
725   order by ' . $order;
726     if ($limit) {
727         $query .= " limit $limit";
728     }
729
730     my $sth = $dbh->prepare($query);
731     $sth->execute( $borrowernumber, $borrowernumber );
732     return $sth->fetchall_arrayref( {} );
733 }
734
735
736 =head2 GetMemberAccountRecords
737
738   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
739
740 Looks up accounting data for the patron with the given borrowernumber.
741
742 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
743 reference-to-array, where each element is a reference-to-hash; the
744 keys are the fields of the C<accountlines> table in the Koha database.
745 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
746 total amount outstanding for all of the account lines.
747
748 =cut
749
750 sub GetMemberAccountRecords {
751     my ($borrowernumber) = @_;
752     my $dbh = C4::Context->dbh;
753     my @acctlines;
754     my $numlines = 0;
755     my $strsth      = qq(
756                         SELECT * 
757                         FROM accountlines 
758                         WHERE borrowernumber=?);
759     $strsth.=" ORDER BY accountlines_id desc";
760     my $sth= $dbh->prepare( $strsth );
761     $sth->execute( $borrowernumber );
762
763     my $total = 0;
764     while ( my $data = $sth->fetchrow_hashref ) {
765         if ( $data->{itemnumber} ) {
766             my $item = Koha::Items->find( $data->{itemnumber} );
767             my $biblio = $item->biblio;
768             $data->{biblionumber} = $biblio->biblionumber;
769             $data->{title}        = $biblio->title;
770         }
771         $acctlines[$numlines] = $data;
772         $numlines++;
773         $total += sprintf "%.0f", 1000*$data->{amountoutstanding}; # convert float to integer to avoid round-off errors
774     }
775     $total /= 1000;
776     return ( $total, \@acctlines,$numlines);
777 }
778
779 =head2 GetMemberAccountBalance
780
781   ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
782
783 Calculates amount immediately owing by the patron - non-issue charges.
784 Based on GetMemberAccountRecords.
785 Charges exempt from non-issue are:
786 * Res (reserves)
787 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
788 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
789
790 =cut
791
792 sub GetMemberAccountBalance {
793     my ($borrowernumber) = @_;
794
795     my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
796
797     my @not_fines;
798     push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
799     push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
800     unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
801         my $dbh = C4::Context->dbh;
802         my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
803         push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
804     }
805     my %not_fine = map {$_ => 1} @not_fines;
806
807     my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
808     my $other_charges = 0;
809     foreach (@$acctlines) {
810         $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
811     }
812
813     return ( $total, $total - $other_charges, $other_charges);
814 }
815
816 sub checkcardnumber {
817     my ( $cardnumber, $borrowernumber ) = @_;
818
819     # If cardnumber is null, we assume they're allowed.
820     return 0 unless defined $cardnumber;
821
822     my $dbh = C4::Context->dbh;
823     my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
824     $query .= " AND borrowernumber <> ?" if ($borrowernumber);
825     my $sth = $dbh->prepare($query);
826     $sth->execute(
827         $cardnumber,
828         ( $borrowernumber ? $borrowernumber : () )
829     );
830
831     return 1 if $sth->fetchrow_hashref;
832
833     my ( $min_length, $max_length ) = get_cardnumber_length();
834     return 2
835         if length $cardnumber > $max_length
836         or length $cardnumber < $min_length;
837
838     return 0;
839 }
840
841 =head2 get_cardnumber_length
842
843     my ($min, $max) = C4::Members::get_cardnumber_length()
844
845 Returns the minimum and maximum length for patron cardnumbers as
846 determined by the CardnumberLength system preference, the
847 BorrowerMandatoryField system preference, and the width of the
848 database column.
849
850 =cut
851
852 sub get_cardnumber_length {
853     my $borrower = Koha::Schema->resultset('Borrower');
854     my $field_size = $borrower->result_source->column_info('cardnumber')->{size};
855     my ( $min, $max ) = ( 0, $field_size ); # borrowers.cardnumber is a nullable varchar(20)
856     $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
857     if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
858         # Is integer and length match
859         if ( $cardnumber_length =~ m|^\d+$| ) {
860             $min = $max = $cardnumber_length
861                 if $cardnumber_length >= $min
862                     and $cardnumber_length <= $max;
863         }
864         # Else assuming it is a range
865         elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
866             $min = $1 if $1 and $min < $1;
867             $max = $2 if $2 and $max > $2;
868         }
869
870     }
871     $min = $max if $min > $max;
872     return ( $min, $max );
873 }
874
875 =head2 GetFirstValidEmailAddress
876
877   $email = GetFirstValidEmailAddress($borrowernumber);
878
879 Return the first valid email address for a borrower, given the borrowernumber.  For now, the order 
880 is defined as email, emailpro, B_email.  Returns the empty string if the borrower has no email 
881 addresses.
882
883 =cut
884
885 sub GetFirstValidEmailAddress {
886     my $borrowernumber = shift;
887
888     my $borrower = Koha::Patrons->find( $borrowernumber );
889
890     return $borrower->first_valid_email_address();
891 }
892
893 =head2 GetNoticeEmailAddress
894
895   $email = GetNoticeEmailAddress($borrowernumber);
896
897 Return the email address of borrower used for notices, given the borrowernumber.
898 Returns the empty string if no email address.
899
900 =cut
901
902 sub GetNoticeEmailAddress {
903     my $borrowernumber = shift;
904
905     my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
906     # if syspref is set to 'first valid' (value == OFF), look up email address
907     if ( $which_address eq 'OFF' ) {
908         return GetFirstValidEmailAddress($borrowernumber);
909     }
910     # specified email address field
911     my $dbh = C4::Context->dbh;
912     my $sth = $dbh->prepare( qq{
913         SELECT $which_address AS primaryemail
914         FROM borrowers
915         WHERE borrowernumber=?
916     } );
917     $sth->execute($borrowernumber);
918     my $data = $sth->fetchrow_hashref;
919     return $data->{'primaryemail'} || '';
920 }
921
922 =head2 GetBorrowersToExpunge
923
924   $borrowers = &GetBorrowersToExpunge(
925       not_borrowed_since => $not_borrowed_since,
926       expired_before       => $expired_before,
927       category_code        => $category_code,
928       patron_list_id       => $patron_list_id,
929       branchcode           => $branchcode
930   );
931
932   This function get all borrowers based on the given criteria.
933
934 =cut
935
936 sub GetBorrowersToExpunge {
937
938     my $params = shift;
939     my $filterdate       = $params->{'not_borrowed_since'};
940     my $filterexpiry     = $params->{'expired_before'};
941     my $filterlastseen   = $params->{'last_seen'};
942     my $filtercategory   = $params->{'category_code'};
943     my $filterbranch     = $params->{'branchcode'} ||
944                         ((C4::Context->preference('IndependentBranches')
945                              && C4::Context->userenv 
946                              && !C4::Context->IsSuperLibrarian()
947                              && C4::Context->userenv->{branch})
948                          ? C4::Context->userenv->{branch}
949                          : "");  
950     my $filterpatronlist = $params->{'patron_list_id'};
951
952     my $dbh   = C4::Context->dbh;
953     my $query = q|
954         SELECT borrowers.borrowernumber,
955                MAX(old_issues.timestamp) AS latestissue,
956                MAX(issues.timestamp) AS currentissue
957         FROM   borrowers
958         JOIN   categories USING (categorycode)
959         LEFT JOIN (
960             SELECT guarantorid
961             FROM borrowers
962             WHERE guarantorid IS NOT NULL
963                 AND guarantorid <> 0
964         ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
965         LEFT JOIN old_issues USING (borrowernumber)
966         LEFT JOIN issues USING (borrowernumber)|;
967     if ( $filterpatronlist  ){
968         $query .= q| LEFT JOIN patron_list_patrons USING (borrowernumber)|;
969     }
970     $query .= q| WHERE  category_type <> 'S'
971         AND tmp.guarantorid IS NULL
972    |;
973     my @query_params;
974     if ( $filterbranch && $filterbranch ne "" ) {
975         $query.= " AND borrowers.branchcode = ? ";
976         push( @query_params, $filterbranch );
977     }
978     if ( $filterexpiry ) {
979         $query .= " AND dateexpiry < ? ";
980         push( @query_params, $filterexpiry );
981     }
982     if ( $filterlastseen ) {
983         $query .= ' AND lastseen < ? ';
984         push @query_params, $filterlastseen;
985     }
986     if ( $filtercategory ) {
987         $query .= " AND categorycode = ? ";
988         push( @query_params, $filtercategory );
989     }
990     if ( $filterpatronlist ){
991         $query.=" AND patron_list_id = ? ";
992         push( @query_params, $filterpatronlist );
993     }
994     $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
995     if ( $filterdate ) {
996         $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
997         push @query_params,$filterdate;
998     }
999     warn $query if $debug;
1000
1001     my $sth = $dbh->prepare($query);
1002     if (scalar(@query_params)>0){  
1003         $sth->execute(@query_params);
1004     }
1005     else {
1006         $sth->execute;
1007     }
1008     
1009     my @results;
1010     while ( my $data = $sth->fetchrow_hashref ) {
1011         push @results, $data;
1012     }
1013     return \@results;
1014 }
1015
1016 =head2 IssueSlip
1017
1018   IssueSlip($branchcode, $borrowernumber, $quickslip)
1019
1020   Returns letter hash ( see C4::Letters::GetPreparedLetter )
1021
1022   $quickslip is boolean, to indicate whether we want a quick slip
1023
1024   IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
1025
1026   Both slips:
1027
1028       <<branches.*>>
1029       <<borrowers.*>>
1030
1031   ISSUESLIP:
1032
1033       <checkedout>
1034          <<biblio.*>>
1035          <<items.*>>
1036          <<biblioitems.*>>
1037          <<issues.*>>
1038       </checkedout>
1039
1040       <overdue>
1041          <<biblio.*>>
1042          <<items.*>>
1043          <<biblioitems.*>>
1044          <<issues.*>>
1045       </overdue>
1046
1047       <news>
1048          <<opac_news.*>>
1049       </news>
1050
1051   ISSUEQSLIP:
1052
1053       <checkedout>
1054          <<biblio.*>>
1055          <<items.*>>
1056          <<biblioitems.*>>
1057          <<issues.*>>
1058       </checkedout>
1059
1060   NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
1061
1062 =cut
1063
1064 sub IssueSlip {
1065     my ($branch, $borrowernumber, $quickslip) = @_;
1066
1067     # FIXME Check callers before removing this statement
1068     #return unless $borrowernumber;
1069
1070     my $patron = Koha::Patrons->find( $borrowernumber );
1071     return unless $patron;
1072
1073     my @issues = @{ GetPendingIssues($borrowernumber) };
1074
1075     for my $issue (@issues) {
1076         $issue->{date_due} = $issue->{date_due_sql};
1077         if ($quickslip) {
1078             my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
1079             if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
1080                 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
1081                   $issue->{now} = 1;
1082             };
1083         }
1084     }
1085
1086     # Sort on timestamp then on issuedate then on issue_id
1087     # useful for tests and could be if modified in a batch
1088     @issues = sort {
1089             $b->{timestamp} <=> $a->{timestamp}
1090          or $b->{issuedate} <=> $a->{issuedate}
1091          or $b->{issue_id}  <=> $a->{issue_id}
1092     } @issues;
1093
1094     my ($letter_code, %repeat, %loops);
1095     if ( $quickslip ) {
1096         $letter_code = 'ISSUEQSLIP';
1097         my @checkouts = map {
1098                 'biblio'       => $_,
1099                 'items'        => $_,
1100                 'biblioitems'  => $_,
1101                 'issues'       => $_,
1102             }, grep { $_->{'now'} } @issues;
1103         %repeat =  (
1104             checkedout => \@checkouts, # History syntax
1105         );
1106         %loops = (
1107             issues => [ map { $_->{issues}{itemnumber} } @checkouts ], # TT syntax
1108         );
1109     }
1110     else {
1111         my @checkouts = map {
1112             'biblio'        => $_,
1113               'items'       => $_,
1114               'biblioitems' => $_,
1115               'issues'      => $_,
1116         }, grep { !$_->{'overdue'} } @issues;
1117         my @overdues = map {
1118             'biblio'        => $_,
1119               'items'       => $_,
1120               'biblioitems' => $_,
1121               'issues'      => $_,
1122         }, grep { $_->{'overdue'} } @issues;
1123         my $news = GetNewsToDisplay( "slip", $branch );
1124         my @news = map {
1125             $_->{'timestamp'} = $_->{'newdate'};
1126             { opac_news => $_ }
1127         } @$news;
1128         $letter_code = 'ISSUESLIP';
1129         %repeat      = (
1130             checkedout => \@checkouts,
1131             overdue    => \@overdues,
1132             news       => \@news,
1133         );
1134         %loops = (
1135             issues => [ map { $_->{issues}{itemnumber} } @checkouts ],
1136             overdues   => [ map { $_->{issues}{itemnumber} } @overdues ],
1137             opac_news => [ map { $_->{opac_news}{idnew} } @news ],
1138         );
1139     }
1140
1141     return  C4::Letters::GetPreparedLetter (
1142         module => 'circulation',
1143         letter_code => $letter_code,
1144         branchcode => $branch,
1145         lang => $patron->lang,
1146         tables => {
1147             'branches'    => $branch,
1148             'borrowers'   => $borrowernumber,
1149         },
1150         repeat => \%repeat,
1151         loops => \%loops,
1152     );
1153 }
1154
1155 =head2 AddMember_Auto
1156
1157 =cut
1158
1159 sub AddMember_Auto {
1160     my ( %borrower ) = @_;
1161
1162     $borrower{'cardnumber'} ||= fixup_cardnumber();
1163
1164     $borrower{'borrowernumber'} = AddMember(%borrower);
1165
1166     return ( %borrower );
1167 }
1168
1169 =head2 AddMember_Opac
1170
1171 =cut
1172
1173 sub AddMember_Opac {
1174     my ( %borrower ) = @_;
1175
1176     $borrower{'categorycode'} //= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
1177     if (not defined $borrower{'password'}){
1178         my $sr = new String::Random;
1179         $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
1180         my $password = $sr->randpattern("AAAAAAAAAA");
1181         $borrower{'password'} = $password;
1182     }
1183
1184     %borrower = AddMember_Auto(%borrower);
1185
1186     return ( $borrower{'borrowernumber'}, $borrower{'password'} );
1187 }
1188
1189 =head2 DeleteExpiredOpacRegistrations
1190
1191     Delete accounts that haven't been upgraded from the 'temporary' category
1192     Returns the number of removed patrons
1193
1194 =cut
1195
1196 sub DeleteExpiredOpacRegistrations {
1197
1198     my $delay = C4::Context->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
1199     my $category_code = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
1200
1201     return 0 if not $category_code or not defined $delay or $delay eq q||;
1202
1203     my $query = qq|
1204 SELECT borrowernumber
1205 FROM borrowers
1206 WHERE categorycode = ? AND DATEDIFF( NOW(), dateenrolled ) > ? |;
1207
1208     my $dbh = C4::Context->dbh;
1209     my $sth = $dbh->prepare($query);
1210     $sth->execute( $category_code, $delay );
1211     my $cnt=0;
1212     while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
1213         Koha::Patrons->find($borrowernumber)->delete;
1214         $cnt++;
1215     }
1216     return $cnt;
1217 }
1218
1219 =head2 DeleteUnverifiedOpacRegistrations
1220
1221     Delete all unverified self registrations in borrower_modifications,
1222     older than the specified number of days.
1223
1224 =cut
1225
1226 sub DeleteUnverifiedOpacRegistrations {
1227     my ( $days ) = @_;
1228     my $dbh = C4::Context->dbh;
1229     my $sql=qq|
1230 DELETE FROM borrower_modifications
1231 WHERE borrowernumber = 0 AND DATEDIFF( NOW(), timestamp ) > ?|;
1232     my $cnt=$dbh->do($sql, undef, ($days) );
1233     return $cnt eq '0E0'? 0: $cnt;
1234 }
1235
1236 sub GetOverduesForPatron {
1237     my ( $borrowernumber ) = @_;
1238
1239     my $sql = "
1240         SELECT *
1241         FROM issues, items, biblio, biblioitems
1242         WHERE items.itemnumber=issues.itemnumber
1243           AND biblio.biblionumber   = items.biblionumber
1244           AND biblio.biblionumber   = biblioitems.biblionumber
1245           AND issues.borrowernumber = ?
1246           AND date_due < NOW()
1247     ";
1248
1249     my $sth = C4::Context->dbh->prepare( $sql );
1250     $sth->execute( $borrowernumber );
1251
1252     return $sth->fetchall_arrayref({});
1253 }
1254
1255 END { }    # module clean-up code here (global destructor)
1256
1257 1;
1258
1259 __END__
1260
1261 =head1 AUTHOR
1262
1263 Koha Team
1264
1265 =cut