Member enrolment fee fixed :
[srvgit] / C4 / Members.pm
index 4f3d692..5224b2e 100644 (file)
@@ -17,7 +17,6 @@ package C4::Members;
 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
 # Suite 330, Boston, MA  02111-1307 USA
 
-# $Id$
 
 use strict;
 require Exporter;
@@ -28,10 +27,14 @@ use Date::Calc qw/Today Add_Delta_YM/;
 use C4::Log; # logaction
 use C4::Overdues;
 use C4::Reserves;
+use C4::Accounts;
 
-our ($VERSION,@ISA,@EXPORT,@EXPORT_OK);
+our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
 
-$VERSION = do { my @v = '$Revision$' =~ /\d+/g; shift(@v) . "." . join( "_", map { sprintf "%03d", $_ } @v ); };
+BEGIN {
+       $VERSION = 3.01;
+       $debug = $ENV{DEBUG} || 0;
+}
 
 =head1 NAME
 
@@ -113,6 +116,7 @@ push @EXPORT, qw(
 push @EXPORT, qw(
   &checkuniquemember 
   &checkuserpassword
+       &Check_Userid
   &fixEthnicity
   &ethnicitycategories 
   &fixup_cardnumber
@@ -121,7 +125,7 @@ push @EXPORT, qw(
 
 =item SearchMember
 
-  ($count, $borrowers) = &SearchMember($searchstring, $type,$category_type);
+  ($count, $borrowers) = &SearchMember($searchstring, $type,$category_type,$filter,$showallbranches);
 
 Looks up patrons (borrowers) by name.
 
@@ -136,6 +140,10 @@ C<$searchstring> is a space-separated list of search terms. Each term
 must match the beginning a borrower's surname, first name, or other
 name.
 
+C<$filter> is assumed to be a list of elements to filter results on
+
+C<$showallbranches> is used in IndependantBranches Context to display all branches results.
+
 C<&SearchMember> returns a two-element list. C<$borrowers> is a
 reference-to-array; each element is a reference-to-hash, whose keys
 are the fields of the C<borrowers> table in the Koha database.
@@ -145,62 +153,82 @@ C<$count> is the number of elements in C<$borrowers>.
 
 #'
 #used by member enquiries from the intranet
-#called by member.pl
+#called by member.pl and circ/circulation.pl
 sub SearchMember {
-    my ($searchstring, $orderby, $type,$category_type ) = @_;
-    my $dbh   = C4::Context->dbh;
-    my $query = "";
-    my $count;
-    my @data;
-    my @bind = ();
+       my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
+       my $dbh   = C4::Context->dbh;
+       my $query = "";
+       my $count;
+       my @data;
+       my @bind = ();
+       
+       # this is used by circulation everytime a new borrowers cardnumber is scanned
+       # so we can check an exact match first, if that works return, otherwise do the rest
+       $query = "SELECT * FROM borrowers
+               LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
+               ";
+       my $sth = $dbh->prepare("$query WHERE cardnumber = ?");
+       $sth->execute($searchstring);
+       my $data = $sth->fetchall_arrayref({});
+       if (@$data){
+               return ( scalar(@$data), $data );
+       }
+    $sth->finish;
 
     if ( $type eq "simple" )    # simple search for one letter only
     {
-        $query =
-          "SELECT * FROM borrowers
-                  LEFT JOIN categories ON borrowers.categorycode=categories.categorycode ".
-                  ($category_type?" AND category_type = ".$dbh->quote($category_type):"").
-                  " WHERE surname LIKE ? OR cardnumber like ? ORDER BY $orderby";
+        $query .= ($category_type ? " AND category_type = ".$dbh->quote($category_type) : ""); 
+        $query .= " WHERE (surname LIKE ? OR cardnumber like ?) ";
+        if (C4::Context->preference("IndependantBranches") && !$showallbranches){
+          if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
+            $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
+          }
+        }
+        $query.=" ORDER BY $orderby";
         @bind = ("$searchstring%","$searchstring");
     }
     else    # advanced search looking in surname, firstname and othernames
     {
         @data  = split( ' ', $searchstring );
         $count = @data;
-        $query = "SELECT * FROM borrowers
-                    LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
-               WHERE ((surname LIKE ? OR surname LIKE ?
-               OR firstname  LIKE ? OR firstname LIKE ?
-               OR othernames LIKE ? OR othernames LIKE ?)
-               ".
-                  ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
-        @bind = (
-            "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
-            "$data[0]%", "% $data[0]%"
-        );
-        for ( my $i = 1 ; $i < $count ; $i++ ) {
-            $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
-                        OR firstname  LIKE ? OR firstname LIKE ?
-                       OR othernames LIKE ? OR othernames LIKE ?)";
-            push( @bind,
-                "$data[$i]%",   "% $data[$i]%", "$data[$i]%",
-                "% $data[$i]%", "$data[$i]%",   "% $data[$i]%" );
-
-            # FIXME - .= <<EOT;
-        }
-        $query = $query . ") OR cardnumber LIKE ?
+        $query .= " WHERE ";
+        if (C4::Context->preference("IndependantBranches") && !$showallbranches){
+          if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
+            $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
+          }      
+               }     
+               $query.="((surname LIKE ? OR surname LIKE ?
+                               OR firstname  LIKE ? OR firstname LIKE ?
+                               OR othernames LIKE ? OR othernames LIKE ?)
+               " .
+               ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
+               @bind = (
+                       "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
+                       "$data[0]%", "% $data[0]%"
+               );
+               for ( my $i = 1 ; $i < $count ; $i++ ) {
+                       $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
+                               OR firstname  LIKE ? OR firstname LIKE ?
+                               OR othernames LIKE ? OR othernames LIKE ?)";
+                       push( @bind,
+                               "$data[$i]%",   "% $data[$i]%", "$data[$i]%",
+                               "% $data[$i]%", "$data[$i]%",   "% $data[$i]%" );
+
+                       # FIXME - .= <<EOT;
+               }
+               $query = $query . ") OR cardnumber LIKE ?
                order by $orderby";
-        push( @bind, $searchstring );
+               push( @bind, $searchstring );
 
-        # FIXME - .= <<EOT;
+               # FIXME - .= <<EOT;
     }
 
