CleanBorrowers fixing.
[koha_gimpoz] / C4 / Circulation.pm
old mode 100755 (executable)
new mode 100644 (file)
index ebe2e11..0add08e
@@ -17,38 +17,81 @@ package C4::Circulation;
 # 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;
 use C4::Context;
 use C4::Stats;
-use C4::Reserves2;
+use C4::Reserves;
 use C4::Koha;
 use C4::Biblio;
-use C4::Accounts;
-use C4::Reserves2;
+use C4::Items;
 use C4::Members;
-use C4::Date;
+use C4::Dates;
+use C4::Calendar;
+use C4::Accounts;
 use Date::Calc qw(
   Today
   Today_and_Now
   Add_Delta_YM
   Add_Delta_DHMS
   Date_to_Days
+  Day_of_Week
+  Add_Delta_Days       
 );
 use POSIX qw(strftime);
 use C4::Branch; # GetBranches
 use C4::Log; # logaction
 
+use Data::Dumper;
+
 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
 
-# set the version for version checking
-$VERSION = do { my @v = '$Revision$' =~ /\d+/g; shift(@v).".".join( "_", map { sprintf "%03d", $_ } @v ); };
+BEGIN {
+       # set the version for version checking
+       $VERSION = 3.01;
+       @ISA    = qw(Exporter);
+
+       # FIXME subs that should probably be elsewhere
+       push @EXPORT, qw(
+               &FixOverduesOnReturn
+               &barcodedecode
+       );
+
+       # subs to deal with issuing a book
+       push @EXPORT, qw(
+               &CanBookBeIssued
+               &CanBookBeRenewed
+               &AddIssue
+               &AddRenewal
+               &GetRenewCount
+               &GetItemIssue
+               &GetItemIssues
+               &GetBorrowerIssues
+               &GetIssuingCharges
+               &GetBiblioIssues
+               &AnonymiseIssueHistory
+       );
+
+       # subs to deal with returns
+       push @EXPORT, qw(
+               &AddReturn
+        &MarkIssueReturned
+       );
+
+       # subs to deal with transfers
+       push @EXPORT, qw(
+               &transferbook
+               &GetTransfers
+               &GetTransfersFromTo
+               &updateWrongTransfer
+               &DeleteTransfer
+       );
+}
 
 =head1 NAME
 
-C4::Circulation::Circ2 - Koha circulation module
+C4::Circulation - Koha circulation module
 
 =head1 SYNOPSIS
 
@@ -62,47 +105,42 @@ Also deals with stocktaking.
 
 =head1 FUNCTIONS
 
-=cut
+=head2 decode
 
-@ISA    = qw(Exporter);
+=head3 $str = &decode($chunk);
 
-# FIXME subs that should probably be elsewhere
-push @EXPORT, qw(
-  &fixoverduesonreturn
-);
+=over 4
 
-# subs to deal with issuing a book
-push @EXPORT, qw(
-  &CanBookBeIssued
-  &CanBookBeRenewed
-  &AddIssue
-  &AddRenewal
-  &GetItemIssue
-  &GetItemIssues
-  &GetBorrowerIssues
-  &GetIssuingCharges
-  &GetBiblioIssues
-  &AnonymiseIssueHistory
-);
-# subs to deal with returns
-push @EXPORT, qw(
-  &AddReturn
-);
+=item Generic filter function for barcode string.
 
-# subs to deal with transfers
-push @EXPORT, qw(
-  &transferbook
-  &GetTransfers
-  &GetTransfersFromTo
-  &updateWrongTransfer
-  &DeleteTransfer
-);
+=back
 
