Members.pm - Handle bad categorycode, Dates.pm - other problems persist.
[koha_ffzg] / C4 / Members.pm
1 package C4::Members;
2
3 # Copyright 2000-2003 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20
21 use strict;
22 require Exporter;
23 use C4::Context;
24 use C4::Dates qw(format_date_in_iso);
25 use Digest::MD5 qw(md5_base64);
26 use Date::Calc qw/Today Add_Delta_YM/;
27 use C4::Log; # logaction
28 use C4::Overdues;
29 use C4::Reserves;
30 use C4::Accounts;
31
32 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
33
34 BEGIN {
35         $VERSION = 3.01;
36         $debug = $ENV{DEBUG} || 0;
37 }
38
39 =head1 NAME
40
41 C4::Members - Perl Module containing convenience functions for member handling
42
43 =head1 SYNOPSIS
44
45 use C4::Members;
46
47 =head1 DESCRIPTION
48
49 This module contains routines for adding, modifying and deleting members/patrons/borrowers 
50
51 =head1 FUNCTIONS
52
53 =over 2
54
55 =cut
56
57 @ISA = qw(Exporter);
58
59 #Get data
60 push @EXPORT, qw(
61   &SearchMember 
62   &GetMemberDetails
63   &GetMember
64   
65   &GetGuarantees 
66   
67   &GetMemberIssuesAndFines
68   &GetPendingIssues
69   &GetAllIssues
70   
71   &get_institutions 
72   &getzipnamecity 
73   &getidcity
74    
75   &GetAge 
76   &GetCities 
77   &GetRoadTypes 
78   &GetRoadTypeDetails 
79   &GetSortDetails
80   &GetTitles    
81   
82   &GetMemberAccountRecords
83   &GetBorNotifyAcctRecord
84   
85   &GetborCatFromCatType 
86   &GetBorrowercategory
87   
88   
89   &GetBorrowersWhoHaveNotBorrowedSince
90   &GetBorrowersWhoHaveNeverBorrowed
91   &GetBorrowersWithIssuesHistoryOlderThan
92   
93   &GetExpiryDate
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   &add_member_orgs
111   &MoveMemberToDeleted
112   &ExtendMemberSubscriptionTo 
113 );
114
115 #Check data
116 push @EXPORT, qw(
117   &checkuniquemember 
118   &checkuserpassword
119         &Check_Userid
120   &fixEthnicity
121   &ethnicitycategories 
122   &fixup_cardnumber
123         &checkcardnumber
124 );
125
126 =item SearchMember
127
128   ($count, $borrowers) = &SearchMember($searchstring, $type,$category_type,$filter,$showallbranches);
129
130 Looks up patrons (borrowers) by name.
131
132 BUGFIX 499: C<$type> is now used to determine type of search.
133 if $type is "simple", search is performed on the first letter of the
134 surname only.
135
136 $category_type is used to get a specified type of user. 
137 (mainly adults when creating a child.)
138
139 C<$searchstring> is a space-separated list of search terms. Each term
140 must match the beginning a borrower's surname, first name, or other
141 name.
142
143 C<$filter> is assumed to be a list of elements to filter results on
144
145 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
146
147 C<&SearchMember> returns a two-element list. C<$borrowers> is a
148 reference-to-array; each element is a reference-to-hash, whose keys
149 are the fields of the C<borrowers> table in the Koha database.
150 C<$count> is the number of elements in C<$borrowers>.
151
152 =cut
153
154 #'
155 #used by member enquiries from the intranet
156 #called by member.pl and circ/circulation.pl
157 sub SearchMember {
158         my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
159         my $dbh   = C4::Context->dbh;
160         my $query = "";
161         my $count;
162         my @data;
163         my @bind = ();
164         
165         # this is used by circulation everytime a new borrowers cardnumber is scanned
166         # so we can check an exact match first, if that works return, otherwise do the rest
167         $query = "SELECT * FROM borrowers
168                 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
169                 ";
170         my $sth = $dbh->prepare("$query WHERE cardnumber = ?");
171         $sth->execute($searchstring);
172         my $data = $sth->fetchall_arrayref({});
173         if (@$data){
174                 return ( scalar(@$data), $data );
175         }
176     $sth->finish;
177
178     if ( $type eq "simple" )    # simple search for one letter only
179     {
180         $query .= ($category_type ? " AND category_type = ".$dbh->quote($category_type) : ""); 
181         $query .= " WHERE (surname LIKE ? OR cardnumber like ?) ";
182         if (C4::Context->preference("IndependantBranches") && !$showallbranches){
183           if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
184             $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
185           }
186         }
187         $query.=" ORDER BY $orderby";
188         @bind = ("$searchstring%","$searchstring");
189     }
190     else    # advanced search looking in surname, firstname and othernames
191     {
192         @data  = split( ' ', $searchstring );
193         $count = @data;
194         $query .= " WHERE ";
195         if (C4::Context->preference("IndependantBranches") && !$showallbranches){
196           if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
197             $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
198           }      
199                 }     
200                 $query.="((surname LIKE ? OR surname LIKE ?
201                                 OR firstname  LIKE ? OR firstname LIKE ?
202                                 OR othernames LIKE ? OR othernames LIKE ?)
203                 " .
204                 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
205                 @bind = (
206                         "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
207                         "$data[0]%", "% $data[0]%"
208                 );
209                 for ( my $i = 1 ; $i < $count ; $i++ ) {
210                         $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
211                                 OR firstname  LIKE ? OR firstname LIKE ?
212                                 OR othernames LIKE ? OR othernames LIKE ?)";
213                         push( @bind,
214                                 "$data[$i]%",   "% $data[$i]%", "$data[$i]%",
215                                 "% $data[$i]%", "$data[$i]%",   "% $data[$i]%" );
216
217                         # FIXME - .= <<EOT;
218                 }
219                 $query = $query . ") OR cardnumber LIKE ?
220                 order by $orderby";
221                 push( @bind, $searchstring );
222
223                 # FIXME - .= <<EOT;
224     }
225
226     $sth = $dbh->prepare($query);
227
228         $debug and print STDERR "Q $orderby : $query\n";
229     $sth->execute(@bind);
230     my @results;
231     $data = $sth->fetchall_arrayref({});
232
233     $sth->finish;
234     return ( scalar(@$data), $data );
235 }
236
237 =head2 GetMemberDetails
238
239 ($borrower, $flags) = &GetMemberDetails($borrowernumber, $cardnumber);
240
241 Looks up a patron and returns information about him or her. If
242 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
243 up the borrower by number; otherwise, it looks up the borrower by card
244 number.
245
246 C<$borrower> is a reference-to-hash whose keys are the fields of the
247 borrowers table in the Koha database. In addition,
248 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
249 about the patron. Its keys act as flags :
250
251     if $borrower->{flags}->{LOST} {
252         # Patron's card was reported lost
253     }
254
255 Each flag has a C<message> key, giving a human-readable explanation of
256 the flag. If the state of a flag means that the patron should not be
257 allowed to borrow any more books, then it will have a C<noissues> key
258 with a true value.
259
260 The possible flags are:
261
262 =head3 CHARGES
263
264 =over 4
265
266 =item Shows the patron's credit or debt, if any.
267
268 =back
269
270 =head3 GNA
271
272 =over 4
273
274 =item (Gone, no address.) Set if the patron has left without giving a
275 forwarding address.
276
277 =back
278
279 =head3 LOST
280
281 =over 4
282
283 =item Set if the patron's card has been reported as lost.
284
285 =back
286
287 =head3 DBARRED
288
289 =over 4
290
291 =item Set if the patron has been debarred.
292
293 =back
294
295 =head3 NOTES
296
297 =over 4
298
299 =item Any additional notes about the patron.
300
301 =back
302
303 =head3 ODUES
304
305 =over 4
306
307 =item Set if the patron has overdue items. This flag has several keys:
308
309 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
310 overdue items. Its elements are references-to-hash, each describing an
311 overdue item. The keys are selected fields from the issues, biblio,
312 biblioitems, and items tables of the Koha database.
313
314 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
315 the overdue items, one per line.
316
317 =back
318
319 =head3 WAITING
320
321 =over 4
322
323 =item Set if any items that the patron has reserved are available.
324
325 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
326 available items. Each element is a reference-to-hash whose keys are
327 fields from the reserves table of the Koha database.
328
329 =back
330
331 =cut
332
333 sub GetMemberDetails {
334     my ( $borrowernumber, $cardnumber ) = @_;
335     my $dbh = C4::Context->dbh;
336     my $query;
337     my $sth;
338     if ($borrowernumber) {
339         $sth = $dbh->prepare("select borrowers.*,category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where  borrowernumber=?");
340         $sth->execute($borrowernumber);
341     }
342     elsif ($cardnumber) {
343         $sth = $dbh->prepare("select borrowers.*,category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?");
344         $sth->execute($cardnumber);
345     }
346     else {
347         return undef;
348     }
349     my $borrower = $sth->fetchrow_hashref;
350     my ($amount) = GetMemberAccountRecords( $borrowernumber);
351     $borrower->{'amountoutstanding'} = $amount;
352         # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
353     my $flags = patronflags( $borrower);
354     my $accessflagshash;
355
356     $sth = $dbh->prepare("select bit,flag from userflags");
357     $sth->execute;
358     while ( my ( $bit, $flag ) = $sth->fetchrow ) {
359         if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
360             $accessflagshash->{$flag} = 1;
361         }
362     }
363     $sth->finish;
364     $borrower->{'flags'}     = $flags;
365     $borrower->{'authflags'} = $accessflagshash;
366
367     # find out how long the membership lasts
368     $sth =
369       $dbh->prepare(
370         "select enrolmentperiod from categories where categorycode = ?");
371     $sth->execute( $borrower->{'categorycode'} );
372     my $enrolment = $sth->fetchrow;
373     $borrower->{'enrolmentperiod'} = $enrolment;
374     return ($borrower);    #, $flags, $accessflagshash);
375 }
376
377 =head2 patronflags
378
379  Not exported
380
381  NOTE!: If you change this function, be sure to update the POD for
382  &GetMemberDetails.
383
384  $flags = &patronflags($patron);
385
386  $flags->{CHARGES}
387         {message}    Message showing patron's credit or debt
388        {noissues}    Set if patron owes >$5.00
389          {GNA}            Set if patron gone w/o address
390         {message}    "Borrower has no valid address"
391         {noissues}    Set.
392         {LOST}        Set if patron's card reported lost
393         {message}    Message to this effect
394         {noissues}    Set.
395         {DBARRED}        Set is patron is debarred
396         {message}    Message to this effect
397         {noissues}    Set.
398          {NOTES}        Set if patron has notes
399         {message}    Notes about patron
400          {ODUES}        Set if patron has overdue books
401         {message}    "Yes"
402         {itemlist}    ref-to-array: list of overdue books
403         {itemlisttext}    Text list of overdue items
404          {WAITING}        Set if there are items available that the
405                 patron reserved
406         {message}    Message to this effect
407         {itemlist}    ref-to-array: list of available items
408
409 =cut
410 # FIXME rename this function.
411 sub patronflags {
412     my %flags;
413     my ( $patroninformation) = @_;
414     my $dbh=C4::Context->dbh;
415     my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
416     if ( $amount > 0 ) {
417         my %flaginfo;
418         my $noissuescharge = C4::Context->preference("noissuescharge");
419         $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
420                 $flaginfo{'amount'} = sprintf "%.02f",$amount;
421         if ( $amount > $noissuescharge ) {
422             $flaginfo{'noissues'} = 1;
423         }
424         $flags{'CHARGES'} = \%flaginfo;
425     }
426     elsif ( $amount < 0 ) {
427         my %flaginfo;
428         $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
429         $flags{'CHARGES'} = \%flaginfo;
430     }
431     if (   $patroninformation->{'gonenoaddress'}
432         && $patroninformation->{'gonenoaddress'} == 1 )
433     {
434         my %flaginfo;
435         $flaginfo{'message'}  = 'Borrower has no valid address.';
436         $flaginfo{'noissues'} = 1;
437         $flags{'GNA'}         = \%flaginfo;
438     }
439     if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
440         my %flaginfo;
441         $flaginfo{'message'}  = 'Borrower\'s card reported lost.';
442         $flaginfo{'noissues'} = 1;
443         $flags{'LOST'}        = \%flaginfo;
444     }
445     if (   $patroninformation->{'debarred'}
446         && $patroninformation->{'debarred'} == 1 )
447     {
448         my %flaginfo;
449         $flaginfo{'message'}  = 'Borrower is Debarred.';
450         $flaginfo{'noissues'} = 1;
451         $flags{'DBARRED'}     = \%flaginfo;
452     }
453     if (   $patroninformation->{'borrowernotes'}
454         && $patroninformation->{'borrowernotes'} )
455     {
456         my %flaginfo;
457         $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
458         $flags{'NOTES'}      = \%flaginfo;
459     }
460     my ( $odues, $itemsoverdue ) =
461       checkoverdues( $patroninformation->{'borrowernumber'}, $dbh );
462     if ( $odues > 0 ) {
463         my %flaginfo;
464         $flaginfo{'message'}  = "Yes";
465         $flaginfo{'itemlist'} = $itemsoverdue;
466         foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
467             @$itemsoverdue )
468         {
469             $flaginfo{'itemlisttext'} .=
470               "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
471         }
472         $flags{'ODUES'} = \%flaginfo;
473     }
474     my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
475     my $nowaiting = scalar @itemswaiting;
476     if ( $nowaiting > 0 ) {
477         my %flaginfo;
478         $flaginfo{'message'}  = "Reserved items available";
479         $flaginfo{'itemlist'} = \@itemswaiting;
480         $flags{'WAITING'}     = \%flaginfo;
481     }
482     return ( \%flags );
483 }
484
485
486 =item GetMember
487
488   $borrower = &GetMember($information, $type);
489
490 Looks up information about a patron (borrower) by either card number
491 ,firstname, or borrower number, depending on $type value.
492 If C<$type> == 'cardnumber', C<&GetBorrower>
493 searches by cardnumber then by firstname if not found in cardnumber; 
494 otherwise, it searches by borrowernumber.
495
496 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
497 the C<borrowers> table in the Koha database.
498
499 =cut
500
501 #'
502 sub GetMember {
503     my ( $information, $type ) = @_;
504     my $dbh = C4::Context->dbh;
505     my $sth;
506         my $select = "
507 SELECT borrowers.*, categories.category_type, categories.description
508 FROM borrowers 
509 LEFT JOIN categories on borrowers.categorycode=categories.categorycode 
510 ";
511         if ($type eq 'cardnumber' || $type eq 'firstname'|| $type eq 'userid'|| $type eq 'borrowernumber'){
512                 $information = uc $information;
513                 $sth = $dbh->prepare("$select WHERE $type=?");
514     } else {
515                 $sth = $dbh->prepare("$select WHERE borrowernumber=?");
516         }
517     $sth->execute($information);
518     my $data = $sth->fetchrow_hashref;
519     $sth->finish;
520     ($data) and return ($data);
521
522     if ($type eq 'cardnumber' || $type eq 'firstname') {    # otherwise, try with firstname
523                 $sth = $dbh->prepare("$select WHERE firstname like ?");
524                 $sth->execute($information);
525                 $data = $sth->fetchrow_hashref;
526                 $sth->finish;
527                 return ($data);
528     }
529         return undef;        
530 }
531
532 =item GetMemberIssuesAndFines
533
534   ($borrowed, $due, $fine) = &GetMemberIssuesAndFines($borrowernumber);
535
536 Returns aggregate data about items borrowed by the patron with the
537 given borrowernumber.
538
539 C<&GetMemberIssuesAndFines> returns a three-element array. C<$borrowed> is the
540 number of books the patron currently has borrowed. C<$due> is the
541 number of overdue items the patron currently has borrowed. C<$fine> is
542 the total fine currently due by the borrower.
543
544 =cut
545
546 #'
547 sub GetMemberIssuesAndFines {
548     my ( $borrowernumber ) = @_;
549     my $dbh   = C4::Context->dbh;
550     my $query =
551       "Select count(*) from issues where borrowernumber='$borrowernumber' and
552     returndate is NULL";
553
554     $debug and print $query, "\n";
555     my $sth = $dbh->prepare($query);
556     $sth->execute;
557     my $data = $sth->fetchrow_hashref;
558     $sth->finish;
559     $sth = $dbh->prepare(
560         "Select count(*) from issues where
561     borrowernumber='$borrowernumber' and date_due < now() and returndate is NULL"
562     );
563     $sth->execute;
564     my $data2 = $sth->fetchrow_hashref;
565     $sth->finish;
566     $sth = $dbh->prepare(
567         "Select sum(amountoutstanding) from accountlines where
568     borrowernumber='$borrowernumber'"
569     );
570     $sth->execute;
571     my $data3 = $sth->fetchrow_hashref;
572     $sth->finish;
573
574     return ( $data2->{'count(*)'}, $data->{'count(*)'},
575         $data3->{'sum(amountoutstanding)'} );
576 }
577
578 =head2
579
580 =item ModMember
581
582   &ModMember($borrowernumber);
583
584 Modify borrower's data
585
586 =cut
587
588 #'
589 sub ModMember {
590     my (%data) = @_;
591     my $dbh = C4::Context->dbh;
592     $data{'dateofbirth'}  = format_date_in_iso( $data{'dateofbirth' } ) if ($data{'dateofbirth' } );
593     $data{'dateexpiry'}   = format_date_in_iso( $data{ 'dateexpiry' } ) if ($data{ 'dateexpiry' } );
594     $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'} ) if ($data{'dateenrolled'} );
595     my $qborrower=$dbh->prepare("SHOW columns from borrowers");
596     $qborrower->execute;
597     my %hashborrowerfields;  
598     while (my ($field)=$qborrower->fetchrow){
599       $hashborrowerfields{$field}=1;
600     }  
601     my $query = "UPDATE borrowers SET \n";
602     my $sth;
603     my @parameters;  
604     
605     # test to know if you must update or not the borrower password
606     if ( $data{'password'} eq '****' ) {
607         delete $data{'password'};
608     } else {
609         $data{'password'} = md5_base64( $data{'password'} )  if ($data{'password'} ne "");
610         delete $data{'password'} if ($data{password} eq "");
611     }
612         foreach (keys %data)
613         { push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne 'borrowernumber' and $_ ne 'flags' and $hashborrowerfields{$_}); }
614     $query .= join (',',@parameters) . "\n WHERE borrowernumber=? \n";
615         $debug and print STDERR "$query (executed w/ arg: $data{'borrowernumber'})";
616         $sth = $dbh->prepare($query);
617         $sth->execute($data{'borrowernumber'});
618         $sth->finish;
619
620 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
621 # so when we update information for an adult we should check for guarantees and update the relevant part
622 # of their records, ie addresses and phone numbers
623     my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
624     if ( $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
625         # is adult check guarantees;
626         UpdateGuarantees(%data);
627     }
628     &logaction(C4::Context->userenv->{'number'},"MEMBERS","MODIFY",$data{'borrowernumber'},"") 
629         if C4::Context->preference("BorrowersLog");
630 }
631
632
633 =head2
634
635 =item AddMember
636
637   $borrowernumber = &AddMember(%borrower);
638
639 insert new borrower into table
640 Returns the borrowernumber
641
642 =cut
643
644 #'
645 sub AddMember {
646     my (%data) = @_;
647     my $dbh = C4::Context->dbh;
648     $data{'userid'} = '' unless $data{'password'};
649     $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
650     $data{'dateofbirth'}  = format_date_in_iso( $data{'dateofbirth'} );
651     $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'});
652     $data{'dateexpiry'}   = format_date_in_iso( $data{'dateexpiry'}  );
653         # This query should be rewritten to use "?" at execute.
654     my $query =
655         "insert into borrowers set cardnumber=" . $dbh->quote( $data{'cardnumber'} )
656       . ",surname="     . $dbh->quote( $data{'surname'} )
657       . ",firstname="   . $dbh->quote( $data{'firstname'} )
658       . ",title="               . $dbh->quote( $data{'title'} )
659       . ",othernames="  . $dbh->quote( $data{'othernames'} )
660       . ",initials="    . $dbh->quote( $data{'initials'} )
661       . ",streetnumber=". $dbh->quote( $data{'streetnumber'} )
662       . ",streettype="  . $dbh->quote( $data{'streettype'} )
663       . ",address="     . $dbh->quote( $data{'address'} )
664       . ",address2="    . $dbh->quote( $data{'address2'} )
665       . ",zipcode="     . $dbh->quote( $data{'zipcode'} )
666       . ",city="                . $dbh->quote( $data{'city'} )
667       . ",phone="               . $dbh->quote( $data{'phone'} )
668       . ",email="               . $dbh->quote( $data{'email'} )
669       . ",mobile="              . $dbh->quote( $data{'mobile'} )
670       . ",phonepro="    . $dbh->quote( $data{'phonepro'} )
671       . ",opacnote="    . $dbh->quote( $data{'opacnote'} )
672       . ",guarantorid=" . $dbh->quote( $data{'guarantorid'} )
673       . ",dateofbirth=" . $dbh->quote( $data{'dateofbirth'} )
674       . ",branchcode="  . $dbh->quote( $data{'branchcode'} )
675       . ",categorycode=" . $dbh->quote( $data{'categorycode'} )
676       . ",dateenrolled=" . $dbh->quote( $data{'dateenrolled'} )
677       . ",contactname=" . $dbh->quote( $data{'contactname'} )
678       . ",borrowernotes=" . $dbh->quote( $data{'borrowernotes'} )
679       . ",dateexpiry="  . $dbh->quote( $data{'dateexpiry'} )
680       . ",contactnote=" . $dbh->quote( $data{'contactnote'} )
681       . ",B_address="   . $dbh->quote( $data{'B_address'} )
682       . ",B_zipcode="   . $dbh->quote( $data{'B_zipcode'} )
683       . ",B_city="              . $dbh->quote( $data{'B_city'} )
684       . ",B_phone="     . $dbh->quote( $data{'B_phone'} )
685       . ",B_email="     . $dbh->quote( $data{'B_email'} )
686       . ",password="    . $dbh->quote( $data{'password'} )
687       . ",userid="              . $dbh->quote( $data{'userid'} )
688       . ",sort1="               . $dbh->quote( $data{'sort1'} )
689       . ",sort2="               . $dbh->quote( $data{'sort2'} )
690       . ",contacttitle=" . $dbh->quote( $data{'contacttitle'} )
691       . ",emailpro="    . $dbh->quote( $data{'emailpro'} )
692       . ",contactfirstname=" . $dbh->quote( $data{'contactfirstname'} )
693           . ",sex="             . $dbh->quote( $data{'sex'} )
694           . ",fax="             . $dbh->quote( $data{'fax'} )
695       . ",relationship=" . $dbh->quote( $data{'relationship'} )
696       . ",B_streetnumber=" . $dbh->quote( $data{'B_streetnumber'} )
697       . ",B_streettype=" . $dbh->quote( $data{'B_streettype'} )
698       . ",gonenoaddress=" . $dbh->quote( $data{'gonenoaddress'} )
699       . ",lost="                . $dbh->quote( $data{'lost'} )
700       . ",debarred="    . $dbh->quote( $data{'debarred'} )
701       . ",ethnicity="   . $dbh->quote( $data{'ethnicity'} )
702       . ",ethnotes="    . $dbh->quote( $data{'ethnotes'} ) ;
703         $debug and print STDERR "AddMember SQL: ($query)\n";
704     my $sth = $dbh->prepare($query);
705         #       print "Executing SQL: $query\n";
706     $sth->execute;
707     $sth->finish;
708     # $data{'borrowernumber'} = $dbh->{'mysql_insertid'};       # unneeded w/ autoincrement ?
709     
710     &logaction(C4::Context->userenv->{'number'},"MEMBERS","CREATE",$data{'borrowernumber'},"") 
711         if C4::Context->preference("BorrowersLog");
712     
713     # check for enrollment fee & add it if needed
714     $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
715     $sth->execute($data{'categorycode'});
716     my ($enrolmentfee) = $sth->fetchrow;
717     if ($enrolmentfee) {
718         # insert fee in patron debts
719         manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
720     }
721     return $data{'borrowernumber'};
722 }
723
724 sub Check_Userid {
725         my ($uid,$member) = @_;
726         my $dbh = C4::Context->dbh;
727     # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
728     # Then we need to tell the user and have them create a new one.
729     my $sth =
730       $dbh->prepare(
731         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
732     $sth->execute( $uid, $member );
733     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
734         return 0;
735     }
736         else {
737                 return 1;
738         }
739 }
740
741
742 sub changepassword {
743     my ( $uid, $member, $digest ) = @_;
744     my $dbh = C4::Context->dbh;
745
746 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
747 #Then we need to tell the user and have them create a new one.
748     my $sth =
749       $dbh->prepare(
750         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
751     $sth->execute( $uid, $member );
752     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
753         return 0;
754     }
755     else {
756         #Everything is good so we can update the information.
757         $sth =
758           $dbh->prepare(
759             "update borrowers set userid=?, password=? where borrowernumber=?");
760         $sth->execute( $uid, $digest, $member );
761         return 1;
762     }
763     
764     &logaction(C4::Context->userenv->{'number'},"MEMBERS","CHANGE PASS",$member,"") 
765         if C4::Context->preference("BorrowersLog");
766 }
767
768
769
770 =item fixup_cardnumber
771
772 Warning: The caller is responsible for locking the members table in write
773 mode, to avoid database corruption.
774
775 =cut
776
777 use vars qw( @weightings );
778 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
779
780 sub fixup_cardnumber ($) {
781     my ($cardnumber) = @_;
782     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
783     $autonumber_members = 0 unless defined $autonumber_members;
784
785     # Find out whether member numbers should be generated
786     # automatically. Should be either "1" or something else.
787     # Defaults to "0", which is interpreted as "no".
788
789     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
790     if ($autonumber_members) {
791         my $dbh = C4::Context->dbh;
792         if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
793
794             # if checkdigit is selected, calculate katipo-style cardnumber.
795             # otherwise, just use the max()
796             # purpose: generate checksum'd member numbers.
797             # We'll assume we just got the max value of digits 2-8 of member #'s
798             # from the database and our job is to increment that by one,
799             # determine the 1st and 9th digits and return the full string.
800             my $sth =
801               $dbh->prepare(
802                 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
803               );
804             $sth->execute;
805
806             my $data = $sth->fetchrow_hashref;
807             $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
808             $sth->finish;
809             if ( !$cardnumber ) {    # If DB has no values,
810                 $cardnumber = 1000000;    # start at 1000000
811             }
812             else {
813                 $cardnumber += 1;
814             }
815
816             my $sum = 0;
817             for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
818
819                 # read weightings, left to right, 1 char at a time
820                 my $temp1 = $weightings[$i];
821
822                 # sequence left to right, 1 char at a time
823                 my $temp2 = substr( $cardnumber, $i, 1 );
824
825                 # mult each char 1-7 by its corresponding weighting
826                 $sum += $temp1 * $temp2;
827             }
828
829             my $rem = ( $sum % 11 );
830             $rem = 'X' if $rem == 10;
831
832             $cardnumber = "V$cardnumber$rem";
833         }
834         else {
835
836      # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
837      # better. I'll leave the original in in case it needs to be changed for you
838             my $sth =
839               $dbh->prepare(
840                 "select max(cast(cardnumber as signed)) from borrowers");
841
842       #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
843
844             $sth->execute;
845
846             my ($result) = $sth->fetchrow;
847             $sth->finish;
848             $cardnumber = $result + 1;
849         }
850     }
851     return $cardnumber;
852 }
853
854 =head2 GetGuarantees
855
856   ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
857   $child0_cardno = $children_arrayref->[0]{"cardnumber"};
858   $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
859
860 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
861 with children) and looks up the borrowers who are guaranteed by that
862 borrower (i.e., the patron's children).
863
864 C<&GetGuarantees> returns two values: an integer giving the number of
865 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
866 of references to hash, which gives the actual results.
867
868 =cut
869
870 #'
871 sub GetGuarantees {
872     my ($borrowernumber) = @_;
873     my $dbh              = C4::Context->dbh;
874     my $sth              =
875       $dbh->prepare(
876 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
877       );
878     $sth->execute($borrowernumber);
879
880     my @dat;
881     my $data = $sth->fetchall_arrayref({}); 
882     $sth->finish;
883     return ( scalar(@$data), $data );
884 }
885
886 =head2 UpdateGuarantees
887
888   &UpdateGuarantees($parent_borrno);
889   
890
891 C<&UpdateGuarantees> borrower data for an adulte and updates all the guarantees
892 with the modified information
893
894 =cut
895
896 #'
897 sub UpdateGuarantees {
898     my (%data) = @_;
899     my $dbh = C4::Context->dbh;
900     my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
901     for ( my $i = 0 ; $i < $count ; $i++ ) {
902
903         # FIXME
904         # It looks like the $i is only being returned to handle walking through
905         # the array, which is probably better done as a foreach loop.
906         #
907         my $guaquery = qq|UPDATE borrowers 
908                           SET address='$data{'address'}',fax='$data{'fax'}',
909                               B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
910                           WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
911                 |;
912         my $sth3 = $dbh->prepare($guaquery);
913         $sth3->execute;
914         $sth3->finish;
915     }
916 }
917 =head2 GetPendingIssues
918
919   ($count, $issues) = &GetPendingIssues($borrowernumber);
920
921 Looks up what the patron with the given borrowernumber has borrowed.
922
923 C<&GetPendingIssues> returns a two-element array. C<$issues> is a
924 reference-to-array, where each element is a reference-to-hash; the
925 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
926 in the Koha database. C<$count> is the number of elements in
927 C<$issues>.
928
929 =cut
930
931 #'
932 sub GetPendingIssues {
933     my ($borrowernumber) = @_;
934     my $dbh              = C4::Context->dbh;
935
936     my $sth              = $dbh->prepare(
937    "SELECT * FROM issues 
938       LEFT JOIN items ON issues.itemnumber=items.itemnumber
939       LEFT JOIN biblio ON     items.biblionumber=biblio.biblionumber 
940       LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
941     WHERE
942       borrowernumber=? 
943       AND returndate IS NULL
944     ORDER BY issues.issuedate"
945     );
946     $sth->execute($borrowernumber);
947     my $data = $sth->fetchall_arrayref({});
948     my $today = POSIX::strftime("%Y%m%d", localtime);
949     foreach( @$data ) {
950         my $datedue = $_->{'date_due'};
951         $datedue =~ s/-//g;
952         if ( $datedue < $today ) {
953             $_->{'overdue'} = 1;
954         }
955     }
956     $sth->finish;
957     return ( scalar(@$data), $data );
958 }
959
960 =head2 GetAllIssues
961
962   ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
963
964 Looks up what the patron with the given borrowernumber has borrowed,
965 and sorts the results.
966
967 C<$sortkey> is the name of a field on which to sort the results. This
968 should be the name of a field in the C<issues>, C<biblio>,
969 C<biblioitems>, or C<items> table in the Koha database.
970
971 C<$limit> is the maximum number of results to return.
972
973 C<&GetAllIssues> returns a two-element array. C<$issues> is a
974 reference-to-array, where each element is a reference-to-hash; the
975 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
976 C<items> tables of the Koha database. C<$count> is the number of
977 elements in C<$issues>
978
979 =cut
980
981 #'
982 sub GetAllIssues {
983     my ( $borrowernumber, $order, $limit ) = @_;
984
985     #FIXME: sanity-check order and limit
986     my $dbh   = C4::Context->dbh;
987     my $count = 0;
988     my $query =
989   "Select *,items.timestamp AS itemstimestamp from 
990   issues 
991   LEFT JOIN items on items.itemnumber=issues.itemnumber
992   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
993   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
994   where borrowernumber=? 
995   order by $order";
996     if ( $limit != 0 ) {
997         $query .= " limit $limit";
998     }
999
1000     #print $query;
1001     my $sth = $dbh->prepare($query);
1002     $sth->execute($borrowernumber);
1003     my @result;
1004     my $i = 0;
1005     while ( my $data = $sth->fetchrow_hashref ) {
1006         $result[$i] = $data;
1007         $i++;
1008         $count++;
1009     }
1010
1011     # get all issued items for borrowernumber from oldissues table
1012     # large chunk of older issues data put into table oldissues
1013     # to speed up db calls for issuing items
1014     if ( C4::Context->preference("ReadingHistory") ) {
1015         my $query2 = "SELECT * FROM oldissues
1016                       LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1017                       LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1018                       LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1019                       WHERE borrowernumber=? 
1020                       ORDER BY $order";
1021         if ( $limit != 0 ) {
1022             $limit = $limit - $count;
1023             $query2 .= " limit $limit";
1024         }
1025
1026         my $sth2 = $dbh->prepare($query2);
1027         $sth2->execute($borrowernumber);
1028
1029         while ( my $data2 = $sth2->fetchrow_hashref ) {
1030             $result[$i] = $data2;
1031             $i++;
1032         }
1033         $sth2->finish;
1034     }
1035     $sth->finish;
1036
1037     return ( $i, \@result );
1038 }
1039
1040
1041 =head2 GetMemberAccountRecords
1042
1043   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1044
1045 Looks up accounting data for the patron with the given borrowernumber.
1046
1047 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1048 reference-to-array, where each element is a reference-to-hash; the
1049 keys are the fields of the C<accountlines> table in the Koha database.
1050 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1051 total amount outstanding for all of the account lines.
1052
1053 =cut
1054
1055 #'
1056 sub GetMemberAccountRecords {
1057     my ($borrowernumber,$date) = @_;
1058     my $dbh = C4::Context->dbh;
1059     my @acctlines;
1060     my $numlines = 0;
1061     my $strsth      = qq(
1062                         SELECT * 
1063                         FROM accountlines 
1064                         WHERE borrowernumber=?);
1065     my @bind = ($borrowernumber);
1066     if ($date && $date ne ''){
1067             $strsth.=" AND date < ? ";
1068             push(@bind,$date);
1069     }
1070     $strsth.=" ORDER BY date desc,timestamp DESC";
1071     my $sth= $dbh->prepare( $strsth );
1072     $sth->execute( @bind );
1073     my $total = 0;
1074     while ( my $data = $sth->fetchrow_hashref ) {
1075         $acctlines[$numlines] = $data;
1076         $numlines++;
1077         $total += $data->{'amountoutstanding'};
1078     }
1079     $sth->finish;
1080     return ( $total, \@acctlines,$numlines);
1081 }
1082
1083 =head2 GetBorNotifyAcctRecord
1084
1085   ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1086
1087 Looks up accounting data for the patron with the given borrowernumber per file number.
1088
1089 (FIXME - I'm not at all sure what this is about.)
1090
1091 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1092 reference-to-array, where each element is a reference-to-hash; the
1093 keys are the fields of the C<accountlines> table in the Koha database.
1094 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1095 total amount outstanding for all of the account lines.
1096
1097 =cut
1098
1099 sub GetBorNotifyAcctRecord {
1100     my ( $borrowernumber, $notifyid ) = @_;
1101     my $dbh = C4::Context->dbh;
1102     my @acctlines;
1103     my $numlines = 0;
1104     my $sth = $dbh->prepare(
1105             "SELECT * 
1106                 FROM accountlines 
1107                 WHERE borrowernumber=? 
1108                     AND notify_id=? 
1109                     AND (accounttype='FU' OR accounttype='N' OR accounttype='M'OR accounttype='A'OR accounttype='F'OR accounttype='L' OR accounttype='IP' OR accounttype='CH' OR accounttype='RE' OR accounttype='RL')
1110                     AND amountoutstanding != '0' 
1111                 ORDER BY notify_id,accounttype
1112                 ");
1113     $sth->execute( $borrowernumber, $notifyid );
1114     my $total = 0;
1115     while ( my $data = $sth->fetchrow_hashref ) {
1116         $acctlines[$numlines] = $data;
1117         $numlines++;
1118         $total += $data->{'amountoutstanding'};
1119     }
1120     $sth->finish;
1121     return ( $total, \@acctlines, $numlines );
1122 }
1123
1124 =head2 checkuniquemember (OUEST-PROVENCE)
1125
1126   $result = &checkuniquemember($collectivity,$surname,$categorycode,$firstname,$dateofbirth);
1127
1128 Checks that a member exists or not in the database.
1129
1130 C<&result> is 1 (=exist) or 0 (=does not exist)
1131 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1132 C<&surname> is the surname
1133 C<&categorycode> is from categorycode table
1134 C<&firstname> is the firstname (only if collectivity=0)
1135 C<&dateofbirth> is the date of birth (only if collectivity=0)
1136
1137 =cut
1138
1139 sub checkuniquemember {
1140     my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1141     my $dbh = C4::Context->dbh;
1142     my $request;
1143     if ($collectivity) {
1144
1145 #                               $request="select count(*) from borrowers where surname=? and categorycode=?";
1146         $request =
1147           "select borrowernumber,categorycode from borrowers where surname=? ";
1148     }
1149     else {
1150
1151 #                               $request="select count(*) from borrowers where surname=? and categorycode=? and firstname=? and dateofbirth=?";
1152         $request =
1153 "select borrowernumber,categorycode from borrowers where surname=?  and firstname=? and dateofbirth=?";
1154     }
1155     my $sth = $dbh->prepare($request);
1156     if ($collectivity) {
1157         $sth->execute( uc($surname) );
1158     }
1159     else {
1160         $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1161     }
1162     my @data = $sth->fetchrow;
1163     if ( $data[0] ) {
1164         $sth->finish;
1165         return $data[0], $data[1];
1166
1167         #
1168     }
1169     else {
1170         $sth->finish;
1171         return 0;
1172     }
1173 }
1174
1175 sub checkcardnumber {
1176         my ($cardnumber,$borrowernumber) = @_;
1177         my $dbh = C4::Context->dbh;
1178         my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1179         $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1180   my $sth = $dbh->prepare($query);
1181   if ($borrowernumber) {
1182    $sth->execute($cardnumber,$borrowernumber);
1183   } else { 
1184          $sth->execute($cardnumber);
1185   } 
1186         if (my $data= $sth->fetchrow_hashref()){
1187                 return 1;
1188         }
1189         else {
1190                 return 0;
1191         }
1192         $sth->finish();
1193 }  
1194
1195
1196 =head2 getzipnamecity (OUEST-PROVENCE)
1197
1198 take all info from table city for the fields city and  zip
1199 check for the name and the zip code of the city selected
1200
1201 =cut
1202
1203 sub getzipnamecity {
1204     my ($cityid) = @_;
1205     my $dbh      = C4::Context->dbh;
1206     my $sth      =
1207       $dbh->prepare(
1208         "select city_name,city_zipcode from cities where cityid=? ");
1209     $sth->execute($cityid);
1210     my @data = $sth->fetchrow;
1211     return $data[0], $data[1];
1212 }
1213
1214
1215 =head2 getdcity (OUEST-PROVENCE)
1216
1217 recover cityid  with city_name condition
1218
1219 =cut
1220
1221 sub getidcity {
1222     my ($city_name) = @_;
1223     my $dbh = C4::Context->dbh;
1224     my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1225     $sth->execute($city_name);
1226     my $data = $sth->fetchrow;
1227     return $data;
1228 }
1229
1230
1231 =head2 GetExpiryDate 
1232
1233   $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1234
1235 Calculate expiry date given a categorycode and starting date.  Date argument must be in ISO format.
1236 Return date is also in ISO format.
1237
1238 =cut
1239
1240 sub GetExpiryDate {
1241     my ( $categorycode, $dateenrolled ) = @_;
1242     my $enrolmentperiod = 12;   # reasonable default
1243     if ($categorycode) {
1244         my $dbh = C4::Context->dbh;
1245         my $sth = $dbh->prepare("select enrolmentperiod from categories where categorycode=?");
1246         $sth->execute($categorycode);
1247         $enrolmentperiod = $sth->fetchrow;
1248         }
1249         # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1250     my @date = split /-/,$dateenrolled;
1251     return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolmentperiod));
1252 }
1253
1254 =head2 checkuserpassword (OUEST-PROVENCE)
1255
1256 check for the password and login are not used
1257 return the number of record 
1258 0=> NOT USED 1=> USED
1259
1260 =cut
1261
1262 sub checkuserpassword {
1263     my ( $borrowernumber, $userid, $password ) = @_;
1264     $password = md5_base64($password);
1265     my $dbh = C4::Context->dbh;
1266     my $sth =
1267       $dbh->prepare(
1268 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1269       );
1270     $sth->execute( $borrowernumber, $userid, $password );
1271     my $number_rows = $sth->fetchrow;
1272     return $number_rows;
1273
1274 }
1275
1276 =head2 GetborCatFromCatType
1277
1278   ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1279
1280 Looks up the different types of borrowers in the database. Returns two
1281 elements: a reference-to-array, which lists the borrower category
1282 codes, and a reference-to-hash, which maps the borrower category codes
1283 to category descriptions.
1284
1285 =cut
1286
1287 #'
1288 sub GetborCatFromCatType {
1289     my ( $category_type, $action ) = @_;
1290     my $dbh     = C4::Context->dbh;
1291     my $request = qq|   SELECT categorycode,description 
1292                         FROM categories 
1293                         $action
1294                         ORDER BY categorycode|;
1295     my $sth = $dbh->prepare($request);
1296     if ($action) {
1297         $sth->execute($category_type);
1298     }
1299     else {
1300         $sth->execute();
1301     }
1302
1303     my %labels;
1304     my @codes;
1305
1306     while ( my $data = $sth->fetchrow_hashref ) {
1307         push @codes, $data->{'categorycode'};
1308         $labels{ $data->{'categorycode'} } = $data->{'description'};
1309     }
1310     $sth->finish;
1311     return ( \@codes, \%labels );
1312 }
1313
1314 =head2 GetBorrowercategory
1315
1316   $hashref = &GetBorrowercategory($categorycode);
1317
1318 Given the borrower's category code, the function returns the corresponding
1319 data hashref for a comprehensive information display.
1320
1321 =cut
1322
1323 sub GetBorrowercategory {
1324     my ($catcode) = @_;
1325     my $dbh       = C4::Context->dbh;
1326     my $sth       =
1327       $dbh->prepare(
1328 "SELECT description,dateofbirthrequired,upperagelimit,category_type 
1329  FROM categories 
1330  WHERE categorycode = ?"
1331       );
1332     $sth->execute($catcode);
1333     my $data =
1334       $sth->fetchrow_hashref;
1335     $sth->finish();
1336     return $data;
1337 }    # sub getborrowercategory
1338
1339 =head2 ethnicitycategories
1340
1341   ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1342
1343 Looks up the different ethnic types in the database. Returns two
1344 elements: a reference-to-array, which lists the ethnicity codes, and a
1345 reference-to-hash, which maps the ethnicity codes to ethnicity
1346 descriptions.
1347
1348 =cut
1349
1350 #'
1351
1352 sub ethnicitycategories {
1353     my $dbh = C4::Context->dbh;
1354     my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1355     $sth->execute;
1356     my %labels;
1357     my @codes;
1358     while ( my $data = $sth->fetchrow_hashref ) {
1359         push @codes, $data->{'code'};
1360         $labels{ $data->{'code'} } = $data->{'name'};
1361     }
1362     $sth->finish;
1363     return ( \@codes, \%labels );
1364 }
1365
1366 =head2 fixEthnicity
1367
1368   $ethn_name = &fixEthnicity($ethn_code);
1369
1370 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1371 corresponding descriptive name from the C<ethnicity> table in the
1372 Koha database ("European" or "Pacific Islander").
1373
1374 =cut
1375
1376 #'
1377
1378 sub fixEthnicity {
1379     my $ethnicity = shift;
1380     return unless $ethnicity;
1381     my $dbh       = C4::Context->dbh;
1382     my $sth       = $dbh->prepare("Select name from ethnicity where code = ?");
1383     $sth->execute($ethnicity);
1384     my $data = $sth->fetchrow_hashref;
1385     $sth->finish;
1386     return $data->{'name'};
1387 }    # sub fixEthnicity
1388
1389 =head2 GetAge
1390
1391   $dateofbirth,$date = &GetAge($date);
1392
1393 this function return the borrowers age with the value of dateofbirth
1394
1395 =cut
1396
1397 #'
1398 sub GetAge{
1399     my ( $date, $date_ref ) = @_;
1400
1401     if ( not defined $date_ref ) {
1402         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1403     }
1404
1405     my ( $year1, $month1, $day1 ) = split /-/, $date;
1406     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1407
1408     my $age = $year2 - $year1;
1409     if ( $month1 . $day1 > $month2 . $day2 ) {
1410         $age--;
1411     }
1412
1413     return $age;
1414 }    # sub get_age
1415
1416 =head2 get_institutions
1417   $insitutions = get_institutions();
1418
1419 Just returns a list of all the borrowers of type I, borrownumber and name
1420
1421 =cut
1422
1423 #'
1424 sub get_institutions {
1425     my $dbh = C4::Context->dbh();
1426     my $sth =
1427       $dbh->prepare(
1428 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1429       );
1430     $sth->execute('I');
1431     my %orgs;
1432     while ( my $data = $sth->fetchrow_hashref() ) {
1433         $orgs{ $data->{'borrowernumber'} } = $data;
1434     }
1435     $sth->finish();
1436     return ( \%orgs );
1437
1438 }    # sub get_institutions
1439
1440 =head2 add_member_orgs
1441
1442   add_member_orgs($borrowernumber,$borrowernumbers);
1443
1444 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1445
1446 =cut
1447
1448 #'
1449 sub add_member_orgs {
1450     my ( $borrowernumber, $otherborrowers ) = @_;
1451     my $dbh   = C4::Context->dbh();
1452     my $query =
1453       "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1454     my $sth = $dbh->prepare($query);
1455     foreach my $otherborrowernumber (@$otherborrowers) {
1456         $sth->execute( $borrowernumber, $otherborrowernumber );
1457     }
1458     $sth->finish();
1459
1460 }    # sub add_member_orgs
1461
1462 =head2 GetCities (OUEST-PROVENCE)
1463
1464   ($id_cityarrayref, $city_hashref) = &GetCities();
1465
1466 Looks up the different city and zip in the database. Returns two
1467 elements: a reference-to-array, which lists the zip city
1468 codes, and a reference-to-hash, which maps the name of the city.
1469 WHERE =>OUEST PROVENCE OR EXTERIEUR
1470
1471 =cut
1472
1473 sub GetCities {
1474
1475     #my ($type_city) = @_;
1476     my $dbh   = C4::Context->dbh;
1477     my $query = qq|SELECT cityid,city_zipcode,city_name 
1478                 FROM cities 
1479                 ORDER BY city_name|;
1480     my $sth = $dbh->prepare($query);
1481
1482     #$sth->execute($type_city);
1483     $sth->execute();
1484     my %city;
1485     my @id;
1486     #    insert empty value to create a empty choice in cgi popup
1487     push @id, " ";
1488     $city{""} = "";
1489     while ( my $data = $sth->fetchrow_hashref ) {
1490         push @id, $data->{'city_zipcode'}."|".$data->{'city_name'};
1491         $city{ $data->{'city_zipcode'}."|".$data->{'city_name'} } = $data->{'city_name'};
1492     }
1493
1494 #test to know if the table contain some records if no the function return nothing
1495     my $id = @id;
1496     $sth->finish;
1497     if ( $id eq 0 ) {
1498         return ();
1499     }
1500     else {
1501         unshift( @id, "" );
1502         return ( \@id, \%city );
1503     }
1504 }
1505
1506 =head2 GetSortDetails (OUEST-PROVENCE)
1507
1508   ($lib) = &GetSortDetails($category,$sortvalue);
1509
1510 Returns the authorized value  details
1511 C<&$lib>return value of authorized value details
1512 C<&$sortvalue>this is the value of authorized value 
1513 C<&$category>this is the value of authorized value category
1514
1515 =cut
1516
1517 sub GetSortDetails {
1518     my ( $category, $sortvalue ) = @_;
1519     my $dbh   = C4::Context->dbh;
1520     my $query = qq|SELECT lib 
1521                 FROM authorised_values 
1522                 WHERE category=?
1523                 AND authorised_value=? |;
1524     my $sth = $dbh->prepare($query);
1525     $sth->execute( $category, $sortvalue );
1526     my $lib = $sth->fetchrow;
1527     return ($lib);
1528 }
1529
1530 =head2 DeleteBorrower 
1531
1532   () = &DeleteBorrower($member);
1533
1534 delete all data fo borrowers and add record to deletedborrowers table
1535 C<&$member>this is the borrowernumber
1536
1537 =cut
1538
1539 sub MoveMemberToDeleted {
1540     my ($member) = @_;
1541     my $dbh = C4::Context->dbh;
1542     my $query;
1543     $query = qq|SELECT * 
1544                   FROM borrowers 
1545                   WHERE borrowernumber=?|;
1546     my $sth = $dbh->prepare($query);
1547     $sth->execute($member);
1548     my @data = $sth->fetchrow_array;
1549     $sth->finish;
1550     $sth =
1551       $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1552           . ( "?," x ( scalar(@data) - 1 ) )
1553           . "?)" );
1554     $sth->execute(@data);
1555     $sth->finish;
1556 }
1557
1558 =head2 DelMember
1559
1560 DelMember($borrowernumber);
1561
1562 This function remove directly a borrower whitout writing it on deleteborrower.
1563 + Deletes reserves for the borrower
1564
1565 =cut
1566
1567 sub DelMember {
1568     my $dbh            = C4::Context->dbh;
1569     my $borrowernumber = shift;
1570         warn "in delmember with $borrowernumber";
1571     return unless $borrowernumber;    # borrowernumber is mandatory.
1572
1573     my $query = qq|DELETE 
1574                   FROM  reserves 
1575                   WHERE borrowernumber=?|;
1576     my $sth = $dbh->prepare($query);
1577     $sth->execute($borrowernumber);
1578     $sth->finish;
1579     $query = "
1580        DELETE
1581        FROM borrowers
1582        WHERE borrowernumber = ?
1583    ";
1584     $sth = $dbh->prepare($query);
1585     $sth->execute($borrowernumber);
1586     $sth->finish;
1587     &logaction(C4::Context->userenv->{'number'},"MEMBERS","DELETE",$borrowernumber,"") 
1588         if C4::Context->preference("BorrowersLog");
1589     return $sth->rows;
1590 }
1591
1592 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1593
1594         $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1595
1596 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1597 Returns ISO date.
1598
1599 =cut
1600
1601 sub ExtendMemberSubscriptionTo {
1602     my ( $borrowerid,$date) = @_;
1603     my $dbh = C4::Context->dbh;
1604     my $borrower = GetMember($borrowerid,'borrowernumber');
1605     unless ($date){
1606       $date=POSIX::strftime("%Y-%m-%d",localtime());
1607       my $borrower = GetMember($borrowerid,'borrowernumber');
1608       $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1609     }
1610     my $sth = $dbh->do(<<EOF);
1611 UPDATE borrowers 
1612 SET  dateexpiry='$date' 
1613 WHERE borrowernumber='$borrowerid'
1614 EOF
1615     # add enrolmentfee if needed
1616     $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1617     $sth->execute($borrower->{'categorycode'});
1618     my ($enrolmentfee) = $sth->fetchrow;
1619     if ($enrolmentfee) {
1620         # insert fee in patron debts
1621         manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1622     }
1623     return $date if ($sth);
1624     return 0;
1625 }
1626
1627 =head2 GetRoadTypes (OUEST-PROVENCE)
1628
1629   ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1630
1631 Looks up the different road type . Returns two
1632 elements: a reference-to-array, which lists the id_roadtype
1633 codes, and a reference-to-hash, which maps the road type of the road .
1634
1635 =cut
1636
1637 sub GetRoadTypes {
1638     my $dbh   = C4::Context->dbh;
1639     my $query = qq|
1640 SELECT roadtypeid,road_type 
1641 FROM roadtype 
1642 ORDER BY road_type|;
1643     my $sth = $dbh->prepare($query);
1644     $sth->execute();
1645     my %roadtype;
1646     my @id;
1647
1648     #    insert empty value to create a empty choice in cgi popup
1649
1650     while ( my $data = $sth->fetchrow_hashref ) {
1651
1652         push @id, $data->{'roadtypeid'};
1653         $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1654     }
1655
1656 #test to know if the table contain some records if no the function return nothing
1657     my $id = @id;
1658     $sth->finish;
1659     if ( $id eq 0 ) {
1660         return ();
1661     }
1662     else {
1663         unshift( @id, "" );
1664         return ( \@id, \%roadtype );
1665     }
1666 }
1667
1668
1669
1670 =head2 GetTitles (OUEST-PROVENCE)
1671
1672   ($borrowertitle)= &GetTitles();
1673
1674 Looks up the different title . Returns array  with all borrowers title
1675
1676 =cut
1677
1678 sub GetTitles {
1679     my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1680     unshift( @borrowerTitle, "" );
1681     return ( \@borrowerTitle);
1682     }
1683
1684
1685
1686 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1687
1688   ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1689
1690 Returns the description of roadtype
1691 C<&$roadtype>return description of road type
1692 C<&$roadtypeid>this is the value of roadtype s
1693
1694 =cut
1695
1696 sub GetRoadTypeDetails {
1697     my ($roadtypeid) = @_;
1698     my $dbh          = C4::Context->dbh;
1699     my $query        = qq|
1700 SELECT road_type 
1701 FROM roadtype 
1702 WHERE roadtypeid=?|;
1703     my $sth = $dbh->prepare($query);
1704     $sth->execute($roadtypeid);
1705     my $roadtype = $sth->fetchrow;
1706     return ($roadtype);
1707 }
1708
1709 =head2 GetBorrowersWhoHaveNotBorrowedSince
1710
1711 &GetBorrowersWhoHaveNotBorrowedSince($date)
1712
1713 this function get all borrowers who haven't borrowed since the date given on input arg.
1714
1715 =cut
1716
1717 sub GetBorrowersWhoHaveNotBorrowedSince {
1718     my $date = shift;
1719     return unless $date;    # date is mandatory.
1720     my $dbh   = C4::Context->dbh;
1721     my $query = "
1722         SELECT borrowers.borrowernumber,max(timestamp)
1723         FROM   borrowers
1724           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1725         WHERE issues.borrowernumber IS NOT NULL
1726         GROUP BY borrowers.borrowernumber
1727    ";
1728     my $sth = $dbh->prepare($query);
1729     $sth->execute;
1730     my @results;
1731
1732     while ( my $data = $sth->fetchrow_hashref ) {
1733         push @results, $data;
1734     }
1735     return \@results;
1736 }
1737
1738 =head2 GetBorrowersWhoHaveNeverBorrowed
1739
1740 $results = &GetBorrowersWhoHaveNeverBorrowed
1741
1742 this function get all borrowers who have never borrowed.
1743
1744 I<$result> is a ref to an array which all elements are a hasref.
1745
1746 =cut
1747
1748 sub GetBorrowersWhoHaveNeverBorrowed {
1749     my $dbh   = C4::Context->dbh;
1750     my $query = "
1751         SELECT borrowers.borrowernumber,max(timestamp)
1752         FROM   borrowers
1753           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1754         WHERE issues.borrowernumber IS NULL
1755    ";
1756     my $sth = $dbh->prepare($query);
1757     $sth->execute;
1758     my @results;
1759     while ( my $data = $sth->fetchrow_hashref ) {
1760         push @results, $data;
1761     }
1762     return \@results;
1763 }
1764
1765 =head2 GetBorrowersWithIssuesHistoryOlderThan
1766
1767 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1768
1769 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1770
1771 I<$result> is a ref to an array which all elements are a hashref.
1772 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1773
1774 =cut
1775
1776 sub GetBorrowersWithIssuesHistoryOlderThan {
1777     my $dbh  = C4::Context->dbh;
1778     my $date = shift;
1779     return unless $date;    # date is mandatory.
1780     my $query = "
1781        SELECT count(borrowernumber) as n,borrowernumber
1782        FROM issues
1783        WHERE returndate < ?
1784          AND borrowernumber IS NOT NULL 
1785        GROUP BY borrowernumber
1786    ";
1787     my $sth = $dbh->prepare($query);
1788     $sth->execute($date);
1789     my @results;
1790
1791     while ( my $data = $sth->fetchrow_hashref ) {
1792         push @results, $data;
1793     }
1794     return \@results;
1795 }
1796
1797 END { }    # module clean-up code here (global destructor)
1798
1799 1;
1800
1801 __END__
1802
1803 =back
1804
1805 =head1 AUTHOR
1806
1807 Koha Team
1808
1809 =cut