-    my $sth = $dbh->prepare($query);
+    $sth = $dbh->prepare($query);
 
-    #  warn "Q $orderby : $query";
+       $debug and print STDERR "Q $orderby : $query\n";
     $sth->execute(@bind);
     my @results;
-    my $data = $sth->fetchall_arrayref({});
+    $data = $sth->fetchall_arrayref({});
 
     $sth->finish;
     return ( scalar(@$data), $data );
@@ -308,11 +336,11 @@ sub GetMemberDetails {
     my $query;
     my $sth;
     if ($borrowernumber) {
-        $sth = $dbh->prepare("select * from borrowers where borrowernumber=?");
+        $sth = $dbh->prepare("select borrowers.*,category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where  borrowernumber=?");
         $sth->execute($borrowernumber);
     }
     elsif ($cardnumber) {
-        $sth = $dbh->prepare("select * from borrowers where cardnumber=?");
+        $sth = $dbh->prepare("select borrowers.*,category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?");
         $sth->execute($cardnumber);
     }
     else {
@@ -321,6 +349,7 @@ sub GetMemberDetails {
     my $borrower = $sth->fetchrow_hashref;
     my ($amount) = GetMemberAccountRecords( $borrowernumber);
     $borrower->{'amountoutstanding'} = $amount;
+       # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
     my $flags = patronflags( $borrower);
     my $accessflagshash;
 
@@ -378,7 +407,7 @@ sub GetMemberDetails {
         {itemlist}    ref-to-array: list of available items
 
 =cut
-
+# FIXME rename this function.
 sub patronflags {
     my %flags;
     my ( $patroninformation) = @_;
@@ -388,6 +417,7 @@ sub patronflags {
         my %flaginfo;
         my $noissuescharge = C4::Context->preference("noissuescharge");
         $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
+               $flaginfo{'amount'} = sprintf "%.02f",$amount;
         if ( $amount > $noissuescharge ) {
             $flaginfo{'noissues'} = 1;
         }
@@ -441,7 +471,7 @@ sub patronflags {
         }
         $flags{'ODUES'} = \%flaginfo;
     }
-    my @itemswaiting = GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
+    my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
     my $nowaiting = scalar @itemswaiting;
     if ( $nowaiting > 0 ) {
         my %flaginfo;
@@ -473,40 +503,30 @@ sub GetMember {
     my ( $information, $type ) = @_;
     my $dbh = C4::Context->dbh;
     my $sth;
-    if ($type eq 'cardnumber' || $type eq 'firstname'|| $type eq 'userid'|| $type eq 'borrowernumber'){
-      $information = uc $information;
-      $sth =
-          $dbh->prepare(
-"Select borrowers.*,categories.category_type,categories.description  from borrowers left join categories on borrowers.categorycode=categories.categorycode where $type=?"
-          );
-        $sth->execute($information);
-    }
-    else {
-        $sth =
-          $dbh->prepare(
-"Select borrowers.*,categories.category_type, categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?"
-          );
-        $sth->execute($information);
-    }
+       my $select = "
+SELECT borrowers.*, categories.category_type, categories.description
+FROM borrowers 
+LEFT JOIN categories on borrowers.categorycode=categories.categorycode 
+";
+       if ($type eq 'cardnumber' || $type eq 'firstname'|| $type eq 'userid'|| $type eq 'borrowernumber'){
+               $information = uc $information;
+               $sth = $dbh->prepare("$select WHERE $type=?");
+    } else {
+               $sth = $dbh->prepare("$select WHERE borrowernumber=?");
+       }
+    $sth->execute($information);
     my $data = $sth->fetchrow_hashref;
-
     $sth->finish;
-    if ($data) {
-        return ($data);
-    }
-    elsif ($type eq 'cardnumber' ||$type eq 'firstname') {    # try with firstname
-        my $sth =
-              $dbh->prepare(
-"Select borrowers.*,categories.category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode  where firstname like ?"
-            );
-            $sth->execute($information);
-            my $data = $sth->fetchrow_hashref;
-            $sth->finish;
-            return ($data);
-    }
-    else {
-        return undef;        
+    ($data) and return ($data);
+
+    if ($type eq 'cardnumber' || $type eq 'firstname') {    # otherwise, try with firstname
+               $sth = $dbh->prepare("$select WHERE firstname like ?");
+               $sth->execute($information);
+               $data = $sth->fetchrow_hashref;
+               $sth->finish;
+               return ($data);
     }
+       return undef;        
 }
 
 =item GetMemberIssuesAndFines
@@ -531,7 +551,7 @@ sub GetMemberIssuesAndFines {
       "Select count(*) from issues where borrowernumber='$borrowernumber' and
     returndate is NULL";
 
-    # print $query;
+    $debug and print $query, "\n";
     my $sth = $dbh->prepare($query);
     $sth->execute;
     my $data = $sth->fetchrow_hashref;
@@ -569,54 +589,41 @@ Modify borrower's data
 sub ModMember {
     my (%data) = @_;
     my $dbh = C4::Context->dbh;
-    $data{'dateofbirth'}  = format_date_in_iso( $data{'dateofbirth'} ) if ($data{'dateofbirth'} );
-    $data{'dateexpiry'}   = format_date_in_iso( $data{'dateexpiry'} ) if ($data{'dateexpiry'} );
+    $data{'dateofbirth'}  = format_date_in_iso( $data{'dateofbirth' } ) if ($data{'dateofbirth' } );
+    $data{'dateexpiry'}   = format_date_in_iso( $data{ 'dateexpiry' } ) if ($data{ 'dateexpiry' } );
     $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'} ) if ($data{'dateenrolled'} );
-#     warn Data::Dumper::Dumper(%data);
-    #   warn "num user".$data{'borrowernumber'};
     my $qborrower=$dbh->prepare("SHOW columns from borrowers");
     $qborrower->execute;
     my %hashborrowerfields;  
     while (my ($field)=$qborrower->fetchrow){
       $hashborrowerfields{$field}=1;
     }  
-    my $query;
+    my $query = "UPDATE borrowers SET \n";
     my $sth;
-    $data{'userid'} = '' if ( $data{'password'} eq '' );  
     my @parameters;  
     
-    # test to know if u must update or not the borrower password
+    # test to know if you must update or not the borrower password
     if ( $data{'password'} eq '****' ) {
         delete $data{'password'};
-        foreach (keys %data)
-        {push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne "borrowernumber" and $hashborrowerfields{$_}) } ;
-        $query = "UPDATE borrowers SET ".join (",",@parameters)
-    ." WHERE borrowernumber=$data{'borrowernumber'}";
-#         warn "$query";
-        $sth = $dbh->prepare($query);
-        $sth->execute;
-    }
-    else {
-        $data{'password'} = md5_base64( $data{'password'} )   if ( $data{'password'} ne '' );
+    } else {
+        $data{'password'} = md5_base64( $data{'password'} )  if ($data{'password'} ne "");
         delete $data{'password'} if ($data{password} eq "");
-        foreach (keys %data)
-        {push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne "borrowernumber" and $hashborrowerfields{$_})} ;
-        
-        $query = "UPDATE borrowers SET ".join (",",@parameters)." WHERE borrowernumber=$data{'borrowernumber'}";
-#         warn "$query";
-        $sth = $dbh->prepare($query);
-        $sth->execute;
     }
-    $sth->finish;
+       foreach (keys %data)
+       { push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne 'borrowernumber' and $_ ne 'flags' and $hashborrowerfields{$_}); }
+    $query .= join (',',@parameters) . "\n WHERE borrowernumber=? \n";
+       $debug and print STDERR "$query (executed w/ arg: $data{'borrowernumber'})";
+       $sth = $dbh->prepare($query);
+       $sth->execute($data{'borrowernumber'});
+       $sth->finish;
 
 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
 # so when we update information for an adult we should check for guarantees and update the relevant part
 # of their records, ie addresses and phone numbers
     my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
-    if ( $borrowercategory->{'category_type'} eq 'A' ) {
+    if ( $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
         # is adult check guarantees;
         UpdateGuarantees(%data);
-
     }
     &logaction(C4::Context->userenv->{'number'},"MEMBERS","MODIFY",$data{'borrowernumber'},"") 
         if C4::Context->preference("BorrowersLog");
@@ -640,116 +647,97 @@ sub AddMember {
     my $dbh = C4::Context->dbh;
     $data{'userid'} = '' unless $data{'password'};
     $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
-    $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} );
-    $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'} );
-    $data{'dateexpiry'}   = format_date_in_iso( $data{'dateexpiry'} );
+    $data{'dateofbirth'}  = format_date_in_iso( $data{'dateofbirth'} );
+    $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'});
+    $data{'dateexpiry'}   = format_date_in_iso( $data{'dateexpiry'}  );
+       # This query should be rewritten to use "?" at execute.
     my $query =
-        "insert into borrowers set cardnumber="
-      . $dbh->quote( $data{'cardnumber'} )
-      . ",surname="
-      . $dbh->quote( $data{'surname'} )
-      . ",firstname="
-      . $dbh->quote( $data{'firstname'} )
-      . ",title="
-      . $dbh->quote( $data{'title'} )
-      . ",othernames="
-      . $dbh->quote( $data{'othernames'} )
-      . ",initials="
-      . $dbh->quote( $data{'initials'} )
-      . ",streetnumber="
-      . $dbh->quote( $data{'streetnumber'} )
-      . ",streettype="
-      . $dbh->quote( $data{'streettype'} )
-      . ",address="
-      . $dbh->quote( $data{'address'} )
-      . ",address2="
-      . $dbh->quote( $data{'address2'} )
-      . ",zipcode="
-      . $dbh->quote( $data{'zipcode'} )
-      . ",city="
-      . $dbh->quote( $data{'city'} )
-      . ",phone="
-      . $dbh->quote( $data{'phone'} )
-      . ",email="
-      . $dbh->quote( $data{'email'} )
-      . ",mobile="
-      . $dbh->quote( $data{'mobile'} )
-      . ",phonepro="
-      . $dbh->quote( $data{'phonepro'} )
-      . ",opacnote="
-      . $dbh->quote( $data{'opacnote'} )
-      . ",guarantorid="
-      . $dbh->quote( $data{'guarantorid'} )
-      . ",dateofbirth="
-      . $dbh->quote( $data{'dateofbirth'} )
-      . ",branchcode="
-      . $dbh->quote( $data{'branchcode'} )
-      . ",categorycode="
-      . $dbh->quote( $data{'categorycode'} )
-      . ",dateenrolled="
-      . $dbh->quote( $data{'dateenrolled'} )
-      . ",contactname="
-      . $dbh->quote( $data{'contactname'} )
-      . ",borrowernotes="
-      . $dbh->quote( $data{'borrowernotes'} )
-      . ",dateexpiry="
-      . $dbh->quote( $data{'dateexpiry'} )
-      . ",contactnote="
-      . $dbh->quote( $data{'contactnote'} )
-      . ",B_address="
-      . $dbh->quote( $data{'B_address'} )
-      . ",B_zipcode="
-      . $dbh->quote( $data{'B_zipcode'} )
-      . ",B_city="
-      . $dbh->quote( $data{'B_city'} )
-      . ",B_phone="
-      . $dbh->quote( $data{'B_phone'} )
-      . ",B_email="
-      . $dbh->quote( $data{'B_email'}, )
-      . ",password="
-      . $dbh->quote( $data{'password'} )
-      . ",userid="
-      . $dbh->quote( $data{'userid'} )
-      . ",sort1="
-      . $dbh->quote( $data{'sort1'} )
-      . ",sort2="
-      . $dbh->quote( $data{'sort2'} )
-      . ",contacttitle="
-      . $dbh->quote( $data{'contacttitle'} )
-      . ",emailpro="
-      . $dbh->quote( $data{'emailpro'} )
-      . ",contactfirstname="
-      . $dbh->quote( $data{'contactfirstname'} ) . ",sex="
-      . $dbh->quote( $data{'sex'} ) . ",fax="
-      . $dbh->quote( $data{'fax'} )
-      . ",relationship="
-      . $dbh->quote( $data{'relationship'} )
-      . ",B_streetnumber="
-      . $dbh->quote( $data{'B_streetnumber'} )
-      . ",B_streettype="
-      . $dbh->quote( $data{'B_streettype'} )
-      . ",gonenoaddress="
-      . $dbh->quote( $data{'gonenoaddress'} )
-      . ",lost="
-      . $dbh->quote( $data{'lost'} )
-      . ",debarred="
-      . $dbh->quote( $data{'debarred'} )
-      . ",ethnicity="
-      . $dbh->quote( $data{'ethnicity'} )
-      . ",ethnotes="
-      . $dbh->quote( $data{'ethnotes'} );
-
+        "insert into borrowers set cardnumber=" . $dbh->quote( $data{'cardnumber'} )
+      . ",surname="    . $dbh->quote( $data{'surname'} )
+      . ",firstname="  . $dbh->quote( $data{'firstname'} )
+      . ",title="              . $dbh->quote( $data{'title'} )
+      . ",othernames="         . $dbh->quote( $data{'othernames'} )
+      . ",initials="   . $dbh->quote( $data{'initials'} )
+      . ",streetnumber=". $dbh->quote( $data{'streetnumber'} )
+      . ",streettype="         . $dbh->quote( $data{'streettype'} )
+      . ",address="    . $dbh->quote( $data{'address'} )
+      . ",address2="   . $dbh->quote( $data{'address2'} )
+      . ",zipcode="    . $dbh->quote( $data{'zipcode'} )
+      . ",city="               . $dbh->quote( $data{'city'} )
+      . ",phone="              . $dbh->quote( $data{'phone'} )
+      . ",email="              . $dbh->quote( $data{'email'} )
+      . ",mobile="             . $dbh->quote( $data{'mobile'} )
+      . ",phonepro="   . $dbh->quote( $data{'phonepro'} )
+      . ",opacnote="   . $dbh->quote( $data{'opacnote'} )
+      . ",guarantorid=" . $dbh->quote( $data{'guarantorid'} )
+      . ",dateofbirth=" . $dbh->quote( $data{'dateofbirth'} )
+      . ",branchcode="         . $dbh->quote( $data{'branchcode'} )
+      . ",categorycode=" . $dbh->quote( $data{'categorycode'} )
+      . ",dateenrolled=" . $dbh->quote( $data{'dateenrolled'} )
+      . ",contactname=" . $dbh->quote( $data{'contactname'} )
+      . ",borrowernotes=" . $dbh->quote( $data{'borrowernotes'} )
+      . ",dateexpiry="         . $dbh->quote( $data{'dateexpiry'} )
+      . ",contactnote=" . $dbh->quote( $data{'contactnote'} )
+      . ",B_address="  . $dbh->quote( $data{'B_address'} )
+      . ",B_zipcode="  . $dbh->quote( $data{'B_zipcode'} )
+      . ",B_city="             . $dbh->quote( $data{'B_city'} )
+      . ",B_phone="    . $dbh->quote( $data{'B_phone'} )
+      . ",B_email="    . $dbh->quote( $data{'B_email'} )
+      . ",password="   . $dbh->quote( $data{'password'} )
+      . ",userid="             . $dbh->quote( $data{'userid'} )
+      . ",sort1="              . $dbh->quote( $data{'sort1'} )
+      . ",sort2="              . $dbh->quote( $data{'sort2'} )
+      . ",contacttitle=" . $dbh->quote( $data{'contacttitle'} )
+      . ",emailpro="   . $dbh->quote( $data{'emailpro'} )
+      . ",contactfirstname=" . $dbh->quote( $data{'contactfirstname'} )
+         . ",sex="             . $dbh->quote( $data{'sex'} )
+         . ",fax="             . $dbh->quote( $data{'fax'} )
+      . ",relationship=" . $dbh->quote( $data{'relationship'} )
+      . ",B_streetnumber=" . $dbh->quote( $data{'B_streetnumber'} )
+      . ",B_streettype=" . $dbh->quote( $data{'B_streettype'} )
+      . ",gonenoaddress=" . $dbh->quote( $data{'gonenoaddress'} )
+      . ",lost="               . $dbh->quote( $data{'lost'} )
+      . ",debarred="   . $dbh->quote( $data{'debarred'} )
+      . ",ethnicity="  . $dbh->quote( $data{'ethnicity'} )
+      . ",ethnotes="   . $dbh->quote( $data{'ethnotes'} );
     my $sth = $dbh->prepare($query);
+#      print "Executing SQL: $query\n";
     $sth->execute;
     $sth->finish;
     $data{'borrowernumber'} = $dbh->{'mysql_insertid'};
     
     &logaction(C4::Context->userenv->{'number'},"MEMBERS","CREATE",$data{'borrowernumber'},"") 
         if C4::Context->preference("BorrowersLog");
-        
+    
+    # check for enrollment fee & add it if needed
+    $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
+    $sth->execute($data{'categorycode'});
+    my ($enrolmentfee) = $sth->fetchrow;
+    if ($enrolmentfee) {
+        # insert fee in patron debts
+        manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
+    }
     return $data{'borrowernumber'};
 }
 
+sub Check_Userid {
+       my ($uid,$member) = @_;
+       my $dbh = C4::Context->dbh;
+    # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
+    # Then we need to tell the user and have them create a new one.
+    my $sth =
+      $dbh->prepare(
+        "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
+    $sth->execute( $uid, $member );
+    if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
+        return 0;
+    }
+       else {
+               return 1;
+       }
+}
+
+
 sub changepassword {
     my ( $uid, $member, $digest ) = @_;
     my $dbh = C4::Context->dbh;
@@ -758,9 +746,9 @@ sub changepassword {
 #Then we need to tell the user and have them create a new one.
     my $sth =
       $dbh->prepare(
-        "select * from borrowers where userid=? and borrowernumber != ?");
+        "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
     $sth->execute( $uid, $member );
-    if ( ( $uid ne '' ) && ( $sth->fetchrow ) ) {
+    if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
         return 0;
     }
     else {
@@ -997,11 +985,13 @@ sub GetAllIssues {
     my $dbh   = C4::Context->dbh;
     my $count = 0;
     my $query =
-"Select *,items.timestamp AS itemstimestamp from issues,biblio,items,biblioitems
-  where borrowernumber=? and
-  items.biblioitemnumber=biblioitems.biblioitemnumber and
-  items.itemnumber=issues.itemnumber and
-  items.biblionumber=biblio.biblionumber order by $order";
+  "Select *,items.timestamp AS itemstimestamp from 
+  issues 
+  LEFT JOIN items on items.itemnumber=issues.itemnumber
+  LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
+  LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
+  where borrowernumber=? 
+  order by $order";
     if ( $limit != 0 ) {
         $query .= " limit $limit";
     }
@@ -1021,11 +1011,11 @@ sub GetAllIssues {
     # large chunk of older issues data put into table oldissues
     # to speed up db calls for issuing items
     if ( C4::Context->preference("ReadingHistory") ) {
-        my $query2 = "SELECT * FROM oldissues,biblio,items,biblioitems
+        my $query2 = "SELECT * FROM oldissues
+                      LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
+                      LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
+                      LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
                       WHERE borrowernumber=? 
-                      AND items.biblioitemnumber=biblioitems.biblioitemnumber
-                      AND items.itemnumber=oldissues.itemnumber
-                      AND items.biblionumber=biblio.biblionumber
                       ORDER BY $order";
         if ( $limit != 0 ) {
             $limit = $limit - $count;
@@ -1068,17 +1058,15 @@ sub GetMemberAccountRecords {
     my @acctlines;
     my $numlines = 0;
     my $strsth      = qq(
-SELECT * 
-FROM accountlines 
-WHERE borrowernumber=?);
+                        SELECT * 
+                        FROM accountlines 
+                        WHERE borrowernumber=?);
     my @bind = ($borrowernumber);
     if ($date && $date ne ''){
-    $strsth.="
-AND date < ? ";
-    push(@bind,$date);
+            $strsth.=" AND date < ? ";
+            push(@bind,$date);
     }
-    $strsth.="
-ORDER BY date desc,timestamp DESC";
+    $strsth.=" ORDER BY date desc,timestamp DESC";
     my $sth= $dbh->prepare( $strsth );
     $sth->execute( @bind );
     my $total = 0;
@@ -1112,16 +1100,15 @@ sub GetBorNotifyAcctRecord {
     my $dbh = C4::Context->dbh;
     my @acctlines;
     my $numlines = 0;
-    my $query    = qq| SELECT * 
-                       FROM accountlines 
-                       WHERE borrowernumber=? 
-                       AND notify_id=? 
-                       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')
-                       AND amountoutstanding != '0' 
-                       ORDER BY notify_id,accounttype
-               |;
-    my $sth = $dbh->prepare($query);
-
+    my $sth = $dbh->prepare(
+            "SELECT * 
+                FROM accountlines 
+                WHERE borrowernumber=? 
+                    AND notify_id=? 
+                    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')
+                    AND amountoutstanding != '0' 
+                ORDER BY notify_id,accounttype
+                ");
     $sth->execute( $borrowernumber, $notifyid );
     my $total = 0;
     while ( my $data = $sth->fetchrow_hashref ) {
@@ -1185,11 +1172,16 @@ sub checkuniquemember {
 }
 
 sub checkcardnumber {
-       my ($cardnumber) = @_;
+       my ($cardnumber,$borrowernumber) = @_;
        my $dbh = C4::Context->dbh;
        my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
-       my $sth = $dbh->prepare($query);
-       $sth->execute($cardnumber);
+       $query .= " AND borrowernumber <> ?" if ($borrowernumber);
+  my $sth = $dbh->prepare($query);
+  if ($borrowernumber) {
+   $sth->execute($cardnumber,$borrowernumber);
+  } else { 
+        $sth->execute($cardnumber);
+  } 
        if (my $data= $sth->fetchrow_hashref()){
                return 1;
        }
@@ -1478,7 +1470,7 @@ sub GetCities {
 
     #my ($type_city) = @_;
     my $dbh   = C4::Context->dbh;
-    my $query = qq|SELECT cityid,city_name 
+    my $query = qq|SELECT cityid,city_zipcode,city_name 
                FROM cities 
                ORDER BY city_name|;
     my $sth = $dbh->prepare($query);
@@ -1487,13 +1479,12 @@ sub GetCities {
     $sth->execute();
     my %city;
     my @id;
-
     #    insert empty value to create a empty choice in cgi popup
-
+    push @id, " ";
+    $city{""} = "";
     while ( my $data = $sth->fetchrow_hashref ) {
-
-        push @id, $data->{'cityid'};
-        $city{ $data->{'cityid'} } = $data->{'city_name'};
+        push @id, $data->{'city_zipcode'}."|".$data->{'city_name'};
+        $city{ $data->{'city_zipcode'}."|".$data->{'city_name'} } = $data->{'city_name'};
     }
 
 #test to know if the table contain some records if no the function return nothing