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