1 package C4::Circulation;
3 # Copyright 2000-2002 Katipo Communications
4 # copyright 2010 BibLibre
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23 #use warnings; FIXME - Bug 2505
33 use C4::ItemCirculationAlertPreference;
36 use C4::Branch; # GetBranches
37 use C4::Log; # logaction
39 GetAuthorisedValueByCode
41 GetKohaAuthorisedValueLib
43 use C4::Overdues qw(CalcFine UpdateFine get_chargeable_units);
44 use C4::RotatingCollections qw(GetCollectionItemBranches);
45 use Algorithm::CheckDigits;
50 use Koha::Borrower::Debarments;
53 use List::MoreUtils qw( uniq );
63 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
67 $VERSION = 3.07.00.049; # for version checking
70 # FIXME subs that should probably be elsewhere
75 &GetPendingOnSiteCheckouts
78 # subs to deal with issuing a book
90 &GetBranchBorrowerCircRule
94 &AnonymiseIssueHistory
95 &CheckIfIssuedToPatron
100 # subs to deal with returns
106 # subs to deal with transfers
113 &IsBranchTransferAllowed
114 &CreateBranchTransferLimit
115 &DeleteBranchTransferLimits
119 # subs to deal with offline circulation
121 &GetOfflineOperations
124 &DeleteOfflineOperation
125 &ProcessOfflineOperation
131 C4::Circulation - Koha circulation module
139 The functions in this module deal with circulation, issues, and
140 returns, as well as general information about the library.
141 Also deals with inventory.
147 $str = &barcodedecode($barcode, [$filter]);
149 Generic filter function for barcode string.
150 Called on every circ if the System Pref itemBarcodeInputFilter is set.
151 Will do some manipulation of the barcode for systems that deliver a barcode
152 to circulation.pl that differs from the barcode stored for the item.
153 For proper functioning of this filter, calling the function on the
154 correct barcode string (items.barcode) should return an unaltered barcode.
156 The optional $filter argument is to allow for testing or explicit
157 behavior that ignores the System Pref. Valid values are the same as the
162 # FIXME -- the &decode fcn below should be wrapped into this one.
163 # FIXME -- these plugins should be moved out of Circulation.pm
166 my ($barcode, $filter) = @_;
167 my $branch = C4::Branch::mybranch();
168 $filter = C4::Context->preference('itemBarcodeInputFilter') unless $filter;
169 $filter or return $barcode; # ensure filter is defined, else return untouched barcode
170 if ($filter eq 'whitespace') {
172 } elsif ($filter eq 'cuecat') {
174 my @fields = split( /\./, $barcode );
175 my @results = map( decode($_), @fields[ 1 .. $#fields ] );
176 ($#results == 2) and return $results[2];
177 } elsif ($filter eq 'T-prefix') {
178 if ($barcode =~ /^[Tt](\d)/) {
179 (defined($1) and $1 eq '0') and return $barcode;
180 $barcode = substr($barcode, 2) + 0; # FIXME: probably should be substr($barcode, 1)
182 return sprintf("T%07d", $barcode);
183 # FIXME: $barcode could be "T1", causing warning: substr outside of string
184 # Why drop the nonzero digit after the T?
185 # Why pass non-digits (or empty string) to "T%07d"?
186 } elsif ($filter eq 'libsuite8') {
187 unless($barcode =~ m/^($branch)-/i){ #if barcode starts with branch code its in Koha style. Skip it.
188 if($barcode =~ m/^(\d)/i){ #Some barcodes even start with 0's & numbers and are assumed to have b as the item type in the libsuite8 software
189 $barcode =~ s/^[0]*(\d+)$/$branch-b-$1/i;
191 $barcode =~ s/^(\D+)[0]*(\d+)$/$branch-$1-$2/i;
194 } elsif ($filter eq 'EAN13') {
195 my $ean = CheckDigits('ean');
196 if ( $ean->is_valid($barcode) ) {
197 #$barcode = sprintf('%013d',$barcode); # this doesn't work on 32-bit systems
198 $barcode = '0' x ( 13 - length($barcode) ) . $barcode;
200 warn "# [$barcode] not valid EAN-13/UPC-A\n";
203 return $barcode; # return barcode, modified or not
208 $str = &decode($chunk);
210 Decodes a segment of a string emitted by a CueCat barcode scanner and
213 FIXME: Should be replaced with Barcode::Cuecat from CPAN
214 or Javascript based decoding on the client side.
221 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
222 my @s = map { index( $seq, $_ ); } split( //, $encoded );
223 my $l = ( $#s + 1 ) % 4;
226 # warn "Error: Cuecat decode parsing failed!";
234 my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
236 chr( ( $n >> 16 ) ^ 67 )
237 .chr( ( $n >> 8 & 255 ) ^ 67 )
238 .chr( ( $n & 255 ) ^ 67 );
241 $r = substr( $r, 0, length($r) - $l );
247 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch,
248 $barcode, $ignore_reserves);
250 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
252 C<$newbranch> is the code for the branch to which the item should be transferred.
254 C<$barcode> is the barcode of the item to be transferred.
256 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
257 Otherwise, if an item is reserved, the transfer fails.
259 Returns three values:
265 is true if the transfer was successful.
269 is a reference-to-hash which may have any of the following keys:
275 There is no item in the catalog with the given barcode. The value is C<$barcode>.
279 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.
281 =item C<DestinationEqualsHolding>
283 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.
287 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.
291 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>.
293 =item C<WasTransferred>
295 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
304 my ( $tbr, $barcode, $ignoreRs ) = @_;
307 my $branches = GetBranches();
308 my $itemnumber = GetItemnumberFromBarcode( $barcode );
309 my $issue = GetItemIssue($itemnumber);
310 my $biblio = GetBiblioFromItemNumber($itemnumber);
313 if ( not $itemnumber ) {
314 $messages->{'BadBarcode'} = $barcode;
318 # get branches of book...
319 my $hbr = $biblio->{'homebranch'};
320 my $fbr = $biblio->{'holdingbranch'};
322 # if using Branch Transfer Limits
323 if ( C4::Context->preference("UseBranchTransferLimits") == 1 ) {
324 if ( C4::Context->preference("item-level_itypes") && C4::Context->preference("BranchTransferLimitsType") eq 'itemtype' ) {
325 if ( ! IsBranchTransferAllowed( $tbr, $fbr, $biblio->{'itype'} ) ) {
326 $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{'itype'};
329 } elsif ( ! IsBranchTransferAllowed( $tbr, $fbr, $biblio->{ C4::Context->preference("BranchTransferLimitsType") } ) ) {
330 $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{ C4::Context->preference("BranchTransferLimitsType") };
336 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
337 $messages->{'IsPermanent'} = $hbr;
341 # can't transfer book if is already there....
342 if ( $fbr eq $tbr ) {
343 $messages->{'DestinationEqualsHolding'} = 1;
347 # check if it is still issued to someone, return it...
348 if ($issue->{borrowernumber}) {
349 AddReturn( $barcode, $fbr );
350 $messages->{'WasReturned'} = $issue->{borrowernumber};
354 # That'll save a database query.
355 my ( $resfound, $resrec, undef ) =
356 CheckReserves( $itemnumber );
357 if ( $resfound and not $ignoreRs ) {
358 $resrec->{'ResFound'} = $resfound;
360 # $messages->{'ResFound'} = $resrec;
364 #actually do the transfer....
366 ModItemTransfer( $itemnumber, $fbr, $tbr );
368 # don't need to update MARC anymore, we do it in batch now
369 $messages->{'WasTransfered'} = 1;
372 ModDateLastSeen( $itemnumber );
373 return ( $dotransfer, $messages, $biblio );
378 my $borrower = shift;
379 my $biblionumber = shift;
382 my $onsite_checkout = $params->{onsite_checkout} || 0;
383 my $cat_borrower = $borrower->{'categorycode'};
384 my $dbh = C4::Context->dbh;
386 # Get which branchcode we need
387 $branch = _GetCircControlBranch($item,$borrower);
388 my $type = (C4::Context->preference('item-level_itypes'))
389 ? $item->{'itype'} # item-level
390 : $item->{'itemtype'}; # biblio-level
392 # given branch, patron category, and item type, determine
393 # applicable issuing rule
394 my $issuing_rule = GetIssuingRule($cat_borrower, $type, $branch);
396 # if a rule is found and has a loan limit set, count
397 # how many loans the patron already has that meet that
399 if (defined($issuing_rule) and defined($issuing_rule->{'maxissueqty'})) {
402 SELECT COUNT(*) AS total, COALESCE(SUM(onsite_checkout), 0) AS onsite_checkouts
404 JOIN items USING (itemnumber)
407 my $rule_itemtype = $issuing_rule->{itemtype};
408 if ($rule_itemtype eq "*") {
409 # matching rule has the default item type, so count only
410 # those existing loans that don't fall under a more
412 if (C4::Context->preference('item-level_itypes')) {
413 $count_query .= " WHERE items.itype NOT IN (
414 SELECT itemtype FROM issuingrules
416 AND (categorycode = ? OR categorycode = ?)
420 $count_query .= " JOIN biblioitems USING (biblionumber)
421 WHERE biblioitems.itemtype NOT IN (
422 SELECT itemtype FROM issuingrules
424 AND (categorycode = ? OR categorycode = ?)
428 push @bind_params, $issuing_rule->{branchcode};
429 push @bind_params, $issuing_rule->{categorycode};
430 push @bind_params, $cat_borrower;
432 # rule has specific item type, so count loans of that
434 if (C4::Context->preference('item-level_itypes')) {
435 $count_query .= " WHERE items.itype = ? ";
437 $count_query .= " JOIN biblioitems USING (biblionumber)
438 WHERE biblioitems.itemtype= ? ";
440 push @bind_params, $type;
443 $count_query .= " AND borrowernumber = ? ";
444 push @bind_params, $borrower->{'borrowernumber'};
445 my $rule_branch = $issuing_rule->{branchcode};
446 if ($rule_branch ne "*") {
447 if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
448 $count_query .= " AND issues.branchcode = ? ";
449 push @bind_params, $branch;
450 } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
451 ; # if branch is the patron's home branch, then count all loans by patron
453 $count_query .= " AND items.homebranch = ? ";
454 push @bind_params, $branch;
458 my ( $checkout_count, $onsite_checkout_count ) = $dbh->selectrow_array( $count_query, {}, @bind_params );
460 my $max_checkouts_allowed = $issuing_rule->{maxissueqty};
461 my $max_onsite_checkouts_allowed = $issuing_rule->{maxonsiteissueqty};
463 if ( $onsite_checkout ) {
464 if ( $onsite_checkout_count >= $max_onsite_checkouts_allowed ) {
466 reason => 'TOO_MANY_ONSITE_CHECKOUTS',
467 count => $onsite_checkout_count,
468 max_allowed => $max_onsite_checkouts_allowed,
472 if ( C4::Context->preference('ConsiderOnSiteCheckoutsAsNormalCheckouts') ) {
473 if ( $checkout_count >= $max_checkouts_allowed ) {
475 reason => 'TOO_MANY_CHECKOUTS',
476 count => $checkout_count,
477 max_allowed => $max_checkouts_allowed,
480 } elsif ( not $onsite_checkout ) {
481 if ( $checkout_count - $onsite_checkout_count >= $max_checkouts_allowed ) {
483 reason => 'TOO_MANY_CHECKOUTS',
484 count => $checkout_count - $onsite_checkout_count,
485 max_allowed => $max_checkouts_allowed,
491 # Now count total loans against the limit for the branch
492 my $branch_borrower_circ_rule = GetBranchBorrowerCircRule($branch, $cat_borrower);
493 if (defined($branch_borrower_circ_rule->{maxissueqty})) {
494 my @bind_params = ();
495 my $branch_count_query = q|
496 SELECT COUNT(*) AS total, COALESCE(SUM(onsite_checkout), 0) AS onsite_checkouts
498 JOIN items USING (itemnumber)
499 WHERE borrowernumber = ?
501 push @bind_params, $borrower->{borrowernumber};
503 if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
504 $branch_count_query .= " AND issues.branchcode = ? ";
505 push @bind_params, $branch;
506 } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
507 ; # if branch is the patron's home branch, then count all loans by patron
509 $branch_count_query .= " AND items.homebranch = ? ";
510 push @bind_params, $branch;
512 my ( $checkout_count, $onsite_checkout_count ) = $dbh->selectrow_array( $branch_count_query, {}, @bind_params );
513 my $max_checkouts_allowed = $branch_borrower_circ_rule->{maxissueqty};
514 my $max_onsite_checkouts_allowed = $branch_borrower_circ_rule->{maxonsiteissueqty};
516 if ( $onsite_checkout ) {
517 if ( $onsite_checkout_count >= $max_onsite_checkouts_allowed ) {
519 reason => 'TOO_MANY_ONSITE_CHECKOUTS',
520 count => $onsite_checkout_count,
521 max_allowed => $max_onsite_checkouts_allowed,
525 if ( C4::Context->preference('ConsiderOnSiteCheckoutsAsNormalCheckouts') ) {
526 if ( $checkout_count >= $max_checkouts_allowed ) {
528 reason => 'TOO_MANY_CHECKOUTS',
529 count => $checkout_count,
530 max_allowed => $max_checkouts_allowed,
533 } elsif ( not $onsite_checkout ) {
534 if ( $checkout_count - $onsite_checkout_count >= $max_checkouts_allowed ) {
536 reason => 'TOO_MANY_CHECKOUTS',
537 count => $checkout_count - $onsite_checkout_count,
538 max_allowed => $max_checkouts_allowed,
544 # OK, the patron can issue !!!
550 @issues = &itemissues($biblioitemnumber, $biblio);
552 Looks up information about who has borrowed the bookZ<>(s) with the
553 given biblioitemnumber.
555 C<$biblio> is ignored.
557 C<&itemissues> returns an array of references-to-hash. The keys
558 include the fields from the C<items> table in the Koha database.
559 Additional keys include:
565 If the item is currently on loan, this gives the due date.
567 If the item is not on loan, then this is either "Available" or
568 "Cancelled", if the item has been withdrawn.
572 If the item is currently on loan, this gives the card number of the
573 patron who currently has the item.
575 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
577 These give the timestamp for the last three times the item was
580 =item C<card0>, C<card1>, C<card2>
582 The card number of the last three patrons who borrowed this item.
584 =item C<borrower0>, C<borrower1>, C<borrower2>
586 The borrower number of the last three patrons who borrowed this item.
594 my ( $bibitem, $biblio ) = @_;
595 my $dbh = C4::Context->dbh;
597 $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
602 $sth->execute($bibitem) || die $sth->errstr;
604 while ( my $data = $sth->fetchrow_hashref ) {
606 # Find out who currently has this item.
607 # FIXME - Wouldn't it be better to do this as a left join of
608 # some sort? Currently, this code assumes that if
609 # fetchrow_hashref() fails, then the book is on the shelf.
610 # fetchrow_hashref() can fail for any number of reasons (e.g.,
611 # database server crash), not just because no items match the
613 my $sth2 = $dbh->prepare(
614 "SELECT * FROM issues
615 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
620 $sth2->execute( $data->{'itemnumber'} );
621 if ( my $data2 = $sth2->fetchrow_hashref ) {
622 $data->{'date_due'} = $data2->{'date_due'};
623 $data->{'card'} = $data2->{'cardnumber'};
624 $data->{'borrower'} = $data2->{'borrowernumber'};
627 $data->{'date_due'} = ($data->{'withdrawn'} eq '1') ? 'Cancelled' : 'Available';
631 # Find the last 3 people who borrowed this item.
632 $sth2 = $dbh->prepare(
633 "SELECT * FROM old_issues
634 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
636 ORDER BY returndate DESC,timestamp DESC"
639 $sth2->execute( $data->{'itemnumber'} );
640 for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
641 { # FIXME : error if there is less than 3 pple borrowing this item
642 if ( my $data2 = $sth2->fetchrow_hashref ) {
643 $data->{"timestamp$i2"} = $data2->{'timestamp'};
644 $data->{"card$i2"} = $data2->{'cardnumber'};
645 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
649 $results[$i] = $data;
656 =head2 CanBookBeIssued
658 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $borrower,
659 $barcode, $duedate, $inprocess, $ignore_reserves );
661 Check if a book can be issued.
663 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
667 =item C<$borrower> hash with borrower informations (from GetMember or GetMemberDetails)
669 =item C<$barcode> is the bar code of the book being issued.
671 =item C<$duedates> is a DateTime object.
673 =item C<$inprocess> boolean switch
674 =item C<$ignore_reserves> boolean switch
682 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
683 Possible values are :
689 sticky due date is invalid
693 borrower gone with no address
697 borrower declared it's card lost
703 =head3 UNKNOWN_BARCODE
717 item is restricted (set by ??)
719 C<$needsconfirmation> a reference to a hash. It contains reasons why the loan
720 could be prevented, but ones that can be overriden by the operator.
722 Possible values are :
730 renewing, not issuing
732 =head3 ISSUED_TO_ANOTHER
734 issued to someone else.
738 reserved for someone else.
742 sticky due date is invalid or due date in the past
746 if the borrower borrows to much things
750 sub CanBookBeIssued {
751 my ( $borrower, $barcode, $duedate, $inprocess, $ignore_reserves, $params ) = @_;
752 my %needsconfirmation; # filled with problems that needs confirmations
753 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
754 my %alerts; # filled with messages that shouldn't stop issuing, but the librarian should be aware of.
756 my $onsite_checkout = $params->{onsite_checkout} || 0;
758 my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
759 my $issue = GetItemIssue($item->{itemnumber});
760 my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
761 $item->{'itemtype'}=$item->{'itype'};
762 my $dbh = C4::Context->dbh;
764 # MANDATORY CHECKS - unless item exists, nothing else matters
765 unless ( $item->{barcode} ) {
766 $issuingimpossible{UNKNOWN_BARCODE} = 1;
768 return ( \%issuingimpossible, \%needsconfirmation ) if %issuingimpossible;
771 # DUE DATE is OK ? -- should already have checked.
773 if ($duedate && ref $duedate ne 'DateTime') {
774 $duedate = dt_from_string($duedate);
776 my $now = DateTime->now( time_zone => C4::Context->tz() );
777 unless ( $duedate ) {
778 my $issuedate = $now->clone();
780 my $branch = _GetCircControlBranch($item,$borrower);
781 my $itype = ( C4::Context->preference('item-level_itypes') ) ? $item->{'itype'} : $biblioitem->{'itemtype'};
782 $duedate = CalcDateDue( $issuedate, $itype, $branch, $borrower );
784 # Offline circ calls AddIssue directly, doesn't run through here
785 # So issuingimpossible should be ok.
788 my $today = $now->clone();
789 $today->truncate( to => 'minute');
790 if (DateTime->compare($duedate,$today) == -1 ) { # duedate cannot be before now
791 $needsconfirmation{INVALID_DATE} = output_pref($duedate);
794 $issuingimpossible{INVALID_DATE} = output_pref($duedate);
800 if ( $borrower->{'category_type'} eq 'X' && ( $item->{barcode} )) {
801 # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1 .
803 branch => C4::Context->userenv->{'branch'},
805 itemnumber => $item->{'itemnumber'},
806 itemtype => $item->{'itemtype'},
807 borrowernumber => $borrower->{'borrowernumber'},
808 ccode => $item->{'ccode'}}
810 ModDateLastSeen( $item->{'itemnumber'} );
811 return( { STATS => 1 }, {});
813 if ( $borrower->{flags}->{GNA} ) {
814 $issuingimpossible{GNA} = 1;
816 if ( $borrower->{flags}->{'LOST'} ) {
817 $issuingimpossible{CARD_LOST} = 1;
819 if ( $borrower->{flags}->{'DBARRED'} ) {
820 $issuingimpossible{DEBARRED} = 1;
822 if ( !defined $borrower->{dateexpiry} || $borrower->{'dateexpiry'} eq '0000-00-00') {
823 $issuingimpossible{EXPIRED} = 1;
825 my $expiry_dt = dt_from_string( $borrower->{dateexpiry}, 'sql', 'floating' );
826 $expiry_dt->truncate( to => 'day');
827 my $today = $now->clone()->truncate(to => 'day');
828 $today->set_time_zone( 'floating' );
829 if ( DateTime->compare($today, $expiry_dt) == 1 ) {
830 $issuingimpossible{EXPIRED} = 1;
839 my ($balance, $non_issue_charges, $other_charges) =
840 C4::Members::GetMemberAccountBalance( $borrower->{'borrowernumber'} );
841 my $amountlimit = C4::Context->preference("noissuescharge");
842 my $allowfineoverride = C4::Context->preference("AllowFineOverride");
843 my $allfinesneedoverride = C4::Context->preference("AllFinesNeedOverride");
844 if ( C4::Context->preference("IssuingInProcess") ) {
845 if ( $non_issue_charges > $amountlimit && !$inprocess && !$allowfineoverride) {
846 $issuingimpossible{DEBT} = sprintf( "%.2f", $non_issue_charges );
847 } elsif ( $non_issue_charges > $amountlimit && !$inprocess && $allowfineoverride) {
848 $needsconfirmation{DEBT} = sprintf( "%.2f", $non_issue_charges );
849 } elsif ( $allfinesneedoverride && $non_issue_charges > 0 && $non_issue_charges <= $amountlimit && !$inprocess ) {
850 $needsconfirmation{DEBT} = sprintf( "%.2f", $non_issue_charges );
854 if ( $non_issue_charges > $amountlimit && $allowfineoverride ) {
855 $needsconfirmation{DEBT} = sprintf( "%.2f", $non_issue_charges );
856 } elsif ( $non_issue_charges > $amountlimit && !$allowfineoverride) {
857 $issuingimpossible{DEBT} = sprintf( "%.2f", $non_issue_charges );
858 } elsif ( $non_issue_charges > 0 && $allfinesneedoverride ) {
859 $needsconfirmation{DEBT} = sprintf( "%.2f", $non_issue_charges );
862 if ($balance > 0 && $other_charges > 0) {
863 $alerts{OTHER_CHARGES} = sprintf( "%.2f", $other_charges );
866 my ($blocktype, $count) = C4::Members::IsMemberBlocked($borrower->{'borrowernumber'});
867 if ($blocktype == -1) {
868 ## patron has outstanding overdue loans
869 if ( C4::Context->preference("OverduesBlockCirc") eq 'block'){
870 $issuingimpossible{USERBLOCKEDOVERDUE} = $count;
872 elsif ( C4::Context->preference("OverduesBlockCirc") eq 'confirmation'){
873 $needsconfirmation{USERBLOCKEDOVERDUE} = $count;
875 } elsif($blocktype == 1) {
876 # patron has accrued fine days or has a restriction. $count is a date
877 if ($count eq '9999-12-31') {
878 $issuingimpossible{USERBLOCKEDNOENDDATE} = $count;
881 $issuingimpossible{USERBLOCKEDWITHENDDATE} = $count;
886 # JB34 CHECKS IF BORROWERS DON'T HAVE ISSUE TOO MANY BOOKS
888 my $toomany = TooMany( $borrower, $item->{biblionumber}, $item, { onsite_checkout => $onsite_checkout } );
889 # if TooMany max_allowed returns 0 the user doesn't have permission to check out this book
891 if ( $toomany->{max_allowed} == 0 ) {
892 $needsconfirmation{PATRON_CANT} = 1;
894 if ( C4::Context->preference("AllowTooManyOverride") ) {
895 $needsconfirmation{TOO_MANY} = $toomany->{reason};
896 $needsconfirmation{current_loan_count} = $toomany->{count};
897 $needsconfirmation{max_loans_allowed} = $toomany->{max_allowed};
899 $issuingimpossible{TOO_MANY} = $toomany->{reason};
900 $issuingimpossible{current_loan_count} = $toomany->{count};
901 $issuingimpossible{max_loans_allowed} = $toomany->{max_allowed};
908 if ( $item->{'notforloan'} )
910 if(!C4::Context->preference("AllowNotForLoanOverride")){
911 $issuingimpossible{NOT_FOR_LOAN} = 1;
912 $issuingimpossible{item_notforloan} = $item->{'notforloan'};
914 $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
915 $needsconfirmation{item_notforloan} = $item->{'notforloan'};
919 # we have to check itemtypes.notforloan also
920 if (C4::Context->preference('item-level_itypes')){
921 # this should probably be a subroutine
922 my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
923 $sth->execute($item->{'itemtype'});
924 my $notforloan=$sth->fetchrow_hashref();
925 if ($notforloan->{'notforloan'}) {
926 if (!C4::Context->preference("AllowNotForLoanOverride")) {
927 $issuingimpossible{NOT_FOR_LOAN} = 1;
928 $issuingimpossible{itemtype_notforloan} = $item->{'itype'};
930 $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
931 $needsconfirmation{itemtype_notforloan} = $item->{'itype'};
935 elsif ($biblioitem->{'notforloan'} == 1){
936 if (!C4::Context->preference("AllowNotForLoanOverride")) {
937 $issuingimpossible{NOT_FOR_LOAN} = 1;
938 $issuingimpossible{itemtype_notforloan} = $biblioitem->{'itemtype'};
940 $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
941 $needsconfirmation{itemtype_notforloan} = $biblioitem->{'itemtype'};
945 if ( $item->{'withdrawn'} && $item->{'withdrawn'} > 0 )
947 $issuingimpossible{WTHDRAWN} = 1;
949 if ( $item->{'restricted'}
950 && $item->{'restricted'} == 1 )
952 $issuingimpossible{RESTRICTED} = 1;
954 if ( $item->{'itemlost'} && C4::Context->preference("IssueLostItem") ne 'nothing' ) {
955 my $code = GetAuthorisedValueByCode( 'LOST', $item->{'itemlost'} );
956 $needsconfirmation{ITEM_LOST} = $code if ( C4::Context->preference("IssueLostItem") eq 'confirm' );
957 $alerts{ITEM_LOST} = $code if ( C4::Context->preference("IssueLostItem") eq 'alert' );
959 if ( C4::Context->preference("IndependentBranches") ) {
960 my $userenv = C4::Context->userenv;
961 unless ( C4::Context->IsSuperLibrarian() ) {
962 if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} ){
963 $issuingimpossible{ITEMNOTSAMEBRANCH} = 1;
964 $issuingimpossible{'itemhomebranch'} = $item->{C4::Context->preference("HomeOrHoldingBranch")};
966 $needsconfirmation{BORRNOTSAMEBRANCH} = GetBranchName( $borrower->{'branchcode'} )
967 if ( $borrower->{'branchcode'} ne $userenv->{branch} );
971 # CHECK IF THERE IS RENTAL CHARGES. RENTAL MUST BE CONFIRMED BY THE BORROWER
973 my $rentalConfirmation = C4::Context->preference("RentalFeesCheckoutConfirmation");
975 if ( $rentalConfirmation ){
976 my ($rentalCharge) = GetIssuingCharges( $item->{'itemnumber'}, $borrower->{'borrowernumber'} );
977 if ( $rentalCharge > 0 ){
978 $rentalCharge = sprintf("%.02f", $rentalCharge);
979 $needsconfirmation{RENTALCHARGE} = $rentalCharge;
984 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
986 if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} ){
988 # Already issued to current borrower. Ask whether the loan should
990 my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed(
991 $borrower->{'borrowernumber'},
992 $item->{'itemnumber'}
994 if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed
995 if ( $renewerror eq 'onsite_checkout' ) {
996 $issuingimpossible{NO_RENEWAL_FOR_ONSITE_CHECKOUTS} = 1;
999 $issuingimpossible{NO_MORE_RENEWALS} = 1;
1003 $needsconfirmation{RENEW_ISSUE} = 1;
1006 elsif ($issue->{borrowernumber}) {
1008 # issued to someone else
1009 my $currborinfo = C4::Members::GetMember( borrowernumber => $issue->{borrowernumber} );
1012 my ( $can_be_returned, $message ) = CanBookBeReturned( $item, C4::Context->userenv->{branch} );
1014 unless ( $can_be_returned ) {
1015 $issuingimpossible{RETURN_IMPOSSIBLE} = 1;
1016 $issuingimpossible{branch_to_return} = $message;
1018 $needsconfirmation{ISSUED_TO_ANOTHER} = 1;
1019 $needsconfirmation{issued_firstname} = $currborinfo->{'firstname'};
1020 $needsconfirmation{issued_surname} = $currborinfo->{'surname'};
1021 $needsconfirmation{issued_cardnumber} = $currborinfo->{'cardnumber'};
1022 $needsconfirmation{issued_borrowernumber} = $currborinfo->{'borrowernumber'};
1026 unless ( $ignore_reserves ) {
1027 # See if the item is on reserve.
1028 my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
1030 my $resbor = $res->{'borrowernumber'};
1031 if ( $resbor ne $borrower->{'borrowernumber'} ) {
1032 my ( $resborrower ) = C4::Members::GetMember( borrowernumber => $resbor );
1033 my $branchname = GetBranchName( $res->{'branchcode'} );
1034 if ( $restype eq "Waiting" )
1036 # The item is on reserve and waiting, but has been
1037 # reserved by some other patron.
1038 $needsconfirmation{RESERVE_WAITING} = 1;
1039 $needsconfirmation{'resfirstname'} = $resborrower->{'firstname'};
1040 $needsconfirmation{'ressurname'} = $resborrower->{'surname'};
1041 $needsconfirmation{'rescardnumber'} = $resborrower->{'cardnumber'};
1042 $needsconfirmation{'resborrowernumber'} = $resborrower->{'borrowernumber'};
1043 $needsconfirmation{'resbranchname'} = $branchname;
1044 $needsconfirmation{'reswaitingdate'} = $res->{'waitingdate'};
1046 elsif ( $restype eq "Reserved" ) {
1047 # The item is on reserve for someone else.
1048 $needsconfirmation{RESERVED} = 1;
1049 $needsconfirmation{'resfirstname'} = $resborrower->{'firstname'};
1050 $needsconfirmation{'ressurname'} = $resborrower->{'surname'};
1051 $needsconfirmation{'rescardnumber'} = $resborrower->{'cardnumber'};
1052 $needsconfirmation{'resborrowernumber'} = $resborrower->{'borrowernumber'};
1053 $needsconfirmation{'resbranchname'} = $branchname;
1054 $needsconfirmation{'resreservedate'} = $res->{'reservedate'};
1060 ## CHECK AGE RESTRICTION
1061 my $agerestriction = $biblioitem->{'agerestriction'};
1062 my ($restriction_age, $daysToAgeRestriction) = GetAgeRestriction( $agerestriction, $borrower );
1063 if ( $daysToAgeRestriction && $daysToAgeRestriction > 0 ) {
1064 if ( C4::Context->preference('AgeRestrictionOverride') ) {
1065 $needsconfirmation{AGE_RESTRICTION} = "$agerestriction";
1068 $issuingimpossible{AGE_RESTRICTION} = "$agerestriction";
1072 ## check for high holds decreasing loan period
1073 my $decrease_loan = C4::Context->preference('decreaseLoanHighHolds');
1074 if ( $decrease_loan && $decrease_loan == 1 ) {
1075 my ( $reserved, $num, $duration, $returndate ) =
1076 checkHighHolds( $item, $borrower );
1078 if ( $num >= C4::Context->preference('decreaseLoanHighHoldsValue') ) {
1079 $needsconfirmation{HIGHHOLDS} = {
1081 duration => $duration,
1082 returndate => output_pref($returndate),
1088 !C4::Context->preference('AllowMultipleIssuesOnABiblio') &&
1089 # don't do the multiple loans per bib check if we've
1090 # already determined that we've got a loan on the same item
1091 !$issuingimpossible{NO_MORE_RENEWALS} &&
1092 !$needsconfirmation{RENEW_ISSUE}
1094 # Check if borrower has already issued an item from the same biblio
1095 # Only if it's not a subscription
1096 my $biblionumber = $item->{biblionumber};
1097 require C4::Serials;
1098 my $is_a_subscription = C4::Serials::CountSubscriptionFromBiblionumber($biblionumber);
1099 unless ($is_a_subscription) {
1100 my $issues = GetIssues( {
1101 borrowernumber => $borrower->{borrowernumber},
1102 biblionumber => $biblionumber,
1104 my @issues = $issues ? @$issues : ();
1105 # if we get here, we don't already have a loan on this item,
1106 # so if there are any loans on this bib, ask for confirmation
1107 if (scalar @issues > 0) {
1108 $needsconfirmation{BIBLIO_ALREADY_ISSUED} = 1;
1113 return ( \%issuingimpossible, \%needsconfirmation, \%alerts );
1116 =head2 CanBookBeReturned
1118 ($returnallowed, $message) = CanBookBeReturned($item, $branch)
1120 Check whether the item can be returned to the provided branch
1124 =item C<$item> is a hash of item information as returned from GetItem
1126 =item C<$branch> is the branchcode where the return is taking place
1134 =item C<$returnallowed> is 0 or 1, corresponding to whether the return is allowed (1) or not (0)
1136 =item C<$message> is the branchcode where the item SHOULD be returned, if the return is not allowed
1142 sub CanBookBeReturned {
1143 my ($item, $branch) = @_;
1144 my $allowreturntobranch = C4::Context->preference("AllowReturnToBranch") || 'anywhere';
1146 # assume return is allowed to start
1150 # identify all cases where return is forbidden
1151 if ($allowreturntobranch eq 'homebranch' && $branch ne $item->{'homebranch'}) {
1153 $message = $item->{'homebranch'};
1154 } elsif ($allowreturntobranch eq 'holdingbranch' && $branch ne $item->{'holdingbranch'}) {
1156 $message = $item->{'holdingbranch'};
1157 } elsif ($allowreturntobranch eq 'homeorholdingbranch' && $branch ne $item->{'homebranch'} && $branch ne $item->{'holdingbranch'}) {
1159 $message = $item->{'homebranch'}; # FIXME: choice of homebranch is arbitrary
1162 return ($allowed, $message);
1165 =head2 CheckHighHolds
1167 used when syspref decreaseLoanHighHolds is active. Returns 1 or 0 to define whether the minimum value held in
1168 decreaseLoanHighHoldsValue is exceeded, the total number of outstanding holds, the number of days the loan
1169 has been decreased to (held in syspref decreaseLoanHighHoldsValue), and the new due date
1173 sub checkHighHolds {
1174 my ( $item, $borrower ) = @_;
1175 my $biblio = GetBiblioFromItemNumber( $item->{itemnumber} );
1176 my $branch = _GetCircControlBranch( $item, $borrower );
1177 my $dbh = C4::Context->dbh;
1178 my $sth = $dbh->prepare(
1179 'select count(borrowernumber) as num_holds from reserves where biblionumber=?'
1181 $sth->execute( $item->{'biblionumber'} );
1182 my ($holds) = $sth->fetchrow_array;
1184 my $issuedate = DateTime->now( time_zone => C4::Context->tz() );
1186 my $calendar = Koha::Calendar->new( branchcode => $branch );
1189 ( C4::Context->preference('item-level_itypes') )
1190 ? $biblio->{'itype'}
1191 : $biblio->{'itemtype'};
1193 C4::Circulation::CalcDateDue( $issuedate, $itype, $branch,
1196 my $reduced_datedue =
1197 $calendar->addDate( $issuedate,
1198 C4::Context->preference('decreaseLoanHighHoldsDuration') );
1200 if ( DateTime->compare( $reduced_datedue, $orig_due ) == -1 ) {
1202 C4::Context->preference('decreaseLoanHighHoldsDuration'),
1206 return ( 0, 0, 0, undef );
1211 &AddIssue($borrower, $barcode, [$datedue], [$cancelreserve], [$issuedate])
1213 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
1217 =item C<$borrower> is a hash with borrower informations (from GetMember or GetMemberDetails).
1219 =item C<$barcode> is the barcode of the item being issued.
1221 =item C<$datedue> is a DateTime object for the max date of return, i.e. the date due (optional).
1222 Calculated if empty.
1224 =item C<$cancelreserve> is 1 to override and cancel any pending reserves for the item (optional).
1226 =item C<$issuedate> is the date to issue the item in iso (YYYY-MM-DD) format (optional).
1227 Defaults to today. Unlike C<$datedue>, NOT a DateTime object, unfortunately.
1229 AddIssue does the following things :
1231 - step 01: check that there is a borrowernumber & a barcode provided
1232 - check for RENEWAL (book issued & being issued to the same patron)
1233 - renewal YES = Calculate Charge & renew
1235 * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
1237 - fill reserve if reserve to this patron
1238 - cancel reserve or not, otherwise
1239 * TRANSFERT PENDING ?
1240 - complete the transfert
1248 my ( $borrower, $barcode, $datedue, $cancelreserve, $issuedate, $sipmode, $params ) = @_;
1250 my $onsite_checkout = $params && $params->{onsite_checkout} ? 1 : 0;
1251 my $auto_renew = $params && $params->{auto_renew};
1252 my $dbh = C4::Context->dbh;
1253 my $barcodecheck = CheckValidBarcode($barcode);
1257 if ( $datedue && ref $datedue ne 'DateTime' ) {
1258 $datedue = dt_from_string($datedue);
1261 # $issuedate defaults to today.
1262 if ( !defined $issuedate ) {
1263 $issuedate = DateTime->now( time_zone => C4::Context->tz() );
1266 if ( ref $issuedate ne 'DateTime' ) {
1267 $issuedate = dt_from_string($issuedate);
1272 # Stop here if the patron or barcode doesn't exist
1273 if ( $borrower && $barcode && $barcodecheck ) {
1274 # find which item we issue
1275 my $item = GetItem( '', $barcode )
1276 or return; # if we don't get an Item, abort.
1278 my $branch = _GetCircControlBranch( $item, $borrower );
1280 # get actual issuing if there is one
1281 my $actualissue = GetItemIssue( $item->{itemnumber} );
1283 # get biblioinformation for this item
1284 my $biblio = GetBiblioFromItemNumber( $item->{itemnumber} );
1286 # check if we just renew the issue.
1287 if ( $actualissue->{borrowernumber} eq $borrower->{'borrowernumber'} ) {
1288 $datedue = AddRenewal(
1289 $borrower->{'borrowernumber'},
1290 $item->{'itemnumber'},
1293 $issuedate, # here interpreted as the renewal date
1297 # it's NOT a renewal
1298 if ( $actualissue->{borrowernumber} ) {
1299 # This book is currently on loan, but not to the person
1300 # who wants to borrow it now. mark it returned before issuing to the new borrower
1301 my ( $allowed, $message ) = CanBookBeReturned( $item, C4::Context->userenv->{branch} );
1302 return unless $allowed;
1303 AddReturn( $item->{'barcode'}, C4::Context->userenv->{'branch'} );
1306 MoveReserve( $item->{'itemnumber'}, $borrower->{'borrowernumber'}, $cancelreserve );
1308 # Starting process for transfer job (checking transfert and validate it if we have one)
1309 my ($datesent) = GetTransfers( $item->{'itemnumber'} );
1311 # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for visibility of this case (maybe for stats ....)
1312 my $sth = $dbh->prepare(
1313 "UPDATE branchtransfers
1314 SET datearrived = now(),
1316 comments = 'Forced branchtransfer'
1317 WHERE itemnumber= ? AND datearrived IS NULL"
1319 $sth->execute( C4::Context->userenv->{'branch'},
1320 $item->{'itemnumber'} );
1323 # If automatic renewal wasn't selected while issuing, set the value according to the issuing rule.
1324 unless ($auto_renew) {
1325 my $issuingrule = GetIssuingRule( $borrower->{categorycode}, $item->{itype}, $branch );
1326 $auto_renew = $issuingrule->{auto_renew};
1329 # Record in the database the fact that the book was issued.
1332 ( C4::Context->preference('item-level_itypes') )
1333 ? $biblio->{'itype'}
1334 : $biblio->{'itemtype'};
1335 $datedue = CalcDateDue( $issuedate, $itype, $branch, $borrower );
1338 $datedue->truncate( to => 'minute' );
1340 $issue = Koha::Database->new()->schema()->resultset('Issue')->create(
1342 borrowernumber => $borrower->{'borrowernumber'},
1343 itemnumber => $item->{'itemnumber'},
1344 issuedate => $issuedate->strftime('%Y-%m-%d %H:%M:%S'),
1345 date_due => $datedue->strftime('%Y-%m-%d %H:%M:%S'),
1346 branchcode => C4::Context->userenv->{'branch'},
1347 onsite_checkout => $onsite_checkout,
1348 auto_renew => $auto_renew ? 1 : 0
1352 if ( C4::Context->preference('ReturnToShelvingCart') ) {
1353 # ReturnToShelvingCart is on, anything issued should be taken off the cart.
1354 CartToShelf( $item->{'itemnumber'} );
1356 $item->{'issues'}++;
1357 if ( C4::Context->preference('UpdateTotalIssuesOnCirc') ) {
1358 UpdateTotalIssues( $item->{'biblionumber'}, 1 );
1361 ## If item was lost, it has now been found, reverse any list item charges if necessary.
1362 if ( $item->{'itemlost'} ) {
1363 if ( C4::Context->preference('RefundLostItemFeeOnReturn') ) {
1364 _FixAccountForLostAndReturned( $item->{'itemnumber'}, undef, $item->{'barcode'} );
1370 issues => $item->{'issues'},
1371 holdingbranch => C4::Context->userenv->{'branch'},
1373 onloan => $datedue->ymd(),
1374 datelastborrowed => DateTime->now( time_zone => C4::Context->tz() )->ymd(),
1376 $item->{'biblionumber'},
1377 $item->{'itemnumber'}
1379 ModDateLastSeen( $item->{'itemnumber'} );
1381 # If it costs to borrow this book, charge it to the patron's account.
1382 my ( $charge, $itemtype ) = GetIssuingCharges( $item->{'itemnumber'}, $borrower->{'borrowernumber'} );
1383 if ( $charge > 0 ) {
1384 AddIssuingCharge( $item->{'itemnumber'}, $borrower->{'borrowernumber'}, $charge );
1385 $item->{'charge'} = $charge;
1388 # Record the fact that this book was issued.
1391 branch => C4::Context->userenv->{'branch'},
1392 type => ( $onsite_checkout ? 'onsite_checkout' : 'issue' ),
1394 other => ( $sipmode ? "SIP-$sipmode" : '' ),
1395 itemnumber => $item->{'itemnumber'},
1396 itemtype => $item->{'itype'},
1397 borrowernumber => $borrower->{'borrowernumber'},
1398 ccode => $item->{'ccode'}
1402 # Send a checkout slip.
1403 my $circulation_alert = 'C4::ItemCirculationAlertPreference';
1405 branchcode => $branch,
1406 categorycode => $borrower->{categorycode},
1407 item_type => $item->{itype},
1408 notification => 'CHECKOUT',
1410 if ( $circulation_alert->is_enabled_for( \%conditions ) ) {
1411 SendCirculationAlert(
1415 borrower => $borrower,
1423 "CIRCULATION", "ISSUE",
1424 $borrower->{'borrowernumber'},
1425 $biblio->{'itemnumber'}
1426 ) if C4::Context->preference("IssueLog");
1431 =head2 GetLoanLength
1433 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1435 Get loan length for an itemtype, a borrower type and a branch
1440 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1441 my $dbh = C4::Context->dbh;
1442 my $sth = $dbh->prepare(qq{
1443 SELECT issuelength, lengthunit, renewalperiod
1445 WHERE categorycode=?
1448 AND issuelength IS NOT NULL
1451 # try to find issuelength & return the 1st available.
1452 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1453 $sth->execute( $borrowertype, $itemtype, $branchcode );
1454 my $loanlength = $sth->fetchrow_hashref;
1457 if defined($loanlength) && defined $loanlength->{issuelength};
1459 $sth->execute( $borrowertype, '*', $branchcode );
1460 $loanlength = $sth->fetchrow_hashref;
1462 if defined($loanlength) && defined $loanlength->{issuelength};
1464 $sth->execute( '*', $itemtype, $branchcode );
1465 $loanlength = $sth->fetchrow_hashref;
1467 if defined($loanlength) && defined $loanlength->{issuelength};
1469 $sth->execute( '*', '*', $branchcode );
1470 $loanlength = $sth->fetchrow_hashref;
1472 if defined($loanlength) && defined $loanlength->{issuelength};
1474 $sth->execute( $borrowertype, $itemtype, '*' );
1475 $loanlength = $sth->fetchrow_hashref;
1477 if defined($loanlength) && defined $loanlength->{issuelength};
1479 $sth->execute( $borrowertype, '*', '*' );
1480 $loanlength = $sth->fetchrow_hashref;
1482 if defined($loanlength) && defined $loanlength->{issuelength};
1484 $sth->execute( '*', $itemtype, '*' );
1485 $loanlength = $sth->fetchrow_hashref;
1487 if defined($loanlength) && defined $loanlength->{issuelength};
1489 $sth->execute( '*', '*', '*' );
1490 $loanlength = $sth->fetchrow_hashref;
1492 if defined($loanlength) && defined $loanlength->{issuelength};
1494 # if no rule is set => 0 day (hardcoded)
1498 lengthunit => 'days',
1504 =head2 GetHardDueDate
1506 my ($hardduedate,$hardduedatecompare) = &GetHardDueDate($borrowertype,$itemtype,branchcode)
1508 Get the Hard Due Date and it's comparison for an itemtype, a borrower type and a branch
1512 sub GetHardDueDate {
1513 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1515 my $rule = GetIssuingRule( $borrowertype, $itemtype, $branchcode );
1517 if ( defined( $rule ) ) {
1518 if ( $rule->{hardduedate} ) {
1519 return (dt_from_string($rule->{hardduedate}, 'iso'),$rule->{hardduedatecompare});
1521 return (undef, undef);
1526 =head2 GetIssuingRule
1528 my $irule = &GetIssuingRule($borrowertype,$itemtype,branchcode)
1530 FIXME - This is a copy-paste of GetLoanLength
1531 as a stop-gap. Do not wish to change API for GetLoanLength
1532 this close to release.
1534 Get the issuing rule for an itemtype, a borrower type and a branch
1535 Returns a hashref from the issuingrules table.
1539 sub GetIssuingRule {
1540 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1541 my $dbh = C4::Context->dbh;
1542 my $sth = $dbh->prepare( "select * from issuingrules where categorycode=? and itemtype=? and branchcode=?" );
1545 $sth->execute( $borrowertype, $itemtype, $branchcode );
1546 $irule = $sth->fetchrow_hashref;
1547 return $irule if defined($irule) ;
1549 $sth->execute( $borrowertype, "*", $branchcode );
1550 $irule = $sth->fetchrow_hashref;
1551 return $irule if defined($irule) ;
1553 $sth->execute( "*", $itemtype, $branchcode );
1554 $irule = $sth->fetchrow_hashref;
1555 return $irule if defined($irule) ;
1557 $sth->execute( "*", "*", $branchcode );
1558 $irule = $sth->fetchrow_hashref;
1559 return $irule if defined($irule) ;
1561 $sth->execute( $borrowertype, $itemtype, "*" );
1562 $irule = $sth->fetchrow_hashref;
1563 return $irule if defined($irule) ;
1565 $sth->execute( $borrowertype, "*", "*" );
1566 $irule = $sth->fetchrow_hashref;
1567 return $irule if defined($irule) ;
1569 $sth->execute( "*", $itemtype, "*" );
1570 $irule = $sth->fetchrow_hashref;
1571 return $irule if defined($irule) ;
1573 $sth->execute( "*", "*", "*" );
1574 $irule = $sth->fetchrow_hashref;
1575 return $irule if defined($irule) ;
1577 # if no rule matches,
1581 =head2 GetBranchBorrowerCircRule
1583 my $branch_cat_rule = GetBranchBorrowerCircRule($branchcode, $categorycode);
1585 Retrieves circulation rule attributes that apply to the given
1586 branch and patron category, regardless of item type.
1587 The return value is a hashref containing the following key:
1589 maxissueqty - maximum number of loans that a
1590 patron of the given category can have at the given
1591 branch. If the value is undef, no limit.
1593 maxonsiteissueqty - maximum of on-site checkouts that a
1594 patron of the given category can have at the given
1595 branch. If the value is undef, no limit.
1597 This will first check for a specific branch and
1598 category match from branch_borrower_circ_rules.
1600 If no rule is found, it will then check default_branch_circ_rules
1601 (same branch, default category). If no rule is found,
1602 it will then check default_borrower_circ_rules (default
1603 branch, same category), then failing that, default_circ_rules
1604 (default branch, default category).
1606 If no rule has been found in the database, it will default to
1610 maxonsiteissueqty - undef
1612 C<$branchcode> and C<$categorycode> should contain the
1613 literal branch code and patron category code, respectively - no
1618 sub GetBranchBorrowerCircRule {
1619 my ( $branchcode, $categorycode ) = @_;
1622 my $dbh = C4::Context->dbh();
1623 $rules = $dbh->selectrow_hashref( q|
1624 SELECT maxissueqty, maxonsiteissueqty
1625 FROM branch_borrower_circ_rules
1626 WHERE branchcode = ?
1627 AND categorycode = ?
1628 |, {}, $branchcode, $categorycode ) ;
1629 return $rules if $rules;
1631 # try same branch, default borrower category
1632 $rules = $dbh->selectrow_hashref( q|
1633 SELECT maxissueqty, maxonsiteissueqty
1634 FROM default_branch_circ_rules
1635 WHERE branchcode = ?
1636 |, {}, $branchcode ) ;
1637 return $rules if $rules;
1639 # try default branch, same borrower category
1640 $rules = $dbh->selectrow_hashref( q|
1641 SELECT maxissueqty, maxonsiteissueqty
1642 FROM default_borrower_circ_rules
1643 WHERE categorycode = ?
1644 |, {}, $categorycode ) ;
1645 return $rules if $rules;
1647 # try default branch, default borrower category
1648 $rules = $dbh->selectrow_hashref( q|
1649 SELECT maxissueqty, maxonsiteissueqty
1650 FROM default_circ_rules
1652 return $rules if $rules;
1654 # built-in default circulation rule
1656 maxissueqty => undef,
1657 maxonsiteissueqty => undef,
1661 =head2 GetBranchItemRule
1663 my $branch_item_rule = GetBranchItemRule($branchcode, $itemtype);
1665 Retrieves circulation rule attributes that apply to the given
1666 branch and item type, regardless of patron category.
1668 The return value is a hashref containing the following keys:
1670 holdallowed => Hold policy for this branch and itemtype. Possible values:
1671 0: No holds allowed.
1672 1: Holds allowed only by patrons that have the same homebranch as the item.
1673 2: Holds allowed from any patron.
1675 returnbranch => branch to which to return item. Possible values:
1676 noreturn: do not return, let item remain where checked in (floating collections)
1677 homebranch: return to item's home branch
1678 holdingbranch: return to issuer branch
1680 This searches branchitemrules in the following order:
1682 * Same branchcode and itemtype
1683 * Same branchcode, itemtype '*'
1684 * branchcode '*', same itemtype
1685 * branchcode and itemtype '*'
1687 Neither C<$branchcode> nor C<$itemtype> should be '*'.
1691 sub GetBranchItemRule {
1692 my ( $branchcode, $itemtype ) = @_;
1693 my $dbh = C4::Context->dbh();
1697 ['SELECT holdallowed, returnbranch
1698 FROM branch_item_rules
1699 WHERE branchcode = ?
1700 AND itemtype = ?', $branchcode, $itemtype],
1701 ['SELECT holdallowed, returnbranch
1702 FROM default_branch_circ_rules
1703 WHERE branchcode = ?', $branchcode],
1704 ['SELECT holdallowed, returnbranch
1705 FROM default_branch_item_rules
1706 WHERE itemtype = ?', $itemtype],
1707 ['SELECT holdallowed, returnbranch
1708 FROM default_circ_rules'],
1711 foreach my $attempt (@attempts) {
1712 my ($query, @bind_params) = @{$attempt};
1713 my $search_result = $dbh->selectrow_hashref ( $query , {}, @bind_params )
1716 # Since branch/category and branch/itemtype use the same per-branch
1717 # defaults tables, we have to check that the key we want is set, not
1718 # just that a row was returned
1719 $result->{'holdallowed'} = $search_result->{'holdallowed'} unless ( defined $result->{'holdallowed'} );
1720 $result->{'returnbranch'} = $search_result->{'returnbranch'} unless ( defined $result->{'returnbranch'} );
1723 # built-in default circulation rule
1724 $result->{'holdallowed'} = 2 unless ( defined $result->{'holdallowed'} );
1725 $result->{'returnbranch'} = 'homebranch' unless ( defined $result->{'returnbranch'} );
1732 ($doreturn, $messages, $iteminformation, $borrower) =
1733 &AddReturn( $barcode, $branch [,$exemptfine] [,$dropbox] [,$returndate] );
1739 =item C<$barcode> is the bar code of the book being returned.
1741 =item C<$branch> is the code of the branch where the book is being returned.
1743 =item C<$exemptfine> indicates that overdue charges for the item will be
1746 =item C<$dropbox> indicates that the check-in date is assumed to be
1747 yesterday, or the last non-holiday as defined in C4::Calendar . If
1748 overdue charges are applied and C<$dropbox> is true, the last charge
1749 will be removed. This assumes that the fines accrual script has run
1750 for _today_. Optional.
1752 =item C<$return_date> allows the default return date to be overridden
1753 by the given return date. Optional.
1757 C<&AddReturn> returns a list of four items:
1759 C<$doreturn> is true iff the return succeeded.
1761 C<$messages> is a reference-to-hash giving feedback on the operation.
1762 The keys of the hash are:
1768 No item with this barcode exists. The value is C<$barcode>.
1772 The book is not currently on loan. The value is C<$barcode>.
1774 =item C<IsPermanent>
1776 The book's home branch is a permanent collection. If you have borrowed
1777 this book, you are not allowed to return it. The value is the code for
1778 the book's home branch.
1782 This book has been withdrawn/cancelled. The value should be ignored.
1784 =item C<Wrongbranch>
1786 This book has was returned to the wrong branch. The value is a hashref
1787 so that C<$messages->{Wrongbranch}->{Wrongbranch}> and C<$messages->{Wrongbranch}->{Rightbranch}>
1788 contain the branchcode of the incorrect and correct return library, respectively.
1792 The item was reserved. The value is a reference-to-hash whose keys are
1793 fields from the reserves table of the Koha database, and
1794 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1795 either C<Waiting>, C<Reserved>, or 0.
1797 =item C<WasReturned>
1799 Value 1 if return is successful.
1801 =item C<NeedsTransfer>
1803 If AutomaticItemReturn is disabled, return branch is given as value of NeedsTransfer.
1807 C<$iteminformation> is a reference-to-hash, giving information about the
1808 returned item from the issues table.
1810 C<$borrower> is a reference-to-hash, giving information about the
1811 patron who last borrowed the book.
1816 my ( $barcode, $branch, $exemptfine, $dropbox, $return_date, $dropboxdate ) = @_;
1818 if ($branch and not GetBranchDetail($branch)) {
1819 warn "AddReturn error: branch '$branch' not found. Reverting to " . C4::Context->userenv->{'branch'};
1822 $branch = C4::Context->userenv->{'branch'} unless $branch; # we trust userenv to be a safe fallback/default
1827 my $validTransfert = 0;
1828 my $stat_type = 'return';
1830 # get information on item
1831 my $itemnumber = GetItemnumberFromBarcode( $barcode );
1832 unless ($itemnumber) {
1833 return (0, { BadBarcode => $barcode }); # no barcode means no item or borrower. bail out.
1835 my $issue = GetItemIssue($itemnumber);
1836 if ($issue and $issue->{borrowernumber}) {
1837 $borrower = C4::Members::GetMemberDetails($issue->{borrowernumber})
1838 or die "Data inconsistency: barcode $barcode (itemnumber:$itemnumber) claims to be issued to non-existent borrowernumber '$issue->{borrowernumber}'\n"
1839 . Dumper($issue) . "\n";
1841 $messages->{'NotIssued'} = $barcode;
1842 # even though item is not on loan, it may still be transferred; therefore, get current branch info
1844 # No issue, no borrowernumber. ONLY if $doreturn, *might* you have a $borrower later.
1845 # Record this as a local use, instead of a return, if the RecordLocalUseOnReturn is on
1846 if (C4::Context->preference("RecordLocalUseOnReturn")) {
1847 $messages->{'LocalUse'} = 1;
1848 $stat_type = 'localuse';
1852 my $item = GetItem($itemnumber) or die "GetItem($itemnumber) failed";
1854 if ( $item->{'location'} eq 'PROC' ) {
1855 if ( C4::Context->preference("InProcessingToShelvingCart") ) {
1856 $item->{'location'} = 'CART';
1859 $item->{location} = $item->{permanent_location};
1862 ModItem( $item, $item->{'biblionumber'}, $item->{'itemnumber'} );
1865 # full item data, but no borrowernumber or checkout info (no issue)
1866 # we know GetItem should work because GetItemnumberFromBarcode worked
1867 my $hbr = GetBranchItemRule($item->{'homebranch'}, $item->{'itype'})->{'returnbranch'} || "homebranch";
1868 # get the proper branch to which to return the item
1869 my $returnbranch = $item->{$hbr} || $branch ;
1870 # if $hbr was "noreturn" or any other non-item table value, then it should 'float' (i.e. stay at this branch)
1872 my $borrowernumber = $borrower->{'borrowernumber'} || undef; # we don't know if we had a borrower or not
1874 my $yaml = C4::Context->preference('UpdateNotForLoanStatusOnCheckin');
1876 $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1878 eval { $rules = YAML::Load($yaml); };
1880 warn "Unable to parse UpdateNotForLoanStatusOnCheckin syspref : $@";
1883 foreach my $key ( keys %$rules ) {
1884 if ( $item->{notforloan} eq $key ) {
1885 $messages->{'NotForLoanStatusUpdated'} = { from => $item->{notforloan}, to => $rules->{$key} };
1886 ModItem( { notforloan => $rules->{$key} }, undef, $itemnumber );
1894 # check if the book is in a permanent collection....
1895 # FIXME -- This 'PE' attribute is largely undocumented. afaict, there's no user interface that reflects this functionality.
1896 if ( $returnbranch ) {
1897 my $branches = GetBranches(); # a potentially expensive call for a non-feature.
1898 $branches->{$returnbranch}->{PE} and $messages->{'IsPermanent'} = $returnbranch;
1901 # check if the return is allowed at this branch
1902 my ($returnallowed, $message) = CanBookBeReturned($item, $branch);
1903 unless ($returnallowed){
1904 $messages->{'Wrongbranch'} = {
1905 Wrongbranch => $branch,
1906 Rightbranch => $message
1909 return ( $doreturn, $messages, $issue, $borrower );
1912 if ( $item->{'withdrawn'} ) { # book has been cancelled
1913 $messages->{'withdrawn'} = 1;
1914 $doreturn = 0 if C4::Context->preference("BlockReturnOfWithdrawnItems");
1917 # case of a return of document (deal with issues and holdingbranch)
1918 my $today = DateTime->now( time_zone => C4::Context->tz() );
1921 my $datedue = $issue->{date_due};
1922 $borrower or warn "AddReturn without current borrower";
1923 my $circControlBranch;
1925 # define circControlBranch only if dropbox mode is set
1926 # don't allow dropbox mode to create an invalid entry in issues (issuedate > today)
1927 # FIXME: check issuedate > returndate, factoring in holidays
1929 $circControlBranch = _GetCircControlBranch($item,$borrower);
1930 $issue->{'overdue'} = DateTime->compare($issue->{'date_due'}, $dropboxdate ) == -1 ? 1 : 0;
1933 if ($borrowernumber) {
1934 if ( ( C4::Context->preference('CalculateFinesOnReturn') && $issue->{'overdue'} ) || $return_date ) {
1935 # we only need to calculate and change the fines if we want to do that on return
1936 # Should be on for hourly loans
1937 my $control = C4::Context->preference('CircControl');
1938 my $control_branchcode =
1939 ( $control eq 'ItemHomeLibrary' ) ? $item->{homebranch}
1940 : ( $control eq 'PatronLibrary' ) ? $borrower->{branchcode}
1941 : $issue->{branchcode};
1944 $return_date ? dt_from_string($return_date) : $today;
1946 my ( $amount, $type, $unitcounttotal ) =
1947 C4::Overdues::CalcFine( $item, $borrower->{categorycode},
1948 $control_branchcode, $datedue, $date_returned );
1952 if ( C4::Context->preference('finesMode') eq 'production' ) {
1953 if ( $amount > 0 ) {
1954 C4::Overdues::UpdateFine( $issue->{itemnumber},
1955 $issue->{borrowernumber},
1956 $amount, $type, output_pref($datedue) );
1958 elsif ($return_date) {
1960 # Backdated returns may have fines that shouldn't exist,
1961 # so in this case, we need to drop those fines to 0
1963 C4::Overdues::UpdateFine( $issue->{itemnumber},
1964 $issue->{borrowernumber},
1965 0, $type, output_pref($datedue) );
1971 MarkIssueReturned( $borrowernumber, $item->{'itemnumber'},
1972 $circControlBranch, $return_date, $borrower->{'privacy'} );
1975 $messages->{'Wrongbranch'} = {
1976 Wrongbranch => $branch,
1977 Rightbranch => $message
1980 return ( 0, { WasReturned => 0 }, $issue, $borrower );
1983 # FIXME is the "= 1" right? This could be the borrower hash.
1984 $messages->{'WasReturned'} = 1;
1988 ModItem({ onloan => undef }, $issue->{'biblionumber'}, $item->{'itemnumber'});
1991 # the holdingbranch is updated if the document is returned to another location.
1992 # this is always done regardless of whether the item was on loan or not
1993 if ($item->{'holdingbranch'} ne $branch) {
1994 UpdateHoldingbranch($branch, $item->{'itemnumber'});
1995 $item->{'holdingbranch'} = $branch; # update item data holdingbranch too
1997 ModDateLastSeen( $item->{'itemnumber'} );
1999 # check if we have a transfer for this document
2000 my ($datesent,$frombranch,$tobranch) = GetTransfers( $item->{'itemnumber'} );
2002 # if we have a transfer to do, we update the line of transfers with the datearrived
2003 my $is_in_rotating_collection = C4::RotatingCollections::isItemInAnyCollection( $item->{'itemnumber'} );
2005 if ( $tobranch eq $branch ) {
2006 my $sth = C4::Context->dbh->prepare(
2007 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
2009 $sth->execute( $item->{'itemnumber'} );
2010 # if we have a reservation with valid transfer, we can set it's status to 'W'
2011 ShelfToCart( $item->{'itemnumber'} ) if ( C4::Context->preference("ReturnToShelvingCart") );
2012 C4::Reserves::ModReserveStatus($item->{'itemnumber'}, 'W');
2014 $messages->{'WrongTransfer'} = $tobranch;
2015 $messages->{'WrongTransferItem'} = $item->{'itemnumber'};
2017 $validTransfert = 1;
2019 ShelfToCart( $item->{'itemnumber'} ) if ( C4::Context->preference("ReturnToShelvingCart") );
2022 # fix up the accounts.....
2023 if ( $item->{'itemlost'} ) {
2024 $messages->{'WasLost'} = 1;
2026 if ( C4::Context->preference('RefundLostItemFeeOnReturn' ) ) {
2027 _FixAccountForLostAndReturned($item->{'itemnumber'}, $borrowernumber, $barcode); # can tolerate undef $borrowernumber
2028 $messages->{'LostItemFeeRefunded'} = 1;
2032 # fix up the overdues in accounts...
2033 if ($borrowernumber) {
2034 my $fix = _FixOverduesOnReturn($borrowernumber, $item->{itemnumber}, $exemptfine, $dropbox);
2035 defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $item->{itemnumber}...) failed!"; # zero is OK, check defined
2037 if ( $issue->{overdue} && $issue->{date_due} ) {
2039 $today = $dropboxdate if $dropbox;
2040 my ($debardate,$reminder) = _debar_user_on_return( $borrower, $item, $issue->{date_due}, $today );
2042 $messages->{'PrevDebarred'} = $debardate;
2044 $messages->{'Debarred'} = $debardate if $debardate;
2046 # there's no overdue on the item but borrower had been previously debarred
2047 } elsif ( $issue->{date_due} and $borrower->{'debarred'} ) {
2048 if ( $borrower->{debarred} eq "9999-12-31") {
2049 $messages->{'ForeverDebarred'} = $borrower->{'debarred'};
2051 my $borrower_debar_dt = dt_from_string( $borrower->{debarred} );
2052 $borrower_debar_dt->truncate(to => 'day');
2053 my $today_dt = $today->clone()->truncate(to => 'day');
2054 if ( DateTime->compare( $borrower_debar_dt, $today_dt ) != -1 ) {
2055 $messages->{'PrevDebarred'} = $borrower->{'debarred'};
2061 # find reserves.....
2062 # if we don't have a reserve with the status W, we launch the Checkreserves routine
2063 my ($resfound, $resrec);
2064 my $lookahead= C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
2065 ($resfound, $resrec, undef) = C4::Reserves::CheckReserves( $item->{'itemnumber'}, undef, $lookahead ) unless ( $item->{'withdrawn'} );
2067 $resrec->{'ResFound'} = $resfound;
2068 $messages->{'ResFound'} = $resrec;
2071 # Record the fact that this book was returned.
2072 # FIXME itemtype should record item level type, not bibliolevel type
2076 itemnumber => $item->{'itemnumber'},
2077 itemtype => $biblio->{'itemtype'},
2078 borrowernumber => $borrowernumber,
2079 ccode => $item->{'ccode'}}
2082 # Send a check-in slip. # NOTE: borrower may be undef. probably shouldn't try to send messages then.
2083 my $circulation_alert = 'C4::ItemCirculationAlertPreference';
2085 branchcode => $branch,
2086 categorycode => $borrower->{categorycode},
2087 item_type => $item->{itype},
2088 notification => 'CHECKIN',
2090 if ($doreturn && $circulation_alert->is_enabled_for(\%conditions)) {
2091 SendCirculationAlert({
2094 borrower => $borrower,
2099 logaction("CIRCULATION", "RETURN", $borrowernumber, $item->{'itemnumber'})
2100 if C4::Context->preference("ReturnLog");
2102 # Remove any OVERDUES related debarment if the borrower has no overdues
2103 if ( $borrowernumber
2104 && $borrower->{'debarred'}
2105 && C4::Context->preference('AutoRemoveOverduesRestrictions')
2106 && !C4::Members::HasOverdues( $borrowernumber )
2107 && @{ GetDebarments({ borrowernumber => $borrowernumber, type => 'OVERDUES' }) }
2109 DelUniqueDebarment({ borrowernumber => $borrowernumber, type => 'OVERDUES' });
2112 # Transfer to returnbranch if Automatic transfer set or append message NeedsTransfer
2113 if (!$is_in_rotating_collection && ($doreturn or $messages->{'NotIssued'}) and !$resfound and ($branch ne $returnbranch) and not $messages->{'WrongTransfer'}){
2114 if (C4::Context->preference("AutomaticItemReturn" ) or
2115 (C4::Context->preference("UseBranchTransferLimits") and
2116 ! IsBranchTransferAllowed($branch, $returnbranch, $item->{C4::Context->preference("BranchTransferLimitsType")} )
2118 $debug and warn sprintf "about to call ModItemTransfer(%s, %s, %s)", $item->{'itemnumber'},$branch, $returnbranch;
2119 $debug and warn "item: " . Dumper($item);
2120 ModItemTransfer($item->{'itemnumber'}, $branch, $returnbranch);
2121 $messages->{'WasTransfered'} = 1;
2123 $messages->{'NeedsTransfer'} = $returnbranch;
2127 return ( $doreturn, $messages, $issue, $borrower );
2130 =head2 MarkIssueReturned
2132 MarkIssueReturned($borrowernumber, $itemnumber, $dropbox_branch, $returndate, $privacy);
2134 Unconditionally marks an issue as being returned by
2135 moving the C<issues> row to C<old_issues> and
2136 setting C<returndate> to the current date, or
2137 the last non-holiday date of the branccode specified in
2138 C<dropbox_branch> . Assumes you've already checked that
2139 it's safe to do this, i.e. last non-holiday > issuedate.
2141 if C<$returndate> is specified (in iso format), it is used as the date
2142 of the return. It is ignored when a dropbox_branch is passed in.
2144 C<$privacy> contains the privacy parameter. If the patron has set privacy to 2,
2145 the old_issue is immediately anonymised
2147 Ideally, this function would be internal to C<C4::Circulation>,
2148 not exported, but it is currently needed by one
2149 routine in C<C4::Accounts>.
2153 sub MarkIssueReturned {
2154 my ( $borrowernumber, $itemnumber, $dropbox_branch, $returndate, $privacy ) = @_;
2156 my $anonymouspatron;
2157 if ( $privacy == 2 ) {
2158 # The default of 0 will not work due to foreign key constraints
2159 # The anonymisation will fail if AnonymousPatron is not a valid entry
2160 # We need to check if the anonymous patron exist, Koha will fail loudly if it does not
2161 # Note that a warning should appear on the about page (System information tab).
2162 $anonymouspatron = C4::Context->preference('AnonymousPatron');
2163 die "Fatal error: the patron ($borrowernumber) has requested their circulation history be anonymized on check-in, but the AnonymousPatron system preference is empty or not set correctly."
2164 unless C4::Members::GetMember( borrowernumber => $anonymouspatron );
2166 my $dbh = C4::Context->dbh;
2167 my $query = 'UPDATE issues SET returndate=';
2169 if ($dropbox_branch) {
2170 my $calendar = Koha::Calendar->new( branchcode => $dropbox_branch );
2171 my $dropboxdate = $calendar->addDate( DateTime->now( time_zone => C4::Context->tz), -1 );
2173 push @bind, $dropboxdate->strftime('%Y-%m-%d %H:%M');
2174 } elsif ($returndate) {
2176 push @bind, $returndate;
2178 $query .= ' now() ';
2180 $query .= ' WHERE borrowernumber = ? AND itemnumber = ?';
2181 push @bind, $borrowernumber, $itemnumber;
2183 my $sth_upd = $dbh->prepare($query);
2184 $sth_upd->execute(@bind);
2185 my $sth_copy = $dbh->prepare('INSERT INTO old_issues SELECT * FROM issues
2186 WHERE borrowernumber = ?
2187 AND itemnumber = ?');
2188 $sth_copy->execute($borrowernumber, $itemnumber);
2189 # anonymise patron checkout immediately if $privacy set to 2 and AnonymousPatron is set to a valid borrowernumber
2190 if ( $privacy == 2) {
2191 my $sth_ano = $dbh->prepare("UPDATE old_issues SET borrowernumber=?
2192 WHERE borrowernumber = ?
2193 AND itemnumber = ?");
2194 $sth_ano->execute($anonymouspatron, $borrowernumber, $itemnumber);
2196 my $sth_del = $dbh->prepare("DELETE FROM issues
2197 WHERE borrowernumber = ?
2198 AND itemnumber = ?");
2199 $sth_del->execute($borrowernumber, $itemnumber);
2201 ModItem( { 'onloan' => undef }, undef, $itemnumber );
2204 =head2 _debar_user_on_return
2206 _debar_user_on_return($borrower, $item, $datedue, today);
2208 C<$borrower> borrower hashref
2210 C<$item> item hashref
2212 C<$datedue> date due DateTime object
2214 C<$today> DateTime object representing the return time
2216 Internal function, called only by AddReturn that calculates and updates
2217 the user fine days, and debars him if necessary.
2219 Should only be called for overdue returns
2223 sub _debar_user_on_return {
2224 my ( $borrower, $item, $dt_due, $dt_today ) = @_;
2226 my $branchcode = _GetCircControlBranch( $item, $borrower );
2228 my $circcontrol = C4::Context->preference('CircControl');
2230 GetIssuingRule( $borrower->{categorycode}, $item->{itype}, $branchcode );
2231 my $finedays = $issuingrule->{finedays};
2232 my $unit = $issuingrule->{lengthunit};
2233 my $chargeable_units = C4::Overdues::get_chargeable_units($unit, $dt_due, $dt_today, $branchcode);
2237 # finedays is in days, so hourly loans must multiply by 24
2238 # thus 1 hour late equals 1 day suspension * finedays rate
2239 $finedays = $finedays * 24 if ( $unit eq 'hours' );
2241 # grace period is measured in the same units as the loan
2243 DateTime::Duration->new( $unit => $issuingrule->{firstremind} );
2245 my $deltadays = DateTime::Duration->new(
2246 days => $chargeable_units
2248 if ( $deltadays->subtract($grace)->is_positive() ) {
2249 my $suspension_days = $deltadays * $finedays;
2251 # If the max suspension days is < than the suspension days
2252 # the suspension days is limited to this maximum period.
2253 my $max_sd = $issuingrule->{maxsuspensiondays};
2254 if ( defined $max_sd ) {
2255 $max_sd = DateTime::Duration->new( days => $max_sd );
2256 $suspension_days = $max_sd
2257 if DateTime::Duration->compare( $max_sd, $suspension_days ) < 0;
2261 $dt_today->clone()->add_duration( $suspension_days );
2263 Koha::Borrower::Debarments::AddUniqueDebarment({
2264 borrowernumber => $borrower->{borrowernumber},
2265 expiration => $new_debar_dt->ymd(),
2266 type => 'SUSPENSION',
2268 # if borrower was already debarred but does not get an extra debarment
2269 if ( $borrower->{debarred} eq Koha::Borrower::Debarments::IsDebarred($borrower->{borrowernumber}) ) {
2270 return ($borrower->{debarred},1);
2272 return $new_debar_dt->ymd();
2278 =head2 _FixOverduesOnReturn
2280 &_FixOverduesOnReturn($brn,$itm, $exemptfine, $dropboxmode);
2282 C<$brn> borrowernumber
2286 C<$exemptfine> BOOL -- remove overdue charge associated with this issue.
2287 C<$dropboxmode> BOOL -- remove lastincrement on overdue charge associated with this issue.
2289 Internal function, called only by AddReturn
2293 sub _FixOverduesOnReturn {
2294 my ($borrowernumber, $item);
2295 unless ($borrowernumber = shift) {
2296 warn "_FixOverduesOnReturn() not supplied valid borrowernumber";
2299 unless ($item = shift) {
2300 warn "_FixOverduesOnReturn() not supplied valid itemnumber";
2303 my ($exemptfine, $dropbox) = @_;
2304 my $dbh = C4::Context->dbh;
2306 # check for overdue fine
2307 my $sth = $dbh->prepare(
2308 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
2310 $sth->execute( $borrowernumber, $item );
2312 # alter fine to show that the book has been returned
2313 my $data = $sth->fetchrow_hashref;
2314 return 0 unless $data; # no warning, there's just nothing to fix
2317 my @bind = ($data->{'accountlines_id'});
2319 $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
2320 if (C4::Context->preference("FinesLog")) {
2321 &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
2323 } elsif ($dropbox && $data->{lastincrement}) {
2324 my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
2325 my $amt = $data->{amount} - $data->{lastincrement} ;
2326 if (C4::Context->preference("FinesLog")) {
2327 &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
2329 $uquery = "update accountlines set accounttype='F' ";
2330 if($outstanding >= 0 && $amt >=0) {
2331 $uquery .= ", amount = ? , amountoutstanding=? ";
2332 unshift @bind, ($amt, $outstanding) ;
2335 $uquery = "update accountlines set accounttype='F' ";
2337 $uquery .= " where (accountlines_id = ?)";
2338 my $usth = $dbh->prepare($uquery);
2339 return $usth->execute(@bind);
2342 =head2 _FixAccountForLostAndReturned
2344 &_FixAccountForLostAndReturned($itemnumber, [$borrowernumber, $barcode]);
2346 Calculates the charge for a book lost and returned.
2348 Internal function, not exported, called only by AddReturn.
2350 FIXME: This function reflects how inscrutable fines logic is. Fix both.
2351 FIXME: Give a positive return value on success. It might be the $borrowernumber who received credit, or the amount forgiven.
2355 sub _FixAccountForLostAndReturned {
2356 my $itemnumber = shift or return;
2357 my $borrowernumber = @_ ? shift : undef;
2358 my $item_id = @_ ? shift : $itemnumber; # Send the barcode if you want that logged in the description
2359 my $dbh = C4::Context->dbh;
2360 # check for charge made for lost book
2361 my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE itemnumber = ? AND accounttype IN ('L', 'Rep', 'W') ORDER BY date DESC, accountno DESC");
2362 $sth->execute($itemnumber);
2363 my $data = $sth->fetchrow_hashref;
2364 $data or return; # bail if there is nothing to do
2365 $data->{accounttype} eq 'W' and return; # Written off
2367 # writeoff this amount
2369 my $amount = $data->{'amount'};
2370 my $acctno = $data->{'accountno'};
2371 my $amountleft; # Starts off undef/zero.
2372 if ($data->{'amountoutstanding'} == $amount) {
2373 $offset = $data->{'amount'};
2374 $amountleft = 0; # Hey, it's zero here, too.
2376 $offset = $amount - $data->{'amountoutstanding'}; # Um, isn't this the same as ZERO? We just tested those two things are ==
2377 $amountleft = $data->{'amountoutstanding'} - $amount; # Um, isn't this the same as ZERO? We just tested those two things are ==
2379 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
2380 WHERE (accountlines_id = ?)");
2381 $usth->execute($data->{'accountlines_id'}); # We might be adjusting an account for some OTHER borrowernumber now. Not the one we passed in.
2382 #check if any credit is left if so writeoff other accounts
2383 my $nextaccntno = getnextacctno($data->{'borrowernumber'});
2384 $amountleft *= -1 if ($amountleft < 0);
2385 if ($amountleft > 0) {
2386 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
2387 AND (amountoutstanding >0) ORDER BY date"); # might want to order by amountoustanding ASC (pay smallest first)
2388 $msth->execute($data->{'borrowernumber'});
2389 # offset transactions
2392 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
2393 if ($accdata->{'amountoutstanding'} < $amountleft) {
2395 $amountleft -= $accdata->{'amountoutstanding'};
2397 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
2400 my $thisacct = $accdata->{'accountlines_id'};
2401 # FIXME: move prepares outside while loop!
2402 my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
2403 WHERE (accountlines_id = ?)");
2404 $usth->execute($newamtos,$thisacct);
2405 $usth = $dbh->prepare("INSERT INTO accountoffsets
2406 (borrowernumber, accountno, offsetaccount, offsetamount)
2409 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
2412 $amountleft *= -1 if ($amountleft > 0);
2413 my $desc = "Item Returned " . $item_id;
2414 $usth = $dbh->prepare("INSERT INTO accountlines
2415 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
2416 VALUES (?,?,now(),?,?,'CR',?)");
2417 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
2418 if ($borrowernumber) {
2419 # FIXME: same as query above. use 1 sth for both
2420 $usth = $dbh->prepare("INSERT INTO accountoffsets
2421 (borrowernumber, accountno, offsetaccount, offsetamount)
2423 $usth->execute($borrowernumber, $data->{'accountno'}, $nextaccntno, $offset);
2425 ModItem({ paidfor => '' }, undef, $itemnumber);
2429 =head2 _GetCircControlBranch
2431 my $circ_control_branch = _GetCircControlBranch($iteminfos, $borrower);
2435 Return the library code to be used to determine which circulation
2436 policy applies to a transaction. Looks up the CircControl and
2437 HomeOrHoldingBranch system preferences.
2439 C<$iteminfos> is a hashref to iteminfo. Only {homebranch or holdingbranch} is used.
2441 C<$borrower> is a hashref to borrower. Only {branchcode} is used.
2445 sub _GetCircControlBranch {
2446 my ($item, $borrower) = @_;
2447 my $circcontrol = C4::Context->preference('CircControl');
2450 if ($circcontrol eq 'PickupLibrary' and (C4::Context->userenv and C4::Context->userenv->{'branch'}) ) {
2451 $branch= C4::Context->userenv->{'branch'};
2452 } elsif ($circcontrol eq 'PatronLibrary') {
2453 $branch=$borrower->{branchcode};
2455 my $branchfield = C4::Context->preference('HomeOrHoldingBranch') || 'homebranch';
2456 $branch = $item->{$branchfield};
2457 # default to item home branch if holdingbranch is used
2458 # and is not defined
2459 if (!defined($branch) && $branchfield eq 'holdingbranch') {
2460 $branch = $item->{homebranch};
2473 $issue = &GetItemIssue($itemnumber);
2475 Returns patron currently having a book, or undef if not checked out.
2477 C<$itemnumber> is the itemnumber.
2479 C<$issue> is a hashref of the row from the issues table.
2484 my ($itemnumber) = @_;
2485 return unless $itemnumber;
2486 my $sth = C4::Context->dbh->prepare(
2487 "SELECT items.*, issues.*
2489 LEFT JOIN items ON issues.itemnumber=items.itemnumber
2490 WHERE issues.itemnumber=?");
2491 $sth->execute($itemnumber);
2492 my $data = $sth->fetchrow_hashref;
2493 return unless $data;
2494 $data->{issuedate_sql} = $data->{issuedate};
2495 $data->{date_due_sql} = $data->{date_due};
2496 $data->{issuedate} = dt_from_string($data->{issuedate}, 'sql');
2497 $data->{issuedate}->truncate(to => 'minute');
2498 $data->{date_due} = dt_from_string($data->{date_due}, 'sql');
2499 $data->{date_due}->truncate(to => 'minute');
2500 my $dt = DateTime->now( time_zone => C4::Context->tz)->truncate( to => 'minute');
2501 $data->{'overdue'} = DateTime->compare($data->{'date_due'}, $dt ) == -1 ? 1 : 0;
2507 $issue = GetOpenIssue( $itemnumber );
2509 Returns the row from the issues table if the item is currently issued, undef if the item is not currently issued
2511 C<$itemnumber> is the item's itemnumber
2518 my ( $itemnumber ) = @_;
2519 return unless $itemnumber;
2520 my $dbh = C4::Context->dbh;
2521 my $sth = $dbh->prepare( "SELECT * FROM issues WHERE itemnumber = ? AND returndate IS NULL" );
2522 $sth->execute( $itemnumber );
2523 return $sth->fetchrow_hashref();
2529 $issues = GetIssues({}); # return all issues!
2530 $issues = GetIssues({ borrowernumber => $borrowernumber, biblionumber => $biblionumber });
2532 Returns all pending issues that match given criteria.
2533 Returns a arrayref or undef if an error occurs.
2535 Allowed criteria are:
2539 =item * borrowernumber
2541 =item * biblionumber
2550 my ($criteria) = @_;
2554 my @allowed = qw(borrowernumber biblionumber itemnumber);
2555 foreach (@allowed) {
2556 if (defined $criteria->{$_}) {
2559 value => $criteria->{$_},
2564 # Do we need to join other tables ?
2566 if (defined $criteria->{biblionumber}) {
2573 $where = "WHERE " . join(' AND ', map { "$_->{field} = ?" } @filters);
2579 if (defined $join{items}) {
2581 LEFT JOIN items ON (issues.itemnumber = items.itemnumber)
2587 my $dbh = C4::Context->dbh;
2588 my $sth = $dbh->prepare($query);
2589 my $rv = $sth->execute(map { $_->{value} } @filters);
2591 return $rv ? $sth->fetchall_arrayref({}) : undef;
2594 =head2 GetItemIssues
2596 $issues = &GetItemIssues($itemnumber, $history);
2598 Returns patrons that have issued a book
2600 C<$itemnumber> is the itemnumber
2601 C<$history> is false if you just want the current "issuer" (if any)
2602 and true if you want issues history from old_issues also.
2604 Returns reference to an array of hashes
2609 my ( $itemnumber, $history ) = @_;
2611 my $today = DateTime->now( time_zome => C4::Context->tz); # get today date
2612 $today->truncate( to => 'minute' );
2613 my $sql = "SELECT * FROM issues
2614 JOIN borrowers USING (borrowernumber)
2615 JOIN items USING (itemnumber)
2616 WHERE issues.itemnumber = ? ";
2619 SELECT * FROM old_issues
2620 LEFT JOIN borrowers USING (borrowernumber)
2621 JOIN items USING (itemnumber)
2622 WHERE old_issues.itemnumber = ? ";
2624 $sql .= "ORDER BY date_due DESC";
2625 my $sth = C4::Context->dbh->prepare($sql);
2627 $sth->execute($itemnumber, $itemnumber);
2629 $sth->execute($itemnumber);
2631 my $results = $sth->fetchall_arrayref({});
2632 foreach (@$results) {
2633 my $date_due = dt_from_string($_->{date_due},'sql');
2634 $date_due->truncate( to => 'minute' );
2636 $_->{overdue} = (DateTime->compare($date_due, $today) == -1) ? 1 : 0;
2641 =head2 GetBiblioIssues
2643 $issues = GetBiblioIssues($biblionumber);
2645 this function get all issues from a biblionumber.
2648 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
2649 tables issues and the firstname,surname & cardnumber from borrowers.
2653 sub GetBiblioIssues {
2654 my $biblionumber = shift;
2655 return unless $biblionumber;
2656 my $dbh = C4::Context->dbh;
2658 SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
2660 LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
2661 LEFT JOIN items ON issues.itemnumber = items.itemnumber
2662 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
2663 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
2664 WHERE biblio.biblionumber = ?
2666 SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
2668 LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
2669 LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
2670 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
2671 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
2672 WHERE biblio.biblionumber = ?
2675 my $sth = $dbh->prepare($query);
2676 $sth->execute($biblionumber, $biblionumber);
2679 while ( my $data = $sth->fetchrow_hashref ) {
2680 push @issues, $data;
2685 =head2 GetUpcomingDueIssues
2687 my $upcoming_dues = GetUpcomingDueIssues( { days_in_advance => 4 } );
2691 sub GetUpcomingDueIssues {
2694 $params->{'days_in_advance'} = 7 unless exists $params->{'days_in_advance'};
2695 my $dbh = C4::Context->dbh;
2697 my $statement = <<END_SQL;
2698 SELECT issues.*, items.itype as itemtype, items.homebranch, TO_DAYS( date_due )-TO_DAYS( NOW() ) as days_until_due, branches.branchemail
2700 LEFT JOIN items USING (itemnumber)
2701 LEFT OUTER JOIN branches USING (branchcode)
2702 WHERE returndate is NULL
2703 HAVING days_until_due >= 0 AND days_until_due <= ?
2706 my @bind_parameters = ( $params->{'days_in_advance'} );
2708 my $sth = $dbh->prepare( $statement );
2709 $sth->execute( @bind_parameters );
2710 my $upcoming_dues = $sth->fetchall_arrayref({});
2712 return $upcoming_dues;
2715 =head2 CanBookBeRenewed
2717 ($ok,$error) = &CanBookBeRenewed($borrowernumber, $itemnumber[, $override_limit]);
2719 Find out whether a borrowed item may be renewed.
2721 C<$borrowernumber> is the borrower number of the patron who currently
2722 has the item on loan.
2724 C<$itemnumber> is the number of the item to renew.
2726 C<$override_limit>, if supplied with a true value, causes
2727 the limit on the number of times that the loan can be renewed
2728 (as controlled by the item type) to be ignored. Overriding also allows
2729 to renew sooner than "No renewal before" and to manually renew loans
2730 that are automatically renewed.
2732 C<$CanBookBeRenewed> returns a true value if the item may be renewed. The
2733 item must currently be on loan to the specified borrower; renewals
2734 must be allowed for the item's type; and the borrower must not have
2735 already renewed the loan. $error will contain the reason the renewal can not proceed
2739 sub CanBookBeRenewed {
2740 my ( $borrowernumber, $itemnumber, $override_limit ) = @_;
2742 my $dbh = C4::Context->dbh;
2745 my $item = GetItem($itemnumber) or return ( 0, 'no_item' );
2746 my $itemissue = GetItemIssue($itemnumber) or return ( 0, 'no_checkout' );
2747 return ( 0, 'onsite_checkout' ) if $itemissue->{onsite_checkout};
2749 $borrowernumber ||= $itemissue->{borrowernumber};
2750 my $borrower = C4::Members::GetMember( borrowernumber => $borrowernumber )
2753 my ( $resfound, $resrec, undef ) = C4::Reserves::CheckReserves($itemnumber);
2755 # This item can fill one or more unfilled reserve, can those unfilled reserves
2756 # all be filled by other available items?
2758 && C4::Context->preference('AllowRenewalIfOtherItemsAvailable') )
2760 my $schema = Koha::Database->new()->schema();
2762 my $item_holds = $schema->resultset('Reserve')->search( { itemnumber => $itemnumber, found => undef } )->count();
2764 # There is an item level hold on this item, no other item can fill the hold
2769 # Get all other items that could possibly fill reserves
2770 my @itemnumbers = $schema->resultset('Item')->search(
2772 biblionumber => $resrec->{biblionumber},
2775 -not => { itemnumber => $itemnumber }
2777 { columns => 'itemnumber' }
2778 )->get_column('itemnumber')->all();
2780 # Get all other reserves that could have been filled by this item
2781 my @borrowernumbers;
2783 my ( $reserve_found, $reserve, undef ) =
2784 C4::Reserves::CheckReserves( $itemnumber, undef, undef, \@borrowernumbers );
2786 if ($reserve_found) {
2787 push( @borrowernumbers, $reserve->{borrowernumber} );
2794 # If the count of the union of the lists of reservable items for each borrower
2795 # is equal or greater than the number of borrowers, we know that all reserves
2796 # can be filled with available items. We can get the union of the sets simply
2797 # by pushing all the elements onto an array and removing the duplicates.
2799 foreach my $b (@borrowernumbers) {
2800 my ($borr) = C4::Members::GetMemberDetails($b);
2801 foreach my $i (@itemnumbers) {
2802 my $item = GetItem($i);
2803 if ( IsAvailableForItemLevelRequest( $item, $borr )
2804 && CanItemBeReserved( $b, $i )
2805 && !IsItemOnHoldAndFound($i) )
2807 push( @reservable, $i );
2812 @reservable = uniq(@reservable);
2814 if ( @reservable >= @borrowernumbers ) {
2819 return ( 0, "on_reserve" ) if $resfound; # '' when no hold was found
2821 return ( 1, undef ) if $override_limit;
2823 my $branchcode = _GetCircControlBranch( $item, $borrower );
2825 GetIssuingRule( $borrower->{categorycode}, $item->{itype}, $branchcode );
2827 return ( 0, "too_many" )
2828 if $issuingrule->{renewalsallowed} <= $itemissue->{renewals};
2830 my $overduesblockrenewing = C4::Context->preference('OverduesBlockRenewing');
2831 my $restrictionblockrenewing = C4::Context->preference('RestrictionBlockRenewing');
2832 my $restricted = Koha::Borrower::Debarments::IsDebarred($borrowernumber);
2833 my $hasoverdues = C4::Members::HasOverdues($borrowernumber);
2835 if ( $restricted and $restrictionblockrenewing ) {
2836 return ( 0, 'restriction');
2837 } elsif ( ($hasoverdues and $overduesblockrenewing eq 'block') || ($itemissue->{overdue} and $overduesblockrenewing eq 'blockitem') ) {
2838 return ( 0, 'overdue');
2841 if ( defined $issuingrule->{norenewalbefore}
2842 and $issuingrule->{norenewalbefore} ne "" )
2845 # Get current time and add norenewalbefore.
2846 # If this is smaller than date_due, it's too soon for renewal.
2847 my $now = dt_from_string;
2850 $issuingrule->{lengthunit} => $issuingrule->{norenewalbefore}
2851 ) < $itemissue->{date_due}
2854 return ( 0, "auto_too_soon" ) if $itemissue->{auto_renew};
2855 return ( 0, "too_soon" );
2857 elsif ( $itemissue->{auto_renew} ) {
2858 return ( 0, "auto_renew" );
2862 # Fallback for automatic renewals:
2863 # If norenewalbefore is undef, don't renew before due date.
2864 elsif ( $itemissue->{auto_renew} ) {
2865 my $now = dt_from_string;
2866 return ( 0, "auto_renew" )
2867 if $now >= $itemissue->{date_due};
2868 return ( 0, "auto_too_soon" );
2871 return ( 1, undef );
2876 &AddRenewal($borrowernumber, $itemnumber, $branch, [$datedue], [$lastreneweddate]);
2880 C<$borrowernumber> is the borrower number of the patron who currently
2883 C<$itemnumber> is the number of the item to renew.
2885 C<$branch> is the library where the renewal took place (if any).
2886 The library that controls the circ policies for the renewal is retrieved from the issues record.
2888 C<$datedue> can be a DateTime object used to set the due date.
2890 C<$lastreneweddate> is an optional ISO-formatted date used to set issues.lastreneweddate. If
2891 this parameter is not supplied, lastreneweddate is set to the current date.
2893 If C<$datedue> is the empty string, C<&AddRenewal> will calculate the due date automatically
2894 from the book's item type.
2899 my $borrowernumber = shift;
2900 my $itemnumber = shift or return;
2902 my $datedue = shift;
2903 my $lastreneweddate = shift || DateTime->now(time_zone => C4::Context->tz)->ymd();
2905 my $item = GetItem($itemnumber) or return;
2906 my $biblio = GetBiblioFromItemNumber($itemnumber) or return;
2908 my $dbh = C4::Context->dbh;
2910 # Find the issues record for this book
2912 $dbh->prepare("SELECT * FROM issues WHERE itemnumber = ?");
2913 $sth->execute( $itemnumber );
2914 my $issuedata = $sth->fetchrow_hashref;
2916 return unless ( $issuedata );
2918 $borrowernumber ||= $issuedata->{borrowernumber};
2920 if ( defined $datedue && ref $datedue ne 'DateTime' ) {
2921 carp 'Invalid date passed to AddRenewal.';
2925 # If the due date wasn't specified, calculate it by adding the
2926 # book's loan length to today's date or the current due date
2927 # based on the value of the RenewalPeriodBase syspref.
2930 my $borrower = C4::Members::GetMember( borrowernumber => $borrowernumber ) or return;
2931 my $itemtype = (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'};
2933 $datedue = (C4::Context->preference('RenewalPeriodBase') eq 'date_due') ?
2934 dt_from_string( $issuedata->{date_due} ) :
2935 DateTime->now( time_zone => C4::Context->tz());
2936 $datedue = CalcDateDue($datedue, $itemtype, $issuedata->{'branchcode'}, $borrower, 'is a renewal');
2939 # Update the issues record to have the new due date, and a new count
2940 # of how many times it has been renewed.
2941 my $renews = $issuedata->{'renewals'} + 1;
2942 $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?, lastreneweddate = ?
2943 WHERE borrowernumber=?
2947 $sth->execute( $datedue->strftime('%Y-%m-%d %H:%M'), $renews, $lastreneweddate, $borrowernumber, $itemnumber );
2949 # Update the renewal count on the item, and tell zebra to reindex
2950 $renews = $biblio->{'renewals'} + 1;
2951 ModItem({ renewals => $renews, onloan => $datedue->strftime('%Y-%m-%d %H:%M')}, $biblio->{'biblionumber'}, $itemnumber);
2953 # Charge a new rental fee, if applicable?
2954 my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2955 if ( $charge > 0 ) {
2956 my $accountno = getnextacctno( $borrowernumber );
2957 my $item = GetBiblioFromItemNumber($itemnumber);
2959 $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
2960 $sth = $dbh->prepare(
2961 "INSERT INTO accountlines
2962 (date, borrowernumber, accountno, amount, manager_id,
2963 description,accounttype, amountoutstanding, itemnumber)
2964 VALUES (now(),?,?,?,?,?,?,?,?)"
2966 $sth->execute( $borrowernumber, $accountno, $charge, $manager_id,
2967 "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
2968 'Rent', $charge, $itemnumber );
2971 # Send a renewal slip according to checkout alert preferencei
2972 if ( C4::Context->preference('RenewalSendNotice') eq '1') {
2973 my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 );
2974 my $circulation_alert = 'C4::ItemCirculationAlertPreference';
2976 branchcode => $branch,
2977 categorycode => $borrower->{categorycode},
2978 item_type => $item->{itype},
2979 notification => 'CHECKOUT',
2981 if ($circulation_alert->is_enabled_for(\%conditions)) {
2982 SendCirculationAlert({
2985 borrower => $borrower,
2991 # Remove any OVERDUES related debarment if the borrower has no overdues
2992 my $borrower = C4::Members::GetMember( borrowernumber => $borrowernumber );
2993 if ( $borrowernumber
2994 && $borrower->{'debarred'}
2995 && !C4::Members::HasOverdues( $borrowernumber )
2996 && @{ GetDebarments({ borrowernumber => $borrowernumber, type => 'OVERDUES' }) }
2998 DelUniqueDebarment({ borrowernumber => $borrowernumber, type => 'OVERDUES' });
3002 UpdateStats({branch => $branch,
3005 itemnumber => $itemnumber,
3006 itemtype => $item->{itype},
3007 borrowernumber => $borrowernumber,
3008 ccode => $item->{'ccode'}}
3014 # check renewal status
3015 my ( $bornum, $itemno ) = @_;
3016 my $dbh = C4::Context->dbh;
3018 my $renewsallowed = 0;
3021 my $borrower = C4::Members::GetMember( borrowernumber => $bornum);
3022 my $item = GetItem($itemno);
3024 # Look in the issues table for this item, lent to this borrower,
3025 # and not yet returned.
3027 # FIXME - I think this function could be redone to use only one SQL call.
3028 my $sth = $dbh->prepare(
3029 "select * from issues
3030 where (borrowernumber = ?)
3031 and (itemnumber = ?)"
3033 $sth->execute( $bornum, $itemno );
3034 my $data = $sth->fetchrow_hashref;
3035 $renewcount = $data->{'renewals'} if $data->{'renewals'};
3036 # $item and $borrower should be calculated
3037 my $branchcode = _GetCircControlBranch($item, $borrower);
3039 my $issuingrule = GetIssuingRule($borrower->{categorycode}, $item->{itype}, $branchcode);
3041 $renewsallowed = $issuingrule->{'renewalsallowed'};
3042 $renewsleft = $renewsallowed - $renewcount;
3043 if($renewsleft < 0){ $renewsleft = 0; }
3044 return ( $renewcount, $renewsallowed, $renewsleft );
3047 =head2 GetSoonestRenewDate
3049 $NoRenewalBeforeThisDate = &GetSoonestRenewDate($borrowernumber, $itemnumber);
3051 Find out the soonest possible renew date of a borrowed item.
3053 C<$borrowernumber> is the borrower number of the patron who currently
3054 has the item on loan.
3056 C<$itemnumber> is the number of the item to renew.
3058 C<$GetSoonestRenewDate> returns the DateTime of the soonest possible
3059 renew date, based on the value "No renewal before" of the applicable
3060 issuing rule. Returns the current date if the item can already be
3061 renewed, and returns undefined if the borrower, loan, or item
3066 sub GetSoonestRenewDate {
3067 my ( $borrowernumber, $itemnumber ) = @_;
3069 my $dbh = C4::Context->dbh;
3071 my $item = GetItem($itemnumber) or return;
3072 my $itemissue = GetItemIssue($itemnumber) or return;
3074 $borrowernumber ||= $itemissue->{borrowernumber};
3075 my $borrower = C4::Members::GetMemberDetails($borrowernumber)
3078 my $branchcode = _GetCircControlBranch( $item, $borrower );
3080 GetIssuingRule( $borrower->{categorycode}, $item->{itype}, $branchcode );
3082 my $now = dt_from_string;
3084 if ( defined $issuingrule->{norenewalbefore}
3085 and $issuingrule->{norenewalbefore} ne "" )
3087 my $soonestrenewal =
3088 $itemissue->{date_due}->subtract(
3089 $issuingrule->{lengthunit} => $issuingrule->{norenewalbefore} );
3091 $soonestrenewal = $now > $soonestrenewal ? $now : $soonestrenewal;
3092 return $soonestrenewal;
3097 =head2 GetIssuingCharges
3099 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
3101 Calculate how much it would cost for a given patron to borrow a given
3102 item, including any applicable discounts.
3104 C<$itemnumber> is the item number of item the patron wishes to borrow.
3106 C<$borrowernumber> is the patron's borrower number.
3108 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
3109 and C<$item_type> is the code for the item's item type (e.g., C<VID>
3114 sub GetIssuingCharges {
3116 # calculate charges due
3117 my ( $itemnumber, $borrowernumber ) = @_;
3119 my $dbh = C4::Context->dbh;
3122 # Get the book's item type and rental charge (via its biblioitem).
3123 my $charge_query = 'SELECT itemtypes.itemtype,rentalcharge FROM items
3124 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber';
3125 $charge_query .= (C4::Context->preference('item-level_itypes'))
3126 ? ' LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype'
3127 : ' LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype';
3129 $charge_query .= ' WHERE items.itemnumber =?';
3131 my $sth = $dbh->prepare($charge_query);
3132 $sth->execute($itemnumber);
3133 if ( my $item_data = $sth->fetchrow_hashref ) {
3134 $item_type = $item_data->{itemtype};
3135 $charge = $item_data->{rentalcharge};
3136 my $branch = C4::Branch::mybranch();
3137 my $discount_query = q|SELECT rentaldiscount,
3138 issuingrules.itemtype, issuingrules.branchcode
3140 LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
3141 WHERE borrowers.borrowernumber = ?
3142 AND (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
3143 AND (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')|;
3144 my $discount_sth = $dbh->prepare($discount_query);
3145 $discount_sth->execute( $borrowernumber, $item_type, $branch );
3146 my $discount_rules = $discount_sth->fetchall_arrayref({});
3147 if (@{$discount_rules}) {
3148 # We may have multiple rules so get the most specific
3149 my $discount = _get_discount_from_rule($discount_rules, $branch, $item_type);
3150 $charge = ( $charge * ( 100 - $discount ) ) / 100;
3154 return ( $charge, $item_type );
3157 # Select most appropriate discount rule from those returned
3158 sub _get_discount_from_rule {
3159 my ($rules_ref, $branch, $itemtype) = @_;
3162 if (@{$rules_ref} == 1) { # only 1 applicable rule use it
3163 $discount = $rules_ref->[0]->{rentaldiscount};
3164 return (defined $discount) ? $discount : 0;
3166 # could have up to 4 does one match $branch and $itemtype
3167 my @d = grep { $_->{branchcode} eq $branch && $_->{itemtype} eq $itemtype } @{$rules_ref};
3169 $discount = $d[0]->{rentaldiscount};
3170 return (defined $discount) ? $discount : 0;
3172 # do we have item type + all branches
3173 @d = grep { $_->{branchcode} eq q{*} && $_->{itemtype} eq $itemtype } @{$rules_ref};
3175 $discount = $d[0]->{rentaldiscount};
3176 return (defined $discount) ? $discount : 0;
3178 # do we all item types + this branch
3179 @d = grep { $_->{branchcode} eq $branch && $_->{itemtype} eq q{*} } @{$rules_ref};
3181 $discount = $d[0]->{rentaldiscount};
3182 return (defined $discount) ? $discount : 0;
3184 # so all and all (surely we wont get here)
3185 @d = grep { $_->{branchcode} eq q{*} && $_->{itemtype} eq q{*} } @{$rules_ref};
3187 $discount = $d[0]->{rentaldiscount};
3188 return (defined $discount) ? $discount : 0;
3194 =head2 AddIssuingCharge
3196 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
3200 sub AddIssuingCharge {
3201 my ( $itemnumber, $borrowernumber, $charge ) = @_;
3202 my $dbh = C4::Context->dbh;
3203 my $nextaccntno = getnextacctno( $borrowernumber );
3205 $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
3207 INSERT INTO accountlines
3208 (borrowernumber, itemnumber, accountno,
3209 date, amount, description, accounttype,
3210 amountoutstanding, manager_id)
3211 VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?,?)
3213 my $sth = $dbh->prepare($query);
3214 $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge, $manager_id );
3219 GetTransfers($itemnumber);
3224 my ($itemnumber) = @_;
3226 my $dbh = C4::Context->dbh;
3232 FROM branchtransfers
3233 WHERE itemnumber = ?
3234 AND datearrived IS NULL
3236 my $sth = $dbh->prepare($query);
3237 $sth->execute($itemnumber);
3238 my @row = $sth->fetchrow_array();
3242 =head2 GetTransfersFromTo
3244 @results = GetTransfersFromTo($frombranch,$tobranch);
3246 Returns the list of pending transfers between $from and $to branch
3250 sub GetTransfersFromTo {
3251 my ( $frombranch, $tobranch ) = @_;
3252 return unless ( $frombranch && $tobranch );
3253 my $dbh = C4::Context->dbh;
3255 SELECT itemnumber,datesent,frombranch
3256 FROM branchtransfers
3259 AND datearrived IS NULL
3261 my $sth = $dbh->prepare($query);
3262 $sth->execute( $frombranch, $tobranch );
3265 while ( my $data = $sth->fetchrow_hashref ) {
3266 push @gettransfers, $data;
3268 return (@gettransfers);
3271 =head2 DeleteTransfer
3273 &DeleteTransfer($itemnumber);
3277 sub DeleteTransfer {
3278 my ($itemnumber) = @_;
3279 return unless $itemnumber;
3280 my $dbh = C4::Context->dbh;
3281 my $sth = $dbh->prepare(
3282 "DELETE FROM branchtransfers
3284 AND datearrived IS NULL "
3286 return $sth->execute($itemnumber);
3289 =head2 AnonymiseIssueHistory
3291 ($rows,$err_history_not_deleted) = AnonymiseIssueHistory($date,$borrowernumber)
3293 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
3294 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
3296 If c<$borrowernumber> is set, it will delete issue history for only that borrower, regardless of their opac privacy
3297 setting (force delete).
3299 return the number of affected rows and a value that evaluates to true if an error occurred deleting the history.
3303 sub AnonymiseIssueHistory {
3305 my $borrowernumber = shift;
3306 my $dbh = C4::Context->dbh;
3309 SET borrowernumber = ?
3310 WHERE returndate < ?
3311 AND borrowernumber IS NOT NULL
3314 # The default of 0 does not work due to foreign key constraints
3315 # The anonymisation should not fail quietly if AnonymousPatron is not a valid entry
3316 # Set it to undef (NULL)
3317 my $anonymouspatron = C4::Context->preference('AnonymousPatron') || undef;
3318 my @bind_params = ($anonymouspatron, $date);
3319 if (defined $borrowernumber) {
3320 $query .= " AND borrowernumber = ?";
3321 push @bind_params, $borrowernumber;
3323 $query .= " AND (SELECT privacy FROM borrowers WHERE borrowers.borrowernumber=old_issues.borrowernumber) <> 0";
3325 my $sth = $dbh->prepare($query);
3326 $sth->execute(@bind_params);
3327 my $anonymisation_err = $dbh->err;
3328 my $rows_affected = $sth->rows; ### doublecheck row count return function
3329 return ($rows_affected, $anonymisation_err);
3332 =head2 SendCirculationAlert
3334 Send out a C<check-in> or C<checkout> alert using the messaging system.
3342 Valid values for this parameter are: C<CHECKIN> and C<CHECKOUT>.
3346 Hashref of information about the item being checked in or out.
3350 Hashref of information about the borrower of the item.
3354 The branchcode from where the checkout or check-in took place.
3360 SendCirculationAlert({
3363 borrower => $borrower,
3369 sub SendCirculationAlert {
3371 my ($type, $item, $borrower, $branch) =
3372 ($opts->{type}, $opts->{item}, $opts->{borrower}, $opts->{branch});
3373 my %message_name = (
3374 CHECKIN => 'Item_Check_in',
3375 CHECKOUT => 'Item_Checkout',
3376 RENEWAL => 'Item_Checkout',
3378 my $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences({
3379 borrowernumber => $borrower->{borrowernumber},
3380 message_name => $message_name{$type},
3382 my $issues_table = ( $type eq 'CHECKOUT' || $type eq 'RENEWAL' ) ? 'issues' : 'old_issues';
3384 my @transports = keys %{ $borrower_preferences->{transports} };
3385 # warn "no transports" unless @transports;
3387 # warn "transport: $_";
3388 my $message = C4::Message->find_last_message($borrower, $type, $_);
3390 #warn "create new message";
3391 my $letter = C4::Letters::GetPreparedLetter (
3392 module => 'circulation',
3393 letter_code => $type,
3394 branchcode => $branch,
3395 message_transport_type => $_,
3397 $issues_table => $item->{itemnumber},
3398 'items' => $item->{itemnumber},
3399 'biblio' => $item->{biblionumber},
3400 'biblioitems' => $item->{biblionumber},
3401 'borrowers' => $borrower,
3402 'branches' => $branch,
3405 C4::Message->enqueue($letter, $borrower, $_);
3407 #warn "append to old message";
3408 my $letter = C4::Letters::GetPreparedLetter (
3409 module => 'circulation',
3410 letter_code => $type,
3411 branchcode => $branch,
3412 message_transport_type => $_,
3414 $issues_table => $item->{itemnumber},
3415 'items' => $item->{itemnumber},
3416 'biblio' => $item->{biblionumber},
3417 'biblioitems' => $item->{biblionumber},
3418 'borrowers' => $borrower,
3419 'branches' => $branch,
3422 $message->append($letter);
3430 =head2 updateWrongTransfer
3432 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
3434 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
3438 sub updateWrongTransfer {
3439 my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
3440 my $dbh = C4::Context->dbh;
3441 # first step validate the actual line of transfert .
3444 "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
3446 $sth->execute($FromLibrary,$itemNumber);
3448 # second step create a new line of branchtransfer to the right location .
3449 ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
3451 #third step changing holdingbranch of item
3452 UpdateHoldingbranch($FromLibrary,$itemNumber);
3455 =head2 UpdateHoldingbranch
3457 $items = UpdateHoldingbranch($branch,$itmenumber);
3459 Simple methode for updating hodlingbranch in items BDD line
3463 sub UpdateHoldingbranch {
3464 my ( $branch,$itemnumber ) = @_;
3465 ModItem({ holdingbranch => $branch }, undef, $itemnumber);
3470 $newdatedue = CalcDateDue($startdate,$itemtype,$branchcode,$borrower);
3472 this function calculates the due date given the start date and configured circulation rules,
3473 checking against the holidays calendar as per the 'useDaysMode' syspref.
3474 C<$startdate> = DateTime object representing start date of loan period (assumed to be today)
3475 C<$itemtype> = itemtype code of item in question
3476 C<$branch> = location whose calendar to use
3477 C<$borrower> = Borrower object
3478 C<$isrenewal> = Boolean: is true if we want to calculate the date due for a renewal. Else is false.
3483 my ( $startdate, $itemtype, $branch, $borrower, $isrenewal ) = @_;
3487 # loanlength now a href
3489 GetLoanLength( $borrower->{'categorycode'}, $itemtype, $branch );
3491 my $length_key = ( $isrenewal and defined $loanlength->{renewalperiod} )
3497 if (ref $startdate ne 'DateTime' ) {
3498 $datedue = dt_from_string($datedue);
3500 $datedue = $startdate->clone;
3504 DateTime->now( time_zone => C4::Context->tz() )
3505 ->truncate( to => 'minute' );
3509 # calculate the datedue as normal
3510 if ( C4::Context->preference('useDaysMode') eq 'Days' )
3511 { # ignoring calendar
3512 if ( $loanlength->{lengthunit} eq 'hours' ) {
3513 $datedue->add( hours => $loanlength->{$length_key} );
3515 $datedue->add( days => $loanlength->{$length_key} );
3516 $datedue->set_hour(23);
3517 $datedue->set_minute(59);
3521 if ($loanlength->{lengthunit} eq 'hours') {
3522 $dur = DateTime::Duration->new( hours => $loanlength->{$length_key});
3525 $dur = DateTime::Duration->new( days => $loanlength->{$length_key});
3527 my $calendar = Koha::Calendar->new( branchcode => $branch );
3528 $datedue = $calendar->addDate( $datedue, $dur, $loanlength->{lengthunit} );
3529 if ($loanlength->{lengthunit} eq 'days') {
3530 $datedue->set_hour(23);
3531 $datedue->set_minute(59);
3535 # if Hard Due Dates are used, retrieve them and apply as necessary
3536 my ( $hardduedate, $hardduedatecompare ) =
3537 GetHardDueDate( $borrower->{'categorycode'}, $itemtype, $branch );
3538 if ($hardduedate) { # hardduedates are currently dates
3539 $hardduedate->truncate( to => 'minute' );
3540 $hardduedate->set_hour(23);
3541 $hardduedate->set_minute(59);
3542 my $cmp = DateTime->compare( $hardduedate, $datedue );
3544 # if the calculated due date is after the 'before' Hard Due Date (ceiling), override
3545 # if the calculated date is before the 'after' Hard Due Date (floor), override
3546 # if the hard due date is set to 'exactly', overrride
3547 if ( $hardduedatecompare == 0 || $hardduedatecompare == $cmp ) {
3548 $datedue = $hardduedate->clone;
3551 # in all other cases, keep the date due as it is
3555 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
3556 if ( C4::Context->preference('ReturnBeforeExpiry') ) {
3557 my $expiry_dt = dt_from_string( $borrower->{dateexpiry}, 'iso', 'floating');
3558 if( $expiry_dt ) { #skip empty expiry date..
3559 $expiry_dt->set( hour => 23, minute => 59);
3560 my $d1= $datedue->clone->set_time_zone('floating');
3561 if ( DateTime->compare( $d1, $expiry_dt ) == 1 ) {
3562 $datedue = $expiry_dt->clone->set_time_zone( C4::Context->tz );
3571 sub CheckValidBarcode{
3573 my $dbh = C4::Context->dbh;
3574 my $query=qq|SELECT count(*)
3578 my $sth = $dbh->prepare($query);
3579 $sth->execute($barcode);
3580 my $exist=$sth->fetchrow ;
3584 =head2 IsBranchTransferAllowed
3586 $allowed = IsBranchTransferAllowed( $toBranch, $fromBranch, $code );
3588 Code is either an itemtype or collection doe depending on the pref BranchTransferLimitsType
3592 sub IsBranchTransferAllowed {
3593 my ( $toBranch, $fromBranch, $code ) = @_;
3595 if ( $toBranch eq $fromBranch ) { return 1; } ## Short circuit for speed.
3597 my $limitType = C4::Context->preference("BranchTransferLimitsType");
3598 my $dbh = C4::Context->dbh;
3600 my $sth = $dbh->prepare("SELECT * FROM branch_transfer_limits WHERE toBranch = ? AND fromBranch = ? AND $limitType = ?");
3601 $sth->execute( $toBranch, $fromBranch, $code );
3602 my $limit = $sth->fetchrow_hashref();
3604 ## If a row is found, then that combination is not allowed, if no matching row is found, then the combination *is allowed*
3605 if ( $limit->{'limitId'} ) {
3612 =head2 CreateBranchTransferLimit
3614 CreateBranchTransferLimit( $toBranch, $fromBranch, $code );
3616 $code is either itemtype or collection code depending on what the pref BranchTransferLimitsType is set to.
3620 sub CreateBranchTransferLimit {
3621 my ( $toBranch, $fromBranch, $code ) = @_;
3622 return unless defined($toBranch) && defined($fromBranch);
3623 my $limitType = C4::Context->preference("BranchTransferLimitsType");
3625 my $dbh = C4::Context->dbh;
3627 my $sth = $dbh->prepare("INSERT INTO branch_transfer_limits ( $limitType, toBranch, fromBranch ) VALUES ( ?, ?, ? )");
3628 return $sth->execute( $code, $toBranch, $fromBranch );
3631 =head2 DeleteBranchTransferLimits
3633 my $result = DeleteBranchTransferLimits($frombranch);
3635 Deletes all the library transfer limits for one library. Returns the
3636 number of limits deleted, 0e0 if no limits were deleted, or undef if
3637 no arguments are supplied.
3641 sub DeleteBranchTransferLimits {
3643 return unless defined $branch;
3644 my $dbh = C4::Context->dbh;
3645 my $sth = $dbh->prepare("DELETE FROM branch_transfer_limits WHERE fromBranch = ?");
3646 return $sth->execute($branch);
3650 my ( $borrowernumber, $itemnum ) = @_;
3652 MarkIssueReturned( $borrowernumber, $itemnum );
3653 my $borrower = C4::Members::GetMember( 'borrowernumber'=>$borrowernumber );
3654 my $item = C4::Items::GetItem( $itemnum );
3655 my $old_note = ($item->{'paidfor'} && ($item->{'paidfor'} ne q{})) ? $item->{'paidfor'}.' / ' : q{};
3656 my @datearr = localtime(time);
3657 my $date = ( 1900 + $datearr[5] ) . "-" . ( $datearr[4] + 1 ) . "-" . $datearr[3];
3658 my $bor = "$borrower->{'firstname'} $borrower->{'surname'} $borrower->{'cardnumber'}";
3659 ModItem({ paidfor => $old_note."Paid for by $bor $date" }, undef, $itemnum);
3664 my ($itemnumber, $mark_returned) = @_;
3666 my $dbh = C4::Context->dbh();
3667 my $sth=$dbh->prepare("SELECT issues.*,items.*,biblio.title
3669 JOIN items USING (itemnumber)
3670 JOIN biblio USING (biblionumber)
3671 WHERE issues.itemnumber=?");
3672 $sth->execute($itemnumber);
3673 my $issues=$sth->fetchrow_hashref();
3675 # If a borrower lost the item, add a replacement cost to the their record
3676 if ( my $borrowernumber = $issues->{borrowernumber} ){
3677 my $borrower = C4::Members::GetMemberDetails( $borrowernumber );
3679 if (C4::Context->preference('WhenLostForgiveFine')){
3680 my $fix = _FixOverduesOnReturn($borrowernumber, $itemnumber, 1, 0); # 1, 0 = exemptfine, no-dropbox
3681 defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $itemnumber...) failed!"; # zero is OK, check defined
3683 if (C4::Context->preference('WhenLostChargeReplacementFee')){
3684 C4::Accounts::chargelostitem($borrowernumber, $itemnumber, $issues->{'replacementprice'}, "Lost Item $issues->{'title'} $issues->{'barcode'}");
3685 #FIXME : Should probably have a way to distinguish this from an item that really was returned.
3686 #warn " $issues->{'borrowernumber'} / $itemnumber ";
3689 MarkIssueReturned($borrowernumber,$itemnumber,undef,undef,$borrower->{'privacy'}) if $mark_returned;
3693 sub GetOfflineOperations {
3694 my $dbh = C4::Context->dbh;
3695 my $sth = $dbh->prepare("SELECT * FROM pending_offline_operations WHERE branchcode=? ORDER BY timestamp");
3696 $sth->execute(C4::Context->userenv->{'branch'});
3697 my $results = $sth->fetchall_arrayref({});
3701 sub GetOfflineOperation {
3702 my $operationid = shift;
3703 return unless $operationid;
3704 my $dbh = C4::Context->dbh;
3705 my $sth = $dbh->prepare("SELECT * FROM pending_offline_operations WHERE operationid=?");
3706 $sth->execute( $operationid );
3707 return $sth->fetchrow_hashref;
3710 sub AddOfflineOperation {
3711 my ( $userid, $branchcode, $timestamp, $action, $barcode, $cardnumber, $amount ) = @_;
3712 my $dbh = C4::Context->dbh;
3713 my $sth = $dbh->prepare("INSERT INTO pending_offline_operations (userid, branchcode, timestamp, action, barcode, cardnumber, amount) VALUES(?,?,?,?,?,?,?)");
3714 $sth->execute( $userid, $branchcode, $timestamp, $action, $barcode, $cardnumber, $amount );
3718 sub DeleteOfflineOperation {
3719 my $dbh = C4::Context->dbh;
3720 my $sth = $dbh->prepare("DELETE FROM pending_offline_operations WHERE operationid=?");
3721 $sth->execute( shift );
3725 sub ProcessOfflineOperation {
3726 my $operation = shift;
3729 if ( $operation->{action} eq 'return' ) {
3730 $report = ProcessOfflineReturn( $operation );
3731 } elsif ( $operation->{action} eq 'issue' ) {
3732 $report = ProcessOfflineIssue( $operation );
3733 } elsif ( $operation->{action} eq 'payment' ) {
3734 $report = ProcessOfflinePayment( $operation );
3737 DeleteOfflineOperation( $operation->{operationid} ) if $operation->{operationid};
3742 sub ProcessOfflineReturn {
3743 my $operation = shift;
3745 my $itemnumber = C4::Items::GetItemnumberFromBarcode( $operation->{barcode} );
3747 if ( $itemnumber ) {
3748 my $issue = GetOpenIssue( $itemnumber );
3751 $issue->{borrowernumber},
3754 $operation->{timestamp},
3757 { renewals => 0, onloan => undef },
3758 $issue->{'biblionumber'},
3763 return "Item not issued.";
3766 return "Item not found.";
3770 sub ProcessOfflineIssue {
3771 my $operation = shift;
3773 my $borrower = C4::Members::GetMemberDetails( undef, $operation->{cardnumber} ); # Get borrower from operation cardnumber
3775 if ( $borrower->{borrowernumber} ) {
3776 my $itemnumber = C4::Items::GetItemnumberFromBarcode( $operation->{barcode} );
3777 unless ($itemnumber) {
3778 return "Barcode not found.";
3780 my $issue = GetOpenIssue( $itemnumber );
3782 if ( $issue and ( $issue->{borrowernumber} ne $borrower->{borrowernumber} ) ) { # Item already issued to another borrower, mark it returned
3784 $issue->{borrowernumber},
3787 $operation->{timestamp},
3792 $operation->{'barcode'},
3795 $operation->{timestamp},
3800 return "Borrower not found.";
3804 sub ProcessOfflinePayment {
3805 my $operation = shift;
3807 my $borrower = C4::Members::GetMemberDetails( undef, $operation->{cardnumber} ); # Get borrower from operation cardnumber
3808 my $amount = $operation->{amount};
3810 recordpayment( $borrower->{borrowernumber}, $amount );
3818 TransferSlip($user_branch, $itemnumber, $barcode, $to_branch)
3820 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
3825 my ($branch, $itemnumber, $barcode, $to_branch) = @_;
3827 my $item = GetItem( $itemnumber, $barcode )
3830 return C4::Letters::GetPreparedLetter (
3831 module => 'circulation',
3832 letter_code => 'TRANSFERSLIP',
3833 branchcode => $branch,
3835 'branches' => $to_branch,
3836 'biblio' => $item->{biblionumber},
3842 =head2 CheckIfIssuedToPatron
3844 CheckIfIssuedToPatron($borrowernumber, $biblionumber)
3846 Return 1 if any record item is issued to patron, otherwise return 0
3850 sub CheckIfIssuedToPatron {
3851 my ($borrowernumber, $biblionumber) = @_;
3853 my $dbh = C4::Context->dbh;
3855 SELECT COUNT(*) FROM issues
3856 LEFT JOIN items ON items.itemnumber = issues.itemnumber
3857 WHERE items.biblionumber = ?
3858 AND issues.borrowernumber = ?
3860 my $is_issued = $dbh->selectrow_array($query, {}, $biblionumber, $borrowernumber );
3861 return 1 if $is_issued;
3867 IsItemIssued( $itemnumber )
3869 Return 1 if the item is on loan, otherwise return 0
3874 my $itemnumber = shift;
3875 my $dbh = C4::Context->dbh;
3876 my $sth = $dbh->prepare(q{
3879 WHERE itemnumber = ?
3881 $sth->execute($itemnumber);
3882 return $sth->fetchrow;
3885 =head2 GetAgeRestriction
3887 my ($ageRestriction, $daysToAgeRestriction) = GetAgeRestriction($record_restrictions, $borrower);
3888 my ($ageRestriction, $daysToAgeRestriction) = GetAgeRestriction($record_restrictions);
3890 if($daysToAgeRestriction <= 0) { #Borrower is allowed to access this material, as he is older or as old as the agerestriction }
3891 if($daysToAgeRestriction > 0) { #Borrower is this many days from meeting the agerestriction }
3893 @PARAM1 the koha.biblioitems.agerestriction value, like K18, PEGI 13, ...
3894 @PARAM2 a borrower-object with koha.borrowers.dateofbirth. (OPTIONAL)
3895 @RETURNS The age restriction age in years and the days to fulfill the age restriction for the given borrower.
3896 Negative days mean the borrower has gone past the age restriction age.
3900 sub GetAgeRestriction {
3901 my ($record_restrictions, $borrower) = @_;
3902 my $markers = C4::Context->preference('AgeRestrictionMarker');
3904 # Split $record_restrictions to something like FSK 16 or PEGI 6
3905 my @values = split ' ', uc($record_restrictions);
3906 return unless @values;
3908 # Search first occurrence of one of the markers
3909 my @markers = split /\|/, uc($markers);
3910 return unless @markers;
3913 my $restriction_year = 0;
3914 for my $value (@values) {
3916 for my $marker (@markers) {
3917 $marker =~ s/^\s+//; #remove leading spaces
3918 $marker =~ s/\s+$//; #remove trailing spaces
3919 if ( $marker eq $value ) {
3920 if ( $index <= $#values ) {
3921 $restriction_year += $values[$index];
3925 elsif ( $value =~ /^\Q$marker\E(\d+)$/ ) {
3927 # Perhaps it is something like "K16" (as in Finland)
3928 $restriction_year += $1;
3932 last if ( $restriction_year > 0 );
3935 #Check if the borrower is age restricted for this material and for how long.
3936 if ($restriction_year && $borrower) {
3937 if ( $borrower->{'dateofbirth'} ) {
3938 my @alloweddate = split /-/, $borrower->{'dateofbirth'};
3939 $alloweddate[0] += $restriction_year;
3941 #Prevent runime eror on leap year (invalid date)
3942 if ( ( $alloweddate[1] == 2 ) && ( $alloweddate[2] == 29 ) ) {
3943 $alloweddate[2] = 28;
3946 #Get how many days the borrower has to reach the age restriction
3947 my @Today = split /-/, DateTime->today->ymd();
3948 my $daysToAgeRestriction = Date_to_Days(@alloweddate) - Date_to_Days(@Today);
3949 #Negative days means the borrower went past the age restriction age
3950 return ($restriction_year, $daysToAgeRestriction);
3954 return ($restriction_year);
3958 =head2 GetPendingOnSiteCheckouts
3962 sub GetPendingOnSiteCheckouts {
3963 my $dbh = C4::Context->dbh;
3964 return $dbh->selectall_arrayref(q|
3970 items.itemcallnumber,
3974 issues.date_due < NOW() AS is_overdue,
3977 borrowers.firstname,
3979 borrowers.cardnumber,
3980 borrowers.borrowernumber
3982 LEFT JOIN issues ON items.itemnumber = issues.itemnumber
3983 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
3984 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
3985 WHERE issues.onsite_checkout = 1
3986 |, { Slice => {} } );
3992 my ($count, $branch, $itemtype, $ccode, $newness)
3993 = @$params{qw(count branch itemtype ccode newness)};
3995 my $dbh = C4::Context->dbh;
3997 SELECT b.biblionumber, b.title, b.author, bi.itemtype, bi.publishercode,
3998 bi.place, bi.publicationyear, b.copyrightdate, bi.pages, bi.size,
3999 i.ccode, SUM(i.issues) AS count
4001 LEFT JOIN items i ON (i.biblionumber = b.biblionumber)
4002 LEFT JOIN biblioitems bi ON (bi.biblionumber = b.biblionumber)
4005 my (@where_strs, @where_args);
4008 push @where_strs, 'i.homebranch = ?';
4009 push @where_args, $branch;
4012 if (C4::Context->preference('item-level_itypes')){
4013 push @where_strs, 'i.itype = ?';
4014 push @where_args, $itemtype;
4016 push @where_strs, 'bi.itemtype = ?';
4017 push @where_args, $itemtype;
4021 push @where_strs, 'i.ccode = ?';
4022 push @where_args, $ccode;
4025 push @where_strs, 'TO_DAYS(NOW()) - TO_DAYS(b.datecreated) <= ?';
4026 push @where_args, $newness;
4030 $query .= 'WHERE ' . join(' AND ', @where_strs);
4034 GROUP BY b.biblionumber
4039 $count = int($count);
4041 $query .= "LIMIT $count";
4044 my $rows = $dbh->selectall_arrayref($query, { Slice => {} }, @where_args);
4054 Koha Development Team <http://koha-community.org/>