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
74 &GetBranchBorrowerCircRule
76 &AnonymiseIssueHistory
79 # subs to deal with returns
85 # subs to deal with transfers
92 &IsBranchTransferAllowed
93 &CreateBranchTransferLimit
94 &DeleteBranchTransferLimits
100 C4::Circulation - Koha circulation module
108 The functions in this module deal with circulation, issues, and
109 returns, as well as general information about the library.
110 Also deals with stocktaking.
116 =head3 $str = &barcodedecode($barcode);
120 =item Generic filter function for barcode string.
121 Called on every circ if the System Pref itemBarcodeInputFilter is set.
122 Will do some manipulation of the barcode for systems that deliver a barcode
123 to circulation.pl that differs from the barcode stored for the item.
124 For proper functioning of this filter, calling the function on the
125 correct barcode string (items.barcode) should return an unaltered barcode.
131 # FIXME -- the &decode fcn below should be wrapped into this one.
132 # FIXME -- these plugins should be moved out of Circulation.pm
136 my $filter = C4::Context->preference('itemBarcodeInputFilter');
137 if($filter eq 'whitespace') {
140 } elsif($filter eq 'cuecat') {
142 my @fields = split( /\./, $barcode );
143 my @results = map( decode($_), @fields[ 1 .. $#fields ] );
144 if ( $#results == 2 ) {
150 } elsif($filter eq 'T-prefix') {
151 if ( $barcode =~ /^[Tt]/) {
152 if (substr($barcode,1,1) eq '0') {
155 $barcode = substr($barcode,2) + 0 ;
158 return sprintf( "T%07d",$barcode);
164 =head3 $str = &decode($chunk);
168 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
178 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
179 my @s = map { index( $seq, $_ ); } split( //, $encoded );
180 my $l = ( $#s + 1 ) % 4;
191 my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
193 chr( ( $n >> 16 ) ^ 67 )
194 .chr( ( $n >> 8 & 255 ) ^ 67 )
195 .chr( ( $n & 255 ) ^ 67 );
198 $r = substr( $r, 0, length($r) - $l );
204 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
206 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
208 C<$newbranch> is the code for the branch to which the item should be transferred.
210 C<$barcode> is the barcode of the item to be transferred.
212 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
213 Otherwise, if an item is reserved, the transfer fails.
215 Returns three values:
219 is true if the transfer was successful.
223 is a reference-to-hash which may have any of the following keys:
229 There is no item in the catalog with the given barcode. The value is C<$barcode>.
233 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.
235 =item C<DestinationEqualsHolding>
237 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.
241 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.
245 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>.
247 =item C<WasTransferred>
249 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
256 my ( $tbr, $barcode, $ignoreRs ) = @_;
259 my $branches = GetBranches();
260 my $itemnumber = GetItemnumberFromBarcode( $barcode );
261 my $issue = GetItemIssue($itemnumber);
262 my $biblio = GetBiblioFromItemNumber($itemnumber);
265 if ( not $itemnumber ) {
266 $messages->{'BadBarcode'} = $barcode;
270 # get branches of book...
271 my $hbr = $biblio->{'homebranch'};
272 my $fbr = $biblio->{'holdingbranch'};
274 # if using Branch Transfer Limits
275 if ( C4::Context->preference("UseBranchTransferLimits") == 1 ) {
276 if ( C4::Context->preference("item-level_itypes") ) {
277 if ( ! IsBranchTransferAllowed( $tbr, $fbr, $biblio->{'itype'} ) ) {
278 $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{'itype'};
281 } elsif ( ! IsBranchTransferAllowed( $tbr, $fbr, $biblio->{'itemtype'} ) ) {
282 $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{'itemtype'};
288 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
289 $messages->{'IsPermanent'} = $hbr;
293 # can't transfer book if is already there....
294 if ( $fbr eq $tbr ) {
295 $messages->{'DestinationEqualsHolding'} = 1;
299 # check if it is still issued to someone, return it...
300 if ($issue->{borrowernumber}) {
301 AddReturn( $barcode, $fbr );
302 $messages->{'WasReturned'} = $issue->{borrowernumber};
306 # That'll save a database query.
307 my ( $resfound, $resrec ) =
308 CheckReserves( $itemnumber );
309 if ( $resfound and not $ignoreRs ) {
310 $resrec->{'ResFound'} = $resfound;
312 # $messages->{'ResFound'} = $resrec;
316 #actually do the transfer....
318 ModItemTransfer( $itemnumber, $fbr, $tbr );
320 # don't need to update MARC anymore, we do it in batch now
321 $messages->{'WasTransfered'} = 1;
322 ModDateLastSeen( $itemnumber );
324 return ( $dotransfer, $messages, $biblio );
329 my $borrower = shift;
330 my $biblionumber = shift;
332 my $cat_borrower = $borrower->{'categorycode'};
333 my $dbh = C4::Context->dbh;
335 # Get which branchcode we need
336 if (C4::Context->preference('CircControl') eq 'PickupLibrary'){
337 $branch = C4::Context->userenv->{'branch'};
339 elsif (C4::Context->preference('CircControl') eq 'PatronLibrary'){
340 $branch = $borrower->{'branchcode'};
344 $branch = $item->{'homebranch'};
346 my $type = (C4::Context->preference('item-level_itypes'))
347 ? $item->{'itype'} # item-level
348 : $item->{'itemtype'}; # biblio-level
350 # given branch, patron category, and item type, determine
351 # applicable issuing rule
352 my $issuing_rule = GetIssuingRule($cat_borrower, $type, $branch);
354 # if a rule is found and has a loan limit set, count
355 # how many loans the patron already has that meet that
357 if (defined($issuing_rule) and defined($issuing_rule->{'maxissueqty'})) {
359 my $count_query = "SELECT COUNT(*) FROM issues
360 JOIN items USING (itemnumber) ";
362 my $rule_itemtype = $issuing_rule->{itemtype};
363 if ($rule_itemtype eq "*") {
364 # matching rule has the default item type, so count only
365 # those existing loans that don't fall under a more
367 if (C4::Context->preference('item-level_itypes')) {
368 $count_query .= " WHERE items.itype NOT IN (
369 SELECT itemtype FROM issuingrules
371 AND (categorycode = ? OR categorycode = ?)
375 $count_query .= " JOIN biblioitems USING (biblionumber)
376 WHERE biblioitems.itemtype NOT IN (
377 SELECT itemtype FROM issuingrules
379 AND (categorycode = ? OR categorycode = ?)
383 push @bind_params, $issuing_rule->{branchcode};
384 push @bind_params, $issuing_rule->{categorycode};
385 push @bind_params, $cat_borrower;
387 # rule has specific item type, so count loans of that
389 if (C4::Context->preference('item-level_itypes')) {
390 $count_query .= " WHERE items.itype = ? ";
392 $count_query .= " JOIN biblioitems USING (biblionumber)
393 WHERE biblioitems.itemtype= ? ";
395 push @bind_params, $type;
398 $count_query .= " AND borrowernumber = ? ";
399 push @bind_params, $borrower->{'borrowernumber'};
400 my $rule_branch = $issuing_rule->{branchcode};
401 if ($rule_branch ne "*") {
402 if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
403 $count_query .= " AND issues.branchcode = ? ";
404 push @bind_params, $branch;
405 } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
406 ; # if branch is the patron's home branch, then count all loans by patron
408 $count_query .= " AND items.homebranch = ? ";
409 push @bind_params, $branch;
413 my $count_sth = $dbh->prepare($count_query);
414 $count_sth->execute(@bind_params);
415 my ($current_loan_count) = $count_sth->fetchrow_array;
417 my $max_loans_allowed = $issuing_rule->{'maxissueqty'};
418 if ($current_loan_count >= $max_loans_allowed) {
419 return "$current_loan_count / $max_loans_allowed";
423 # Now count total loans against the limit for the branch
424 my $branch_borrower_circ_rule = GetBranchBorrowerCircRule($branch, $cat_borrower);
425 if (defined($branch_borrower_circ_rule->{maxissueqty})) {
426 my @bind_params = ();
427 my $branch_count_query = "SELECT COUNT(*) FROM issues
428 JOIN items USING (itemnumber)
429 WHERE borrowernumber = ? ";
430 push @bind_params, $borrower->{borrowernumber};
432 if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
433 $branch_count_query .= " AND issues.branchcode = ? ";
434 push @bind_params, $branch;
435 } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
436 ; # if branch is the patron's home branch, then count all loans by patron
438 $branch_count_query .= " AND items.homebranch = ? ";
439 push @bind_params, $branch;
441 my $branch_count_sth = $dbh->prepare($branch_count_query);
442 $branch_count_sth->execute(@bind_params);
443 my ($current_loan_count) = $branch_count_sth->fetchrow_array;
445 my $max_loans_allowed = $branch_borrower_circ_rule->{maxissueqty};
446 if ($current_loan_count >= $max_loans_allowed) {
447 return "$current_loan_count / $max_loans_allowed";
451 # OK, the patron can issue !!!
457 @issues = &itemissues($biblioitemnumber, $biblio);
459 Looks up information about who has borrowed the bookZ<>(s) with the
460 given biblioitemnumber.
462 C<$biblio> is ignored.
464 C<&itemissues> returns an array of references-to-hash. The keys
465 include the fields from the C<items> table in the Koha database.
466 Additional keys include:
472 If the item is currently on loan, this gives the due date.
474 If the item is not on loan, then this is either "Available" or
475 "Cancelled", if the item has been withdrawn.
479 If the item is currently on loan, this gives the card number of the
480 patron who currently has the item.
482 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
484 These give the timestamp for the last three times the item was
487 =item C<card0>, C<card1>, C<card2>
489 The card number of the last three patrons who borrowed this item.
491 =item C<borrower0>, C<borrower1>, C<borrower2>
493 The borrower number of the last three patrons who borrowed this item.
501 my ( $bibitem, $biblio ) = @_;
502 my $dbh = C4::Context->dbh;
504 $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
509 $sth->execute($bibitem) || die $sth->errstr;
511 while ( my $data = $sth->fetchrow_hashref ) {
513 # Find out who currently has this item.
514 # FIXME - Wouldn't it be better to do this as a left join of
515 # some sort? Currently, this code assumes that if
516 # fetchrow_hashref() fails, then the book is on the shelf.
517 # fetchrow_hashref() can fail for any number of reasons (e.g.,
518 # database server crash), not just because no items match the
520 my $sth2 = $dbh->prepare(
521 "SELECT * FROM issues
522 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
527 $sth2->execute( $data->{'itemnumber'} );
528 if ( my $data2 = $sth2->fetchrow_hashref ) {
529 $data->{'date_due'} = $data2->{'date_due'};
530 $data->{'card'} = $data2->{'cardnumber'};
531 $data->{'borrower'} = $data2->{'borrowernumber'};
534 $data->{'date_due'} = ($data->{'wthdrawn'} eq '1') ? 'Cancelled' : 'Available';
539 # Find the last 3 people who borrowed this item.
540 $sth2 = $dbh->prepare(
541 "SELECT * FROM old_issues
542 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
544 ORDER BY returndate DESC,timestamp DESC"
547 $sth2->execute( $data->{'itemnumber'} );
548 for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
549 { # FIXME : error if there is less than 3 pple borrowing this item
550 if ( my $data2 = $sth2->fetchrow_hashref ) {
551 $data->{"timestamp$i2"} = $data2->{'timestamp'};
552 $data->{"card$i2"} = $data2->{'cardnumber'};
553 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
558 $results[$i] = $data;
566 =head2 CanBookBeIssued
568 Check if a book can be issued.
570 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $borrower, $barcode, $duedatespec, $inprocess );
572 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
576 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
578 =item C<$barcode> is the bar code of the book being issued.
580 =item C<$duedatespec> is a C4::Dates object.
590 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
591 Possible values are :
597 sticky due date is invalid
601 borrower gone with no address
605 borrower declared it's card lost
611 =head3 UNKNOWN_BARCODE
625 item is restricted (set by ??)
627 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
628 Possible values are :
636 renewing, not issuing
638 =head3 ISSUED_TO_ANOTHER
640 issued to someone else.
644 reserved for someone else.
648 sticky due date is invalid
652 if the borrower borrows to much things
656 sub CanBookBeIssued {
657 my ( $borrower, $barcode, $duedate, $inprocess ) = @_;
658 my %needsconfirmation; # filled with problems that needs confirmations
659 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
660 my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
661 my $issue = GetItemIssue($item->{itemnumber});
662 my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
663 $item->{'itemtype'}=$item->{'itype'};
664 my $dbh = C4::Context->dbh;
667 # DUE DATE is OK ? -- should already have checked.
669 #$issuingimpossible{INVALID_DATE} = 1 unless ($duedate);
674 if ( $borrower->{'category_type'} eq 'X' && ( $item->{barcode} )) {
675 # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1 .
676 &UpdateStats(C4::Context->userenv->{'branch'},'localuse','','',$item->{'itemnumber'},$item->{'itemtype'},$borrower->{'borrowernumber'});
677 return( { STATS => 1 }, {});
679 if ( $borrower->{flags}->{GNA} ) {
680 $issuingimpossible{GNA} = 1;
682 if ( $borrower->{flags}->{'LOST'} ) {
683 $issuingimpossible{CARD_LOST} = 1;
685 if ( $borrower->{flags}->{'DBARRED'} ) {
686 $issuingimpossible{DEBARRED} = 1;
688 if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
689 $issuingimpossible{EXPIRED} = 1;
691 my @expirydate= split /-/,$borrower->{'dateexpiry'};
692 if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
693 Date_to_Days(Today) > Date_to_Days( @expirydate )) {
694 $issuingimpossible{EXPIRED} = 1;
703 C4::Members::GetMemberAccountRecords( $borrower->{'borrowernumber'}, '' && $duedate->output('iso') );
704 if ( C4::Context->preference("IssuingInProcess") ) {
705 my $amountlimit = C4::Context->preference("noissuescharge");
706 if ( $amount > $amountlimit && !$inprocess ) {
707 $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
709 elsif ( $amount > 0 && $amount <= $amountlimit && !$inprocess ) {
710 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
715 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
720 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
722 my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
723 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
728 unless ( $item->{barcode} ) {
729 $issuingimpossible{UNKNOWN_BARCODE} = 1;
731 if ( $item->{'notforloan'}
732 && $item->{'notforloan'} > 0 )
734 $issuingimpossible{NOT_FOR_LOAN} = 1;
736 elsif ( !$item->{'notforloan'} ){
737 # we have to check itemtypes.notforloan also
738 if (C4::Context->preference('item-level_itypes')){
739 # this should probably be a subroutine
740 my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
741 $sth->execute($item->{'itemtype'});
742 my $notforloan=$sth->fetchrow_hashref();
744 if ($notforloan->{'notforloan'} == 1){
745 $issuingimpossible{NOT_FOR_LOAN} = 1;
748 elsif ($biblioitem->{'notforloan'} == 1){
749 $issuingimpossible{NOT_FOR_LOAN} = 1;
752 if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
754 $issuingimpossible{WTHDRAWN} = 1;
756 if ( $item->{'restricted'}
757 && $item->{'restricted'} == 1 )
759 $issuingimpossible{RESTRICTED} = 1;
761 if ( C4::Context->preference("IndependantBranches") ) {
762 my $userenv = C4::Context->userenv;
763 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
764 $issuingimpossible{NOTSAMEBRANCH} = 1
765 if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} );
770 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
772 if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
775 # Already issued to current borrower. Ask whether the loan should
777 my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed(
778 $borrower->{'borrowernumber'},
779 $item->{'itemnumber'}
781 if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed
782 $issuingimpossible{NO_MORE_RENEWALS} = 1;
785 $needsconfirmation{RENEW_ISSUE} = 1;
788 elsif ($issue->{borrowernumber}) {
790 # issued to someone else
791 my $currborinfo = GetMemberDetails( $issue->{borrowernumber} );
793 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
794 $needsconfirmation{ISSUED_TO_ANOTHER} =
795 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
798 # See if the item is on reserve.
799 my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
801 my $resbor = $res->{'borrowernumber'};
802 my ( $resborrower ) = C4::Members::GetMemberDetails( $resbor, 0 );
803 my $branches = GetBranches();
804 my $branchname = $branches->{ $res->{'branchcode'} }->{'branchname'};
805 if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
807 # The item is on reserve and waiting, but has been
808 # reserved by some other patron.
809 $needsconfirmation{RESERVE_WAITING} =
810 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
812 elsif ( $restype eq "Reserved" ) {
813 # The item is on reserve for someone else.
814 $needsconfirmation{RESERVED} =
815 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
818 if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" ) {
819 if ( $borrower->{'categorycode'} eq 'W' ) {
821 return ( \%emptyhash, \%needsconfirmation );
824 return ( \%issuingimpossible, \%needsconfirmation );
829 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
831 &AddIssue($borrower, $barcode, [$datedue], [$cancelreserve], [$issuedate])
835 =item C<$borrower> is a hash with borrower informations (from GetMemberDetails).
837 =item C<$barcode> is the barcode of the item being issued.
839 =item C<$datedue> is a C4::Dates object for the max date of return, i.e. the date due (optional).
842 =item C<$cancelreserve> is 1 to override and cancel any pending reserves for the item (optional).
844 =item C<$issuedate> is the date to issue the item in iso (YYYY-MM-DD) format (optional).
845 Defaults to today. Unlike C<$datedue>, NOT a C4::Dates object, unfortunately.
847 AddIssue does the following things :
848 - step 01: check that there is a borrowernumber & a barcode provided
849 - check for RENEWAL (book issued & being issued to the same patron)
850 - renewal YES = Calculate Charge & renew
852 * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
854 - fill reserve if reserve to this patron
855 - cancel reserve or not, otherwise
856 * TRANSFERT PENDING ?
857 - complete the transfert
865 my ( $borrower, $barcode, $datedue, $cancelreserve, $issuedate, $sipmode) = @_;
866 my $dbh = C4::Context->dbh;
867 my $barcodecheck=CheckValidBarcode($barcode);
869 # $issuedate defaults to today.
870 if ( ! defined $issuedate ) {
871 $issuedate = strftime( "%Y-%m-%d", localtime );
872 # TODO: for hourly circ, this will need to be a C4::Dates object
873 # and all calls to AddIssue including issuedate will need to pass a Dates object.
875 if ($borrower and $barcode and $barcodecheck ne '0'){
876 # find which item we issue
877 my $item = GetItem('', $barcode) or return undef; # if we don't get an Item, abort.
878 my $branch = (C4::Context->preference('CircControl') eq 'PickupLibrary') ? C4::Context->userenv->{'branch'} :
879 (C4::Context->preference('CircControl') eq 'PatronLibrary') ? $borrower->{'branchcode'} :
880 $item->{'homebranch'}; # fallback to item's homebranch
882 # get actual issuing if there is one
883 my $actualissue = GetItemIssue( $item->{itemnumber});
885 # get biblioinformation for this item
886 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
889 # check if we just renew the issue.
891 if ($actualissue->{borrowernumber} eq $borrower->{'borrowernumber'}) {
892 $datedue = AddRenewal(
893 $borrower->{'borrowernumber'},
894 $item->{'itemnumber'},
897 $issuedate, # here interpreted as the renewal date
902 if ( $actualissue->{borrowernumber}) {
903 # This book is currently on loan, but not to the person
904 # who wants to borrow it now. mark it returned before issuing to the new borrower
907 C4::Context->userenv->{'branch'}
911 # See if the item is on reserve.
912 my ( $restype, $res ) =
913 C4::Reserves::CheckReserves( $item->{'itemnumber'} );
915 my $resbor = $res->{'borrowernumber'};
916 if ( $resbor eq $borrower->{'borrowernumber'} ) {
917 # The item is reserved by the current patron
918 ModReserveFill($res);
920 elsif ( $restype eq "Waiting" ) {
922 # The item is on reserve and waiting, but has been
923 # reserved by some other patron.
925 elsif ( $restype eq "Reserved" ) {
927 # The item is reserved by someone else.
928 if ($cancelreserve) { # cancel reserves on this item
929 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
932 if ($cancelreserve) {
933 CancelReserve($res->{'biblionumber'}, 0, $res->{'borrowernumber'});
936 # set waiting reserve to first in reserve queue as book isn't waiting now
938 $res->{'biblionumber'},
939 $res->{'borrowernumber'},
945 # Starting process for transfer job (checking transfert and validate it if we have one)
946 my ($datesent) = GetTransfers($item->{'itemnumber'});
948 # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for visibility of this case (maybe for stats ....)
951 "UPDATE branchtransfers
952 SET datearrived = now(),
954 comments = 'Forced branchtransfer'
955 WHERE itemnumber= ? AND datearrived IS NULL"
957 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
960 # Record in the database the fact that the book was issued.
964 (borrowernumber, itemnumber,issuedate, date_due, branchcode)
968 my $itype = ( C4::Context->preference('item-level_itypes') ) ? $biblio->{'itype'} : $biblio->{'itemtype'};
969 my $loanlength = GetLoanLength( $borrower->{'categorycode'}, $itype, $branch );
970 $datedue = CalcDateDue( C4::Dates->new( $issuedate, 'iso' ), $loanlength, $branch );
972 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
973 if ( C4::Context->preference('ReturnBeforeExpiry') && $datedue->output('iso') gt $borrower->{dateexpiry} ) {
974 $datedue = C4::Dates->new( $borrower->{dateexpiry}, 'iso' );
978 $borrower->{'borrowernumber'}, # borrowernumber
979 $item->{'itemnumber'}, # itemnumber
980 $issuedate, # issuedate
981 $datedue->output('iso'), # date_due
982 C4::Context->userenv->{'branch'} # branchcode
986 ModItem({ issues => $item->{'issues'},
987 holdingbranch => C4::Context->userenv->{'branch'},
989 datelastborrowed => C4::Dates->new()->output('iso'),
990 onloan => $datedue->output('iso'),
991 }, $item->{'biblionumber'}, $item->{'itemnumber'});
992 ModDateLastSeen( $item->{'itemnumber'} );
994 # If it costs to borrow this book, charge it to the patron's account.
995 my ( $charge, $itemtype ) = GetIssuingCharges(
996 $item->{'itemnumber'},
997 $borrower->{'borrowernumber'}
1001 $item->{'itemnumber'},
1002 $borrower->{'borrowernumber'}, $charge
1004 $item->{'charge'} = $charge;
1007 # Record the fact that this book was issued.
1009 C4::Context->userenv->{'branch'},
1011 ($sipmode ? "SIP-$sipmode" : ''), $item->{'itemnumber'},
1012 $item->{'itype'}, $borrower->{'borrowernumber'}
1016 logaction("CIRCULATION", "ISSUE", $borrower->{'borrowernumber'}, $biblio->{'biblionumber'})
1017 if C4::Context->preference("IssueLog");
1019 return ($datedue); # not necessarily the same as when it came in!
1022 =head2 GetLoanLength
1024 Get loan length for an itemtype, a borrower type and a branch
1026 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1031 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1032 my $dbh = C4::Context->dbh;
1035 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1037 # warn "in get loan lenght $borrowertype $itemtype $branchcode ";
1038 # try to find issuelength & return the 1st available.
1039 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1040 $sth->execute( $borrowertype, $itemtype, $branchcode );
1041 my $loanlength = $sth->fetchrow_hashref;
1042 return $loanlength->{issuelength}
1043 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1045 $sth->execute( $borrowertype, "*", $branchcode );
1046 $loanlength = $sth->fetchrow_hashref;
1047 return $loanlength->{issuelength}
1048 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1050 $sth->execute( "*", $itemtype, $branchcode );
1051 $loanlength = $sth->fetchrow_hashref;
1052 return $loanlength->{issuelength}
1053 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1055 $sth->execute( "*", "*", $branchcode );
1056 $loanlength = $sth->fetchrow_hashref;
1057 return $loanlength->{issuelength}
1058 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1060 $sth->execute( $borrowertype, $itemtype, "*" );
1061 $loanlength = $sth->fetchrow_hashref;
1062 return $loanlength->{issuelength}
1063 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1065 $sth->execute( $borrowertype, "*", "*" );
1066 $loanlength = $sth->fetchrow_hashref;
1067 return $loanlength->{issuelength}
1068 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1070 $sth->execute( "*", $itemtype, "*" );
1071 $loanlength = $sth->fetchrow_hashref;
1072 return $loanlength->{issuelength}
1073 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1075 $sth->execute( "*", "*", "*" );
1076 $loanlength = $sth->fetchrow_hashref;
1077 return $loanlength->{issuelength}
1078 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1080 # if no rule is set => 21 days (hardcoded)
1084 =head2 GetIssuingRule
1086 FIXME - This is a copy-paste of GetLoanLength
1087 as a stop-gap. Do not wish to change API for GetLoanLength
1088 this close to release, however, Overdues::GetIssuingRules is broken.
1090 Get the issuing rule for an itemtype, a borrower type and a branch
1091 Returns a hashref from the issuingrules table.
1093 my $irule = &GetIssuingRule($borrowertype,$itemtype,branchcode)
1097 sub GetIssuingRule {
1098 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1099 my $dbh = C4::Context->dbh;
1100 my $sth = $dbh->prepare( "select * from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null" );
1103 $sth->execute( $borrowertype, $itemtype, $branchcode );
1104 $irule = $sth->fetchrow_hashref;
1105 return $irule if defined($irule) ;
1107 $sth->execute( $borrowertype, "*", $branchcode );
1108 $irule = $sth->fetchrow_hashref;
1109 return $irule if defined($irule) ;
1111 $sth->execute( "*", $itemtype, $branchcode );
1112 $irule = $sth->fetchrow_hashref;
1113 return $irule if defined($irule) ;
1115 $sth->execute( "*", "*", $branchcode );
1116 $irule = $sth->fetchrow_hashref;
1117 return $irule if defined($irule) ;
1119 $sth->execute( $borrowertype, $itemtype, "*" );
1120 $irule = $sth->fetchrow_hashref;
1121 return $irule if defined($irule) ;
1123 $sth->execute( $borrowertype, "*", "*" );
1124 $irule = $sth->fetchrow_hashref;
1125 return $irule if defined($irule) ;
1127 $sth->execute( "*", $itemtype, "*" );
1128 $irule = $sth->fetchrow_hashref;
1129 return $irule if defined($irule) ;
1131 $sth->execute( "*", "*", "*" );
1132 $irule = $sth->fetchrow_hashref;
1133 return $irule if defined($irule) ;
1135 # if no rule matches,
1139 =head2 GetBranchBorrowerCircRule
1143 my $branch_cat_rule = GetBranchBorrowerCircRule($branchcode, $categorycode);
1147 Retrieves circulation rule attributes that apply to the given
1148 branch and patron category, regardless of item type.
1149 The return value is a hashref containing the following key:
1151 maxissueqty - maximum number of loans that a
1152 patron of the given category can have at the given
1153 branch. If the value is undef, no limit.
1155 This will first check for a specific branch and
1156 category match from branch_borrower_circ_rules.
1158 If no rule is found, it will then check default_branch_circ_rules
1159 (same branch, default category). If no rule is found,
1160 it will then check default_borrower_circ_rules (default
1161 branch, same category), then failing that, default_circ_rules
1162 (default branch, default category).
1164 If no rule has been found in the database, it will default to
1169 C<$branchcode> and C<$categorycode> should contain the
1170 literal branch code and patron category code, respectively - no
1175 sub GetBranchBorrowerCircRule {
1176 my $branchcode = shift;
1177 my $categorycode = shift;
1179 my $branch_cat_query = "SELECT maxissueqty
1180 FROM branch_borrower_circ_rules
1181 WHERE branchcode = ?
1182 AND categorycode = ?";
1183 my $dbh = C4::Context->dbh();
1184 my $sth = $dbh->prepare($branch_cat_query);
1185 $sth->execute($branchcode, $categorycode);
1187 if ($result = $sth->fetchrow_hashref()) {
1191 # try same branch, default borrower category
1192 my $branch_query = "SELECT maxissueqty
1193 FROM default_branch_circ_rules
1194 WHERE branchcode = ?";
1195 $sth = $dbh->prepare($branch_query);
1196 $sth->execute($branchcode);
1197 if ($result = $sth->fetchrow_hashref()) {
1201 # try default branch, same borrower category
1202 my $category_query = "SELECT maxissueqty
1203 FROM default_borrower_circ_rules
1204 WHERE categorycode = ?";
1205 $sth = $dbh->prepare($category_query);
1206 $sth->execute($categorycode);
1207 if ($result = $sth->fetchrow_hashref()) {
1211 # try default branch, default borrower category
1212 my $default_query = "SELECT maxissueqty
1213 FROM default_circ_rules";
1214 $sth = $dbh->prepare($default_query);
1216 if ($result = $sth->fetchrow_hashref()) {
1220 # built-in default circulation rule
1222 maxissueqty => undef,
1228 ($doreturn, $messages, $iteminformation, $borrower) =
1229 &AddReturn($barcode, $branch, $exemptfine, $dropbox);
1235 =item C<$barcode> is the bar code of the book being returned.
1237 =item C<$branch> is the code of the branch where the book is being returned.
1239 =item C<$exemptfine> indicates that overdue charges for the item will be
1242 =item C<$dropbox> indicates that the check-in date is assumed to be
1243 yesterday, or the last non-holiday as defined in C4::Calendar . If
1244 overdue charges are applied and C<$dropbox> is true, the last charge
1245 will be removed. This assumes that the fines accrual script has run
1250 C<&AddReturn> returns a list of four items:
1252 C<$doreturn> is true iff the return succeeded.
1254 C<$messages> is a reference-to-hash giving the reason for failure:
1260 No item with this barcode exists. The value is C<$barcode>.
1264 The book is not currently on loan. The value is C<$barcode>.
1266 =item C<IsPermanent>
1268 The book's home branch is a permanent collection. If you have borrowed
1269 this book, you are not allowed to return it. The value is the code for
1270 the book's home branch.
1274 This book has been withdrawn/cancelled. The value should be ignored.
1278 The item was reserved. The value is a reference-to-hash whose keys are
1279 fields from the reserves table of the Koha database, and
1280 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1281 either C<Waiting>, C<Reserved>, or 0.
1285 C<$borrower> is a reference-to-hash, giving information about the
1286 patron who last borrowed the book.
1291 my ( $barcode, $branch, $exemptfine, $dropbox ) = @_;
1292 my $dbh = C4::Context->dbh;
1296 my $validTransfert = 0;
1297 my $reserveDone = 0;
1299 # get information on item
1300 my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1301 my $biblio = GetBiblioItemData($iteminformation->{'biblioitemnumber'});
1302 # use Data::Dumper;warn Data::Dumper::Dumper($iteminformation);
1303 unless ($iteminformation->{'itemnumber'} ) {
1304 $messages->{'BadBarcode'} = $barcode;
1308 if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1309 $messages->{'NotIssued'} = $barcode;
1310 # even though item is not on loan, it may still
1311 # be transferred; therefore, get current branch information
1312 my $curr_iteminfo = GetItem($iteminformation->{'itemnumber'});
1313 $iteminformation->{'homebranch'} = $curr_iteminfo->{'homebranch'};
1314 $iteminformation->{'holdingbranch'} = $curr_iteminfo->{'holdingbranch'};
1318 # check if the book is in a permanent collection....
1319 my $hbr = $iteminformation->{C4::Context->preference("HomeOrHoldingBranch")};
1320 my $branches = GetBranches();
1321 # FIXME -- This 'PE' attribute is largely undocumented. afaict, there's no user interface that reflects this functionality.
1322 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1323 $messages->{'IsPermanent'} = $hbr;
1326 # if independent branches are on and returning to different branch, refuse the return
1327 if ($hbr ne C4::Context->userenv->{'branch'} && C4::Context->preference("IndependantBranches")){
1328 $messages->{'Wrongbranch'} = 1;
1332 # check that the book has been cancelled
1333 if ( $iteminformation->{'wthdrawn'} ) {
1334 $messages->{'wthdrawn'} = 1;
1338 # new op dev : if the book returned in an other branch update the holding branch
1340 # update issues, thereby returning book (should push this out into another subroutine
1341 $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1343 # case of a return of document (deal with issues and holdingbranch)
1346 my $circControlBranch;
1348 # don't allow dropbox mode to create an invalid entry in issues (issuedate > returndate) FIXME: actually checks eq, not gt
1349 undef($dropbox) if ( $iteminformation->{'issuedate'} eq C4::Dates->today('iso') );
1350 if (C4::Context->preference('CircControl') eq 'ItemHomeBranch' ) {
1351 $circControlBranch = $iteminformation->{homebranch};
1352 } elsif ( C4::Context->preference('CircControl') eq 'PatronLibrary') {
1353 $circControlBranch = $borrower->{branchcode};
1354 } else { # CircControl must be PickupLibrary.
1355 $circControlBranch = $iteminformation->{holdingbranch};
1356 # FIXME - is this right ? are we sure that the holdingbranch is still the pickup branch?
1359 MarkIssueReturned($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'},$circControlBranch);
1360 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1363 # continue to deal with returns cases, but not only if we have an issue
1365 # the holdingbranch is updated if the document is returned in an other location .
1366 if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} ) {
1367 UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});
1368 # reload iteminformation holdingbranch with the userenv value
1369 $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1371 ModDateLastSeen( $iteminformation->{'itemnumber'} );
1372 ModItem({ onloan => undef }, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'});
1374 if ($iteminformation->{borrowernumber}){
1375 ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1377 # fix up the accounts.....
1378 if ( $iteminformation->{'itemlost'} ) {
1379 $messages->{'WasLost'} = 1;
1382 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1383 # check if we have a transfer for this document
1384 my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1386 # if we have a transfer to do, we update the line of transfers with the datearrived
1388 if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1391 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1393 $sth->execute( $iteminformation->{'itemnumber'} );
1395 # 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'
1396 C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1399 $messages->{'WrongTransfer'} = $tobranch;
1400 $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1402 $validTransfert = 1;
1405 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1406 # fix up the accounts.....
1407 if ($iteminformation->{'itemlost'}) {
1408 FixAccountForLostAndReturned($iteminformation, $borrower);
1409 $messages->{'WasLost'} = 1;
1411 # fix up the overdues in accounts...
1412 FixOverduesOnReturn( $borrower->{'borrowernumber'},
1413 $iteminformation->{'itemnumber'}, $exemptfine, $dropbox );
1415 # find reserves.....
1416 # if we don't have a reserve with the status W, we launch the Checkreserves routine
1417 my ( $resfound, $resrec ) =
1418 C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1420 $resrec->{'ResFound'} = $resfound;
1421 $messages->{'ResFound'} = $resrec;
1426 # Record the fact that this book was returned.
1428 $branch, 'return', '0', '',
1429 $iteminformation->{'itemnumber'},
1430 $biblio->{'itemtype'},
1431 $borrower->{'borrowernumber'}
1434 logaction("CIRCULATION", "RETURN", $iteminformation->{borrowernumber}, $iteminformation->{'biblionumber'})
1435 if C4::Context->preference("ReturnLog");
1437 #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1438 #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1440 if ( ( $branch ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1441 if (C4::Context->preference("AutomaticItemReturn") == 1) {
1442 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1443 $messages->{'WasTransfered'} = 1;
1444 } elsif ( C4::Context->preference("UseBranchTransferLimits") == 1
1445 && ! IsTransferAllowed( $branch, $iteminformation->{'homebranch'}, $iteminformation->{'itemtype'} )
1447 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1448 $messages->{'WasTransfered'} = 1;
1451 $messages->{'NeedsTransfer'} = 1;
1455 return ( $doreturn, $messages, $iteminformation, $borrower );
1458 =head2 MarkIssueReturned
1462 MarkIssueReturned($borrowernumber, $itemnumber, $dropbox_branch, $returndate);
1466 Unconditionally marks an issue as being returned by
1467 moving the C<issues> row to C<old_issues> and
1468 setting C<returndate> to the current date, or
1469 the last non-holiday date of the branccode specified in
1470 C<dropbox_branch> . Assumes you've already checked that
1471 it's safe to do this, i.e. last non-holiday > issuedate.
1473 if C<$returndate> is specified (in iso format), it is used as the date
1474 of the return. It is ignored when a dropbox_branch is passed in.
1476 Ideally, this function would be internal to C<C4::Circulation>,
1477 not exported, but it is currently needed by one
1478 routine in C<C4::Accounts>.
1482 sub MarkIssueReturned {
1483 my ( $borrowernumber, $itemnumber, $dropbox_branch, $returndate ) = @_;
1484 my $dbh = C4::Context->dbh;
1485 my $query = "UPDATE issues SET returndate=";
1487 if ($dropbox_branch) {
1488 my $calendar = C4::Calendar->new( branchcode => $dropbox_branch );
1489 my $dropboxdate = $calendar->addDate( C4::Dates->new(), -1 );
1491 push @bind, $dropboxdate->output('iso');
1492 } elsif ($returndate) {
1494 push @bind, $returndate;
1496 $query .= " now() ";
1498 $query .= " WHERE borrowernumber = ? AND itemnumber = ?";
1499 push @bind, $borrowernumber, $itemnumber;
1501 my $sth_upd = $dbh->prepare($query);
1502 $sth_upd->execute(@bind);
1503 my $sth_copy = $dbh->prepare("INSERT INTO old_issues SELECT * FROM issues
1504 WHERE borrowernumber = ?
1505 AND itemnumber = ?");
1506 $sth_copy->execute($borrowernumber, $itemnumber);
1507 my $sth_del = $dbh->prepare("DELETE FROM issues
1508 WHERE borrowernumber = ?
1509 AND itemnumber = ?");
1510 $sth_del->execute($borrowernumber, $itemnumber);
1513 =head2 FixOverduesOnReturn
1515 &FixOverduesOnReturn($brn,$itm, $exemptfine, $dropboxmode);
1517 C<$brn> borrowernumber
1521 C<$exemptfine> BOOL -- remove overdue charge associated with this issue.
1522 C<$dropboxmode> BOOL -- remove lastincrement on overdue charge associated with this issue.
1524 internal function, called only by AddReturn
1528 sub FixOverduesOnReturn {
1529 my ( $borrowernumber, $item, $exemptfine, $dropbox ) = @_;
1530 my $dbh = C4::Context->dbh;
1532 # check for overdue fine
1535 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1537 $sth->execute( $borrowernumber, $item );
1539 # alter fine to show that the book has been returned
1541 if ($data = $sth->fetchrow_hashref) {
1543 my @bind = ($borrowernumber,$item ,$data->{'accountno'});
1545 $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
1546 if (C4::Context->preference("FinesLog")) {
1547 &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
1549 } elsif ($dropbox && $data->{lastincrement}) {
1550 my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
1551 my $amt = $data->{amount} - $data->{lastincrement} ;
1552 if (C4::Context->preference("FinesLog")) {
1553 &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
1555 $uquery = "update accountlines set accounttype='F' ";
1556 if($outstanding >= 0 && $amt >=0) {
1557 $uquery .= ", amount = ? , amountoutstanding=? ";
1558 unshift @bind, ($amt, $outstanding) ;
1561 $uquery = "update accountlines set accounttype='F' ";
1563 $uquery .= " where (borrowernumber = ?) and (itemnumber = ?) and (accountno = ?)";
1564 my $usth = $dbh->prepare($uquery);
1565 $usth->execute(@bind);
1573 =head2 FixAccountForLostAndReturned
1575 &FixAccountForLostAndReturned($iteminfo,$borrower);
1577 Calculates the charge for a book lost and returned (Not exported & used only once)
1579 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1581 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1583 Internal function, called by AddReturn
1587 sub FixAccountForLostAndReturned {
1588 my ($iteminfo, $borrower) = @_;
1589 my $dbh = C4::Context->dbh;
1590 my $itm = $iteminfo->{'itemnumber'};
1591 # check for charge made for lost book
1592 my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1593 $sth->execute($itm);
1594 if (my $data = $sth->fetchrow_hashref) {
1595 # writeoff this amount
1597 my $amount = $data->{'amount'};
1598 my $acctno = $data->{'accountno'};
1600 if ($data->{'amountoutstanding'} == $amount) {
1601 $offset = $data->{'amount'};
1604 $offset = $amount - $data->{'amountoutstanding'};
1605 $amountleft = $data->{'amountoutstanding'} - $amount;
1607 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1608 WHERE (borrowernumber = ?)
1609 AND (itemnumber = ?) AND (accountno = ?) ");
1610 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1612 #check if any credit is left if so writeoff other accounts
1613 my $nextaccntno = getnextacctno($data->{'borrowernumber'});
1614 if ($amountleft < 0){
1617 if ($amountleft > 0){
1618 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1619 AND (amountoutstanding >0) ORDER BY date");
1620 $msth->execute($data->{'borrowernumber'});
1621 # offset transactions
1624 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1625 if ($accdata->{'amountoutstanding'} < $amountleft) {
1627 $amountleft -= $accdata->{'amountoutstanding'};
1629 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1632 my $thisacct = $accdata->{'accountno'};
1633 my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1634 WHERE (borrowernumber = ?)
1635 AND (accountno=?)");
1636 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1638 $usth = $dbh->prepare("INSERT INTO accountoffsets
1639 (borrowernumber, accountno, offsetaccount, offsetamount)
1642 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
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);
1656 $usth = $dbh->prepare("INSERT INTO accountoffsets
1657 (borrowernumber, accountno, offsetaccount, offsetamount)
1659 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1661 ModItem({ paidfor => '' }, undef, $itm);
1669 $issues = &GetItemIssue($itemnumber);
1671 Returns patrons currently having a book. nothing if item is not issued atm
1673 C<$itemnumber> is the itemnumber
1675 Returns an array of hashes
1677 FIXME: Though the above says that this function returns nothing if the
1678 item is not issued, this actually returns a hasref that looks like
1689 my ( $itemnumber) = @_;
1690 return unless $itemnumber;
1691 my $dbh = C4::Context->dbh;
1695 my $today = POSIX::strftime("%Y%m%d", localtime);
1697 my $sth = $dbh->prepare(
1698 "SELECT * FROM issues
1699 LEFT JOIN items ON issues.itemnumber=items.itemnumber
1701 issues.itemnumber=?");
1702 $sth->execute($itemnumber);
1703 my $data = $sth->fetchrow_hashref;
1704 my $datedue = $data->{'date_due'};
1706 if ( $datedue < $today ) {
1707 $data->{'overdue'} = 1;
1709 $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1716 $issue = GetOpenIssue( $itemnumber );
1718 Returns the row from the issues table if the item is currently issued, undef if the item is not currently issued
1720 C<$itemnumber> is the item's itemnumber
1727 my ( $itemnumber ) = @_;
1729 my $dbh = C4::Context->dbh;
1730 my $sth = $dbh->prepare( "SELECT * FROM issues WHERE itemnumber = ? AND returndate IS NULL" );
1731 $sth->execute( $itemnumber );
1732 my $issue = $sth->fetchrow_hashref();
1736 =head2 GetItemIssues
1738 $issues = &GetItemIssues($itemnumber, $history);
1740 Returns patrons that have issued a book
1742 C<$itemnumber> is the itemnumber
1743 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1745 Returns an array of hashes
1750 my ( $itemnumber,$history ) = @_;
1751 my $dbh = C4::Context->dbh;
1755 my $today = POSIX::strftime("%Y%m%d", localtime);
1757 my $sql = "SELECT * FROM issues
1758 JOIN borrowers USING (borrowernumber)
1759 JOIN items USING (itemnumber)
1760 WHERE issues.itemnumber = ? ";
1763 SELECT * FROM old_issues
1764 LEFT JOIN borrowers USING (borrowernumber)
1765 JOIN items USING (itemnumber)
1766 WHERE old_issues.itemnumber = ? ";
1768 $sql .= "ORDER BY date_due DESC";
1769 my $sth = $dbh->prepare($sql);
1771 $sth->execute($itemnumber, $itemnumber);
1773 $sth->execute($itemnumber);
1775 while ( my $data = $sth->fetchrow_hashref ) {
1776 my $datedue = $data->{'date_due'};
1778 if ( $datedue < $today ) {
1779 $data->{'overdue'} = 1;
1781 my $itemnumber = $data->{'itemnumber'};
1782 push @GetItemIssues, $data;
1785 return ( \@GetItemIssues );
1788 =head2 GetBiblioIssues
1790 $issues = GetBiblioIssues($biblionumber);
1792 this function get all issues from a biblionumber.
1795 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1796 tables issues and the firstname,surname & cardnumber from borrowers.
1800 sub GetBiblioIssues {
1801 my $biblionumber = shift;
1802 return undef unless $biblionumber;
1803 my $dbh = C4::Context->dbh;
1805 SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1807 LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1808 LEFT JOIN items ON issues.itemnumber = items.itemnumber
1809 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1810 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1811 WHERE biblio.biblionumber = ?
1813 SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1815 LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
1816 LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
1817 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1818 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1819 WHERE biblio.biblionumber = ?
1822 my $sth = $dbh->prepare($query);
1823 $sth->execute($biblionumber, $biblionumber);
1826 while ( my $data = $sth->fetchrow_hashref ) {
1827 push @issues, $data;
1832 =head2 GetUpcomingDueIssues
1836 my $upcoming_dues = GetUpcomingDueIssues( { days_in_advance => 4 } );
1842 sub GetUpcomingDueIssues {
1845 $params->{'days_in_advance'} = 7 unless exists $params->{'days_in_advance'};
1846 my $dbh = C4::Context->dbh;
1848 my $statement = <<END_SQL;
1849 SELECT issues.*, items.itype as itemtype, items.homebranch, TO_DAYS( date_due )-TO_DAYS( NOW() ) as days_until_due
1851 LEFT JOIN items USING (itemnumber)
1852 WhERE returndate is NULL
1853 AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ?
1856 my @bind_parameters = ( $params->{'days_in_advance'} );
1858 my $sth = $dbh->prepare( $statement );
1859 $sth->execute( @bind_parameters );
1860 my $upcoming_dues = $sth->fetchall_arrayref({});
1863 return $upcoming_dues;
1866 =head2 CanBookBeRenewed
1868 ($ok,$error) = &CanBookBeRenewed($borrowernumber, $itemnumber[, $override_limit]);
1870 Find out whether a borrowed item may be renewed.
1872 C<$dbh> is a DBI handle to the Koha database.
1874 C<$borrowernumber> is the borrower number of the patron who currently
1875 has the item on loan.
1877 C<$itemnumber> is the number of the item to renew.
1879 C<$override_limit>, if supplied with a true value, causes
1880 the limit on the number of times that the loan can be renewed
1881 (as controlled by the item type) to be ignored.
1883 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1884 item must currently be on loan to the specified borrower; renewals
1885 must be allowed for the item's type; and the borrower must not have
1886 already renewed the loan. $error will contain the reason the renewal can not proceed
1890 sub CanBookBeRenewed {
1892 # check renewal status
1893 my ( $borrowernumber, $itemnumber, $override_limit ) = @_;
1894 my $dbh = C4::Context->dbh;
1899 # Look in the issues table for this item, lent to this borrower,
1900 # and not yet returned.
1902 # FIXME - I think this function could be redone to use only one SQL call.
1903 my $sth1 = $dbh->prepare(
1904 "SELECT * FROM issues
1905 WHERE borrowernumber = ?
1908 $sth1->execute( $borrowernumber, $itemnumber );
1909 if ( my $data1 = $sth1->fetchrow_hashref ) {
1911 # Found a matching item
1913 # See if this item may be renewed. This query is convoluted
1914 # because it's a bit messy: given the item number, we need to find
1915 # the biblioitem, which gives us the itemtype, which tells us
1916 # whether it may be renewed.
1917 my $query = "SELECT renewalsallowed FROM items ";
1918 $query .= (C4::Context->preference('item-level_itypes'))
1919 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1920 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1921 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1922 $query .= "WHERE items.itemnumber = ?";
1923 my $sth2 = $dbh->prepare($query);
1924 $sth2->execute($itemnumber);
1925 if ( my $data2 = $sth2->fetchrow_hashref ) {
1926 $renews = $data2->{'renewalsallowed'};
1928 if ( ( $renews && $renews > $data1->{'renewals'} ) || $override_limit ) {
1935 my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1943 return ($renewokay,$error);
1948 &AddRenewal($borrowernumber, $itemnumber, $branch, [$datedue], [$lastreneweddate]);
1952 C<$borrowernumber> is the borrower number of the patron who currently
1955 C<$itemnumber> is the number of the item to renew.
1957 C<$branch> is the library branch. Defaults to the homebranch of the ITEM.
1959 C<$datedue> can be a C4::Dates object used to set the due date.
1961 C<$lastreneweddate> is an optional ISO-formatted date used to set issues.lastreneweddate. If
1962 this parameter is not supplied, lastreneweddate is set to the current date.
1964 If C<$datedue> is the empty string, C<&AddRenewal> will calculate the due date automatically
1965 from the book's item type.
1970 my $borrowernumber = shift or return undef;
1971 my $itemnumber = shift or return undef;
1972 my $item = GetItem($itemnumber) or return undef;
1973 my $biblio = GetBiblioFromItemNumber($itemnumber) or return undef;
1974 my $branch = (@_) ? shift : $item->{homebranch}; # opac-renew doesn't send branch
1975 my $datedue = shift;
1976 my $lastreneweddate = shift;
1978 # If the due date wasn't specified, calculate it by adding the
1979 # book's loan length to today's date.
1980 unless ($datedue && $datedue->output('iso')) {
1982 my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 ) or return undef;
1983 my $loanlength = GetLoanLength(
1984 $borrower->{'categorycode'},
1985 (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1986 $item->{homebranch} # item's homebranch determines loanlength OR do we want the branch specified by the AddRenewal argument?
1988 #FIXME -- use circControl?
1989 $datedue = CalcDateDue(C4::Dates->new(),$loanlength,$branch); # this branch is the transactional branch.
1990 # The question of whether to use item's homebranch calendar is open.
1993 # $lastreneweddate defaults to today.
1994 unless (defined $lastreneweddate) {
1995 $lastreneweddate = strftime( "%Y-%m-%d", localtime );
1998 my $dbh = C4::Context->dbh;
1999 # Find the issues record for this book
2001 $dbh->prepare("SELECT * FROM issues
2002 WHERE borrowernumber=?
2005 $sth->execute( $borrowernumber, $itemnumber );
2006 my $issuedata = $sth->fetchrow_hashref;
2009 # Update the issues record to have the new due date, and a new count
2010 # of how many times it has been renewed.
2011 my $renews = $issuedata->{'renewals'} + 1;
2012 $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?, lastreneweddate = ?
2013 WHERE borrowernumber=?
2016 $sth->execute( $datedue->output('iso'), $renews, $lastreneweddate, $borrowernumber, $itemnumber );
2019 # Update the renewal count on the item, and tell zebra to reindex
2020 $renews = $biblio->{'renewals'} + 1;
2021 ModItem({ renewals => $renews }, $biblio->{'biblionumber'}, $itemnumber);
2023 # Charge a new rental fee, if applicable?
2024 my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2025 if ( $charge > 0 ) {
2026 my $accountno = getnextacctno( $borrowernumber );
2027 my $item = GetBiblioFromItemNumber($itemnumber);
2028 $sth = $dbh->prepare(
2029 "INSERT INTO accountlines
2031 borrowernumber, accountno, amount,
2033 accounttype, amountoutstanding, itemnumber
2035 VALUES (now(),?,?,?,?,?,?,?)"
2037 $sth->execute( $borrowernumber, $accountno, $charge,
2038 "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
2039 'Rent', $charge, $itemnumber );
2043 UpdateStats( $branch, 'renew', $charge, '', $itemnumber, $item->{itype}, $borrowernumber);
2048 # check renewal status
2049 my ($bornum,$itemno)=@_;
2050 my $dbh = C4::Context->dbh;
2052 my $renewsallowed = 0;
2054 # Look in the issues table for this item, lent to this borrower,
2055 # and not yet returned.
2057 # FIXME - I think this function could be redone to use only one SQL call.
2058 my $sth = $dbh->prepare("select * from issues
2059 where (borrowernumber = ?)
2060 and (itemnumber = ?)");
2061 $sth->execute($bornum,$itemno);
2062 my $data = $sth->fetchrow_hashref;
2063 $renewcount = $data->{'renewals'} if $data->{'renewals'};
2065 my $query = "SELECT renewalsallowed FROM items ";
2066 $query .= (C4::Context->preference('item-level_itypes'))
2067 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2068 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
2069 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2070 $query .= "WHERE items.itemnumber = ?";
2071 my $sth2 = $dbh->prepare($query);
2072 $sth2->execute($itemno);
2073 my $data2 = $sth2->fetchrow_hashref();
2074 $renewsallowed = $data2->{'renewalsallowed'};
2075 $renewsleft = $renewsallowed - $renewcount;
2076 return ($renewcount,$renewsallowed,$renewsleft);
2079 =head2 GetIssuingCharges
2081 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
2083 Calculate how much it would cost for a given patron to borrow a given
2084 item, including any applicable discounts.
2086 C<$itemnumber> is the item number of item the patron wishes to borrow.
2088 C<$borrowernumber> is the patron's borrower number.
2090 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
2091 and C<$item_type> is the code for the item's item type (e.g., C<VID>
2096 sub GetIssuingCharges {
2098 # calculate charges due
2099 my ( $itemnumber, $borrowernumber ) = @_;
2101 my $dbh = C4::Context->dbh;
2104 # Get the book's item type and rental charge (via its biblioitem).
2105 my $qcharge = "SELECT itemtypes.itemtype,rentalcharge FROM items
2106 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
2107 $qcharge .= (C4::Context->preference('item-level_itypes'))
2108 ? " LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2109 : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2111 $qcharge .= "WHERE items.itemnumber =?";
2113 my $sth1 = $dbh->prepare($qcharge);
2114 $sth1->execute($itemnumber);
2115 if ( my $data1 = $sth1->fetchrow_hashref ) {
2116 $item_type = $data1->{'itemtype'};
2117 $charge = $data1->{'rentalcharge'};
2118 my $q2 = "SELECT rentaldiscount FROM borrowers
2119 LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
2120 WHERE borrowers.borrowernumber = ?
2121 AND issuingrules.itemtype = ?";
2122 my $sth2 = $dbh->prepare($q2);
2123 $sth2->execute( $borrowernumber, $item_type );
2124 if ( my $data2 = $sth2->fetchrow_hashref ) {
2125 my $discount = $data2->{'rentaldiscount'};
2126 if ( $discount eq 'NULL' ) {
2129 $charge = ( $charge * ( 100 - $discount ) ) / 100;
2135 return ( $charge, $item_type );
2138 =head2 AddIssuingCharge
2140 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
2144 sub AddIssuingCharge {
2145 my ( $itemnumber, $borrowernumber, $charge ) = @_;
2146 my $dbh = C4::Context->dbh;
2147 my $nextaccntno = getnextacctno( $borrowernumber );
2149 INSERT INTO accountlines
2150 (borrowernumber, itemnumber, accountno,
2151 date, amount, description, accounttype,
2153 VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
2155 my $sth = $dbh->prepare($query);
2156 $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
2162 GetTransfers($itemnumber);
2167 my ($itemnumber) = @_;
2169 my $dbh = C4::Context->dbh;
2175 FROM branchtransfers
2176 WHERE itemnumber = ?
2177 AND datearrived IS NULL
2179 my $sth = $dbh->prepare($query);
2180 $sth->execute($itemnumber);
2181 my @row = $sth->fetchrow_array();
2187 =head2 GetTransfersFromTo
2189 @results = GetTransfersFromTo($frombranch,$tobranch);
2191 Returns the list of pending transfers between $from and $to branch
2195 sub GetTransfersFromTo {
2196 my ( $frombranch, $tobranch ) = @_;
2197 return unless ( $frombranch && $tobranch );
2198 my $dbh = C4::Context->dbh;
2200 SELECT itemnumber,datesent,frombranch
2201 FROM branchtransfers
2204 AND datearrived IS NULL
2206 my $sth = $dbh->prepare($query);
2207 $sth->execute( $frombranch, $tobranch );
2210 while ( my $data = $sth->fetchrow_hashref ) {
2211 push @gettransfers, $data;
2214 return (@gettransfers);
2217 =head2 DeleteTransfer
2219 &DeleteTransfer($itemnumber);
2223 sub DeleteTransfer {
2224 my ($itemnumber) = @_;
2225 my $dbh = C4::Context->dbh;
2226 my $sth = $dbh->prepare(
2227 "DELETE FROM branchtransfers
2229 AND datearrived IS NULL "
2231 $sth->execute($itemnumber);
2235 =head2 AnonymiseIssueHistory
2237 $rows = AnonymiseIssueHistory($borrowernumber,$date)
2239 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
2240 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
2242 return the number of affected rows.
2246 sub AnonymiseIssueHistory {
2248 my $borrowernumber = shift;
2249 my $dbh = C4::Context->dbh;
2252 SET borrowernumber = NULL
2253 WHERE returndate < '".$date."'
2254 AND borrowernumber IS NOT NULL
2256 $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
2257 my $rows_affected = $dbh->do($query);
2258 return $rows_affected;
2261 =head2 updateWrongTransfer
2263 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
2265 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
2269 sub updateWrongTransfer {
2270 my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
2271 my $dbh = C4::Context->dbh;
2272 # first step validate the actual line of transfert .
2275 "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
2277 $sth->execute($FromLibrary,$itemNumber);
2280 # second step create a new line of branchtransfer to the right location .
2281 ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
2283 #third step changing holdingbranch of item
2284 UpdateHoldingbranch($FromLibrary,$itemNumber);
2287 =head2 UpdateHoldingbranch
2289 $items = UpdateHoldingbranch($branch,$itmenumber);
2290 Simple methode for updating hodlingbranch in items BDD line
2294 sub UpdateHoldingbranch {
2295 my ( $branch,$itemnumber ) = @_;
2296 ModItem({ holdingbranch => $branch }, undef, $itemnumber);
2301 $newdatedue = CalcDateDue($startdate,$loanlength,$branchcode);
2302 this function calculates the due date given the loan length ,
2303 checking against the holidays calendar as per the 'useDaysMode' syspref.
2304 C<$startdate> = C4::Dates object representing start date of loan period (assumed to be today)
2305 C<$branch> = location whose calendar to use
2306 C<$loanlength> = loan length prior to adjustment
2310 my ($startdate,$loanlength,$branch) = @_;
2311 if(C4::Context->preference('useDaysMode') eq 'Days') { # ignoring calendar
2312 my $datedue = time + ($loanlength) * 86400;
2313 #FIXME - assumes now even though we take a startdate
2314 my @datearr = localtime($datedue);
2315 return C4::Dates->new( sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
2317 my $calendar = C4::Calendar->new( branchcode => $branch );
2318 my $datedue = $calendar->addDate($startdate, $loanlength);
2323 =head2 CheckValidDatedue
2324 This function does not account for holiday exceptions nor does it handle the 'useDaysMode' syspref .
2325 To be replaced by CalcDateDue() once C4::Calendar use is tested.
2327 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
2328 this function validates the loan length against the holidays calendar, and adjusts the due date as per the 'useDaysMode' syspref.
2329 C<$date_due> = returndate calculate with no day check
2330 C<$itemnumber> = itemnumber
2331 C<$branchcode> = location of issue (affected by 'CircControl' syspref)
2332 C<$loanlength> = loan length prior to adjustment
2335 sub CheckValidDatedue {
2336 my ($date_due,$itemnumber,$branchcode)=@_;
2337 my @datedue=split('-',$date_due->output('iso'));
2338 my $years=$datedue[0];
2339 my $month=$datedue[1];
2340 my $day=$datedue[2];
2341 # die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
2343 for (my $i=0;$i<2;$i++){
2344 $dow=Day_of_Week($years,$month,$day);
2345 ($dow=0) if ($dow>6);
2346 my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
2347 my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2348 my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2349 if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
2351 (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
2354 my $newdatedue=C4::Dates->new(sprintf("%04d-%02d-%02d",$years,$month,$day),'iso');
2359 =head2 CheckRepeatableHolidays
2361 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
2362 this function checks if the date due is a repeatable holiday
2363 C<$date_due> = returndate calculate with no day check
2364 C<$itemnumber> = itemnumber
2365 C<$branchcode> = localisation of issue
2369 sub CheckRepeatableHolidays{
2370 my($itemnumber,$week_day,$branchcode)=@_;
2371 my $dbh = C4::Context->dbh;
2372 my $query = qq|SELECT count(*)
2373 FROM repeatable_holidays
2376 my $sth = $dbh->prepare($query);
2377 $sth->execute($branchcode,$week_day);
2378 my $result=$sth->fetchrow;
2384 =head2 CheckSpecialHolidays
2386 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2387 this function check if the date is a special holiday
2388 C<$years> = the years of datedue
2389 C<$month> = the month of datedue
2390 C<$day> = the day of datedue
2391 C<$itemnumber> = itemnumber
2392 C<$branchcode> = localisation of issue
2396 sub CheckSpecialHolidays{
2397 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
2398 my $dbh = C4::Context->dbh;
2399 my $query=qq|SELECT count(*)
2400 FROM `special_holidays`
2406 my $sth = $dbh->prepare($query);
2407 $sth->execute($years,$month,$day,$branchcode);
2408 my $countspecial=$sth->fetchrow ;
2410 return $countspecial;
2413 =head2 CheckRepeatableSpecialHolidays
2415 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2416 this function check if the date is a repeatble special holidays
2417 C<$month> = the month of datedue
2418 C<$day> = the day of datedue
2419 C<$itemnumber> = itemnumber
2420 C<$branchcode> = localisation of issue
2424 sub CheckRepeatableSpecialHolidays{
2425 my ($month,$day,$itemnumber,$branchcode) = @_;
2426 my $dbh = C4::Context->dbh;
2427 my $query=qq|SELECT count(*)
2428 FROM `repeatable_holidays`
2433 my $sth = $dbh->prepare($query);
2434 $sth->execute($month,$day,$branchcode);
2435 my $countspecial=$sth->fetchrow ;
2437 return $countspecial;
2442 sub CheckValidBarcode{
2444 my $dbh = C4::Context->dbh;
2445 my $query=qq|SELECT count(*)
2449 my $sth = $dbh->prepare($query);
2450 $sth->execute($barcode);
2451 my $exist=$sth->fetchrow ;
2456 =head2 IsBranchTransferAllowed
2458 $allowed = IsBranchTransferAllowed( $toBranch, $fromBranch, $itemtype );
2462 sub IsBranchTransferAllowed {
2463 my ( $toBranch, $fromBranch, $itemtype ) = @_;
2465 if ( $toBranch eq $fromBranch ) { return 1; } ## Short circuit for speed.
2467 my $dbh = C4::Context->dbh;
2469 my $sth = $dbh->prepare('SELECT * FROM branch_transfer_limits WHERE toBranch = ? AND fromBranch = ? AND itemtype = ?');
2470 $sth->execute( $toBranch, $fromBranch, $itemtype );
2471 my $limit = $sth->fetchrow_hashref();
2473 ## If a row is found, then that combination is not allowed, if no matching row is found, then the combination *is allowed*
2474 if ( $limit->{'limitId'} ) {
2481 =head2 CreateBranchTransferLimit
2483 CreateBranchTransferLimit( $toBranch, $fromBranch, $itemtype );
2487 sub CreateBranchTransferLimit {
2488 my ( $toBranch, $fromBranch, $itemtype ) = @_;
2490 my $dbh = C4::Context->dbh;
2492 my $sth = $dbh->prepare("INSERT INTO branch_transfer_limits ( itemtype, toBranch, fromBranch ) VALUES ( ?, ?, ? )");
2493 $sth->execute( $itemtype, $toBranch, $fromBranch );
2496 =head2 DeleteBranchTransferLimits
2498 DeleteBranchTransferLimits();
2502 sub DeleteBranchTransferLimits {
2503 my $dbh = C4::Context->dbh;
2504 my $sth = $dbh->prepare("TRUNCATE TABLE branch_transfer_limits");
2515 Koha Developement team <info@koha.org>