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 under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #use warnings; FIXME - Bug 2505
32 use C4::Dates qw(format_date);
34 use C4::ItemCirculationAlertPreference;
37 use C4::Branch; # GetBranches
38 use C4::Log; # logaction
40 GetAuthorisedValueByCode
42 GetKohaAuthorisedValueLib
44 use C4::Overdues qw(CalcFine UpdateFine);
45 use C4::RotatingCollections qw(GetCollectionItemBranches);
46 use Algorithm::CheckDigits;
51 use Koha::Borrower::Debarments;
62 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
66 $VERSION = 3.07.00.049; # for version checking
69 # FIXME subs that should probably be elsewhere
76 # subs to deal with issuing a book
88 &GetBranchBorrowerCircRule
92 &AnonymiseIssueHistory
93 &CheckIfIssuedToPatron
97 # subs to deal with returns
103 # subs to deal with transfers
110 &IsBranchTransferAllowed
111 &CreateBranchTransferLimit
112 &DeleteBranchTransferLimits
116 # subs to deal with offline circulation
118 &GetOfflineOperations
121 &DeleteOfflineOperation
122 &ProcessOfflineOperation
128 C4::Circulation - Koha circulation module
136 The functions in this module deal with circulation, issues, and
137 returns, as well as general information about the library.
138 Also deals with stocktaking.
144 $str = &barcodedecode($barcode, [$filter]);
146 Generic filter function for barcode string.
147 Called on every circ if the System Pref itemBarcodeInputFilter is set.
148 Will do some manipulation of the barcode for systems that deliver a barcode
149 to circulation.pl that differs from the barcode stored for the item.
150 For proper functioning of this filter, calling the function on the
151 correct barcode string (items.barcode) should return an unaltered barcode.
153 The optional $filter argument is to allow for testing or explicit
154 behavior that ignores the System Pref. Valid values are the same as the
159 # FIXME -- the &decode fcn below should be wrapped into this one.
160 # FIXME -- these plugins should be moved out of Circulation.pm
163 my ($barcode, $filter) = @_;
164 my $branch = C4::Branch::mybranch();
165 $filter = C4::Context->preference('itemBarcodeInputFilter') unless $filter;
166 $filter or return $barcode; # ensure filter is defined, else return untouched barcode
167 if ($filter eq 'whitespace') {
169 } elsif ($filter eq 'cuecat') {
171 my @fields = split( /\./, $barcode );
172 my @results = map( decode($_), @fields[ 1 .. $#fields ] );
173 ($#results == 2) and return $results[2];
174 } elsif ($filter eq 'T-prefix') {
175 if ($barcode =~ /^[Tt](\d)/) {
176 (defined($1) and $1 eq '0') and return $barcode;
177 $barcode = substr($barcode, 2) + 0; # FIXME: probably should be substr($barcode, 1)
179 return sprintf("T%07d", $barcode);
180 # FIXME: $barcode could be "T1", causing warning: substr outside of string
181 # Why drop the nonzero digit after the T?
182 # Why pass non-digits (or empty string) to "T%07d"?
183 } elsif ($filter eq 'libsuite8') {
184 unless($barcode =~ m/^($branch)-/i){ #if barcode starts with branch code its in Koha style. Skip it.
185 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
186 $barcode =~ s/^[0]*(\d+)$/$branch-b-$1/i;
188 $barcode =~ s/^(\D+)[0]*(\d+)$/$branch-$1-$2/i;
191 } elsif ($filter eq 'EAN13') {
192 my $ean = CheckDigits('ean');
193 if ( $ean->is_valid($barcode) ) {
194 #$barcode = sprintf('%013d',$barcode); # this doesn't work on 32-bit systems
195 $barcode = '0' x ( 13 - length($barcode) ) . $barcode;
197 warn "# [$barcode] not valid EAN-13/UPC-A\n";
200 return $barcode; # return barcode, modified or not
205 $str = &decode($chunk);
207 Decodes a segment of a string emitted by a CueCat barcode scanner and
210 FIXME: Should be replaced with Barcode::Cuecat from CPAN
211 or Javascript based decoding on the client side.
218 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
219 my @s = map { index( $seq, $_ ); } split( //, $encoded );
220 my $l = ( $#s + 1 ) % 4;
223 # warn "Error: Cuecat decode parsing failed!";
231 my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
233 chr( ( $n >> 16 ) ^ 67 )
234 .chr( ( $n >> 8 & 255 ) ^ 67 )
235 .chr( ( $n & 255 ) ^ 67 );
238 $r = substr( $r, 0, length($r) - $l );
244 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch,
245 $barcode, $ignore_reserves);
247 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
249 C<$newbranch> is the code for the branch to which the item should be transferred.
251 C<$barcode> is the barcode of the item to be transferred.
253 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
254 Otherwise, if an item is reserved, the transfer fails.
256 Returns three values:
262 is true if the transfer was successful.
266 is a reference-to-hash which may have any of the following keys:
272 There is no item in the catalog with the given barcode. The value is C<$barcode>.
276 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.
278 =item C<DestinationEqualsHolding>
280 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.
284 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.
288 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>.
290 =item C<WasTransferred>
292 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
301 my ( $tbr, $barcode, $ignoreRs ) = @_;
304 my $branches = GetBranches();
305 my $itemnumber = GetItemnumberFromBarcode( $barcode );
306 my $issue = GetItemIssue($itemnumber);
307 my $biblio = GetBiblioFromItemNumber($itemnumber);
310 if ( not $itemnumber ) {
311 $messages->{'BadBarcode'} = $barcode;
315 # get branches of book...
316 my $hbr = $biblio->{'homebranch'};
317 my $fbr = $biblio->{'holdingbranch'};
319 # if using Branch Transfer Limits
320 if ( C4::Context->preference("UseBranchTransferLimits") == 1 ) {
321 if ( C4::Context->preference("item-level_itypes") && C4::Context->preference("BranchTransferLimitsType") eq 'itemtype' ) {
322 if ( ! IsBranchTransferAllowed( $tbr, $fbr, $biblio->{'itype'} ) ) {
323 $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{'itype'};
326 } elsif ( ! IsBranchTransferAllowed( $tbr, $fbr, $biblio->{ C4::Context->preference("BranchTransferLimitsType") } ) ) {
327 $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{ C4::Context->preference("BranchTransferLimitsType") };
333 if ( $hbr && $branches->{$hbr}->{'PE'} ) {
334 $messages->{'IsPermanent'} = $hbr;
338 # can't transfer book if is already there....
339 if ( $fbr eq $tbr ) {
340 $messages->{'DestinationEqualsHolding'} = 1;
344 # check if it is still issued to someone, return it...
345 if ($issue->{borrowernumber}) {
346 AddReturn( $barcode, $fbr );
347 $messages->{'WasReturned'} = $issue->{borrowernumber};
351 # That'll save a database query.
352 my ( $resfound, $resrec, undef ) =
353 CheckReserves( $itemnumber );
354 if ( $resfound and not $ignoreRs ) {
355 $resrec->{'ResFound'} = $resfound;
357 # $messages->{'ResFound'} = $resrec;
361 #actually do the transfer....
363 ModItemTransfer( $itemnumber, $fbr, $tbr );
365 # don't need to update MARC anymore, we do it in batch now
366 $messages->{'WasTransfered'} = 1;
369 ModDateLastSeen( $itemnumber );
370 return ( $dotransfer, $messages, $biblio );
375 my $borrower = shift;
376 my $biblionumber = shift;
378 my $cat_borrower = $borrower->{'categorycode'};
379 my $dbh = C4::Context->dbh;
381 # Get which branchcode we need
382 $branch = _GetCircControlBranch($item,$borrower);
383 my $type = (C4::Context->preference('item-level_itypes'))
384 ? $item->{'itype'} # item-level
385 : $item->{'itemtype'}; # biblio-level
387 # given branch, patron category, and item type, determine
388 # applicable issuing rule
389 my $issuing_rule = GetIssuingRule($cat_borrower, $type, $branch);
391 # if a rule is found and has a loan limit set, count
392 # how many loans the patron already has that meet that
394 if (defined($issuing_rule) and defined($issuing_rule->{'maxissueqty'})) {
396 my $count_query = "SELECT COUNT(*) FROM issues
397 JOIN items USING (itemnumber) ";
399 my $rule_itemtype = $issuing_rule->{itemtype};
400 if ($rule_itemtype eq "*") {
401 # matching rule has the default item type, so count only
402 # those existing loans that don't fall under a more
404 if (C4::Context->preference('item-level_itypes')) {
405 $count_query .= " WHERE items.itype NOT IN (
406 SELECT itemtype FROM issuingrules
408 AND (categorycode = ? OR categorycode = ?)
412 $count_query .= " JOIN biblioitems USING (biblionumber)
413 WHERE biblioitems.itemtype NOT IN (
414 SELECT itemtype FROM issuingrules
416 AND (categorycode = ? OR categorycode = ?)
420 push @bind_params, $issuing_rule->{branchcode};
421 push @bind_params, $issuing_rule->{categorycode};
422 push @bind_params, $cat_borrower;
424 # rule has specific item type, so count loans of that
426 if (C4::Context->preference('item-level_itypes')) {
427 $count_query .= " WHERE items.itype = ? ";
429 $count_query .= " JOIN biblioitems USING (biblionumber)
430 WHERE biblioitems.itemtype= ? ";
432 push @bind_params, $type;
435 $count_query .= " AND borrowernumber = ? ";
436 push @bind_params, $borrower->{'borrowernumber'};
437 my $rule_branch = $issuing_rule->{branchcode};
438 if ($rule_branch ne "*") {
439 if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
440 $count_query .= " AND issues.branchcode = ? ";
441 push @bind_params, $branch;
442 } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
443 ; # if branch is the patron's home branch, then count all loans by patron
445 $count_query .= " AND items.homebranch = ? ";
446 push @bind_params, $branch;
450 my $count_sth = $dbh->prepare($count_query);
451 $count_sth->execute(@bind_params);
452 my ($current_loan_count) = $count_sth->fetchrow_array;
454 my $max_loans_allowed = $issuing_rule->{'maxissueqty'};
455 if ($current_loan_count >= $max_loans_allowed) {
456 return ($current_loan_count, $max_loans_allowed);
460 # Now count total loans against the limit for the branch
461 my $branch_borrower_circ_rule = GetBranchBorrowerCircRule($branch, $cat_borrower);
462 if (defined($branch_borrower_circ_rule->{maxissueqty})) {
463 my @bind_params = ();
464 my $branch_count_query = "SELECT COUNT(*) FROM issues
465 JOIN items USING (itemnumber)
466 WHERE borrowernumber = ? ";
467 push @bind_params, $borrower->{borrowernumber};
469 if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
470 $branch_count_query .= " AND issues.branchcode = ? ";
471 push @bind_params, $branch;
472 } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
473 ; # if branch is the patron's home branch, then count all loans by patron
475 $branch_count_query .= " AND items.homebranch = ? ";
476 push @bind_params, $branch;
478 my $branch_count_sth = $dbh->prepare($branch_count_query);
479 $branch_count_sth->execute(@bind_params);
480 my ($current_loan_count) = $branch_count_sth->fetchrow_array;
482 my $max_loans_allowed = $branch_borrower_circ_rule->{maxissueqty};
483 if ($current_loan_count >= $max_loans_allowed) {
484 return ($current_loan_count, $max_loans_allowed);
488 # OK, the patron can issue !!!
494 @issues = &itemissues($biblioitemnumber, $biblio);
496 Looks up information about who has borrowed the bookZ<>(s) with the
497 given biblioitemnumber.
499 C<$biblio> is ignored.
501 C<&itemissues> returns an array of references-to-hash. The keys
502 include the fields from the C<items> table in the Koha database.
503 Additional keys include:
509 If the item is currently on loan, this gives the due date.
511 If the item is not on loan, then this is either "Available" or
512 "Cancelled", if the item has been withdrawn.
516 If the item is currently on loan, this gives the card number of the
517 patron who currently has the item.
519 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
521 These give the timestamp for the last three times the item was
524 =item C<card0>, C<card1>, C<card2>
526 The card number of the last three patrons who borrowed this item.
528 =item C<borrower0>, C<borrower1>, C<borrower2>
530 The borrower number of the last three patrons who borrowed this item.
538 my ( $bibitem, $biblio ) = @_;
539 my $dbh = C4::Context->dbh;
541 $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
546 $sth->execute($bibitem) || die $sth->errstr;
548 while ( my $data = $sth->fetchrow_hashref ) {
550 # Find out who currently has this item.
551 # FIXME - Wouldn't it be better to do this as a left join of
552 # some sort? Currently, this code assumes that if
553 # fetchrow_hashref() fails, then the book is on the shelf.
554 # fetchrow_hashref() can fail for any number of reasons (e.g.,
555 # database server crash), not just because no items match the
557 my $sth2 = $dbh->prepare(
558 "SELECT * FROM issues
559 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
564 $sth2->execute( $data->{'itemnumber'} );
565 if ( my $data2 = $sth2->fetchrow_hashref ) {
566 $data->{'date_due'} = $data2->{'date_due'};
567 $data->{'card'} = $data2->{'cardnumber'};
568 $data->{'borrower'} = $data2->{'borrowernumber'};
571 $data->{'date_due'} = ($data->{'withdrawn'} eq '1') ? 'Cancelled' : 'Available';
575 # Find the last 3 people who borrowed this item.
576 $sth2 = $dbh->prepare(
577 "SELECT * FROM old_issues
578 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
580 ORDER BY returndate DESC,timestamp DESC"
583 $sth2->execute( $data->{'itemnumber'} );
584 for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
585 { # FIXME : error if there is less than 3 pple borrowing this item
586 if ( my $data2 = $sth2->fetchrow_hashref ) {
587 $data->{"timestamp$i2"} = $data2->{'timestamp'};
588 $data->{"card$i2"} = $data2->{'cardnumber'};
589 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
593 $results[$i] = $data;
600 =head2 CanBookBeIssued
602 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $borrower,
603 $barcode, $duedatespec, $inprocess, $ignore_reserves );
605 Check if a book can be issued.
607 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
611 =item C<$borrower> hash with borrower informations (from GetMember or GetMemberDetails)
613 =item C<$barcode> is the bar code of the book being issued.
615 =item C<$duedatespec> is a C4::Dates object.
617 =item C<$inprocess> boolean switch
618 =item C<$ignore_reserves> boolean switch
626 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
627 Possible values are :
633 sticky due date is invalid
637 borrower gone with no address
641 borrower declared it's card lost
647 =head3 UNKNOWN_BARCODE
661 item is restricted (set by ??)
663 C<$needsconfirmation> a reference to a hash. It contains reasons why the loan
664 could be prevented, but ones that can be overriden by the operator.
666 Possible values are :
674 renewing, not issuing
676 =head3 ISSUED_TO_ANOTHER
678 issued to someone else.
682 reserved for someone else.
686 sticky due date is invalid or due date in the past
690 if the borrower borrows to much things
694 sub CanBookBeIssued {
695 my ( $borrower, $barcode, $duedate, $inprocess, $ignore_reserves ) = @_;
696 my %needsconfirmation; # filled with problems that needs confirmations
697 my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
698 my %alerts; # filled with messages that shouldn't stop issuing, but the librarian should be aware of.
700 my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
701 my $issue = GetItemIssue($item->{itemnumber});
702 my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
703 $item->{'itemtype'}=$item->{'itype'};
704 my $dbh = C4::Context->dbh;
706 # MANDATORY CHECKS - unless item exists, nothing else matters
707 unless ( $item->{barcode} ) {
708 $issuingimpossible{UNKNOWN_BARCODE} = 1;
710 return ( \%issuingimpossible, \%needsconfirmation ) if %issuingimpossible;
713 # DUE DATE is OK ? -- should already have checked.
715 if ($duedate && ref $duedate ne 'DateTime') {
716 $duedate = dt_from_string($duedate);
718 my $now = DateTime->now( time_zone => C4::Context->tz() );
719 unless ( $duedate ) {
720 my $issuedate = $now->clone();
722 my $branch = _GetCircControlBranch($item,$borrower);
723 my $itype = ( C4::Context->preference('item-level_itypes') ) ? $item->{'itype'} : $biblioitem->{'itemtype'};
724 $duedate = CalcDateDue( $issuedate, $itype, $branch, $borrower );
726 # Offline circ calls AddIssue directly, doesn't run through here
727 # So issuingimpossible should be ok.
730 my $today = $now->clone();
731 $today->truncate( to => 'minute');
732 if (DateTime->compare($duedate,$today) == -1 ) { # duedate cannot be before now
733 $needsconfirmation{INVALID_DATE} = output_pref($duedate);
736 $issuingimpossible{INVALID_DATE} = output_pref($duedate);
742 if ( $borrower->{'category_type'} eq 'X' && ( $item->{barcode} )) {
743 # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1 .
745 branch => C4::Context->userenv->{'branch'},
747 itemnumber => $item->{'itemnumber'},
748 itemtype => $item->{'itemtype'},
749 borrowernumber => $borrower->{'borrowernumber'},
750 ccode => $item->{'ccode'}}
752 ModDateLastSeen( $item->{'itemnumber'} );
753 return( { STATS => 1 }, {});
755 if ( $borrower->{flags}->{GNA} ) {
756 $issuingimpossible{GNA} = 1;
758 if ( $borrower->{flags}->{'LOST'} ) {
759 $issuingimpossible{CARD_LOST} = 1;
761 if ( $borrower->{flags}->{'DBARRED'} ) {
762 $issuingimpossible{DEBARRED} = 1;
764 if ( !defined $borrower->{dateexpiry} || $borrower->{'dateexpiry'} eq '0000-00-00') {
765 $issuingimpossible{EXPIRED} = 1;
767 my ($y, $m, $d) = split /-/,$borrower->{'dateexpiry'};
768 if ($y && $m && $d) { # are we really writing oinvalid dates to borrs
769 my $expiry_dt = DateTime->new(
773 time_zone => C4::Context->tz,
775 $expiry_dt->truncate( to => 'day');
776 my $today = $now->clone()->truncate(to => 'day');
777 if (DateTime->compare($today, $expiry_dt) == 1) {
778 $issuingimpossible{EXPIRED} = 1;
781 carp("Invalid expity date in borr");
782 $issuingimpossible{EXPIRED} = 1;
790 my ($balance, $non_issue_charges, $other_charges) =
791 C4::Members::GetMemberAccountBalance( $borrower->{'borrowernumber'} );
792 my $amountlimit = C4::Context->preference("noissuescharge");
793 my $allowfineoverride = C4::Context->preference("AllowFineOverride");
794 my $allfinesneedoverride = C4::Context->preference("AllFinesNeedOverride");
795 if ( C4::Context->preference("IssuingInProcess") ) {
796 if ( $non_issue_charges > $amountlimit && !$inprocess && !$allowfineoverride) {
797 $issuingimpossible{DEBT} = sprintf( "%.2f", $non_issue_charges );
798 } elsif ( $non_issue_charges > $amountlimit && !$inprocess && $allowfineoverride) {
799 $needsconfirmation{DEBT} = sprintf( "%.2f", $non_issue_charges );
800 } elsif ( $allfinesneedoverride && $non_issue_charges > 0 && $non_issue_charges <= $amountlimit && !$inprocess ) {
801 $needsconfirmation{DEBT} = sprintf( "%.2f", $non_issue_charges );
805 if ( $non_issue_charges > $amountlimit && $allowfineoverride ) {
806 $needsconfirmation{DEBT} = sprintf( "%.2f", $non_issue_charges );
807 } elsif ( $non_issue_charges > $amountlimit && !$allowfineoverride) {
808 $issuingimpossible{DEBT} = sprintf( "%.2f", $non_issue_charges );
809 } elsif ( $non_issue_charges > 0 && $allfinesneedoverride ) {
810 $needsconfirmation{DEBT} = sprintf( "%.2f", $non_issue_charges );
813 if ($balance > 0 && $other_charges > 0) {
814 $alerts{OTHER_CHARGES} = sprintf( "%.2f", $other_charges );
817 my ($blocktype, $count) = C4::Members::IsMemberBlocked($borrower->{'borrowernumber'});
818 if ($blocktype == -1) {
819 ## patron has outstanding overdue loans
820 if ( C4::Context->preference("OverduesBlockCirc") eq 'block'){
821 $issuingimpossible{USERBLOCKEDOVERDUE} = $count;
823 elsif ( C4::Context->preference("OverduesBlockCirc") eq 'confirmation'){
824 $needsconfirmation{USERBLOCKEDOVERDUE} = $count;
826 } elsif($blocktype == 1) {
827 # patron has accrued fine days or has a restriction. $count is a date
828 if ($count eq '9999-12-31') {
829 $issuingimpossible{USERBLOCKEDNOENDDATE} = $count;
832 $issuingimpossible{USERBLOCKEDWITHENDDATE} = $count;
837 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
839 my ($current_loan_count, $max_loans_allowed) = TooMany( $borrower, $item->{biblionumber}, $item );
840 # if TooMany max_loans_allowed returns 0 the user doesn't have permission to check out this book
841 if (defined $max_loans_allowed && $max_loans_allowed == 0) {
842 $needsconfirmation{PATRON_CANT} = 1;
844 if($max_loans_allowed){
845 if ( C4::Context->preference("AllowTooManyOverride") ) {
846 $needsconfirmation{TOO_MANY} = 1;
847 $needsconfirmation{current_loan_count} = $current_loan_count;
848 $needsconfirmation{max_loans_allowed} = $max_loans_allowed;
850 $issuingimpossible{TOO_MANY} = 1;
851 $issuingimpossible{current_loan_count} = $current_loan_count;
852 $issuingimpossible{max_loans_allowed} = $max_loans_allowed;
860 if ( $item->{'notforloan'} )
862 if(!C4::Context->preference("AllowNotForLoanOverride")){
863 $issuingimpossible{NOT_FOR_LOAN} = 1;
864 $issuingimpossible{item_notforloan} = $item->{'notforloan'};
866 $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
867 $needsconfirmation{item_notforloan} = $item->{'notforloan'};
871 # we have to check itemtypes.notforloan also
872 if (C4::Context->preference('item-level_itypes')){
873 # this should probably be a subroutine
874 my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
875 $sth->execute($item->{'itemtype'});
876 my $notforloan=$sth->fetchrow_hashref();
877 if ($notforloan->{'notforloan'}) {
878 if (!C4::Context->preference("AllowNotForLoanOverride")) {
879 $issuingimpossible{NOT_FOR_LOAN} = 1;
880 $issuingimpossible{itemtype_notforloan} = $item->{'itype'};
882 $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
883 $needsconfirmation{itemtype_notforloan} = $item->{'itype'};
887 elsif ($biblioitem->{'notforloan'} == 1){
888 if (!C4::Context->preference("AllowNotForLoanOverride")) {
889 $issuingimpossible{NOT_FOR_LOAN} = 1;
890 $issuingimpossible{itemtype_notforloan} = $biblioitem->{'itemtype'};
892 $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
893 $needsconfirmation{itemtype_notforloan} = $biblioitem->{'itemtype'};
897 if ( $item->{'withdrawn'} && $item->{'withdrawn'} > 0 )
899 $issuingimpossible{WTHDRAWN} = 1;
901 if ( $item->{'restricted'}
902 && $item->{'restricted'} == 1 )
904 $issuingimpossible{RESTRICTED} = 1;
906 if ( $item->{'itemlost'} && C4::Context->preference("IssueLostItem") ne 'nothing' ) {
907 my $code = GetAuthorisedValueByCode( 'LOST', $item->{'itemlost'} );
908 $needsconfirmation{ITEM_LOST} = $code if ( C4::Context->preference("IssueLostItem") eq 'confirm' );
909 $alerts{ITEM_LOST} = $code if ( C4::Context->preference("IssueLostItem") eq 'alert' );
911 if ( C4::Context->preference("IndependentBranches") ) {
912 my $userenv = C4::Context->userenv;
913 unless ( C4::Context->IsSuperLibrarian() ) {
914 if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} ){
915 $issuingimpossible{ITEMNOTSAMEBRANCH} = 1;
916 $issuingimpossible{'itemhomebranch'} = $item->{C4::Context->preference("HomeOrHoldingBranch")};
918 $needsconfirmation{BORRNOTSAMEBRANCH} = GetBranchName( $borrower->{'branchcode'} )
919 if ( $borrower->{'branchcode'} ne $userenv->{branch} );
923 # CHECK IF THERE IS RENTAL CHARGES. RENTAL MUST BE CONFIRMED BY THE BORROWER
925 my $rentalConfirmation = C4::Context->preference("RentalFeesCheckoutConfirmation");
927 if ( $rentalConfirmation ){
928 my ($rentalCharge) = GetIssuingCharges( $item->{'itemnumber'}, $borrower->{'borrowernumber'} );
929 if ( $rentalCharge ){
930 $rentalCharge = sprintf("%.02f", $rentalCharge);
931 $needsconfirmation{RENTALCHARGE} = $rentalCharge;
936 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
938 if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} ){
940 # Already issued to current borrower. Ask whether the loan should
942 my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed(
943 $borrower->{'borrowernumber'},
944 $item->{'itemnumber'}
946 if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed
947 $issuingimpossible{NO_MORE_RENEWALS} = 1;
950 $needsconfirmation{RENEW_ISSUE} = 1;
953 elsif ($issue->{borrowernumber}) {
955 # issued to someone else
956 my $currborinfo = C4::Members::GetMember( borrowernumber => $issue->{borrowernumber} );
958 # warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
959 $needsconfirmation{ISSUED_TO_ANOTHER} = 1;
960 $needsconfirmation{issued_firstname} = $currborinfo->{'firstname'};
961 $needsconfirmation{issued_surname} = $currborinfo->{'surname'};
962 $needsconfirmation{issued_cardnumber} = $currborinfo->{'cardnumber'};
963 $needsconfirmation{issued_borrowernumber} = $currborinfo->{'borrowernumber'};
966 unless ( $ignore_reserves ) {
967 # See if the item is on reserve.
968 my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
970 my $resbor = $res->{'borrowernumber'};
971 if ( $resbor ne $borrower->{'borrowernumber'} ) {
972 my ( $resborrower ) = C4::Members::GetMember( borrowernumber => $resbor );
973 my $branchname = GetBranchName( $res->{'branchcode'} );
974 if ( $restype eq "Waiting" )
976 # The item is on reserve and waiting, but has been
977 # reserved by some other patron.
978 $needsconfirmation{RESERVE_WAITING} = 1;
979 $needsconfirmation{'resfirstname'} = $resborrower->{'firstname'};
980 $needsconfirmation{'ressurname'} = $resborrower->{'surname'};
981 $needsconfirmation{'rescardnumber'} = $resborrower->{'cardnumber'};
982 $needsconfirmation{'resborrowernumber'} = $resborrower->{'borrowernumber'};
983 $needsconfirmation{'resbranchname'} = $branchname;
984 $needsconfirmation{'reswaitingdate'} = format_date($res->{'waitingdate'});
986 elsif ( $restype eq "Reserved" ) {
987 # The item is on reserve for someone else.
988 $needsconfirmation{RESERVED} = 1;
989 $needsconfirmation{'resfirstname'} = $resborrower->{'firstname'};
990 $needsconfirmation{'ressurname'} = $resborrower->{'surname'};
991 $needsconfirmation{'rescardnumber'} = $resborrower->{'cardnumber'};
992 $needsconfirmation{'resborrowernumber'} = $resborrower->{'borrowernumber'};
993 $needsconfirmation{'resbranchname'} = $branchname;
994 $needsconfirmation{'resreservedate'} = format_date($res->{'reservedate'});
1000 ## CHECK AGE RESTRICTION
1001 # get $marker from preferences. Could be something like "FSK|PEGI|Alter|Age:"
1002 my $markers = C4::Context->preference('AgeRestrictionMarker');
1003 my $bibvalues = $biblioitem->{'agerestriction'};
1004 my $restriction_age = GetAgeRestriction( $bibvalues );
1006 if ( $restriction_age > 0 ) {
1007 if ( $borrower->{'dateofbirth'} ) {
1008 my @alloweddate = split /-/, $borrower->{'dateofbirth'};
1009 $alloweddate[0] += $restriction_age;
1011 #Prevent runime eror on leap year (invalid date)
1012 if ( ( $alloweddate[1] == 2 ) && ( $alloweddate[2] == 29 ) ) {
1013 $alloweddate[2] = 28;
1016 if ( Date_to_Days(Today) < Date_to_Days(@alloweddate) - 1 ) {
1017 if ( C4::Context->preference('AgeRestrictionOverride') ) {
1018 $needsconfirmation{AGE_RESTRICTION} = "$bibvalues";
1021 $issuingimpossible{AGE_RESTRICTION} = "$bibvalues";
1027 ## check for high holds decreasing loan period
1028 my $decrease_loan = C4::Context->preference('decreaseLoanHighHolds');
1029 if ( $decrease_loan && $decrease_loan == 1 ) {
1030 my ( $reserved, $num, $duration, $returndate ) =
1031 checkHighHolds( $item, $borrower );
1033 if ( $num >= C4::Context->preference('decreaseLoanHighHoldsValue') ) {
1034 $needsconfirmation{HIGHHOLDS} = {
1036 duration => $duration,
1037 returndate => output_pref($returndate),
1043 !C4::Context->preference('AllowMultipleIssuesOnABiblio') &&
1044 # don't do the multiple loans per bib check if we've
1045 # already determined that we've got a loan on the same item
1046 !$issuingimpossible{NO_MORE_RENEWALS} &&
1047 !$needsconfirmation{RENEW_ISSUE}
1049 # Check if borrower has already issued an item from the same biblio
1050 # Only if it's not a subscription
1051 my $biblionumber = $item->{biblionumber};
1052 require C4::Serials;
1053 my $is_a_subscription = C4::Serials::CountSubscriptionFromBiblionumber($biblionumber);
1054 unless ($is_a_subscription) {
1055 my $issues = GetIssues( {
1056 borrowernumber => $borrower->{borrowernumber},
1057 biblionumber => $biblionumber,
1059 my @issues = $issues ? @$issues : ();
1060 # if we get here, we don't already have a loan on this item,
1061 # so if there are any loans on this bib, ask for confirmation
1062 if (scalar @issues > 0) {
1063 $needsconfirmation{BIBLIO_ALREADY_ISSUED} = 1;
1068 return ( \%issuingimpossible, \%needsconfirmation, \%alerts );
1071 =head2 CanBookBeReturned
1073 ($returnallowed, $message) = CanBookBeReturned($item, $branch)
1075 Check whether the item can be returned to the provided branch
1079 =item C<$item> is a hash of item information as returned from GetItem
1081 =item C<$branch> is the branchcode where the return is taking place
1089 =item C<$returnallowed> is 0 or 1, corresponding to whether the return is allowed (1) or not (0)
1091 =item C<$message> is the branchcode where the item SHOULD be returned, if the return is not allowed
1097 sub CanBookBeReturned {
1098 my ($item, $branch) = @_;
1099 my $allowreturntobranch = C4::Context->preference("AllowReturnToBranch") || 'anywhere';
1101 # assume return is allowed to start
1105 # identify all cases where return is forbidden
1106 if ($allowreturntobranch eq 'homebranch' && $branch ne $item->{'homebranch'}) {
1108 $message = $item->{'homebranch'};
1109 } elsif ($allowreturntobranch eq 'holdingbranch' && $branch ne $item->{'holdingbranch'}) {
1111 $message = $item->{'holdingbranch'};
1112 } elsif ($allowreturntobranch eq 'homeorholdingbranch' && $branch ne $item->{'homebranch'} && $branch ne $item->{'holdingbranch'}) {
1114 $message = $item->{'homebranch'}; # FIXME: choice of homebranch is arbitrary
1117 return ($allowed, $message);
1120 =head2 CheckHighHolds
1122 used when syspref decreaseLoanHighHolds is active. Returns 1 or 0 to define whether the minimum value held in
1123 decreaseLoanHighHoldsValue is exceeded, the total number of outstanding holds, the number of days the loan
1124 has been decreased to (held in syspref decreaseLoanHighHoldsValue), and the new due date
1128 sub checkHighHolds {
1129 my ( $item, $borrower ) = @_;
1130 my $biblio = GetBiblioFromItemNumber( $item->{itemnumber} );
1131 my $branch = _GetCircControlBranch( $item, $borrower );
1132 my $dbh = C4::Context->dbh;
1133 my $sth = $dbh->prepare(
1134 'select count(borrowernumber) as num_holds from reserves where biblionumber=?'
1136 $sth->execute( $item->{'biblionumber'} );
1137 my ($holds) = $sth->fetchrow_array;
1139 my $issuedate = DateTime->now( time_zone => C4::Context->tz() );
1141 my $calendar = Koha::Calendar->new( branchcode => $branch );
1144 ( C4::Context->preference('item-level_itypes') )
1145 ? $biblio->{'itype'}
1146 : $biblio->{'itemtype'};
1148 C4::Circulation::CalcDateDue( $issuedate, $itype, $branch,
1151 my $reduced_datedue =
1152 $calendar->addDate( $issuedate,
1153 C4::Context->preference('decreaseLoanHighHoldsDuration') );
1155 if ( DateTime->compare( $reduced_datedue, $orig_due ) == -1 ) {
1157 C4::Context->preference('decreaseLoanHighHoldsDuration'),
1161 return ( 0, 0, 0, undef );
1166 &AddIssue($borrower, $barcode, [$datedue], [$cancelreserve], [$issuedate])
1168 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
1172 =item C<$borrower> is a hash with borrower informations (from GetMember or GetMemberDetails).
1174 =item C<$barcode> is the barcode of the item being issued.
1176 =item C<$datedue> is a C4::Dates object for the max date of return, i.e. the date due (optional).
1177 Calculated if empty.
1179 =item C<$cancelreserve> is 1 to override and cancel any pending reserves for the item (optional).
1181 =item C<$issuedate> is the date to issue the item in iso (YYYY-MM-DD) format (optional).
1182 Defaults to today. Unlike C<$datedue>, NOT a C4::Dates object, unfortunately.
1184 AddIssue does the following things :
1186 - step 01: check that there is a borrowernumber & a barcode provided
1187 - check for RENEWAL (book issued & being issued to the same patron)
1188 - renewal YES = Calculate Charge & renew
1190 * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
1192 - fill reserve if reserve to this patron
1193 - cancel reserve or not, otherwise
1194 * TRANSFERT PENDING ?
1195 - complete the transfert
1203 my ( $borrower, $barcode, $datedue, $cancelreserve, $issuedate, $sipmode, $params ) = @_;
1204 my $onsite_checkout = $params && $params->{onsite_checkout} ? 1 : 0;
1205 my $auto_renew = $params && $params->{auto_renew};
1206 my $dbh = C4::Context->dbh;
1207 my $barcodecheck=CheckValidBarcode($barcode);
1209 if ($datedue && ref $datedue ne 'DateTime') {
1210 $datedue = dt_from_string($datedue);
1212 # $issuedate defaults to today.
1213 if ( ! defined $issuedate ) {
1214 $issuedate = DateTime->now(time_zone => C4::Context->tz());
1217 if ( ref $issuedate ne 'DateTime') {
1218 $issuedate = dt_from_string($issuedate);
1222 if ($borrower and $barcode and $barcodecheck ne '0'){#??? wtf
1223 # find which item we issue
1224 my $item = GetItem('', $barcode) or return; # if we don't get an Item, abort.
1225 my $branch = _GetCircControlBranch($item,$borrower);
1227 # get actual issuing if there is one
1228 my $actualissue = GetItemIssue( $item->{itemnumber});
1230 # get biblioinformation for this item
1231 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
1234 # check if we just renew the issue.
1236 if ($actualissue->{borrowernumber} eq $borrower->{'borrowernumber'}) {
1237 $datedue = AddRenewal(
1238 $borrower->{'borrowernumber'},
1239 $item->{'itemnumber'},
1242 $issuedate, # here interpreted as the renewal date
1246 # it's NOT a renewal
1247 if ( $actualissue->{borrowernumber}) {
1248 # This book is currently on loan, but not to the person
1249 # who wants to borrow it now. mark it returned before issuing to the new borrower
1252 C4::Context->userenv->{'branch'}
1256 MoveReserve( $item->{'itemnumber'}, $borrower->{'borrowernumber'}, $cancelreserve );
1257 # Starting process for transfer job (checking transfert and validate it if we have one)
1258 my ($datesent) = GetTransfers($item->{'itemnumber'});
1260 # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for visibility of this case (maybe for stats ....)
1263 "UPDATE branchtransfers
1264 SET datearrived = now(),
1266 comments = 'Forced branchtransfer'
1267 WHERE itemnumber= ? AND datearrived IS NULL"
1269 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
1272 # If automatic renewal wasn't selected while issuing, set the value according to the issuing rule.
1273 unless ($auto_renew) {
1274 my $issuingrule = GetIssuingRule($borrower->{categorycode}, $item->{itype}, $branch);
1275 $auto_renew = $issuingrule->{auto_renew};
1278 # Record in the database the fact that the book was issued.
1282 (borrowernumber, itemnumber,issuedate, date_due, branchcode, onsite_checkout, auto_renew)
1283 VALUES (?,?,?,?,?,?,?)"
1286 my $itype = ( C4::Context->preference('item-level_itypes') ) ? $biblio->{'itype'} : $biblio->{'itemtype'};
1287 $datedue = CalcDateDue( $issuedate, $itype, $branch, $borrower );
1290 $datedue->truncate( to => 'minute');
1293 $borrower->{'borrowernumber'}, # borrowernumber
1294 $item->{'itemnumber'}, # itemnumber
1295 $issuedate->strftime('%Y-%m-%d %H:%M:00'), # issuedate
1296 $datedue->strftime('%Y-%m-%d %H:%M:00'), # date_due
1297 C4::Context->userenv->{'branch'}, # branchcode
1299 $auto_renew ? 1 : 0 # automatic renewal
1301 if ( C4::Context->preference('ReturnToShelvingCart') ) { ## ReturnToShelvingCart is on, anything issued should be taken off the cart.
1302 CartToShelf( $item->{'itemnumber'} );
1304 $item->{'issues'}++;
1305 if ( C4::Context->preference('UpdateTotalIssuesOnCirc') ) {
1306 UpdateTotalIssues($item->{'biblionumber'}, 1);
1309 ## If item was lost, it has now been found, reverse any list item charges if neccessary.
1310 if ( $item->{'itemlost'} ) {
1311 if ( C4::Context->preference('RefundLostItemFeeOnReturn' ) ) {
1312 _FixAccountForLostAndReturned( $item->{'itemnumber'}, undef, $item->{'barcode'} );
1316 ModItem({ issues => $item->{'issues'},
1317 holdingbranch => C4::Context->userenv->{'branch'},
1319 datelastborrowed => DateTime->now(time_zone => C4::Context->tz())->ymd(),
1320 onloan => $datedue->ymd(),
1321 }, $item->{'biblionumber'}, $item->{'itemnumber'});
1322 ModDateLastSeen( $item->{'itemnumber'} );
1324 # If it costs to borrow this book, charge it to the patron's account.
1325 my ( $charge, $itemtype ) = GetIssuingCharges(
1326 $item->{'itemnumber'},
1327 $borrower->{'borrowernumber'}
1329 if ( $charge > 0 ) {
1331 $item->{'itemnumber'},
1332 $borrower->{'borrowernumber'}, $charge
1334 $item->{'charge'} = $charge;
1337 # Record the fact that this book was issued.
1339 branch => C4::Context->userenv->{'branch'},
1340 type => ( $onsite_checkout ? 'onsite_checkout' : 'issue' ),
1342 other => ($sipmode ? "SIP-$sipmode" : ''),
1343 itemnumber => $item->{'itemnumber'},
1344 itemtype => $item->{'itype'},
1345 borrowernumber => $borrower->{'borrowernumber'},
1346 ccode => $item->{'ccode'}}
1349 # Send a checkout slip.
1350 my $circulation_alert = 'C4::ItemCirculationAlertPreference';
1352 branchcode => $branch,
1353 categorycode => $borrower->{categorycode},
1354 item_type => $item->{itype},
1355 notification => 'CHECKOUT',
1357 if ($circulation_alert->is_enabled_for(\%conditions)) {
1358 SendCirculationAlert({
1361 borrower => $borrower,
1367 logaction("CIRCULATION", "ISSUE", $borrower->{'borrowernumber'}, $biblio->{'itemnumber'})
1368 if C4::Context->preference("IssueLog");
1370 return ($datedue); # not necessarily the same as when it came in!
1373 =head2 GetLoanLength
1375 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1377 Get loan length for an itemtype, a borrower type and a branch
1382 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1383 my $dbh = C4::Context->dbh;
1384 my $sth = $dbh->prepare(qq{
1385 SELECT issuelength, lengthunit, renewalperiod
1387 WHERE categorycode=?
1390 AND issuelength IS NOT NULL
1393 # try to find issuelength & return the 1st available.
1394 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1395 $sth->execute( $borrowertype, $itemtype, $branchcode );
1396 my $loanlength = $sth->fetchrow_hashref;
1399 if defined($loanlength) && $loanlength->{issuelength};
1401 $sth->execute( $borrowertype, '*', $branchcode );
1402 $loanlength = $sth->fetchrow_hashref;
1404 if defined($loanlength) && $loanlength->{issuelength};
1406 $sth->execute( '*', $itemtype, $branchcode );
1407 $loanlength = $sth->fetchrow_hashref;
1409 if defined($loanlength) && $loanlength->{issuelength};
1411 $sth->execute( '*', '*', $branchcode );
1412 $loanlength = $sth->fetchrow_hashref;
1414 if defined($loanlength) && $loanlength->{issuelength};
1416 $sth->execute( $borrowertype, $itemtype, '*' );
1417 $loanlength = $sth->fetchrow_hashref;
1419 if defined($loanlength) && $loanlength->{issuelength};
1421 $sth->execute( $borrowertype, '*', '*' );
1422 $loanlength = $sth->fetchrow_hashref;
1424 if defined($loanlength) && $loanlength->{issuelength};
1426 $sth->execute( '*', $itemtype, '*' );
1427 $loanlength = $sth->fetchrow_hashref;
1429 if defined($loanlength) && $loanlength->{issuelength};
1431 $sth->execute( '*', '*', '*' );
1432 $loanlength = $sth->fetchrow_hashref;
1434 if defined($loanlength) && $loanlength->{issuelength};
1436 # if no rule is set => 21 days (hardcoded)
1439 renewalperiod => 21,
1440 lengthunit => 'days',
1446 =head2 GetHardDueDate
1448 my ($hardduedate,$hardduedatecompare) = &GetHardDueDate($borrowertype,$itemtype,branchcode)
1450 Get the Hard Due Date and it's comparison for an itemtype, a borrower type and a branch
1454 sub GetHardDueDate {
1455 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1457 my $rule = GetIssuingRule( $borrowertype, $itemtype, $branchcode );
1459 if ( defined( $rule ) ) {
1460 if ( $rule->{hardduedate} ) {
1461 return (dt_from_string($rule->{hardduedate}, 'iso'),$rule->{hardduedatecompare});
1463 return (undef, undef);
1468 =head2 GetIssuingRule
1470 my $irule = &GetIssuingRule($borrowertype,$itemtype,branchcode)
1472 FIXME - This is a copy-paste of GetLoanLength
1473 as a stop-gap. Do not wish to change API for GetLoanLength
1474 this close to release.
1476 Get the issuing rule for an itemtype, a borrower type and a branch
1477 Returns a hashref from the issuingrules table.
1481 sub GetIssuingRule {
1482 my ( $borrowertype, $itemtype, $branchcode ) = @_;
1483 my $dbh = C4::Context->dbh;
1484 my $sth = $dbh->prepare( "select * from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null" );
1487 $sth->execute( $borrowertype, $itemtype, $branchcode );
1488 $irule = $sth->fetchrow_hashref;
1489 return $irule if defined($irule) ;
1491 $sth->execute( $borrowertype, "*", $branchcode );
1492 $irule = $sth->fetchrow_hashref;
1493 return $irule if defined($irule) ;
1495 $sth->execute( "*", $itemtype, $branchcode );
1496 $irule = $sth->fetchrow_hashref;
1497 return $irule if defined($irule) ;
1499 $sth->execute( "*", "*", $branchcode );
1500 $irule = $sth->fetchrow_hashref;
1501 return $irule if defined($irule) ;
1503 $sth->execute( $borrowertype, $itemtype, "*" );
1504 $irule = $sth->fetchrow_hashref;
1505 return $irule if defined($irule) ;
1507 $sth->execute( $borrowertype, "*", "*" );
1508 $irule = $sth->fetchrow_hashref;
1509 return $irule if defined($irule) ;
1511 $sth->execute( "*", $itemtype, "*" );
1512 $irule = $sth->fetchrow_hashref;
1513 return $irule if defined($irule) ;
1515 $sth->execute( "*", "*", "*" );
1516 $irule = $sth->fetchrow_hashref;
1517 return $irule if defined($irule) ;
1519 # if no rule matches,
1523 =head2 GetBranchBorrowerCircRule
1525 my $branch_cat_rule = GetBranchBorrowerCircRule($branchcode, $categorycode);
1527 Retrieves circulation rule attributes that apply to the given
1528 branch and patron category, regardless of item type.
1529 The return value is a hashref containing the following key:
1531 maxissueqty - maximum number of loans that a
1532 patron of the given category can have at the given
1533 branch. If the value is undef, no limit.
1535 This will first check for a specific branch and
1536 category match from branch_borrower_circ_rules.
1538 If no rule is found, it will then check default_branch_circ_rules
1539 (same branch, default category). If no rule is found,
1540 it will then check default_borrower_circ_rules (default
1541 branch, same category), then failing that, default_circ_rules
1542 (default branch, default category).
1544 If no rule has been found in the database, it will default to
1549 C<$branchcode> and C<$categorycode> should contain the
1550 literal branch code and patron category code, respectively - no
1555 sub GetBranchBorrowerCircRule {
1556 my $branchcode = shift;
1557 my $categorycode = shift;
1559 my $branch_cat_query = "SELECT maxissueqty
1560 FROM branch_borrower_circ_rules
1561 WHERE branchcode = ?
1562 AND categorycode = ?";
1563 my $dbh = C4::Context->dbh();
1564 my $sth = $dbh->prepare($branch_cat_query);
1565 $sth->execute($branchcode, $categorycode);
1567 if ($result = $sth->fetchrow_hashref()) {
1571 # try same branch, default borrower category
1572 my $branch_query = "SELECT maxissueqty
1573 FROM default_branch_circ_rules
1574 WHERE branchcode = ?";
1575 $sth = $dbh->prepare($branch_query);
1576 $sth->execute($branchcode);
1577 if ($result = $sth->fetchrow_hashref()) {
1581 # try default branch, same borrower category
1582 my $category_query = "SELECT maxissueqty
1583 FROM default_borrower_circ_rules
1584 WHERE categorycode = ?";
1585 $sth = $dbh->prepare($category_query);
1586 $sth->execute($categorycode);
1587 if ($result = $sth->fetchrow_hashref()) {
1591 # try default branch, default borrower category
1592 my $default_query = "SELECT maxissueqty
1593 FROM default_circ_rules";
1594 $sth = $dbh->prepare($default_query);
1596 if ($result = $sth->fetchrow_hashref()) {
1600 # built-in default circulation rule
1602 maxissueqty => undef,
1606 =head2 GetBranchItemRule
1608 my $branch_item_rule = GetBranchItemRule($branchcode, $itemtype);
1610 Retrieves circulation rule attributes that apply to the given
1611 branch and item type, regardless of patron category.
1613 The return value is a hashref containing the following keys:
1615 holdallowed => Hold policy for this branch and itemtype. Possible values:
1616 0: No holds allowed.
1617 1: Holds allowed only by patrons that have the same homebranch as the item.
1618 2: Holds allowed from any patron.
1620 returnbranch => branch to which to return item. Possible values:
1621 noreturn: do not return, let item remain where checked in (floating collections)
1622 homebranch: return to item's home branch
1624 This searches branchitemrules in the following order:
1626 * Same branchcode and itemtype
1627 * Same branchcode, itemtype '*'
1628 * branchcode '*', same itemtype
1629 * branchcode and itemtype '*'
1631 Neither C<$branchcode> nor C<$itemtype> should be '*'.
1635 sub GetBranchItemRule {
1636 my ( $branchcode, $itemtype ) = @_;
1637 my $dbh = C4::Context->dbh();
1641 ['SELECT holdallowed, returnbranch
1642 FROM branch_item_rules
1643 WHERE branchcode = ?
1644 AND itemtype = ?', $branchcode, $itemtype],
1645 ['SELECT holdallowed, returnbranch
1646 FROM default_branch_circ_rules
1647 WHERE branchcode = ?', $branchcode],
1648 ['SELECT holdallowed, returnbranch
1649 FROM default_branch_item_rules
1650 WHERE itemtype = ?', $itemtype],
1651 ['SELECT holdallowed, returnbranch
1652 FROM default_circ_rules'],
1655 foreach my $attempt (@attempts) {
1656 my ($query, @bind_params) = @{$attempt};
1657 my $search_result = $dbh->selectrow_hashref ( $query , {}, @bind_params )
1660 # Since branch/category and branch/itemtype use the same per-branch
1661 # defaults tables, we have to check that the key we want is set, not
1662 # just that a row was returned
1663 $result->{'holdallowed'} = $search_result->{'holdallowed'} unless ( defined $result->{'holdallowed'} );
1664 $result->{'returnbranch'} = $search_result->{'returnbranch'} unless ( defined $result->{'returnbranch'} );
1667 # built-in default circulation rule
1668 $result->{'holdallowed'} = 2 unless ( defined $result->{'holdallowed'} );
1669 $result->{'returnbranch'} = 'homebranch' unless ( defined $result->{'returnbranch'} );
1676 ($doreturn, $messages, $iteminformation, $borrower) =
1677 &AddReturn( $barcode, $branch [,$exemptfine] [,$dropbox] [,$returndate] );
1683 =item C<$barcode> is the bar code of the book being returned.
1685 =item C<$branch> is the code of the branch where the book is being returned.
1687 =item C<$exemptfine> indicates that overdue charges for the item will be
1690 =item C<$dropbox> indicates that the check-in date is assumed to be
1691 yesterday, or the last non-holiday as defined in C4::Calendar . If
1692 overdue charges are applied and C<$dropbox> is true, the last charge
1693 will be removed. This assumes that the fines accrual script has run
1694 for _today_. Optional.
1696 =item C<$return_date> allows the default return date to be overridden
1697 by the given return date. Optional.
1701 C<&AddReturn> returns a list of four items:
1703 C<$doreturn> is true iff the return succeeded.
1705 C<$messages> is a reference-to-hash giving feedback on the operation.
1706 The keys of the hash are:
1712 No item with this barcode exists. The value is C<$barcode>.
1716 The book is not currently on loan. The value is C<$barcode>.
1718 =item C<IsPermanent>
1720 The book's home branch is a permanent collection. If you have borrowed
1721 this book, you are not allowed to return it. The value is the code for
1722 the book's home branch.
1726 This book has been withdrawn/cancelled. The value should be ignored.
1728 =item C<Wrongbranch>
1730 This book has was returned to the wrong branch. The value is a hashref
1731 so that C<$messages->{Wrongbranch}->{Wrongbranch}> and C<$messages->{Wrongbranch}->{Rightbranch}>
1732 contain the branchcode of the incorrect and correct return library, respectively.
1736 The item was reserved. The value is a reference-to-hash whose keys are
1737 fields from the reserves table of the Koha database, and
1738 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1739 either C<Waiting>, C<Reserved>, or 0.
1743 C<$iteminformation> is a reference-to-hash, giving information about the
1744 returned item from the issues table.
1746 C<$borrower> is a reference-to-hash, giving information about the
1747 patron who last borrowed the book.
1752 my ( $barcode, $branch, $exemptfine, $dropbox, $return_date ) = @_;
1754 if ($branch and not GetBranchDetail($branch)) {
1755 warn "AddReturn error: branch '$branch' not found. Reverting to " . C4::Context->userenv->{'branch'};
1758 $branch = C4::Context->userenv->{'branch'} unless $branch; # we trust userenv to be a safe fallback/default
1763 my $validTransfert = 0;
1764 my $stat_type = 'return';
1766 # get information on item
1767 my $itemnumber = GetItemnumberFromBarcode( $barcode );
1768 unless ($itemnumber) {
1769 return (0, { BadBarcode => $barcode }); # no barcode means no item or borrower. bail out.
1771 my $issue = GetItemIssue($itemnumber);
1772 # warn Dumper($iteminformation);
1773 if ($issue and $issue->{borrowernumber}) {
1774 $borrower = C4::Members::GetMemberDetails($issue->{borrowernumber})
1775 or die "Data inconsistency: barcode $barcode (itemnumber:$itemnumber) claims to be issued to non-existant borrowernumber '$issue->{borrowernumber}'\n"
1776 . Dumper($issue) . "\n";
1778 $messages->{'NotIssued'} = $barcode;
1779 # even though item is not on loan, it may still be transferred; therefore, get current branch info
1781 # No issue, no borrowernumber. ONLY if $doreturn, *might* you have a $borrower later.
1782 # Record this as a local use, instead of a return, if the RecordLocalUseOnReturn is on
1783 if (C4::Context->preference("RecordLocalUseOnReturn")) {
1784 $messages->{'LocalUse'} = 1;
1785 $stat_type = 'localuse';
1789 my $item = GetItem($itemnumber) or die "GetItem($itemnumber) failed";
1790 # full item data, but no borrowernumber or checkout info (no issue)
1791 # we know GetItem should work because GetItemnumberFromBarcode worked
1792 my $hbr = GetBranchItemRule($item->{'homebranch'}, $item->{'itype'})->{'returnbranch'} || "homebranch";
1793 # get the proper branch to which to return the item
1794 $hbr = $item->{$hbr} || $branch ;
1795 # if $hbr was "noreturn" or any other non-item table value, then it should 'float' (i.e. stay at this branch)
1797 my $borrowernumber = $borrower->{'borrowernumber'} || undef; # we don't know if we had a borrower or not
1799 my $yaml = C4::Context->preference('UpdateNotForLoanStatusOnCheckin');
1801 $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1803 eval { $rules = YAML::Load($yaml); };
1805 warn "Unable to parse UpdateNotForLoanStatusOnCheckin syspref : $@";
1808 foreach my $key ( keys %$rules ) {
1809 if ( $item->{notforloan} eq $key ) {
1810 $messages->{'NotForLoanStatusUpdated'} = { from => $item->{notforloan}, to => $rules->{$key} };
1811 ModItem( { notforloan => $rules->{$key} }, undef, $itemnumber );
1819 # check if the book is in a permanent collection....
1820 # FIXME -- This 'PE' attribute is largely undocumented. afaict, there's no user interface that reflects this functionality.
1822 my $branches = GetBranches(); # a potentially expensive call for a non-feature.
1823 $branches->{$hbr}->{PE} and $messages->{'IsPermanent'} = $hbr;
1826 # check if the return is allowed at this branch
1827 my ($returnallowed, $message) = CanBookBeReturned($item, $branch);
1828 unless ($returnallowed){
1829 $messages->{'Wrongbranch'} = {
1830 Wrongbranch => $branch,
1831 Rightbranch => $message
1834 return ( $doreturn, $messages, $issue, $borrower );
1837 if ( $item->{'withdrawn'} ) { # book has been cancelled
1838 $messages->{'withdrawn'} = 1;
1839 $doreturn = 0 if C4::Context->preference("BlockReturnOfWithdrawnItems");
1842 # case of a return of document (deal with issues and holdingbranch)
1843 my $today = DateTime->now( time_zone => C4::Context->tz() );
1846 my $datedue = $issue->{date_due};
1847 $borrower or warn "AddReturn without current borrower";
1848 my $circControlBranch;
1850 # define circControlBranch only if dropbox mode is set
1851 # don't allow dropbox mode to create an invalid entry in issues (issuedate > today)
1852 # FIXME: check issuedate > returndate, factoring in holidays
1853 #$circControlBranch = _GetCircControlBranch($item,$borrower) unless ( $item->{'issuedate'} eq C4::Dates->today('iso') );;
1854 $circControlBranch = _GetCircControlBranch($item,$borrower);
1855 $issue->{'overdue'} = DateTime->compare($issue->{'date_due'}, $today ) == -1 ? 1 : 0;
1858 if ($borrowernumber) {
1859 if ( ( C4::Context->preference('CalculateFinesOnReturn') && $issue->{'overdue'} ) || $return_date ) {
1860 # we only need to calculate and change the fines if we want to do that on return
1861 # Should be on for hourly loans
1862 my $control = C4::Context->preference('CircControl');
1863 my $control_branchcode =
1864 ( $control eq 'ItemHomeLibrary' ) ? $item->{homebranch}
1865 : ( $control eq 'PatronLibrary' ) ? $borrower->{branchcode}
1866 : $issue->{branchcode};
1869 $return_date ? dt_from_string($return_date) : $today;
1871 my ( $amount, $type, $unitcounttotal ) =
1872 C4::Overdues::CalcFine( $item, $borrower->{categorycode},
1873 $control_branchcode, $datedue, $date_returned );
1877 if ( C4::Context->preference('finesMode') eq 'production' ) {
1878 if ( $amount > 0 ) {
1879 C4::Overdues::UpdateFine( $issue->{itemnumber},
1880 $issue->{borrowernumber},
1881 $amount, $type, output_pref($datedue) );
1883 elsif ($return_date) {
1885 # Backdated returns may have fines that shouldn't exist,
1886 # so in this case, we need to drop those fines to 0
1888 C4::Overdues::UpdateFine( $issue->{itemnumber},
1889 $issue->{borrowernumber},
1890 0, $type, output_pref($datedue) );
1895 MarkIssueReturned( $borrowernumber, $item->{'itemnumber'},
1896 $circControlBranch, $return_date, $borrower->{'privacy'} );
1898 # FIXME is the "= 1" right? This could be the borrower hash.
1899 $messages->{'WasReturned'} = 1;
1903 ModItem({ onloan => undef }, $issue->{'biblionumber'}, $item->{'itemnumber'});
1906 # the holdingbranch is updated if the document is returned to another location.
1907 # this is always done regardless of whether the item was on loan or not
1908 if ($item->{'holdingbranch'} ne $branch) {
1909 UpdateHoldingbranch($branch, $item->{'itemnumber'});
1910 $item->{'holdingbranch'} = $branch; # update item data holdingbranch too
1912 ModDateLastSeen( $item->{'itemnumber'} );
1914 # check if we have a transfer for this document
1915 my ($datesent,$frombranch,$tobranch) = GetTransfers( $item->{'itemnumber'} );
1917 # if we have a transfer to do, we update the line of transfers with the datearrived
1918 my $is_in_rotating_collection = C4::RotatingCollections::isItemInAnyCollection( $item->{'itemnumber'} );
1920 if ( $tobranch eq $branch ) {
1921 my $sth = C4::Context->dbh->prepare(
1922 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1924 $sth->execute( $item->{'itemnumber'} );
1925 # if we have a reservation with valid transfer, we can set it's status to 'W'
1926 ShelfToCart( $item->{'itemnumber'} ) if ( C4::Context->preference("ReturnToShelvingCart") );
1927 C4::Reserves::ModReserveStatus($item->{'itemnumber'}, 'W');
1929 $messages->{'WrongTransfer'} = $tobranch;
1930 $messages->{'WrongTransferItem'} = $item->{'itemnumber'};
1932 $validTransfert = 1;
1934 ShelfToCart( $item->{'itemnumber'} ) if ( C4::Context->preference("ReturnToShelvingCart") );
1937 # fix up the accounts.....
1938 if ( $item->{'itemlost'} ) {
1939 $messages->{'WasLost'} = 1;
1941 if ( C4::Context->preference('RefundLostItemFeeOnReturn' ) ) {
1942 _FixAccountForLostAndReturned($item->{'itemnumber'}, $borrowernumber, $barcode); # can tolerate undef $borrowernumber
1943 $messages->{'LostItemFeeRefunded'} = 1;
1947 # fix up the overdues in accounts...
1948 if ($borrowernumber) {
1949 my $fix = _FixOverduesOnReturn($borrowernumber, $item->{itemnumber}, $exemptfine, $dropbox);
1950 defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $item->{itemnumber}...) failed!"; # zero is OK, check defined
1952 if ( $issue->{overdue} && $issue->{date_due} ) {
1954 my ($debardate,$reminder) = _debar_user_on_return( $borrower, $item, $issue->{date_due}, $today );
1956 $messages->{'PrevDebarred'} = $debardate;
1958 $messages->{'Debarred'} = $debardate if $debardate;
1960 # there's no overdue on the item but borrower had been previously debarred
1961 } elsif ( $issue->{date_due} and $borrower->{'debarred'} ) {
1962 my $borrower_debar_dt = dt_from_string( $borrower->{debarred} );
1963 $borrower_debar_dt->truncate(to => 'day');
1964 my $today_dt = $today->clone()->truncate(to => 'day');
1965 if ( DateTime->compare( $borrower_debar_dt, $today_dt ) != -1 ) {
1966 $messages->{'PrevDebarred'} = $borrower->{'debarred'};
1971 # find reserves.....
1972 # if we don't have a reserve with the status W, we launch the Checkreserves routine
1973 my ($resfound, $resrec);
1974 my $lookahead= C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1975 ($resfound, $resrec, undef) = C4::Reserves::CheckReserves( $item->{'itemnumber'}, undef, $lookahead ) unless ( $item->{'withdrawn'} );
1977 $resrec->{'ResFound'} = $resfound;
1978 $messages->{'ResFound'} = $resrec;
1981 # Record the fact that this book was returned.
1982 # FIXME itemtype should record item level type, not bibliolevel type
1986 itemnumber => $item->{'itemnumber'},
1987 itemtype => $biblio->{'itemtype'},
1988 borrowernumber => $borrowernumber,
1989 ccode => $item->{'ccode'}}
1992 # Send a check-in slip. # NOTE: borrower may be undef. probably shouldn't try to send messages then.
1993 my $circulation_alert = 'C4::ItemCirculationAlertPreference';
1995 branchcode => $branch,
1996 categorycode => $borrower->{categorycode},
1997 item_type => $item->{itype},
1998 notification => 'CHECKIN',
2000 if ($doreturn && $circulation_alert->is_enabled_for(\%conditions)) {
2001 SendCirculationAlert({
2004 borrower => $borrower,
2009 logaction("CIRCULATION", "RETURN", $borrowernumber, $item->{'itemnumber'})
2010 if C4::Context->preference("ReturnLog");
2012 # Remove any OVERDUES related debarment if the borrower has no overdues
2013 if ( $borrowernumber
2014 && $borrower->{'debarred'}
2015 && C4::Context->preference('AutoRemoveOverduesRestrictions')
2016 && !HasOverdues( $borrowernumber )
2017 && @{ GetDebarments({ borrowernumber => $borrowernumber, type => 'OVERDUES' }) }
2019 DelUniqueDebarment({ borrowernumber => $borrowernumber, type => 'OVERDUES' });
2022 # FIXME: make this comment intelligible.
2023 #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
2024 #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
2026 if ( !$is_in_rotating_collection && ($doreturn or $messages->{'NotIssued'}) and !$resfound and ($branch ne $hbr) and not $messages->{'WrongTransfer'}){
2027 if ( C4::Context->preference("AutomaticItemReturn" ) or
2028 (C4::Context->preference("UseBranchTransferLimits") and
2029 ! IsBranchTransferAllowed($branch, $hbr, $item->{C4::Context->preference("BranchTransferLimitsType")} )
2031 $debug and warn sprintf "about to call ModItemTransfer(%s, %s, %s)", $item->{'itemnumber'},$branch, $hbr;
2032 $debug and warn "item: " . Dumper($item);
2033 ModItemTransfer($item->{'itemnumber'}, $branch, $hbr);
2034 $messages->{'WasTransfered'} = 1;
2036 $messages->{'NeedsTransfer'} = 1; # TODO: instead of 1, specify branchcode that the transfer SHOULD go to, $item->{homebranch}
2040 return ( $doreturn, $messages, $issue, $borrower );
2043 =head2 MarkIssueReturned
2045 MarkIssueReturned($borrowernumber, $itemnumber, $dropbox_branch, $returndate, $privacy);
2047 Unconditionally marks an issue as being returned by
2048 moving the C<issues> row to C<old_issues> and
2049 setting C<returndate> to the current date, or
2050 the last non-holiday date of the branccode specified in
2051 C<dropbox_branch> . Assumes you've already checked that
2052 it's safe to do this, i.e. last non-holiday > issuedate.
2054 if C<$returndate> is specified (in iso format), it is used as the date
2055 of the return. It is ignored when a dropbox_branch is passed in.
2057 C<$privacy> contains the privacy parameter. If the patron has set privacy to 2,
2058 the old_issue is immediately anonymised
2060 Ideally, this function would be internal to C<C4::Circulation>,
2061 not exported, but it is currently needed by one
2062 routine in C<C4::Accounts>.
2066 sub MarkIssueReturned {
2067 my ( $borrowernumber, $itemnumber, $dropbox_branch, $returndate, $privacy ) = @_;
2069 my $dbh = C4::Context->dbh;
2070 my $query = 'UPDATE issues SET returndate=';
2072 if ($dropbox_branch) {
2073 my $calendar = Koha::Calendar->new( branchcode => $dropbox_branch );
2074 my $dropboxdate = $calendar->addDate( DateTime->now( time_zone => C4::Context->tz), -1 );
2076 push @bind, $dropboxdate->strftime('%Y-%m-%d %H:%M');
2077 } elsif ($returndate) {
2079 push @bind, $returndate;
2081 $query .= ' now() ';
2083 $query .= ' WHERE borrowernumber = ? AND itemnumber = ?';
2084 push @bind, $borrowernumber, $itemnumber;
2086 my $sth_upd = $dbh->prepare($query);
2087 $sth_upd->execute(@bind);
2088 my $sth_copy = $dbh->prepare('INSERT INTO old_issues SELECT * FROM issues
2089 WHERE borrowernumber = ?
2090 AND itemnumber = ?');
2091 $sth_copy->execute($borrowernumber, $itemnumber);
2092 # anonymise patron checkout immediately if $privacy set to 2 and AnonymousPatron is set to a valid borrowernumber
2093 if ( $privacy == 2) {
2094 # The default of 0 does not work due to foreign key constraints
2095 # The anonymisation will fail quietly if AnonymousPatron is not a valid entry
2096 # FIXME the above is unacceptable - bug 9942 relates
2097 my $anonymouspatron = (C4::Context->preference('AnonymousPatron')) ? C4::Context->preference('AnonymousPatron') : 0;
2098 my $sth_ano = $dbh->prepare("UPDATE old_issues SET borrowernumber=?
2099 WHERE borrowernumber = ?
2100 AND itemnumber = ?");
2101 $sth_ano->execute($anonymouspatron, $borrowernumber, $itemnumber);
2103 my $sth_del = $dbh->prepare("DELETE FROM issues
2104 WHERE borrowernumber = ?
2105 AND itemnumber = ?");
2106 $sth_del->execute($borrowernumber, $itemnumber);
2108 ModItem( { 'onloan' => undef }, undef, $itemnumber );
2111 =head2 _debar_user_on_return
2113 _debar_user_on_return($borrower, $item, $datedue, today);
2115 C<$borrower> borrower hashref
2117 C<$item> item hashref
2119 C<$datedue> date due DateTime object
2121 C<$today> DateTime object representing the return time
2123 Internal function, called only by AddReturn that calculates and updates
2124 the user fine days, and debars him if necessary.
2126 Should only be called for overdue returns
2130 sub _debar_user_on_return {
2131 my ( $borrower, $item, $dt_due, $dt_today ) = @_;
2133 my $branchcode = _GetCircControlBranch( $item, $borrower );
2134 my $calendar = Koha::Calendar->new( branchcode => $branchcode );
2136 # $deltadays is a DateTime::Duration object
2137 my $deltadays = $calendar->days_between( $dt_due, $dt_today );
2139 my $circcontrol = C4::Context->preference('CircControl');
2141 GetIssuingRule( $borrower->{categorycode}, $item->{itype}, $branchcode );
2142 my $finedays = $issuingrule->{finedays};
2143 my $unit = $issuingrule->{lengthunit};
2147 # finedays is in days, so hourly loans must multiply by 24
2148 # thus 1 hour late equals 1 day suspension * finedays rate
2149 $finedays = $finedays * 24 if ( $unit eq 'hours' );
2151 # grace period is measured in the same units as the loan
2153 DateTime::Duration->new( $unit => $issuingrule->{firstremind} );
2155 if ( $deltadays->subtract($grace)->is_positive() ) {
2156 my $suspension_days = $deltadays * $finedays;
2158 # If the max suspension days is < than the suspension days
2159 # the suspension days is limited to this maximum period.
2160 my $max_sd = $issuingrule->{maxsuspensiondays};
2161 if ( defined $max_sd ) {
2162 $max_sd = DateTime::Duration->new( days => $max_sd );
2163 $suspension_days = $max_sd
2164 if DateTime::Duration->compare( $max_sd, $suspension_days ) < 0;
2168 $dt_today->clone()->add_duration( $suspension_days );
2170 Koha::Borrower::Debarments::AddUniqueDebarment({
2171 borrowernumber => $borrower->{borrowernumber},
2172 expiration => $new_debar_dt->ymd(),
2173 type => 'SUSPENSION',
2175 # if borrower was already debarred but does not get an extra debarment
2176 if ( $borrower->{debarred} eq Koha::Borrower::Debarments::IsDebarred($borrower->{borrowernumber}) ) {
2177 return ($borrower->{debarred},1);
2179 return $new_debar_dt->ymd();
2185 =head2 _FixOverduesOnReturn
2187 &_FixOverduesOnReturn($brn,$itm, $exemptfine, $dropboxmode);
2189 C<$brn> borrowernumber
2193 C<$exemptfine> BOOL -- remove overdue charge associated with this issue.
2194 C<$dropboxmode> BOOL -- remove lastincrement on overdue charge associated with this issue.
2196 Internal function, called only by AddReturn
2200 sub _FixOverduesOnReturn {
2201 my ($borrowernumber, $item);
2202 unless ($borrowernumber = shift) {
2203 warn "_FixOverduesOnReturn() not supplied valid borrowernumber";
2206 unless ($item = shift) {
2207 warn "_FixOverduesOnReturn() not supplied valid itemnumber";
2210 my ($exemptfine, $dropbox) = @_;
2211 my $dbh = C4::Context->dbh;
2213 # check for overdue fine
2214 my $sth = $dbh->prepare(
2215 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
2217 $sth->execute( $borrowernumber, $item );
2219 # alter fine to show that the book has been returned
2220 my $data = $sth->fetchrow_hashref;
2221 return 0 unless $data; # no warning, there's just nothing to fix
2224 my @bind = ($data->{'accountlines_id'});
2226 $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
2227 if (C4::Context->preference("FinesLog")) {
2228 &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
2230 } elsif ($dropbox && $data->{lastincrement}) {
2231 my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
2232 my $amt = $data->{amount} - $data->{lastincrement} ;
2233 if (C4::Context->preference("FinesLog")) {
2234 &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
2236 $uquery = "update accountlines set accounttype='F' ";
2237 if($outstanding >= 0 && $amt >=0) {
2238 $uquery .= ", amount = ? , amountoutstanding=? ";
2239 unshift @bind, ($amt, $outstanding) ;
2242 $uquery = "update accountlines set accounttype='F' ";
2244 $uquery .= " where (accountlines_id = ?)";
2245 my $usth = $dbh->prepare($uquery);
2246 return $usth->execute(@bind);
2249 =head2 _FixAccountForLostAndReturned
2251 &_FixAccountForLostAndReturned($itemnumber, [$borrowernumber, $barcode]);
2253 Calculates the charge for a book lost and returned.
2255 Internal function, not exported, called only by AddReturn.
2257 FIXME: This function reflects how inscrutable fines logic is. Fix both.
2258 FIXME: Give a positive return value on success. It might be the $borrowernumber who received credit, or the amount forgiven.
2262 sub _FixAccountForLostAndReturned {
2263 my $itemnumber = shift or return;
2264 my $borrowernumber = @_ ? shift : undef;
2265 my $item_id = @_ ? shift : $itemnumber; # Send the barcode if you want that logged in the description
2266 my $dbh = C4::Context->dbh;
2267 # check for charge made for lost book
2268 my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE itemnumber = ? AND accounttype IN ('L', 'Rep', 'W') ORDER BY date DESC, accountno DESC");
2269 $sth->execute($itemnumber);
2270 my $data = $sth->fetchrow_hashref;
2271 $data or return; # bail if there is nothing to do
2272 $data->{accounttype} eq 'W' and return; # Written off
2274 # writeoff this amount
2276 my $amount = $data->{'amount'};
2277 my $acctno = $data->{'accountno'};
2278 my $amountleft; # Starts off undef/zero.
2279 if ($data->{'amountoutstanding'} == $amount) {
2280 $offset = $data->{'amount'};
2281 $amountleft = 0; # Hey, it's zero here, too.
2283 $offset = $amount - $data->{'amountoutstanding'}; # Um, isn't this the same as ZERO? We just tested those two things are ==
2284 $amountleft = $data->{'amountoutstanding'} - $amount; # Um, isn't this the same as ZERO? We just tested those two things are ==
2286 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
2287 WHERE (accountlines_id = ?)");
2288 $usth->execute($data->{'accountlines_id'}); # We might be adjusting an account for some OTHER borrowernumber now. Not the one we passed in.
2289 #check if any credit is left if so writeoff other accounts
2290 my $nextaccntno = getnextacctno($data->{'borrowernumber'});
2291 $amountleft *= -1 if ($amountleft < 0);
2292 if ($amountleft > 0) {
2293 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
2294 AND (amountoutstanding >0) ORDER BY date"); # might want to order by amountoustanding ASC (pay smallest first)
2295 $msth->execute($data->{'borrowernumber'});
2296 # offset transactions
2299 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
2300 if ($accdata->{'amountoutstanding'} < $amountleft) {
2302 $amountleft -= $accdata->{'amountoutstanding'};
2304 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
2307 my $thisacct = $accdata->{'accountlines_id'};
2308 # FIXME: move prepares outside while loop!
2309 my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
2310 WHERE (accountlines_id = ?)");
2311 $usth->execute($newamtos,$thisacct);
2312 $usth = $dbh->prepare("INSERT INTO accountoffsets
2313 (borrowernumber, accountno, offsetaccount, offsetamount)
2316 $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
2319 $amountleft *= -1 if ($amountleft > 0);
2320 my $desc = "Item Returned " . $item_id;
2321 $usth = $dbh->prepare("INSERT INTO accountlines
2322 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
2323 VALUES (?,?,now(),?,?,'CR',?)");
2324 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
2325 if ($borrowernumber) {
2326 # FIXME: same as query above. use 1 sth for both
2327 $usth = $dbh->prepare("INSERT INTO accountoffsets
2328 (borrowernumber, accountno, offsetaccount, offsetamount)
2330 $usth->execute($borrowernumber, $data->{'accountno'}, $nextaccntno, $offset);
2332 ModItem({ paidfor => '' }, undef, $itemnumber);
2336 =head2 _GetCircControlBranch
2338 my $circ_control_branch = _GetCircControlBranch($iteminfos, $borrower);
2342 Return the library code to be used to determine which circulation
2343 policy applies to a transaction. Looks up the CircControl and
2344 HomeOrHoldingBranch system preferences.
2346 C<$iteminfos> is a hashref to iteminfo. Only {homebranch or holdingbranch} is used.
2348 C<$borrower> is a hashref to borrower. Only {branchcode} is used.
2352 sub _GetCircControlBranch {
2353 my ($item, $borrower) = @_;
2354 my $circcontrol = C4::Context->preference('CircControl');
2357 if ($circcontrol eq 'PickupLibrary' and (C4::Context->userenv and C4::Context->userenv->{'branch'}) ) {
2358 $branch= C4::Context->userenv->{'branch'};
2359 } elsif ($circcontrol eq 'PatronLibrary') {
2360 $branch=$borrower->{branchcode};
2362 my $branchfield = C4::Context->preference('HomeOrHoldingBranch') || 'homebranch';
2363 $branch = $item->{$branchfield};
2364 # default to item home branch if holdingbranch is used
2365 # and is not defined
2366 if (!defined($branch) && $branchfield eq 'holdingbranch') {
2367 $branch = $item->{homebranch};
2380 $issue = &GetItemIssue($itemnumber);
2382 Returns patron currently having a book, or undef if not checked out.
2384 C<$itemnumber> is the itemnumber.
2386 C<$issue> is a hashref of the row from the issues table.
2391 my ($itemnumber) = @_;
2392 return unless $itemnumber;
2393 my $sth = C4::Context->dbh->prepare(
2394 "SELECT items.*, issues.*
2396 LEFT JOIN items ON issues.itemnumber=items.itemnumber
2397 WHERE issues.itemnumber=?");
2398 $sth->execute($itemnumber);
2399 my $data = $sth->fetchrow_hashref;
2400 return unless $data;
2401 $data->{issuedate} = dt_from_string($data->{issuedate}, 'sql');
2402 $data->{issuedate}->truncate(to => 'minute');
2403 $data->{date_due} = dt_from_string($data->{date_due}, 'sql');
2404 $data->{date_due}->truncate(to => 'minute');
2405 my $dt = DateTime->now( time_zone => C4::Context->tz)->truncate( to => 'minute');
2406 $data->{'overdue'} = DateTime->compare($data->{'date_due'}, $dt ) == -1 ? 1 : 0;
2412 $issue = GetOpenIssue( $itemnumber );
2414 Returns the row from the issues table if the item is currently issued, undef if the item is not currently issued
2416 C<$itemnumber> is the item's itemnumber
2423 my ( $itemnumber ) = @_;
2424 return unless $itemnumber;
2425 my $dbh = C4::Context->dbh;
2426 my $sth = $dbh->prepare( "SELECT * FROM issues WHERE itemnumber = ? AND returndate IS NULL" );
2427 $sth->execute( $itemnumber );
2428 return $sth->fetchrow_hashref();
2434 $issues = GetIssues({}); # return all issues!
2435 $issues = GetIssues({ borrowernumber => $borrowernumber, biblionumber => $biblionumber });
2437 Returns all pending issues that match given criteria.
2438 Returns a arrayref or undef if an error occurs.
2440 Allowed criteria are:
2444 =item * borrowernumber
2446 =item * biblionumber
2455 my ($criteria) = @_;
2459 my @allowed = qw(borrowernumber biblionumber itemnumber);
2460 foreach (@allowed) {
2461 if (defined $criteria->{$_}) {
2464 value => $criteria->{$_},
2469 # Do we need to join other tables ?
2471 if (defined $criteria->{biblionumber}) {
2478 $where = "WHERE " . join(' AND ', map { "$_->{field} = ?" } @filters);
2484 if (defined $join{items}) {
2486 LEFT JOIN items ON (issues.itemnumber = items.itemnumber)
2492 my $dbh = C4::Context->dbh;
2493 my $sth = $dbh->prepare($query);
2494 my $rv = $sth->execute(map { $_->{value} } @filters);
2496 return $rv ? $sth->fetchall_arrayref({}) : undef;
2499 =head2 GetItemIssues
2501 $issues = &GetItemIssues($itemnumber, $history);
2503 Returns patrons that have issued a book
2505 C<$itemnumber> is the itemnumber
2506 C<$history> is false if you just want the current "issuer" (if any)
2507 and true if you want issues history from old_issues also.
2509 Returns reference to an array of hashes
2514 my ( $itemnumber, $history ) = @_;
2516 my $today = DateTime->now( time_zome => C4::Context->tz); # get today date
2517 $today->truncate( to => 'minute' );
2518 my $sql = "SELECT * FROM issues
2519 JOIN borrowers USING (borrowernumber)
2520 JOIN items USING (itemnumber)
2521 WHERE issues.itemnumber = ? ";
2524 SELECT * FROM old_issues
2525 LEFT JOIN borrowers USING (borrowernumber)
2526 JOIN items USING (itemnumber)
2527 WHERE old_issues.itemnumber = ? ";
2529 $sql .= "ORDER BY date_due DESC";
2530 my $sth = C4::Context->dbh->prepare($sql);
2532 $sth->execute($itemnumber, $itemnumber);
2534 $sth->execute($itemnumber);
2536 my $results = $sth->fetchall_arrayref({});
2537 foreach (@$results) {
2538 my $date_due = dt_from_string($_->{date_due},'sql');
2539 $date_due->truncate( to => 'minute' );
2541 $_->{overdue} = (DateTime->compare($date_due, $today) == -1) ? 1 : 0;
2546 =head2 GetBiblioIssues
2548 $issues = GetBiblioIssues($biblionumber);
2550 this function get all issues from a biblionumber.
2553 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
2554 tables issues and the firstname,surname & cardnumber from borrowers.
2558 sub GetBiblioIssues {
2559 my $biblionumber = shift;
2560 return unless $biblionumber;
2561 my $dbh = C4::Context->dbh;
2563 SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
2565 LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
2566 LEFT JOIN items ON issues.itemnumber = items.itemnumber
2567 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
2568 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
2569 WHERE biblio.biblionumber = ?
2571 SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
2573 LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
2574 LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
2575 LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
2576 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
2577 WHERE biblio.biblionumber = ?
2580 my $sth = $dbh->prepare($query);
2581 $sth->execute($biblionumber, $biblionumber);
2584 while ( my $data = $sth->fetchrow_hashref ) {
2585 push @issues, $data;
2590 =head2 GetUpcomingDueIssues
2592 my $upcoming_dues = GetUpcomingDueIssues( { days_in_advance => 4 } );
2596 sub GetUpcomingDueIssues {
2599 $params->{'days_in_advance'} = 7 unless exists $params->{'days_in_advance'};
2600 my $dbh = C4::Context->dbh;
2602 my $statement = <<END_SQL;
2603 SELECT issues.*, items.itype as itemtype, items.homebranch, TO_DAYS( date_due )-TO_DAYS( NOW() ) as days_until_due, branches.branchemail
2605 LEFT JOIN items USING (itemnumber)
2606 LEFT OUTER JOIN branches USING (branchcode)
2607 WHERE returndate is NULL
2608 HAVING days_until_due >= 0 AND days_until_due <= ?
2611 my @bind_parameters = ( $params->{'days_in_advance'} );
2613 my $sth = $dbh->prepare( $statement );
2614 $sth->execute( @bind_parameters );
2615 my $upcoming_dues = $sth->fetchall_arrayref({});
2617 return $upcoming_dues;
2620 =head2 CanBookBeRenewed
2622 ($ok,$error) = &CanBookBeRenewed($borrowernumber, $itemnumber[, $override_limit]);
2624 Find out whether a borrowed item may be renewed.
2626 C<$borrowernumber> is the borrower number of the patron who currently
2627 has the item on loan.
2629 C<$itemnumber> is the number of the item to renew.
2631 C<$override_limit>, if supplied with a true value, causes
2632 the limit on the number of times that the loan can be renewed
2633 (as controlled by the item type) to be ignored. Overriding also allows
2634 to renew sooner than "No renewal before" and to manually renew loans
2635 that are automatically renewed.
2637 C<$CanBookBeRenewed> returns a true value if the item may be renewed. The
2638 item must currently be on loan to the specified borrower; renewals
2639 must be allowed for the item's type; and the borrower must not have
2640 already renewed the loan. $error will contain the reason the renewal can not proceed
2644 sub CanBookBeRenewed {
2645 my ( $borrowernumber, $itemnumber, $override_limit ) = @_;
2647 my $dbh = C4::Context->dbh;
2650 my $item = GetItem($itemnumber) or return ( 0, 'no_item' );
2651 my $itemissue = GetItemIssue($itemnumber) or return ( 0, 'no_checkout' );
2653 $borrowernumber ||= $itemissue->{borrowernumber};
2654 my $borrower = C4::Members::GetMember( borrowernumber => $borrowernumber )
2657 my ( $resfound, $resrec, undef ) = C4::Reserves::CheckReserves($itemnumber);
2659 return ( 0, "on_reserve" ) if $resfound; # '' when no hold was found
2661 return ( 1, undef ) if $override_limit;
2663 my $branchcode = _GetCircControlBranch( $item, $borrower );
2665 GetIssuingRule( $borrower->{categorycode}, $item->{itype}, $branchcode );
2667 return ( 0, "too_many" )
2668 if $issuingrule->{renewalsallowed} <= $itemissue->{renewals};
2670 if ( $issuingrule->{norenewalbefore} ) {
2672 # Get current time and add norenewalbefore.
2673 # If this is smaller than date_due, it's too soon for renewal.
2675 DateTime->now( time_zone => C4::Context->tz() )->add(
2676 $issuingrule->{lengthunit} => $issuingrule->{norenewalbefore}
2677 ) < $itemissue->{date_due}
2680 return ( 0, "auto_too_soon" ) if $itemissue->{auto_renew};
2681 return ( 0, "too_soon" );
2685 return ( 0, "auto_renew" ) if $itemissue->{auto_renew};
2686 return ( 1, undef );
2691 &AddRenewal($borrowernumber, $itemnumber, $branch, [$datedue], [$lastreneweddate]);
2695 C<$borrowernumber> is the borrower number of the patron who currently
2698 C<$itemnumber> is the number of the item to renew.
2700 C<$branch> is the library where the renewal took place (if any).
2701 The library that controls the circ policies for the renewal is retrieved from the issues record.
2703 C<$datedue> can be a C4::Dates object used to set the due date.
2705 C<$lastreneweddate> is an optional ISO-formatted date used to set issues.lastreneweddate. If
2706 this parameter is not supplied, lastreneweddate is set to the current date.
2708 If C<$datedue> is the empty string, C<&AddRenewal> will calculate the due date automatically
2709 from the book's item type.
2714 my $borrowernumber = shift;
2715 my $itemnumber = shift or return;
2717 my $datedue = shift;
2718 my $lastreneweddate = shift || DateTime->now(time_zone => C4::Context->tz)->ymd();
2720 my $item = GetItem($itemnumber) or return;
2721 my $biblio = GetBiblioFromItemNumber($itemnumber) or return;
2723 my $dbh = C4::Context->dbh;
2725 # Find the issues record for this book
2727 $dbh->prepare("SELECT * FROM issues WHERE itemnumber = ?");
2728 $sth->execute( $itemnumber );
2729 my $issuedata = $sth->fetchrow_hashref;
2731 return unless ( $issuedata );
2733 $borrowernumber ||= $issuedata->{borrowernumber};
2735 if ( defined $datedue && ref $datedue ne 'DateTime' ) {
2736 carp 'Invalid date passed to AddRenewal.';
2740 # If the due date wasn't specified, calculate it by adding the
2741 # book's loan length to today's date or the current due date
2742 # based on the value of the RenewalPeriodBase syspref.
2745 my $borrower = C4::Members::GetMember( borrowernumber => $borrowernumber ) or return;
2746 my $itemtype = (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'};
2748 $datedue = (C4::Context->preference('RenewalPeriodBase') eq 'date_due') ?
2749 dt_from_string( $issuedata->{date_due} ) :
2750 DateTime->now( time_zone => C4::Context->tz());
2751 $datedue = CalcDateDue($datedue, $itemtype, $issuedata->{'branchcode'}, $borrower, 'is a renewal');
2754 # Update the issues record to have the new due date, and a new count
2755 # of how many times it has been renewed.
2756 my $renews = $issuedata->{'renewals'} + 1;
2757 $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?, lastreneweddate = ?
2758 WHERE borrowernumber=?
2762 $sth->execute( $datedue->strftime('%Y-%m-%d %H:%M'), $renews, $lastreneweddate, $borrowernumber, $itemnumber );
2764 # Update the renewal count on the item, and tell zebra to reindex
2765 $renews = $biblio->{'renewals'} + 1;
2766 ModItem({ renewals => $renews, onloan => $datedue->strftime('%Y-%m-%d %H:%M')}, $biblio->{'biblionumber'}, $itemnumber);
2768 # Charge a new rental fee, if applicable?
2769 my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2770 if ( $charge > 0 ) {
2771 my $accountno = getnextacctno( $borrowernumber );
2772 my $item = GetBiblioFromItemNumber($itemnumber);
2774 $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
2775 $sth = $dbh->prepare(
2776 "INSERT INTO accountlines
2777 (date, borrowernumber, accountno, amount, manager_id,
2778 description,accounttype, amountoutstanding, itemnumber)
2779 VALUES (now(),?,?,?,?,?,?,?,?)"
2781 $sth->execute( $borrowernumber, $accountno, $charge, $manager_id,
2782 "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
2783 'Rent', $charge, $itemnumber );
2786 # Send a renewal slip according to checkout alert preferencei
2787 if ( C4::Context->preference('RenewalSendNotice') eq '1') {
2788 my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 );
2789 my $circulation_alert = 'C4::ItemCirculationAlertPreference';
2791 branchcode => $branch,
2792 categorycode => $borrower->{categorycode},
2793 item_type => $item->{itype},
2794 notification => 'CHECKOUT',
2796 if ($circulation_alert->is_enabled_for(\%conditions)) {
2797 SendCirculationAlert({
2800 borrower => $borrower,
2806 # Remove any OVERDUES related debarment if the borrower has no overdues
2807 my $borrower = C4::Members::GetMember( borrowernumber => $borrowernumber );
2808 if ( $borrowernumber
2809 && $borrower->{'debarred'}
2810 && !HasOverdues( $borrowernumber )
2811 && @{ GetDebarments({ borrowernumber => $borrowernumber, type => 'OVERDUES' }) }
2813 DelUniqueDebarment({ borrowernumber => $borrowernumber, type => 'OVERDUES' });
2817 UpdateStats({branch => $branch,
2820 itemnumber => $itemnumber,
2821 itemtype => $item->{itype},
2822 borrowernumber => $borrowernumber,
2823 ccode => $item->{'ccode'}}
2829 # check renewal status
2830 my ( $bornum, $itemno ) = @_;
2831 my $dbh = C4::Context->dbh;
2833 my $renewsallowed = 0;
2836 my $borrower = C4::Members::GetMember( borrowernumber => $bornum);
2837 my $item = GetItem($itemno);
2839 # Look in the issues table for this item, lent to this borrower,
2840 # and not yet returned.
2842 # FIXME - I think this function could be redone to use only one SQL call.
2843 my $sth = $dbh->prepare(
2844 "select * from issues
2845 where (borrowernumber = ?)
2846 and (itemnumber = ?)"
2848 $sth->execute( $bornum, $itemno );
2849 my $data = $sth->fetchrow_hashref;
2850 $renewcount = $data->{'renewals'} if $data->{'renewals'};
2851 # $item and $borrower should be calculated
2852 my $branchcode = _GetCircControlBranch($item, $borrower);
2854 my $issuingrule = GetIssuingRule($borrower->{categorycode}, $item->{itype}, $branchcode);
2856 $renewsallowed = $issuingrule->{'renewalsallowed'};
2857 $renewsleft = $renewsallowed - $renewcount;
2858 if($renewsleft < 0){ $renewsleft = 0; }
2859 return ( $renewcount, $renewsallowed, $renewsleft );
2862 =head2 GetSoonestRenewDate
2864 $NoRenewalBeforeThisDate = &GetSoonestRenewDate($borrowernumber, $itemnumber);
2866 Find out the soonest possible renew date of a borrowed item.
2868 C<$borrowernumber> is the borrower number of the patron who currently
2869 has the item on loan.
2871 C<$itemnumber> is the number of the item to renew.
2873 C<$GetSoonestRenewDate> returns the DateTime of the soonest possible
2874 renew date, based on the value "No renewal before" of the applicable
2875 issuing rule. Returns the current date if the item can already be
2876 renewed, and returns undefined if the borrower, loan, or item
2881 sub GetSoonestRenewDate {
2882 my ( $borrowernumber, $itemnumber ) = @_;
2884 my $dbh = C4::Context->dbh;
2886 my $item = GetItem($itemnumber) or return;
2887 my $itemissue = GetItemIssue($itemnumber) or return;
2889 $borrowernumber ||= $itemissue->{borrowernumber};
2890 my $borrower = C4::Members::GetMemberDetails($borrowernumber)
2893 my $branchcode = _GetCircControlBranch( $item, $borrower );
2895 GetIssuingRule( $borrower->{categorycode}, $item->{itype}, $branchcode );
2897 my $now = DateTime->now( time_zone => C4::Context->tz() );
2899 if ( $issuingrule->{norenewalbefore} ) {
2900 my $soonestrenewal =
2901 $itemissue->{date_due}->subtract(
2902 $issuingrule->{lengthunit} => $issuingrule->{norenewalbefore} );
2904 $soonestrenewal = $now > $soonestrenewal ? $now : $soonestrenewal;
2905 return $soonestrenewal;
2910 =head2 GetIssuingCharges
2912 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
2914 Calculate how much it would cost for a given patron to borrow a given
2915 item, including any applicable discounts.
2917 C<$itemnumber> is the item number of item the patron wishes to borrow.
2919 C<$borrowernumber> is the patron's borrower number.
2921 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
2922 and C<$item_type> is the code for the item's item type (e.g., C<VID>
2927 sub GetIssuingCharges {
2929 # calculate charges due
2930 my ( $itemnumber, $borrowernumber ) = @_;
2932 my $dbh = C4::Context->dbh;
2935 # Get the book's item type and rental charge (via its biblioitem).
2936 my $charge_query = 'SELECT itemtypes.itemtype,rentalcharge FROM items
2937 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber';
2938 $charge_query .= (C4::Context->preference('item-level_itypes'))
2939 ? ' LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype'
2940 : ' LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype';
2942 $charge_query .= ' WHERE items.itemnumber =?';
2944 my $sth = $dbh->prepare($charge_query);
2945 $sth->execute($itemnumber);
2946 if ( my $item_data = $sth->fetchrow_hashref ) {
2947 $item_type = $item_data->{itemtype};
2948 $charge = $item_data->{rentalcharge};
2949 my $branch = C4::Branch::mybranch();
2950 my $discount_query = q|SELECT rentaldiscount,
2951 issuingrules.itemtype, issuingrules.branchcode
2953 LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
2954 WHERE borrowers.borrowernumber = ?
2955 AND (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
2956 AND (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')|;
2957 my $discount_sth = $dbh->prepare($discount_query);
2958 $discount_sth->execute( $borrowernumber, $item_type, $branch );
2959 my $discount_rules = $discount_sth->fetchall_arrayref({});
2960 if (@{$discount_rules}) {
2961 # We may have multiple rules so get the most specific
2962 my $discount = _get_discount_from_rule($discount_rules, $branch, $item_type);
2963 $charge = ( $charge * ( 100 - $discount ) ) / 100;
2967 return ( $charge, $item_type );
2970 # Select most appropriate discount rule from those returned
2971 sub _get_discount_from_rule {
2972 my ($rules_ref, $branch, $itemtype) = @_;
2975 if (@{$rules_ref} == 1) { # only 1 applicable rule use it
2976 $discount = $rules_ref->[0]->{rentaldiscount};
2977 return (defined $discount) ? $discount : 0;
2979 # could have up to 4 does one match $branch and $itemtype
2980 my @d = grep { $_->{branchcode} eq $branch && $_->{itemtype} eq $itemtype } @{$rules_ref};
2982 $discount = $d[0]->{rentaldiscount};
2983 return (defined $discount) ? $discount : 0;
2985 # do we have item type + all branches
2986 @d = grep { $_->{branchcode} eq q{*} && $_->{itemtype} eq $itemtype } @{$rules_ref};
2988 $discount = $d[0]->{rentaldiscount};
2989 return (defined $discount) ? $discount : 0;
2991 # do we all item types + this branch
2992 @d = grep { $_->{branchcode} eq $branch && $_->{itemtype} eq q{*} } @{$rules_ref};
2994 $discount = $d[0]->{rentaldiscount};
2995 return (defined $discount) ? $discount : 0;
2997 # so all and all (surely we wont get here)
2998 @d = grep { $_->{branchcode} eq q{*} && $_->{itemtype} eq q{*} } @{$rules_ref};
3000 $discount = $d[0]->{rentaldiscount};
3001 return (defined $discount) ? $discount : 0;
3007 =head2 AddIssuingCharge
3009 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
3013 sub AddIssuingCharge {
3014 my ( $itemnumber, $borrowernumber, $charge ) = @_;
3015 my $dbh = C4::Context->dbh;
3016 my $nextaccntno = getnextacctno( $borrowernumber );
3018 $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
3020 INSERT INTO accountlines
3021 (borrowernumber, itemnumber, accountno,
3022 date, amount, description, accounttype,
3023 amountoutstanding, manager_id)
3024 VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?,?)
3026 my $sth = $dbh->prepare($query);
3027 $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge, $manager_id );
3032 GetTransfers($itemnumber);
3037 my ($itemnumber) = @_;
3039 my $dbh = C4::Context->dbh;
3045 FROM branchtransfers
3046 WHERE itemnumber = ?
3047 AND datearrived IS NULL
3049 my $sth = $dbh->prepare($query);
3050 $sth->execute($itemnumber);
3051 my @row = $sth->fetchrow_array();
3055 =head2 GetTransfersFromTo
3057 @results = GetTransfersFromTo($frombranch,$tobranch);
3059 Returns the list of pending transfers between $from and $to branch
3063 sub GetTransfersFromTo {
3064 my ( $frombranch, $tobranch ) = @_;
3065 return unless ( $frombranch && $tobranch );
3066 my $dbh = C4::Context->dbh;
3068 SELECT itemnumber,datesent,frombranch
3069 FROM branchtransfers
3072 AND datearrived IS NULL
3074 my $sth = $dbh->prepare($query);
3075 $sth->execute( $frombranch, $tobranch );
3078 while ( my $data = $sth->fetchrow_hashref ) {
3079 push @gettransfers, $data;
3081 return (@gettransfers);
3084 =head2 DeleteTransfer
3086 &DeleteTransfer($itemnumber);
3090 sub DeleteTransfer {
3091 my ($itemnumber) = @_;
3092 return unless $itemnumber;
3093 my $dbh = C4::Context->dbh;
3094 my $sth = $dbh->prepare(
3095 "DELETE FROM branchtransfers
3097 AND datearrived IS NULL "
3099 return $sth->execute($itemnumber);
3102 =head2 AnonymiseIssueHistory
3104 ($rows,$err_history_not_deleted) = AnonymiseIssueHistory($date,$borrowernumber)
3106 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
3107 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
3109 If c<$borrowernumber> is set, it will delete issue history for only that borrower, regardless of their opac privacy
3110 setting (force delete).
3112 return the number of affected rows and a value that evaluates to true if an error occurred deleting the history.
3116 sub AnonymiseIssueHistory {
3118 my $borrowernumber = shift;
3119 my $dbh = C4::Context->dbh;
3122 SET borrowernumber = ?
3123 WHERE returndate < ?
3124 AND borrowernumber IS NOT NULL
3127 # The default of 0 does not work due to foreign key constraints
3128 # The anonymisation will fail quietly if AnonymousPatron is not a valid entry
3129 my $anonymouspatron = (C4::Context->preference('AnonymousPatron')) ? C4::Context->preference('AnonymousPatron') : 0;
3130 my @bind_params = ($anonymouspatron, $date);
3131 if (defined $borrowernumber) {
3132 $query .= " AND borrowernumber = ?";
3133 push @bind_params, $borrowernumber;
3135 $query .= " AND (SELECT privacy FROM borrowers WHERE borrowers.borrowernumber=old_issues.borrowernumber) <> 0";
3137 my $sth = $dbh->prepare($query);
3138 $sth->execute(@bind_params);
3139 my $anonymisation_err = $dbh->err;
3140 my $rows_affected = $sth->rows; ### doublecheck row count return function
3141 return ($rows_affected, $anonymisation_err);
3144 =head2 SendCirculationAlert
3146 Send out a C<check-in> or C<checkout> alert using the messaging system.
3154 Valid values for this parameter are: C<CHECKIN> and C<CHECKOUT>.
3158 Hashref of information about the item being checked in or out.
3162 Hashref of information about the borrower of the item.
3166 The branchcode from where the checkout or check-in took place.
3172 SendCirculationAlert({
3175 borrower => $borrower,
3181 sub SendCirculationAlert {
3183 my ($type, $item, $borrower, $branch) =
3184 ($opts->{type}, $opts->{item}, $opts->{borrower}, $opts->{branch});
3185 my %message_name = (
3186 CHECKIN => 'Item_Check_in',
3187 CHECKOUT => 'Item_Checkout',
3188 RENEWAL => 'Item_Checkout',
3190 my $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences({
3191 borrowernumber => $borrower->{borrowernumber},
3192 message_name => $message_name{$type},
3194 my $issues_table = ( $type eq 'CHECKOUT' || $type eq 'RENEWAL' ) ? 'issues' : 'old_issues';
3195 my $letter = C4::Letters::GetPreparedLetter (
3196 module => 'circulation',
3197 letter_code => $type,
3198 branchcode => $branch,
3200 $issues_table => $item->{itemnumber},
3201 'items' => $item->{itemnumber},
3202 'biblio' => $item->{biblionumber},
3203 'biblioitems' => $item->{biblionumber},
3204 'borrowers' => $borrower,
3205 'branches' => $branch,
3209 my @transports = keys %{ $borrower_preferences->{transports} };
3210 # warn "no transports" unless @transports;
3212 # warn "transport: $_";
3213 my $message = C4::Message->find_last_message($borrower, $type, $_);
3215 #warn "create new message";
3216 C4::Message->enqueue($letter, $borrower, $_);
3218 #warn "append to old message";
3219 $message->append($letter);
3227 =head2 updateWrongTransfer
3229 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
3231 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
3235 sub updateWrongTransfer {
3236 my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
3237 my $dbh = C4::Context->dbh;
3238 # first step validate the actual line of transfert .
3241 "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
3243 $sth->execute($FromLibrary,$itemNumber);
3245 # second step create a new line of branchtransfer to the right location .
3246 ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
3248 #third step changing holdingbranch of item
3249 UpdateHoldingbranch($FromLibrary,$itemNumber);
3252 =head2 UpdateHoldingbranch
3254 $items = UpdateHoldingbranch($branch,$itmenumber);
3256 Simple methode for updating hodlingbranch in items BDD line
3260 sub UpdateHoldingbranch {
3261 my ( $branch,$itemnumber ) = @_;
3262 ModItem({ holdingbranch => $branch }, undef, $itemnumber);
3267 $newdatedue = CalcDateDue($startdate,$itemtype,$branchcode,$borrower);
3269 this function calculates the due date given the start date and configured circulation rules,
3270 checking against the holidays calendar as per the 'useDaysMode' syspref.
3271 C<$startdate> = C4::Dates object representing start date of loan period (assumed to be today)
3272 C<$itemtype> = itemtype code of item in question
3273 C<$branch> = location whose calendar to use
3274 C<$borrower> = Borrower object
3275 C<$isrenewal> = Boolean: is true if we want to calculate the date due for a renewal. Else is false.
3280 my ( $startdate, $itemtype, $branch, $borrower, $isrenewal ) = @_;
3284 # loanlength now a href
3286 GetLoanLength( $borrower->{'categorycode'}, $itemtype, $branch );
3288 my $length_key = ( $isrenewal and defined $loanlength->{renewalperiod} )
3294 if (ref $startdate ne 'DateTime' ) {
3295 $datedue = dt_from_string($datedue);
3297 $datedue = $startdate->clone;
3301 DateTime->now( time_zone => C4::Context->tz() )
3302 ->truncate( to => 'minute' );
3306 # calculate the datedue as normal
3307 if ( C4::Context->preference('useDaysMode') eq 'Days' )
3308 { # ignoring calendar
3309 if ( $loanlength->{lengthunit} eq 'hours' ) {
3310 $datedue->add( hours => $loanlength->{$length_key} );
3312 $datedue->add( days => $loanlength->{$length_key} );
3313 $datedue->set_hour(23);
3314 $datedue->set_minute(59);
3318 if ($loanlength->{lengthunit} eq 'hours') {
3319 $dur = DateTime::Duration->new( hours => $loanlength->{$length_key});
3322 $dur = DateTime::Duration->new( days => $loanlength->{$length_key});
3324 my $calendar = Koha::Calendar->new( branchcode => $branch );
3325 $datedue = $calendar->addDate( $datedue, $dur, $loanlength->{lengthunit} );
3326 if ($loanlength->{lengthunit} eq 'days') {
3327 $datedue->set_hour(23);
3328 $datedue->set_minute(59);
3332 # if Hard Due Dates are used, retreive them and apply as necessary
3333 my ( $hardduedate, $hardduedatecompare ) =
3334 GetHardDueDate( $borrower->{'categorycode'}, $itemtype, $branch );
3335 if ($hardduedate) { # hardduedates are currently dates
3336 $hardduedate->truncate( to => 'minute' );
3337 $hardduedate->set_hour(23);
3338 $hardduedate->set_minute(59);
3339 my $cmp = DateTime->compare( $hardduedate, $datedue );
3341 # if the calculated due date is after the 'before' Hard Due Date (ceiling), override
3342 # if the calculated date is before the 'after' Hard Due Date (floor), override
3343 # if the hard due date is set to 'exactly', overrride
3344 if ( $hardduedatecompare == 0 || $hardduedatecompare == $cmp ) {
3345 $datedue = $hardduedate->clone;
3348 # in all other cases, keep the date due as it is
3352 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
3353 if ( C4::Context->preference('ReturnBeforeExpiry') ) {
3354 my $expiry_dt = dt_from_string( $borrower->{dateexpiry}, 'iso' );
3355 $expiry_dt->set( hour => 23, minute => 59);
3356 if ( DateTime->compare( $datedue, $expiry_dt ) == 1 ) {
3357 $datedue = $expiry_dt->clone;
3365 =head2 CheckRepeatableHolidays
3367 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
3369 This function checks if the date due is a repeatable holiday
3371 C<$date_due> = returndate calculate with no day check
3372 C<$itemnumber> = itemnumber
3373 C<$branchcode> = localisation of issue
3377 sub CheckRepeatableHolidays{
3378 my($itemnumber,$week_day,$branchcode)=@_;
3379 my $dbh = C4::Context->dbh;
3380 my $query = qq|SELECT count(*)
3381 FROM repeatable_holidays
3384 my $sth = $dbh->prepare($query);
3385 $sth->execute($branchcode,$week_day);
3386 my $result=$sth->fetchrow;
3391 =head2 CheckSpecialHolidays
3393 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
3395 This function check if the date is a special holiday
3397 C<$years> = the years of datedue
3398 C<$month> = the month of datedue
3399 C<$day> = the day of datedue
3400 C<$itemnumber> = itemnumber
3401 C<$branchcode> = localisation of issue
3405 sub CheckSpecialHolidays{
3406 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
3407 my $dbh = C4::Context->dbh;
3408 my $query=qq|SELECT count(*)
3409 FROM `special_holidays`
3415 my $sth = $dbh->prepare($query);
3416 $sth->execute($years,$month,$day,$branchcode);
3417 my $countspecial=$sth->fetchrow ;
3418 return $countspecial;
3421 =head2 CheckRepeatableSpecialHolidays
3423 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
3425 This function check if the date is a repeatble special holidays
3427 C<$month> = the month of datedue
3428 C<$day> = the day of datedue
3429 C<$itemnumber> = itemnumber
3430 C<$branchcode> = localisation of issue
3434 sub CheckRepeatableSpecialHolidays{
3435 my ($month,$day,$itemnumber,$branchcode) = @_;
3436 my $dbh = C4::Context->dbh;
3437 my $query=qq|SELECT count(*)
3438 FROM `repeatable_holidays`
3443 my $sth = $dbh->prepare($query);
3444 $sth->execute($month,$day,$branchcode);
3445 my $countspecial=$sth->fetchrow ;
3446 return $countspecial;
3451 sub CheckValidBarcode{
3453 my $dbh = C4::Context->dbh;
3454 my $query=qq|SELECT count(*)
3458 my $sth = $dbh->prepare($query);
3459 $sth->execute($barcode);
3460 my $exist=$sth->fetchrow ;
3464 =head2 IsBranchTransferAllowed
3466 $allowed = IsBranchTransferAllowed( $toBranch, $fromBranch, $code );
3468 Code is either an itemtype or collection doe depending on the pref BranchTransferLimitsType
3472 sub IsBranchTransferAllowed {
3473 my ( $toBranch, $fromBranch, $code ) = @_;
3475 if ( $toBranch eq $fromBranch ) { return 1; } ## Short circuit for speed.
3477 my $limitType = C4::Context->preference("BranchTransferLimitsType");
3478 my $dbh = C4::Context->dbh;
3480 my $sth = $dbh->prepare("SELECT * FROM branch_transfer_limits WHERE toBranch = ? AND fromBranch = ? AND $limitType = ?");
3481 $sth->execute( $toBranch, $fromBranch, $code );
3482 my $limit = $sth->fetchrow_hashref();
3484 ## If a row is found, then that combination is not allowed, if no matching row is found, then the combination *is allowed*
3485 if ( $limit->{'limitId'} ) {
3492 =head2 CreateBranchTransferLimit
3494 CreateBranchTransferLimit( $toBranch, $fromBranch, $code );
3496 $code is either itemtype or collection code depending on what the pref BranchTransferLimitsType is set to.
3500 sub CreateBranchTransferLimit {
3501 my ( $toBranch, $fromBranch, $code ) = @_;
3502 return unless defined($toBranch) && defined($fromBranch);
3503 my $limitType = C4::Context->preference("BranchTransferLimitsType");
3505 my $dbh = C4::Context->dbh;
3507 my $sth = $dbh->prepare("INSERT INTO branch_transfer_limits ( $limitType, toBranch, fromBranch ) VALUES ( ?, ?, ? )");
3508 return $sth->execute( $code, $toBranch, $fromBranch );
3511 =head2 DeleteBranchTransferLimits
3513 my $result = DeleteBranchTransferLimits($frombranch);
3515 Deletes all the library transfer limits for one library. Returns the
3516 number of limits deleted, 0e0 if no limits were deleted, or undef if
3517 no arguments are supplied.
3521 sub DeleteBranchTransferLimits {
3523 return unless defined $branch;
3524 my $dbh = C4::Context->dbh;
3525 my $sth = $dbh->prepare("DELETE FROM branch_transfer_limits WHERE fromBranch = ?");
3526 return $sth->execute($branch);
3530 my ( $borrowernumber, $itemnum ) = @_;
3532 MarkIssueReturned( $borrowernumber, $itemnum );
3533 my $borrower = C4::Members::GetMember( 'borrowernumber'=>$borrowernumber );
3534 my $item = C4::Items::GetItem( $itemnum );
3535 my $old_note = ($item->{'paidfor'} && ($item->{'paidfor'} ne q{})) ? $item->{'paidfor'}.' / ' : q{};
3536 my @datearr = localtime(time);
3537 my $date = ( 1900 + $datearr[5] ) . "-" . ( $datearr[4] + 1 ) . "-" . $datearr[3];
3538 my $bor = "$borrower->{'firstname'} $borrower->{'surname'} $borrower->{'cardnumber'}";
3539 ModItem({ paidfor => $old_note."Paid for by $bor $date" }, undef, $itemnum);
3544 my ($itemnumber, $mark_returned) = @_;
3546 my $dbh = C4::Context->dbh();
3547 my $sth=$dbh->prepare("SELECT issues.*,items.*,biblio.title
3549 JOIN items USING (itemnumber)
3550 JOIN biblio USING (biblionumber)
3551 WHERE issues.itemnumber=?");
3552 $sth->execute($itemnumber);
3553 my $issues=$sth->fetchrow_hashref();
3555 # If a borrower lost the item, add a replacement cost to the their record
3556 if ( my $borrowernumber = $issues->{borrowernumber} ){
3557 my $borrower = C4::Members::GetMemberDetails( $borrowernumber );
3559 if (C4::Context->preference('WhenLostForgiveFine')){
3560 my $fix = _FixOverduesOnReturn($borrowernumber, $itemnumber, 1, 0); # 1, 0 = exemptfine, no-dropbox
3561 defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $itemnumber...) failed!"; # zero is OK, check defined
3563 if (C4::Context->preference('WhenLostChargeReplacementFee')){
3564 C4::Accounts::chargelostitem($borrowernumber, $itemnumber, $issues->{'replacementprice'}, "Lost Item $issues->{'title'} $issues->{'barcode'}");
3565 #FIXME : Should probably have a way to distinguish this from an item that really was returned.
3566 #warn " $issues->{'borrowernumber'} / $itemnumber ";
3569 MarkIssueReturned($borrowernumber,$itemnumber,undef,undef,$borrower->{'privacy'}) if $mark_returned;
3573 sub GetOfflineOperations {
3574 my $dbh = C4::Context->dbh;
3575 my $sth = $dbh->prepare("SELECT * FROM pending_offline_operations WHERE branchcode=? ORDER BY timestamp");
3576 $sth->execute(C4::Context->userenv->{'branch'});
3577 my $results = $sth->fetchall_arrayref({});
3581 sub GetOfflineOperation {
3582 my $operationid = shift;
3583 return unless $operationid;
3584 my $dbh = C4::Context->dbh;
3585 my $sth = $dbh->prepare("SELECT * FROM pending_offline_operations WHERE operationid=?");
3586 $sth->execute( $operationid );
3587 return $sth->fetchrow_hashref;
3590 sub AddOfflineOperation {
3591 my ( $userid, $branchcode, $timestamp, $action, $barcode, $cardnumber, $amount ) = @_;
3592 my $dbh = C4::Context->dbh;
3593 my $sth = $dbh->prepare("INSERT INTO pending_offline_operations (userid, branchcode, timestamp, action, barcode, cardnumber, amount) VALUES(?,?,?,?,?,?,?)");
3594 $sth->execute( $userid, $branchcode, $timestamp, $action, $barcode, $cardnumber, $amount );
3598 sub DeleteOfflineOperation {
3599 my $dbh = C4::Context->dbh;
3600 my $sth = $dbh->prepare("DELETE FROM pending_offline_operations WHERE operationid=?");
3601 $sth->execute( shift );
3605 sub ProcessOfflineOperation {
3606 my $operation = shift;
3609 if ( $operation->{action} eq 'return' ) {
3610 $report = ProcessOfflineReturn( $operation );
3611 } elsif ( $operation->{action} eq 'issue' ) {
3612 $report = ProcessOfflineIssue( $operation );
3613 } elsif ( $operation->{action} eq 'payment' ) {
3614 $report = ProcessOfflinePayment( $operation );
3617 DeleteOfflineOperation( $operation->{operationid} ) if $operation->{operationid};
3622 sub ProcessOfflineReturn {
3623 my $operation = shift;
3625 my $itemnumber = C4::Items::GetItemnumberFromBarcode( $operation->{barcode} );
3627 if ( $itemnumber ) {
3628 my $issue = GetOpenIssue( $itemnumber );
3631 $issue->{borrowernumber},
3634 $operation->{timestamp},
3637 { renewals => 0, onloan => undef },
3638 $issue->{'biblionumber'},
3643 return "Item not issued.";
3646 return "Item not found.";
3650 sub ProcessOfflineIssue {
3651 my $operation = shift;
3653 my $borrower = C4::Members::GetMemberDetails( undef, $operation->{cardnumber} ); # Get borrower from operation cardnumber
3655 if ( $borrower->{borrowernumber} ) {
3656 my $itemnumber = C4::Items::GetItemnumberFromBarcode( $operation->{barcode} );
3657 unless ($itemnumber) {
3658 return "Barcode not found.";
3660 my $issue = GetOpenIssue( $itemnumber );
3662 if ( $issue and ( $issue->{borrowernumber} ne $borrower->{borrowernumber} ) ) { # Item already issued to another borrower, mark it returned
3664 $issue->{borrowernumber},
3667 $operation->{timestamp},
3672 $operation->{'barcode'},
3675 $operation->{timestamp},
3680 return "Borrower not found.";
3684 sub ProcessOfflinePayment {
3685 my $operation = shift;
3687 my $borrower = C4::Members::GetMemberDetails( undef, $operation->{cardnumber} ); # Get borrower from operation cardnumber
3688 my $amount = $operation->{amount};
3690 recordpayment( $borrower->{borrowernumber}, $amount );
3698 TransferSlip($user_branch, $itemnumber, $to_branch)
3700 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
3705 my ($branch, $itemnumber, $to_branch) = @_;
3707 my $item = GetItem( $itemnumber )
3710 my $pulldate = C4::Dates->new();
3712 return C4::Letters::GetPreparedLetter (
3713 module => 'circulation',
3714 letter_code => 'TRANSFERSLIP',
3715 branchcode => $branch,
3717 'branches' => $to_branch,
3718 'biblio' => $item->{biblionumber},
3724 =head2 CheckIfIssuedToPatron
3726 CheckIfIssuedToPatron($borrowernumber, $biblionumber)
3728 Return 1 if any record item is issued to patron, otherwise return 0
3732 sub CheckIfIssuedToPatron {
3733 my ($borrowernumber, $biblionumber) = @_;
3735 my $items = GetItemsByBiblioitemnumber($biblionumber);
3737 foreach my $item (@{$items}) {
3738 return 1 if ($item->{borrowernumber} && $item->{borrowernumber} eq $borrowernumber);
3746 IsItemIssued( $itemnumber )
3748 Return 1 if the item is on loan, otherwise return 0
3753 my $itemnumber = shift;
3754 my $dbh = C4::Context->dbh;
3755 my $sth = $dbh->prepare(q{
3758 WHERE itemnumber = ?
3760 $sth->execute($itemnumber);
3761 return $sth->fetchrow;
3764 sub GetAgeRestriction {
3765 my ($record_restrictions) = @_;
3766 my $markers = C4::Context->preference('AgeRestrictionMarker');
3768 # Split $record_restrictions to something like FSK 16 or PEGI 6
3769 my @values = split ' ', uc($record_restrictions);
3770 return unless @values;
3772 # Search first occurence of one of the markers
3773 my @markers = split /\|/, uc($markers);
3774 return unless @markers;
3777 my $restriction_year = 0;
3778 for my $value (@values) {
3780 for my $marker (@markers) {
3781 $marker =~ s/^\s+//; #remove leading spaces
3782 $marker =~ s/\s+$//; #remove trailing spaces
3783 if ( $marker eq $value ) {
3784 if ( $index <= $#values ) {
3785 $restriction_year += $values[$index];
3789 elsif ( $value =~ /^\Q$marker\E(\d+)$/ ) {
3791 # Perhaps it is something like "K16" (as in Finland)
3792 $restriction_year += $1;
3796 last if ( $restriction_year > 0 );
3799 return $restriction_year;
3808 Koha Development Team <http://koha-community.org/>