+
+=head2 AddRenewal
+
+&AddRenewal($borrowernumber, $itemnumber, $datedue);
+
+Renews a loan.
+
+C<$borrowernumber> is the borrower number of the patron who currently
+has the item.
+
+C<$itemnumber> is the number of the item to renew.
+
+C<$datedue> can be used to set the due date. If C<$datedue> is the
+empty string, C<&AddRenewal> will calculate the due date automatically
+from the book's item type. If you wish to set the due date manually,
+C<$datedue> should be in the form YYYY-MM-DD.
+
+=cut
+
+sub AddRenewal {
+
+ 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.
+ unless ( $datedue ) {
+
+
+ my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 );
+ my $loanlength = GetLoanLength(
+ $borrower->{'categorycode'},
+ (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
+ $borrower->{'branchcode'}
+ );
+ #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=?"
+ );
+ $sth->execute( $borrowernumber, $itemnumber );
+ my $issuedata = $sth->fetchrow_hashref;
+ $sth->finish;
+
+ # Update the issues record to have the new due date, and a new count
+ # of how many times it has been renewed.
+ my $renews = $issuedata->{'renewals'} + 1;
+ $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?
+ WHERE borrowernumber=?
+ AND itemnumber=?"
+ );
+ $sth->execute( $datedue->output('iso'), $renews, $borrowernumber, $itemnumber );
+ $sth->finish;
+
+ # 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 = GetBiblioFromItemNumber($itemnumber);
+ $sth = $dbh->prepare(
+ "INSERT INTO accountlines
+ (borrowernumber,accountno,date,amount,
+ description,accounttype,amountoutstanding,
+ itemnumber)
+ VALUES (?,?,now(),?,?,?,?,?)"
+ );
+ $sth->execute( $borrowernumber, $accountno, $charge,
+ "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
+ '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
+
+($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
+
+Calculate how much it would cost for a given patron to borrow a given
+item, including any applicable discounts.
+
+C<$itemnumber> is the item number of item the patron wishes to borrow.
+
+C<$borrowernumber> is the patron's borrower number.
+
+C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
+and C<$item_type> is the code for the item's item type (e.g., C<VID>
+if it's a video).
+
+=cut
+
+sub GetIssuingCharges {
+
+ # calculate charges due
+ my ( $itemnumber, $borrowernumber ) = @_;
+ my $charge = 0;
+ my $dbh = C4::Context->dbh;
+ my $item_type;
+
+ # Get the book's item type and rental charge (via its biblioitem).
+ 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'};
+ $charge = $data1->{'rentalcharge'};
+ my $q2 = "SELECT rentaldiscount FROM borrowers
+ LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
+ WHERE borrowers.borrowernumber = ?
+ AND issuingrules.itemtype = ?";
+ my $sth2 = $dbh->prepare($q2);
+ $sth2->execute( $borrowernumber, $item_type );
+ if ( my $data2 = $sth2->fetchrow_hashref ) {
+ my $discount = $data2->{'rentaldiscount'};
+ if ( $discount eq 'NULL' ) {
+ $discount = 0;
+ }
+ $charge = ( $charge * ( 100 - $discount ) ) / 100;
+ }
+ $sth2->finish;
+ }
+
+ $sth1->finish;
+ return ( $charge, $item_type );
+}
+
+=head2 AddIssuingCharge
+
+&AddIssuingCharge( $itemno, $borrowernumber, $charge )
+
+=cut
+
+sub AddIssuingCharge {
+ my ( $itemnumber, $borrowernumber, $charge ) = @_;
+ my $dbh = C4::Context->dbh;
+ my $nextaccntno = getnextacctno( $borrowernumber );
+ my $query ="
+ INSERT INTO accountlines
+ (borrowernumber, itemnumber, accountno,
+ date, amount, description, accounttype,
+ amountoutstanding)
+ VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
+ ";
+ my $sth = $dbh->prepare($query);
+ $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
+ $sth->finish;
+}
+
+=head2 GetTransfers
+
+GetTransfers($itemnumber);
+
+=cut
+
+sub GetTransfers {
+ my ($itemnumber) = @_;
+
+ my $dbh = C4::Context->dbh;
+
+ my $query = '
+ SELECT datesent,
+ frombranch,
+ tobranch
+ FROM branchtransfers
+ WHERE itemnumber = ?
+ AND datearrived IS NULL
+ ';
+ my $sth = $dbh->prepare($query);
+ $sth->execute($itemnumber);
+ my @row = $sth->fetchrow_array();
+ $sth->finish;
+ return @row;
+}
+
+
+=head2 GetTransfersFromTo
+
+@results = GetTransfersFromTo($frombranch,$tobranch);
+
+Returns the list of pending transfers between $from and $to branch
+
+=cut
+
+sub GetTransfersFromTo {
+ my ( $frombranch, $tobranch ) = @_;
+ return unless ( $frombranch && $tobranch );
+ my $dbh = C4::Context->dbh;
+ my $query = "
+ SELECT itemnumber,datesent,frombranch
+ FROM branchtransfers
+ WHERE frombranch=?
+ AND tobranch=?
+ AND datearrived IS NULL
+ ";
+ my $sth = $dbh->prepare($query);
+ $sth->execute( $frombranch, $tobranch );
+ my @gettransfers;
+
+ while ( my $data = $sth->fetchrow_hashref ) {
+ push @gettransfers, $data;
+ }
+ $sth->finish;
+ return (@gettransfers);
+}
+
+=head2 DeleteTransfer
+
+&DeleteTransfer($itemnumber);
+
+=cut
+
+sub DeleteTransfer {
+ my ($itemnumber) = @_;
+ my $dbh = C4::Context->dbh;
+ my $sth = $dbh->prepare(
+ "DELETE FROM branchtransfers
+ WHERE itemnumber=?
+ AND datearrived IS NULL "
+ );
+ $sth->execute($itemnumber);
+ $sth->finish;
+}
+
+=head2 AnonymiseIssueHistory
+
+$rows = AnonymiseIssueHistory($borrowernumber,$date)
+
+This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
+if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
+
+return the number of affected rows.
+
+=cut
+
+sub AnonymiseIssueHistory {
+ my $date = shift;
+ my $borrowernumber = shift;
+ my $dbh = C4::Context->dbh;
+ my $query = "
+ UPDATE old_issues
+ SET borrowernumber = NULL
+ WHERE returndate < '".$date."'
+ AND borrowernumber IS NOT NULL
+ ";
+ $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
+ my $rows_affected = $dbh->do($query);
+ return $rows_affected;
+}
+
+=head2 updateWrongTransfer
+
+$items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
+
+This function validate the line of brachtransfer but with the wrong destination (mistake from a librarian ...), and create a new line in branchtransfer from the actual library to the original library of reservation
+
+=cut
+
+sub updateWrongTransfer {
+ my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
+ my $dbh = C4::Context->dbh;
+# first step validate the actual line of transfert .
+ my $sth =
+ $dbh->prepare(
+ "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
+ );
+ $sth->execute($FromLibrary,$itemNumber);
+ $sth->finish;
+
+# second step create a new line of branchtransfer to the right location .
+ ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
+
+#third step changing holdingbranch of item
+ UpdateHoldingbranch($FromLibrary,$itemNumber);
+}
+
+=head2 UpdateHoldingbranch
+
+$items = UpdateHoldingbranch($branch,$itmenumber);
+Simple methode for updating hodlingbranch in items BDD line
+
+=cut
+
+sub UpdateHoldingbranch {
+ 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;
+
+__END__
+
+=head1 AUTHOR
+
+Koha Developement team <info@koha.org>
+
+=cut
+