1 package C4::Circulation;
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
22 #use warnings; # soon!
42 use POSIX qw(strftime);
43 use C4::Branch; # GetBranches
44 use C4::Log; # logaction
48 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
52 $VERSION = 3.02; # for version checking
55 # FIXME subs that should probably be elsewhere
61 # subs to deal with issuing a book
73 &GetBranchBorrowerCircRule
75 &AnonymiseIssueHistory
78 # subs to deal with returns
84 # subs to deal with transfers
96 C4::Circulation - Koha circulation module
104 The functions in this module deal with circulation, issues, and
105 returns, as well as general information about the library.
106 Also deals with stocktaking.
112 =head3 $str = &barcodedecode($barcode, [$filter]);
116 =item Generic filter function for barcode string.
117 Called on every circ if the System Pref itemBarcodeInputFilter is set.
118 Will do some manipulation of the barcode for systems that deliver a barcode
119 to circulation.pl that differs from the barcode stored for the item.
120 For proper functioning of this filter, calling the function on the
121 correct barcode string (items.barcode) should return an unaltered barcode.
123 The optional $filter argument is to allow for testing or explicit
124 behavior that ignores the System Pref. Valid values are the same as the
131 # FIXME -- the &decode fcn below should be wrapped into this one.
132 # FIXME -- these plugins should be moved out of Circulation.pm
135 my ($barcode, $filter) = @_;
136 $filter = C4::Context->preference('itemBarcodeInputFilter') unless $filter;
137 $filter or return $barcode; # ensure filter is defined, else return untouched barcode
138 if ($filter eq 'whitespace') {
140 } elsif ($filter eq 'cuecat') {
142 my @fields = split( /\./, $barcode );
143 my @results = map( decode($_), @fields[ 1 .. $#fields ] );
144 ($#results == 2) and return $results[2];
145 } elsif ($filter eq 'T-prefix') {
146 if ($barcode =~ /^[Tt](\d)/) {
147 (defined($1) and $1 eq '0') and return $barcode;
148 $barcode = substr($barcode, 2) + 0; # FIXME: probably should be substr($barcode, 1)
150 return sprintf("T%07d", $barcode);
151 # FIXME: $barcode could be "T1", causing warning: substr outside of string
152 # Why drop the nonzero digit after the T?
153 # Why pass non-digits (or empty string) to "T%07d"?
155 return $barcode; # return barcode, modified or not
160 =head3 $str = &decode($chunk);
164 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
167 FIXME: Should be replaced with Barcode::Cuecat from CPAN
168 or Javascript based decoding on the client side.
177 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
178 my @s = map { index( $seq, $_ ); } split( //, $encoded );
179 my $l = ( $#s + 1 ) % 4;
182 # warn "Error: Cuecat decode parsing failed!";
190 my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
192 chr( ( $n >> 16 ) ^ 67 )
193 .chr( ( $n >> 8 & 255 ) ^ 67 )
194 .chr( ( $n & 255 ) ^ 67 );
197 $r = substr( $r, 0, length($r) - $l );
203 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
205 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
207 C<$newbranch> is the code for the branch to which the item should be transferred.
209 C<$barcode> is the barcode of the item to be transferred.
211 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
212 Otherwise, if an item is reserved, the transfer fails.
214 Returns three values:
218 is true if the transfer was successful.
222 is a reference-to-hash which may have any of the following keys:
228 There is no item in the catalog with the given barcode. The value is C<$barcode>.
232 The item's home branch is permanent. This doesn't prevent the item from being transferred, though. The value is the code of the item's home branch.
234 =item C<DestinationEqualsHolding>
236 The item is already at the branch to which it is being transferred. The transfer is nonetheless considered to have failed. The value should be ignored.
240 The item was on loan, and C<&transferbook> automatically returned it before transferring it. The value is the borrower number of the patron who had the item.
244 The item was reserved. The value is a reference-to-hash whose keys are fields from the reserves table of the Koha database, and C<biblioitemnumber>. It also has the key C<ResFound>, whose value is either C<Waiting> or C<Reserved>.
246 =item C<WasTransferred>
248 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
255 my ( $tbr, $barcode, $ignoreRs ) = @_;
258 my $branches = GetBranches();
259 my $itemnumber = GetItemnumberFromBarcode( $barcode );
260 my $issue = GetItemIssue($itemnumber);
261 my $biblio = GetBiblioFromItemNumber($itemnumber);
264 if ( not $itemnumber ) {
265 $messages->{'BadBarcode'} = $barcode;
269 # get branches of book...
270 my $hbr = $biblio->{'homebranch'};
271 my $fbr = $biblio->{'holdingbranch'};
274 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
275 $messages->{'IsPermanent'} = $hbr;
278 # can't transfer book if is already there....
279 if ( $fbr eq $tbr ) {
280 $messages->{'DestinationEqualsHolding'} = 1;
284 # check if it is still issued to someone, return it...
285 if ($issue->{borrowernumber}) {
286 AddReturn( $barcode, $fbr );
287 $messages->{'WasReturned'} = $issue->{borrowernumber};
291 # That'll save a database query.
292 my ( $resfound, $resrec ) =
293 CheckReserves( $itemnumber );
294 if ( $resfound and not $ignoreRs ) {
295 $resrec->{'ResFound'} = $resfound;
297 # $messages->{'ResFound'} = $resrec;
301 #actually do the transfer....
303 ModItemTransfer( $itemnumber, $fbr, $tbr );
305 # don't need to update MARC anymore, we do it in batch now
306 $messages->{'WasTransfered'} = 1;
307 ModDateLastSeen( $itemnumber );
309 return ( $dotransfer, $messages, $biblio );
314 my $borrower = shift;
315 my $biblionumber = shift;
317 my $cat_borrower = $borrower->{'categorycode'};
318 my $dbh = C4::Context->dbh;
320 # Get which branchcode we need
321 if (C4::Context->preference('CircControl') eq 'PickupLibrary'){
322 $branch = C4::Context->userenv->{'branch'};
324 elsif (C4::Context->preference('CircControl') eq 'PatronLibrary'){
325 $branch = $borrower->{'branchcode'};
329 $branch = $item->{'homebranch'};
331 my $type = (C4::Context->preference('item-level_itypes'))
332 ? $item->{'itype'} # item-level
333 : $item->{'itemtype'}; # biblio-level
335 # given branch, patron category, and item type, determine
336 # applicable issuing rule
337 my $issuing_rule = GetIssuingRule($cat_borrower, $type, $branch);
339 # if a rule is found and has a loan limit set, count
340 # how many loans the patron already has that meet that
342 if (defined($issuing_rule) and defined($issuing_rule->{'maxissueqty'})) {
344 my $count_query = "SELECT COUNT(*) FROM issues
345 JOIN items USING (itemnumber) ";
347 my $rule_itemtype = $issuing_rule->{itemtype};
348 if ($rule_itemtype eq "*") {
349 # matching rule has the default item type, so count only
350 # those existing loans that don't fall under a more
352 if (C4::Context->preference('item-level_itypes')) {
353 $count_query .= " WHERE items.itype NOT IN (
354 SELECT itemtype FROM issuingrules
356 AND (categorycode = ? OR categorycode = ?)
360 $count_query .= " JOIN biblioitems USING (biblionumber)
361 WHERE biblioitems.itemtype NOT IN (
362 SELECT itemtype FROM issuingrules
364 AND (categorycode = ? OR categorycode = ?)
368 push @bind_params, $issuing_rule->{branchcode};
369 push @bind_params, $issuing_rule->{categorycode};
370 push @bind_params, $cat_borrower;
372 # rule has specific item type, so count loans of that
374 if (C4::Context->preference('item-level_itypes')) {
375 $count_query .= " WHERE items.itype = ? ";
377 $count_query .= " JOIN biblioitems USING (biblionumber)
378 WHERE biblioitems.itemtype= ? ";
380 push @bind_params, $type;
383 $count_query .= " AND borrowernumber = ? ";
384 push @bind_params, $borrower->{'borrowernumber'};
385 my $rule_branch = $issuing_rule->{branchcode};
386 if ($rule_branch ne "*") {
387 if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
388 $count_query .= " AND issues.branchcode = ? ";
389 push @bind_params, $branch;
390 } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
391 ; # if branch is the patron's home branch, then count all loans by patron
393 $count_query .= " AND items.homebranch = ? ";
394 push @bind_params, $branch;
398 my $count_sth = $dbh->prepare($count_query);
399 $count_sth->execute(@bind_params);
400 my ($current_loan_count) = $count_sth->fetchrow_array;
402 my $max_loans_allowed = $issuing_rule->{'maxissueqty'};
403 if ($current_loan_count >= $max_loans_allowed) {
404 return "$current_loan_count / $max_loans_allowed";
408 # Now count total loans against the limit for the branch
409 my $branch_borrower_circ_rule = GetBranchBorrowerCircRule($branch, $cat_borrower);
410 if (defined($branch_borrower_circ_rule->{maxissueqty})) {
411 my @bind_params = ();
412 my $branch_count_query = "SELECT COUNT(*) FROM issues
413 JOIN items USING (itemnumber)
414 WHERE borrowernumber = ? ";
415 push @bind_params, $borrower->{borrowernumber};
417 if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
418 $branch_count_query .= " AND issues.branchcode = ? ";
419 push @bind_params, $branch;
420 } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
421 ; # if branch is the patron's home branch, then count all loans by patron
423 $branch_count_query .= " AND items.homebranch = ? ";
424 push @bind_params, $branch;
426 my $branch_count_sth = $dbh->prepare($branch_count_query);
427 $branch_count_sth->execute(@bind_params);
428 my ($current_loan_count) = $branch_count_sth->fetchrow_array;
430 my $max_loans_allowed = $branch_borrower_circ_rule->{maxissueqty};
431 if ($current_loan_count >= $max_loans_allowed) {
432 return "$current_loan_count / $max_loans_allowed";
436 # OK, the patron can issue !!!
442 @issues = &itemissues($biblioitemnumber, $biblio);
444 Looks up information about who has borrowed the bookZ<>(s) with the
445 given biblioitemnumber.
447 C<$biblio> is ignored.
449 C<&itemissues> returns an array of references-to-hash. The keys
450 include the fields from the C<items> table in the Koha database.
451 Additional keys include:
457 If the item is currently on loan, this gives the due date.
459 If the item is not on loan, then this is either "Available" or
460 "Cancelled", if the item has been withdrawn.
464 If the item is currently on loan, this gives the card number of the
465 patron who currently has the item.
467 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
469 These give the timestamp for the last three times the item was
472 =item C<card0>, C<card1>, C<card2>
474 The card number of the last three patrons who borrowed this item.
476 =item C<borrower0>, C<borrower1>, C<borrower2>
478 The borrower number of the last three patrons who borrowed this item.
486 my ( $bibitem, $biblio ) = @_;
487 my $dbh = C4::Context->dbh;
489 $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
494 $sth->execute($bibitem) || die $sth->errstr;
496 while ( my $data = $sth->fetchrow_hashref ) {
498 # Find out who currently has this item.
499 # FIXME - Wouldn't it be better to do this as a left join of
500 # some sort? Currently, this code assumes that if
501 # fetchrow_hashref() fails, then the book is on the shelf.
502 # fetchrow_hashref() can fail for any number of reasons (e.g.,
503 # database server crash), not just because no items match the
505 my $sth2 = $dbh->prepare(
506 "SELECT * FROM issues
507 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
512 $sth2->execute( $data->{'itemnumber'} );
513 if ( my $data2 = $sth2->fetchrow_hashref ) {
514 $data->{'date_due'} = $data2->{'date_due'};
515 $data->{'card'} = $data2->{'cardnumber'};
516 $data->{'borrower'} = $data2->{'borrowernumber'};
519 $data->{'date_due'} = ($data->{'wthdrawn'} eq '1') ? 'Cancelled' : 'Available';
524 # Find the last 3 people who borrowed this item.
525 $sth2 = $dbh->prepare(
526 "SELECT * FROM old_issues
527 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
529 ORDER BY returndate DESC,timestamp DESC"
532 $sth2->execute( $data->{'itemnumber'} );
533 for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
534 { # FIXME : error if there is less than 3 pple borrowing this item
535 if ( my $data2 = $sth2->fetchrow_hashref ) {
536 $data->{"timestamp$i2"} = $data2->{'timestamp'};
537 $data->{"card$i2"} = $data2->{'cardnumber'};
538 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
543 $results[$i] = $data;
551 =head2 CanBookBeIssued
553 Check if a book can be issued.
555 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $borrower, $barcode, $duedatespec, $inprocess );
557 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
561 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
563 =item C<$barcode> is the bar code of the book being issued.
565 =item C<$duedatespec> is a C4::Dates object.
575 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
576 Possible values are :
582 sticky due date is invalid
586 borrower gone with no address
590 borrower declared it's card lost
596 =head3 UNKNOWN_BARCODE
610 item is restricted (set by ??)
612 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
613 Possible values are :
621 renewing, not issuing
623 =head3 ISSUED_TO_ANOTHER
625 issued to someone else.
629 reserved for someone else.
633 sticky due date is invalid
637 if the borrower borrows to much things
641 sub CanBookBeIssued {
642 my ( $borrower, $barcode, $duedate, $inprocess ) = @_;
643 my %needsconfirmation; # filled with problems that needs confirmations
644 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
645 my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
646 my $issue = GetItemIssue($item->{itemnumber});
647 my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
648 $item->{'itemtype'}=$item->{'itype'};
649 my $dbh = C4::Context->dbh;
651 # MANDATORY CHECKS - unless item exists, nothing else matters
652 unless ( $item->{barcode} ) {
653 $issuingimpossible{UNKNOWN_BARCODE} = 1;
655 return ( \%issuingimpossible, \%needsconfirmation ) if %issuingimpossible;
658 # DUE DATE is OK ? -- should already have checked.
660 unless ( $duedate ) {
661 my $issuedate = strftime( "%Y-%m-%d", localtime );
662 my $branch = (C4::Context->preference('CircControl') eq 'PickupLibrary') ? C4::Context->userenv->{'branch'} :
663 (C4::Context->preference('CircControl') eq 'PatronLibrary') ? $borrower->{'branchcode'} :
664 $item->{'homebranch'}; # fallback to item's homebranch
665 my $itype = ( C4::Context->preference('item-level_itypes') ) ? $item->{'itype'} : $biblioitem->{'itemtype'};
666 my $loanlength = GetLoanLength( $borrower->{'categorycode'}, $itype, $branch );
667 $duedate = CalcDateDue( C4::Dates->new( $issuedate, 'iso' ), $loanlength, $branch, $borrower );
669 # Offline circ calls AddIssue directly, doesn't run through here
670 # So issuingimpossible should be ok.
672 $issuingimpossible{INVALID_DATE} = $duedate->output('syspref') unless ( $duedate && $duedate->output('iso') ge C4::Dates->today('iso') );
677 if ( $borrower->{'category_type'} eq 'X' && ( $item->{barcode} )) {
678 # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1 .
679 &UpdateStats(C4::Context->userenv->{'branch'},'localuse','','',$item->{'itemnumber'},$item->{'itemtype'},$borrower->{'borrowernumber'});
680 return( { STATS => 1 }, {});
682 if ( $borrower->{flags}->{GNA} ) {
683 $issuingimpossible{GNA} = 1;
685 if ( $borrower->{flags}->{'LOST'} ) {
686 $issuingimpossible{CARD_LOST} = 1;
688 if ( $borrower->{flags}->{'DBARRED'} ) {
689 $issuingimpossible{DEBARRED} = 1;
691 if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
692 $issuingimpossible{EXPIRED} = 1;
694 my @expirydate= split /-/,$borrower->{'dateexpiry'};
695 if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
696 Date_to_Days(Today) > Date_to_Days( @expirydate )) {
697 $issuingimpossible{EXPIRED} = 1;
706 C4::Members::GetMemberAccountRecords( $borrower->{'borrowernumber'}, '' && $duedate->output('iso') );
707 if ( C4::Context->preference("IssuingInProcess") ) {
708 my $amountlimit = C4::Context->preference("noissuescharge");
709 if ( $amount > $amountlimit && !$inprocess ) {
710 $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
712 elsif ( $amount > 0 && $amount <= $amountlimit && !$inprocess ) {
713 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
718 $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
722 my ($blocktype, $count) = C4::Members::IsMemberBlocked($borrower->{'borrowernumber'});
723 if($blocktype == -1){
724 ## remaining overdue documents
725 $needsconfirmation{USERBLOCKEDREMAINING} = $count;
726 }elsif($blocktype == 1){
727 ## blocked because of overdue return
728 $issuingimpossible{USERBLOCKEDOVERDUE} = $count;
732 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
734 my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
735 # if TooMany return / 0, then the user has no permission to check out this book
736 if ($toomany =~ /\/ 0/) {
737 $needsconfirmation{PATRON_CANT} = 1;
739 $needsconfirmation{TOO_MANY} = $toomany if $toomany;
745 unless ( $item->{barcode} ) {
746 $issuingimpossible{UNKNOWN_BARCODE} = 1;
748 if ( $item->{'notforloan'}
749 && $item->{'notforloan'} > 0 )
751 if(C4::Context->preference("AllowNotForLoanOverride")){
752 $issuingimpossible{NOT_FOR_LOAN_CAN_FORCE} = 1;
754 $issuingimpossible{NOT_FOR_LOAN} = 1;
757 elsif ( !$item->{'notforloan'} ){
758 # we have to check itemtypes.notforloan also
759 if (C4::Context->preference('item-level_itypes')){
760 # this should probably be a subroutine
761 my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
762 $sth->execute($item->{'itemtype'});
763 my $notforloan=$sth->fetchrow_hashref();
765 if ($notforloan->{'notforloan'} == 1){
766 $issuingimpossible{NOT_FOR_LOAN} = 1;
769 elsif ($biblioitem->{'notforloan'} == 1){
770 $issuingimpossible{NOT_FOR_LOAN} = 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);
884 # $issuedate defaults to today.
885 if ( ! defined $issuedate ) {
886 $issuedate = strftime( "%Y-%m-%d", localtime );
887 # TODO: for hourly circ, this will need to be a C4::Dates object
888 # and all calls to AddIssue including issuedate will need to pass a Dates object.
890 if ($borrower and $barcode and $barcodecheck ne '0'){
891 # find which item we issue
892 my $item = GetItem('', $barcode) or return undef; # if we don't get an Item, abort.
893 my $branch = (C4::Context->preference('CircControl') eq 'PickupLibrary') ? C4::Context->userenv->{'branch'} :
894 (C4::Context->preference('CircControl') eq 'PatronLibrary') ? $borrower->{'branchcode'} :
895 $item->{'homebranch'}; # fallback to item's homebranch
897 # get actual issuing if there is one
898 my $actualissue = GetItemIssue( $item->{itemnumber});
900 # get biblioinformation for this item
901 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
904 # check if we just renew the issue.
906 if ($actualissue->{borrowernumber} eq $borrower->{'borrowernumber'}) {
907 $datedue = AddRenewal(
908 $borrower->{'borrowernumber'},
909 $item->{'itemnumber'},
912 $issuedate, # here interpreted as the renewal date
917 if ( $actualissue->{borrowernumber}) {
918 # This book is currently on loan, but not to the person
919 # who wants to borrow it now. mark it returned before issuing to the new borrower
922 C4::Context->userenv->{'branch'}
926 # See if the item is on reserve.
927 my ( $restype, $res ) =
928 C4::Reserves::CheckReserves( $item->{'itemnumber'} );
930 my $resbor = $res->{'borrowernumber'};
931 if ( $resbor eq $borrower->{'borrowernumber'} ) {
932 # The item is reserved by the current patron
933 ModReserveFill($res);
935 elsif ( $restype eq "Waiting" ) {
937 # The item is on reserve and waiting, but has been
938 # reserved by some other patron.
940 elsif ( $restype eq "Reserved" ) {
942 # The item is reserved by someone else.
943 if ($cancelreserve) { # cancel reserves on this item
944 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
947 if ($cancelreserve) {
948 CancelReserve($res->{'biblionumber'}, 0, $res->{'borrowernumber'});
951 # set waiting reserve to first in reserve queue as book isn't waiting now
953 $res->{'biblionumber'},
954 $res->{'borrowernumber'},
960 # Starting process for transfer job (checking transfert and validate it if we have one)
961 my ($datesent) = GetTransfers($item->{'itemnumber'});
963 # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for visibility of this case (maybe for stats ....)
966 "UPDATE branchtransfers
967 SET datearrived = now(),
969 comments = 'Forced branchtransfer'
970 WHERE itemnumber= ? AND datearrived IS NULL"
972 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
975 # Record in the database the fact that the book was issued.
979 (borrowernumber, itemnumber,issuedate, date_due, branchcode)
983 my $itype = ( C4::Context->preference('item-level_itypes') ) ? $biblio->{'itype'} : $biblio->{'itemtype'};
984 my $loanlength = GetLoanLength( $borrower->{'categorycode'}, $itype, $branch );
985 $datedue = CalcDateDue( C4::Dates->new( $issuedate, 'iso' ), $loanlength, $branch );
987 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
988 if ( C4::Context->preference('ReturnBeforeExpiry') && $datedue->output('iso') gt $borrower->{dateexpiry} ) {
989 $datedue = C4::Dates->new( $borrower->{dateexpiry}, 'iso' );
993 $borrower->{'borrowernumber'}, # borrowernumber
994 $item->{'itemnumber'}, # itemnumber
995 $issuedate, # issuedate
996 $datedue->output('iso'), # date_due
997 C4::Context->userenv->{'branch'} # branchcode
1000 $item->{'issues'}++;
1001 ModItem({ issues => $item->{'issues'},
1002 holdingbranch => C4::Context->userenv->{'branch'},
1004 datelastborrowed => C4::Dates->new()->output('iso'),
1005 onloan => $datedue->output('iso'),
1006 }, $item->{'biblionumber'}, $item->{'itemnumber'});
1007 ModDateLastSeen( $item->{'itemnumber'} );
1009 # If it costs to borrow this book, charge it to the patron's account.
1010 my ( $charge, $itemtype ) = GetIssuingCharges(
1011 $item->{'itemnumber'},
1012 $borrower->{'borrowernumber'}
1014 if ( $charge > 0 ) {
1016 $item->{'itemnumber'},
1017 $borrower->{'borrowernumber'}, $charge
1019 $item->{'charge'} = $charge;
1022 # Record the fact that this book was issued.
1024 C4::Context->userenv->{'branch'},
1026 ($sipmode ? "SIP-$sipmode" : ''), $item->{'itemnumber'},
1027 $item->{'itype'}, $borrower->{'borrowernumber'}
1031 logaction("CIRCULATION", "ISSUE", $borrower->{'borrowernumber'}, $biblio->{'biblionumber'})
1032 if C4::Context->preference("IssueLog");
1034 return ($datedue); # not necessarily the same as when it came in!
1037 =head2 GetLoanLength
1039 Get loan length for an itemtype, a borrower type and a branch
1041 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1046 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1047 my $dbh = C4::Context->dbh;
1050 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1052 # warn "in get loan lenght $borrowertype $itemtype $branchcode ";
1053 # try to find issuelength & return the 1st available.
1054 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1055 $sth->execute( $borrowertype, $itemtype, $branchcode );
1056 my $loanlength = $sth->fetchrow_hashref;
1057 return $loanlength->{issuelength}
1058 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1060 $sth->execute( $borrowertype, "*", $branchcode );
1061 $loanlength = $sth->fetchrow_hashref;
1062 return $loanlength->{issuelength}
1063 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1065 $sth->execute( "*", $itemtype, $branchcode );
1066 $loanlength = $sth->fetchrow_hashref;
1067 return $loanlength->{issuelength}
1068 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1070 $sth->execute( "*", "*", $branchcode );
1071 $loanlength = $sth->fetchrow_hashref;
1072 return $loanlength->{issuelength}
1073 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1075 $sth->execute( $borrowertype, $itemtype, "*" );
1076 $loanlength = $sth->fetchrow_hashref;
1077 return $loanlength->{issuelength}
1078 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1080 $sth->execute( $borrowertype, "*", "*" );
1081 $loanlength = $sth->fetchrow_hashref;
1082 return $loanlength->{issuelength}
1083 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1085 $sth->execute( "*", $itemtype, "*" );
1086 $loanlength = $sth->fetchrow_hashref;
1087 return $loanlength->{issuelength}
1088 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1090 $sth->execute( "*", "*", "*" );
1091 $loanlength = $sth->fetchrow_hashref;
1092 return $loanlength->{issuelength}
1093 if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1095 # if no rule is set => 21 days (hardcoded)
1099 =head2 GetIssuingRule
1101 FIXME - This is a copy-paste of GetLoanLength
1102 as a stop-gap. Do not wish to change API for GetLoanLength
1103 this close to release, however, Overdues::GetIssuingRules is broken.
1105 Get the issuing rule for an itemtype, a borrower type and a branch
1106 Returns a hashref from the issuingrules table.
1108 my $irule = &GetIssuingRule($borrowertype,$itemtype,branchcode)
1112 sub GetIssuingRule {
1113 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1114 my $dbh = C4::Context->dbh;
1115 my $sth = $dbh->prepare( "select * from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null" );
1118 $sth->execute( $borrowertype, $itemtype, $branchcode );
1119 $irule = $sth->fetchrow_hashref;
1120 return $irule if defined($irule) ;
1122 $sth->execute( $borrowertype, "*", $branchcode );
1123 $irule = $sth->fetchrow_hashref;
1124 return $irule if defined($irule) ;
1126 $sth->execute( "*", $itemtype, $branchcode );
1127 $irule = $sth->fetchrow_hashref;
1128 return $irule if defined($irule) ;
1130 $sth->execute( "*", "*", $branchcode );
1131 $irule = $sth->fetchrow_hashref;
1132 return $irule if defined($irule) ;
1134 $sth->execute( $borrowertype, $itemtype, "*" );
1135 $irule = $sth->fetchrow_hashref;
1136 return $irule if defined($irule) ;
1138 $sth->execute( $borrowertype, "*", "*" );
1139 $irule = $sth->fetchrow_hashref;
1140 return $irule if defined($irule) ;
1142 $sth->execute( "*", $itemtype, "*" );
1143 $irule = $sth->fetchrow_hashref;
1144 return $irule if defined($irule) ;
1146 $sth->execute( "*", "*", "*" );
1147 $irule = $sth->fetchrow_hashref;
1148 return $irule if defined($irule) ;
1150 # if no rule matches,
1154 =head2 GetBranchBorrowerCircRule
1158 my $branch_cat_rule = GetBranchBorrowerCircRule($branchcode, $categorycode);
1162 Retrieves circulation rule attributes that apply to the given
1163 branch and patron category, regardless of item type.
1164 The return value is a hashref containing the following key:
1166 maxissueqty - maximum number of loans that a
1167 patron of the given category can have at the given
1168 branch. If the value is undef, no limit.
1170 This will first check for a specific branch and
1171 category match from branch_borrower_circ_rules.
1173 If no rule is found, it will then check default_branch_circ_rules
1174 (same branch, default category). If no rule is found,
1175 it will then check default_borrower_circ_rules (default
1176 branch, same category), then failing that, default_circ_rules
1177 (default branch, default category).
1179 If no rule has been found in the database, it will default to
1184 C<$branchcode> and C<$categorycode> should contain the
1185 literal branch code and patron category code, respectively - no
1190 sub GetBranchBorrowerCircRule {
1191 my $branchcode = shift;
1192 my $categorycode = shift;
1194 my $branch_cat_query = "SELECT maxissueqty
1195 FROM branch_borrower_circ_rules
1196 WHERE branchcode = ?
1197 AND categorycode = ?";
1198 my $dbh = C4::Context->dbh();
1199 my $sth = $dbh->prepare($branch_cat_query);
1200 $sth->execute($branchcode, $categorycode);
1202 if ($result = $sth->fetchrow_hashref()) {
1206 # try same branch, default borrower category
1207 my $branch_query = "SELECT maxissueqty
1208 FROM default_branch_circ_rules
1209 WHERE branchcode = ?";
1210 $sth = $dbh->prepare($branch_query);
1211 $sth->execute($branchcode);
1212 if ($result = $sth->fetchrow_hashref()) {
1216 # try default branch, same borrower category
1217 my $category_query = "SELECT maxissueqty
1218 FROM default_borrower_circ_rules
1219 WHERE categorycode = ?";
1220 $sth = $dbh->prepare($category_query);
1221 $sth->execute($categorycode);
1222 if ($result = $sth->fetchrow_hashref()) {
1226 # try default branch, default borrower category
1227 my $default_query = "SELECT maxissueqty
1228 FROM default_circ_rules";
1229 $sth = $dbh->prepare($default_query);
1231 if ($result = $sth->fetchrow_hashref()) {
1235 # built-in default circulation rule
1237 maxissueqty => undef,
1243 ($doreturn, $messages, $iteminformation, $borrower) =
1244 &AddReturn($barcode, $branch, $exemptfine, $dropbox);
1250 =item C<$barcode> is the bar code of the book being returned.
1252 =item C<$branch> is the code of the branch where the book is being returned.
1254 =item C<$exemptfine> indicates that overdue charges for the item will be
1257 =item C<$dropbox> indicates that the check-in date is assumed to be
1258 yesterday, or the last non-holiday as defined in C4::Calendar . If
1259 overdue charges are applied and C<$dropbox> is true, the last charge
1260 will be removed. This assumes that the fines accrual script has run
1265 C<&AddReturn> returns a list of four items:
1267 C<$doreturn> is true iff the return succeeded.
1269 C<$messages> is a reference-to-hash giving the reason for failure:
1275 No item with this barcode exists. The value is C<$barcode>.
1279 The book is not currently on loan. The value is C<$barcode>.
1281 =item C<IsPermanent>
1283 The book's home branch is a permanent collection. If you have borrowed
1284 this book, you are not allowed to return it. The value is the code for
1285 the book's home branch.
1289 This book has been withdrawn/cancelled. The value should be ignored.
1293 The item was reserved. The value is a reference-to-hash whose keys are
1294 fields from the reserves table of the Koha database, and
1295 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1296 either C<Waiting>, C<Reserved>, or 0.
1300 C<$borrower> is a reference-to-hash, giving information about the
1301 patron who last borrowed the book.
1306 my ( $barcode, $branch, $exemptfine, $dropbox ) = @_;
1307 my $dbh = C4::Context->dbh;
1311 my $validTransfert = 0;
1312 my $reserveDone = 0;
1314 # get information on item
1315 my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1316 my $biblio = GetBiblioItemData($iteminformation->{'biblioitemnumber'});
1317 # use Data::Dumper;warn Data::Dumper::Dumper($iteminformation);
1318 unless ($iteminformation->{'itemnumber'} ) {
1319 $messages->{'BadBarcode'} = $barcode;
1323 if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1324 $messages->{'NotIssued'} = $barcode;
1325 # even though item is not on loan, it may still
1326 # be transferred; therefore, get current branch information
1327 my $curr_iteminfo = GetItem($iteminformation->{'itemnumber'});
1328 $iteminformation->{'homebranch'} = $curr_iteminfo->{'homebranch'};
1329 $iteminformation->{'holdingbranch'} = $curr_iteminfo->{'holdingbranch'};
1330 $iteminformation->{'itemlost'} = $curr_iteminfo->{'itemlost'};
1334 # check if the book is in a permanent collection....
1335 my $hbr = $iteminformation->{C4::Context->preference("HomeOrHoldingBranch")};
1336 my $branches = GetBranches();
1337 # FIXME -- This 'PE' attribute is largely undocumented. afaict, there's no user interface that reflects this functionality.
1338 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1339 $messages->{'IsPermanent'} = $hbr;
1342 # if independent branches are on and returning to different branch, refuse the return
1343 if ($hbr ne C4::Context->userenv->{'branch'} && C4::Context->preference("IndependantBranches")){
1344 $messages->{'Wrongbranch'} = 1;
1348 # check that the book has been cancelled
1349 if ( $iteminformation->{'wthdrawn'} ) {
1350 $messages->{'wthdrawn'} = 1;
1354 # new op dev : if the book returned in an other branch update the holding branch
1356 # update issues, thereby returning book (should push this out into another subroutine
1357 $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1359 # case of a return of document (deal with issues and holdingbranch)
1362 my $circControlBranch;
1364 # don't allow dropbox mode to create an invalid entry in issues (issuedate > returndate) FIXME: actually checks eq, not gt
1365 undef($dropbox) if ( $iteminformation->{'issuedate'} eq C4::Dates->today('iso') );
1366 if (C4::Context->preference('CircControl') eq 'ItemHomeBranch' ) {
1367 $circControlBranch = $iteminformation->{homebranch};
1368 } elsif ( C4::Context->preference('CircControl') eq 'PatronLibrary') {
1369 $circControlBranch = $borrower->{branchcode};
1370 } else { # CircControl must be PickupLibrary.
1371 $circControlBranch = $iteminformation->{holdingbranch};
1372 # FIXME - is this right ? are we sure that the holdingbranch is still the pickup branch?
1375 MarkIssueReturned($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'},$circControlBranch);
1376 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
1377 # continue to deal with returns cases, but not only if we have an issue
1379 # the holdingbranch is updated if the document is returned in an other location .
1380 if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} ) {
1381 UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});
1382 # reload iteminformation holdingbranch with the userenv value
1383 $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1385 ModDateLastSeen( $iteminformation->{'itemnumber'} );
1386 ModItem({ onloan => undef }, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'});
1388 if ($iteminformation->{borrowernumber}){
1389 ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1392 # fix up the accounts.....
1393 if ( $iteminformation->{'itemlost'} ) {
1394 $messages->{'WasLost'} = 1;
1397 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1398 # check if we have a transfer for this document
1399 my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1401 # if we have a transfer to do, we update the line of transfers with the datearrived
1403 if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1406 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1408 $sth->execute( $iteminformation->{'itemnumber'} );
1410 # 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'
1411 C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1414 $messages->{'WrongTransfer'} = $tobranch;
1415 $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1417 $validTransfert = 1;
1420 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1421 # fix up the accounts.....
1422 if ($iteminformation->{'itemlost'}) {
1423 FixAccountForLostAndReturned($iteminformation, $borrower);
1424 $messages->{'WasLost'} = 1;
1426 # fix up the overdues in accounts...
1427 FixOverduesOnReturn( $borrower->{'borrowernumber'},
1428 $iteminformation->{'itemnumber'}, $exemptfine, $dropbox );
1430 # find reserves.....
1431 # if we don't have a reserve with the status W, we launch the Checkreserves routine
1432 my ( $resfound, $resrec ) =
1433 C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1435 $resrec->{'ResFound'} = $resfound;
1436 $messages->{'ResFound'} = $resrec;
1441 # Record the fact that this book was returned.
1443 $branch, 'return', '0', '',
1444 $iteminformation->{'itemnumber'},
1445 $biblio->{'itemtype'},
1446 $borrower->{'borrowernumber'}
1449 logaction("CIRCULATION", "RETURN", $iteminformation->{borrowernumber}, $iteminformation->{'biblionumber'})
1450 if C4::Context->preference("ReturnLog");
1452 #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1453 #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1455 if ($doreturn and ($branch ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1456 if (C4::Context->preference("AutomaticItemReturn") == 1) {
1457 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1458 $messages->{'WasTransfered'} = 1;
1461 $messages->{'NeedsTransfer'} = 1;
1465 return ( $doreturn, $messages, $iteminformation, $borrower );
1468 =head2 MarkIssueReturned
1472 MarkIssueReturned($borrowernumber, $itemnumber, $dropbox_branch, $returndate);
1476 Unconditionally marks an issue as being returned by
1477 moving the C<issues> row to C<old_issues> and
1478 setting C<returndate> to the current date, or
1479 the last non-holiday date of the branccode specified in
1480 C<dropbox_branch> . Assumes you've already checked that
1481 it's safe to do this, i.e. last non-holiday > issuedate.
1483 if C<$returndate> is specified (in iso format), it is used as the date
1484 of the return. It is ignored when a dropbox_branch is passed in.
1486 Ideally, this function would be internal to C<C4::Circulation>,
1487 not exported, but it is currently needed by one
1488 routine in C<C4::Accounts>.
1492 sub MarkIssueReturned {
1493 my ( $borrowernumber, $itemnumber, $dropbox_branch, $returndate ) = @_;
1494 my $dbh = C4::Context->dbh;
1495 my $query = "UPDATE issues SET returndate=";
1497 if ($dropbox_branch) {
1498 my $calendar = C4::Calendar->new( branchcode => $dropbox_branch );
1499 my $dropboxdate = $calendar->addDate( C4::Dates->new(), -1 );
1501 push @bind, $dropboxdate->output('iso');
1502 } elsif ($returndate) {
1504 push @bind, $returndate;
1506 $query .= " now() ";
1508 $query .= " WHERE borrowernumber = ? AND itemnumber = ?";
1509 push @bind, $borrowernumber, $itemnumber;
1511 my $sth_upd = $dbh->prepare($query);
1512 $sth_upd->execute(@bind);
1513 my $sth_copy = $dbh->prepare("INSERT INTO old_issues SELECT * FROM issues
1514 WHERE borrowernumber = ?
1515 AND itemnumber = ?");
1516 $sth_copy->execute($borrowernumber, $itemnumber);
1517 my $sth_del = $dbh->prepare("DELETE FROM issues
1518 WHERE borrowernumber = ?
1519 AND itemnumber = ?");
1520 $sth_del->execute($borrowernumber, $itemnumber);
1523 =head2 FixOverduesOnReturn
1525 &FixOverduesOnReturn($brn,$itm, $exemptfine, $dropboxmode);
1527 C<$brn> borrowernumber
1531 C<$exemptfine> BOOL -- remove overdue charge associated with this issue.
1532 C<$dropboxmode> BOOL -- remove lastincrement on overdue charge associated with this issue.
1534 internal function, called only by AddReturn
1538 sub FixOverduesOnReturn {
1539 my ( $borrowernumber, $item, $exemptfine, $dropbox ) = @_;
1540 my $dbh = C4::Context->dbh;
1542 # check for overdue fine
1545 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1547 $sth->execute( $borrowernumber, $item );
1549 # alter fine to show that the book has been returned
1551 if ($data = $sth->fetchrow_hashref) {
1553 my @bind = ($borrowernumber,$item ,$data->{'accountno'});
1555 $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
1556 if (C4::Context->preference("FinesLog")) {
1557 &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
1559 } elsif ($dropbox && $data->{lastincrement}) {
1560 my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
1561 my $amt = $data->{amount} - $data->{lastincrement} ;
1562 if (C4::Context->preference("FinesLog")) {
1563 &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
1565 $uquery = "update accountlines set accounttype='F' ";
1566 if($outstanding >= 0 && $amt >=0) {
1567 $uquery .= ", amount = ? , amountoutstanding=? ";
1568 unshift @bind, ($amt, $outstanding) ;
1571 $uquery = "update accountlines set accounttype='F' ";
1573 $uquery .= " where (borrowernumber = ?) and (itemnumber = ?) and (accountno = ?)";
1574 my $usth = $dbh->prepare($uquery);
1575 $usth->execute(@bind);
1583 =head2 FixAccountForLostAndReturned
1585 &FixAccountForLostAndReturned($iteminfo,$borrower);
1587 Calculates the charge for a book lost and returned (Not exported & used only once)
1589 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1591 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1593 Internal function, called by AddReturn
1597 sub FixAccountForLostAndReturned {
1598 my ($iteminfo, $borrower) = @_;
1599 my $dbh = C4::Context->dbh;
1600 my $itm = $iteminfo->{'itemnumber'};
1601 # check for charge made for lost book
1602 my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1603 $sth->execute($itm);
1604 if (my $data = $sth->fetchrow_hashref) {
1605 # writeoff this amount
1607 my $amount = $data->{'amount'};
1608 my $acctno = $data->{'accountno'};
1610 if ($data->{'amountoutstanding'} == $amount) {
1611 $offset = $data->{'amount'};
1614 $offset = $amount - $data->{'amountoutstanding'};
1615 $amountleft = $data->{'amountoutstanding'} - $amount;
1617 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1618 WHERE (borrowernumber = ?)
1619 AND (itemnumber = ?) AND (accountno = ?) ");
1620 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1621 #check if any credit is left if so writeoff other accounts
1622 my $nextaccntno = getnextacctno($data->{'borrowernumber'});
1623 if ($amountleft < 0){
1626 if ($amountleft > 0){
1627 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1628 AND (amountoutstanding >0) ORDER BY date");
1629 $msth->execute($data->{'borrowernumber'});
1630 # offset transactions
1633 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1634 if ($accdata->{'amountoutstanding'} < $amountleft) {
1636 $amountleft -= $accdata->{'amountoutstanding'};
1638 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1641 my $thisacct = $accdata->{'accountno'};
1642 my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1643 WHERE (borrowernumber = ?)
1644 AND (accountno=?)");
1645 $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1647 $usth = $dbh->prepare("INSERT INTO accountoffsets
1648 (borrowernumber, accountno, offsetaccount, offsetamount)
1651 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1653 $msth->finish; # $msth might actually have data left
1655 if ($amountleft > 0){
1658 my $desc="Item Returned ".$iteminfo->{'barcode'};
1659 $usth = $dbh->prepare("INSERT INTO accountlines
1660 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1661 VALUES (?,?,now(),?,?,'CR',?)");
1662 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1663 $usth = $dbh->prepare("INSERT INTO accountoffsets
1664 (borrowernumber, accountno, offsetaccount, offsetamount)
1666 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1667 ModItem({ paidfor => '' }, undef, $itm);
1675 $issues = &GetItemIssue($itemnumber);
1677 Returns patron currently having a book, or undef if not checked out.
1679 C<$itemnumber> is the itemnumber
1681 C<$issues> is an array of hashes.
1686 my ($itemnumber) = @_;
1687 return unless $itemnumber;
1688 my $sth = C4::Context->dbh->prepare(
1691 LEFT JOIN items ON issues.itemnumber=items.itemnumber
1692 WHERE issues.itemnumber=?");
1693 $sth->execute($itemnumber);
1694 my $data = $sth->fetchrow_hashref;
1695 return unless $data;
1696 $data->{'overdue'} = ($data->{'date_due'} lt C4::Dates->today('iso')) ? 1 : 0;
1697 $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue.
1698 # FIXME: that would mean issues.itemnumber IS NULL and we didn't really match it.
1702 =head2 GetItemIssues
1704 $issues = &GetItemIssues($itemnumber, $history);
1706 Returns patrons that have issued a book
1708 C<$itemnumber> is the itemnumber
1709 C<$history> is false if you just want the current "issuer" (if any)
1710 and true if you want issues history from old_issues also.
1712 Returns reference to an array of hashes
1717 my ( $itemnumber, $history ) = @_;
1719 my $today = C4::Dates->today('iso'); # get today date
1720 my $sql = "SELECT * FROM issues
1721 JOIN borrowers USING (borrowernumber)
1722 JOIN items USING (itemnumber)
1723 WHERE issues.itemnumber = ? ";
1726 SELECT * FROM old_issues
1727 LEFT JOIN borrowers USING (borrowernumber)
1728 JOIN items USING (itemnumber)
1729 WHERE old_issues.itemnumber = ? ";
1731 $sql .= "ORDER BY date_due DESC";
1732 my $sth = C4::Context->dbh->prepare($sql);
1734 $sth->execute($itemnumber, $itemnumber);
1736 $sth->execute($itemnumber);
1738 my $results = $sth->fetchall_arrayref({});
1739 foreach (@$results) {
1740 $_->{'overdue'} = ($_->{'date_due'} lt $today) ? 1 : 0;
1745 =head2 GetBiblioIssues
1747 $issues = GetBiblioIssues($biblionumber);
1749 this function get all issues from a biblionumber.
1752 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1753 tables issues and the firstname,surname & cardnumber from borrowers.
1757 sub GetBiblioIssues {
1758 my $biblionumber = shift;
1759 return undef unless $biblionumber;
1760 my $dbh = C4::Context->dbh;
1762 SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1764 LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1765 LEFT JOIN items ON issues.itemnumber = items.itemnumber
1766 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1767 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1768 WHERE biblio.biblionumber = ?
1770 SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1772 LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
1773 LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
1774 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1775 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1776 WHERE biblio.biblionumber = ?
1779 my $sth = $dbh->prepare($query);
1780 $sth->execute($biblionumber, $biblionumber);
1783 while ( my $data = $sth->fetchrow_hashref ) {
1784 push @issues, $data;
1789 =head2 GetUpcomingDueIssues
1793 my $upcoming_dues = GetUpcomingDueIssues( { days_in_advance => 4 } );
1799 sub GetUpcomingDueIssues {
1802 $params->{'days_in_advance'} = 7 unless exists $params->{'days_in_advance'};
1803 my $dbh = C4::Context->dbh;
1805 my $statement = <<END_SQL;
1806 SELECT issues.*, items.itype as itemtype, items.homebranch, TO_DAYS( date_due )-TO_DAYS( NOW() ) as days_until_due
1808 LEFT JOIN items USING (itemnumber)
1809 WhERE returndate is NULL
1810 AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ?
1813 my @bind_parameters = ( $params->{'days_in_advance'} );
1815 my $sth = $dbh->prepare( $statement );
1816 $sth->execute( @bind_parameters );
1817 my $upcoming_dues = $sth->fetchall_arrayref({});
1820 return $upcoming_dues;
1823 =head2 CanBookBeRenewed
1825 ($ok,$error) = &CanBookBeRenewed($borrowernumber, $itemnumber[, $override_limit]);
1827 Find out whether a borrowed item may be renewed.
1829 C<$dbh> is a DBI handle to the Koha database.
1831 C<$borrowernumber> is the borrower number of the patron who currently
1832 has the item on loan.
1834 C<$itemnumber> is the number of the item to renew.
1836 C<$override_limit>, if supplied with a true value, causes
1837 the limit on the number of times that the loan can be renewed
1838 (as controlled by the item type) to be ignored.
1840 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1841 item must currently be on loan to the specified borrower; renewals
1842 must be allowed for the item's type; and the borrower must not have
1843 already renewed the loan. $error will contain the reason the renewal can not proceed
1847 sub CanBookBeRenewed {
1849 # check renewal status
1850 my ( $borrowernumber, $itemnumber, $override_limit ) = @_;
1851 my $dbh = C4::Context->dbh;
1856 # Look in the issues table for this item, lent to this borrower,
1857 # and not yet returned.
1859 # FIXME - I think this function could be redone to use only one SQL call.
1860 my $sth1 = $dbh->prepare(
1861 "SELECT * FROM issues
1862 WHERE borrowernumber = ?
1865 $sth1->execute( $borrowernumber, $itemnumber );
1866 if ( my $data1 = $sth1->fetchrow_hashref ) {
1868 # Found a matching item
1870 # See if this item may be renewed. This query is convoluted
1871 # because it's a bit messy: given the item number, we need to find
1872 # the biblioitem, which gives us the itemtype, which tells us
1873 # whether it may be renewed.
1874 my $query = "SELECT renewalsallowed FROM items ";
1875 $query .= (C4::Context->preference('item-level_itypes'))
1876 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1877 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1878 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1879 $query .= "WHERE items.itemnumber = ?";
1880 my $sth2 = $dbh->prepare($query);
1881 $sth2->execute($itemnumber);
1882 if ( my $data2 = $sth2->fetchrow_hashref ) {
1883 $renews = $data2->{'renewalsallowed'};
1885 if ( ( $renews && $renews > $data1->{'renewals'} ) || $override_limit ) {
1892 my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1900 return ($renewokay,$error);
1905 &AddRenewal($borrowernumber, $itemnumber, $branch, [$datedue], [$lastreneweddate]);
1909 C<$borrowernumber> is the borrower number of the patron who currently
1912 C<$itemnumber> is the number of the item to renew.
1914 C<$branch> is the library branch. Defaults to the homebranch of the ITEM.
1916 C<$datedue> can be a C4::Dates object used to set the due date.
1918 C<$lastreneweddate> is an optional ISO-formatted date used to set issues.lastreneweddate. If
1919 this parameter is not supplied, lastreneweddate is set to the current date.
1921 If C<$datedue> is the empty string, C<&AddRenewal> will calculate the due date automatically
1922 from the book's item type.
1927 my $borrowernumber = shift or return undef;
1928 my $itemnumber = shift or return undef;
1929 my $item = GetItem($itemnumber) or return undef;
1930 my $biblio = GetBiblioFromItemNumber($itemnumber) or return undef;
1931 my $branch = (@_) ? shift : $item->{homebranch}; # opac-renew doesn't send branch
1932 my $datedue = shift;
1933 my $lastreneweddate = shift;
1935 # If the due date wasn't specified, calculate it by adding the
1936 # book's loan length to today's date.
1937 unless ($datedue && $datedue->output('iso')) {
1939 my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 ) or return undef;
1940 my $loanlength = GetLoanLength(
1941 $borrower->{'categorycode'},
1942 (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1943 $item->{homebranch} # item's homebranch determines loanlength OR do we want the branch specified by the AddRenewal argument?
1945 #FIXME -- use circControl?
1946 $datedue = CalcDateDue(C4::Dates->new(),$loanlength,$branch); # this branch is the transactional branch.
1947 # The question of whether to use item's homebranch calendar is open.
1950 # $lastreneweddate defaults to today.
1951 unless (defined $lastreneweddate) {
1952 $lastreneweddate = strftime( "%Y-%m-%d", localtime );
1955 my $dbh = C4::Context->dbh;
1956 # Find the issues record for this book
1958 $dbh->prepare("SELECT * FROM issues
1959 WHERE borrowernumber=?
1962 $sth->execute( $borrowernumber, $itemnumber );
1963 my $issuedata = $sth->fetchrow_hashref;
1966 # If the due date wasn't specified, calculate it by adding the
1967 # book's loan length to today's date or the current due date
1968 # based on the value of the RenewalPeriodBase syspref.
1969 unless ($datedue && $datedue->output('iso')) {
1971 my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 ) or return undef;
1972 my $loanlength = GetLoanLength(
1973 $borrower->{'categorycode'},
1974 (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1975 $item->{homebranch} # item's homebranch determines loanlength OR do we want the branch specified by the AddRenewal argument?
1978 $datedue = (C4::Context->preference('RenewalPeriodBase') eq 'date_due') ?
1979 C4::Dates->new($issuedata->{date_due}, 'iso') :
1981 #FIXME -- use circControl?
1982 $datedue = CalcDateDue($datedue,$loanlength,$branch,$borrower); # this branch is the transactional branch.
1983 # The question of whether to use item's homebranch calendar is open.
1986 # Update the issues record to have the new due date, and a new count
1987 # of how many times it has been renewed.
1988 my $renews = $issuedata->{'renewals'} + 1;
1989 $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?, lastreneweddate = ?
1990 WHERE borrowernumber=?
1993 $sth->execute( $datedue->output('iso'), $renews, $lastreneweddate, $borrowernumber, $itemnumber );
1996 # Update the renewal count on the item, and tell zebra to reindex
1997 $renews = $biblio->{'renewals'} + 1;
1998 ModItem({ renewals => $renews, onloan => $datedue->output('iso') }, $biblio->{'biblionumber'}, $itemnumber);
2000 # Charge a new rental fee, if applicable?
2001 my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2002 if ( $charge > 0 ) {
2003 my $accountno = getnextacctno( $borrowernumber );
2004 my $item = GetBiblioFromItemNumber($itemnumber);
2005 $sth = $dbh->prepare(
2006 "INSERT INTO accountlines
2008 borrowernumber, accountno, amount,
2010 accounttype, amountoutstanding, itemnumber
2012 VALUES (now(),?,?,?,?,?,?,?)"
2014 $sth->execute( $borrowernumber, $accountno, $charge,
2015 "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
2016 'Rent', $charge, $itemnumber );
2020 UpdateStats( $branch, 'renew', $charge, '', $itemnumber, $item->{itype}, $borrowernumber);
2025 # check renewal status
2026 my ($bornum,$itemno)=@_;
2027 my $dbh = C4::Context->dbh;
2029 my $renewsallowed = 0;
2031 # Look in the issues table for this item, lent to this borrower,
2032 # and not yet returned.
2034 # FIXME - I think this function could be redone to use only one SQL call.
2035 my $sth = $dbh->prepare("select * from issues
2036 where (borrowernumber = ?)
2037 and (itemnumber = ?)");
2038 $sth->execute($bornum,$itemno);
2039 my $data = $sth->fetchrow_hashref;
2040 $renewcount = $data->{'renewals'} if $data->{'renewals'};
2042 my $query = "SELECT renewalsallowed FROM items ";
2043 $query .= (C4::Context->preference('item-level_itypes'))
2044 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2045 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
2046 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2047 $query .= "WHERE items.itemnumber = ?";
2048 my $sth2 = $dbh->prepare($query);
2049 $sth2->execute($itemno);
2050 my $data2 = $sth2->fetchrow_hashref();
2051 $renewsallowed = $data2->{'renewalsallowed'};
2052 $renewsleft = $renewsallowed - $renewcount;
2053 return ($renewcount,$renewsallowed,$renewsleft);
2056 =head2 GetIssuingCharges
2058 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
2060 Calculate how much it would cost for a given patron to borrow a given
2061 item, including any applicable discounts.
2063 C<$itemnumber> is the item number of item the patron wishes to borrow.
2065 C<$borrowernumber> is the patron's borrower number.
2067 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
2068 and C<$item_type> is the code for the item's item type (e.g., C<VID>
2073 sub GetIssuingCharges {
2075 # calculate charges due
2076 my ( $itemnumber, $borrowernumber ) = @_;
2078 my $dbh = C4::Context->dbh;
2081 # Get the book's item type and rental charge (via its biblioitem).
2082 my $qcharge = "SELECT itemtypes.itemtype,rentalcharge FROM items
2083 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
2084 $qcharge .= (C4::Context->preference('item-level_itypes'))
2085 ? " LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2086 : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2088 $qcharge .= "WHERE items.itemnumber =?";
2090 my $sth1 = $dbh->prepare($qcharge);
2091 $sth1->execute($itemnumber);
2092 if ( my $data1 = $sth1->fetchrow_hashref ) {
2093 $item_type = $data1->{'itemtype'};
2094 $charge = $data1->{'rentalcharge'};
2095 my $q2 = "SELECT rentaldiscount FROM borrowers
2096 LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
2097 WHERE borrowers.borrowernumber = ?
2098 AND issuingrules.itemtype = ?";
2099 my $sth2 = $dbh->prepare($q2);
2100 $sth2->execute( $borrowernumber, $item_type );
2101 if ( my $data2 = $sth2->fetchrow_hashref ) {
2102 my $discount = $data2->{'rentaldiscount'};
2103 if ( $discount eq 'NULL' ) {
2106 $charge = ( $charge * ( 100 - $discount ) ) / 100;
2112 return ( $charge, $item_type );
2115 =head2 AddIssuingCharge
2117 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
2121 sub AddIssuingCharge {
2122 my ( $itemnumber, $borrowernumber, $charge ) = @_;
2123 my $dbh = C4::Context->dbh;
2124 my $nextaccntno = getnextacctno( $borrowernumber );
2126 INSERT INTO accountlines
2127 (borrowernumber, itemnumber, accountno,
2128 date, amount, description, accounttype,
2130 VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
2132 my $sth = $dbh->prepare($query);
2133 $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
2139 GetTransfers($itemnumber);
2144 my ($itemnumber) = @_;
2146 my $dbh = C4::Context->dbh;
2152 FROM branchtransfers
2153 WHERE itemnumber = ?
2154 AND datearrived IS NULL
2156 my $sth = $dbh->prepare($query);
2157 $sth->execute($itemnumber);
2158 my @row = $sth->fetchrow_array();
2164 =head2 GetTransfersFromTo
2166 @results = GetTransfersFromTo($frombranch,$tobranch);
2168 Returns the list of pending transfers between $from and $to branch
2172 sub GetTransfersFromTo {
2173 my ( $frombranch, $tobranch ) = @_;
2174 return unless ( $frombranch && $tobranch );
2175 my $dbh = C4::Context->dbh;
2177 SELECT itemnumber,datesent,frombranch
2178 FROM branchtransfers
2181 AND datearrived IS NULL
2183 my $sth = $dbh->prepare($query);
2184 $sth->execute( $frombranch, $tobranch );
2187 while ( my $data = $sth->fetchrow_hashref ) {
2188 push @gettransfers, $data;
2191 return (@gettransfers);
2194 =head2 DeleteTransfer
2196 &DeleteTransfer($itemnumber);
2200 sub DeleteTransfer {
2201 my ($itemnumber) = @_;
2202 my $dbh = C4::Context->dbh;
2203 my $sth = $dbh->prepare(
2204 "DELETE FROM branchtransfers
2206 AND datearrived IS NULL "
2208 $sth->execute($itemnumber);
2212 =head2 AnonymiseIssueHistory
2214 $rows = AnonymiseIssueHistory($borrowernumber,$date)
2216 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
2217 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
2219 return the number of affected rows.
2223 sub AnonymiseIssueHistory {
2225 my $borrowernumber = shift;
2226 my $dbh = C4::Context->dbh;
2229 SET borrowernumber = NULL
2230 WHERE returndate < '".$date."'
2231 AND borrowernumber IS NOT NULL
2233 $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
2234 my $rows_affected = $dbh->do($query);
2235 return $rows_affected;
2238 =head2 updateWrongTransfer
2240 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
2242 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
2246 sub updateWrongTransfer {
2247 my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
2248 my $dbh = C4::Context->dbh;
2249 # first step validate the actual line of transfert .
2252 "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
2254 $sth->execute($FromLibrary,$itemNumber);
2257 # second step create a new line of branchtransfer to the right location .
2258 ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
2260 #third step changing holdingbranch of item
2261 UpdateHoldingbranch($FromLibrary,$itemNumber);
2264 =head2 UpdateHoldingbranch
2266 $items = UpdateHoldingbranch($branch,$itmenumber);
2267 Simple methode for updating hodlingbranch in items BDD line
2271 sub UpdateHoldingbranch {
2272 my ( $branch,$itemnumber ) = @_;
2273 ModItem({ holdingbranch => $branch }, undef, $itemnumber);
2278 $newdatedue = CalcDateDue($startdate,$loanlength,$branchcode);
2279 this function calculates the due date given the loan length ,
2280 checking against the holidays calendar as per the 'useDaysMode' syspref.
2281 C<$startdate> = C4::Dates object representing start date of loan period (assumed to be today)
2282 C<$branch> = location whose calendar to use
2283 C<$loanlength> = loan length prior to adjustment
2287 my ($startdate,$loanlength,$branch,$borrower) = @_;
2290 if(C4::Context->preference('useDaysMode') eq 'Days') { # ignoring calendar
2291 my $timedue = time + ($loanlength) * 86400;
2292 #FIXME - assumes now even though we take a startdate
2293 my @datearr = localtime($timedue);
2294 $datedue = C4::Dates->new( sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
2296 my $calendar = C4::Calendar->new( branchcode => $branch );
2297 $datedue = $calendar->addDate($startdate, $loanlength);
2300 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
2301 if ( C4::Context->preference('ReturnBeforeExpiry') && $datedue->output('iso') gt $borrower->{dateexpiry} ) {
2302 $datedue = C4::Dates->new( $borrower->{dateexpiry}, 'iso' );
2305 # if ceilingDueDate ON the datedue can't be after the ceiling date
2306 if ( C4::Context->preference('ceilingDueDate')
2307 && ( C4::Context->preference('ceilingDueDate') =~ C4::Dates->regexp('syspref') )
2308 && $datedue->output gt C4::Context->preference('ceilingDueDate') ) {
2309 $datedue = C4::Dates->new( C4::Context->preference('ceilingDueDate') );
2315 =head2 CheckValidDatedue
2316 This function does not account for holiday exceptions nor does it handle the 'useDaysMode' syspref .
2317 To be replaced by CalcDateDue() once C4::Calendar use is tested.
2319 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
2320 this function validates the loan length against the holidays calendar, and adjusts the due date as per the 'useDaysMode' syspref.
2321 C<$date_due> = returndate calculate with no day check
2322 C<$itemnumber> = itemnumber
2323 C<$branchcode> = location of issue (affected by 'CircControl' syspref)
2324 C<$loanlength> = loan length prior to adjustment
2327 sub CheckValidDatedue {
2328 my ($date_due,$itemnumber,$branchcode)=@_;
2329 my @datedue=split('-',$date_due->output('iso'));
2330 my $years=$datedue[0];
2331 my $month=$datedue[1];
2332 my $day=$datedue[2];
2333 # die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
2335 for (my $i=0;$i<2;$i++){
2336 $dow=Day_of_Week($years,$month,$day);
2337 ($dow=0) if ($dow>6);
2338 my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
2339 my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2340 my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2341 if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
2343 (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
2346 my $newdatedue=C4::Dates->new(sprintf("%04d-%02d-%02d",$years,$month,$day),'iso');
2351 =head2 CheckRepeatableHolidays
2353 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
2354 this function checks if the date due is a repeatable holiday
2355 C<$date_due> = returndate calculate with no day check
2356 C<$itemnumber> = itemnumber
2357 C<$branchcode> = localisation of issue
2361 sub CheckRepeatableHolidays{
2362 my($itemnumber,$week_day,$branchcode)=@_;
2363 my $dbh = C4::Context->dbh;
2364 my $query = qq|SELECT count(*)
2365 FROM repeatable_holidays
2368 my $sth = $dbh->prepare($query);
2369 $sth->execute($branchcode,$week_day);
2370 my $result=$sth->fetchrow;
2376 =head2 CheckSpecialHolidays
2378 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2379 this function check if the date is a special holiday
2380 C<$years> = the years of datedue
2381 C<$month> = the month of datedue
2382 C<$day> = the day of datedue
2383 C<$itemnumber> = itemnumber
2384 C<$branchcode> = localisation of issue
2388 sub CheckSpecialHolidays{
2389 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
2390 my $dbh = C4::Context->dbh;
2391 my $query=qq|SELECT count(*)
2392 FROM `special_holidays`
2398 my $sth = $dbh->prepare($query);
2399 $sth->execute($years,$month,$day,$branchcode);
2400 my $countspecial=$sth->fetchrow ;
2402 return $countspecial;
2405 =head2 CheckRepeatableSpecialHolidays
2407 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2408 this function check if the date is a repeatble special holidays
2409 C<$month> = the month of datedue
2410 C<$day> = the day of datedue
2411 C<$itemnumber> = itemnumber
2412 C<$branchcode> = localisation of issue
2416 sub CheckRepeatableSpecialHolidays{
2417 my ($month,$day,$itemnumber,$branchcode) = @_;
2418 my $dbh = C4::Context->dbh;
2419 my $query=qq|SELECT count(*)
2420 FROM `repeatable_holidays`
2425 my $sth = $dbh->prepare($query);
2426 $sth->execute($month,$day,$branchcode);
2427 my $countspecial=$sth->fetchrow ;
2429 return $countspecial;
2434 sub CheckValidBarcode{
2436 my $dbh = C4::Context->dbh;
2437 my $query=qq|SELECT count(*)
2441 my $sth = $dbh->prepare($query);
2442 $sth->execute($barcode);
2443 my $exist=$sth->fetchrow ;
2454 Koha Developement team <info@koha.org>