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
77 &AnonymiseIssueHistory
80 # subs to deal with returns
86 # subs to deal with transfers
98 C4::Circulation - Koha circulation module
106 The functions in this module deal with circulation, issues, and
107 returns, as well as general information about the library.
108 Also deals with stocktaking.
114 =head3 $str = &barcodedecode($barcode, [$filter]);
118 =item Generic filter function for barcode string.
119 Called on every circ if the System Pref itemBarcodeInputFilter is set.
120 Will do some manipulation of the barcode for systems that deliver a barcode
121 to circulation.pl that differs from the barcode stored for the item.
122 For proper functioning of this filter, calling the function on the
123 correct barcode string (items.barcode) should return an unaltered barcode.
125 The optional $filter argument is to allow for testing or explicit
126 behavior that ignores the System Pref. Valid values are the same as the
133 # FIXME -- the &decode fcn below should be wrapped into this one.
134 # FIXME -- these plugins should be moved out of Circulation.pm
137 my ($barcode, $filter) = @_;
138 $filter = C4::Context->preference('itemBarcodeInputFilter') unless $filter;
139 $filter or return $barcode; # ensure filter is defined, else return untouched barcode
140 if ($filter eq 'whitespace') {
142 } elsif ($filter eq 'cuecat') {
144 my @fields = split( /\./, $barcode );
145 my @results = map( decode($_), @fields[ 1 .. $#fields ] );
146 ($#results == 2) and return $results[2];
147 } elsif ($filter eq 'T-prefix') {
148 if ($barcode =~ /^[Tt](\d)/) {
149 (defined($1) and $1 eq '0') and return $barcode;
150 $barcode = substr($barcode, 2) + 0; # FIXME: probably should be substr($barcode, 1)
152 return sprintf("T%07d", $barcode);
153 # FIXME: $barcode could be "T1", causing warning: substr outside of string
154 # Why drop the nonzero digit after the T?
155 # Why pass non-digits (or empty string) to "T%07d"?
157 return $barcode; # return barcode, modified or not
162 =head3 $str = &decode($chunk);
166 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
169 FIXME: Should be replaced with Barcode::Cuecat from CPAN
170 or Javascript based decoding on the client side.
179 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
180 my @s = map { index( $seq, $_ ); } split( //, $encoded );
181 my $l = ( $#s + 1 ) % 4;
184 # warn "Error: Cuecat decode parsing failed!";
192 my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
194 chr( ( $n >> 16 ) ^ 67 )
195 .chr( ( $n >> 8 & 255 ) ^ 67 )
196 .chr( ( $n & 255 ) ^ 67 );
199 $r = substr( $r, 0, length($r) - $l );
205 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
207 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
209 C<$newbranch> is the code for the branch to which the item should be transferred.
211 C<$barcode> is the barcode of the item to be transferred.
213 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
214 Otherwise, if an item is reserved, the transfer fails.
216 Returns three values:
220 is true if the transfer was successful.
224 is a reference-to-hash which may have any of the following keys:
230 There is no item in the catalog with the given barcode. The value is C<$barcode>.
234 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.
236 =item C<DestinationEqualsHolding>
238 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.
242 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.
246 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>.
248 =item C<WasTransferred>
250 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
257 my ( $tbr, $barcode, $ignoreRs ) = @_;
260 my $branches = GetBranches();
261 my $itemnumber = GetItemnumberFromBarcode( $barcode );
262 my $issue = GetItemIssue($itemnumber);
263 my $biblio = GetBiblioFromItemNumber($itemnumber);
266 if ( not $itemnumber ) {
267 $messages->{'BadBarcode'} = $barcode;
271 # get branches of book...
272 my $hbr = $biblio->{'homebranch'};
273 my $fbr = $biblio->{'holdingbranch'};
276 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
277 $messages->{'IsPermanent'} = $hbr;
280 # can't transfer book if is already there....
281 if ( $fbr eq $tbr ) {
282 $messages->{'DestinationEqualsHolding'} = 1;
286 # check if it is still issued to someone, return it...
287 if ($issue->{borrowernumber}) {
288 AddReturn( $barcode, $fbr );
289 $messages->{'WasReturned'} = $issue->{borrowernumber};
293 # That'll save a database query.
294 my ( $resfound, $resrec ) =
295 CheckReserves( $itemnumber );
296 if ( $resfound and not $ignoreRs ) {
297 $resrec->{'ResFound'} = $resfound;
299 # $messages->{'ResFound'} = $resrec;
303 #actually do the transfer....
305 ModItemTransfer( $itemnumber, $fbr, $tbr );
307 # don't need to update MARC anymore, we do it in batch now
308 $messages->{'WasTransfered'} = 1;
309 ModDateLastSeen( $itemnumber );
311 return ( $dotransfer, $messages, $biblio );
316 my $borrower = shift;
317 my $biblionumber = shift;
319 my $cat_borrower = $borrower->{'categorycode'};
320 my $dbh = C4::Context->dbh;
322 # Get which branchcode we need
323 $branch = _GetCircControlBranch($item,$borrower);
324 my $type = (C4::Context->preference('item-level_itypes'))
325 ? $item->{'itype'} # item-level
326 : $item->{'itemtype'}; # biblio-level
328 # given branch, patron category, and item type, determine
329 # applicable issuing rule
330 my $issuing_rule = GetIssuingRule($cat_borrower, $type, $branch);
332 # if a rule is found and has a loan limit set, count
333 # how many loans the patron already has that meet that
335 if (defined($issuing_rule) and defined($issuing_rule->{'maxissueqty'})) {
337 my $count_query = "SELECT COUNT(*) FROM issues
338 JOIN items USING (itemnumber) ";
340 my $rule_itemtype = $issuing_rule->{itemtype};
341 if ($rule_itemtype eq "*") {
342 # matching rule has the default item type, so count only
343 # those existing loans that don't fall under a more
345 if (C4::Context->preference('item-level_itypes')) {
346 $count_query .= " WHERE items.itype NOT IN (
347 SELECT itemtype FROM issuingrules
349 AND (categorycode = ? OR categorycode = ?)
353 $count_query .= " JOIN biblioitems USING (biblionumber)
354 WHERE biblioitems.itemtype NOT IN (
355 SELECT itemtype FROM issuingrules
357 AND (categorycode = ? OR categorycode = ?)
361 push @bind_params, $issuing_rule->{branchcode};
362 push @bind_params, $issuing_rule->{categorycode};
363 push @bind_params, $cat_borrower;
365 # rule has specific item type, so count loans of that
367 if (C4::Context->preference('item-level_itypes')) {
368 $count_query .= " WHERE items.itype = ? ";
370 $count_query .= " JOIN biblioitems USING (biblionumber)
371 WHERE biblioitems.itemtype= ? ";
373 push @bind_params, $type;
376 $count_query .= " AND borrowernumber = ? ";
377 push @bind_params, $borrower->{'borrowernumber'};
378 my $rule_branch = $issuing_rule->{branchcode};
379 if ($rule_branch ne "*") {
380 if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
381 $count_query .= " AND issues.branchcode = ? ";
382 push @bind_params, $branch;
383 } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
384 ; # if branch is the patron's home branch, then count all loans by patron
386 $count_query .= " AND items.homebranch = ? ";
387 push @bind_params, $branch;
391 my $count_sth = $dbh->prepare($count_query);
392 $count_sth->execute(@bind_params);
393 my ($current_loan_count) = $count_sth->fetchrow_array;
395 my $max_loans_allowed = $issuing_rule->{'maxissueqty'};
396 if ($current_loan_count >= $max_loans_allowed) {
397 return "$current_loan_count / $max_loans_allowed";
401 # Now count total loans against the limit for the branch
402 my $branch_borrower_circ_rule = GetBranchBorrowerCircRule($branch, $cat_borrower);
403 if (defined($branch_borrower_circ_rule->{maxissueqty})) {
404 my @bind_params = ();
405 my $branch_count_query = "SELECT COUNT(*) FROM issues
406 JOIN items USING (itemnumber)
407 WHERE borrowernumber = ? ";
408 push @bind_params, $borrower->{borrowernumber};
410 if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
411 $branch_count_query .= " AND issues.branchcode = ? ";
412 push @bind_params, $branch;
413 } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
414 ; # if branch is the patron's home branch, then count all loans by patron
416 $branch_count_query .= " AND items.homebranch = ? ";
417 push @bind_params, $branch;
419 my $branch_count_sth = $dbh->prepare($branch_count_query);
420 $branch_count_sth->execute(@bind_params);
421 my ($current_loan_count) = $branch_count_sth->fetchrow_array;
423 my $max_loans_allowed = $branch_borrower_circ_rule->{maxissueqty};
424 if ($current_loan_count >= $max_loans_allowed) {
425 return "$current_loan_count / $max_loans_allowed";
429 # OK, the patron can issue !!!
435 @issues = &itemissues($biblioitemnumber, $biblio);
437 Looks up information about who has borrowed the bookZ<>(s) with the
438 given biblioitemnumber.
440 C<$biblio> is ignored.
442 C<&itemissues> returns an array of references-to-hash. The keys
443 include the fields from the C<items> table in the Koha database.
444 Additional keys include:
450 If the item is currently on loan, this gives the due date.
452 If the item is not on loan, then this is either "Available" or
453 "Cancelled", if the item has been withdrawn.
457 If the item is currently on loan, this gives the card number of the
458 patron who currently has the item.
460 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
462 These give the timestamp for the last three times the item was
465 =item C<card0>, C<card1>, C<card2>
467 The card number of the last three patrons who borrowed this item.
469 =item C<borrower0>, C<borrower1>, C<borrower2>
471 The borrower number of the last three patrons who borrowed this item.
479 my ( $bibitem, $biblio ) = @_;
480 my $dbh = C4::Context->dbh;
482 $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
487 $sth->execute($bibitem) || die $sth->errstr;
489 while ( my $data = $sth->fetchrow_hashref ) {
491 # Find out who currently has this item.
492 # FIXME - Wouldn't it be better to do this as a left join of
493 # some sort? Currently, this code assumes that if
494 # fetchrow_hashref() fails, then the book is on the shelf.
495 # fetchrow_hashref() can fail for any number of reasons (e.g.,
496 # database server crash), not just because no items match the
498 my $sth2 = $dbh->prepare(
499 "SELECT * FROM issues
500 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
505 $sth2->execute( $data->{'itemnumber'} );
506 if ( my $data2 = $sth2->fetchrow_hashref ) {
507 $data->{'date_due'} = $data2->{'date_due'};
508 $data->{'card'} = $data2->{'cardnumber'};
509 $data->{'borrower'} = $data2->{'borrowernumber'};
512 $data->{'date_due'} = ($data->{'wthdrawn'} eq '1') ? 'Cancelled' : 'Available';
517 # Find the last 3 people who borrowed this item.
518 $sth2 = $dbh->prepare(
519 "SELECT * FROM old_issues
520 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
522 ORDER BY returndate DESC,timestamp DESC"
525 $sth2->execute( $data->{'itemnumber'} );
526 for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
527 { # FIXME : error if there is less than 3 pple borrowing this item
528 if ( my $data2 = $sth2->fetchrow_hashref ) {
529 $data->{"timestamp$i2"} = $data2->{'timestamp'};
530 $data->{"card$i2"} = $data2->{'cardnumber'};
531 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
536 $results[$i] = $data;
544 =head2 CanBookBeIssued
546 Check if a book can be issued.
548 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $borrower, $barcode, $duedatespec, $inprocess );
550 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
554 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
556 =item C<$barcode> is the bar code of the book being issued.
558 =item C<$duedatespec> is a C4::Dates object.
568 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
569 Possible values are :
575 sticky due date is invalid
579 borrower gone with no address
583 borrower declared it's card lost
589 =head3 UNKNOWN_BARCODE
603 item is restricted (set by ??)
605 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
606 Possible values are :
614 renewing, not issuing
616 =head3 ISSUED_TO_ANOTHER
618 issued to someone else.
622 reserved for someone else.
626 sticky due date is invalid
630 if the borrower borrows to much things
634 sub CanBookBeIssued {
635 my ( $borrower, $barcode, $duedate, $inprocess ) = @_;
636 my %needsconfirmation; # filled with problems that needs confirmations
637 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
638 my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
639 my $issue = GetItemIssue($item->{itemnumber});
640 my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
641 $item->{'itemtype'}=$item->{'itype'};
642 my $dbh = C4::Context->dbh;
644 # MANDATORY CHECKS - unless item exists, nothing else matters
645 unless ( $item->{barcode} ) {
646 $issuingimpossible{UNKNOWN_BARCODE} = 1;
648 return ( \%issuingimpossible, \%needsconfirmation ) if %issuingimpossible;
651 # DUE DATE is OK ? -- should already have checked.
653 unless ( $duedate ) {
654 my $issuedate = strftime( "%Y-%m-%d", localtime );
656 my $branch = _GetCircControlBranch($item,$borrower);
657 my $itype = ( C4::Context->preference('item-level_itypes') ) ? $item->{'itype'} : $biblioitem->{'itemtype'};
658 my $loanlength = GetLoanLength( $borrower->{'categorycode'}, $itype, $branch );
659 $duedate = CalcDateDue( C4::Dates->new( $issuedate, 'iso' ), $loanlength, $branch, $borrower );
661 # Offline circ calls AddIssue directly, doesn't run through here
662 # So issuingimpossible should be ok.
664 $issuingimpossible{INVALID_DATE} = $duedate->output('syspref') unless ( $duedate && $duedate->output('iso') ge C4::Dates->today('iso') );
669 if ( $borrower->{'category_type'} eq 'X' && ( $item->{barcode} )) {
670 # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1 .
671 &UpdateStats(C4::Context->userenv->{'branch'},'localuse','','',$item->{'itemnumber'},$item->{'itemtype'},$borrower->{'borrowernumber'});
672 return( { STATS => 1 }, {});
674 if ( $borrower->{flags}->{GNA} ) {
675 $issuingimpossible{GNA} = 1;
677 if ( $borrower->{flags}->{'LOST'} ) {
678 $issuingimpossible{CARD_LOST} = 1;
680 if ( $borrower->{flags}->{'DBARRED'} ) {
681 $issuingimpossible{DEBARRED} = 1;
683 if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
684 $issuingimpossible{EXPIRED} = 1;
686 my @expirydate= split (/-/,$borrower->{'dateexpiry'});
687 if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
688 Date_to_Days(Today) > Date_to_Days( @expirydate )) {
689 $issuingimpossible{EXPIRED} = 1;
698 C4::Members::GetMemberAccountRecords( $borrower->{'borrowernumber'}, '' && $duedate->output('iso') );
699 if ( C4::Context->preference("IssuingInProcess") ) {
700 my $amountlimit = C4::Context->preference("noissuescharge");
701 if ( $amount > $amountlimit && !$inprocess ) {
702 $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
704 elsif ( $amount > 0 && $amount <= $amountlimit && !$inprocess ) {
705 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
710 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
714 my ($blocktype, $count) = C4::Members::IsMemberBlocked($borrower->{'borrowernumber'});
715 if($blocktype == -1){
716 ## remaining overdue documents
717 $needsconfirmation{USERBLOCKEDREMAINING} = $count;
718 }elsif($blocktype == 1){
719 ## blocked because of overdue return
720 $issuingimpossible{USERBLOCKEDOVERDUE} = $count;
724 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
726 my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
727 # if TooMany return / 0, then the user has no permission to check out this book
728 if ($toomany =~ /\/ 0/) {
729 $needsconfirmation{PATRON_CANT} = 1;
731 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
737 unless ( $item->{barcode} ) {
738 $issuingimpossible{UNKNOWN_BARCODE} = 1;
740 if ( $item->{'notforloan'}
741 && $item->{'notforloan'} > 0 )
743 if(C4::Context->preference("AllowNotForLoanOverride")){
744 $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
746 $issuingimpossible{NOT_FOR_LOAN} = 1;
749 elsif ( !$item->{'notforloan'} ){
750 # we have to check itemtypes.notforloan also
751 if (C4::Context->preference('item-level_itypes')){
752 # this should probably be a subroutine
753 my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
754 $sth->execute($item->{'itemtype'});
755 my $notforloan=$sth->fetchrow_hashref();
757 if ($notforloan->{'notforloan'}) {
758 if (!C4::Context->preference("AllowNotForLoanOverride")) {
759 $issuingimpossible{NOT_FOR_LOAN} = 1;
761 $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
765 elsif ($biblioitem->{'notforloan'} == 1){
766 if (!C4::Context->preference("AllowNotForLoanOverride")) {
767 $issuingimpossible{NOT_FOR_LOAN} = 1;
769 $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
773 if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
775 $issuingimpossible{WTHDRAWN} = 1;
777 if ( $item->{'restricted'}
778 && $item->{'restricted'} == 1 )
780 $issuingimpossible{RESTRICTED} = 1;
782 if ( C4::Context->preference("IndependantBranches") ) {
783 my $userenv = C4::Context->userenv;
784 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
785 $issuingimpossible{NOTSAMEBRANCH} = 1
786 if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} );
791 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
793 if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
796 # Already issued to current borrower. Ask whether the loan should
798 my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed(
799 $borrower->{'borrowernumber'},
800 $item->{'itemnumber'}
802 if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed
803 $issuingimpossible{NO_MORE_RENEWALS} = 1;
806 $needsconfirmation{RENEW_ISSUE} = 1;
809 elsif ($issue->{borrowernumber}) {
811 # issued to someone else
812 my $currborinfo = C4::Members::GetMemberDetails( $issue->{borrowernumber} );
814 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
815 $needsconfirmation{ISSUED_TO_ANOTHER} =
816 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
819 # See if the item is on reserve.
820 my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
822 my $resbor = $res->{'borrowernumber'};
823 my ( $resborrower ) = C4::Members::GetMemberDetails( $resbor, 0 );
824 my $branches = GetBranches();
825 my $branchname = $branches->{ $res->{'branchcode'} }->{'branchname'};
826 if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
828 # The item is on reserve and waiting, but has been
829 # reserved by some other patron.
830 $needsconfirmation{RESERVE_WAITING} =
831 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
833 elsif ( $restype eq "Reserved" ) {
834 # The item is on reserve for someone else.
835 $needsconfirmation{RESERVED} =
836 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
839 return ( \%issuingimpossible, \%needsconfirmation );
844 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
846 &AddIssue($borrower, $barcode, [$datedue], [$cancelreserve], [$issuedate])
850 =item C<$borrower> is a hash with borrower informations (from GetMemberDetails).
852 =item C<$barcode> is the barcode of the item being issued.
854 =item C<$datedue> is a C4::Dates object for the max date of return, i.e. the date due (optional).
857 =item C<$cancelreserve> is 1 to override and cancel any pending reserves for the item (optional).
859 =item C<$issuedate> is the date to issue the item in iso (YYYY-MM-DD) format (optional).
860 Defaults to today. Unlike C<$datedue>, NOT a C4::Dates object, unfortunately.
862 AddIssue does the following things :
863 - step 01: check that there is a borrowernumber & a barcode provided
864 - check for RENEWAL (book issued & being issued to the same patron)
865 - renewal YES = Calculate Charge & renew
867 * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
869 - fill reserve if reserve to this patron
870 - cancel reserve or not, otherwise
871 * TRANSFERT PENDING ?
872 - complete the transfert
880 my ( $borrower, $barcode, $datedue, $cancelreserve, $issuedate, $sipmode) = @_;
881 my $dbh = C4::Context->dbh;
882 my $barcodecheck=CheckValidBarcode($barcode);
883 # $issuedate defaults to today.
884 if ( ! defined $issuedate ) {
885 $issuedate = strftime( "%Y-%m-%d", localtime );
886 # TODO: for hourly circ, this will need to be a C4::Dates object
887 # and all calls to AddIssue including issuedate will need to pass a Dates object.
889 if ($borrower and $barcode and $barcodecheck ne '0'){
890 # find which item we issue
891 my $item = GetItem('', $barcode) or return undef; # if we don't get an Item, abort.
892 my $hbr = C4::Context->preference("HomeOrHoldingBranch")||"homebranch";
893 my $branch = _GetCircControlBranch($item,$borrower);
895 # get actual issuing if there is one
896 my $actualissue = GetItemIssue( $item->{itemnumber});
898 # get biblioinformation for this item
899 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
902 # check if we just renew the issue.
904 if ($actualissue->{borrowernumber} eq $borrower->{'borrowernumber'}) {
905 $datedue = AddRenewal(
906 $borrower->{'borrowernumber'},
907 $item->{'itemnumber'},
910 $issuedate, # here interpreted as the renewal date
915 if ( $actualissue->{borrowernumber}) {
916 # This book is currently on loan, but not to the person
917 # who wants to borrow it now. mark it returned before issuing to the new borrower
920 C4::Context->userenv->{'branch'}
924 # See if the item is on reserve.
925 my ( $restype, $res ) =
926 C4::Reserves::CheckReserves( $item->{'itemnumber'} );
928 my $resbor = $res->{'borrowernumber'};
929 if ( $resbor eq $borrower->{'borrowernumber'} ) {
930 # The item is reserved by the current patron
931 ModReserveFill($res);
933 elsif ( $restype eq "Waiting" ) {
935 # The item is on reserve and waiting, but has been
936 # reserved by some other patron.
938 elsif ( $restype eq "Reserved" ) {
940 # The item is reserved by someone else.
941 if ($cancelreserve) { # cancel reserves on this item
942 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
945 if ($cancelreserve) {
946 CancelReserve($res->{'biblionumber'}, 0, $res->{'borrowernumber'});
949 # set waiting reserve to first in reserve queue as book isn't waiting now
951 $res->{'biblionumber'},
952 $res->{'borrowernumber'},
958 # Starting process for transfer job (checking transfert and validate it if we have one)
959 my ($datesent) = GetTransfers($item->{'itemnumber'});
961 # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for visibility of this case (maybe for stats ....)
964 "UPDATE branchtransfers
965 SET datearrived = now(),
967 comments = 'Forced branchtransfer'
968 WHERE itemnumber= ? AND datearrived IS NULL"
970 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
973 # Record in the database the fact that the book was issued.
977 (borrowernumber, itemnumber,issuedate, date_due, branchcode)
981 my $itype = ( C4::Context->preference('item-level_itypes') ) ? $biblio->{'itype'} : $biblio->{'itemtype'};
982 my $loanlength = GetLoanLength( $borrower->{'categorycode'}, $itype, $branch );
983 $datedue = CalcDateDue( C4::Dates->new( $issuedate, 'iso' ), $loanlength, $branch, $borrower );
985 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
986 if ( C4::Context->preference('ReturnBeforeExpiry') && $datedue->output('iso') gt $borrower->{dateexpiry} ) {
987 $datedue = C4::Dates->new( $borrower->{dateexpiry}, 'iso' );
991 $borrower->{'borrowernumber'}, # borrowernumber
992 $item->{'itemnumber'}, # itemnumber
993 $issuedate, # issuedate
994 $datedue->output('iso'), # date_due
998 ModItem({ issues => $item->{'issues'},
999 holdingbranch => C4::Context->userenv->{branch},
1001 datelastborrowed => C4::Dates->new()->output('iso'),
1002 onloan => $datedue->output('iso'),
1003 }, $item->{'biblionumber'}, $item->{'itemnumber'});
1004 ModDateLastSeen( $item->{'itemnumber'} );
1006 # If it costs to borrow this book, charge it to the patron's account.
1007 my ( $charge, $itemtype ) = GetIssuingCharges(
1008 $item->{'itemnumber'},
1009 $borrower->{'borrowernumber'}
1011 if ( $charge > 0 ) {
1013 $item->{'itemnumber'},
1014 $borrower->{'borrowernumber'}, $charge
1016 $item->{'charge'} = $charge;
1019 # Record the fact that this book was issued.
1021 C4::Context->userenv->{'branch'},
1023 ($sipmode ? "SIP-$sipmode" : ''), $item->{'itemnumber'},
1024 $item->{'itype'}, $borrower->{'borrowernumber'}
1028 logaction("CIRCULATION", "ISSUE", $borrower->{'borrowernumber'}, $biblio->{'biblionumber'})
1029 if C4::Context->preference("IssueLog");
1031 return ($datedue); # not necessarily the same as when it came in!
1034 =head2 GetLoanLength
1036 Get loan length for an itemtype, a borrower type and a branch
1038 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1043 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1044 my $dbh = C4::Context->dbh;
1047 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1049 # warn "in get loan lenght $borrowertype $itemtype $branchcode ";
1050 # try to find issuelength & return the 1st available.
1051 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1052 $sth->execute( $borrowertype, $itemtype, $branchcode );
1053 my $loanlength = $sth->fetchrow_hashref;
1054 return $loanlength->{issuelength}
1055 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1057 $sth->execute( $borrowertype, "*", $branchcode );
1058 $loanlength = $sth->fetchrow_hashref;
1059 return $loanlength->{issuelength}
1060 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1062 $sth->execute( "*", $itemtype, $branchcode );
1063 $loanlength = $sth->fetchrow_hashref;
1064 return $loanlength->{issuelength}
1065 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1067 $sth->execute( "*", "*", $branchcode );
1068 $loanlength = $sth->fetchrow_hashref;
1069 return $loanlength->{issuelength}
1070 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1072 $sth->execute( $borrowertype, $itemtype, "*" );
1073 $loanlength = $sth->fetchrow_hashref;
1074 return $loanlength->{issuelength}
1075 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1077 $sth->execute( $borrowertype, "*", "*" );
1078 $loanlength = $sth->fetchrow_hashref;
1079 return $loanlength->{issuelength}
1080 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1082 $sth->execute( "*", $itemtype, "*" );
1083 $loanlength = $sth->fetchrow_hashref;
1084 return $loanlength->{issuelength}
1085 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1087 $sth->execute( "*", "*", "*" );
1088 $loanlength = $sth->fetchrow_hashref;
1089 return $loanlength->{issuelength}
1090 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1092 # if no rule is set => 21 days (hardcoded)
1096 =head2 GetIssuingRule
1098 FIXME - This is a copy-paste of GetLoanLength
1099 as a stop-gap. Do not wish to change API for GetLoanLength
1100 this close to release, however, Overdues::GetIssuingRules is broken.
1102 Get the issuing rule for an itemtype, a borrower type and a branch
1103 Returns a hashref from the issuingrules table.
1105 my $irule = &GetIssuingRule($borrowertype,$itemtype,branchcode)
1109 sub GetIssuingRule {
1110 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1111 my $dbh = C4::Context->dbh;
1112 my $sth = $dbh->prepare( "select * from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null" );
1115 $sth->execute( $borrowertype, $itemtype, $branchcode );
1116 $irule = $sth->fetchrow_hashref;
1117 return $irule if defined($irule) ;
1119 $sth->execute( $borrowertype, "*", $branchcode );
1120 $irule = $sth->fetchrow_hashref;
1121 return $irule if defined($irule) ;
1123 $sth->execute( "*", $itemtype, $branchcode );
1124 $irule = $sth->fetchrow_hashref;
1125 return $irule if defined($irule) ;
1127 $sth->execute( "*", "*", $branchcode );
1128 $irule = $sth->fetchrow_hashref;
1129 return $irule if defined($irule) ;
1131 $sth->execute( $borrowertype, $itemtype, "*" );
1132 $irule = $sth->fetchrow_hashref;
1133 return $irule if defined($irule) ;
1135 $sth->execute( $borrowertype, "*", "*" );
1136 $irule = $sth->fetchrow_hashref;
1137 return $irule if defined($irule) ;
1139 $sth->execute( "*", $itemtype, "*" );
1140 $irule = $sth->fetchrow_hashref;
1141 return $irule if defined($irule) ;
1143 $sth->execute( "*", "*", "*" );
1144 $irule = $sth->fetchrow_hashref;
1145 return $irule if defined($irule) ;
1147 # if no rule matches,
1151 =head2 GetBranchBorrowerCircRule
1155 my $branch_cat_rule = GetBranchBorrowerCircRule($branchcode, $categorycode);
1159 Retrieves circulation rule attributes that apply to the given
1160 branch and patron category, regardless of item type.
1161 The return value is a hashref containing the following key:
1163 maxissueqty - maximum number of loans that a
1164 patron of the given category can have at the given
1165 branch. If the value is undef, no limit.
1167 This will first check for a specific branch and
1168 category match from branch_borrower_circ_rules.
1170 If no rule is found, it will then check default_branch_circ_rules
1171 (same branch, default category). If no rule is found,
1172 it will then check default_borrower_circ_rules (default
1173 branch, same category), then failing that, default_circ_rules
1174 (default branch, default category).
1176 If no rule has been found in the database, it will default to
1181 C<$branchcode> and C<$categorycode> should contain the
1182 literal branch code and patron category code, respectively - no
1187 sub GetBranchBorrowerCircRule {
1188 my $branchcode = shift;
1189 my $categorycode = shift;
1191 my $branch_cat_query = "SELECT maxissueqty
1192 FROM branch_borrower_circ_rules
1193 WHERE branchcode = ?
1194 AND categorycode = ?";
1195 my $dbh = C4::Context->dbh();
1196 my $sth = $dbh->prepare($branch_cat_query);
1197 $sth->execute($branchcode, $categorycode);
1199 if ($result = $sth->fetchrow_hashref()) {
1203 # try same branch, default borrower category
1204 my $branch_query = "SELECT maxissueqty
1205 FROM default_branch_circ_rules
1206 WHERE branchcode = ?";
1207 $sth = $dbh->prepare($branch_query);
1208 $sth->execute($branchcode);
1209 if ($result = $sth->fetchrow_hashref()) {
1213 # try default branch, same borrower category
1214 my $category_query = "SELECT maxissueqty
1215 FROM default_borrower_circ_rules
1216 WHERE categorycode = ?";
1217 $sth = $dbh->prepare($category_query);
1218 $sth->execute($categorycode);
1219 if ($result = $sth->fetchrow_hashref()) {
1223 # try default branch, default borrower category
1224 my $default_query = "SELECT maxissueqty
1225 FROM default_circ_rules";
1226 $sth = $dbh->prepare($default_query);
1228 if ($result = $sth->fetchrow_hashref()) {
1232 # built-in default circulation rule
1234 maxissueqty => undef,
1237 =head2 GetBranchItemRule
1241 my $branch_item_rule = GetBranchItemRule($branchcode, $itemtype);
1245 Retrieves circulation rule attributes that apply to the given
1246 branch and item type, regardless of patron category.
1248 The return value is a hashref containing the following key:
1250 holdallowed => Hold policy for this branch and itemtype. Possible values:
1251 0: No holds allowed.
1252 1: Holds allowed only by patrons that have the same homebranch as the item.
1253 2: Holds allowed from any patron.
1255 This searches branchitemrules in the following order:
1257 * Same branchcode and itemtype
1258 * Same branchcode, itemtype '*'
1259 * branchcode '*', same itemtype
1260 * branchcode and itemtype '*'
1262 Neither C<$branchcode> nor C<$categorycode> should be '*'.
1266 sub GetBranchItemRule {
1267 my ( $branchcode, $itemtype ) = @_;
1268 my $dbh = C4::Context->dbh();
1272 ['SELECT holdallowed
1273 FROM branch_item_rules
1274 WHERE branchcode = ?
1275 AND itemtype = ?', $branchcode, $itemtype],
1276 ['SELECT holdallowed
1277 FROM default_branch_circ_rules
1278 WHERE branchcode = ?', $branchcode],
1279 ['SELECT holdallowed
1280 FROM default_branch_item_rules
1281 WHERE itemtype = ?', $itemtype],
1282 ['SELECT holdallowed
1283 FROM default_circ_rules'],
1286 foreach my $attempt (@attempts) {
1287 my ($query, @bind_params) = @{$attempt};
1289 # Since branch/category and branch/itemtype use the same per-branch
1290 # defaults tables, we have to check that the key we want is set, not
1291 # just that a row was returned
1292 return $result if ( defined( $result->{'holdallowed'} = $dbh->selectrow_array( $query, {}, @bind_params ) ) );
1295 # built-in default circulation rule
1304 ($doreturn, $messages, $iteminformation, $borrower) =
1305 &AddReturn($barcode, $branch, $exemptfine, $dropbox);
1311 =item C<$barcode> is the bar code of the book being returned.
1313 =item C<$branch> is the code of the branch where the book is being returned.
1315 =item C<$exemptfine> indicates that overdue charges for the item will be
1318 =item C<$dropbox> indicates that the check-in date is assumed to be
1319 yesterday, or the last non-holiday as defined in C4::Calendar . If
1320 overdue charges are applied and C<$dropbox> is true, the last charge
1321 will be removed. This assumes that the fines accrual script has run
1326 C<&AddReturn> returns a list of four items:
1328 C<$doreturn> is true iff the return succeeded.
1330 C<$messages> is a reference-to-hash giving the reason for failure:
1336 No item with this barcode exists. The value is C<$barcode>.
1340 The book is not currently on loan. The value is C<$barcode>.
1342 =item C<IsPermanent>
1344 The book's home branch is a permanent collection. If you have borrowed
1345 this book, you are not allowed to return it. The value is the code for
1346 the book's home branch.
1350 This book has been withdrawn/cancelled. The value should be ignored.
1354 The item was reserved. The value is a reference-to-hash whose keys are
1355 fields from the reserves table of the Koha database, and
1356 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1357 either C<Waiting>, C<Reserved>, or 0.
1361 C<$iteminformation> is a reference-to-hash, giving information about the
1362 returned item from the issues table.
1364 C<$borrower> is a reference-to-hash, giving information about the
1365 patron who last borrowed the book.
1370 my ( $barcode, $branch, $exemptfine, $dropbox ) = @_;
1371 my $dbh = C4::Context->dbh;
1375 my $validTransfert = 0;
1376 my $reserveDone = 0;
1377 $branch ||=C4::Context->userenv->{'branch'};
1379 # get information on item
1380 my $itemnumber = GetItemnumberFromBarcode($barcode);
1381 my $iteminformation = GetItemIssue( $itemnumber );
1382 my $biblio = GetBiblioItemData($iteminformation->{'biblioitemnumber'});
1383 # use Data::Dumper;warn Data::Dumper::Dumper($iteminformation);
1384 unless ( $iteminformation->{'itemnumber'} or $itemnumber) {
1385 $messages->{'BadBarcode'} = $barcode;
1388 $iteminformation->{'itemnumber'} = $itemnumber;
1390 if ( not $iteminformation->{borrowernumber} ) {
1391 $messages->{'NotIssued'} = $barcode;
1395 # even though item is not on loan, it may still
1396 # be transferred; therefore, get current branch information
1397 my $curr_iteminfo = GetItem($itemnumber);
1398 $iteminformation->{'homebranch'} = $curr_iteminfo->{'homebranch'};
1399 $iteminformation->{'holdingbranch'} = $curr_iteminfo->{'holdingbranch'};
1400 $iteminformation->{'itemlost'} = $curr_iteminfo->{'itemlost'};
1402 # check if the book is in a permanent collection....
1403 my $hbr = C4::Context->preference("HomeOrHoldingBranchReturn") || "homebranch";
1404 $hbr = $iteminformation->{$hbr};
1405 my $branches = GetBranches();
1406 # FIXME -- This 'PE' attribute is largely undocumented. afaict, there's no user interface that reflects this functionality.
1407 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1408 $messages->{'IsPermanent'} = $hbr;
1411 # if independent branches are on and returning to different branch, refuse the return
1412 if ($hbr ne $branch && C4::Context->preference("IndependantBranches") && $iteminformation->{borrowernumber}){
1413 $messages->{'Wrongbranch'} = 1;
1417 # check that the book has been cancelled
1418 if ( $iteminformation->{'wthdrawn'} ) {
1419 $messages->{'wthdrawn'} = 1;
1423 # We know the document was just seen
1424 ModDateLastSeen( $iteminformation->{'itemnumber'} );
1426 # new op dev : if the book returned in an other branch update the holding branch
1428 # update issues, thereby returning book (should push this out into another subroutine
1429 $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1431 # case of a return of document (deal with issues and holdingbranch)
1434 my $circControlBranch = _GetCircControlBranch($iteminformation,$borrower);
1436 # don't allow dropbox mode to create an invalid entry in issues (issuedate > returndate) FIXME: actually checks eq, not gt
1437 undef($dropbox) if ( $iteminformation->{'issuedate'} eq C4::Dates->today('iso') );
1439 MarkIssueReturned($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'},$circControlBranch);
1440 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1441 # continue to deal with returns cases, but not only if we have an issue
1444 # We update the holdingbranch from circControlBranch variable
1445 UpdateHoldingbranch($branch,$iteminformation->{'itemnumber'});
1446 $iteminformation->{'holdingbranch'} = $branch;
1448 ModItem({ onloan => undef }, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'});
1450 if ($iteminformation->{borrowernumber}){
1451 ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1455 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1456 # check if we have a transfer for this document
1457 my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1459 # if we have a transfer to do, we update the line of transfers with the datearrived
1461 if ( $tobranch eq $branch ) {
1464 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1466 $sth->execute( $iteminformation->{'itemnumber'} );
1468 # 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'
1469 C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1472 $messages->{'WrongTransfer'} = $tobranch;
1473 $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1475 $validTransfert = 1;
1478 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1479 # fix up the accounts.....
1480 if ($iteminformation->{'itemlost'}) {
1481 FixAccountForLostAndReturned($iteminformation, $borrower);
1482 ModItem({ itemlost => '0' }, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'});
1483 $messages->{'WasLost'} = 1;
1485 # fix up the overdues in accounts...
1486 FixOverduesOnReturn( $borrower->{'borrowernumber'},
1487 $iteminformation->{'itemnumber'}, $exemptfine, $dropbox );
1489 # find reserves.....
1490 # if we don't have a reserve with the status W, we launch the Checkreserves routine
1491 my ( $resfound, $resrec ) =
1492 C4::Reserves::CheckReserves( $itemnumber, $barcode );
1494 $resrec->{'ResFound'} = $resfound;
1495 $messages->{'ResFound'} = $resrec;
1500 # Record the fact that this book was returned.
1502 $branch, 'return', '0', '',
1503 $iteminformation->{'itemnumber'},
1504 $biblio->{'itemtype'},
1505 $borrower->{'borrowernumber'}
1508 logaction("CIRCULATION", "RETURN", $iteminformation->{borrowernumber}, $iteminformation->{'biblionumber'})
1509 if C4::Context->preference("ReturnLog");
1511 #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1512 #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1513 if (($doreturn or $messages->{'NotIssued'})
1514 and ($branch ne $hbr)
1515 and not $messages->{'WrongTransfer'}
1516 and ($validTransfert ne 1)
1517 and ($reserveDone ne 1) ){
1518 if (C4::Context->preference("AutomaticItemReturn") == 1) {
1519 ModItemTransfer($iteminformation->{'itemnumber'}, $branch, $iteminformation->{$hbr});
1520 $messages->{'WasTransfered'} = 1;
1523 $messages->{'NeedsTransfer'} = 1;
1527 return ( $doreturn, $messages, $iteminformation, $borrower );
1530 =head2 MarkIssueReturned
1534 MarkIssueReturned($borrowernumber, $itemnumber, $dropbox_branch, $returndate);
1538 Unconditionally marks an issue as being returned by
1539 moving the C<issues> row to C<old_issues> and
1540 setting C<returndate> to the current date, or
1541 the last non-holiday date of the branccode specified in
1542 C<dropbox_branch> . Assumes you've already checked that
1543 it's safe to do this, i.e. last non-holiday > issuedate.
1545 if C<$returndate> is specified (in iso format), it is used as the date
1546 of the return. It is ignored when a dropbox_branch is passed in.
1548 Ideally, this function would be internal to C<C4::Circulation>,
1549 not exported, but it is currently needed by one
1550 routine in C<C4::Accounts>.
1554 sub MarkIssueReturned {
1555 my ( $borrowernumber, $itemnumber, $dropbox_branch, $returndate ) = @_;
1556 my $dbh = C4::Context->dbh;
1557 my $query = "UPDATE issues SET returndate=";
1559 if ($dropbox_branch) {
1560 my $calendar = C4::Calendar->new( branchcode => $dropbox_branch );
1561 my $dropboxdate = $calendar->addDate( C4::Dates->new(), -1 );
1563 push @bind, $dropboxdate->output('iso');
1564 } elsif ($returndate) {
1566 push @bind, $returndate;
1568 $query .= " now() ";
1570 $query .= " WHERE borrowernumber = ? AND itemnumber = ?";
1571 push @bind, $borrowernumber, $itemnumber;
1573 my $sth_upd = $dbh->prepare($query);
1574 $sth_upd->execute(@bind);
1575 my $sth_copy = $dbh->prepare("INSERT INTO old_issues SELECT * FROM issues
1576 WHERE borrowernumber = ?
1577 AND itemnumber = ?");
1578 $sth_copy->execute($borrowernumber, $itemnumber);
1579 my $sth_del = $dbh->prepare("DELETE FROM issues
1580 WHERE borrowernumber = ?
1581 AND itemnumber = ?");
1582 $sth_del->execute($borrowernumber, $itemnumber);
1585 =head2 FixOverduesOnReturn
1587 &FixOverduesOnReturn($brn,$itm, $exemptfine, $dropboxmode);
1589 C<$brn> borrowernumber
1593 C<$exemptfine> BOOL -- remove overdue charge associated with this issue.
1594 C<$dropboxmode> BOOL -- remove lastincrement on overdue charge associated with this issue.
1596 internal function, called only by AddReturn
1600 sub FixOverduesOnReturn {
1601 my ( $borrowernumber, $item, $exemptfine, $dropbox ) = @_;
1602 my $dbh = C4::Context->dbh;
1604 # check for overdue fine
1607 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1609 $sth->execute( $borrowernumber, $item );
1611 # alter fine to show that the book has been returned
1613 if ($data = $sth->fetchrow_hashref) {
1615 my @bind = ($borrowernumber,$item ,$data->{'accountno'});
1617 $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
1618 if (C4::Context->preference("FinesLog")) {
1619 &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
1621 } elsif ($dropbox && $data->{lastincrement}) {
1622 my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
1623 my $amt = $data->{amount} - $data->{lastincrement} ;
1624 if (C4::Context->preference("FinesLog")) {
1625 &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
1627 $uquery = "update accountlines set accounttype='F' ";
1628 if($outstanding >= 0 && $amt >=0) {
1629 $uquery .= ", amount = ? , amountoutstanding=? ";
1630 unshift @bind, ($amt, $outstanding) ;
1633 $uquery = "update accountlines set accounttype='F' ";
1635 $uquery .= " where (borrowernumber = ?) and (itemnumber = ?) and (accountno = ?)";
1636 my $usth = $dbh->prepare($uquery);
1637 $usth->execute(@bind);
1645 =head2 FixAccountForLostAndReturned
1647 &FixAccountForLostAndReturned($iteminfo,$borrower);
1649 Calculates the charge for a book lost and returned (Not exported & used only once)
1651 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1653 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1655 Internal function, called by AddReturn
1659 sub FixAccountForLostAndReturned {
1660 my ($iteminfo, $borrower) = @_;
1661 my $dbh = C4::Context->dbh;
1662 my $itm = $iteminfo->{'itemnumber'};
1663 # check for charge made for lost book
1664 my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1665 $sth->execute($itm);
1666 if (my $data = $sth->fetchrow_hashref) {
1667 # writeoff this amount
1669 my $amount = $data->{'amount'};
1670 my $acctno = $data->{'accountno'};
1672 if ($data->{'amountoutstanding'} == $amount) {
1673 $offset = $data->{'amount'};
1676 $offset = $amount - $data->{'amountoutstanding'};
1677 $amountleft = $data->{'amountoutstanding'} - $amount;
1679 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1680 WHERE (borrowernumber = ?)
1681 AND (itemnumber = ?) AND (accountno = ?) ");
1682 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1683 #check if any credit is left if so writeoff other accounts
1684 my $nextaccntno = getnextacctno($data->{'borrowernumber'});
1685 if ($amountleft < 0){
1688 if ($amountleft > 0){
1689 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1690 AND (amountoutstanding >0) ORDER BY date");
1691 $msth->execute($data->{'borrowernumber'});
1692 # offset transactions
1695 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1696 if ($accdata->{'amountoutstanding'} < $amountleft) {
1698 $amountleft -= $accdata->{'amountoutstanding'};
1700 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1703 my $thisacct = $accdata->{'accountno'};
1704 my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1705 WHERE (borrowernumber = ?)
1706 AND (accountno=?)");
1707 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1709 $usth = $dbh->prepare("INSERT INTO accountoffsets
1710 (borrowernumber, accountno, offsetaccount, offsetamount)
1713 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1715 $msth->finish; # $msth might actually have data left
1717 if ($amountleft > 0){
1720 my $desc="Item Returned ".$iteminfo->{'barcode'};
1721 $usth = $dbh->prepare("INSERT INTO accountlines
1722 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1723 VALUES (?,?,now(),?,?,'CR',?)");
1724 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1725 $usth = $dbh->prepare("INSERT INTO accountoffsets
1726 (borrowernumber, accountno, offsetaccount, offsetamount)
1728 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1729 ModItem({ paidfor => '' }, undef, $itm);
1735 =head2 _GetCircControlBranch
1737 my $circ_control_branch = _GetCircControlBranch($iteminfos, $borrower);
1741 Return the library code to be used to determine which circulation
1742 policy applies to a transaction. Looks up the CircControl and
1743 HomeOrHoldingBranch system preferences.
1745 C<$iteminfos> is a hashref to iteminfo. Only {itemnumber} is used.
1747 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1751 sub _GetCircControlBranch {
1752 my ($iteminfos, $borrower) = @_;
1753 my $circcontrol = C4::Context->preference('CircControl');
1756 if ($circcontrol eq 'PickupLibrary') {
1757 $branch= C4::Context->userenv->{'branch'};
1758 } elsif ($circcontrol eq 'PatronLibrary') {
1759 $branch=$borrower->{branchcode};
1761 my $branchfield = C4::Context->preference('HomeOrHoldingBranch') || 'homebranch';
1762 $branch = $iteminfos->{$branchfield};
1769 $issues = &GetItemIssue($itemnumber);
1771 Returns patron currently having a book, or undef if not checked out.
1773 C<$itemnumber> is the itemnumber
1775 C<$issues> is an array of hashes.
1780 my ($itemnumber) = @_;
1781 return unless $itemnumber;
1782 my $sth = C4::Context->dbh->prepare(
1785 LEFT JOIN items ON issues.itemnumber=items.itemnumber
1786 WHERE issues.itemnumber=?");
1787 $sth->execute($itemnumber);
1788 my $data = $sth->fetchrow_hashref;
1789 return unless $data;
1790 $data->{'overdue'} = ($data->{'date_due'} lt C4::Dates->today('iso')) ? 1 : 0;
1791 $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue.
1792 # FIXME: that would mean issues.itemnumber IS NULL and we didn't really match it.
1798 $issue = GetOpenIssue( $itemnumber );
1800 Returns the row from the issues table if the item is currently issued, undef if the item is not currently issued
1802 C<$itemnumber> is the item's itemnumber
1809 my ( $itemnumber ) = @_;
1811 my $dbh = C4::Context->dbh;
1812 my $sth = $dbh->prepare( "SELECT * FROM issues WHERE itemnumber = ? AND returndate IS NULL" );
1813 $sth->execute( $itemnumber );
1814 my $issue = $sth->fetchrow_hashref();
1818 =head2 GetItemIssues
1820 $issues = &GetItemIssues($itemnumber, $history);
1822 Returns patrons that have issued a book
1824 C<$itemnumber> is the itemnumber
1825 C<$history> is false if you just want the current "issuer" (if any)
1826 and true if you want issues history from old_issues also.
1828 Returns reference to an array of hashes
1833 my ( $itemnumber, $history ) = @_;
1835 my $today = C4::Dates->today('iso'); # get today date
1836 my $sql = "SELECT * FROM issues
1837 JOIN borrowers USING (borrowernumber)
1838 JOIN items USING (itemnumber)
1839 WHERE issues.itemnumber = ? ";
1842 SELECT * FROM old_issues
1843 LEFT JOIN borrowers USING (borrowernumber)
1844 JOIN items USING (itemnumber)
1845 WHERE old_issues.itemnumber = ? ";
1847 $sql .= "ORDER BY date_due DESC";
1848 my $sth = C4::Context->dbh->prepare($sql);
1850 $sth->execute($itemnumber, $itemnumber);
1852 $sth->execute($itemnumber);
1854 my $results = $sth->fetchall_arrayref({});
1855 foreach (@$results) {
1856 $_->{'overdue'} = ($_->{'date_due'} lt $today) ? 1 : 0;
1861 =head2 GetBiblioIssues
1863 $issues = GetBiblioIssues($biblionumber);
1865 this function get all issues from a biblionumber.
1868 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1869 tables issues and the firstname,surname & cardnumber from borrowers.
1873 sub GetBiblioIssues {
1874 my $biblionumber = shift;
1875 return undef unless $biblionumber;
1876 my $dbh = C4::Context->dbh;
1878 SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1880 LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1881 LEFT JOIN items ON issues.itemnumber = items.itemnumber
1882 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1883 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1884 WHERE biblio.biblionumber = ?
1886 SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1888 LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
1889 LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
1890 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1891 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1892 WHERE biblio.biblionumber = ?
1895 my $sth = $dbh->prepare($query);
1896 $sth->execute($biblionumber, $biblionumber);
1899 while ( my $data = $sth->fetchrow_hashref ) {
1900 push @issues, $data;
1905 =head2 GetUpcomingDueIssues
1909 my $upcoming_dues = GetUpcomingDueIssues( { days_in_advance => 4 } );
1915 sub GetUpcomingDueIssues {
1918 $params->{'days_in_advance'} = 7 unless exists $params->{'days_in_advance'};
1919 my $dbh = C4::Context->dbh;
1921 my $statement = <<END_SQL;
1922 SELECT issues.*, items.itype as itemtype, items.homebranch, TO_DAYS( date_due )-TO_DAYS( NOW() ) as days_until_due
1924 LEFT JOIN items USING (itemnumber)
1925 WhERE returndate is NULL
1926 AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ?
1929 my @bind_parameters = ( $params->{'days_in_advance'} );
1931 my $sth = $dbh->prepare( $statement );
1932 $sth->execute( @bind_parameters );
1933 my $upcoming_dues = $sth->fetchall_arrayref({});
1936 return $upcoming_dues;
1939 =head2 CanBookBeRenewed
1941 ($ok,$error) = &CanBookBeRenewed($borrowernumber, $itemnumber[, $override_limit]);
1943 Find out whether a borrowed item may be renewed.
1945 C<$dbh> is a DBI handle to the Koha database.
1947 C<$borrowernumber> is the borrower number of the patron who currently
1948 has the item on loan.
1950 C<$itemnumber> is the number of the item to renew.
1952 C<$override_limit>, if supplied with a true value, causes
1953 the limit on the number of times that the loan can be renewed
1954 (as controlled by the item type) to be ignored.
1956 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1957 item must currently be on loan to the specified borrower; renewals
1958 must be allowed for the item's type; and the borrower must not have
1959 already renewed the loan. $error will contain the reason the renewal can not proceed
1963 sub CanBookBeRenewed {
1965 # check renewal status
1966 my ( $borrowernumber, $itemnumber, $override_limit ) = @_;
1967 my $dbh = C4::Context->dbh;
1972 # Look in the issues table for this item, lent to this borrower,
1973 # and not yet returned.
1975 # FIXME - I think this function could be redone to use only one SQL call.
1976 my $sth1 = $dbh->prepare(
1977 "SELECT * FROM issues
1978 WHERE borrowernumber = ?
1981 $sth1->execute( $borrowernumber, $itemnumber );
1982 if ( my $data1 = $sth1->fetchrow_hashref ) {
1984 # Found a matching item
1986 # See if this item may be renewed. This query is convoluted
1987 # because it's a bit messy: given the item number, we need to find
1988 # the biblioitem, which gives us the itemtype, which tells us
1989 # whether it may be renewed.
1990 my $query = "SELECT renewalsallowed FROM items ";
1991 $query .= (C4::Context->preference('item-level_itypes'))
1992 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1993 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1994 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1995 $query .= "WHERE items.itemnumber = ?";
1996 my $sth2 = $dbh->prepare($query);
1997 $sth2->execute($itemnumber);
1998 if ( my $data2 = $sth2->fetchrow_hashref ) {
1999 $renews = $data2->{'renewalsallowed'};
2001 if ( ( $renews && $renews > $data1->{'renewals'} ) || $override_limit ) {
2008 my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
2016 return ($renewokay,$error);
2021 &AddRenewal($borrowernumber, $itemnumber, $branch, [$datedue], [$lastreneweddate]);
2025 C<$borrowernumber> is the borrower number of the patron who currently
2028 C<$itemnumber> is the number of the item to renew.
2030 C<$branch> is the library where the renewal took place (if any).
2031 The library that controls the circ policies for the renewal is retrieved from the issues record.
2033 C<$datedue> can be a C4::Dates object used to set the due date.
2035 C<$lastreneweddate> is an optional ISO-formatted date used to set issues.lastreneweddate. If
2036 this parameter is not supplied, lastreneweddate is set to the current date.
2038 If C<$datedue> is the empty string, C<&AddRenewal> will calculate the due date automatically
2039 from the book's item type.
2045 my $borrowernumber = shift or return undef;
2046 my $itemnumber = shift or return undef;
2047 my $item = GetItem($itemnumber) or return undef;
2048 my $branch = (@_) ? shift : $item->{homebranch}; # opac-renew doesn't send branch
2049 my $datedue = shift;
2050 my $lastreneweddate = shift || C4::Dates->new()->output('iso');
2053 my $biblio = GetBiblioFromItemNumber($itemnumber) or return undef;
2055 # If the due date wasn't specified, calculate it by adding the
2056 # book's loan length to today's date.
2057 unless ($datedue && $datedue->output('iso')) {
2059 my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 ) or return undef;
2060 my $loanlength = GetLoanLength(
2061 $borrower->{'categorycode'},
2062 (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
2063 $item->{homebranch} # item's homebranch determines loanlength OR do we want the branch specified by the AddRenewal argument?
2065 #FIXME -- use circControl?
2066 $datedue = CalcDateDue(C4::Dates->new(),$loanlength,$branch,$borrower); # this branch is the transactional branch.
2067 # The question of whether to use item's homebranch calendar is open.
2070 # $lastreneweddate defaults to today.
2071 unless (defined $lastreneweddate) {
2072 $lastreneweddate = strftime( "%Y-%m-%d", localtime );
2075 my $dbh = C4::Context->dbh;
2076 # Find the issues record for this book
2078 $dbh->prepare("SELECT * FROM issues
2079 WHERE borrowernumber=?
2082 $sth->execute( $borrowernumber, $itemnumber );
2083 my $issuedata = $sth->fetchrow_hashref;
2085 if($datedue && ! $datedue->output('iso')){
2086 warn "Invalid date passed to AddRenewal.";
2089 # If the due date wasn't specified, calculate it by adding the
2090 # book's loan length to today's date or the current due date
2091 # based on the value of the RenewalPeriodBase syspref.
2094 my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 ) or return undef;
2095 my $loanlength = GetLoanLength(
2096 $borrower->{'categorycode'},
2097 (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
2098 $issuedata->{'branchcode'} ); # that's the circ control branch.
2100 $datedue = (C4::Context->preference('RenewalPeriodBase') eq 'date_due') ?
2101 C4::Dates->new($issuedata->{date_due}, 'iso') :
2103 $datedue = CalcDateDue($datedue,$loanlength,$issuedata->{'branchcode'},$borrower);
2106 # Update the issues record to have the new due date, and a new count
2107 # of how many times it has been renewed.
2108 my $renews = $issuedata->{'renewals'} + 1;
2109 $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?, lastreneweddate = ?
2110 WHERE borrowernumber=?
2113 $sth->execute( $datedue->output('iso'), $renews, $lastreneweddate, $borrowernumber, $itemnumber );
2116 # Update the renewal count on the item, and tell zebra to reindex
2117 $renews = $biblio->{'renewals'} + 1;
2118 ModItem({ renewals => $renews, onloan => $datedue->output('iso') }, $biblio->{'biblionumber'}, $itemnumber);
2120 # Charge a new rental fee, if applicable?
2121 my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2122 if ( $charge > 0 ) {
2123 my $accountno = getnextacctno( $borrowernumber );
2124 my $item = GetBiblioFromItemNumber($itemnumber);
2125 $sth = $dbh->prepare(
2126 "INSERT INTO accountlines
2128 borrowernumber, accountno, amount,
2130 accounttype, amountoutstanding, itemnumber
2132 VALUES (now(),?,?,?,?,?,?,?)"
2134 $sth->execute( $borrowernumber, $accountno, $charge,
2135 "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
2136 'Rent', $charge, $itemnumber );
2140 UpdateStats( $branch, 'renew', $charge, '', $itemnumber, $item->{itype}, $borrowernumber);
2145 # check renewal status
2146 my ($bornum,$itemno)=@_;
2147 my $dbh = C4::Context->dbh;
2149 my $renewsallowed = 0;
2151 # Look in the issues table for this item, lent to this borrower,
2152 # and not yet returned.
2154 # FIXME - I think this function could be redone to use only one SQL call.
2155 my $sth = $dbh->prepare("select * from issues
2156 where (borrowernumber = ?)
2157 and (itemnumber = ?)");
2158 $sth->execute($bornum,$itemno);
2159 my $data = $sth->fetchrow_hashref;
2160 $renewcount = $data->{'renewals'} if $data->{'renewals'};
2162 my $query = "SELECT renewalsallowed FROM items ";
2163 $query .= (C4::Context->preference('item-level_itypes'))
2164 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2165 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
2166 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2167 $query .= "WHERE items.itemnumber = ?";
2168 my $sth2 = $dbh->prepare($query);
2169 $sth2->execute($itemno);
2170 my $data2 = $sth2->fetchrow_hashref();
2171 $renewsallowed = $data2->{'renewalsallowed'};
2172 $renewsleft = $renewsallowed - $renewcount;
2173 return ($renewcount,$renewsallowed,$renewsleft);
2176 =head2 GetIssuingCharges
2178 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
2180 Calculate how much it would cost for a given patron to borrow a given
2181 item, including any applicable discounts.
2183 C<$itemnumber> is the item number of item the patron wishes to borrow.
2185 C<$borrowernumber> is the patron's borrower number.
2187 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
2188 and C<$item_type> is the code for the item's item type (e.g., C<VID>
2193 sub GetIssuingCharges {
2195 # calculate charges due
2196 my ( $itemnumber, $borrowernumber ) = @_;
2198 my $dbh = C4::Context->dbh;
2201 # Get the book's item type and rental charge (via its biblioitem).
2202 my $qcharge = "SELECT itemtypes.itemtype,rentalcharge FROM items
2203 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
2204 $qcharge .= (C4::Context->preference('item-level_itypes'))
2205 ? " LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2206 : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2208 $qcharge .= "WHERE items.itemnumber =?";
2210 my $sth1 = $dbh->prepare($qcharge);
2211 $sth1->execute($itemnumber);
2212 if ( my $data1 = $sth1->fetchrow_hashref ) {
2213 $item_type = $data1->{'itemtype'};
2214 $charge = $data1->{'rentalcharge'};
2215 my $q2 = "SELECT rentaldiscount FROM borrowers
2216 LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
2217 WHERE borrowers.borrowernumber = ?
2218 AND issuingrules.itemtype = ?";
2219 my $sth2 = $dbh->prepare($q2);
2220 $sth2->execute( $borrowernumber, $item_type );
2221 if ( my $data2 = $sth2->fetchrow_hashref ) {
2222 my $discount = $data2->{'rentaldiscount'};
2223 if ( $discount eq 'NULL' ) {
2226 $charge = ( $charge * ( 100 - $discount ) ) / 100;
2232 return ( $charge, $item_type );
2235 =head2 AddIssuingCharge
2237 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
2241 sub AddIssuingCharge {
2242 my ( $itemnumber, $borrowernumber, $charge ) = @_;
2243 my $dbh = C4::Context->dbh;
2244 my $nextaccntno = getnextacctno( $borrowernumber );
2246 INSERT INTO accountlines
2247 (borrowernumber, itemnumber, accountno,
2248 date, amount, description, accounttype,
2250 VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
2252 my $sth = $dbh->prepare($query);
2253 $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
2259 GetTransfers($itemnumber);
2264 my ($itemnumber) = @_;
2266 my $dbh = C4::Context->dbh;
2272 FROM branchtransfers
2273 WHERE itemnumber = ?
2274 AND datearrived IS NULL
2276 my $sth = $dbh->prepare($query);
2277 $sth->execute($itemnumber);
2278 my @row = $sth->fetchrow_array();
2284 =head2 GetTransfersFromTo
2286 @results = GetTransfersFromTo($frombranch,$tobranch);
2288 Returns the list of pending transfers between $from and $to branch
2292 sub GetTransfersFromTo {
2293 my ( $frombranch, $tobranch ) = @_;
2294 return unless ( $frombranch && $tobranch );
2295 my $dbh = C4::Context->dbh;
2297 SELECT itemnumber,datesent,frombranch
2298 FROM branchtransfers
2301 AND datearrived IS NULL
2303 my $sth = $dbh->prepare($query);
2304 $sth->execute( $frombranch, $tobranch );
2307 while ( my $data = $sth->fetchrow_hashref ) {
2308 push @gettransfers, $data;
2311 return (@gettransfers);
2314 =head2 DeleteTransfer
2316 &DeleteTransfer($itemnumber);
2320 sub DeleteTransfer {
2321 my ($itemnumber) = @_;
2322 my $dbh = C4::Context->dbh;
2323 my $sth = $dbh->prepare(
2324 "DELETE FROM branchtransfers
2326 AND datearrived IS NULL "
2328 $sth->execute($itemnumber);
2332 =head2 AnonymiseIssueHistory
2334 $rows = AnonymiseIssueHistory($borrowernumber,$date)
2336 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
2337 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
2339 return the number of affected rows.
2343 sub AnonymiseIssueHistory {
2345 my $borrowernumber = shift;
2346 my $dbh = C4::Context->dbh;
2349 SET borrowernumber = NULL
2350 WHERE returndate < '".$date."'
2351 AND borrowernumber IS NOT NULL
2353 $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
2354 my $rows_affected = $dbh->do($query);
2355 return $rows_affected;
2358 =head2 updateWrongTransfer
2360 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
2362 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
2366 sub updateWrongTransfer {
2367 my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
2368 my $dbh = C4::Context->dbh;
2369 # first step validate the actual line of transfert .
2372 "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
2374 $sth->execute($FromLibrary,$itemNumber);
2377 # second step create a new line of branchtransfer to the right location .
2378 ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
2380 #third step changing holdingbranch of item
2381 UpdateHoldingbranch($FromLibrary,$itemNumber);
2384 =head2 UpdateHoldingbranch
2386 $items = UpdateHoldingbranch($branch,$itmenumber);
2387 Simple methode for updating hodlingbranch in items BDD line
2391 sub UpdateHoldingbranch {
2392 my ( $branch,$itemnumber ) = @_;
2393 ModItem({ holdingbranch => $branch }, undef, $itemnumber);
2398 $newdatedue = CalcDateDue($startdate,$loanlength,$branchcode);
2399 this function calculates the due date given the loan length ,
2400 checking against the holidays calendar as per the 'useDaysMode' syspref.
2401 C<$startdate> = C4::Dates object representing start date of loan period (assumed to be today)
2402 C<$branch> = location whose calendar to use
2403 C<$loanlength> = loan length prior to adjustment
2407 my ($startdate,$loanlength,$branch,$borrower) = @_;
2410 my $calendar = C4::Calendar->new( branchcode => $branch );
2411 $datedue = $calendar->addDate($startdate, $loanlength);
2413 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
2414 if ( C4::Context->preference('ReturnBeforeExpiry') && $datedue->output('iso') gt $borrower->{dateexpiry} ) {
2415 $datedue = C4::Dates->new( $borrower->{dateexpiry}, 'iso' );
2418 # if ceilingDueDate ON the datedue can't be after the ceiling date
2419 if ( C4::Context->preference('ceilingDueDate')
2420 && ( C4::Context->preference('ceilingDueDate') =~ C4::Dates->regexp('syspref') )
2421 && $datedue->output gt C4::Context->preference('ceilingDueDate') ) {
2422 $datedue = C4::Dates->new( C4::Context->preference('ceilingDueDate') );
2428 =head2 CheckValidDatedue
2429 This function does not account for holiday exceptions nor does it handle the 'useDaysMode' syspref .
2430 To be replaced by CalcDateDue() once C4::Calendar use is tested.
2432 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
2433 this function validates the loan length against the holidays calendar, and adjusts the due date as per the 'useDaysMode' syspref.
2434 C<$date_due> = returndate calculate with no day check
2435 C<$itemnumber> = itemnumber
2436 C<$branchcode> = location of issue (affected by 'CircControl' syspref)
2437 C<$loanlength> = loan length prior to adjustment
2440 sub CheckValidDatedue {
2441 my ($date_due,$itemnumber,$branchcode)=@_;
2442 my @datedue=split('-',$date_due->output('iso'));
2443 my $years=$datedue[0];
2444 my $month=$datedue[1];
2445 my $day=$datedue[2];
2446 # die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
2448 for (my $i=0;$i<2;$i++){
2449 $dow=Day_of_Week($years,$month,$day);
2450 ($dow=0) if ($dow>6);
2451 my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
2452 my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2453 my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2454 if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
2456 (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
2459 my $newdatedue=C4::Dates->new(sprintf("%04d-%02d-%02d",$years,$month,$day),'iso');
2464 =head2 CheckRepeatableHolidays
2466 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
2467 this function checks if the date due is a repeatable holiday
2468 C<$date_due> = returndate calculate with no day check
2469 C<$itemnumber> = itemnumber
2470 C<$branchcode> = localisation of issue
2474 sub CheckRepeatableHolidays{
2475 my($itemnumber,$week_day,$branchcode)=@_;
2476 my $dbh = C4::Context->dbh;
2477 my $query = qq|SELECT count(*)
2478 FROM repeatable_holidays
2481 my $sth = $dbh->prepare($query);
2482 $sth->execute($branchcode,$week_day);
2483 my $result=$sth->fetchrow;
2489 =head2 CheckSpecialHolidays
2491 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2492 this function check if the date is a special holiday
2493 C<$years> = the years of datedue
2494 C<$month> = the month of datedue
2495 C<$day> = the day of datedue
2496 C<$itemnumber> = itemnumber
2497 C<$branchcode> = localisation of issue
2501 sub CheckSpecialHolidays{
2502 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
2503 my $dbh = C4::Context->dbh;
2504 my $query=qq|SELECT count(*)
2505 FROM `special_holidays`
2511 my $sth = $dbh->prepare($query);
2512 $sth->execute($years,$month,$day,$branchcode);
2513 my $countspecial=$sth->fetchrow ;
2515 return $countspecial;
2518 =head2 CheckRepeatableSpecialHolidays
2520 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2521 this function check if the date is a repeatble special holidays
2522 C<$month> = the month of datedue
2523 C<$day> = the day of datedue
2524 C<$itemnumber> = itemnumber
2525 C<$branchcode> = localisation of issue
2529 sub CheckRepeatableSpecialHolidays{
2530 my ($month,$day,$itemnumber,$branchcode) = @_;
2531 my $dbh = C4::Context->dbh;
2532 my $query=qq|SELECT count(*)
2533 FROM `repeatable_holidays`
2538 my $sth = $dbh->prepare($query);
2539 $sth->execute($month,$day,$branchcode);
2540 my $countspecial=$sth->fetchrow ;
2542 return $countspecial;
2547 sub CheckValidBarcode{
2549 my $dbh = C4::Context->dbh;
2550 my $query=qq|SELECT count(*)
2554 my $sth = $dbh->prepare($query);
2555 $sth->execute($barcode);
2556 my $exist=$sth->fetchrow ;
2567 Koha Developement team <info@koha.org>