use Modern::Perl;
use DateTime;
use POSIX qw( floor );
-use Koha::DateUtils;
+use YAML::XS;
+use Encode;
+
+use Koha::DateUtils qw( dt_from_string output_pref );
use C4::Context;
-use C4::Stats;
-use C4::Reserves;
-use C4::Biblio;
-use C4::Items;
-use C4::Members;
+use C4::Stats qw( UpdateStats );
+use C4::Reserves qw( CheckReserves CanItemBeReserved MoveReserve ModReserve ModReserveMinusPriority RevertWaitingStatus IsItemOnHoldAndFound IsAvailableForItemLevelRequest );
+use C4::Biblio qw( UpdateTotalIssues );
+use C4::Items qw( ModItemTransfer ModDateLastSeen CartToShelf );
use C4::Accounts;
use C4::ItemCirculationAlertPreference;
use C4::Message;
-use C4::Debug;
-use C4::Log; # logaction
-use C4::Overdues qw(CalcFine UpdateFine get_chargeable_units);
+use C4::Log qw( logaction ); # logaction
+use C4::Overdues;
use C4::RotatingCollections qw(GetCollectionItemBranches);
-use Algorithm::CheckDigits;
+use Algorithm::CheckDigits qw( CheckDigits );
-use Data::Dumper;
+use Data::Dumper qw( Dumper );
use Koha::Account;
use Koha::AuthorisedValues;
use Koha::Biblioitems;
-use Koha::DateUtils;
+use Koha::DateUtils qw( dt_from_string output_pref );
use Koha::Calendar;
use Koha::Checkouts;
use Koha::Illrequests;
use Koha::Items;
use Koha::Patrons;
-use Koha::Patron::Debarments;
+use Koha::Patron::Debarments qw( DelUniqueDebarment GetDebarments AddUniqueDebarment );
use Koha::Database;
use Koha::Libraries;
use Koha::Account::Lines;
use Koha::Account::Offsets;
use Koha::Config::SysPrefs;
use Koha::Charges::Fees;
-use Koha::Util::SystemPreferences;
+use Koha::Config::SysPref;
use Koha::Checkouts::ReturnClaims;
-use Carp;
-use List::MoreUtils qw( uniq any );
+use Koha::SearchEngine::Indexer;
+use Koha::Exceptions::Checkout;
+use Koha::Plugins;
+use Koha::Recalls;
+use Carp qw( carp );
+use List::MoreUtils qw( any );
use Scalar::Util qw( looks_like_number );
-use Try::Tiny;
-use Date::Calc qw(
- Today
- Today_and_Now
- Add_Delta_YM
- Add_Delta_DHMS
- Date_to_Days
- Day_of_Week
- Add_Delta_Days
-);
-use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
-
+use Date::Calc qw( Date_to_Days );
+our (@ISA, @EXPORT_OK);
BEGIN {
- require Exporter;
- @ISA = qw(Exporter);
-
- # FIXME subs that should probably be elsewhere
- push @EXPORT, qw(
- &barcodedecode
- &LostItem
- &ReturnLostItem
- &GetPendingOnSiteCheckouts
- );
-
- # subs to deal with issuing a book
- push @EXPORT, qw(
- &CanBookBeIssued
- &CanBookBeRenewed
- &AddIssue
- &AddRenewal
- &GetRenewCount
- &GetSoonestRenewDate
- &GetLatestAutoRenewDate
- &GetIssuingCharges
- &GetBranchBorrowerCircRule
- &GetBranchItemRule
- &GetBiblioIssues
- &GetOpenIssue
- &CheckIfIssuedToPatron
- &IsItemIssued
- GetTopIssues
- );
-
- # subs to deal with returns
- push @EXPORT, qw(
- &AddReturn
- &MarkIssueReturned
- );
-
- # subs to deal with transfers
- push @EXPORT, qw(
- &transferbook
- &GetTransfers
- &GetTransfersFromTo
- &updateWrongTransfer
- &DeleteTransfer
- &IsBranchTransferAllowed
- &CreateBranchTransferLimit
- &DeleteBranchTransferLimits
- &TransferSlip
- );
-
- # subs to deal with offline circulation
- push @EXPORT, qw(
- &GetOfflineOperations
- &GetOfflineOperation
- &AddOfflineOperation
- &DeleteOfflineOperation
- &ProcessOfflineOperation
+
+ require Exporter;
+ @ISA = qw(Exporter);
+
+ # FIXME subs that should probably be elsewhere
+ push @EXPORT_OK, qw(
+ barcodedecode
+ LostItem
+ ReturnLostItem
+ GetPendingOnSiteCheckouts
+
+ CanBookBeIssued
+ checkHighHolds
+ CanBookBeRenewed
+ AddIssue
+ GetLoanLength
+ GetHardDueDate
+ AddRenewal
+ GetRenewCount
+ GetSoonestRenewDate
+ GetLatestAutoRenewDate
+ GetIssuingCharges
+ AddIssuingCharge
+ GetBranchBorrowerCircRule
+ GetBranchItemRule
+ GetBiblioIssues
+ GetOpenIssue
+ GetUpcomingDueIssues
+ CheckIfIssuedToPatron
+ IsItemIssued
+ GetAgeRestriction
+ GetTopIssues
+
+ AddReturn
+ MarkIssueReturned
+
+ transferbook
+ TooMany
+ GetTransfers
+ GetTransfersFromTo
+ updateWrongTransfer
+ CalcDateDue
+ CheckValidBarcode
+ IsBranchTransferAllowed
+ CreateBranchTransferLimit
+ DeleteBranchTransferLimits
+ TransferSlip
+
+ GetOfflineOperations
+ GetOfflineOperation
+ AddOfflineOperation
+ DeleteOfflineOperation
+ ProcessOfflineOperation
+ ProcessOfflinePayment
);
+ push @EXPORT_OK, '_GetCircControlBranch'; # This is wrong!
}
=head1 NAME
my ($barcode, $filter) = @_;
my $branch = C4::Context::mybranch();
$filter = C4::Context->preference('itemBarcodeInputFilter') unless $filter;
+ Koha::Plugins->call('item_barcode_transform', \$barcode );
$filter or return $barcode; # ensure filter is defined, else return untouched barcode
if ($filter eq 'whitespace') {
$barcode =~ s/\s//g;
} elsif ($filter eq 'cuecat') {
chomp($barcode);
my @fields = split( /\./, $barcode );
- my @results = map( decode($_), @fields[ 1 .. $#fields ] );
+ my @results = map( C4::Circulation::_decode($_), @fields[ 1 .. $#fields ] );
($#results == 2) and return $results[2];
} elsif ($filter eq 'T-prefix') {
if ($barcode =~ /^[Tt](\d)/) {
return $barcode; # return barcode, modified or not
}
-=head2 decode
+=head2 _decode
- $str = &decode($chunk);
+ $str = &_decode($chunk);
Decodes a segment of a string emitted by a CueCat barcode scanner and
returns it.
=cut
-sub decode {
+sub _decode {
my ($encoded) = @_;
my $seq =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
+=item C<RecallPlacedAtHoldingBranch>
+
+A recall for this item was found, and the transfer has already been completed as the item's branch matches the recall's pickup branch.
+
+=item C<RecallFound>
+
+A recall for this item was found, and the item needs to be transferred to the recall's pickup branch.
+
=back
=back
# That'll save a database query.
my ( $resfound, $resrec, undef ) =
CheckReserves( $itemnumber );
- if ( $resfound and not $ignoreRs ) {
+ if ( $resfound ) {
$resrec->{'ResFound'} = $resfound;
$messages->{'ResFound'} = $resrec;
- $dotransfer = 1;
+ $dotransfer = 0 unless $ignoreRs;
+ }
+
+ # find recall
+ if ( C4::Context->preference('UseRecalls') ) {
+ my $recall = Koha::Recalls->find({ itemnumber => $itemnumber, status => 'in_transit' });
+ if ( defined $recall ) {
+ # do a transfer if the recall branch is different to the item holding branch
+ if ( $recall->branchcode eq $fbr ) {
+ $dotransfer = 0;
+ $messages->{'RecallPlacedAtHoldingBranch'} = 1;
+ } else {
+ $dotransfer = 1;
+ $messages->{'RecallFound'} = $recall;
+ }
+ }
}
#actually do the transfer....
ModItemTransfer( $itemnumber, $fbr, $tbr, $trigger );
# don't need to update MARC anymore, we do it in batch now
- $messages->{'WasTransfered'} = 1;
+ $messages->{'WasTransfered'} = $tbr;
}
ModDateLastSeen( $itemnumber );
$checkouts = $patron->checkouts; # if branch is the patron's home branch, then count all loans by patron
} else {
$checkouts = $patron->checkouts->search(
- { 'item.homebranch' => $maxissueqty_rule->branchcode },
- { prefetch => 'item' } );
+ { 'item.homebranch' => $maxissueqty_rule->branchcode } );
}
} else {
$checkouts = $patron->checkouts; # if rule is not branch specific then count all loans by patron
}
+ $checkouts = $checkouts->search(undef, { prefetch => 'item' });
+
my $sum_checkouts;
my $rule_itemtype = $maxissueqty_rule->itemtype;
- while ( my $c = $checkouts->next ) {
- my $itemtype = $c->item->effective_itemtype;
- my @types;
- unless ( $rule_itemtype ) {
- # matching rule has the default item type, so count only
- # those existing loans that don't fall under a more
- # specific rule
- @types = Koha::CirculationRules->search(
- {
- branchcode => $maxissueqty_rule->branchcode,
- categorycode => [ $maxissueqty_rule->categorycode, $cat_borrower ],
- itemtype => { '!=' => undef },
- rule_name => 'maxissueqty'
- }
- )->get_column('itemtype');
- next if grep {$_ eq $itemtype} @types;
- } else {
- my @types;
- if ( $parent_maxissueqty_rule ) {
+ my @types;
+ unless ( $rule_itemtype ) {
+ # matching rule has the default item type, so count only
+ # those existing loans that don't fall under a more
+ # specific rule
+ @types = Koha::CirculationRules->search(
+ {
+ branchcode => $maxissueqty_rule->branchcode,
+ categorycode => [ $maxissueqty_rule->categorycode, $cat_borrower ],
+ itemtype => { '!=' => undef },
+ rule_name => 'maxissueqty'
+ }
+ )->get_column('itemtype');
+ } else {
+ if ( $parent_maxissueqty_rule ) {
# if we have a parent item type then we count loans of the
# specific item type or its siblings or parent
- my $children = Koha::ItemTypes->search({ parent_type => $parent_type });
- @types = $children->get_column('itemtype');
- push @types, $parent_type;
- } elsif ( $child_types ) {
+ my $children = Koha::ItemTypes->search({ parent_type => $parent_type });
+ @types = $children->get_column('itemtype');
+ push @types, $parent_type;
+ } elsif ( $child_types ) {
# If we are a parent type, we need to count all child types and our own type
- @types = $child_types->get_column('itemtype');
- push @types, $type; # And don't forget to count our own types
- } else { push @types, $type; } # Otherwise only count the specific itemtype
+ @types = $child_types->get_column('itemtype');
+ push @types, $type; # And don't forget to count our own types
+ } else {
+ # Otherwise only count the specific itemtype
+ push @types, $type;
+ }
+ }
+ while ( my $c = $checkouts->next ) {
+ my $itemtype = $c->item->effective_itemtype;
+
+ unless ( $rule_itemtype ) {
+ next if grep {$_ eq $itemtype} @types;
+ } else {
next unless grep {$_ eq $itemtype} @types;
}
+
$sum_checkouts->{total}++;
$sum_checkouts->{onsite_checkouts}++ if $c->onsite_checkout;
$sum_checkouts->{itemtype}->{$itemtype}++;
$checkouts = $patron->checkouts->search(
{ 'me.branchcode' => $branch} );
} elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
- ; # if branch is the patron's home branch, then count all loans by patron
+ $checkouts = $patron->checkouts; # if branch is the patron's home branch, then count all loans by patron
} else {
$checkouts = $patron->checkouts->search(
- { 'item.homebranch' => $branch} );
+ { 'item.homebranch' => $branch},
+ { prefetch => 'item' } );
}
my $checkout_count = $checkouts->count;
reserved for someone else.
+=head3 TRANSFERRED
+
+reserved and being transferred for someone else.
+
=head3 INVALID_DATE
sticky due date is invalid or due date in the past
if the borrower borrows to much things
+=head3 RECALLED
+
+recalled by someone else
+
=cut
sub CanBookBeIssued {
#
if ( $patron->category->category_type eq 'X' && ( $item_object->barcode )) {
# stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1 .
- &UpdateStats({
+ C4::Stats::UpdateStats({
branch => C4::Context->userenv->{'branch'},
type => 'localuse',
itemnumber => $item_object->itemnumber,
my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
$no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
if ( defined $no_issues_charge_guarantees ) {
- my @guarantees = map { $_->guarantee } $patron->guarantee_relationships();
- my $guarantees_non_issues_charges;
+ my @guarantees = map { $_->guarantee } $patron->guarantee_relationships->as_list;
+ my $guarantees_non_issues_charges = 0;
foreach my $g ( @guarantees ) {
$guarantees_non_issues_charges += $g->account->non_issues_charges;
}
my $no_issues_charge_guarantors = C4::Context->preference("NoIssuesChargeGuarantorsWithGuarantees");
$no_issues_charge_guarantors = undef unless looks_like_number( $no_issues_charge_guarantors );
if ( defined $no_issues_charge_guarantors ) {
- my $guarantors_non_issues_charges += $patron->relationships_debt({ include_guarantors => 1, only_this_guarantor => 0, include_this_patron => 1 });
+ my $guarantors_non_issues_charges = $patron->relationships_debt({ include_guarantors => 1, only_this_guarantor => 0, include_this_patron => 1 });
if ( $guarantors_non_issues_charges > $no_issues_charge_guarantors && !$inprocess && !$allowfineoverride) {
$issuingimpossible{DEBT_GUARANTORS} = $guarantors_non_issues_charges;
}
}
- unless ( $ignore_reserves ) {
+ my $recall;
+ # CHECK IF ITEM HAS BEEN RECALLED BY ANOTHER PATRON
+ # Only bother doing this if UseRecalls is enabled and the item is recallable
+ # Don't look at recalls that are in transit
+ if ( C4::Context->preference('UseRecalls') and $item_object->can_be_waiting_recall ) {
+ my @recalls = $biblio->recalls({},{ order_by => { -asc => 'recalldate' } })->filter_by_current->as_list;
+
+ foreach my $r ( @recalls ) {
+ if ( $r->itemnumber and
+ $r->itemnumber == $item_object->itemnumber and
+ $r->borrowernumber == $patron->borrowernumber and
+ ( $r->waiting or $r->requested ) ) {
+ $messages{RECALLED} = $r->recall_id;
+ $recall = $r;
+ # this item is recalled by or already waiting for this borrower and the recall can be fulfilled
+ last;
+ }
+ elsif ( $r->itemnumber and
+ $r->itemnumber == $item_object->itemnumber and
+ $r->in_transit ) {
+ # recalled item is in transit
+ $issuingimpossible{RECALLED_INTRANSIT} = $r->branchcode;
+ }
+ elsif ( $r->item_level_recall and
+ $r->itemnumber == $item_object->itemnumber and
+ $r->borrowernumber != $patron->borrowernumber and
+ !$r->in_transit ) {
+ # this specific item has been recalled by a different patron
+ $needsconfirmation{RECALLED} = $r;
+ $recall = $r;
+ last;
+ }
+ elsif ( !$r->item_level_recall and
+ $r->borrowernumber != $patron->borrowernumber and
+ !$r->in_transit ) {
+ # a different patron has placed a biblio-level recall and this item is eligible to fill it
+ $needsconfirmation{RECALLED} = $r;
+ $recall = $r;
+ last;
+ }
+ }
+ }
+
+ unless ( $ignore_reserves and defined $recall ) {
# See if the item is on reserve.
my ( $restype, $res ) = C4::Reserves::CheckReserves( $item_object->itemnumber );
if ($restype) {
$needsconfirmation{'resreservedate'} = $res->{reservedate};
$needsconfirmation{'reserve_id'} = $res->{reserve_id};
}
+ elsif ( $restype eq "Transferred" ) {
+ # The item is determined hold being transferred for someone else.
+ $needsconfirmation{TRANSFERRED} = 1;
+ $needsconfirmation{'resfirstname'} = $patron->firstname;
+ $needsconfirmation{'ressurname'} = $patron->surname;
+ $needsconfirmation{'rescardnumber'} = $patron->cardnumber;
+ $needsconfirmation{'resborrowernumber'} = $patron->borrowernumber;
+ $needsconfirmation{'resbranchcode'} = $patron->branchcode;
+ $needsconfirmation{'resreservedate'} = $res->{reservedate};
+ $needsconfirmation{'reserve_id'} = $res->{reserve_id};
+ }
+ elsif ( $restype eq "Processing" ) {
+ # The item is determined hold being processed for someone else.
+ $needsconfirmation{PROCESSING} = 1;
+ $needsconfirmation{'resfirstname'} = $patron->firstname;
+ $needsconfirmation{'ressurname'} = $patron->surname;
+ $needsconfirmation{'rescardnumber'} = $patron->cardnumber;
+ $needsconfirmation{'resborrowernumber'} = $patron->borrowernumber;
+ $needsconfirmation{'resbranchcode'} = $patron->branchcode;
+ $needsconfirmation{'resreservedate'} = $res->{reservedate};
+ $needsconfirmation{'reserve_id'} = $res->{reserve_id};
+ }
}
}
}
## check for high holds decreasing loan period
if ( C4::Context->preference('decreaseLoanHighHolds') ) {
- my $check = checkHighHolds( $item_unblessed, $patron_unblessed );
+ my $check = checkHighHolds( $item_object, $patron );
if ( $check->{exceeded} ) {
if ($override_high_holds) {
=cut
sub checkHighHolds {
- my ( $item, $borrower ) = @_;
- my $branchcode = _GetCircControlBranch( $item, $borrower );
- my $item_object = Koha::Items->find( $item->{itemnumber} );
+ my ( $item, $patron ) = @_;
+ my $branchcode = _GetCircControlBranch( $item->unblessed, $patron->unblessed );
my $return_data = {
exceeded => 0,
due_date => undef,
};
- my $holds = Koha::Holds->search( { biblionumber => $item->{'biblionumber'} } );
+ my $holds = Koha::Holds->search( { biblionumber => $item->biblionumber } );
if ( $holds->count() ) {
$return_data->{outstanding} = $holds->count();
}
# Remove any items that are not holdable for this patron
- @items = grep { CanItemBeReserved( $borrower->{borrowernumber}, $_->itemnumber, undef, { ignore_found_holds => 1 } )->{status} eq 'OK' } @items;
+ @items = grep { CanItemBeReserved( $patron , $_, undef, { ignore_found_holds => 1 } )->{status} eq 'OK' } @items;
my $items_count = scalar @items;
my $issuedate = dt_from_string();
- my $itype = $item_object->effective_itemtype;
+ my $itype = $item->effective_itemtype;
my $daysmode = Koha::CirculationRules->get_effective_daysmode(
{
- categorycode => $borrower->{categorycode},
+ categorycode => $patron->categorycode,
itemtype => $itype,
branchcode => $branchcode,
}
);
my $calendar = Koha::Calendar->new( branchcode => $branchcode, days_mode => $daysmode );
- my $orig_due = C4::Circulation::CalcDateDue( $issuedate, $itype, $branchcode, $borrower );
+ my $orig_due = C4::Circulation::CalcDateDue( $issuedate, $itype, $branchcode, $patron->unblessed );
- my $decreaseLoanHighHoldsDuration = C4::Context->preference('decreaseLoanHighHoldsDuration');
+ my $rule = Koha::CirculationRules->get_effective_rule(
+ {
+ categorycode => $patron->categorycode,
+ itemtype => $item->effective_itemtype,
+ branchcode => $branchcode,
+ rule_name => 'decreaseloanholds',
+ }
+ );
- my $reduced_datedue = $calendar->addDate( $issuedate, $decreaseLoanHighHoldsDuration );
+ my $duration;
+ if ( defined($rule) && $rule->rule_value ne '' ){
+ # overrides decreaseLoanHighHoldsDuration syspref
+ $duration = $rule->rule_value;
+ } else {
+ $duration = C4::Context->preference('decreaseLoanHighHoldsDuration');
+ }
+ my $reduced_datedue = $calendar->addDuration( $issuedate, $duration );
$reduced_datedue->set_hour($orig_due->hour);
$reduced_datedue->set_minute($orig_due->minute);
$reduced_datedue->truncate( to => 'minute' );
if ( DateTime->compare( $reduced_datedue, $orig_due ) == -1 ) {
$return_data->{exceeded} = 1;
- $return_data->{duration} = $decreaseLoanHighHoldsDuration;
+ $return_data->{duration} = $duration;
$return_data->{due_date} = $reduced_datedue;
}
}
* RESERVE PLACED ?
- fill reserve if reserve to this patron
- cancel reserve or not, otherwise
+ * RECALL PLACED ?
+ - fill recall if recall to this patron
+ - cancel recall or not
+ - revert recall's waiting status or not
* TRANSFERT PENDING ?
- complete the transfert
* ISSUE THE BOOK
my $onsite_checkout = $params && $params->{onsite_checkout} ? 1 : 0;
my $switch_onsite_checkout = $params && $params->{switch_onsite_checkout};
my $auto_renew = $params && $params->{auto_renew};
+ my $cancel_recall = $params && $params->{cancel_recall};
+ my $recall_id = $params && $params->{recall_id};
my $dbh = C4::Context->dbh;
my $barcodecheck = CheckValidBarcode($barcode);
my ( $allowed, $message ) = CanBookBeReturned( $item_unblessed, C4::Context->userenv->{branch} );
return unless $allowed;
AddReturn( $item_object->barcode, C4::Context->userenv->{'branch'} );
+ # AddReturn certainly has side-effects, like onloan => undef
+ $item_object->discard_changes;
+ }
+
+ if ( C4::Context->preference('UseRecalls') ) {
+ Koha::Recalls->move_recall(
+ {
+ action => $cancel_recall,
+ recall_id => $recall_id,
+ item => $item_object,
+ borrowernumber => $borrower->{borrowernumber},
+ }
+ );
}
C4::Reserves::MoveReserve( $item_object->itemnumber, $borrower->{'borrowernumber'}, $cancelreserve );
$auto_renew = $rule->rule_value if $rule;
}
- # Record in the database the fact that the book was issued.
- unless ($datedue) {
- my $itype = $item_object->effective_itemtype;
- $datedue = CalcDateDue( $issuedate, $itype, $branchcode, $borrower );
-
- }
- $datedue->truncate( to => 'minute' );
-
my $issue_attributes = {
borrowernumber => $borrower->{'borrowernumber'},
issuedate => $issuedate->strftime('%Y-%m-%d %H:%M:%S'),
auto_renew => $auto_renew ? 1 : 0,
};
+ # Get ID of logged in user. if called from a batch job,
+ # no user session exists and C4::Context->userenv() returns
+ # the scalar '0'. Only do this if the syspref says so
+ if ( C4::Context->preference('RecordStaffUserOnCheckout') ) {
+ my $userenv = C4::Context->userenv();
+ my $usernumber = (ref($userenv) eq 'HASH') ? $userenv->{'number'} : undef;
+ if ($usernumber) {
+ $issue_attributes->{issuer_id} = $usernumber;
+ }
+ }
+
+ # In the case that the borrower has an on-site checkout
+ # and SwitchOnSiteCheckouts is enabled this converts it to a regular checkout
$issue = Koha::Checkouts->find( { itemnumber => $item_object->itemnumber } );
if ($issue) {
$issue->set($issue_attributes)->store;
}
)->store;
}
+ $issue->discard_changes;
+ C4::Auth::track_login_daily( $borrower->{userid} );
if ( $item_object->location && $item_object->location eq 'CART'
&& ( !$item_object->permanent_location || $item_object->permanent_location ne 'CART' ) ) {
## Item was moved to cart via UpdateItemLocationOnCheckin, anything issued should be taken off the cart.
UpdateTotalIssues( $item_object->biblionumber, 1 );
}
+ # Record if item was lost
+ my $was_lost = $item_object->itemlost;
+
$item_object->issues( ( $item_object->issues || 0 ) + 1);
$item_object->holdingbranch(C4::Context->userenv->{'branch'});
$item_object->itemlost(0);
$item_object->onloan($datedue->ymd());
$item_object->datelastborrowed( dt_from_string()->ymd() );
+ $item_object->datelastseen( dt_from_string()->ymd() );
$item_object->store({log_action => 0});
- ModDateLastSeen( $item_object->itemnumber );
+
+ # If the item was lost, it has now been found, charge the overdue if necessary
+ if ($was_lost) {
+ if ( $item_object->{_charge} ) {
+ $actualissue //= Koha::Old::Checkouts->search(
+ { itemnumber => $item_unblessed->{itemnumber} },
+ {
+ order_by => { '-desc' => 'returndate' },
+ rows => 1
+ }
+ )->single;
+ unless ( exists( $borrower->{branchcode} ) ) {
+ my $patron = $actualissue->patron;
+ $borrower = $patron->unblessed;
+ }
+ _CalculateAndUpdateFine(
+ {
+ issue => $actualissue,
+ item => $item_unblessed,
+ borrower => $borrower,
+ return_date => $issuedate
+ }
+ );
+ _FixOverduesOnReturn( $borrower->{borrowernumber},
+ $item_object->itemnumber, undef, 'RENEWED' );
+ }
+ }
# If it costs to borrow this book, charge it to the patron's account.
my ( $charge, $itemtype ) = GetIssuingCharges( $item_object->itemnumber, $borrower->{'borrowernumber'} );
}
# Record the fact that this book was issued.
- &UpdateStats(
+ C4::Stats::UpdateStats(
{
branch => C4::Context->userenv->{'branch'},
type => ( $onsite_checkout ? 'onsite_checkout' : 'issue' ),
The return value is a hashref containing the following keys:
holdallowed => Hold policy for this branch and itemtype. Possible values:
- 0: No holds allowed.
- 1: Holds allowed only by patrons that have the same homebranch as the item.
- 2: Holds allowed from any patron.
+ not_allowed: No holds allowed.
+ from_home_library: Holds allowed only by patrons that have the same homebranch as the item.
+ from_any_library: Holds allowed from any patron.
+ from_local_hold_group: Holds allowed from libraries in hold group
returnbranch => branch to which to return item. Possible values:
noreturn: do not return, let item remain where checked in (floating collections)
my ( $branchcode, $itemtype ) = @_;
# Search for rules!
- my $holdallowed_rule = Koha::CirculationRules->get_effective_rule(
- {
- branchcode => $branchcode,
- itemtype => $itemtype,
- rule_name => 'holdallowed',
- }
- );
- my $hold_fulfillment_policy_rule = Koha::CirculationRules->get_effective_rule(
- {
- branchcode => $branchcode,
- itemtype => $itemtype,
- rule_name => 'hold_fulfillment_policy',
- }
- );
- my $returnbranch_rule = Koha::CirculationRules->get_effective_rule(
- {
- branchcode => $branchcode,
- itemtype => $itemtype,
- rule_name => 'returnbranch',
- }
- );
+ my $rules = Koha::CirculationRules->get_effective_rules({
+ branchcode => $branchcode,
+ itemtype => $itemtype,
+ rules => ['holdallowed', 'hold_fulfillment_policy', 'returnbranch']
+ });
# built-in default circulation rule
- my $rules;
- $rules->{holdallowed} = defined $holdallowed_rule
- ? $holdallowed_rule->rule_value
- : 2;
- $rules->{hold_fulfillment_policy} = defined $hold_fulfillment_policy_rule
- ? $hold_fulfillment_policy_rule->rule_value
- : 'any';
- $rules->{returnbranch} = defined $returnbranch_rule
- ? $returnbranch_rule->rule_value
- : 'homebranch';
+ $rules->{holdallowed} //= 'from_any_library';
+ $rules->{hold_fulfillment_policy} //= 'any';
+ $rules->{returnbranch} //= 'homebranch';
return $rules;
}
If AutomaticItemReturn is disabled, return branch is given as value of NeedsTransfer.
+=item C<RecallFound>
+
+This item can fill a recall. The recall object is returned. If the recall pickup branch differs from
+the branch this item is being returned at, C<RecallNeedsTransfer> is also returned which contains this
+branchcode.
+
+=item C<TransferredRecall>
+
+This item has been transferred to this branch to fill a recall. The recall object is returned.
+
=back
C<$iteminformation> is a reference-to-hash, giving information about the
. Dumper($issue->unblessed) . "\n";
} else {
$messages->{'NotIssued'} = $barcode;
- $item->onloan(undef)->store if defined $item->onloan;
+ $item->onloan(undef)->store({skip_record_index=>1}) if defined $item->onloan;
# even though item is not on loan, it may still be transferred; therefore, get current branch info
$doreturn = 0;
my $borrowernumber = $patron ? $patron->borrowernumber : undef; # we don't know if we had a borrower or not
my $patron_unblessed = $patron ? $patron->unblessed : {};
- my $update_loc_rules = get_yaml_pref_hash('UpdateItemLocationOnCheckin');
+ my $update_loc_rules = Koha::Config::SysPrefs->find('UpdateItemLocationOnCheckin')->get_yaml_pref_hash();
map { $update_loc_rules->{$_} = $update_loc_rules->{$_}[0] } keys %$update_loc_rules; #We can only move to one location so we flatten the arrays
if ($update_loc_rules) {
if (defined $update_loc_rules->{_ALL_}) {
if ($update_loc_rules->{_ALL_} eq '_PERM_') { $update_loc_rules->{_ALL_} = $item->permanent_location; }
if ($update_loc_rules->{_ALL_} eq '_BLANK_') { $update_loc_rules->{_ALL_} = ''; }
- if ( $item->location ne $update_loc_rules->{_ALL_}) {
+ if (
+ ( defined $item->location && $item->location ne $update_loc_rules->{_ALL_}) ||
+ (!defined $item->location && $update_loc_rules->{_ALL_} ne "")
+ ) {
$messages->{'ItemLocationUpdated'} = { from => $item->location, to => $update_loc_rules->{_ALL_} };
- $item->location($update_loc_rules->{_ALL_})->store;
+ $item->location($update_loc_rules->{_ALL_})->store({skip_record_index=>1});
}
}
else {
if ( $update_loc_rules->{$key} eq '_BLANK_') { $update_loc_rules->{$key} = '' ;}
if ( ($item->location eq $key && $item->location ne $update_loc_rules->{$key}) || ($key eq '_BLANK_' && $item->location eq '' && $update_loc_rules->{$key} ne '') ) {
$messages->{'ItemLocationUpdated'} = { from => $item->location, to => $update_loc_rules->{$key} };
- $item->location($update_loc_rules->{$key})->store;
+ $item->location($update_loc_rules->{$key})->store({skip_record_index=>1});
last;
}
}
if ($yaml) {
$yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
my $rules;
- eval { $rules = YAML::Load($yaml); };
+ eval { $rules = YAML::XS::Load(Encode::encode_utf8($yaml)); };
if ($@) {
warn "Unable to parse UpdateNotForLoanStatusOnCheckin syspref : $@";
}
foreach my $key ( keys %$rules ) {
if ( $item->notforloan eq $key ) {
$messages->{'NotForLoanStatusUpdated'} = { from => $item->notforloan, to => $rules->{$key} };
- $item->notforloan($rules->{$key})->store({ log_action => 0 });
+ $item->notforloan($rules->{$key})->store({ log_action => 0, skip_record_index => 1 });
last;
}
}
Rightbranch => $message
};
$doreturn = 0;
+ my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
+ $indexer->index_records( $item->biblionumber, "specialUpdate", "biblioserver" );
return ( $doreturn, $messages, $issue, $patron_unblessed);
}
if ($patron) {
eval {
- MarkIssueReturned( $borrowernumber, $item->itemnumber, $return_date, $patron->privacy );
+ MarkIssueReturned( $borrowernumber, $item->itemnumber, $return_date, $patron->privacy, { skip_record_index => 1} );
};
unless ( $@ ) {
if (
_CalculateAndUpdateFine( { issue => $issue, item => $item->unblessed, borrower => $patron_unblessed, return_date => $return_date } );
}
} else {
- carp "The checkin for the following issue failed, Please go to the about page, section 'data corrupted' to know how to fix this problem ($@)" . Dumper( $issue->unblessed );
+ carp "The checkin for the following issue failed, Please go to the about page and check all messages on the 'System information' to see if there are configuration / data issues ($@)" . Dumper( $issue->unblessed );
+
+ my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
+ $indexer->index_records( $item->biblionumber, "specialUpdate", "biblioserver" );
return ( 0, { WasReturned => 0, DataCorrupted => 1 }, $issue, $patron_unblessed );
}
# FIXME is the "= 1" right? This could be the borrower hash.
$messages->{'WasReturned'} = 1;
+ } else {
+ $item->onloan(undef)->store({ log_action => 0 , skip_record_index => 1 });
}
-
- $item->onloan(undef)->store({ log_action => 0 });
}
# the holdingbranch is updated if the document is returned to another location.
# this is always done regardless of whether the item was on loan or not
if ($item->holdingbranch ne $branch) {
- $item->holdingbranch($branch)->store;
+ $item->holdingbranch($branch)->store({ skip_record_index => 1 });
}
my $item_was_lost = $item->itemlost;
my $leave_item_lost = C4::Context->preference("BlockReturnOfLostItems") ? 1 : 0;
- my $updated_item = ModDateLastSeen( $item->itemnumber, $leave_item_lost ); # will unset itemlost if needed
+ my $updated_item = ModDateLastSeen( $item->itemnumber, $leave_item_lost, { skip_record_index => 1 } ); # will unset itemlost if needed
# fix up the accounts.....
- if ( $item_was_lost ) {
+ if ($item_was_lost) {
$messages->{'WasLost'} = 1;
unless ( C4::Context->preference("BlockReturnOfLostItems") ) {
- $messages->{'LostItemFeeRefunded'} = $updated_item->{_refunded};
+ my @object_messages = @{ $updated_item->object_messages };
+ for my $message (@object_messages) {
+ $messages->{'LostItemFeeRefunded'} = 1
+ if $message->message eq 'lost_refunded';
+ $messages->{'LostItemFeeRestored'} = 1
+ if $message->message eq 'lost_restored';
+
+ if ( $message->message eq 'lost_charge' ) {
+ $issue //= Koha::Old::Checkouts->search(
+ { itemnumber => $item->itemnumber },
+ { order_by => { '-desc' => 'returndate' }, rows => 1 }
+ )->single;
+ unless ( exists( $patron_unblessed->{branchcode} ) ) {
+ my $patron = $issue->patron;
+ $patron_unblessed = $patron->unblessed;
+ }
+ _CalculateAndUpdateFine(
+ {
+ issue => $issue,
+ item => $item->unblessed,
+ borrower => $patron_unblessed,
+ return_date => $return_date
+ }
+ );
+ _FixOverduesOnReturn( $patron_unblessed->{borrowernumber},
+ $item->itemnumber, undef, 'RETURNED' );
+ $messages->{'LostItemFeeCharged'} = 1;
+ }
+ }
}
}
# check if we have a transfer for this document
- my ($datesent,$frombranch,$tobranch) = GetTransfers( $item->itemnumber );
+ my $transfer = $item->get_transfer;
# if we have a transfer to complete, we update the line of transfers with the datearrived
- my $is_in_rotating_collection = C4::RotatingCollections::isItemInAnyCollection( $item->itemnumber );
- if ($datesent) {
- # At this point we will either fill the transfer or it is a wrong transfer
- # either way we should not now generate a new transfer
+ if ($transfer) {
$validTransfer = 0;
- if ( $tobranch eq $branch ) {
- my $sth = C4::Context->dbh->prepare(
- "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
- );
- $sth->execute( $item->itemnumber );
- $messages->{'TransferArrived'} = $frombranch;
- } else {
- $messages->{'WrongTransfer'} = $tobranch;
- $messages->{'WrongTransferItem'} = $item->itemnumber;
+ if ( $transfer->in_transit ) {
+ if ( $transfer->tobranch eq $branch ) {
+ $transfer->receive;
+ $messages->{'TransferArrived'} = $transfer->frombranch;
+ # validTransfer=1 allows us returning the item back if the reserve is cancelled
+ $validTransfer = 1 if $transfer->reason eq 'Reserve';
+ }
+ else {
+ $messages->{'WrongTransfer'} = $transfer->tobranch;
+ $messages->{'WrongTransferItem'} = $item->itemnumber;
+ $messages->{'TransferTrigger'} = $transfer->reason;
+ }
+ }
+ else {
+ if ( $transfer->tobranch eq $branch ) {
+ $transfer->receive;
+ $messages->{'TransferArrived'} = $transfer->frombranch;
+ # validTransfer=1 allows us returning the item back if the reserve is cancelled
+ $validTransfer = 1 if $transfer->reason eq 'Reserve';
+ }
+ else {
+ $messages->{'WasTransfered'} = $transfer->tobranch;
+ $messages->{'TransferTrigger'} = $transfer->reason;
+ }
}
}
}
}
+ # find recalls...
+ if ( C4::Context->preference('UseRecalls') ) {
+ # check if this item is recallable first, which includes checking if UseRecalls syspref is enabled
+ my $recall = undef;
+ $recall = $item->check_recalls if $item->can_be_waiting_recall;
+ if ( defined $recall ) {
+ $messages->{RecallFound} = $recall;
+ if ( $recall->branchcode ne $branch ) {
+ $messages->{RecallNeedsTransfer} = $branch;
+ }
+ }
+ }
+
# find reserves.....
# launch the Checkreserves routine to find any holds
my ($resfound, $resrec);
}
# Record the fact that this book was returned.
- UpdateStats({
+ C4::Stats::UpdateStats({
branch => $branch,
type => $stat_type,
itemnumber => $itemnumber,
item => $item->unblessed,
borrower => $patron->unblessed,
branch => $branch,
+ issue => $issue
});
}
$request->status('RET') if $request;
}
+ if ( C4::Context->preference('UseRecalls') ) {
+ # all recalls that have triggered a transfer will have an allocated itemnumber
+ my $transfer_recall = Koha::Recalls->find({ itemnumber => $item->itemnumber, status => 'in_transit' });
+ if ( $transfer_recall and $transfer_recall->branchcode eq $branch ) {
+ $messages->{TransferredRecall} = $transfer_recall;
+ }
+ }
+
# Transfer to returnbranch if Automatic transfer set or append message NeedsTransfer
- if ($validTransfer && !$is_in_rotating_collection && ($doreturn or $messages->{'NotIssued'}) and !$resfound and ($branch ne $returnbranch) ){
+ if ( $validTransfer && !C4::RotatingCollections::isItemInAnyCollection( $item->itemnumber )
+ && ( $doreturn or $messages->{'NotIssued'} )
+ and !$resfound
+ and ( $branch ne $returnbranch )
+ and not $messages->{'WrongTransfer'}
+ and not $messages->{'WasTransfered'}
+ and not $messages->{TransferredRecall}
+ and not $messages->{RecallNeedsTransfer} )
+ {
my $BranchTransferLimitsType = C4::Context->preference("BranchTransferLimitsType") eq 'itemtype' ? 'effective_itemtype' : 'ccode';
if (C4::Context->preference("AutomaticItemReturn" ) or
(C4::Context->preference("UseBranchTransferLimits") and
! IsBranchTransferAllowed($branch, $returnbranch, $item->$BranchTransferLimitsType )
)) {
- $debug and warn sprintf "about to call ModItemTransfer(%s, %s, %s, %s)", $item->itemnumber,$branch, $returnbranch, $transfer_trigger;
- $debug and warn "item: " . Dumper($item->unblessed);
- ModItemTransfer($item->itemnumber, $branch, $returnbranch, $transfer_trigger);
- $messages->{'WasTransfered'} = 1;
+ ModItemTransfer($item->itemnumber, $branch, $returnbranch, $transfer_trigger, { skip_record_index => 1 });
+ $messages->{'WasTransfered'} = $returnbranch;
+ $messages->{'TransferTrigger'} = $transfer_trigger;
} else {
$messages->{'NeedsTransfer'} = $returnbranch;
$messages->{'TransferTrigger'} = $transfer_trigger;
}
}
+ my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
+ $indexer->index_records( $item->biblionumber, "specialUpdate", "biblioserver" );
+
if ( $doreturn and $issue ) {
my $checkin = Koha::Old::Checkouts->find($issue->id);
=head2 MarkIssueReturned
- MarkIssueReturned($borrowernumber, $itemnumber, $returndate, $privacy);
+ MarkIssueReturned($borrowernumber, $itemnumber, $returndate, $privacy, [$params] );
Unconditionally marks an issue as being returned by
moving the C<issues> row to C<old_issues> and
not exported, but it is currently used in misc/cronjobs/longoverdue.pl
and offline_circ/process_koc.pl.
+The last optional parameter allos passing skip_record_index to the item store call.
+
=cut
sub MarkIssueReturned {
- my ( $borrowernumber, $itemnumber, $returndate, $privacy ) = @_;
+ my ( $borrowernumber, $itemnumber, $returndate, $privacy, $params ) = @_;
# Retrieve the issue
my $issue = Koha::Checkouts->find( { itemnumber => $itemnumber } ) or return;
my $issue_id = $issue->issue_id;
- my $anonymouspatron;
- if ( $privacy && $privacy == 2 ) {
- # The default of 0 will not work due to foreign key constraints
- # The anonymisation will fail if AnonymousPatron is not a valid entry
- # We need to check if the anonymous patron exist, Koha will fail loudly if it does not
- # Note that a warning should appear on the about page (System information tab).
- $anonymouspatron = C4::Context->preference('AnonymousPatron');
- 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."
- unless Koha::Patrons->find( $anonymouspatron );
- }
-
my $schema = Koha::Database->schema;
# FIXME Improve the return value and handle it from callers
# anonymise patron checkout immediately if $privacy set to 2 and AnonymousPatron is set to a valid borrowernumber
if ( $privacy && $privacy == 2) {
- $old_checkout->borrowernumber($anonymouspatron)->store;
+ $old_checkout->anonymize;
}
# And finally delete the issue
$issue->delete;
- $issue->item->onloan(undef)->store({ log_action => 0 });
+ $issue->item->onloan(undef)->store({ log_action => 0, skip_record_index => $params->{skip_record_index} });
if ( C4::Context->preference('StoreLastBorrower') ) {
my $item = Koha::Items->find( $itemnumber );
# grace period is measured in the same units as the loan
my $grace =
- DateTime::Duration->new( $unit => $issuing_rule->{firstremind} );
+ DateTime::Duration->new( $unit => $issuing_rule->{firstremind} // 0);
my $deltadays = DateTime::Duration->new(
days => $chargeable_units
branchcode => $branchcode,
days_mode => 'Calendar'
);
- $new_debar_dt = $calendar->addDate( $return_date, $suspension_days );
+ $new_debar_dt = $calendar->addDuration( $return_date, $suspension_days );
}
else {
$new_debar_dt = $return_date->clone()->add_duration($suspension_days);
my $amountoutstanding = $accountline->amountoutstanding;
if ( $accountline->amount == 0 && $payments->count == 0 ) {
$accountline->delete;
+ return 0; # no warning, we've just removed a zero value fine (backdated return)
} elsif ($exemptfine && ($amountoutstanding != 0)) {
my $account = Koha::Account->new({patron_id => $borrowernumber});
my $credit = $account->add_credit(
}
);
- $credit->apply({ debits => [ $accountline ], offset_type => 'Forgiven' });
+ $credit->apply({ debits => [ $accountline ] });
if (C4::Context->preference("FinesLog")) {
&logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
}
-
- $accountline->status('FORGIVEN');
- $accountline->store();
- } else {
- $accountline->status($status);
- $accountline->store();
-
}
+
+ $accountline->status($status);
+ return $accountline->store();
}
);
}
-=head2 GetBiblioIssues
-
- $issues = GetBiblioIssues($biblionumber);
-
-this function get all issues from a biblionumber.
-
-Return:
-C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash contains all column from
-tables issues and the firstname,surname & cardnumber from borrowers.
-
-=cut
-
-sub GetBiblioIssues {
- my $biblionumber = shift;
- return unless $biblionumber;
- my $dbh = C4::Context->dbh;
- my $query = "
- SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
- FROM issues
- LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
- LEFT JOIN items ON issues.itemnumber = items.itemnumber
- LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
- LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
- WHERE biblio.biblionumber = ?
- UNION ALL
- SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
- FROM old_issues
- LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
- LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
- LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
- LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
- WHERE biblio.biblionumber = ?
- ORDER BY timestamp
- ";
- my $sth = $dbh->prepare($query);
- $sth->execute($biblionumber, $biblionumber);
-
- my @issues;
- while ( my $data = $sth->fetchrow_hashref ) {
- push @issues, $data;
- }
- return \@issues;
-}
-
=head2 GetUpcomingDueIssues
my $upcoming_dues = GetUpcomingDueIssues( { days_in_advance => 4 } );
$params->{'days_in_advance'} = 7 unless exists $params->{'days_in_advance'};
my $dbh = C4::Context->dbh;
-
- my $statement = <<END_SQL;
-SELECT *
-FROM (
- SELECT issues.*, items.itype as itemtype, items.homebranch, TO_DAYS( date_due )-TO_DAYS( NOW() ) as days_until_due, branches.branchemail
- FROM issues
- LEFT JOIN items USING (itemnumber)
- LEFT OUTER JOIN branches USING (branchcode)
- WHERE returndate is NULL
-) tmp
-WHERE days_until_due >= 0 AND days_until_due <= ?
-END_SQL
-
+ my $statement;
+ $statement = q{
+ SELECT issues.*, items.itype as itemtype, items.homebranch, TO_DAYS( date_due )-TO_DAYS( NOW() ) as days_until_due, branches.branchemail
+ FROM issues
+ LEFT JOIN items USING (itemnumber)
+ LEFT JOIN branches ON branches.branchcode =
+ };
+ $statement .= $params->{'owning_library'} ? " items.homebranch " : " issues.branchcode ";
+ $statement .= " WHERE returndate is NULL AND TO_DAYS( date_due )-TO_DAYS( NOW() ) BETWEEN 0 AND ?";
my @bind_parameters = ( $params->{'days_in_advance'} );
my $sth = $dbh->prepare( $statement );
sub CanBookBeRenewed {
my ( $borrowernumber, $itemnumber, $override_limit, $cron ) = @_;
- my $dbh = C4::Context->dbh;
- my $renews = 1;
my $auto_renew = "no";
my $item = Koha::Items->find($itemnumber) or return ( 0, 'no_item' );
branchcode => $branchcode,
rules => [
'renewalsallowed',
- 'no_auto_renewal_after',
- 'no_auto_renewal_after_hard_limit',
'lengthunit',
- 'norenewalbefore',
+ 'unseen_renewals_allowed'
]
}
);
return ( 0, "too_many" )
if not $issuing_rule->{renewalsallowed} or $issuing_rule->{renewalsallowed} <= $issue->renewals;
+ return ( 0, "too_unseen" )
+ if C4::Context->preference('UnseenRenewals') &&
+ $issuing_rule->{unseen_renewals_allowed} &&
+ $issuing_rule->{unseen_renewals_allowed} <= $issue->unseen_renewals;
+
my $overduesblockrenewing = C4::Context->preference('OverduesBlockRenewing');
my $restrictionblockrenewing = C4::Context->preference('RestrictionBlockRenewing');
$patron = Koha::Patrons->find($borrowernumber); # FIXME Is this really useful?
return ( 0, 'overdue');
}
- if ( $issue->auto_renew && $patron->autorenew_checkouts ) {
-
- if ( $patron->category->effective_BlockExpiredPatronOpacActions and $patron->is_expired ) {
- return ( 0, 'auto_account_expired' );
- }
-
- if ( defined $issuing_rule->{no_auto_renewal_after}
- and $issuing_rule->{no_auto_renewal_after} ne "" ) {
- # Get issue_date and add no_auto_renewal_after
- # If this is greater than today, it's too late for renewal.
- my $maximum_renewal_date = dt_from_string($issue->issuedate, 'sql');
- $maximum_renewal_date->add(
- $issuing_rule->{lengthunit} => $issuing_rule->{no_auto_renewal_after}
- );
- my $now = dt_from_string;
- if ( $now >= $maximum_renewal_date ) {
- return ( 0, "auto_too_late" );
- }
- }
- if ( defined $issuing_rule->{no_auto_renewal_after_hard_limit}
- and $issuing_rule->{no_auto_renewal_after_hard_limit} ne "" ) {
- # If no_auto_renewal_after_hard_limit is >= today, it's also too late for renewal
- if ( dt_from_string >= dt_from_string( $issuing_rule->{no_auto_renewal_after_hard_limit} ) ) {
- return ( 0, "auto_too_late" );
- }
- }
-
- if ( C4::Context->preference('OPACFineNoRenewalsBlockAutoRenew') ) {
- my $fine_no_renewals = C4::Context->preference("OPACFineNoRenewals");
- my $amountoutstanding =
- C4::Context->preference("OPACFineNoRenewalsIncludeCredit")
- ? $patron->account->balance
- : $patron->account->outstanding_debits->total_outstanding;
- if ( $amountoutstanding and $amountoutstanding > $fine_no_renewals ) {
- return ( 0, "auto_too_much_oweing" );
- }
- }
- }
-
- if ( defined $issuing_rule->{norenewalbefore}
- and $issuing_rule->{norenewalbefore} ne "" )
- {
-
- # Calculate soonest renewal by subtracting 'No renewal before' from due date
- my $soonestrenewal = dt_from_string( $issue->date_due, 'sql' )->subtract(
- $issuing_rule->{lengthunit} => $issuing_rule->{norenewalbefore} );
-
- # Depending on syspref reset the exact time, only check the date
- if ( C4::Context->preference('NoRenewalBeforePrecision') eq 'date'
- and $issuing_rule->{lengthunit} eq 'days' )
- {
- $soonestrenewal->truncate( to => 'day' );
- }
-
- if ( $soonestrenewal > dt_from_string() )
- {
- $auto_renew = ($issue->auto_renew && $patron->autorenew_checkouts) ? "auto_too_soon" : "too_soon";
- }
- elsif ( $issue->auto_renew && $patron->autorenew_checkouts ) {
- $auto_renew = "ok";
- }
- }
+ $auto_renew = _CanBookBeAutoRenewed({
+ patron => $patron,
+ item => $item,
+ branchcode => $branchcode,
+ issue => $issue
+ });
+ return ( 0, $auto_renew ) if $auto_renew =~ 'auto_too_soon' && $cron;
+ # cron wants 'too_soon' over 'on_reserve' for performance and to avoid
+ # extra notices being sent. Cron also implies no override
+ return ( 0, $auto_renew ) if $auto_renew =~ 'auto_account_expired';
+ return ( 0, $auto_renew ) if $auto_renew =~ 'auto_too_late';
+ return ( 0, $auto_renew ) if $auto_renew =~ 'auto_too_much_oweing';
+ }
- # Fallback for automatic renewals:
- # If norenewalbefore is undef, don't renew before due date.
- if ( $issue->auto_renew && $auto_renew eq "no" && $patron->autorenew_checkouts ) {
- my $now = dt_from_string;
- if ( $now >= dt_from_string( $issue->date_due, 'sql' ) ){
- $auto_renew = "ok";
+ if ( C4::Context->preference('UseRecalls') ) {
+ my $recall = undef;
+ $recall = $item->check_recalls if $item->can_be_waiting_recall;
+ if ( defined $recall ) {
+ if ( $recall->item_level_recall ) {
+ # item-level recall. check if this item is the recalled item, otherwise renewal will be allowed
+ return ( 0, 'recalled' ) if ( $recall->itemnumber == $item->itemnumber );
} else {
- $auto_renew = "auto_too_soon";
+ # biblio-level recall, so only disallow renewal if the biblio-level recall has been fulfilled by a different item
+ return ( 0, 'recalled' ) unless ( $recall->waiting );
}
}
}
- my ( $resfound, $resrec, undef ) = C4::Reserves::CheckReserves($itemnumber);
+ my ( $resfound, $resrec, $possible_reserves ) = C4::Reserves::CheckReserves($itemnumber);
# If next hold is non priority, then check if any hold with priority (non_priority = 0) exists for the same biblionumber.
if ( $resfound && $resrec->{non_priority} ) {
if ( $resfound
&& C4::Context->preference('AllowRenewalIfOtherItemsAvailable') )
{
- my $schema = Koha::Database->new()->schema();
-
- my $item_holds = $schema->resultset('Reserve')->search( { itemnumber => $itemnumber, found => undef } )->count();
+ my $item_holds = Koha::Holds->search( { itemnumber => $itemnumber, found => undef } )->count();
if ($item_holds) {
# There is an item level hold on this item, no other item can fill the hold
$resfound = 1;
else {
# Get all other items that could possibly fill reserves
- my @itemnumbers = $schema->resultset('Item')->search(
- {
- biblionumber => $resrec->{biblionumber},
- onloan => undef,
- notforloan => 0,
- -not => { itemnumber => $itemnumber }
- },
- { columns => 'itemnumber' }
- )->get_column('itemnumber')->all();
+ my $items = Koha::Items->search({
+ biblionumber => $resrec->{biblionumber},
+ onloan => undef,
+ notforloan => 0,
+ -not => { itemnumber => $itemnumber }
+ });
# Get all other reserves that could have been filled by this item
- my @borrowernumbers;
- while (1) {
- my ( $reserve_found, $reserve, undef ) =
- C4::Reserves::CheckReserves( $itemnumber, undef, undef, \@borrowernumbers );
-
- if ($reserve_found) {
- push( @borrowernumbers, $reserve->{borrowernumber} );
- }
- else {
- last;
- }
- }
+ my @borrowernumbers = map { $_->{borrowernumber} } @$possible_reserves;
+ my $patrons = Koha::Patrons->search({
+ borrowernumber => { -in => \@borrowernumbers }
+ });
# If the count of the union of the lists of reservable items for each borrower
# is equal or greater than the number of borrowers, we know that all reserves
# can be filled with available items. We can get the union of the sets simply
# by pushing all the elements onto an array and removing the duplicates.
my @reservable;
- my %patrons;
- ITEM: foreach my $itemnumber (@itemnumbers) {
- my $item = Koha::Items->find( $itemnumber );
- next if IsItemOnHoldAndFound( $itemnumber );
- for my $borrowernumber (@borrowernumbers) {
- my $patron = $patrons{$borrowernumber} //= Koha::Patrons->find( $borrowernumber );
+ ITEM: while ( my $item = $items->next ) {
+ next if IsItemOnHoldAndFound( $item->itemnumber );
+ while ( my $patron = $patrons->next ) {
next unless IsAvailableForItemLevelRequest($item, $patron);
- next unless CanItemBeReserved($borrowernumber,$itemnumber);
-
- push @reservable, $itemnumber;
+ next unless CanItemBeReserved($patron,$item,undef,{ignore_hold_counts=>1})->{status} eq 'OK';
+ push @reservable, $item->itemnumber;
if (@reservable >= @borrowernumbers) {
$resfound = 0;
last ITEM;
}
last;
}
+ $patrons->reset;
}
}
}
- if( $cron ) { #The cron wants to return 'too_soon' over 'on_reserve'
- return ( 0, $auto_renew ) if $auto_renew =~ 'too_soon';#$auto_renew ne "no" && $auto_renew ne "ok";
- return ( 0, "on_reserve" ) if $resfound; # '' when no hold was found
- } else { # For other purposes we want 'on_reserve' before 'too_soon'
- return ( 0, "on_reserve" ) if $resfound; # '' when no hold was found
- return ( 0, $auto_renew ) if $auto_renew =~ 'too_soon';#$auto_renew ne "no" && $auto_renew ne "ok";
+
+ return ( 0, "on_reserve" ) if $resfound; # '' when no hold was found
+ return ( 0, $auto_renew ) if $auto_renew =~ 'too_soon';#$auto_renew ne "no" && $auto_renew ne "ok";
+ if ( GetSoonestRenewDate($borrowernumber, $itemnumber) > dt_from_string() ){
+ return (0, "too_soon") unless $override_limit;
}
return ( 0, "auto_renew" ) if $auto_renew eq "ok" && !$override_limit; # 0 if auto-renewal should not succeed
=head2 AddRenewal
- &AddRenewal($borrowernumber, $itemnumber, $branch, [$datedue], [$lastreneweddate]);
+ &AddRenewal($borrowernumber, $itemnumber, $branch, [$datedue], [$lastreneweddate], [$seen]);
Renews a loan.
If C<$datedue> is the empty string, C<&AddRenewal> will calculate the due date automatically
from the book's item type.
+C<$seen> is a boolean flag indicating if the item was seen or not during the renewal. This
+informs the incrementing of the unseen_renewals column. If this flag is not supplied, we
+fallback to a true value
+
=cut
sub AddRenewal {
my $datedue = shift;
my $lastreneweddate = shift || dt_from_string();
my $skipfinecalc = shift;
+ my $seen = shift;
+
+ # Fallback on a 'seen' renewal
+ $seen = defined $seen && $seen == 0 ? 0 : 1;
my $item_object = Koha::Items->find($itemnumber) or return;
my $biblio = $item_object->biblio;
}
);
+ # Increment the unseen renewals, if appropriate
+ # We only do so if the syspref is enabled and
+ # a maximum value has been set in the circ rules
+ my $unseen_renewals = $issue->unseen_renewals;
+ if (C4::Context->preference('UnseenRenewals')) {
+ my $rule = Koha::CirculationRules->get_effective_rule(
+ { categorycode => $patron->categorycode,
+ itemtype => $item_object->effective_itemtype,
+ branchcode => $circ_library->branchcode,
+ rule_name => 'unseen_renewals_allowed'
+ }
+ );
+ if (!$seen && $rule && $rule->rule_value) {
+ $unseen_renewals++;
+ } else {
+ # If the renewal is seen, unseen should revert to 0
+ $unseen_renewals = 0;
+ }
+ }
+
# Update the issues record to have the new due date, and a new count
# of how many times it has been renewed.
my $renews = ( $issue->renewals || 0 ) + 1;
- my $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?, lastreneweddate = ?
- WHERE borrowernumber=?
- AND itemnumber=?"
- );
+ my $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?, unseen_renewals = ?, lastreneweddate = ? WHERE issue_id = ?");
- $sth->execute( $datedue->strftime('%Y-%m-%d %H:%M'), $renews, $lastreneweddate, $borrowernumber, $itemnumber );
+ eval{
+ $sth->execute( $datedue->strftime('%Y-%m-%d %H:%M'), $renews, $unseen_renewals, $lastreneweddate, $issue->issue_id );
+ };
+ if( $sth->err ){
+ Koha::Exceptions::Checkout::FailedRenewal->throw(
+ error => 'Update of issue# ' . $issue->issue_id . ' failed with error: ' . $sth->errstr
+ );
+ }
# Update the renewal count on the item, and tell zebra to reindex
$renews = ( $item_object->renewals || 0 ) + 1;
}
# Add the renewal to stats
- UpdateStats(
+ C4::Stats::UpdateStats(
{
branch => $item_object->renewal_branchcode({branch => $branch}),
type => 'renew',
my ( $bornum, $itemno ) = @_;
my $dbh = C4::Context->dbh;
my $renewcount = 0;
+ my $unseencount = 0;
my $renewsallowed = 0;
+ my $unseenallowed = 0;
my $renewsleft = 0;
+ my $unseenleft = 0;
my $patron = Koha::Patrons->find( $bornum );
my $item = Koha::Items->find($itemno);
- return (0, 0, 0) unless $patron or $item; # Wrong call, no renewal allowed
+ return (0, 0, 0, 0, 0, 0) unless $patron or $item; # Wrong call, no renewal allowed
# Look in the issues table for this item, lent to this borrower,
# and not yet returned.
$sth->execute( $bornum, $itemno );
my $data = $sth->fetchrow_hashref;
$renewcount = $data->{'renewals'} if $data->{'renewals'};
+ $unseencount = $data->{'unseen_renewals'} if $data->{'unseen_renewals'};
# $item and $borrower should be calculated
my $branchcode = _GetCircControlBranch($item->unblessed, $patron->unblessed);
- my $rule = Koha::CirculationRules->get_effective_rule(
+ my $rules = Koha::CirculationRules->get_effective_rules(
{
categorycode => $patron->categorycode,
itemtype => $item->effective_itemtype,
branchcode => $branchcode,
- rule_name => 'renewalsallowed',
+ rules => [ 'renewalsallowed', 'unseen_renewals_allowed' ]
}
);
-
- $renewsallowed = $rule ? $rule->rule_value : 0;
+ $renewsallowed = $rules ? $rules->{renewalsallowed} : 0;
+ $unseenallowed = $rules->{unseen_renewals_allowed} ?
+ $rules->{unseen_renewals_allowed} :
+ 0;
$renewsleft = $renewsallowed - $renewcount;
+ $unseenleft = $unseenallowed - $unseencount;
if($renewsleft < 0){ $renewsleft = 0; }
- return ( $renewcount, $renewsallowed, $renewsleft );
+ if($unseenleft < 0){ $unseenleft = 0; }
+ return (
+ $renewcount,
+ $renewsallowed,
+ $renewsleft,
+ $unseencount,
+ $unseenallowed,
+ $unseenleft
+ );
}
=head2 GetSoonestRenewDate
);
my $now = dt_from_string;
- return $now unless $issuing_rule;
if ( defined $issuing_rule->{norenewalbefore}
and $issuing_rule->{norenewalbefore} ne "" )
$soonestrenewal->truncate( to => 'day' );
}
return $soonestrenewal if $now < $soonestrenewal;
+ } elsif ( $itemissue->auto_renew && $patron->autorenew_checkouts ) {
+ # Checkouts with auto-renewing fall back to due date
+ my $soonestrenewal = dt_from_string( $itemissue->date_due );
+ if ( C4::Context->preference('NoRenewalBeforePrecision') eq 'date'
+ and $issuing_rule->{lengthunit} eq 'days' )
+ {
+ $soonestrenewal->truncate( to => 'day' );
+ }
+ return $soonestrenewal;
}
return $now;
}
if ( my $item_data = $sth->fetchrow_hashref ) {
$item_type = $item_data->{itemtype};
$charge = $item_data->{rentalcharge};
- my $branch = C4::Context::mybranch();
- my $patron = Koha::Patrons->find( $borrowernumber );
- my $discount = _get_discount_from_rule($patron->categorycode, $branch, $item_type);
- if ($discount) {
- # We may have multiple rules so get the most specific
- $charge = ( $charge * ( 100 - $discount ) ) / 100;
- }
if ($charge) {
+ # FIXME This should follow CircControl
+ my $branch = C4::Context::mybranch();
+ my $patron = Koha::Patrons->find( $borrowernumber );
+ my $discount = Koha::CirculationRules->get_effective_rule({
+ categorycode => $patron->categorycode,
+ branchcode => $branch,
+ itemtype => $item_type,
+ rule_name => 'rentaldiscount'
+ });
+ if ($discount) {
+ $charge = ( $charge * ( 100 - $discount->rule_value ) ) / 100;
+ }
$charge = sprintf '%.2f', $charge; # ensure no fractions of a penny returned
}
}
return ( $charge, $item_type );
}
-# Select most appropriate discount rule from those returned
-sub _get_discount_from_rule {
- my ($categorycode, $branchcode, $itemtype) = @_;
-
- # Set search precedences
- my @params = (
- {
- branchcode => $branchcode,
- itemtype => $itemtype,
- categorycode => $categorycode,
- },
- {
- branchcode => undef,
- categorycode => $categorycode,
- itemtype => $itemtype,
- },
- {
- branchcode => $branchcode,
- categorycode => $categorycode,
- itemtype => undef,
- },
- {
- branchcode => undef,
- categorycode => $categorycode,
- itemtype => undef,
- },
- );
-
- foreach my $params (@params) {
- my $rule = Koha::CirculationRules->search(
- {
- rule_name => 'rentaldiscount',
- %$params,
- }
- )->next();
-
- return $rule->rule_value if $rule;
- }
-
- # none of the above
- return 0;
-}
-
=head2 AddIssuingCharge
&AddIssuingCharge( $checkout, $charge, $type )
SELECT datesent,
frombranch,
tobranch,
- branchtransfer_id
+ branchtransfer_id,
+ daterequested,
+ reason
FROM branchtransfers
WHERE itemnumber = ?
AND datearrived IS NULL
+ AND datecancelled IS NULL
';
my $sth = $dbh->prepare($query);
$sth->execute($itemnumber);
FROM branchtransfers
WHERE frombranch=?
AND tobranch=?
+ AND datecancelled IS NULL
+ AND datesent IS NOT NULL
AND datearrived IS NULL
";
my $sth = $dbh->prepare($query);
return (@gettransfers);
}
-=head2 DeleteTransfer
-
- &DeleteTransfer($itemnumber);
-
-=cut
-
-sub DeleteTransfer {
- my ($itemnumber) = @_;
- return unless $itemnumber;
- my $dbh = C4::Context->dbh;
- my $sth = $dbh->prepare(
- "DELETE FROM branchtransfers
- WHERE itemnumber=?
- AND datearrived IS NULL "
- );
- return $sth->execute($itemnumber);
-}
-
=head2 SendCirculationAlert
Send out a C<check-in> or C<checkout> alert using the messaging system.
sub SendCirculationAlert {
my ($opts) = @_;
- my ($type, $item, $borrower, $branch) =
- ($opts->{type}, $opts->{item}, $opts->{borrower}, $opts->{branch});
+ my ($type, $item, $borrower, $branch, $issue) =
+ ($opts->{type}, $opts->{item}, $opts->{borrower}, $opts->{branch}, $opts->{issue});
my %message_name = (
CHECKIN => 'Item_Check_in',
CHECKOUT => 'Item_Checkout',
borrowernumber => $borrower->{borrowernumber},
message_name => $message_name{$type},
});
- my $issues_table = ( $type eq 'CHECKOUT' || $type eq 'RENEWAL' ) ? 'issues' : 'old_issues';
+
+
+ my $tables = {
+ items => $item->{itemnumber},
+ biblio => $item->{biblionumber},
+ biblioitems => $item->{biblionumber},
+ borrowers => $borrower,
+ branches => $branch,
+ };
+
+ # TODO: Currently, we need to pass an issue_id as identifier for old_issues, but still an itemnumber for issues.
+ # See C4::Letters:: _parseletter_sth
+ if( $type eq 'CHECKIN' ){
+ $tables->{old_issues} = $issue->issue_id;
+ } else {
+ $tables->{issues} = $item->{itemnumber};
+ }
my $schema = Koha::Database->new->schema;
my @transports = keys %{ $borrower_preferences->{transports} };
branchcode => $branch,
message_transport_type => $mtt,
lang => $borrower->{lang},
- tables => {
- $issues_table => $item->{itemnumber},
- 'items' => $item->{itemnumber},
- 'biblio' => $item->{biblionumber},
- 'biblioitems' => $item->{biblionumber},
- 'borrowers' => $borrower,
- 'branches' => $branch,
- }
+ tables => $tables,
) or next;
- $schema->storage->txn_begin;
C4::Context->dbh->do(q|LOCK TABLE message_queue READ|) unless $do_not_lock;
C4::Context->dbh->do(q|LOCK TABLE message_queue WRITE|) unless $do_not_lock;
my $message = C4::Message->find_last_message($borrower, $type, $mtt);
$message->update;
}
C4::Context->dbh->do(q|UNLOCK TABLES|) unless $do_not_lock;
- $schema->storage->txn_commit;
}
return;
sub updateWrongTransfer {
my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
- my $dbh = C4::Context->dbh;
-# first step validate the actual line of transfert .
- my $sth =
- $dbh->prepare(
- "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
- );
- $sth->execute($FromLibrary,$itemNumber);
-
-# second step create a new line of branchtransfer to the right location .
- ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
-
-#third step changing holdingbranch of item
- my $item = Koha::Items->find($itemNumber)->holdingbranch($FromLibrary)->store;
+
+ # first step: cancel the original transfer
+ my $item = Koha::Items->find($itemNumber);
+ my $transfer = $item->get_transfer;
+ $transfer->set({ datecancelled => dt_from_string, cancellation_reason => 'WrongTransfer' })->store();
+
+ # second step: create a new transfer to the right location
+ my $new_transfer = $item->request_transfer(
+ {
+ to => $transfer->to_library,
+ reason => $transfer->reason,
+ comment => $transfer->comments,
+ ignore_limits => 1,
+ enqueue => 1
+ }
+ );
+
+ return $new_transfer;
}
=head2 CalcDateDue
$dur = DateTime::Duration->new( days => $loanlength->{$length_key});
}
my $calendar = Koha::Calendar->new( branchcode => $branch, days_mode => $daysmode );
- $datedue = $calendar->addDate( $datedue, $dur, $loanlength->{lengthunit} );
+ $datedue = $calendar->addDuration( $datedue, $dur, $loanlength->{lengthunit} );
if ($loanlength->{lengthunit} eq 'days') {
$datedue->set_hour(23);
$datedue->set_minute(59);
#warn " $issues->{'borrowernumber'} / $itemnumber ";
}
- MarkIssueReturned($borrowernumber,$itemnumber,undef,$patron->privacy) if $mark_returned;
+ MarkIssueReturned($borrowernumber,$itemnumber,undef,$patron->privacy,$params) if $mark_returned;
}
- #When item is marked lost automatically cancel its outstanding transfers and set items holdingbranch to the transfer source branch (frombranch)
- if (my ( $datesent,$frombranch,$tobranch ) = GetTransfers($itemnumber)) {
- Koha::Items->find($itemnumber)->holdingbranch($frombranch)->store({ skip_record_index => $params->{skip_record_index} });
+ # When an item is marked as lost, we should automatically cancel its outstanding transfers.
+ my $item = Koha::Items->find($itemnumber);
+ my $transfers = $item->get_transfers;
+ while (my $transfer = $transfers->next) {
+ $transfer->cancel({ reason => 'ItemLost', force => 1 });
}
- my $transferdeleted = DeleteTransfer($itemnumber);
}
sub GetOfflineOperations {
}
}
+sub _CanBookBeAutoRenewed {
+ my ( $params ) = @_;
+ my $patron = $params->{patron};
+ my $item = $params->{item};
+ my $branchcode = $params->{branchcode};
+ my $issue = $params->{issue};
+
+ return "no" unless $issue->auto_renew && $patron->autorenew_checkouts;
+
+ my $issuing_rule = Koha::CirculationRules->get_effective_rules(
+ {
+ categorycode => $patron->categorycode,
+ itemtype => $item->effective_itemtype,
+ branchcode => $branchcode,
+ rules => [
+ 'no_auto_renewal_after',
+ 'no_auto_renewal_after_hard_limit',
+ 'lengthunit',
+ 'norenewalbefore',
+ ]
+ }
+ );
+
+ if ( $patron->category->effective_BlockExpiredPatronOpacActions and $patron->is_expired ) {
+ return 'auto_account_expired';
+ }
+
+ if ( defined $issuing_rule->{no_auto_renewal_after}
+ and $issuing_rule->{no_auto_renewal_after} ne "" ) {
+ # Get issue_date and add no_auto_renewal_after
+ # If this is greater than today, it's too late for renewal.
+ my $maximum_renewal_date = dt_from_string($issue->issuedate, 'sql');
+ $maximum_renewal_date->add(
+ $issuing_rule->{lengthunit} => $issuing_rule->{no_auto_renewal_after}
+ );
+ my $now = dt_from_string;
+ if ( $now >= $maximum_renewal_date ) {
+ return "auto_too_late";
+ }
+ }
+ if ( defined $issuing_rule->{no_auto_renewal_after_hard_limit}
+ and $issuing_rule->{no_auto_renewal_after_hard_limit} ne "" ) {
+ # If no_auto_renewal_after_hard_limit is >= today, it's also too late for renewal
+ if ( dt_from_string >= dt_from_string( $issuing_rule->{no_auto_renewal_after_hard_limit} ) ) {
+ return "auto_too_late";
+ }
+ }
+
+ if ( C4::Context->preference('OPACFineNoRenewalsBlockAutoRenew') ) {
+ my $fine_no_renewals = C4::Context->preference("OPACFineNoRenewals");
+ my $amountoutstanding =
+ C4::Context->preference("OPACFineNoRenewalsIncludeCredit")
+ ? $patron->account->balance
+ : $patron->account->outstanding_debits->total_outstanding;
+ if ( $amountoutstanding and $amountoutstanding > $fine_no_renewals ) {
+ return "auto_too_much_oweing";
+ }
+ }
+
+ if ( defined $issuing_rule->{norenewalbefore}
+ and $issuing_rule->{norenewalbefore} ne "" ) {
+ if ( GetSoonestRenewDate($patron->id, $item->id) > dt_from_string()) {
+ return "auto_too_soon";
+ } else {
+ return "ok";
+ }
+ }
+
+ # Fallback for automatic renewals:
+ # If norenewalbefore is undef, don't renew before due date.
+ my $now = dt_from_string;
+ if ( $now >= dt_from_string( $issue->date_due, 'sql' ) ){
+ return "ok";
+ } else {
+ return "auto_too_soon";
+ }
+}
+
sub _item_denied_renewal {
my ($params) = @_;