-# subs to remove
-push @EXPORT, qw(
-  &decode
-  &dotransfer
-);
+=cut
+
+# FIXME From Paul : i don't understand what this sub does & why it has to be called on every circ. Speak of this with chris maybe ?
+# FIXME -- the &decode fcn below should be wrapped into this one.
+
+sub barcodedecode {
+    my ($barcode) = @_;
+    my $filter = C4::Context->preference('itemBarcodeInputFilter');
+       if($filter eq 'whitespace') {
+               $barcode =~ s/\s//g;
+               return $barcode;
+       } elsif($filter eq 'cuecat') {
+               chomp($barcode);
+           my @fields = split( /\./, $barcode );
+           my @results = map( decode($_), @fields[ 1 .. $#fields ] );
+           if ( $#results == 2 ) {
+               return $results[2];
+           }
+           else {
+               return $barcode;
+           }
+       } elsif($filter eq 'T-prefix') {
+               my $num = ( $barcode =~ /^[Tt] /) ? substr($barcode,2) + 0 : $barcode;
+               return sprintf( "T%07d",$num);
+       }
+}
 
 =head2 decode
 
@@ -117,9 +155,6 @@ returns it.
 
 =cut
 
-# FIXME - At least, I'm pretty sure this is for decoding CueCat stuff.
-
-# FIXME From Paul : i don't understand what this sub does & why it has to be called on every circ. Speak of this with chris maybe ?
 sub decode {
     my ($encoded) = @_;
     my $seq =
@@ -203,7 +238,6 @@ The item was eligible to be transferred. Barring problems communicating with the
 sub transferbook {
     my ( $tbr, $barcode, $ignoreRs ) = @_;
     my $messages;
-    my %env;
     my $dotransfer      = 1;
     my $branches        = GetBranches();
     my $itemnumber = GetItemnumberFromBarcode( $barcode );
@@ -250,65 +284,23 @@ sub transferbook {
 
     #actually do the transfer....
     if ($dotransfer) {
-        dotransfer( $itemnumber, $fbr, $tbr );
+        ModItemTransfer( $itemnumber, $fbr, $tbr );
 
         # don't need to update MARC anymore, we do it in batch now
         $messages->{'WasTransfered'} = 1;
+               ModDateLastSeen( $itemnumber );
     }
     return ( $dotransfer, $messages, $biblio );
 }
 
-# Not exported
-# FIXME - This is only used in &transferbook. Why bother making it a
-# separate function?
-sub dotransfer {
-    my ( $itm, $fbr, $tbr ) = @_;
-    
-    my $dbh = C4::Context->dbh;
-    $itm = $dbh->quote($itm);
-    $fbr = $dbh->quote($fbr);
-    $tbr = $dbh->quote($tbr);
-    
-    #new entry in branchtransfers....
-    $dbh->do(
-"INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
-                    VALUES ($itm, $fbr, now(), $tbr)"
-    );
-
-    #update holdingbranch in items .....
-      $dbh->do(
-          "UPDATE items set holdingbranch = $tbr WHERE items.itemnumber = $itm");
-    &ModDateLastSeen($itm);
-    &domarctransfer( $dbh, $itm );
-    return;
-}
-
-##New sub to dotransfer in marc tables as well. Not exported -TG 10/04/2006
-sub domarctransfer {
-    my ( $dbh, $itemnumber ) = @_;
-    $itemnumber =~ s /\'//g;    ##itemnumber seems to come with quotes-TG
-    my $sth =
-      $dbh->prepare(
-        "select biblionumber,holdingbranch from items where itemnumber=$itemnumber"
-      );
-    $sth->execute();
-    while ( my ( $biblionumber, $holdingbranch ) = $sth->fetchrow ) {
-        &ModItemInMarconefield( $biblionumber, $itemnumber,
-            'items.holdingbranch', $holdingbranch );
-    }
-    return;
-}
-
 =head2 CanBookBeIssued
 
 Check if a book can be issued.
 
-my ($issuingimpossible,$needsconfirmation) = CanBookBeIssued($env,$borrower,$barcode,$year,$month,$day);
+my ($issuingimpossible,$needsconfirmation) = CanBookBeIssued($borrower,$barcode,$year,$month,$day);
 
 =over 4
 
-=item C<$env> Environment variable. Should be empty usually, but used by other subs. Next code cleaning could drop it.
-
 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
 
 =item C<$barcode> is the bar code of the book being issued.
@@ -388,150 +380,153 @@ if the borrower borrows to much things
 =cut
 
 # check if a book can be issued.
-# returns an array with errors if any
 
-sub TooMany ($$) {
+
+sub TooMany {
     my $borrower        = shift;
     my $biblionumber = shift;
+       my $item                = shift;
     my $cat_borrower    = $borrower->{'categorycode'};
-    my $branch_borrower = $borrower->{'branchcode'};
     my $dbh             = C4::Context->dbh;
-
-    my $sth =
-      $dbh->prepare('select itemtype from biblioitems where biblionumber = ?');
-    $sth->execute($biblionumber);
-    my $type = $sth->fetchrow;
-    $sth =
+       my $branch;
+       # Get which branchcode we need
+       if (C4::Context->preference('CircControl') eq 'PickupLibrary'){
+               $branch = C4::Context->userenv->{'branch'}; 
+       }
+       elsif (C4::Context->preference('CircControl') eq 'PatronLibrary'){
+        $branch = $borrower->{'branchcode'}; 
+       }
+       else {
+               # items home library
+               $branch = $item->{'homebranch'};
+       }
+       my $type = (C4::Context->preference('item-level_itypes')) 
+                       ? $item->{'itype'}         # item-level
+                       : $item->{'itemtype'};     # biblio-level
+  
+       my $sth =
       $dbh->prepare(
-'select * from issuingrules where categorycode = ? and itemtype = ? and branchcode = ?'
+                'SELECT * FROM issuingrules 
+                        WHERE categorycode = ? 
+                            AND itemtype = ? 
+                            AND branchcode = ?'
       );
 
-#     my $sth2 = $dbh->prepare("select COUNT(*) from issues i, biblioitems s where i.borrowernumber = ? and i.returndate is null and i.itemnumber = s.biblioitemnumber and s.itemtype like ?");
-    my $sth2 =
-      $dbh->prepare(
-"select COUNT(*) from issues i, biblioitems s1, items s2 where i.borrowernumber = ? and i.returndate is null and i.itemnumber = s2.itemnumber and s1.itemtype like ? and s1.biblioitemnumber = s2.biblioitemnumber"
-      );
+    my $query2 = "SELECT  COUNT(*) FROM issues i, biblioitems s1, items s2 
+                WHERE i.borrowernumber = ? 
+                    AND i.itemnumber = s2.itemnumber 
+                    AND s1.biblioitemnumber = s2.biblioitemnumber";
+    if (C4::Context->preference('item-level_itypes')){
+          $query2.=" AND s2.itype=? ";
+    } else { 
+          $query2.=" AND s1.itemtype= ? ";
+    }
+    my $sth2=  $dbh->prepare($query2);
     my $sth3 =
       $dbh->prepare(
-'select COUNT(*) from issues where borrowernumber = ? and returndate is null'
-      );
+            'SELECT COUNT(*) FROM issues
+                WHERE borrowernumber = ?'
+            );
     my $alreadyissued;
 
-    # check the 3 parameters
-    $sth->execute( $cat_borrower, $type, $branch_borrower );
+    # check the 3 parameters (branch / itemtype / category code
+    $sth->execute( $cat_borrower, $type, $branch );
     my $result = $sth->fetchrow_hashref;
+#     warn "$cat_borrower, $type, $branch = ".Data::Dumper::Dumper($result);
 
-    #    warn "==>".$result->{maxissueqty};
-
-# Currently, using defined($result) ie on an entire hash reports whether memory
-# for that aggregate has ever been allocated. As $result is used all over the place
-# it would rarely return as undefined.
-    if ( defined( $result->{maxissueqty} ) ) {
-        $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
-        my $alreadyissued = $sth2->fetchrow;
-        if ( $result->{'maxissueqty'} <= $alreadyissued ) {
-            return ( "a $alreadyissued / ".( $result->{maxissueqty} + 0 ) );
-        }
-        else {
-            return;
-        }
-    }
-
-    # check for branch=*
-    $sth->execute( $cat_borrower, $type, "" );
-    $result = $sth->fetchrow_hashref;
-    if ( defined( $result->{maxissueqty} ) ) {
-        $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
+    if ( $result->{maxissueqty} ne '' ) {
+#         warn "checking on everything set";
+        $sth2->execute( $borrower->{'borrowernumber'}, $type );
         my $alreadyissued = $sth2->fetchrow;
         if ( $result->{'maxissueqty'} <= $alreadyissued ) {
-            return ( "b $alreadyissued / ".( $result->{maxissueqty} + 0 ) );
+            return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/itemtype failed)" );
         }
-        else {
-            return;
+        # now checking for total
+        $sth->execute( $cat_borrower, '*', $branch );
+        my $result = $sth->fetchrow_hashref;
+        if ( $result->{maxissueqty} ne '' ) {
+            $sth2->execute( $borrower->{'borrowernumber'}, $type );
+            my $alreadyissued = $sth2->fetchrow;
+            if ( $result->{'maxissueqty'} <= $alreadyissued ) {
+                return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/total failed)"  );
+            }
         }
     }
 
-    # check for itemtype=*
-    $sth->execute( $cat_borrower, "*", $branch_borrower );
+    # check the 2 parameters (branch / itemtype / default categorycode
+    $sth->execute( '*', $type, $branch );
     $result = $sth->fetchrow_hashref;
-    if ( defined( $result->{maxissueqty} ) ) {
-        $sth3->execute( $borrower->{'borrowernumber'} );
-        my ($alreadyissued) = $sth3->fetchrow;
-        if ( $result->{'maxissueqty'} <= $alreadyissued ) {
-
-#        warn "HERE : $alreadyissued / ($result->{maxissueqty} for $borrower->{'borrowernumber'}";
-            return ( "c $alreadyissued / " . ( $result->{maxissueqty} + 0 ) );
-        }
-        else {
-            return;
-        }
-    }
+#     warn "*, $type, $branch = ".Data::Dumper::Dumper($result);
 
-    # check for borrowertype=*
-    $sth->execute( "*", $type, $branch_borrower );
-    $result = $sth->fetchrow_hashref;
-    if ( defined( $result->{maxissueqty} ) ) {
-        $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
+    if ( $result->{maxissueqty} ne '' ) {
+#         warn "checking on 2 parameters (default categorycode)";
+        $sth2->execute( $borrower->{'borrowernumber'}, $type );
         my $alreadyissued = $sth2->fetchrow;
         if ( $result->{'maxissueqty'} <= $alreadyissued ) {
-            return ( "d $alreadyissued / " . ( $result->{maxissueqty} + 0 ) );
-        }
-        else {
-            return;
-        }
-    }
-
-    $sth->execute( "*", "*", $branch_borrower );
-    $result = $sth->fetchrow_hashref;
-    if ( defined( $result->{maxissueqty} ) ) {
-        $sth3->execute( $borrower->{'borrowernumber'} );
-        my $alreadyissued = $sth3->fetchrow;
-        if ( $result->{'maxissueqty'} <= $alreadyissued ) {
-            return ( "e $alreadyissued / " . ( $result->{maxissueqty} + 0 ) );
+            return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / itemtype failed)"  );
         }
-        else {
-            return;
+        # now checking for total
+        $sth->execute( '*', '*', $branch );
+        my $result = $sth->fetchrow_hashref;
+        if ( $result->{maxissueqty} ne '' ) {
+            $sth2->execute( $borrower->{'borrowernumber'}, $type );
+            my $alreadyissued = $sth2->fetchrow;
+            if ( $result->{'maxissueqty'} <= $alreadyissued ) {
+                return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / total failed)" );
+            }
         }
     }
-
-    $sth->execute( "*", $type, "" );
+    
+    # check the 1 parameters (default branch / itemtype / categorycode
+    $sth->execute( $cat_borrower, $type, '*' );
     $result = $sth->fetchrow_hashref;
-    if ( defined( $result->{maxissueqty} ) && $result->{maxissueqty} >= 0 ) {
-        $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
+#     warn "$cat_borrower, $type, * = ".Data::Dumper::Dumper($result);
+    
+    if ( $result->{maxissueqty} ne '' ) {
+#         warn "checking on 1 parameter (default branch + categorycode)";
+        $sth2->execute( $borrower->{'borrowernumber'}, $type );
         my $alreadyissued = $sth2->fetchrow;
         if ( $result->{'maxissueqty'} <= $alreadyissued ) {
-            return ( "f $alreadyissued / " . ( $result->{maxissueqty} + 0 ) );
+            return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch/category/itemtype failed)"  );
         }
-        else {
-            return;
+        # now checking for total
+        $sth->execute( $cat_borrower, '*', '*' );
+        my $result = $sth->fetchrow_hashref;
+        if ( $result->{maxissueqty} ne '' ) {
+            $sth2->execute( $borrower->{'borrowernumber'}, $type );
+            my $alreadyissued = $sth2->fetchrow;
+            if ( $result->{'maxissueqty'} <= $alreadyissued ) {
+                return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / category / total failed)"  );
+            }
         }
     }
 
-    $sth->execute( $cat_borrower, "*", "" );
+    # check the 0 parameters (default branch / itemtype / default categorycode
+    $sth->execute( '*', $type, '*' );
     $result = $sth->fetchrow_hashref;
-    if ( defined( $result->{maxissueqty} ) ) {
-        $sth2->execute( $borrower->{'borrowernumber'}, "%$type%" );
+#     warn "*, $type, * = ".Data::Dumper::Dumper($result);
+
+    if ( $result->{maxissueqty} ne '' ) {
+#         warn "checking on default branch and default categorycode";
+        $sth2->execute( $borrower->{'borrowernumber'}, $type );
         my $alreadyissued = $sth2->fetchrow;
         if ( $result->{'maxissueqty'} <= $alreadyissued ) {
-            return ( "g $alreadyissued / " . ( $result->{maxissueqty} + 0 ) );
-        }
-        else {
-            return;
+            return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / itemtype failed)"  );
         }
-    }
-
-    $sth->execute( "*", "*", "" );
+       }
+    # now checking for total
+    $sth->execute( '*', '*', '*' );
     $result = $sth->fetchrow_hashref;
-    if ( defined( $result->{maxissueqty} ) ) {
-        $sth3->execute( $borrower->{'borrowernumber'} );
-        my $alreadyissued = $sth3->fetchrow;
-        if ( $result->{'maxissueqty'} <= $alreadyissued ) {
-            return ( "h $alreadyissued / " . ( $result->{maxissueqty} + 0 ) );
-        }
-        else {
-            return;
-        }
-    }
+    if ( $result->{maxissueqty} ne '' ) {
+               warn "checking total";
+               $sth2->execute( $borrower->{'borrowernumber'}, $type );
+               my $alreadyissued = $sth2->fetchrow;
+               if ( $result->{'maxissueqty'} <= $alreadyissued ) {
+                       return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / total failed)"  );
+               }
+       }
+
+    # OK, the patron can issue !!!
     return;
 }
 
@@ -583,12 +578,6 @@ The borrower number of the last three patrons who borrowed this item.
 sub itemissues {
     my ( $bibitem, $biblio ) = @_;
     my $dbh = C4::Context->dbh;
-
-    # FIXME - If this function die()s, the script will abort, and the
-    # user won't get anything; depending on how far the script has
-    # gotten, the user might get a blank page. It would be much better
-    # to at least print an error message. The easiest way to do this
-    # is to set $SIG{__DIE__}.
     my $sth =
       $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
       || die $dbh->errstr;
@@ -610,7 +599,6 @@ sub itemissues {
             "SELECT * FROM issues
                 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
                 WHERE itemnumber = ?
-                    AND returndate IS NULL
             "
         );
 
@@ -621,34 +609,19 @@ sub itemissues {
             $data->{'borrower'} = $data2->{'borrowernumber'};
         }
         else {
-            if ( $data->{'wthdrawn'} eq '1' ) {
-                $data->{'date_due'} = 'Cancelled';
-            }
-            else {
-                $data->{'date_due'} = 'Available';
-            }    # else
-        }    # else
+            $data->{'date_due'} = ($data->{'wthdrawn'} eq '1') ? 'Cancelled' : 'Available';
+        }
 
         $sth2->finish;
 
         # Find the last 3 people who borrowed this item.
         $sth2 = $dbh->prepare(
-            "SELECT * FROM issues, borrowers
+            "SELECT * FROM old_issues
                 LEFT JOIN borrowers ON  issues.borrowernumber = borrowers.borrowernumber
                 WHERE itemnumber = ?
-                AND returndate IS NOT NULL
                 ORDER BY returndate DESC,timestamp DESC"
         );
 
-#        $sth2 = $dbh->prepare("
-#            SELECT *
-#            FROM issues
-#                LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
-#            WHERE   itemnumber = ?
-#                AND returndate is not NULL
-#            ORDER BY returndate DESC,timestamp DESC
-#        ");
-
         $sth2->execute( $data->{'itemnumber'} );
         for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
         {    # FIXME : error if there is less than 3 pple borrowing this item
@@ -670,30 +643,36 @@ sub itemissues {
 
 =head2 CanBookBeIssued
 
-$issuingimpossible, $needsconfirmation = 
-        CanBookBeIssued( $env, $borrower, $barcode, $year, $month, $day, $inprocess );
-
+( $issuingimpossible, $needsconfirmation ) = 
+        CanBookBeIssued( $borrower, $barcode, $duedatespec, $inprocess );
+C<$duedatespec> is a C4::Dates object.
 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
 
 =cut
 
 sub CanBookBeIssued {
-    my ( $env, $borrower, $barcode, $year, $month, $day, $inprocess ) = @_;
+    my ( $borrower, $barcode, $duedate, $inprocess ) = @_;
     my %needsconfirmation;    # filled with problems that needs confirmations
     my %issuingimpossible;    # filled with problems that causes the issue to be IMPOSSIBLE
     my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
     my $issue = GetItemIssue($item->{itemnumber});
+       my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
+       $item->{'itemtype'}=$item->{'itype'}; 
     my $dbh             = C4::Context->dbh;
 
     #
-    # DUE DATE is OK ?
+    # DUE DATE is OK ? -- should already have checked.
     #
-    my ( $duedate, $invalidduedate ) = fixdate( $year, $month, $day );
-    $issuingimpossible{INVALID_DATE} = 1 if ($invalidduedate);
+    #$issuingimpossible{INVALID_DATE} = 1 unless ($duedate);
 
     #
     # BORROWER STATUS
     #
+    if ( $borrower->{'category_type'} eq 'X' && (  $item->{barcode}  )) { 
+       # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1  .
+        &UpdateStats(C4::Context->userenv->{'branch'},'localuse','','',$item->{'itemnumber'},$item->{'itemtype'},$borrower->{'borrowernumber'});
+        return( { STATS => 1 }, {});
+    }
     if ( $borrower->{flags}->{GNA} ) {
         $issuingimpossible{GNA} = 1;
     }
@@ -703,22 +682,22 @@ sub CanBookBeIssued {
     if ( $borrower->{flags}->{'DBARRED'} ) {
         $issuingimpossible{DEBARRED} = 1;
     }
-    if ( Date_to_Days(Today) > 
-        Date_to_Days( split "-", $borrower->{'dateexpiry'} ) )
-    {
-
-        #
-        #if (&Date_Cmp(&ParseDate($borrower->{expiry}),&ParseDate("today"))<0) {
+    if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
         $issuingimpossible{EXPIRED} = 1;
+    } else {
+        my @expirydate=  split /-/,$borrower->{'dateexpiry'};
+        if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
+            Date_to_Days(Today) > Date_to_Days( @expirydate )) {
+            $issuingimpossible{EXPIRED} = 1;                                   
+        }
     }
-
     #
     # BORROWER STATUS
     #
 
     # DEBTS
-    my $amount =
-      checkaccount( $borrower->{'borrowernumber'}, $dbh, $duedate );
+    my ($amount) =
+      C4::Members::GetMemberAccountRecords( $borrower->{'borrowernumber'}, '' && $duedate->output('iso') );
     if ( C4::Context->preference("IssuingInProcess") ) {
         my $amountlimit = C4::Context->preference("noissuescharge");
         if ( $amount > $amountlimit && !$inprocess ) {
@@ -737,7 +716,7 @@ sub CanBookBeIssued {
     #
     # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
     #
-    my $toomany = TooMany( $borrower, $item->{biblionumber} );
+       my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
     $needsconfirmation{TOO_MANY} = $toomany if $toomany;
 
     #
@@ -751,6 +730,22 @@ sub CanBookBeIssued {
     {
         $issuingimpossible{NOT_FOR_LOAN} = 1;
     }
+       elsif ( !$item->{'notforloan'} ){
+               # we have to check itemtypes.notforloan also
+               if (C4::Context->preference('item-level_itypes')){
+                       # this should probably be a subroutine
+                       my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
+                       $sth->execute($item->{'itemtype'});
+                       my $notforloan=$sth->fetchrow_hashref();
+                       $sth->finish();
+                       if ($notforloan->{'notforloan'} == 1){
+                               $issuingimpossible{NOT_FOR_LOAN} = 1;                           
+                       }
+               }
+               elsif ($biblioitem->{'notforloan'} == 1){
+                       $issuingimpossible{NOT_FOR_LOAN} = 1;
+               }
+       }
     if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
     {
         $issuingimpossible{WTHDRAWN} = 1;
@@ -764,7 +759,7 @@ sub CanBookBeIssued {
         my $userenv = C4::Context->userenv;
         if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
             $issuingimpossible{NOTSAMEBRANCH} = 1
-              if ( $item->{'holdingbranch'} ne $userenv->{branch} );
+              if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} );
         }
     }
 
@@ -776,7 +771,7 @@ sub CanBookBeIssued {
 
         # Already issued to current borrower. Ask whether the loan should
         # be renewed.
-        my ($CanBookBeRenewed) = CanBookBeRenewed(
+        my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed(
             $borrower->{'borrowernumber'},
             $item->{'itemnumber'}
         );
@@ -784,8 +779,7 @@ sub CanBookBeIssued {
             $issuingimpossible{NO_MORE_RENEWALS} = 1;
         }
         else {
-
-            #        $needsconfirmation{RENEW_ISSUE} = 1;
+            $needsconfirmation{RENEW_ISSUE} = 1;
         }
     }
     elsif ($issue->{borrowernumber}) {
@@ -799,61 +793,42 @@ sub CanBookBeIssued {
     }
 
     # See if the item is on reserve.
-    my ( $restype, $res ) = CheckReserves( $item->{'itemnumber'} );
+    my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
     if ($restype) {
-        my $resbor = $res->{'borrowernumber'};
+               my $resbor = $res->{'borrowernumber'};
+               my ( $resborrower, $flags ) = GetMemberDetails( $resbor, 0 );
+               my $branches  = GetBranches();
+               my $branchname = $branches->{ $res->{'branchcode'} }->{'branchname'};
         if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
         {
-
             # The item is on reserve and waiting, but has been
             # reserved by some other patron.
-            my ( $resborrower, $flags ) =
-              GetMemberDetails( $resbor, 0 );
-            my $branches   = GetBranches();
-            my $branchname =
-              $branches->{ $res->{'branchcode'} }->{'branchname'};
             $needsconfirmation{RESERVE_WAITING} =
 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
-
-# CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'}); Doesn't belong in a checking subroutine.
         }
         elsif ( $restype eq "Reserved" ) {
-
             # The item is on reserve for someone else.
-            my ( $resborrower, $flags ) =
-              GetMemberDetails( $resbor, 0 );
-            my $branches   = GetBranches();
-            my $branchname =
-              $branches->{ $res->{'branchcode'} }->{'branchname'};
             $needsconfirmation{RESERVED} =
 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
         }
     }
-    if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" )
-    {
+    if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" ) {
         if ( $borrower->{'categorycode'} eq 'W' ) {
-            my %issuingimpossible;
-            return ( \%issuingimpossible, \%needsconfirmation );
+            my %emptyhash;
+            return ( \%emptyhash, \%needsconfirmation );
         }
-        else {
-            return ( \%issuingimpossible, \%needsconfirmation );
-        }
-    }
-    else {
-        return ( \%issuingimpossible, \%needsconfirmation );
-    }
+       }
+       return ( \%issuingimpossible, \%needsconfirmation );
 }
 
 =head2 AddIssue
 
 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
 
-&AddIssue($env,$borrower,$barcode,$date)
+&AddIssue($borrower,$barcode,$date)
 
 =over 4
 
-=item C<$env> Environment variable. Should be empty usually, but used by other subs. Next code cleaning could drop it.
-
 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
 
 =item C<$barcode> is the bar code of the book being issued.
@@ -861,7 +836,7 @@ Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this
 =item C<$date> contains the max date of return. calculated if empty.
 
 AddIssue does the following things :
-- step 0�: check that there is a borrowernumber & a barcode provided
+- step 01: check that there is a borrowernumber & a barcode provided
 - check for RENEWAL (book issued & being issued to the same patron)
     - renewal YES = Calculate Charge & renew
     - renewal NO  = 
@@ -878,108 +853,104 @@ AddIssue does the following things :
 =cut
 
 sub AddIssue {
-    my ( $env, $borrower, $barcode, $date, $cancelreserve ) = @_;
-    
+    my ( $borrower, $barcode, $date, $cancelreserve ) = @_;
     my $dbh = C4::Context->dbh;
-if ($borrower and $barcode){
-#   my ($borrower, $flags) = &GetMemberDetails($borrowernumber, 0);
-    # find which item we issue
-    my $item = GetItem('', $barcode);
-    
-    # get actual issuing if there is one
-    my $actualissue = GetItemIssue( $item->{itemnumber});
-    
-    # get biblioinformation for this item
-    my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
-
-#
-# check if we just renew the issue.
-#
-    if ( $actualissue->{borrowernumber} eq $borrower->{'borrowernumber'} ) {
-        # we renew, do we need to add some charge ?
-        my ( $charge, $itemtype ) = GetIssuingCharges(
-            $item->{'itemnumber'},
-            $borrower->{'borrowernumber'}
-        );
-        if ( $charge > 0 ) {
-            AddIssuingCharge(
-                $item->{'itemnumber'},
-                $borrower->{'borrowernumber'}, $charge
-            );
-            $item->{'charge'} = $charge;
-        }
-        &UpdateStats(
-            $env,                           $env->{'branchcode'},
-            'renew',                        $charge,
-            '',                             $item->{'itemnumber'},
-            $biblio->{'itemtype'}, $borrower->{'borrowernumber'}
-        );
-        AddRenewal(
-            $borrower->{'borrowernumber'},
-            $item->{'itemnumber'}
-        );
-    }
-    else {# it's NOT a renewal
-        if ( $actualissue->{borrowernumber}) {
-            # This book is currently on loan, but not to the person
-            # who wants to borrow it now. mark it returned before issuing to the new borrower
-            AddReturn(
-                $item->{'barcode'},
-                C4::Context->userenv->{'branch'}
-            );
-        }
-
-        # See if the item is on reserve.
-        my ( $restype, $res ) =
-          CheckReserves( $item->{'itemnumber'} );
-        if ($restype) {
-            my $resbor = $res->{'borrowernumber'};
-            if ( $resbor eq $borrower->{'borrowernumber'} ) {
-
-                # The item is reserved by the current patron
-                FillReserve($res);
-            }
-            elsif ( $restype eq "Waiting" ) {
-
-                # warn "Waiting";
-                # The item is on reserve and waiting, but has been
-                # reserved by some other patron.
-                my ( $resborrower, $flags ) = GetMemberDetails( $resbor, 0 );
-                my $branches   = GetBranches();
-                my $branchname =
-                  $branches->{ $res->{'branchcode'} }->{'branchname'};
-                if ($cancelreserve) {
-                    CancelReserve( 0, $res->{'itemnumber'},
-                        $res->{'borrowernumber'} );
-                }
-                else {
-
-       # set waiting reserve to first in reserve queue as book isn't waiting now
-                    UpdateReserve(
-                        1,
-                        $res->{'biblionumber'},
-                        $res->{'borrowernumber'},
-                        $res->{'branchcode'}
-                    );
-                }
-            }
-            elsif ( $restype eq "Reserved" ) {
-
-                # warn "Reserved";
-                # The item is reserved by someone else.
-                my ( $resborrower, $flags ) =
-                  GetMemberDetails( $resbor, 0 );
-                my $branches   = GetBranches();
-                my $branchname =
-                  $branches->{ $res->{'branchcode'} }->{'branchname'};
-                if ($cancelreserve) { # cancel reserves on this item
-                    CancelReserve( 0, $res->{'itemnumber'},
-                        $res->{'borrowernumber'} );
-                }
-            }
-        }
-
-        # Starting process for transfer job (checking transfert and validate it if we have one)
+       my $barcodecheck=CheckValidBarcode($barcode);
+       if ($borrower and $barcode and $barcodecheck ne '0'){
+               # find which item we issue
+               my $item = GetItem('', $barcode);
+               my $datedue; 
+               
+               my $branch;
+               # Get which branchcode we need
+               if (C4::Context->preference('CircControl') eq 'PickupLibrary'){
+                       $branch = C4::Context->userenv->{'branch'}; 
+               }
+               elsif (C4::Context->preference('CircControl') eq 'PatronLibrary'){
+                       $branch = $borrower->{'branchcode'}; 
+               }
+               else {
+                       # items home library
+                       $branch = $item->{'homebranch'};
+               }
+               
+               # get actual issuing if there is one
+               my $actualissue = GetItemIssue( $item->{itemnumber});
+               
+               # get biblioinformation for this item
+               my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
+               
+               #
+               # check if we just renew the issue.
+               #
+               if ( $actualissue->{borrowernumber} eq $borrower->{'borrowernumber'} ) {
+                       AddRenewal(
+                               $borrower->{'borrowernumber'},
+                               $item->{'itemnumber'},
+                               $branch,
+                               $date
+                       );
+
+               }
+               else {
+        # it's NOT a renewal
+                       if ( $actualissue->{borrowernumber}) {
+                               # This book is currently on loan, but not to the person
+                               # who wants to borrow it now. mark it returned before issuing to the new borrower
+                               AddReturn(
+                                       $item->{'barcode'},
+                                       C4::Context->userenv->{'branch'}
+                               );
+                       }
+
+                       # See if the item is on reserve.
+                       my ( $restype, $res ) =
+                         C4::Reserves::CheckReserves( $item->{'itemnumber'} );
+                       if ($restype) {
+                               my $resbor = $res->{'borrowernumber'};
+                               if ( $resbor eq $borrower->{'borrowernumber'} ) {
+
+                                       # The item is reserved by the current patron
+                                       ModReserveFill($res);
+                               }
+                               elsif ( $restype eq "Waiting" ) {
+
+                                       # warn "Waiting";
+                                       # The item is on reserve and waiting, but has been
+                                       # reserved by some other patron.
+                                       my ( $resborrower, $flags ) = GetMemberDetails( $resbor, 0 );
+                                       my $branches   = GetBranches();
+                                       my $branchname =
+                                         $branches->{ $res->{'branchcode'} }->{'branchname'};
+                               }
+                               elsif ( $restype eq "Reserved" ) {
+
+                                       # warn "Reserved";
+                                       # The item is reserved by someone else.
+                                       my ( $resborrower, $flags ) =
+                                         GetMemberDetails( $resbor, 0 );
+                                       my $branches   = GetBranches();
+                                       my $branchname =  $branches->{ $res->{'branchcode'} }->{'branchname'};
+                                       if ($cancelreserve) { # cancel reserves on this item
+                                               CancelReserve( 0, $res->{'itemnumber'},
+                                                       $res->{'borrowernumber'} );
+                                       }
+                               }
+                               if ($cancelreserve) {
+                                       CancelReserve( $res->{'biblionumber'}, 0,
+                    $res->{'borrowernumber'} );
+                               }
+                               else {
+                                       # set waiting reserve to first in reserve queue as book isn't waiting now
+                                       ModReserve(1,
+                                               $res->{'biblionumber'},
+                                               $res->{'borrowernumber'},
+                                               $res->{'branchcode'}
+                                       );
+                               }
+                       }
+
+                       # Starting process for transfer job (checking transfert and validate it if we have one)
             my ($datesent) = GetTransfers($item->{'itemnumber'});
             if ($datesent) {
         #      updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for lisibility of this case (maybe for stats ....)
@@ -988,7 +959,7 @@ if ($borrower and $barcode){
                     "UPDATE branchtransfers 
                         SET datearrived = now(),
                         tobranch = ?,
-                        comments = 'Forced branchtransfert'
+                        comments = 'Forced branchtransfer'
                     WHERE itemnumber= ? AND datearrived IS NULL"
                     );
                     $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
@@ -1002,44 +973,37 @@ if ($borrower and $barcode){
                     (borrowernumber, itemnumber,issuedate, date_due, branchcode)
                 VALUES (?,?,?,?,?)"
           );
-        my $loanlength = GetLoanLength(
-            $borrower->{'categorycode'},
-            $biblio->{'itemtype'},
-            $borrower->{'branchcode'}
-        );
-        my $datedue  = time + ($loanlength) * 86400;
-        my @datearr  = localtime($datedue);
-        my $dateduef =
-            ( 1900 + $datearr[5] ) . "-"
-          . ( $datearr[4] + 1 ) . "-"
-          . $datearr[3];
+               my $dateduef;
         if ($date) {
             $dateduef = $date;
-        }
-
-       # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
-        if ( C4::Context->preference('ReturnBeforeExpiry')
-            && $dateduef gt $borrower->{dateexpiry} )
-        {
-            $dateduef = $borrower->{dateexpiry};
-        }
-        $sth->execute(
+        } else {
+                       my $itype=(C4::Context->preference('item-level_itypes')) ?  $biblio->{'itype'} : $biblio->{'itemtype'} ;
+               my $loanlength = GetLoanLength(
+                   $borrower->{'categorycode'},
+                   $itype,
+                $branch
+               );
+                       $dateduef = CalcDateDue(C4::Dates->new(),$loanlength,$branch);
+               # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
+               if ( C4::Context->preference('ReturnBeforeExpiry') && $dateduef->output('iso') gt $borrower->{dateexpiry} ) {
+                   $dateduef = C4::Dates->new($borrower->{dateexpiry},'iso');
+               }
+        };
+               $sth->execute(
             $borrower->{'borrowernumber'},
             $item->{'itemnumber'},
-            strftime( "%Y-%m-%d", localtime ),$dateduef, $env->{'branchcode'}
+            strftime( "%Y-%m-%d", localtime ),$dateduef->output('iso'), C4::Context->userenv->{'branch'}
         );
         $sth->finish;
         $item->{'issues'}++;
-        $sth =
-          $dbh->prepare(
-            "UPDATE items SET issues=?, holdingbranch=?, itemlost=0, datelastborrowed  = now() WHERE itemnumber=?");
-        $sth->execute(
-            $item->{'issues'},
-            C4::Context->userenv->{'branch'},
-            $item->{'itemnumber'}
-        );
-        $sth->finish;
-        &ModDateLastSeen( $item->{'itemnumber'} );
+        ModItem({ issues           => $item->{'issues'},
+                  holdingbranch    => C4::Context->userenv->{'branch'},
+                  itemlost         => 0,
+                  datelastborrowed => C4::Dates->new()->output('iso'),
+                  onloan           => $dateduef->output('iso'),
+                }, $item->{'biblionumber'}, $item->{'itemnumber'});
+        ModDateLastSeen( $item->{'itemnumber'} );
+        
         # If it costs to borrow this book, charge it to the patron's account.
         my ( $charge, $itemtype ) = GetIssuingCharges(
             $item->{'itemnumber'},
@@ -1055,16 +1019,17 @@ if ($borrower and $barcode){
 
         # Record the fact that this book was issued.
         &UpdateStats(
-            $env,                           $env->{'branchcode'},
+            C4::Context->userenv->{'branch'},
             'issue',                        $charge,
             '',                             $item->{'itemnumber'},
             $item->{'itemtype'}, $borrower->{'borrowernumber'}
         );
     }
     
-    &logaction(C4::Context->userenv->{'number'},"CIRCULATION","ISSUE",$borrower->{'borrowernumber'},$biblio->{'biblionumber'}) 
+    logaction("CIRCULATION", "ISSUE", $borrower->{'borrowernumber'}, $biblio->{'biblionumber'}) 
         if C4::Context->preference("IssueLog");
-  }  
+    return ($datedue);
+  }
 }
 
 =head2 GetLoanLength
@@ -1080,9 +1045,9 @@ sub GetLoanLength {
     my $dbh = C4::Context->dbh;
     my $sth =
       $dbh->prepare(
-"select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=?"
+"select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
       );
-
+# warn "in get loan lenght $borrowertype $itemtype $branchcode ";
 # try to find issuelength & return the 1st available.
 # check with borrowertype, itemtype and branchcode, then without one of those parameters
     $sth->execute( $borrowertype, $itemtype, $branchcode );
@@ -1090,7 +1055,7 @@ sub GetLoanLength {
     return $loanlength->{issuelength}
       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
 
-    $sth->execute( $borrowertype, $itemtype, "" );
+    $sth->execute( $borrowertype, $itemtype, "*" );
     $loanlength = $sth->fetchrow_hashref;
     return $loanlength->{issuelength}
       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
@@ -1105,7 +1070,7 @@ sub GetLoanLength {
     return $loanlength->{issuelength}
       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
 
-    $sth->execute( $borrowertype, "*", "" );
+    $sth->execute( $borrowertype, "*", "*" );
     $loanlength = $sth->fetchrow_hashref;
     return $loanlength->{issuelength}
       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
@@ -1115,12 +1080,12 @@ sub GetLoanLength {
     return $loanlength->{issuelength}
       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
 
-    $sth->execute( "*", $itemtype, "" );
+    $sth->execute( "*", $itemtype, "*" );
     $loanlength = $sth->fetchrow_hashref;
     return $loanlength->{issuelength}
       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
 
-    $sth->execute( "*", "*", "" );
+    $sth->execute( "*", "*", "*" );
     $loanlength = $sth->fetchrow_hashref;
     return $loanlength->{issuelength}
       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
@@ -1132,12 +1097,13 @@ sub GetLoanLength {
 =head2 AddReturn
 
 ($doreturn, $messages, $iteminformation, $borrower) =
-    &AddReturn($barcode, $branch);
+    &AddReturn($barcode, $branch, $exemptfine);
 
 Returns a book.
 
 C<$barcode> is the bar code of the book being returned. C<$branch> is
-the code of the branch where the book is being returned.
+the code of the branch where the book is being returned.  C<$exemptfine>
+indicates that overdue charges for the item will not be applied.
 
 C<&AddReturn> returns a list of four items:
 
@@ -1179,21 +1145,8 @@ patron who last borrowed the book.
 
 =cut
 
-# FIXME - This API is bogus. There's no need to return $borrower and
-# $iteminformation; the caller can ask about those separately, if it
-# cares (it'd be inefficient to make two database calls instead of
-# one, but &GetMemberDetails and &getiteminformation can be
-# memoized if this is an issue).
-#
-# The ($doreturn, $messages) tuple is redundant: if the return
-# succeeded, that's all the caller needs to know. So &AddReturn can
-# return 1 and 0 on success and failure, and set
-# $C4::Circulation::Circ2::errmsg to indicate the error. Or it can
-# return undef for success, and an error message on error (though this
-# is more C-ish than Perl-ish).
-
 sub AddReturn {
-    my ( $barcode, $branch ) = @_;
+    my ( $barcode, $branch, $exemptfine ) = @_;
     my $dbh      = C4::Context->dbh;
     my $messages;
     my $doreturn = 1;
@@ -1203,6 +1156,8 @@ sub AddReturn {
     
     # get information on item
     my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
+    my $biblio = GetBiblioItemData($iteminformation->{'biblioitemnumber'});
+#     use Data::Dumper;warn Data::Dumper::Dumper($iteminformation);  
     unless ($iteminformation->{'itemnumber'} ) {
         $messages->{'BadBarcode'} = $barcode;
         $doreturn = 0;
@@ -1210,6 +1165,11 @@ sub AddReturn {
         # find the borrower
         if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
             $messages->{'NotIssued'} = $barcode;
+            # even though item is not on loan, it may still
+            # be transferred; therefore, get current branch information
+            my $curr_iteminfo = GetItem($iteminformation->{'itemnumber'});
+            $iteminformation->{'homebranch'} = $curr_iteminfo->{'homebranch'};
+            $iteminformation->{'holdingbranch'} = $curr_iteminfo->{'holdingbranch'};
             $doreturn = 0;
         }
     
@@ -1219,7 +1179,13 @@ sub AddReturn {
         if ( $hbr && $branches->{$hbr}->{'PE'} ) {
             $messages->{'IsPermanent'} = $hbr;
         }
-    
+               
+                   # if independent branches are on and returning to different branch, refuse the return
+        if ($hbr ne C4::Context->userenv->{'branch'} && C4::Context->preference("IndependantBranches")){
+                         $messages->{'Wrongbranch'} = 1;
+                         $doreturn=0;
+                   }
+                       
         # check that the book has been cancelled
         if ( $iteminformation->{'wthdrawn'} ) {
             $messages->{'wthdrawn'} = 1;
@@ -1229,32 +1195,29 @@ sub AddReturn {
     #     new op dev : if the book returned in an other branch update the holding branch
     
     # update issues, thereby returning book (should push this out into another subroutine
-        $borrower = GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
+        $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
     
     # case of a return of document (deal with issues and holdingbranch)
     
         if ($doreturn) {
-            my $sth =
-            $dbh->prepare(
-    "update issues set returndate = now() where (borrowernumber = ?) and (itemnumber = ?) and (returndate is null)"
-            );
-            $sth->execute( $borrower->{'borrowernumber'},
-                $iteminformation->{'itemnumber'} );
+            MarkIssueReturned($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
             $messages->{'WasReturned'} = 1;    # FIXME is the "= 1" right?
         }
     
     # continue to deal with returns cases, but not only if we have an issue
     
-    # the holdingbranch is updated if the document is returned in an other location .
-    if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} )
-            {
-                    UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});    
-    #          reload iteminformation holdingbranch with the userenv value
-                    $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
-            }
+        # the holdingbranch is updated if the document is returned in an other location .
+        if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} ) {
+                       UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'}); 
+                       #               reload iteminformation holdingbranch with the userenv value
+                       $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
+        }
         ModDateLastSeen( $iteminformation->{'itemnumber'} );
-        ($borrower) = GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
-        
+        ModItem({ onloan => undef }, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'});
+                   
+                   if ($iteminformation->{borrowernumber}){
+                         ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
+        }       
         # fix up the accounts.....
         if ( $iteminformation->{'itemlost'} ) {
             $messages->{'WasLost'} = 1;
@@ -1269,12 +1232,12 @@ sub AddReturn {
             if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
                     my $sth =
                     $dbh->prepare(
-                            "update branchtransfers set datearrived = now() where itemnumber= ? AND datearrived IS NULL"
+                            "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
                     );
                     $sth->execute( $iteminformation->{'itemnumber'} );
                     $sth->finish;
     #         now we check if there is a reservation with the validate of transfer if we have one, we can         set it with the status 'W'
-            SetWaitingStatus( $iteminformation->{'itemnumber'} );
+            C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
             }
         else {
             $messages->{'WrongTransfer'} = $tobranch;
@@ -1284,14 +1247,19 @@ sub AddReturn {
         }
     
     # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
-    # fix up the overdues in accounts...
-        fixoverduesonreturn( $borrower->{'borrowernumber'},
-            $iteminformation->{'itemnumber'} );
+        # fix up the accounts.....
+        if ($iteminformation->{'itemlost'}) {
+                FixAccountForLostAndReturned($iteminformation, $borrower);
+                $messages->{'WasLost'} = 1;
+        }
+        # fix up the overdues in accounts...
+        FixOverduesOnReturn( $borrower->{'borrowernumber'},
+            $iteminformation->{'itemnumber'}, $exemptfine );
     
     # find reserves.....
     #     if we don't have a reserve with the status W, we launch the Checkreserves routine
         my ( $resfound, $resrec ) =
-        CheckReserves( $iteminformation->{'itemnumber'} );
+        C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
         if ($resfound) {
             $resrec->{'ResFound'}   = $resfound;
             $messages->{'ResFound'} = $resrec;
@@ -1303,39 +1271,80 @@ sub AddReturn {
         UpdateStats(
             $branch, 'return', '0', '',
             $iteminformation->{'itemnumber'},
-            $iteminformation->{'itemtype'},
+            $biblio->{'itemtype'},
             $borrower->{'borrowernumber'}
         );
         
-        &logaction(C4::Context->userenv->{'number'},"CIRCULATION","RETURN",$iteminformation->{borrowernumber},$iteminformation->{'biblionumber'}) 
+        logaction("CIRCULATION", "RETURN", $iteminformation->{borrowernumber}, $iteminformation->{'biblionumber'}) 
             if C4::Context->preference("ReturnLog");
         
         #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
         #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
         
         if ( ($iteminformation->{'holdingbranch'} ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
-                    if (C4::Context->preference("AutomaticItemReturn") == 1) {
-                    dotransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
-                    $messages->{'WasTransfered'} = 1;
-                    warn "was transfered";
-                    }
+                       if (C4::Context->preference("AutomaticItemReturn") == 1) {
+                               ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
+                               $messages->{'WasTransfered'} = 1;
+                       }
+                       else {
+                               $messages->{'NeedsTransfer'} = 1;
+                       }
         }
     }
     return ( $doreturn, $messages, $iteminformation, $borrower );
 }
 
-=head2 fixoverdueonreturn
+=head2 MarkIssueReturned
+
+=over 4
 
-    &fixoverdueonreturn($brn,$itm);
+MarkIssueReturned($borrowernumber, $itemnumber);
+
+=back
+
+Unconditionally marks an issue as being returned by
+moving the C<issues> row to C<old_issues> and
+setting C<returndate> to the current date.
+
+Ideally, this function would be internal to C<C4::Circulation>,
+not exported, but it is currently needed by one 
+routine in C<C4::Accounts>.
+
+=cut
+
+sub MarkIssueReturned {
+    my ($borrowernumber, $itemnumber) = @_;
+
+    my $dbh = C4::Context->dbh;
+    # FIXME transaction
+    my $sth_upd  = $dbh->prepare("UPDATE issues SET returndate = now() 
+                                  WHERE borrowernumber = ?
+                                  AND itemnumber = ?");
+    $sth_upd->execute($borrowernumber, $itemnumber);
+    my $sth_copy = $dbh->prepare("INSERT INTO old_issues SELECT * FROM issues 
+                                  WHERE borrowernumber = ?
+                                  AND itemnumber = ?");
+    $sth_copy->execute($borrowernumber, $itemnumber);
+    my $sth_del  = $dbh->prepare("DELETE FROM issues
+                                  WHERE borrowernumber = ?
+                                  AND itemnumber = ?");
+    $sth_del->execute($borrowernumber, $itemnumber);
+}
+
+=head2 FixOverduesOnReturn
+
+    &FixOverduesOnReturn($brn,$itm, $exemptfine);
 
 C<$brn> borrowernumber
 
 C<$itm> itemnumber
 
+internal function, called only by AddReturn
+
 =cut
 
-sub fixoverduesonreturn {
-    my ( $borrowernumber, $item ) = @_;
+sub FixOverduesOnReturn {
+    my ( $borrowernumber, $item, $exemptfine ) = @_;
     my $dbh = C4::Context->dbh;
 
     # check for overdue fine
@@ -1346,27 +1355,124 @@ sub fixoverduesonreturn {
     $sth->execute( $borrowernumber, $item );
 
     # alter fine to show that the book has been returned
-    if ( my $data = $sth->fetchrow_hashref ) {
-        my $usth =
-          $dbh->prepare(
-"UPDATE accountlines SET accounttype='F' WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accountno = ?)"
-          );
-        $usth->execute( $borrowernumber, $item, $data->{'accountno'} );
+   my $data; 
+       if ($data = $sth->fetchrow_hashref) {
+        my $uquery =($exemptfine)? "update accountlines set accounttype='FFOR', amountoutstanding=0":"update accountlines set accounttype='F' ";
+               $uquery .= " where (borrowernumber = ?) and (itemnumber = ?) and (accountno = ?)";
+        my $usth = $dbh->prepare($uquery);
+        $usth->execute($borrowernumber,$item ,$data->{'accountno'});
         $usth->finish();
     }
+
     $sth->finish();
     return;
 }
 
+=head2 FixAccountForLostAndReturned
+
+       &FixAccountForLostAndReturned($iteminfo,$borrower);
+
+Calculates the charge for a book lost and returned (Not exported & used only once)
+
+C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
+
+C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
+
+Internal function, called by AddReturn
+
+=cut
+
+sub FixAccountForLostAndReturned {
+       my ($iteminfo, $borrower) = @_;
+       my %env;
+       my $dbh = C4::Context->dbh;
+       my $itm = $iteminfo->{'itemnumber'};
+       # check for charge made for lost book
+       my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
+       $sth->execute($itm);
+       if (my $data = $sth->fetchrow_hashref) {
+       # writeoff this amount
+               my $offset;
+               my $amount = $data->{'amount'};
+               my $acctno = $data->{'accountno'};
+               my $amountleft;
+               if ($data->{'amountoutstanding'} == $amount) {
+               $offset = $data->{'amount'};
+               $amountleft = 0;
+               } else {
+               $offset = $amount - $data->{'amountoutstanding'};
+               $amountleft = $data->{'amountoutstanding'} - $amount;
+               }
+               my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
+                       WHERE (borrowernumber = ?)
+                       AND (itemnumber = ?) AND (accountno = ?) ");
+               $usth->execute($data->{'borrowernumber'},$itm,$acctno);
+               $usth->finish;
+       #check if any credit is left if so writeoff other accounts
+               my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
+               if ($amountleft < 0){
+               $amountleft*=-1;
+               }
+               if ($amountleft > 0){
+               my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
+                                                       AND (amountoutstanding >0) ORDER BY date");
+               $msth->execute($data->{'borrowernumber'});
+       # offset transactions
+               my $newamtos;
+               my $accdata;
+               while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
+                       if ($accdata->{'amountoutstanding'} < $amountleft) {
+                       $newamtos = 0;
+                       $amountleft -= $accdata->{'amountoutstanding'};
+                       }  else {
+                       $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
+                       $amountleft = 0;
+                       }
+                       my $thisacct = $accdata->{'accountno'};
+                       my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
+                                       WHERE (borrowernumber = ?)
+                                       AND (accountno=?)");
+                       $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
+                       $usth->finish;
+                       $usth = $dbh->prepare("INSERT INTO accountoffsets
+                               (borrowernumber, accountno, offsetaccount,  offsetamount)
+                               VALUES
+                               (?,?,?,?)");
+                       $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
+                       $usth->finish;
+               }
+               $msth->finish;
+               }
+               if ($amountleft > 0){
+                       $amountleft*=-1;
+               }
+               my $desc="Item Returned ".$iteminfo->{'barcode'};
+               $usth = $dbh->prepare("INSERT INTO accountlines
+                       (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
+                       VALUES (?,?,now(),?,?,'CR',?)");
+               $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
+               $usth->finish;
+               $usth = $dbh->prepare("INSERT INTO accountoffsets
+                       (borrowernumber, accountno, offsetaccount,  offsetamount)
+                       VALUES (?,?,?,?)");
+               $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
+               $usth->finish;
+        ModItem({ paidfor => '' }, undef, $itm);
+       }
+       $sth->finish;
+       return;
+}
+
 =head2 GetItemIssue
 
-$issues = &GetBorrowerIssue($itemnumber);
+$issues = &GetItemIssue($itemnumber);
 
 Returns patrons currently having a book. nothing if item is not issued atm
 
 C<$itemnumber> is the itemnumber
 
 Returns an array of hashes
+
 =cut
 
 sub GetItemIssue {
@@ -1382,7 +1488,7 @@ sub GetItemIssue {
         "SELECT * FROM issues 
         LEFT JOIN items ON issues.itemnumber=items.itemnumber
     WHERE
-    issues.itemnumber=?  AND returndate IS NULL ");
+    issues.itemnumber=?");
     $sth->execute($itemnumber);
     my $data = $sth->fetchrow_hashref;
     my $datedue = $data->{'date_due'};
@@ -1397,7 +1503,7 @@ sub GetItemIssue {
 
 =head2 GetItemIssues
 
-$issues = &GetBorrowerIssues($itemnumber, $history);
+$issues = &GetItemIssues($itemnumber, $history);
 
 Returns patrons that have issued a book
 
@@ -1405,6 +1511,7 @@ C<$itemnumber> is the itemnumber
 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
 
 Returns an array of hashes
+
 =cut
 
 sub GetItemIssues {
@@ -1415,13 +1522,24 @@ sub GetItemIssues {
     # get today date
     my $today = POSIX::strftime("%Y%m%d", localtime);
 
-    my $sth = $dbh->prepare(
-        "SELECT * FROM issues 
-    WHERE
-    itemnumber=?".($history?"":" AND returndate IS NULL ").
-    "ORDER BY issues.date_due DESC"
-    );
-    $sth->execute($itemnumber);
+    my $sql = "SELECT * FROM issues 
+              JOIN borrowers USING (borrowernumber)
+              JOIN items USING (itemnumber)
+              WHERE issues.itemnumber = ? ";
+    if ($history) {
+        $sql .= "UNION ALL
+                 SELECT * FROM old_issues 
+                 LEFT JOIN borrowers USING (borrowernumber)
+                 JOIN items USING (itemnumber)
+                 WHERE old_issues.itemnumber = ? ";
+    }
+    $sql .= "ORDER BY date_due DESC";
+    my $sth = $dbh->prepare($sql);
+    if ($history) {
+        $sth->execute($itemnumber, $itemnumber);
+    } else {
+        $sth->execute($itemnumber);
+    }
     while ( my $data = $sth->fetchrow_hashref ) {
         my $datedue = $data->{'date_due'};
         $datedue =~ s/-//g;
@@ -1429,62 +1547,12 @@ sub GetItemIssues {
             $data->{'overdue'} = 1;
         }
         my $itemnumber = $data->{'itemnumber'};
-
         push @GetItemIssues, $data;
     }
     $sth->finish;
     return ( \@GetItemIssues );
 }
 
-=head2 GetBorrowerIssues
-
-$issues = &GetBorrowerIssues($borrower);
-
-Returns a list of books currently on loan to a patron.
-
-C<$borrower->{borrowernumber}> is the borrower number of the patron
-whose issues we want to list.
-
-C<&GetBorrowerIssues> returns a PHP-style array: C<$issues> is a
-reference-to-hash whose keys are integers in the range 1...I<n>, where
-I<n> is the number of items on issue (either today or before today).
-C<$issues-E<gt>{I<n>}> is a reference-to-hash whose keys are all of
-the fields of the biblio, biblioitems, items, and issues fields of the
-Koha database for that particular item.
-
-=cut
-
-sub GetBorrowerIssues {
-    my ( $borrower ) = @_;
-    my $dbh = C4::Context->dbh;
-    my @GetBorrowerIssues;
-    # get today date
-    my $today = POSIX::strftime("%Y%m%d", localtime);
-
-    my $sth = $dbh->prepare(
-        "SELECT * FROM issues 
-    LEFT JOIN items ON issues.itemnumber=items.itemnumber
-    LEFT JOIN biblio ON     items.biblionumber=biblio.biblionumber 
-    LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
-    WHERE
-    borrowernumber=? AND returndate IS NULL
-    ORDER BY issues.date_due"
-    );
-    $sth->execute($borrower->{'borrowernumber'});
-    while ( my $data = $sth->fetchrow_hashref ) {
-        my $datedue = $data->{'date_due'};
-        $datedue =~ s/-//g;
-        if ( $datedue < $today ) {
-            $data->{'overdue'} = 1;
-        }
-        my $itemnumber = $data->{'itemnumber'};
-
-        push @GetBorrowerIssues, $data;
-    }
-    $sth->finish;
-    return ( \@GetBorrowerIssues );
-}
-
 =head2 GetBiblioIssues
 
 $issues = GetBiblioIssues($biblionumber);
@@ -1502,17 +1570,25 @@ sub GetBiblioIssues {
     return undef unless $biblionumber;
     my $dbh   = C4::Context->dbh;
     my $query = "
-        SELECT issues.*,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
+        SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
         FROM issues
             LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
             LEFT JOIN items ON issues.itemnumber = items.itemnumber
             LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
             LEFT JOIN biblio ON biblio.biblionumber = items.biblioitemnumber
         WHERE biblio.biblionumber = ?
-        ORDER BY issues.timestamp
+        UNION ALL
+        SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
+        FROM old_issues
+            LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
+            LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
+            LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
+            LEFT JOIN biblio ON biblio.biblionumber = items.biblioitemnumber
+        WHERE biblio.biblionumber = ?
+        ORDER BY timestamp
     ";
     my $sth = $dbh->prepare($query);
-    $sth->execute($biblionumber);
+    $sth->execute($biblionumber, $biblionumber);
 
     my @issues;
     while ( my $data = $sth->fetchrow_hashref ) {
@@ -1523,12 +1599,10 @@ sub GetBiblioIssues {
 
 =head2 CanBookBeRenewed
 
-$ok = &CanBookBeRenewed($borrowernumber, $itemnumber);
+($ok,$error) = &CanBookBeRenewed($borrowernumber, $itemnumber);
 
 Find out whether a borrowed item may be renewed.
 
-C<$env> is ignored.
-
 C<$dbh> is a DBI handle to the Koha database.
 
 C<$borrowernumber> is the borrower number of the patron who currently
@@ -1539,7 +1613,7 @@ C<$itemnumber> is the number of the item to renew.
 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
 item must currently be on loan to the specified borrower; renewals
 must be allowed for the item's type; and the borrower must not have
-already renewed the loan.
+already renewed the loan. $error will contain the reason the renewal can not proceed
 
 =cut
 
@@ -1550,6 +1624,7 @@ sub CanBookBeRenewed {
     my $dbh       = C4::Context->dbh;
     my $renews    = 1;
     my $renewokay = 0;
+       my $error;
 
     # Look in the issues table for this item, lent to this borrower,
     # and not yet returned.
@@ -1558,8 +1633,7 @@ sub CanBookBeRenewed {
     my $sth1 = $dbh->prepare(
         "SELECT * FROM issues
             WHERE borrowernumber = ?
-            AND itemnumber = ?
-            AND returndate IS NULL"
+            AND itemnumber = ?"
     );
     $sth1->execute( $borrowernumber, $itemnumber );
     if ( my $data1 = $sth1->fetchrow_hashref ) {
@@ -1570,13 +1644,13 @@ sub CanBookBeRenewed {
         # because it's a bit messy: given the item number, we need to find
         # the biblioitem, which gives us the itemtype, which tells us
         # whether it may be renewed.
-        my $sth2 = $dbh->prepare(
-            "SELECT renewalsallowed FROM items
-                LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
-                LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
-                WHERE items.itemnumber = ?
-                "
-        );
+        my $query = "SELECT renewalsallowed FROM items ";
+        $query .= (C4::Context->preference('item-level_itypes'))
+                    ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
+                    : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
+                       LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
+        $query .= "WHERE items.itemnumber = ?";
+        my $sth2 = $dbh->prepare($query);
         $sth2->execute($itemnumber);
         if ( my $data2 = $sth2->fetchrow_hashref ) {
             $renews = $data2->{'renewalsallowed'};
@@ -1584,19 +1658,19 @@ sub CanBookBeRenewed {
         if ( $renews && $renews > $data1->{'renewals'} ) {
             $renewokay = 1;
         }
+        else {
+                       $error="too_many";
+               }
         $sth2->finish;
-        my ( $resfound, $resrec ) = C4::Reserves2::CheckReserves($itemnumber);
-        if ($resfound) {
-            $renewokay = 0;
-        }
-        ( $resfound, $resrec ) = C4::Reserves2::CheckReserves($itemnumber);
+        my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
         if ($resfound) {
             $renewokay = 0;
+                       $error="on_reserve"
         }
 
     }
     $sth1->finish;
-    return ($renewokay);
+    return ($renewokay,$error);
 }
 
 =head2 AddRenewal
@@ -1605,12 +1679,6 @@ sub CanBookBeRenewed {
 
 Renews a loan.
 
-C<$env-E<gt>{branchcode}> is the code of the branch where the
-renewal is taking place.
-
-C<$env-E<gt>{usercode}> is the value to log in C<statistics.usercode>
-in the Koha database.
-
 C<$borrowernumber> is the borrower number of the patron who currently
 has the item.
 
@@ -1625,32 +1693,37 @@ C<$datedue> should be in the form YYYY-MM-DD.
 
 sub AddRenewal {
 
-    my ( $borrowernumber, $itemnumber, $datedue ) = @_;
+    my ( $borrowernumber, $itemnumber, $branch ,$datedue ) = @_;
     my $dbh = C4::Context->dbh;
-
+    my $biblio = GetBiblioFromItemNumber($itemnumber);
     # If the due date wasn't specified, calculate it by adding the
     # book's loan length to today's date.
-    if ( $datedue eq "" ) {
+    unless ( $datedue ) {
+
 
-        my $biblio = GetBiblioFromItemNumber($itemnumber);
-        my $borrower = GetMemberDetails( $borrowernumber, 0 );
+        my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 );
         my $loanlength = GetLoanLength(
             $borrower->{'categorycode'},
-            $biblio->{'itemtype'},
-            $borrower->{'branchcode'}
+             (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
+                       $borrower->{'branchcode'}
         );
-        my ( $due_year, $due_month, $due_day ) =
-          Add_Delta_DHMS( Today_and_Now(), $loanlength, 0, 0, 0 );
-        $datedue = "$due_year-$due_month-$due_day";
-
+               #FIXME --  choose issuer or borrower branch -- use circControl.
+
+               #FIXME -- $debug-ify the (0)
+        #my @darray = Add_Delta_DHMS( Today_and_Now(), $loanlength, 0, 0, 0 );
+        #$datedue = C4::Dates->new( sprintf("%04d-%02d-%02d",@darray[0..2]), 'iso');
+               #(0) and print STDERR  "C4::Dates->new->output = " . C4::Dates->new()->output()
+               #               . "\ndatedue->output = " . $datedue->output()
+               #               . "\n(Y,M,D) = " . join ',', @darray;
+               #$datedue=CheckValidDatedue($datedue,$itemnumber,$branch,$loanlength);
+               $datedue =  CalcDateDue(C4::Dates->new(),$loanlength,$branch);
     }
 
     # Find the issues record for this book
     my $sth =
       $dbh->prepare("SELECT * FROM issues
                         WHERE borrowernumber=? 
-                        AND itemnumber=? 
-                        AND returndate IS NULL"
+                        AND itemnumber=?"
       );
     $sth->execute( $borrowernumber, $itemnumber );
     my $issuedata = $sth->fetchrow_hashref;
@@ -1661,20 +1734,20 @@ sub AddRenewal {
     my $renews = $issuedata->{'renewals'} + 1;
     $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?
                             WHERE borrowernumber=? 
-                            AND itemnumber=? 
-                            AND returndate IS NULL"
+                            AND itemnumber=?"
     );
-    $sth->execute( $datedue, $renews, $borrowernumber, $itemnumber );
+    $sth->execute( $datedue->output('iso'), $renews, $borrowernumber, $itemnumber );
     $sth->finish;
 
-    # Log the renewal
-    UpdateStats( C4::Context->userenv->{'branchcode'}, 'renew', '', '', $itemnumber );
+    # Update the renewal count on the item, and tell zebra to reindex
+    $renews = $biblio->{'renewals'} + 1;
+    ModItem({ renewals => $renews }, $biblio->{'biblionumber'}, $itemnumber);
 
     # Charge a new rental fee, if applicable?
     my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
     if ( $charge > 0 ) {
         my $accountno = getnextacctno( $borrowernumber );
-        my $item = GetBiblioFromItemNumbe(r$itemnumber);
+        my $item = GetBiblioFromItemNumber($itemnumber);
         $sth = $dbh->prepare(
                 "INSERT INTO accountlines
                     (borrowernumber,accountno,date,amount,
@@ -1687,6 +1760,40 @@ sub AddRenewal {
             'Rent', $charge, $itemnumber );
         $sth->finish;
     }
+    # Log the renewal
+    UpdateStats( $branch, 'renew', $charge, '', $itemnumber );
+}
+
+sub GetRenewCount {
+    # check renewal status
+    my ($bornum,$itemno)=@_;
+    my $dbh = C4::Context->dbh;
+    my $renewcount = 0;
+        my $renewsallowed = 0;
+        my $renewsleft = 0;
+    # Look in the issues table for this item, lent to this borrower,
+    # and not yet returned.
+
+    # FIXME - I think this function could be redone to use only one SQL call.
+    my $sth = $dbh->prepare("select * from issues
+                                where (borrowernumber = ?)
+                                and (itemnumber = ?)");
+    $sth->execute($bornum,$itemno);
+    my $data = $sth->fetchrow_hashref;
+    $renewcount = $data->{'renewals'} if $data->{'renewals'};
+    $sth->finish;
+    my $query = "SELECT renewalsallowed FROM items ";
+    $query .= (C4::Context->preference('item-level_itypes'))
+                ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
+                : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
+                   LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
+    $query .= "WHERE items.itemnumber = ?";
+    my $sth2 = $dbh->prepare($query);
+    $sth2->execute($itemno);
+    my $data2 = $sth2->fetchrow_hashref();
+    $renewsallowed = $data2->{'renewalsallowed'};
+    $renewsleft = $renewsallowed - $renewcount;
+    return ($renewcount,$renewsallowed,$renewsleft);
 }
 
 =head2 GetIssuingCharges
@@ -1696,8 +1803,6 @@ sub AddRenewal {
 Calculate how much it would cost for a given patron to borrow a given
 item, including any applicable discounts.
 
-C<$env> is ignored.
-
 C<$itemnumber> is the item number of item the patron wishes to borrow.
 
 C<$borrowernumber> is the patron's borrower number.
@@ -1717,13 +1822,15 @@ sub GetIssuingCharges {
     my $item_type;
 
     # Get the book's item type and rental charge (via its biblioitem).
-    my $sth1 = $dbh->prepare(
-        "SELECT itemtypes.itemtype,rentalcharge FROM items
-            LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
-            LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
-            WHERE items.itemnumber =?
-        "
-    );
+    my $qcharge =     "SELECT itemtypes.itemtype,rentalcharge FROM items
+            LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
+       $qcharge .= (C4::Context->preference('item-level_itypes'))
+                ? " LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
+                : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
+       
+    $qcharge .=      "WHERE items.itemnumber =?";
+   
+    my $sth1 = $dbh->prepare($qcharge);
     $sth1->execute($itemnumber);
     if ( my $data1 = $sth1->fetchrow_hashref ) {
         $item_type = $data1->{'itemtype'};
@@ -1861,7 +1968,7 @@ sub AnonymiseIssueHistory {
     my $borrowernumber = shift;
     my $dbh            = C4::Context->dbh;
     my $query          = "
-        UPDATE issues
+        UPDATE old_issues
         SET    borrowernumber = NULL
         WHERE  returndate < '".$date."'
           AND borrowernumber IS NOT NULL
@@ -1891,7 +1998,7 @@ sub updateWrongTransfer {
                $sth->finish;
 
 # second step create a new line of branchtransfer to the right location .
-       dotransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
+       ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
 
 #third step changing holdingbranch of item
        UpdateHoldingbranch($FromLibrary,$itemNumber);
@@ -1901,20 +2008,169 @@ sub updateWrongTransfer {
 
 $items = UpdateHoldingbranch($branch,$itmenumber);
 Simple methode for updating hodlingbranch in items BDD line
+
 =cut
 
 sub UpdateHoldingbranch {
-       my ( $branch,$itmenumber ) = @_;
-       my $dbh = C4::Context->dbh;     
-# first step validate the actual line of transfert .
-       my $sth =
-               $dbh->prepare(
-                       "update items set holdingbranch = ? where itemnumber= ?"
-               );
-               $sth->execute($branch,$itmenumber);
-               $sth->finish;
-        
-       
+       my ( $branch,$itemnumber ) = @_;
+    ModItem({ holdingbranch => $branch }, undef, $itemnumber);
+}
+
+=head2 CalcDateDue
+
+$newdatedue = CalcDateDue($startdate,$loanlength,$branchcode);
+this function calculates the due date given the loan length ,
+checking against the holidays calendar as per the 'useDaysMode' syspref.
+C<$startdate>   = C4::Dates object representing start date of loan period (assumed to be today)
+C<$branch>  = location whose calendar to use
+C<$loanlength>  = loan length prior to adjustment
+=cut
+
+sub CalcDateDue { 
+       my ($startdate,$loanlength,$branch) = @_;
+       if(C4::Context->preference('useDaysMode') eq 'Days') {  # ignoring calendar
+               my $datedue = time + ($loanlength) * 86400;
+       #FIXME - assumes now even though we take a startdate 
+               my @datearr  = localtime($datedue);
+               return C4::Dates->new( sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
+       } else {
+               my $calendar = C4::Calendar->new(  branchcode => $branch );
+               my $datedue = $calendar->addDate($startdate, $loanlength);
+               return $datedue;
+       }
+}
+
+=head2 CheckValidDatedue
+       This function does not account for holiday exceptions nor does it handle the 'useDaysMode' syspref .
+       To be replaced by CalcDateDue() once C4::Calendar use is tested.
+
+$newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
+this function validates the loan length against the holidays calendar, and adjusts the due date as per the 'useDaysMode' syspref.
+C<$date_due>   = returndate calculate with no day check
+C<$itemnumber>  = itemnumber
+C<$branchcode>  = location of issue (affected by 'CircControl' syspref)
+C<$loanlength>  = loan length prior to adjustment
+=cut
+
+sub CheckValidDatedue {
+my ($date_due,$itemnumber,$branchcode)=@_;
+my @datedue=split('-',$date_due->output('iso'));
+my $years=$datedue[0];
+my $month=$datedue[1];
+my $day=$datedue[2];
+# die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
+my $dow;
+for (my $i=0;$i<2;$i++){
+    $dow=Day_of_Week($years,$month,$day);
+    ($dow=0) if ($dow>6);
+    my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
+    my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
+    my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
+        if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
+        $i=0;
+        (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
+        }
+    }
+    my $newdatedue=C4::Dates->new(sprintf("%04d-%02d-%02d",$years,$month,$day),'iso');
+return $newdatedue;
+}
+
+
+=head2 CheckRepeatableHolidays
+
+$countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
+this function checks if the date due is a repeatable holiday
+C<$date_due>   = returndate calculate with no day check
+C<$itemnumber>  = itemnumber
+C<$branchcode>  = localisation of issue 
+
+=cut
+
+sub CheckRepeatableHolidays{
+my($itemnumber,$week_day,$branchcode)=@_;
+my $dbh = C4::Context->dbh;
+my $query = qq|SELECT count(*)  
+       FROM repeatable_holidays 
+       WHERE branchcode=?
+       AND weekday=?|;
+my $sth = $dbh->prepare($query);
+$sth->execute($branchcode,$week_day);
+my $result=$sth->fetchrow;
+$sth->finish;
+return $result;
+}
+
+
+=head2 CheckSpecialHolidays
+
+$countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
+this function check if the date is a special holiday
+C<$years>   = the years of datedue
+C<$month>   = the month of datedue
+C<$day>     = the day of datedue
+C<$itemnumber>  = itemnumber
+C<$branchcode>  = localisation of issue 
+
+=cut
+
+sub CheckSpecialHolidays{
+my ($years,$month,$day,$itemnumber,$branchcode) = @_;
+my $dbh = C4::Context->dbh;
+my $query=qq|SELECT count(*) 
+            FROM `special_holidays`
+            WHERE year=?
+            AND month=?
+            AND day=?
+             AND branchcode=?
+           |;
+my $sth = $dbh->prepare($query);
+$sth->execute($years,$month,$day,$branchcode);
+my $countspecial=$sth->fetchrow ;
+$sth->finish;
+return $countspecial;
+}
+
+=head2 CheckRepeatableSpecialHolidays
+
+$countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
+this function check if the date is a repeatble special holidays
+C<$month>   = the month of datedue
+C<$day>     = the day of datedue
+C<$itemnumber>  = itemnumber
+C<$branchcode>  = localisation of issue 
+
+=cut
+
+sub CheckRepeatableSpecialHolidays{
+my ($month,$day,$itemnumber,$branchcode) = @_;
+my $dbh = C4::Context->dbh;
+my $query=qq|SELECT count(*) 
+            FROM `repeatable_holidays`
+            WHERE month=?
+            AND day=?
+             AND branchcode=?
+           |;
+my $sth = $dbh->prepare($query);
+$sth->execute($month,$day,$branchcode);
+my $countspecial=$sth->fetchrow ;
+$sth->finish;
+return $countspecial;
+}
+
+
+
+sub CheckValidBarcode{
+my ($barcode) = @_;
+my $dbh = C4::Context->dbh;
+my $query=qq|SELECT count(*) 
+            FROM items 
+             WHERE barcode=?
+           |;
+my $sth = $dbh->prepare($query);
+$sth->execute($barcode);
+my $exist=$sth->fetchrow ;
+$sth->finish;
+return $exist;
 }
 
 1;