1 package C4::Circulation;
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
22 #use warnings; # soon!
42 use POSIX qw(strftime);
43 use C4::Branch; # GetBranches
44 use C4::Log; # logaction
48 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
52 $VERSION = 3.02; # for version checking
55 # FIXME subs that should probably be elsewhere
61 # subs to deal with issuing a book
73 &GetBranchBorrowerCircRule
75 &AnonymiseIssueHistory
78 # subs to deal with returns
84 # subs to deal with transfers
96 C4::Circulation - Koha circulation module
104 The functions in this module deal with circulation, issues, and
105 returns, as well as general information about the library.
106 Also deals with stocktaking.
112 =head3 $str = &barcodedecode($barcode, [$filter]);
116 =item Generic filter function for barcode string.
117 Called on every circ if the System Pref itemBarcodeInputFilter is set.
118 Will do some manipulation of the barcode for systems that deliver a barcode
119 to circulation.pl that differs from the barcode stored for the item.
120 For proper functioning of this filter, calling the function on the
121 correct barcode string (items.barcode) should return an unaltered barcode.
123 The optional $filter argument is to allow for testing or explicit
124 behavior that ignores the System Pref. Valid values are the same as the
131 # FIXME -- the &decode fcn below should be wrapped into this one.
132 # FIXME -- these plugins should be moved out of Circulation.pm
135 my ($barcode, $filter) = @_;
136 $filter = C4::Context->preference('itemBarcodeInputFilter') unless $filter;
137 $filter or return $barcode; # ensure filter is defined, else return untouched barcode
138 if ($filter eq 'whitespace') {
140 } elsif ($filter eq 'cuecat') {
142 my @fields = split( /\./, $barcode );
143 my @results = map( decode($_), @fields[ 1 .. $#fields ] );
144 ($#results == 2) and return $results[2];
145 } elsif ($filter eq 'T-prefix') {
146 if ($barcode =~ /^[Tt](\d)/) {
147 (defined($1) and $1 eq '0') and return $barcode;
148 $barcode = substr($barcode, 2) + 0; # FIXME: probably should be substr($barcode, 1)
150 return sprintf("T%07d", $barcode);
151 # FIXME: $barcode could be "T1", causing warning: substr outside of string
152 # Why drop the nonzero digit after the T?
153 # Why pass non-digits (or empty string) to "T%07d"?
155 return $barcode; # return barcode, modified or not
160 =head3 $str = &decode($chunk);
164 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
167 FIXME: Should be replaced with Barcode::Cuecat from CPAN
168 or Javascript based decoding on the client side.
177 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
178 my @s = map { index( $seq, $_ ); } split( //, $encoded );
179 my $l = ( $#s + 1 ) % 4;
182 # warn "Error: Cuecat decode parsing failed!";
190 my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
192 chr( ( $n >> 16 ) ^ 67 )
193 .chr( ( $n >> 8 & 255 ) ^ 67 )
194 .chr( ( $n & 255 ) ^ 67 );
197 $r = substr( $r, 0, length($r) - $l );
203 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
205 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
207 C<$newbranch> is the code for the branch to which the item should be transferred.
209 C<$barcode> is the barcode of the item to be transferred.
211 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
212 Otherwise, if an item is reserved, the transfer fails.
214 Returns three values:
218 is true if the transfer was successful.
222 is a reference-to-hash which may have any of the following keys:
228 There is no item in the catalog with the given barcode. The value is C<$barcode>.
232 The item's home branch is permanent. This doesn't prevent the item from being transferred, though. The value is the code of the item's home branch.
234 =item C<DestinationEqualsHolding>
236 The item is already at the branch to which it is being transferred. The transfer is nonetheless considered to have failed. The value should be ignored.
240 The item was on loan, and C<&transferbook> automatically returned it before transferring it. The value is the borrower number of the patron who had the item.
244 The item was reserved. The value is a reference-to-hash whose keys are fields from the reserves table of the Koha database, and C<biblioitemnumber>. It also has the key C<ResFound>, whose value is either C<Waiting> or C<Reserved>.
246 =item C<WasTransferred>
248 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
255 my ( $tbr, $barcode, $ignoreRs ) = @_;
258 my $branches = GetBranches();
259 my $itemnumber = GetItemnumberFromBarcode( $barcode );
260 my $issue = GetItemIssue($itemnumber);
261 my $biblio = GetBiblioFromItemNumber($itemnumber);
264 if ( not $itemnumber ) {
265 $messages->{'BadBarcode'} = $barcode;
269 # get branches of book...
270 my $hbr = $biblio->{'homebranch'};
271 my $fbr = $biblio->{'holdingbranch'};
274 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
275 $messages->{'IsPermanent'} = $hbr;
278 # can't transfer book if is already there....
279 if ( $fbr eq $tbr ) {
280 $messages->{'DestinationEqualsHolding'} = 1;
284 # check if it is still issued to someone, return it...
285 if ($issue->{borrowernumber}) {
286 AddReturn( $barcode, $fbr );
287 $messages->{'WasReturned'} = $issue->{borrowernumber};
291 # That'll save a database query.
292 my ( $resfound, $resrec ) =
293 CheckReserves( $itemnumber );
294 if ( $resfound and not $ignoreRs ) {
295 $resrec->{'ResFound'} = $resfound;
297 # $messages->{'ResFound'} = $resrec;
301 #actually do the transfer....
303 ModItemTransfer( $itemnumber, $fbr, $tbr );
305 # don't need to update MARC anymore, we do it in batch now
306 $messages->{'WasTransfered'} = 1;
307 ModDateLastSeen( $itemnumber );
309 return ( $dotransfer, $messages, $biblio );
314 my $borrower = shift;
315 my $biblionumber = shift;
317 my $cat_borrower = $borrower->{'categorycode'};
318 my $dbh = C4::Context->dbh;
320 # Get which branchcode we need
321 $branch = _GetCircControlBranch($item,$borrower);
322 my $type = (C4::Context->preference('item-level_itypes'))
323 ? $item->{'itype'} # item-level
324 : $item->{'itemtype'}; # biblio-level
326 # given branch, patron category, and item type, determine
327 # applicable issuing rule
328 my $issuing_rule = GetIssuingRule($cat_borrower, $type, $branch);
330 # if a rule is found and has a loan limit set, count
331 # how many loans the patron already has that meet that
333 if (defined($issuing_rule) and defined($issuing_rule->{'maxissueqty'})) {
335 my $count_query = "SELECT COUNT(*) FROM issues
336 JOIN items USING (itemnumber) ";
338 my $rule_itemtype = $issuing_rule->{itemtype};
339 if ($rule_itemtype eq "*") {
340 # matching rule has the default item type, so count only
341 # those existing loans that don't fall under a more
343 if (C4::Context->preference('item-level_itypes')) {
344 $count_query .= " WHERE items.itype NOT IN (
345 SELECT itemtype FROM issuingrules
347 AND (categorycode = ? OR categorycode = ?)
351 $count_query .= " JOIN biblioitems USING (biblionumber)
352 WHERE biblioitems.itemtype NOT IN (
353 SELECT itemtype FROM issuingrules
355 AND (categorycode = ? OR categorycode = ?)
359 push @bind_params, $issuing_rule->{branchcode};
360 push @bind_params, $issuing_rule->{categorycode};
361 push @bind_params, $cat_borrower;
363 # rule has specific item type, so count loans of that
365 if (C4::Context->preference('item-level_itypes')) {
366 $count_query .= " WHERE items.itype = ? ";
368 $count_query .= " JOIN biblioitems USING (biblionumber)
369 WHERE biblioitems.itemtype= ? ";
371 push @bind_params, $type;
374 $count_query .= " AND borrowernumber = ? ";
375 push @bind_params, $borrower->{'borrowernumber'};
376 my $rule_branch = $issuing_rule->{branchcode};
377 if ($rule_branch ne "*") {
378 if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
379 $count_query .= " AND issues.branchcode = ? ";
380 push @bind_params, $branch;
381 } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
382 ; # if branch is the patron's home branch, then count all loans by patron
384 $count_query .= " AND items.homebranch = ? ";
385 push @bind_params, $branch;
389 my $count_sth = $dbh->prepare($count_query);
390 $count_sth->execute(@bind_params);
391 my ($current_loan_count) = $count_sth->fetchrow_array;
393 my $max_loans_allowed = $issuing_rule->{'maxissueqty'};
394 if ($current_loan_count >= $max_loans_allowed) {
395 return "$current_loan_count / $max_loans_allowed";
399 # Now count total loans against the limit for the branch
400 my $branch_borrower_circ_rule = GetBranchBorrowerCircRule($branch, $cat_borrower);
401 if (defined($branch_borrower_circ_rule->{maxissueqty})) {
402 my @bind_params = ();
403 my $branch_count_query = "SELECT COUNT(*) FROM issues
404 JOIN items USING (itemnumber)
405 WHERE borrowernumber = ? ";
406 push @bind_params, $borrower->{borrowernumber};
408 if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
409 $branch_count_query .= " AND issues.branchcode = ? ";
410 push @bind_params, $branch;
411 } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
412 ; # if branch is the patron's home branch, then count all loans by patron
414 $branch_count_query .= " AND items.homebranch = ? ";
415 push @bind_params, $branch;
417 my $branch_count_sth = $dbh->prepare($branch_count_query);
418 $branch_count_sth->execute(@bind_params);
419 my ($current_loan_count) = $branch_count_sth->fetchrow_array;
421 my $max_loans_allowed = $branch_borrower_circ_rule->{maxissueqty};
422 if ($current_loan_count >= $max_loans_allowed) {
423 return "$current_loan_count / $max_loans_allowed";
427 # OK, the patron can issue !!!
433 @issues = &itemissues($biblioitemnumber, $biblio);
435 Looks up information about who has borrowed the bookZ<>(s) with the
436 given biblioitemnumber.
438 C<$biblio> is ignored.
440 C<&itemissues> returns an array of references-to-hash. The keys
441 include the fields from the C<items> table in the Koha database.
442 Additional keys include:
448 If the item is currently on loan, this gives the due date.
450 If the item is not on loan, then this is either "Available" or
451 "Cancelled", if the item has been withdrawn.
455 If the item is currently on loan, this gives the card number of the
456 patron who currently has the item.
458 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
460 These give the timestamp for the last three times the item was
463 =item C<card0>, C<card1>, C<card2>
465 The card number of the last three patrons who borrowed this item.
467 =item C<borrower0>, C<borrower1>, C<borrower2>
469 The borrower number of the last three patrons who borrowed this item.
477 my ( $bibitem, $biblio ) = @_;
478 my $dbh = C4::Context->dbh;
480 $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
485 $sth->execute($bibitem) || die $sth->errstr;
487 while ( my $data = $sth->fetchrow_hashref ) {
489 # Find out who currently has this item.
490 # FIXME - Wouldn't it be better to do this as a left join of
491 # some sort? Currently, this code assumes that if
492 # fetchrow_hashref() fails, then the book is on the shelf.
493 # fetchrow_hashref() can fail for any number of reasons (e.g.,
494 # database server crash), not just because no items match the
496 my $sth2 = $dbh->prepare(
497 "SELECT * FROM issues
498 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
503 $sth2->execute( $data->{'itemnumber'} );
504 if ( my $data2 = $sth2->fetchrow_hashref ) {
505 $data->{'date_due'} = $data2->{'date_due'};
506 $data->{'card'} = $data2->{'cardnumber'};
507 $data->{'borrower'} = $data2->{'borrowernumber'};
510 $data->{'date_due'} = ($data->{'wthdrawn'} eq '1') ? 'Cancelled' : 'Available';
515 # Find the last 3 people who borrowed this item.
516 $sth2 = $dbh->prepare(
517 "SELECT * FROM old_issues
518 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
520 ORDER BY returndate DESC,timestamp DESC"
523 $sth2->execute( $data->{'itemnumber'} );
524 for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
525 { # FIXME : error if there is less than 3 pple borrowing this item
526 if ( my $data2 = $sth2->fetchrow_hashref ) {
527 $data->{"timestamp$i2"} = $data2->{'timestamp'};
528 $data->{"card$i2"} = $data2->{'cardnumber'};
529 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
534 $results[$i] = $data;
542 =head2 CanBookBeIssued
544 Check if a book can be issued.
546 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $borrower, $barcode, $duedatespec, $inprocess );
548 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
552 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
554 =item C<$barcode> is the bar code of the book being issued.
556 =item C<$duedatespec> is a C4::Dates object.
566 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
567 Possible values are :
573 sticky due date is invalid
577 borrower gone with no address
581 borrower declared it's card lost
587 =head3 UNKNOWN_BARCODE
601 item is restricted (set by ??)
603 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
604 Possible values are :
612 renewing, not issuing
614 =head3 ISSUED_TO_ANOTHER
616 issued to someone else.
620 reserved for someone else.
624 sticky due date is invalid
628 if the borrower borrows to much things
632 sub CanBookBeIssued {
633 my ( $borrower, $barcode, $duedate, $inprocess ) = @_;
634 my %needsconfirmation; # filled with problems that needs confirmations
635 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
636 my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
637 my $issue = GetItemIssue($item->{itemnumber});
638 my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
639 $item->{'itemtype'}=$item->{'itype'};
640 my $dbh = C4::Context->dbh;
642 # MANDATORY CHECKS - unless item exists, nothing else matters
643 unless ( $item->{barcode} ) {
644 $issuingimpossible{UNKNOWN_BARCODE} = 1;
646 return ( \%issuingimpossible, \%needsconfirmation ) if %issuingimpossible;
649 # DUE DATE is OK ? -- should already have checked.
651 unless ( $duedate ) {
652 my $issuedate = strftime( "%Y-%m-%d", localtime );
654 my $branch = _GetCircControlBranch($item,$borrower);
655 my $itype = ( C4::Context->preference('item-level_itypes') ) ? $item->{'itype'} : $biblioitem->{'itemtype'};
656 my $loanlength = GetLoanLength( $borrower->{'categorycode'}, $itype, $branch );
657 $duedate = CalcDateDue( C4::Dates->new( $issuedate, 'iso' ), $loanlength, $branch, $borrower );
659 # Offline circ calls AddIssue directly, doesn't run through here
660 # So issuingimpossible should be ok.
662 $issuingimpossible{INVALID_DATE} = $duedate->output('syspref') unless ( $duedate && $duedate->output('iso') ge C4::Dates->today('iso') );
667 if ( $borrower->{'category_type'} eq 'X' && ( $item->{barcode} )) {
668 # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1 .
669 &UpdateStats(C4::Context->userenv->{'branch'},'localuse','','',$item->{'itemnumber'},$item->{'itemtype'},$borrower->{'borrowernumber'});
670 return( { STATS => 1 }, {});
672 if ( $borrower->{flags}->{GNA} ) {
673 $issuingimpossible{GNA} = 1;
675 if ( $borrower->{flags}->{'LOST'} ) {
676 $issuingimpossible{CARD_LOST} = 1;
678 if ( $borrower->{flags}->{'DBARRED'} ) {
679 $issuingimpossible{DEBARRED} = 1;
681 if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
682 $issuingimpossible{EXPIRED} = 1;
684 my @expirydate= split /-/,$borrower->{'dateexpiry'};
685 if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
686 Date_to_Days(Today) > Date_to_Days( @expirydate )) {
687 $issuingimpossible{EXPIRED} = 1;
696 C4::Members::GetMemberAccountRecords( $borrower->{'borrowernumber'}, '' && $duedate->output('iso') );
697 if ( C4::Context->preference("IssuingInProcess") ) {
698 my $amountlimit = C4::Context->preference("noissuescharge");
699 if ( $amount > $amountlimit && !$inprocess ) {
700 $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
702 elsif ( $amount > 0 && $amount <= $amountlimit && !$inprocess ) {
703 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
708 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
712 my ($blocktype, $count) = C4::Members::IsMemberBlocked($borrower->{'borrowernumber'});
713 if($blocktype == -1){
714 ## remaining overdue documents
715 $needsconfirmation{USERBLOCKEDREMAINING} = $count;
716 }elsif($blocktype == 1){
717 ## blocked because of overdue return
718 $issuingimpossible{USERBLOCKEDOVERDUE} = $count;
722 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
724 my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
725 # if TooMany return / 0, then the user has no permission to check out this book
726 if ($toomany =~ /\/ 0/) {
727 $needsconfirmation{PATRON_CANT} = 1;
729 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
735 unless ( $item->{barcode} ) {
736 $issuingimpossible{UNKNOWN_BARCODE} = 1;
738 if ( $item->{'notforloan'}
739 && $item->{'notforloan'} > 0 )
741 if(C4::Context->preference("AllowNotForLoanOverride")){
742 $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
744 $issuingimpossible{NOT_FOR_LOAN} = 1;
747 elsif ( !$item->{'notforloan'} ){
748 # we have to check itemtypes.notforloan also
749 if (C4::Context->preference('item-level_itypes')){
750 # this should probably be a subroutine
751 my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
752 $sth->execute($item->{'itemtype'});
753 my $notforloan=$sth->fetchrow_hashref();
755 if ($notforloan->{'notforloan'}) {
756 if (!C4::Context->preference("AllowNotForLoanOverride")) {
757 $issuingimpossible{NOT_FOR_LOAN} = 1;
759 $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
763 elsif ($biblioitem->{'notforloan'} == 1){
764 if (!C4::Context->preference("AllowNotForLoanOverride")) {
765 $issuingimpossible{NOT_FOR_LOAN} = 1;
767 $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
771 if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
773 $issuingimpossible{WTHDRAWN} = 1;
775 if ( $item->{'restricted'}
776 && $item->{'restricted'} == 1 )
778 $issuingimpossible{RESTRICTED} = 1;
780 if ( C4::Context->preference("IndependantBranches") ) {
781 my $userenv = C4::Context->userenv;
782 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
783 $issuingimpossible{NOTSAMEBRANCH} = 1
784 if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} );
789 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
791 if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
794 # Already issued to current borrower. Ask whether the loan should
796 my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed(
797 $borrower->{'borrowernumber'},
798 $item->{'itemnumber'}
800 if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed
801 $issuingimpossible{NO_MORE_RENEWALS} = 1;
804 $needsconfirmation{RENEW_ISSUE} = 1;
807 elsif ($issue->{borrowernumber}) {
809 # issued to someone else
810 my $currborinfo = C4::Members::GetMemberDetails( $issue->{borrowernumber} );
812 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
813 $needsconfirmation{ISSUED_TO_ANOTHER} =
814 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
817 # See if the item is on reserve.
818 my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
820 my $resbor = $res->{'borrowernumber'};
821 my ( $resborrower ) = C4::Members::GetMemberDetails( $resbor, 0 );
822 my $branches = GetBranches();
823 my $branchname = $branches->{ $res->{'branchcode'} }->{'branchname'};
824 if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
826 # The item is on reserve and waiting, but has been
827 # reserved by some other patron.
828 $needsconfirmation{RESERVE_WAITING} =
829 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
831 elsif ( $restype eq "Reserved" ) {
832 # The item is on reserve for someone else.
833 $needsconfirmation{RESERVED} =
834 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
837 return ( \%issuingimpossible, \%needsconfirmation );
842 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
844 &AddIssue($borrower, $barcode, [$datedue], [$cancelreserve], [$issuedate])
848 =item C<$borrower> is a hash with borrower informations (from GetMemberDetails).
850 =item C<$barcode> is the barcode of the item being issued.
852 =item C<$datedue> is a C4::Dates object for the max date of return, i.e. the date due (optional).
855 =item C<$cancelreserve> is 1 to override and cancel any pending reserves for the item (optional).
857 =item C<$issuedate> is the date to issue the item in iso (YYYY-MM-DD) format (optional).
858 Defaults to today. Unlike C<$datedue>, NOT a C4::Dates object, unfortunately.
860 AddIssue does the following things :
861 - step 01: check that there is a borrowernumber & a barcode provided
862 - check for RENEWAL (book issued & being issued to the same patron)
863 - renewal YES = Calculate Charge & renew
865 * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
867 - fill reserve if reserve to this patron
868 - cancel reserve or not, otherwise
869 * TRANSFERT PENDING ?
870 - complete the transfert
878 my ( $borrower, $barcode, $datedue, $cancelreserve, $issuedate, $sipmode) = @_;
879 my $dbh = C4::Context->dbh;
880 my $barcodecheck=CheckValidBarcode($barcode);
882 # $issuedate defaults to today.
883 if ( ! defined $issuedate ) {
884 $issuedate = strftime( "%Y-%m-%d", localtime );
885 # TODO: for hourly circ, this will need to be a C4::Dates object
886 # and all calls to AddIssue including issuedate will need to pass a Dates object.
888 if ($borrower and $barcode and $barcodecheck ne '0'){
889 # find which item we issue
890 my $item = GetItem('', $barcode) or return undef; # if we don't get an Item, abort.
891 my $hbr = C4::Context->preference("HomeOrHoldingBranch")||"homebranch";
892 my $branch = _GetCircControlBranch($item,$borrower);
894 # get actual issuing if there is one
895 my $actualissue = GetItemIssue( $item->{itemnumber});
897 # get biblioinformation for this item
898 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
901 # check if we just renew the issue.
903 if ($actualissue->{borrowernumber} eq $borrower->{'borrowernumber'}) {
904 $datedue = AddRenewal(
905 $borrower->{'borrowernumber'},
906 $item->{'itemnumber'},
909 $issuedate, # here interpreted as the renewal date
914 if ( $actualissue->{borrowernumber}) {
915 # This book is currently on loan, but not to the person
916 # who wants to borrow it now. mark it returned before issuing to the new borrower
919 C4::Context->userenv->{'branch'}
923 # See if the item is on reserve.
924 my ( $restype, $res ) =
925 C4::Reserves::CheckReserves( $item->{'itemnumber'} );
927 my $resbor = $res->{'borrowernumber'};
928 if ( $resbor eq $borrower->{'borrowernumber'} ) {
929 # The item is reserved by the current patron
930 ModReserveFill($res);
932 elsif ( $restype eq "Waiting" ) {
934 # The item is on reserve and waiting, but has been
935 # reserved by some other patron.
937 elsif ( $restype eq "Reserved" ) {
939 # The item is reserved by someone else.
940 if ($cancelreserve) { # cancel reserves on this item
941 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
944 if ($cancelreserve) {
945 CancelReserve($res->{'biblionumber'}, 0, $res->{'borrowernumber'});
948 # set waiting reserve to first in reserve queue as book isn't waiting now
950 $res->{'biblionumber'},
951 $res->{'borrowernumber'},
957 # Starting process for transfer job (checking transfert and validate it if we have one)
958 my ($datesent) = GetTransfers($item->{'itemnumber'});
960 # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for visibility of this case (maybe for stats ....)
963 "UPDATE branchtransfers
964 SET datearrived = now(),
966 comments = 'Forced branchtransfer'
967 WHERE itemnumber= ? AND datearrived IS NULL"
969 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
972 # Record in the database the fact that the book was issued.
976 (borrowernumber, itemnumber,issuedate, date_due, branchcode)
980 my $itype = ( C4::Context->preference('item-level_itypes') ) ? $biblio->{'itype'} : $biblio->{'itemtype'};
981 my $loanlength = GetLoanLength( $borrower->{'categorycode'}, $itype, $branch );
982 $datedue = CalcDateDue( C4::Dates->new( $issuedate, 'iso' ), $loanlength, $branch );
984 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
985 if ( C4::Context->preference('ReturnBeforeExpiry') && $datedue->output('iso') gt $borrower->{dateexpiry} ) {
986 $datedue = C4::Dates->new( $borrower->{dateexpiry}, 'iso' );
990 $borrower->{'borrowernumber'}, # borrowernumber
991 $item->{'itemnumber'}, # itemnumber
992 $issuedate, # issuedate
993 $datedue->output('iso'), # date_due
997 ModItem({ issues => $item->{'issues'},
998 holdingbranch => C4::Context->userenv->{branch},
1000 datelastborrowed => C4::Dates->new()->output('iso'),
1001 onloan => $datedue->output('iso'),
1002 }, $item->{'biblionumber'}, $item->{'itemnumber'});
1003 ModDateLastSeen( $item->{'itemnumber'} );
1005 # If it costs to borrow this book, charge it to the patron's account.
1006 my ( $charge, $itemtype ) = GetIssuingCharges(
1007 $item->{'itemnumber'},
1008 $borrower->{'borrowernumber'}
1010 if ( $charge > 0 ) {
1012 $item->{'itemnumber'},
1013 $borrower->{'borrowernumber'}, $charge
1015 $item->{'charge'} = $charge;
1018 # Record the fact that this book was issued.
1020 C4::Context->userenv->{'branch'},
1022 ($sipmode ? "SIP-$sipmode" : ''), $item->{'itemnumber'},
1023 $item->{'itype'}, $borrower->{'borrowernumber'}
1027 logaction("CIRCULATION", "ISSUE", $borrower->{'borrowernumber'}, $biblio->{'biblionumber'})
1028 if C4::Context->preference("IssueLog");
1030 return ($datedue); # not necessarily the same as when it came in!
1033 =head2 GetLoanLength
1035 Get loan length for an itemtype, a borrower type and a branch
1037 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1042 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1043 my $dbh = C4::Context->dbh;
1046 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1048 # warn "in get loan lenght $borrowertype $itemtype $branchcode ";
1049 # try to find issuelength & return the 1st available.
1050 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1051 $sth->execute( $borrowertype, $itemtype, $branchcode );
1052 my $loanlength = $sth->fetchrow_hashref;
1053 return $loanlength->{issuelength}
1054 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1056 $sth->execute( $borrowertype, "*", $branchcode );
1057 $loanlength = $sth->fetchrow_hashref;
1058 return $loanlength->{issuelength}
1059 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1061 $sth->execute( "*", $itemtype, $branchcode );
1062 $loanlength = $sth->fetchrow_hashref;
1063 return $loanlength->{issuelength}
1064 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1066 $sth->execute( "*", "*", $branchcode );
1067 $loanlength = $sth->fetchrow_hashref;
1068 return $loanlength->{issuelength}
1069 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1071 $sth->execute( $borrowertype, $itemtype, "*" );
1072 $loanlength = $sth->fetchrow_hashref;
1073 return $loanlength->{issuelength}
1074 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1076 $sth->execute( $borrowertype, "*", "*" );
1077 $loanlength = $sth->fetchrow_hashref;
1078 return $loanlength->{issuelength}
1079 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1081 $sth->execute( "*", $itemtype, "*" );
1082 $loanlength = $sth->fetchrow_hashref;
1083 return $loanlength->{issuelength}
1084 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1086 $sth->execute( "*", "*", "*" );
1087 $loanlength = $sth->fetchrow_hashref;
1088 return $loanlength->{issuelength}
1089 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1091 # if no rule is set => 21 days (hardcoded)
1095 =head2 GetIssuingRule
1097 FIXME - This is a copy-paste of GetLoanLength
1098 as a stop-gap. Do not wish to change API for GetLoanLength
1099 this close to release, however, Overdues::GetIssuingRules is broken.
1101 Get the issuing rule for an itemtype, a borrower type and a branch
1102 Returns a hashref from the issuingrules table.
1104 my $irule = &GetIssuingRule($borrowertype,$itemtype,branchcode)
1108 sub GetIssuingRule {
1109 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1110 my $dbh = C4::Context->dbh;
1111 my $sth = $dbh->prepare( "select * from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null" );
1114 $sth->execute( $borrowertype, $itemtype, $branchcode );
1115 $irule = $sth->fetchrow_hashref;
1116 return $irule if defined($irule) ;
1118 $sth->execute( $borrowertype, "*", $branchcode );
1119 $irule = $sth->fetchrow_hashref;
1120 return $irule if defined($irule) ;
1122 $sth->execute( "*", $itemtype, $branchcode );
1123 $irule = $sth->fetchrow_hashref;
1124 return $irule if defined($irule) ;
1126 $sth->execute( "*", "*", $branchcode );
1127 $irule = $sth->fetchrow_hashref;
1128 return $irule if defined($irule) ;
1130 $sth->execute( $borrowertype, $itemtype, "*" );
1131 $irule = $sth->fetchrow_hashref;
1132 return $irule if defined($irule) ;
1134 $sth->execute( $borrowertype, "*", "*" );
1135 $irule = $sth->fetchrow_hashref;
1136 return $irule if defined($irule) ;
1138 $sth->execute( "*", $itemtype, "*" );
1139 $irule = $sth->fetchrow_hashref;
1140 return $irule if defined($irule) ;
1142 $sth->execute( "*", "*", "*" );
1143 $irule = $sth->fetchrow_hashref;
1144 return $irule if defined($irule) ;
1146 # if no rule matches,
1150 =head2 GetBranchBorrowerCircRule
1154 my $branch_cat_rule = GetBranchBorrowerCircRule($branchcode, $categorycode);
1158 Retrieves circulation rule attributes that apply to the given
1159 branch and patron category, regardless of item type.
1160 The return value is a hashref containing the following key:
1162 maxissueqty - maximum number of loans that a
1163 patron of the given category can have at the given
1164 branch. If the value is undef, no limit.
1166 This will first check for a specific branch and
1167 category match from branch_borrower_circ_rules.
1169 If no rule is found, it will then check default_branch_circ_rules
1170 (same branch, default category). If no rule is found,
1171 it will then check default_borrower_circ_rules (default
1172 branch, same category), then failing that, default_circ_rules
1173 (default branch, default category).
1175 If no rule has been found in the database, it will default to
1180 C<$branchcode> and C<$categorycode> should contain the
1181 literal branch code and patron category code, respectively - no
1186 sub GetBranchBorrowerCircRule {
1187 my $branchcode = shift;
1188 my $categorycode = shift;
1190 my $branch_cat_query = "SELECT maxissueqty
1191 FROM branch_borrower_circ_rules
1192 WHERE branchcode = ?
1193 AND categorycode = ?";
1194 my $dbh = C4::Context->dbh();
1195 my $sth = $dbh->prepare($branch_cat_query);
1196 $sth->execute($branchcode, $categorycode);
1198 if ($result = $sth->fetchrow_hashref()) {
1202 # try same branch, default borrower category
1203 my $branch_query = "SELECT maxissueqty
1204 FROM default_branch_circ_rules
1205 WHERE branchcode = ?";
1206 $sth = $dbh->prepare($branch_query);
1207 $sth->execute($branchcode);
1208 if ($result = $sth->fetchrow_hashref()) {
1212 # try default branch, same borrower category
1213 my $category_query = "SELECT maxissueqty
1214 FROM default_borrower_circ_rules
1215 WHERE categorycode = ?";
1216 $sth = $dbh->prepare($category_query);
1217 $sth->execute($categorycode);
1218 if ($result = $sth->fetchrow_hashref()) {
1222 # try default branch, default borrower category
1223 my $default_query = "SELECT maxissueqty
1224 FROM default_circ_rules";
1225 $sth = $dbh->prepare($default_query);
1227 if ($result = $sth->fetchrow_hashref()) {
1231 # built-in default circulation rule
1233 maxissueqty => undef,
1239 ($doreturn, $messages, $iteminformation, $borrower) =
1240 &AddReturn($barcode, $branch, $exemptfine, $dropbox);
1246 =item C<$barcode> is the bar code of the book being returned.
1248 =item C<$branch> is the code of the branch where the book is being returned.
1250 =item C<$exemptfine> indicates that overdue charges for the item will be
1253 =item C<$dropbox> indicates that the check-in date is assumed to be
1254 yesterday, or the last non-holiday as defined in C4::Calendar . If
1255 overdue charges are applied and C<$dropbox> is true, the last charge
1256 will be removed. This assumes that the fines accrual script has run
1261 C<&AddReturn> returns a list of four items:
1263 C<$doreturn> is true iff the return succeeded.
1265 C<$messages> is a reference-to-hash giving the reason for failure:
1271 No item with this barcode exists. The value is C<$barcode>.
1275 The book is not currently on loan. The value is C<$barcode>.
1277 =item C<IsPermanent>
1279 The book's home branch is a permanent collection. If you have borrowed
1280 this book, you are not allowed to return it. The value is the code for
1281 the book's home branch.
1285 This book has been withdrawn/cancelled. The value should be ignored.
1289 The item was reserved. The value is a reference-to-hash whose keys are
1290 fields from the reserves table of the Koha database, and
1291 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1292 either C<Waiting>, C<Reserved>, or 0.
1296 C<$iteminformation> is a reference-to-hash, giving information about the
1297 returned item from the issues table.
1299 C<$borrower> is a reference-to-hash, giving information about the
1300 patron who last borrowed the book.
1305 my ( $barcode, $branch, $exemptfine, $dropbox ) = @_;
1306 my $dbh = C4::Context->dbh;
1310 my $validTransfert = 0;
1311 my $reserveDone = 0;
1312 $branch ||=C4::Context->userenv->{'branch'};
1314 # get information on item
1315 my $itemnumber = GetItemnumberFromBarcode($barcode);
1316 my $iteminformation = GetItemIssue( $itemnumber );
1317 my $biblio = GetBiblioItemData($iteminformation->{'biblioitemnumber'});
1318 # use Data::Dumper;warn Data::Dumper::Dumper($iteminformation);
1319 unless ( $iteminformation->{'itemnumber'} or $itemnumber) {
1320 $messages->{'BadBarcode'} = $barcode;
1324 if ( not $iteminformation->{borrowernumber} ) {
1325 $messages->{'NotIssued'} = $barcode;
1329 # even though item is not on loan, it may still
1330 # be transferred; therefore, get current branch information
1331 my $curr_iteminfo = GetItem($itemnumber);
1332 $iteminformation->{'homebranch'} = $curr_iteminfo->{'homebranch'};
1333 $iteminformation->{'holdingbranch'} = $curr_iteminfo->{'holdingbranch'};
1334 $iteminformation->{'itemlost'} = $curr_iteminfo->{'itemlost'};
1336 # check if the book is in a permanent collection....
1337 my $hbr = $iteminformation->{C4::Context->preference("HomeOrHoldingBranch")};
1338 my $branches = GetBranches();
1339 # FIXME -- This 'PE' attribute is largely undocumented. afaict, there's no user interface that reflects this functionality.
1340 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1341 $messages->{'IsPermanent'} = $hbr;
1344 # if independent branches are on and returning to different branch, refuse the return
1345 if ($hbr ne $branch && C4::Context->preference("IndependantBranches") && $iteminformation->{borrowernumber}){
1346 $messages->{'Wrongbranch'} = 1;
1350 # check that the book has been cancelled
1351 if ( $iteminformation->{'wthdrawn'} ) {
1352 $messages->{'wthdrawn'} = 1;
1357 # new op dev : if the book returned in an other branch update the holding branch
1359 # update issues, thereby returning book (should push this out into another subroutine
1360 $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1362 # case of a return of document (deal with issues and holdingbranch)
1365 my $circControlBranch = _GetCircControlBranch($iteminformation,$borrower);
1367 # don't allow dropbox mode to create an invalid entry in issues (issuedate > returndate) FIXME: actually checks eq, not gt
1368 undef($dropbox) if ( $iteminformation->{'issuedate'} eq C4::Dates->today('iso') );
1370 MarkIssueReturned($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'},$circControlBranch);
1371 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1372 # continue to deal with returns cases, but not only if we have an issue
1375 # We update the holdingbranch from circControlBranch variable
1376 UpdateHoldingbranch($branch,$iteminformation->{'itemnumber'});
1377 $iteminformation->{'holdingbranch'} = $branch;
1380 ModDateLastSeen( $iteminformation->{'itemnumber'} );
1381 ModItem({ onloan => undef }, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'});
1383 if ($iteminformation->{borrowernumber}){
1384 ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1388 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1389 # check if we have a transfer for this document
1390 my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1392 # if we have a transfer to do, we update the line of transfers with the datearrived
1394 if ( $tobranch eq $branch ) {
1397 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1399 $sth->execute( $iteminformation->{'itemnumber'} );
1401 # 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'
1402 C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1405 $messages->{'WrongTransfer'} = $tobranch;
1406 $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1408 $validTransfert = 1;
1411 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1412 # fix up the accounts.....
1413 if ($iteminformation->{'itemlost'}) {
1414 FixAccountForLostAndReturned($iteminformation, $borrower);
1415 ModItem({ itemlost => '0' }, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'});
1416 $messages->{'WasLost'} = 1;
1418 # fix up the overdues in accounts...
1419 FixOverduesOnReturn( $borrower->{'borrowernumber'},
1420 $iteminformation->{'itemnumber'}, $exemptfine, $dropbox );
1422 # find reserves.....
1423 # if we don't have a reserve with the status W, we launch the Checkreserves routine
1424 my ( $resfound, $resrec ) =
1425 C4::Reserves::CheckReserves( $itemnumber, $barcode );
1427 $resrec->{'ResFound'} = $resfound;
1428 $messages->{'ResFound'} = $resrec;
1433 # Record the fact that this book was returned.
1435 $branch, 'return', '0', '',
1436 $iteminformation->{'itemnumber'},
1437 $biblio->{'itemtype'},
1438 $borrower->{'borrowernumber'}
1441 logaction("CIRCULATION", "RETURN", $iteminformation->{borrowernumber}, $iteminformation->{'biblionumber'})
1442 if C4::Context->preference("ReturnLog");
1444 #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1445 #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1447 if (($doreturn or $messages->{'NotIssued'}) and ($branch ne $iteminformation->{$hbr}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1448 if (C4::Context->preference("AutomaticItemReturn") == 1) {
1449 ModItemTransfer($iteminformation->{'itemnumber'}, $branch, $iteminformation->{$hbr});
1450 $messages->{'WasTransfered'} = 1;
1453 $messages->{'NeedsTransfer'} = 1;
1457 return ( $doreturn, $messages, $iteminformation, $borrower );
1460 =head2 MarkIssueReturned
1464 MarkIssueReturned($borrowernumber, $itemnumber, $dropbox_branch, $returndate);
1468 Unconditionally marks an issue as being returned by
1469 moving the C<issues> row to C<old_issues> and
1470 setting C<returndate> to the current date, or
1471 the last non-holiday date of the branccode specified in
1472 C<dropbox_branch> . Assumes you've already checked that
1473 it's safe to do this, i.e. last non-holiday > issuedate.
1475 if C<$returndate> is specified (in iso format), it is used as the date
1476 of the return. It is ignored when a dropbox_branch is passed in.
1478 Ideally, this function would be internal to C<C4::Circulation>,
1479 not exported, but it is currently needed by one
1480 routine in C<C4::Accounts>.
1484 sub MarkIssueReturned {
1485 my ( $borrowernumber, $itemnumber, $dropbox_branch, $returndate ) = @_;
1486 my $dbh = C4::Context->dbh;
1487 my $query = "UPDATE issues SET returndate=";
1489 if ($dropbox_branch) {
1490 my $calendar = C4::Calendar->new( branchcode => $dropbox_branch );
1491 my $dropboxdate = $calendar->addDate( C4::Dates->new(), -1 );
1493 push @bind, $dropboxdate->output('iso');
1494 } elsif ($returndate) {
1496 push @bind, $returndate;
1498 $query .= " now() ";
1500 $query .= " WHERE borrowernumber = ? AND itemnumber = ?";
1501 push @bind, $borrowernumber, $itemnumber;
1503 my $sth_upd = $dbh->prepare($query);
1504 $sth_upd->execute(@bind);
1505 my $sth_copy = $dbh->prepare("INSERT INTO old_issues SELECT * FROM issues
1506 WHERE borrowernumber = ?
1507 AND itemnumber = ?");
1508 $sth_copy->execute($borrowernumber, $itemnumber);
1509 my $sth_del = $dbh->prepare("DELETE FROM issues
1510 WHERE borrowernumber = ?
1511 AND itemnumber = ?");
1512 $sth_del->execute($borrowernumber, $itemnumber);
1515 =head2 FixOverduesOnReturn
1517 &FixOverduesOnReturn($brn,$itm, $exemptfine, $dropboxmode);
1519 C<$brn> borrowernumber
1523 C<$exemptfine> BOOL -- remove overdue charge associated with this issue.
1524 C<$dropboxmode> BOOL -- remove lastincrement on overdue charge associated with this issue.
1526 internal function, called only by AddReturn
1530 sub FixOverduesOnReturn {
1531 my ( $borrowernumber, $item, $exemptfine, $dropbox ) = @_;
1532 my $dbh = C4::Context->dbh;
1534 # check for overdue fine
1537 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1539 $sth->execute( $borrowernumber, $item );
1541 # alter fine to show that the book has been returned
1543 if ($data = $sth->fetchrow_hashref) {
1545 my @bind = ($borrowernumber,$item ,$data->{'accountno'});
1547 $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
1548 if (C4::Context->preference("FinesLog")) {
1549 &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
1551 } elsif ($dropbox && $data->{lastincrement}) {
1552 my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
1553 my $amt = $data->{amount} - $data->{lastincrement} ;
1554 if (C4::Context->preference("FinesLog")) {
1555 &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
1557 $uquery = "update accountlines set accounttype='F' ";
1558 if($outstanding >= 0 && $amt >=0) {
1559 $uquery .= ", amount = ? , amountoutstanding=? ";
1560 unshift @bind, ($amt, $outstanding) ;
1563 $uquery = "update accountlines set accounttype='F' ";
1565 $uquery .= " where (borrowernumber = ?) and (itemnumber = ?) and (accountno = ?)";
1566 my $usth = $dbh->prepare($uquery);
1567 $usth->execute(@bind);
1575 =head2 FixAccountForLostAndReturned
1577 &FixAccountForLostAndReturned($iteminfo,$borrower);
1579 Calculates the charge for a book lost and returned (Not exported & used only once)
1581 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1583 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1585 Internal function, called by AddReturn
1589 sub FixAccountForLostAndReturned {
1590 my ($iteminfo, $borrower) = @_;
1591 my $dbh = C4::Context->dbh;
1592 my $itm = $iteminfo->{'itemnumber'};
1593 # check for charge made for lost book
1594 my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1595 $sth->execute($itm);
1596 if (my $data = $sth->fetchrow_hashref) {
1597 # writeoff this amount
1599 my $amount = $data->{'amount'};
1600 my $acctno = $data->{'accountno'};
1602 if ($data->{'amountoutstanding'} == $amount) {
1603 $offset = $data->{'amount'};
1606 $offset = $amount - $data->{'amountoutstanding'};
1607 $amountleft = $data->{'amountoutstanding'} - $amount;
1609 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1610 WHERE (borrowernumber = ?)
1611 AND (itemnumber = ?) AND (accountno = ?) ");
1612 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1613 #check if any credit is left if so writeoff other accounts
1614 my $nextaccntno = getnextacctno($data->{'borrowernumber'});
1615 if ($amountleft < 0){
1618 if ($amountleft > 0){
1619 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1620 AND (amountoutstanding >0) ORDER BY date");
1621 $msth->execute($data->{'borrowernumber'});
1622 # offset transactions
1625 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1626 if ($accdata->{'amountoutstanding'} < $amountleft) {
1628 $amountleft -= $accdata->{'amountoutstanding'};
1630 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1633 my $thisacct = $accdata->{'accountno'};
1634 my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1635 WHERE (borrowernumber = ?)
1636 AND (accountno=?)");
1637 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1639 $usth = $dbh->prepare("INSERT INTO accountoffsets
1640 (borrowernumber, accountno, offsetaccount, offsetamount)
1643 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1645 $msth->finish; # $msth might actually have data left
1647 if ($amountleft > 0){
1650 my $desc="Item Returned ".$iteminfo->{'barcode'};
1651 $usth = $dbh->prepare("INSERT INTO accountlines
1652 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1653 VALUES (?,?,now(),?,?,'CR',?)");
1654 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1655 $usth = $dbh->prepare("INSERT INTO accountoffsets
1656 (borrowernumber, accountno, offsetaccount, offsetamount)
1658 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1659 ModItem({ paidfor => '' }, undef, $itm);
1665 =head2 _GetCircControlBranch
1667 my $circ_control_branch = _GetCircControlBranch($iteminfos, $borrower);
1671 Return the library code to be used to determine which circulation
1672 policy applies to a transaction. Looks up the CircControl and
1673 HomeOrHoldingBranch system preferences.
1675 C<$iteminfos> is a hashref to iteminfo. Only {itemnumber} is used.
1677 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1681 sub _GetCircControlBranch {
1682 my ($iteminfos, $borrower) = @_;
1683 my $circcontrol = C4::Context->preference('CircControl');
1686 if ($circcontrol eq 'PickupLibrary') {
1687 $branch= C4::Context->userenv->{'branch'};
1688 } elsif ($circcontrol eq 'PatronLibrary') {
1689 $branch=$borrower->{branchcode};
1691 my $branchfield = C4::Context->preference('HomeOrHoldingBranch') || 'homebranch';
1692 $branch = $iteminfos->{$branchfield};
1699 $issues = &GetItemIssue($itemnumber);
1701 Returns patron currently having a book, or undef if not checked out.
1703 C<$itemnumber> is the itemnumber
1705 C<$issues> is an array of hashes.
1710 my ($itemnumber) = @_;
1711 return unless $itemnumber;
1712 my $sth = C4::Context->dbh->prepare(
1715 LEFT JOIN items ON issues.itemnumber=items.itemnumber
1716 WHERE issues.itemnumber=?");
1717 $sth->execute($itemnumber);
1718 my $data = $sth->fetchrow_hashref;
1719 return unless $data;
1720 $data->{'overdue'} = ($data->{'date_due'} lt C4::Dates->today('iso')) ? 1 : 0;
1721 $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue.
1722 # FIXME: that would mean issues.itemnumber IS NULL and we didn't really match it.
1726 =head2 GetItemIssues
1728 $issues = &GetItemIssues($itemnumber, $history);
1730 Returns patrons that have issued a book
1732 C<$itemnumber> is the itemnumber
1733 C<$history> is false if you just want the current "issuer" (if any)
1734 and true if you want issues history from old_issues also.
1736 Returns reference to an array of hashes
1741 my ( $itemnumber, $history ) = @_;
1743 my $today = C4::Dates->today('iso'); # get today date
1744 my $sql = "SELECT * FROM issues
1745 JOIN borrowers USING (borrowernumber)
1746 JOIN items USING (itemnumber)
1747 WHERE issues.itemnumber = ? ";
1750 SELECT * FROM old_issues
1751 LEFT JOIN borrowers USING (borrowernumber)
1752 JOIN items USING (itemnumber)
1753 WHERE old_issues.itemnumber = ? ";
1755 $sql .= "ORDER BY date_due DESC";
1756 my $sth = C4::Context->dbh->prepare($sql);
1758 $sth->execute($itemnumber, $itemnumber);
1760 $sth->execute($itemnumber);
1762 my $results = $sth->fetchall_arrayref({});
1763 foreach (@$results) {
1764 $_->{'overdue'} = ($_->{'date_due'} lt $today) ? 1 : 0;
1769 =head2 GetBiblioIssues
1771 $issues = GetBiblioIssues($biblionumber);
1773 this function get all issues from a biblionumber.
1776 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1777 tables issues and the firstname,surname & cardnumber from borrowers.
1781 sub GetBiblioIssues {
1782 my $biblionumber = shift;
1783 return undef unless $biblionumber;
1784 my $dbh = C4::Context->dbh;
1786 SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1788 LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1789 LEFT JOIN items ON issues.itemnumber = items.itemnumber
1790 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1791 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1792 WHERE biblio.biblionumber = ?
1794 SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1796 LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
1797 LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
1798 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1799 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1800 WHERE biblio.biblionumber = ?
1803 my $sth = $dbh->prepare($query);
1804 $sth->execute($biblionumber, $biblionumber);
1807 while ( my $data = $sth->fetchrow_hashref ) {
1808 push @issues, $data;
1813 =head2 GetUpcomingDueIssues
1817 my $upcoming_dues = GetUpcomingDueIssues( { days_in_advance => 4 } );
1823 sub GetUpcomingDueIssues {
1826 $params->{'days_in_advance'} = 7 unless exists $params->{'days_in_advance'};
1827 my $dbh = C4::Context->dbh;
1829 my $statement = <<END_SQL;
1830 SELECT issues.*, items.itype as itemtype, items.homebranch, TO_DAYS( date_due )-TO_DAYS( NOW() ) as days_until_due
1832 LEFT JOIN items USING (itemnumber)
1833 WhERE returndate is NULL
1834 AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ?
1837 my @bind_parameters = ( $params->{'days_in_advance'} );
1839 my $sth = $dbh->prepare( $statement );
1840 $sth->execute( @bind_parameters );
1841 my $upcoming_dues = $sth->fetchall_arrayref({});
1844 return $upcoming_dues;
1847 =head2 CanBookBeRenewed
1849 ($ok,$error) = &CanBookBeRenewed($borrowernumber, $itemnumber[, $override_limit]);
1851 Find out whether a borrowed item may be renewed.
1853 C<$dbh> is a DBI handle to the Koha database.
1855 C<$borrowernumber> is the borrower number of the patron who currently
1856 has the item on loan.
1858 C<$itemnumber> is the number of the item to renew.
1860 C<$override_limit>, if supplied with a true value, causes
1861 the limit on the number of times that the loan can be renewed
1862 (as controlled by the item type) to be ignored.
1864 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1865 item must currently be on loan to the specified borrower; renewals
1866 must be allowed for the item's type; and the borrower must not have
1867 already renewed the loan. $error will contain the reason the renewal can not proceed
1871 sub CanBookBeRenewed {
1873 # check renewal status
1874 my ( $borrowernumber, $itemnumber, $override_limit ) = @_;
1875 my $dbh = C4::Context->dbh;
1880 # Look in the issues table for this item, lent to this borrower,
1881 # and not yet returned.
1883 # FIXME - I think this function could be redone to use only one SQL call.
1884 my $sth1 = $dbh->prepare(
1885 "SELECT * FROM issues
1886 WHERE borrowernumber = ?
1889 $sth1->execute( $borrowernumber, $itemnumber );
1890 if ( my $data1 = $sth1->fetchrow_hashref ) {
1892 # Found a matching item
1894 # See if this item may be renewed. This query is convoluted
1895 # because it's a bit messy: given the item number, we need to find
1896 # the biblioitem, which gives us the itemtype, which tells us
1897 # whether it may be renewed.
1898 my $query = "SELECT renewalsallowed FROM items ";
1899 $query .= (C4::Context->preference('item-level_itypes'))
1900 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1901 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1902 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1903 $query .= "WHERE items.itemnumber = ?";
1904 my $sth2 = $dbh->prepare($query);
1905 $sth2->execute($itemnumber);
1906 if ( my $data2 = $sth2->fetchrow_hashref ) {
1907 $renews = $data2->{'renewalsallowed'};
1909 if ( ( $renews && $renews > $data1->{'renewals'} ) || $override_limit ) {
1916 my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1924 return ($renewokay,$error);
1929 &AddRenewal($borrowernumber, $itemnumber, $branch, [$datedue], [$lastreneweddate]);
1933 C<$borrowernumber> is the borrower number of the patron who currently
1936 C<$itemnumber> is the number of the item to renew.
1938 C<$branch> is the library where the renewal took place (if any).
1939 The library that controls the circ policies for the renewal is retrieved from the issues record.
1941 C<$datedue> can be a C4::Dates object used to set the due date.
1943 C<$lastreneweddate> is an optional ISO-formatted date used to set issues.lastreneweddate. If
1944 this parameter is not supplied, lastreneweddate is set to the current date.
1946 If C<$datedue> is the empty string, C<&AddRenewal> will calculate the due date automatically
1947 from the book's item type.
1953 my $borrowernumber = shift or return undef;
1954 my $itemnumber = shift or return undef;
1955 my $item = GetItem($itemnumber) or return undef;
1956 my $branch = (@_) ? shift : $item->{homebranch}; # opac-renew doesn't send branch
1957 my $datedue = shift;
1958 my $lastreneweddate = shift || C4::Dates->new()->output('iso');
1961 my $biblio = GetBiblioFromItemNumber($itemnumber) or return undef;
1963 # If the due date wasn't specified, calculate it by adding the
1964 # book's loan length to today's date.
1965 unless ($datedue && $datedue->output('iso')) {
1967 my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 ) or return undef;
1968 my $loanlength = GetLoanLength(
1969 $borrower->{'categorycode'},
1970 (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1971 $item->{homebranch} # item's homebranch determines loanlength OR do we want the branch specified by the AddRenewal argument?
1973 #FIXME -- use circControl?
1974 $datedue = CalcDateDue(C4::Dates->new(),$loanlength,$branch); # this branch is the transactional branch.
1975 # The question of whether to use item's homebranch calendar is open.
1978 # $lastreneweddate defaults to today.
1979 unless (defined $lastreneweddate) {
1980 $lastreneweddate = strftime( "%Y-%m-%d", localtime );
1983 my $dbh = C4::Context->dbh;
1984 # Find the issues record for this book
1986 $dbh->prepare("SELECT * FROM issues
1987 WHERE borrowernumber=?
1990 $sth->execute( $borrowernumber, $itemnumber );
1991 my $issuedata = $sth->fetchrow_hashref;
1993 if($datedue && ! $datedue->output('iso')){
1994 warn "Invalid date passed to AddRenewal.";
1997 # If the due date wasn't specified, calculate it by adding the
1998 # book's loan length to today's date or the current due date
1999 # based on the value of the RenewalPeriodBase syspref.
2002 my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 ) or return undef;
2003 my $loanlength = GetLoanLength(
2004 $borrower->{'categorycode'},
2005 (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
2006 $issuedata->{'branchcode'} ); # that's the circ control branch.
2008 $datedue = (C4::Context->preference('RenewalPeriodBase') eq 'date_due') ?
2009 C4::Dates->new($issuedata->{date_due}, 'iso') :
2011 $datedue = CalcDateDue($datedue,$loanlength,$issuedata->{'branchcode'},$borrower);
2014 # Update the issues record to have the new due date, and a new count
2015 # of how many times it has been renewed.
2016 my $renews = $issuedata->{'renewals'} + 1;
2017 $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?, lastreneweddate = ?
2018 WHERE borrowernumber=?
2021 $sth->execute( $datedue->output('iso'), $renews, $lastreneweddate, $borrowernumber, $itemnumber );
2024 # Update the renewal count on the item, and tell zebra to reindex
2025 $renews = $biblio->{'renewals'} + 1;
2026 ModItem({ renewals => $renews, onloan => $datedue->output('iso') }, $biblio->{'biblionumber'}, $itemnumber);
2028 # Charge a new rental fee, if applicable?
2029 my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2030 if ( $charge > 0 ) {
2031 my $accountno = getnextacctno( $borrowernumber );
2032 my $item = GetBiblioFromItemNumber($itemnumber);
2033 $sth = $dbh->prepare(
2034 "INSERT INTO accountlines
2036 borrowernumber, accountno, amount,
2038 accounttype, amountoutstanding, itemnumber
2040 VALUES (now(),?,?,?,?,?,?,?)"
2042 $sth->execute( $borrowernumber, $accountno, $charge,
2043 "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
2044 'Rent', $charge, $itemnumber );
2048 UpdateStats( $branch, 'renew', $charge, '', $itemnumber, $item->{itype}, $borrowernumber);
2053 # check renewal status
2054 my ($bornum,$itemno)=@_;
2055 my $dbh = C4::Context->dbh;
2057 my $renewsallowed = 0;
2059 # Look in the issues table for this item, lent to this borrower,
2060 # and not yet returned.
2062 # FIXME - I think this function could be redone to use only one SQL call.
2063 my $sth = $dbh->prepare("select * from issues
2064 where (borrowernumber = ?)
2065 and (itemnumber = ?)");
2066 $sth->execute($bornum,$itemno);
2067 my $data = $sth->fetchrow_hashref;
2068 $renewcount = $data->{'renewals'} if $data->{'renewals'};
2070 my $query = "SELECT renewalsallowed FROM items ";
2071 $query .= (C4::Context->preference('item-level_itypes'))
2072 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2073 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
2074 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2075 $query .= "WHERE items.itemnumber = ?";
2076 my $sth2 = $dbh->prepare($query);
2077 $sth2->execute($itemno);
2078 my $data2 = $sth2->fetchrow_hashref();
2079 $renewsallowed = $data2->{'renewalsallowed'};
2080 $renewsleft = $renewsallowed - $renewcount;
2081 return ($renewcount,$renewsallowed,$renewsleft);
2084 =head2 GetIssuingCharges
2086 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
2088 Calculate how much it would cost for a given patron to borrow a given
2089 item, including any applicable discounts.
2091 C<$itemnumber> is the item number of item the patron wishes to borrow.
2093 C<$borrowernumber> is the patron's borrower number.
2095 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
2096 and C<$item_type> is the code for the item's item type (e.g., C<VID>
2101 sub GetIssuingCharges {
2103 # calculate charges due
2104 my ( $itemnumber, $borrowernumber ) = @_;
2106 my $dbh = C4::Context->dbh;
2109 # Get the book's item type and rental charge (via its biblioitem).
2110 my $qcharge = "SELECT itemtypes.itemtype,rentalcharge FROM items
2111 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
2112 $qcharge .= (C4::Context->preference('item-level_itypes'))
2113 ? " LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2114 : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2116 $qcharge .= "WHERE items.itemnumber =?";
2118 my $sth1 = $dbh->prepare($qcharge);
2119 $sth1->execute($itemnumber);
2120 if ( my $data1 = $sth1->fetchrow_hashref ) {
2121 $item_type = $data1->{'itemtype'};
2122 $charge = $data1->{'rentalcharge'};
2123 my $q2 = "SELECT rentaldiscount FROM borrowers
2124 LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
2125 WHERE borrowers.borrowernumber = ?
2126 AND issuingrules.itemtype = ?";
2127 my $sth2 = $dbh->prepare($q2);
2128 $sth2->execute( $borrowernumber, $item_type );
2129 if ( my $data2 = $sth2->fetchrow_hashref ) {
2130 my $discount = $data2->{'rentaldiscount'};
2131 if ( $discount eq 'NULL' ) {
2134 $charge = ( $charge * ( 100 - $discount ) ) / 100;
2140 return ( $charge, $item_type );
2143 =head2 AddIssuingCharge
2145 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
2149 sub AddIssuingCharge {
2150 my ( $itemnumber, $borrowernumber, $charge ) = @_;
2151 my $dbh = C4::Context->dbh;
2152 my $nextaccntno = getnextacctno( $borrowernumber );
2154 INSERT INTO accountlines
2155 (borrowernumber, itemnumber, accountno,
2156 date, amount, description, accounttype,
2158 VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
2160 my $sth = $dbh->prepare($query);
2161 $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
2167 GetTransfers($itemnumber);
2172 my ($itemnumber) = @_;
2174 my $dbh = C4::Context->dbh;
2180 FROM branchtransfers
2181 WHERE itemnumber = ?
2182 AND datearrived IS NULL
2184 my $sth = $dbh->prepare($query);
2185 $sth->execute($itemnumber);
2186 my @row = $sth->fetchrow_array();
2192 =head2 GetTransfersFromTo
2194 @results = GetTransfersFromTo($frombranch,$tobranch);
2196 Returns the list of pending transfers between $from and $to branch
2200 sub GetTransfersFromTo {
2201 my ( $frombranch, $tobranch ) = @_;
2202 return unless ( $frombranch && $tobranch );
2203 my $dbh = C4::Context->dbh;
2205 SELECT itemnumber,datesent,frombranch
2206 FROM branchtransfers
2209 AND datearrived IS NULL
2211 my $sth = $dbh->prepare($query);
2212 $sth->execute( $frombranch, $tobranch );
2215 while ( my $data = $sth->fetchrow_hashref ) {
2216 push @gettransfers, $data;
2219 return (@gettransfers);
2222 =head2 DeleteTransfer
2224 &DeleteTransfer($itemnumber);
2228 sub DeleteTransfer {
2229 my ($itemnumber) = @_;
2230 my $dbh = C4::Context->dbh;
2231 my $sth = $dbh->prepare(
2232 "DELETE FROM branchtransfers
2234 AND datearrived IS NULL "
2236 $sth->execute($itemnumber);
2240 =head2 AnonymiseIssueHistory
2242 $rows = AnonymiseIssueHistory($borrowernumber,$date)
2244 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
2245 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
2247 return the number of affected rows.
2251 sub AnonymiseIssueHistory {
2253 my $borrowernumber = shift;
2254 my $dbh = C4::Context->dbh;
2257 SET borrowernumber = NULL
2258 WHERE returndate < '".$date."'
2259 AND borrowernumber IS NOT NULL
2261 $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
2262 my $rows_affected = $dbh->do($query);
2263 return $rows_affected;
2266 =head2 updateWrongTransfer
2268 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
2270 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
2274 sub updateWrongTransfer {
2275 my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
2276 my $dbh = C4::Context->dbh;
2277 # first step validate the actual line of transfert .
2280 "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
2282 $sth->execute($FromLibrary,$itemNumber);
2285 # second step create a new line of branchtransfer to the right location .
2286 ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
2288 #third step changing holdingbranch of item
2289 UpdateHoldingbranch($FromLibrary,$itemNumber);
2292 =head2 UpdateHoldingbranch
2294 $items = UpdateHoldingbranch($branch,$itmenumber);
2295 Simple methode for updating hodlingbranch in items BDD line
2299 sub UpdateHoldingbranch {
2300 my ( $branch,$itemnumber ) = @_;
2301 ModItem({ holdingbranch => $branch }, undef, $itemnumber);
2306 $newdatedue = CalcDateDue($startdate,$loanlength,$branchcode);
2307 this function calculates the due date given the loan length ,
2308 checking against the holidays calendar as per the 'useDaysMode' syspref.
2309 C<$startdate> = C4::Dates object representing start date of loan period (assumed to be today)
2310 C<$branch> = location whose calendar to use
2311 C<$loanlength> = loan length prior to adjustment
2315 my ($startdate,$loanlength,$branch,$borrower) = @_;
2318 if(C4::Context->preference('useDaysMode') eq 'Days') { # ignoring calendar
2319 my $timedue = time + ($loanlength) * 86400;
2320 #FIXME - assumes now even though we take a startdate
2321 my @datearr = localtime($timedue);
2322 $datedue = C4::Dates->new( sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
2324 my $calendar = C4::Calendar->new( branchcode => $branch );
2325 $datedue = $calendar->addDate($startdate, $loanlength);
2328 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
2329 if ( C4::Context->preference('ReturnBeforeExpiry') && $datedue->output('iso') gt $borrower->{dateexpiry} ) {
2330 $datedue = C4::Dates->new( $borrower->{dateexpiry}, 'iso' );
2333 # if ceilingDueDate ON the datedue can't be after the ceiling date
2334 if ( C4::Context->preference('ceilingDueDate')
2335 && ( C4::Context->preference('ceilingDueDate') =~ C4::Dates->regexp('syspref') )
2336 && $datedue->output gt C4::Context->preference('ceilingDueDate') ) {
2337 $datedue = C4::Dates->new( C4::Context->preference('ceilingDueDate') );
2343 =head2 CheckValidDatedue
2344 This function does not account for holiday exceptions nor does it handle the 'useDaysMode' syspref .
2345 To be replaced by CalcDateDue() once C4::Calendar use is tested.
2347 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
2348 this function validates the loan length against the holidays calendar, and adjusts the due date as per the 'useDaysMode' syspref.
2349 C<$date_due> = returndate calculate with no day check
2350 C<$itemnumber> = itemnumber
2351 C<$branchcode> = location of issue (affected by 'CircControl' syspref)
2352 C<$loanlength> = loan length prior to adjustment
2355 sub CheckValidDatedue {
2356 my ($date_due,$itemnumber,$branchcode)=@_;
2357 my @datedue=split('-',$date_due->output('iso'));
2358 my $years=$datedue[0];
2359 my $month=$datedue[1];
2360 my $day=$datedue[2];
2361 # die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
2363 for (my $i=0;$i<2;$i++){
2364 $dow=Day_of_Week($years,$month,$day);
2365 ($dow=0) if ($dow>6);
2366 my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
2367 my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2368 my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2369 if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
2371 (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
2374 my $newdatedue=C4::Dates->new(sprintf("%04d-%02d-%02d",$years,$month,$day),'iso');
2379 =head2 CheckRepeatableHolidays
2381 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
2382 this function checks if the date due is a repeatable holiday
2383 C<$date_due> = returndate calculate with no day check
2384 C<$itemnumber> = itemnumber
2385 C<$branchcode> = localisation of issue
2389 sub CheckRepeatableHolidays{
2390 my($itemnumber,$week_day,$branchcode)=@_;
2391 my $dbh = C4::Context->dbh;
2392 my $query = qq|SELECT count(*)
2393 FROM repeatable_holidays
2396 my $sth = $dbh->prepare($query);
2397 $sth->execute($branchcode,$week_day);
2398 my $result=$sth->fetchrow;
2404 =head2 CheckSpecialHolidays
2406 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2407 this function check if the date is a special holiday
2408 C<$years> = the years of datedue
2409 C<$month> = the month of datedue
2410 C<$day> = the day of datedue
2411 C<$itemnumber> = itemnumber
2412 C<$branchcode> = localisation of issue
2416 sub CheckSpecialHolidays{
2417 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
2418 my $dbh = C4::Context->dbh;
2419 my $query=qq|SELECT count(*)
2420 FROM `special_holidays`
2426 my $sth = $dbh->prepare($query);
2427 $sth->execute($years,$month,$day,$branchcode);
2428 my $countspecial=$sth->fetchrow ;
2430 return $countspecial;
2433 =head2 CheckRepeatableSpecialHolidays
2435 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2436 this function check if the date is a repeatble special holidays
2437 C<$month> = the month of datedue
2438 C<$day> = the day of datedue
2439 C<$itemnumber> = itemnumber
2440 C<$branchcode> = localisation of issue
2444 sub CheckRepeatableSpecialHolidays{
2445 my ($month,$day,$itemnumber,$branchcode) = @_;
2446 my $dbh = C4::Context->dbh;
2447 my $query=qq|SELECT count(*)
2448 FROM `repeatable_holidays`
2453 my $sth = $dbh->prepare($query);
2454 $sth->execute($month,$day,$branchcode);
2455 my $countspecial=$sth->fetchrow ;
2457 return $countspecial;
2462 sub CheckValidBarcode{
2464 my $dbh = C4::Context->dbh;
2465 my $query=qq|SELECT count(*)
2469 my $sth = $dbh->prepare($query);
2470 $sth->execute($barcode);
2471 my $exist=$sth->fetchrow ;
2482 Koha Developement team <info@koha.org>