3 # This file is part of Koha.
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21 use Test::More tests => 63;
24 use Test::Deep qw( cmp_deeply );
30 use POSIX qw( floor );
32 use t::lib::TestBuilder;
35 use C4::Calendar qw( new insert_single_holiday insert_week_day_holiday delete_holiday );
36 use C4::Circulation qw( AddIssue AddReturn CanBookBeRenewed GetIssuingCharges AddRenewal GetSoonestRenewDate GetLatestAutoRenewDate LostItem GetUpcomingDueIssues CanBookBeIssued AddIssuingCharge MarkIssueReturned ProcessOfflinePayment transferbook updateWrongTransfer );
38 use C4::Items qw( ModItemTransfer );
40 use C4::Reserves qw( AddReserve ModReserve ModReserveCancelAll ModReserveAffect CheckReserves GetOtherReserves );
41 use C4::Overdues qw( CalcFine UpdateFine get_chargeable_units );
42 use C4::Members::Messaging qw( SetMessagingPreference );
43 use Koha::DateUtils qw( dt_from_string output_pref );
46 use Koha::Item::Transfers;
49 use Koha::Patron::Debarments qw( GetDebarments AddDebarment DelUniqueDebarment );
51 use Koha::CirculationRules;
52 use Koha::Subscriptions;
53 use Koha::Account::Lines;
54 use Koha::Account::Offsets;
56 use Koha::Notice::Messages;
57 use Koha::Cache::Memory::Lite;
59 my $builder = t::lib::TestBuilder->new;
62 my $staff = $builder->build_object({ class => "Koha::Patrons" });
63 t::lib::Mocks::mock_userenv({ patron => $staff, branchcode => $library->{branchcode} });
67 my ( $error, $question, $alert ) = @_;
69 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
70 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
71 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
75 sub test_debarment_on_checkout {
77 my $item = $params->{item};
78 my $library = $params->{library};
79 my $patron = $params->{patron};
80 my $due_date = $params->{due_date} || dt_from_string;
81 my $return_date = $params->{return_date} || dt_from_string;
82 my $expected_expiration_date = $params->{expiration_date};
84 $expected_expiration_date = output_pref(
86 dt => $expected_expiration_date,
92 my $line_number = $caller[2];
93 AddIssue( $patron, $item->barcode, $due_date );
95 my ( undef, $message ) = AddReturn( $item->barcode, $library->{branchcode}, undef, $return_date );
96 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
97 or diag('AddReturn returned message ' . Dumper $message );
98 my $debarments = Koha::Patron::Debarments::GetDebarments(
99 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
100 is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
102 is( $debarments->[0]->{expiration},
103 $expected_expiration_date, 'Test at line ' . $line_number );
104 Koha::Patron::Debarments::DelUniqueDebarment(
105 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
108 my $schema = Koha::Database->schema;
109 $schema->storage->txn_begin;
110 my $dbh = C4::Context->dbh;
112 # Prevent random failures by mocking ->now
113 my $now_value = dt_from_string;
114 my $mocked_datetime = Test::MockModule->new('DateTime');
115 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
117 my $cache = Koha::Caches->get_instance();
118 $dbh->do(q|DELETE FROM special_holidays|);
119 $dbh->do(q|DELETE FROM repeatable_holidays|);
120 my $branches = Koha::Libraries->search();
121 for my $branch ( $branches->next ) {
122 my $key = $branch->branchcode . "_holidays";
123 $cache->clear_from_cache($key);
126 # Start with a clean slate
127 $dbh->do('DELETE FROM issues');
128 $dbh->do('DELETE FROM borrowers');
130 # Disable recording of the staff who checked out an item until we're ready for it
131 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 0);
133 my $module = Test::MockModule->new('C4::Context');
135 my $library = $builder->build({
138 my $library2 = $builder->build({
141 my $itemtype = $builder->build(
143 source => 'Itemtype',
147 rentalcharge_daily => 0,
148 defaultreplacecost => undef,
153 my $patron_category = $builder->build(
155 source => 'Category',
157 category_type => 'P',
159 BlockExpiredPatronOpacActions => -1, # Pick the pref value
164 my $CircControl = C4::Context->preference('CircControl');
165 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
168 homebranch => $library2->{branchcode},
169 holdingbranch => $library2->{branchcode}
173 branchcode => $library2->{branchcode}
176 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
178 # No userenv, PickupLibrary
179 t::lib::Mocks::mock_preference('IndependentBranches', '0');
180 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
182 C4::Context->preference('CircControl'),
184 'CircControl changed to PickupLibrary'
187 C4::Circulation::_GetCircControlBranch($item, $borrower),
188 $item->{$HomeOrHoldingBranch},
189 '_GetCircControlBranch returned item branch (no userenv defined)'
192 # No userenv, PatronLibrary
193 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
195 C4::Context->preference('CircControl'),
197 'CircControl changed to PatronLibrary'
200 C4::Circulation::_GetCircControlBranch($item, $borrower),
201 $borrower->{branchcode},
202 '_GetCircControlBranch returned borrower branch'
205 # No userenv, ItemHomeLibrary
206 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
208 C4::Context->preference('CircControl'),
210 'CircControl changed to ItemHomeLibrary'
213 $item->{$HomeOrHoldingBranch},
214 C4::Circulation::_GetCircControlBranch($item, $borrower),
215 '_GetCircControlBranch returned item branch'
219 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
220 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
222 # Userenv set, PickupLibrary
223 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
225 C4::Context->preference('CircControl'),
227 'CircControl changed to PickupLibrary'
230 C4::Circulation::_GetCircControlBranch($item, $borrower),
231 $library2->{branchcode},
232 '_GetCircControlBranch returned current branch'
235 # Userenv set, PatronLibrary
236 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
238 C4::Context->preference('CircControl'),
240 'CircControl changed to PatronLibrary'
243 C4::Circulation::_GetCircControlBranch($item, $borrower),
244 $borrower->{branchcode},
245 '_GetCircControlBranch returned borrower branch'
248 # Userenv set, ItemHomeLibrary
249 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
251 C4::Context->preference('CircControl'),
253 'CircControl changed to ItemHomeLibrary'
256 C4::Circulation::_GetCircControlBranch($item, $borrower),
257 $item->{$HomeOrHoldingBranch},
258 '_GetCircControlBranch returned item branch'
261 # Reset initial configuration
262 t::lib::Mocks::mock_preference('CircControl', $CircControl);
264 C4::Context->preference('CircControl'),
266 'CircControl reset to its initial value'
269 # Set a simple circ policy
270 $dbh->do('DELETE FROM circulation_rules');
271 Koha::CirculationRules->set_rules(
273 categorycode => undef,
277 reservesallowed => 25,
279 lengthunit => 'days',
280 renewalsallowed => 1,
282 norenewalbefore => undef,
290 subtest "CanBookBeRenewed AllowRenewalIfOtherItemsAvailable multiple borrowers and items tests" => sub {
293 #Can only reserve from home branch
294 Koha::CirculationRules->set_rule(
298 rule_name => 'holdallowed',
302 Koha::CirculationRules->set_rule(
305 categorycode => undef,
307 rule_name => 'onshelfholds',
312 # Patrons from three different branches
313 my $patron_borrower = $builder->build_object({ class => 'Koha::Patrons' });
314 my $patron_hold_1 = $builder->build_object({ class => 'Koha::Patrons' });
315 my $patron_hold_2 = $builder->build_object({ class => 'Koha::Patrons' });
316 my $biblio = $builder->build_sample_biblio();
318 # Item at each patron branch
319 my $item_1 = $builder->build_sample_item({
320 biblionumber => $biblio->biblionumber,
321 homebranch => $patron_borrower->branchcode
323 my $item_2 = $builder->build_sample_item({
324 biblionumber => $biblio->biblionumber,
325 homebranch => $patron_hold_2->branchcode
327 my $item_3 = $builder->build_sample_item({
328 biblionumber => $biblio->biblionumber,
329 homebranch => $patron_hold_1->branchcode
332 my $issue = AddIssue( $patron_borrower->unblessed, $item_1->barcode);
333 my $datedue = dt_from_string( $issue->date_due() );
334 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
339 branchcode => $patron_hold_1->branchcode,
340 borrowernumber => $patron_hold_1->borrowernumber,
341 biblionumber => $biblio->biblionumber,
343 reservation_date => dt_from_string(),
344 expiration_date => undef,
351 branchcode => $patron_hold_2->branchcode,
352 borrowernumber => $patron_hold_2->borrowernumber,
353 biblionumber => $biblio->biblionumber,
355 reservation_date => dt_from_string(),
356 expiration_date => undef,
361 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
363 my ( $renewokay, $error ) = CanBookBeRenewed($patron_borrower->borrowernumber, $item_1->itemnumber);
364 is( $renewokay, 0, 'Cannot renew, reserved');
365 is( $error, 'on_reserve', 'Cannot renew, reserved (returned error is on_reserve)');
367 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
369 ( $renewokay, $error ) = CanBookBeRenewed($patron_borrower->borrowernumber, $item_1->itemnumber);
370 is( $renewokay, 1, 'Can renew, two items available for two holds');
371 is( $error, undef, 'Can renew, each reserve has an item');
376 subtest "GetIssuingCharges tests" => sub {
378 my $branch_discount = $builder->build_object({ class => 'Koha::Libraries' });
379 my $branch_no_discount = $builder->build_object({ class => 'Koha::Libraries' });
380 Koha::CirculationRules->set_rule(
382 categorycode => undef,
383 branchcode => $branch_discount->branchcode,
385 rule_name => 'rentaldiscount',
389 my $itype_charge = $builder->build_object({
390 class => 'Koha::ItemTypes',
395 my $itype_no_charge = $builder->build_object({
396 class => 'Koha::ItemTypes',
401 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
402 my $item_1 = $builder->build_sample_item({ itype => $itype_charge->itemtype });
403 my $item_2 = $builder->build_sample_item({ itype => $itype_no_charge->itemtype });
405 t::lib::Mocks::mock_userenv({ branchcode => $branch_no_discount->branchcode });
406 # For now the sub always uses the env branch, this should follow CircControl instead
407 my ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
408 is( $charge + 0, 10.00, "Charge fetched correctly when no discount exists");
409 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
410 is( $charge + 0, 0.00, "Charge fetched correctly when no discount exists and no charge");
412 t::lib::Mocks::mock_userenv({ branchcode => $branch_discount->branchcode });
413 # For now the sub always uses the env branch, this should follow CircControl instead
414 ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
415 is( $charge + 0, 8.50, "Charge fetched correctly when discount exists");
416 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
417 is( $charge + 0, 0.00, "Charge fetched correctly when discount exists and no charge");
421 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
422 subtest "CanBookBeRenewed tests" => sub {
425 C4::Context->set_preference('ItemsDeniedRenewal','');
426 # Generate test biblio
427 my $biblio = $builder->build_sample_biblio();
429 my $branch = $library2->{branchcode};
431 my $item_1 = $builder->build_sample_item(
433 biblionumber => $biblio->biblionumber,
435 replacementprice => 12.00,
439 $reused_itemnumber_1 = $item_1->itemnumber;
441 my $item_2 = $builder->build_sample_item(
443 biblionumber => $biblio->biblionumber,
445 replacementprice => 23.00,
449 $reused_itemnumber_2 = $item_2->itemnumber;
451 my $item_3 = $builder->build_sample_item(
453 biblionumber => $biblio->biblionumber,
455 replacementprice => 23.00,
461 my %renewing_borrower_data = (
463 surname => 'Renewal',
464 categorycode => $patron_category->{categorycode},
465 branchcode => $branch,
468 my %reserving_borrower_data = (
469 firstname => 'Katrin',
470 surname => 'Reservation',
471 categorycode => $patron_category->{categorycode},
472 branchcode => $branch,
475 my %hold_waiting_borrower_data = (
477 surname => 'Reservation',
478 categorycode => $patron_category->{categorycode},
479 branchcode => $branch,
482 my %restricted_borrower_data = (
483 firstname => 'Alice',
484 surname => 'Reservation',
485 categorycode => $patron_category->{categorycode},
486 debarred => '3228-01-01',
487 branchcode => $branch,
490 my %expired_borrower_data = (
493 categorycode => $patron_category->{categorycode},
494 branchcode => $branch,
495 dateexpiry => dt_from_string->subtract( months => 1 ),
498 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
499 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
500 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
501 my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
502 my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
504 my $renewing_borrower_obj = Koha::Patrons->find( $renewing_borrowernumber );
505 my $renewing_borrower = $renewing_borrower_obj->unblessed;
506 my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
507 my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
514 my $checkitem = undef;
517 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
518 my $datedue = dt_from_string( $issue->date_due() );
519 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
521 my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
522 $datedue = dt_from_string( $issue->date_due() );
523 is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
526 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
527 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
529 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
530 is( $renewokay, 1, 'Can renew, no holds for this title or item');
533 # Biblio-level hold, renewal test
536 branchcode => $branch,
537 borrowernumber => $reserving_borrowernumber,
538 biblionumber => $biblio->biblionumber,
539 priority => $priority,
540 reservation_date => $resdate,
541 expiration_date => $expdate,
543 itemnumber => $checkitem,
548 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
549 Koha::CirculationRules->set_rule(
551 categorycode => undef,
554 rule_name => 'onshelfholds',
558 Koha::CirculationRules->set_rule(
560 categorycode => undef,
563 rule_name => 'renewalsallowed',
567 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
568 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
569 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
570 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
571 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
574 # Second biblio-level hold
575 my $reserve_id = AddReserve(
577 branchcode => $branch,
578 borrowernumber => $reserving_borrowernumber,
579 biblionumber => $biblio->biblionumber,
580 priority => $priority,
581 reservation_date => $resdate,
582 expiration_date => $expdate,
584 itemnumber => $checkitem,
588 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
589 is( $renewokay, 0, 'Renewal not possible when single patron\'s holds exceed the number of available items');
590 Koha::Holds->find($reserve_id)->delete;
592 # Now let's add an item level hold, we should no longer be able to renew the item
593 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
595 borrowernumber => $hold_waiting_borrowernumber,
596 biblionumber => $biblio->biblionumber,
597 itemnumber => $item_1->itemnumber,
598 branchcode => $branch,
600 reservedate => '1999-01-01',
603 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
604 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
607 # Now let's add a waiting hold on the 3rd item, it's no longer available tp check out by just anyone, so we should no longer
608 # be able to renew these items
609 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
611 borrowernumber => $hold_waiting_borrowernumber,
612 biblionumber => $biblio->biblionumber,
613 itemnumber => $item_3->itemnumber,
614 branchcode => $branch,
619 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
620 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
621 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
622 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
623 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
625 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
626 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
627 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
629 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
630 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
631 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
633 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
634 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
635 AddIssue($reserving_borrower, $item_3->barcode);
636 my $reserve = $dbh->selectrow_hashref(
637 'SELECT * FROM old_reserves WHERE reserve_id = ?',
641 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
643 # Item-level hold, renewal test
646 branchcode => $branch,
647 borrowernumber => $reserving_borrowernumber,
648 biblionumber => $biblio->biblionumber,
649 priority => $priority,
650 reservation_date => $resdate,
651 expiration_date => $expdate,
653 itemnumber => $item_1->itemnumber,
658 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
659 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
660 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
662 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
663 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
665 # Items can't fill hold for reasons
666 $item_1->notforloan(1)->store;
667 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
668 is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
669 $item_1->set({notforloan => 0, itype => $itemtype })->store;
671 # FIXME: Add more for itemtype not for loan etc.
673 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
674 my $item_5 = $builder->build_sample_item(
676 biblionumber => $biblio->biblionumber,
678 replacementprice => 23.00,
682 my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
683 is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
685 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
686 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
687 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
688 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
689 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
690 is( $error, 'restriction', "Correct error returned");
692 # Users cannot renew an overdue item
693 my $item_6 = $builder->build_sample_item(
695 biblionumber => $biblio->biblionumber,
697 replacementprice => 23.00,
702 my $item_7 = $builder->build_sample_item(
704 biblionumber => $biblio->biblionumber,
706 replacementprice => 23.00,
711 my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
712 is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
714 my $now = dt_from_string();
715 my $five_weeks = DateTime::Duration->new(weeks => 5);
716 my $five_weeks_ago = $now - $five_weeks;
717 t::lib::Mocks::mock_preference('finesMode', 'production');
719 my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
720 is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
722 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
723 C4::Overdues::UpdateFine(
725 issue_id => $passeddatedue1->id(),
726 itemnumber => $item_7->itemnumber,
727 borrowernumber => $renewing_borrower->{borrowernumber},
729 due => Koha::DateUtils::output_pref($five_weeks_ago)
733 # Make sure fine calculation isn't skipped when adding renewal
734 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
736 my $staff = $builder->build_object({ class => "Koha::Patrons" });
737 t::lib::Mocks::mock_userenv({ patron => $staff });
739 t::lib::Mocks::mock_preference('RenewalLog', 0);
740 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
741 my %params_renewal = (
742 timestamp => { -like => $date . "%" },
743 module => "CIRCULATION",
747 timestamp => { -like => $date . "%" },
748 module => "CIRCULATION",
751 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
752 my $dt = dt_from_string();
753 Time::Fake->offset( $dt->epoch );
754 my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
755 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
756 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
757 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
760 t::lib::Mocks::mock_preference('RenewalLog', 1);
761 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
762 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
763 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
764 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
765 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
767 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
768 is( $fines->count, 2, 'AddRenewal left both fines' );
769 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
770 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
773 t::lib::Mocks::mock_preference('OverduesBlockRenewing','allow');
774 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
775 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
776 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
777 is( $renewokay, 1, '(Bug 8236), Can renew, this item is overdue but not pref does not block');
779 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
780 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
781 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is not overdue but patron has overdues');
782 is( $error, 'overdue', "Correct error returned");
783 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
784 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue so patron has overdues');
785 is( $error, 'overdue', "Correct error returned");
787 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
788 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
789 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
790 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
791 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
792 is( $error, 'overdue', "Correct error returned");
795 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
796 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
797 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
798 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
799 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
800 $new_log_size = Koha::ActionLogs->count( \%params_issue );
801 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
803 $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
806 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
810 # Test automatic renewal before value for "norenewalbefore" in policy is set
811 # In this case automatic renewal is not permitted prior to due date
812 my $item_4 = $builder->build_sample_item(
814 biblionumber => $biblio->biblionumber,
816 replacementprice => 16.00,
821 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
823 ( $renewokay, $error, $info ) =
824 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
825 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
826 is( $error, 'auto_too_soon',
827 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
828 is( $info->{soonest_renew_date} , dt_from_string($issue->date_due), "Due date is returned as earliest renewal date when error is 'auto_too_soon'" );
831 branchcode => $branch,
832 borrowernumber => $reserving_borrowernumber,
833 biblionumber => $biblio->biblionumber,
834 itemnumber => $bibitems,
835 priority => $priority,
836 reservation_date => $resdate,
837 expiration_date => $expdate,
840 itemnumber => $item_4->itemnumber,
844 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
845 is( $renewokay, 0, 'Still should not be able to renew' );
846 is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' );
847 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, undef, 1 );
848 is( $renewokay, 0, 'Still should not be able to renew' );
849 is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' );
850 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due), "Due date is returned as earliest renewal date when error is 'auto_too_soon'" );
851 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
852 is( $renewokay, 0, 'Still should not be able to renew' );
853 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
854 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1, 1 );
855 is( $renewokay, 0, 'Still should not be able to renew' );
856 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
857 $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
858 Koha::Cache::Memory::Lite->flush();
859 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
860 is( $renewokay, 0, 'Still should not be able to renew' );
861 is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
862 ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
866 $renewing_borrower_obj->autorenew_checkouts(0)->store;
867 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
868 is( $renewokay, 1, 'No renewal before is undef, but patron opted out of auto_renewal' );
869 $renewing_borrower_obj->autorenew_checkouts(1)->store;
873 # Test premature manual renewal
874 Koha::CirculationRules->set_rule(
876 categorycode => undef,
879 rule_name => 'norenewalbefore',
884 ( $renewokay, $error, $info ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
885 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
886 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
887 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
890 # Test premature automatic renewal
891 ( $renewokay, $error, $info ) =
892 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
893 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
894 is( $error, 'auto_too_soon',
895 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
897 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'auto_too_soon'");
899 $renewing_borrower_obj->autorenew_checkouts(0)->store;
900 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
901 is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' );
902 is( $error, 'too_soon', 'Error is too_soon, no auto' );
903 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
904 $renewing_borrower_obj->autorenew_checkouts(1)->store;
906 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
907 # and test automatic renewal again
908 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
909 Koha::Cache::Memory::Lite->flush();
910 ( $renewokay, $error, $info ) =
911 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
912 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
913 is( $error, 'auto_too_soon',
914 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
916 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
918 $renewing_borrower_obj->autorenew_checkouts(0)->store;
919 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
920 is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' );
921 is( $error, 'too_soon', 'Error is too_soon, no auto' );
922 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
923 $renewing_borrower_obj->autorenew_checkouts(1)->store;
925 # Change policy so that loans can be renewed 99 days prior to the due date
926 # and test automatic renewal again
927 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
928 Koha::Cache::Memory::Lite->flush();
929 ( $renewokay, $error ) =
930 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
931 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
932 is( $error, 'auto_renew',
933 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
936 $renewing_borrower_obj->autorenew_checkouts(0)->store;
937 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
938 is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' );
939 $renewing_borrower_obj->autorenew_checkouts(1)->store;
941 subtest "too_late_renewal / no_auto_renewal_after" => sub {
943 my $item_to_auto_renew = $builder->build_sample_item(
945 biblionumber => $biblio->biblionumber,
950 my $ten_days_before = dt_from_string->add( days => -10 );
951 my $ten_days_ahead = dt_from_string->add( days => 10 );
952 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
954 Koha::CirculationRules->set_rules(
956 categorycode => undef,
960 norenewalbefore => '7',
961 no_auto_renewal_after => '9',
965 ( $renewokay, $error ) =
966 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
967 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
968 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
970 Koha::CirculationRules->set_rules(
972 categorycode => undef,
976 norenewalbefore => '7',
977 no_auto_renewal_after => '10',
981 ( $renewokay, $error ) =
982 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
983 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
984 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
986 Koha::CirculationRules->set_rules(
988 categorycode => undef,
992 norenewalbefore => '7',
993 no_auto_renewal_after => '11',
997 ( $renewokay, $error ) =
998 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
999 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1000 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
1002 Koha::CirculationRules->set_rules(
1004 categorycode => undef,
1005 branchcode => undef,
1008 norenewalbefore => '10',
1009 no_auto_renewal_after => '11',
1013 ( $renewokay, $error ) =
1014 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1015 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1016 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1018 Koha::CirculationRules->set_rules(
1020 categorycode => undef,
1021 branchcode => undef,
1024 norenewalbefore => '10',
1025 no_auto_renewal_after => undef,
1026 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1030 ( $renewokay, $error ) =
1031 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1032 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1033 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1035 Koha::CirculationRules->set_rules(
1037 categorycode => undef,
1038 branchcode => undef,
1041 norenewalbefore => '7',
1042 no_auto_renewal_after => '15',
1043 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1047 ( $renewokay, $error ) =
1048 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1049 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1050 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1052 Koha::CirculationRules->set_rules(
1054 categorycode => undef,
1055 branchcode => undef,
1058 norenewalbefore => '10',
1059 no_auto_renewal_after => undef,
1060 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
1064 ( $renewokay, $error ) =
1065 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1066 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1067 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1070 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
1072 my $item_to_auto_renew = $builder->build_sample_item(
1074 biblionumber => $biblio->biblionumber,
1079 my $ten_days_before = dt_from_string->add( days => -10 );
1080 my $ten_days_ahead = dt_from_string->add( days => 10 );
1081 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1083 Koha::CirculationRules->set_rules(
1085 categorycode => undef,
1086 branchcode => undef,
1089 norenewalbefore => '10',
1090 no_auto_renewal_after => '11',
1094 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
1095 C4::Context->set_preference('OPACFineNoRenewals','10');
1096 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1097 my $fines_amount = 5;
1098 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
1099 $account->add_debit(
1101 amount => $fines_amount,
1102 interface => 'test',
1104 item_id => $item_to_auto_renew->itemnumber,
1105 description => "Some fines"
1107 )->status('RETURNED')->store;
1108 ( $renewokay, $error ) =
1109 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1110 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1111 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
1113 $account->add_debit(
1115 amount => $fines_amount,
1116 interface => 'test',
1118 item_id => $item_to_auto_renew->itemnumber,
1119 description => "Some fines"
1121 )->status('RETURNED')->store;
1122 ( $renewokay, $error ) =
1123 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1124 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1125 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
1127 $account->add_debit(
1129 amount => $fines_amount,
1130 interface => 'test',
1132 item_id => $item_to_auto_renew->itemnumber,
1133 description => "Some fines"
1135 )->status('RETURNED')->store;
1136 ( $renewokay, $error ) =
1137 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1138 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1139 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
1141 $account->add_credit(
1143 amount => $fines_amount,
1144 interface => 'test',
1146 description => "Some payment"
1149 ( $renewokay, $error ) =
1150 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1151 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1152 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1154 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
1155 ( $renewokay, $error ) =
1156 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1157 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1158 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1160 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
1161 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1164 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
1166 my $item_to_auto_renew = $builder->build_sample_item(
1168 biblionumber => $biblio->biblionumber,
1173 Koha::CirculationRules->set_rules(
1175 categorycode => undef,
1176 branchcode => undef,
1179 norenewalbefore => 10,
1180 no_auto_renewal_after => 11,
1185 my $ten_days_before = dt_from_string->add( days => -10 );
1186 my $ten_days_ahead = dt_from_string->add( days => 10 );
1188 # Patron is expired and BlockExpiredPatronOpacActions=0
1189 # => auto renew is allowed
1190 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
1191 my $patron = $expired_borrower;
1192 my $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1193 ( $renewokay, $error ) =
1194 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1195 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1196 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
1197 Koha::Checkouts->find( $checkout->issue_id )->delete;
1200 # Patron is expired and BlockExpiredPatronOpacActions=1
1201 # => auto renew is not allowed
1202 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1203 $patron = $expired_borrower;
1204 $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1205 ( $renewokay, $error ) =
1206 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1207 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1208 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
1209 Koha::Checkouts->find( $checkout->issue_id )->delete;
1212 # Patron is not expired and BlockExpiredPatronOpacActions=1
1213 # => auto renew is allowed
1214 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1215 $patron = $renewing_borrower;
1216 $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1217 ( $renewokay, $error ) =
1218 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1219 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1220 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1221 Koha::Checkouts->find( $checkout->issue_id )->delete;
1224 subtest "GetLatestAutoRenewDate" => sub {
1226 my $item_to_auto_renew = $builder->build_sample_item(
1228 biblionumber => $biblio->biblionumber,
1233 my $ten_days_before = dt_from_string->add( days => -10 );
1234 my $ten_days_ahead = dt_from_string->add( days => 10 );
1235 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1236 Koha::CirculationRules->set_rules(
1238 categorycode => undef,
1239 branchcode => undef,
1242 norenewalbefore => '7',
1243 no_auto_renewal_after => '',
1244 no_auto_renewal_after_hard_limit => undef,
1248 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1249 is( $latest_auto_renew_date, undef, 'GetLatestAutoRenewDate should return undef if no_auto_renewal_after or no_auto_renewal_after_hard_limit are not defined' );
1250 my $five_days_before = dt_from_string->add( days => -5 );
1251 Koha::CirculationRules->set_rules(
1253 categorycode => undef,
1254 branchcode => undef,
1257 norenewalbefore => '10',
1258 no_auto_renewal_after => '5',
1259 no_auto_renewal_after_hard_limit => undef,
1263 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1264 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1265 $five_days_before->truncate( to => 'minute' ),
1266 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1268 my $five_days_ahead = dt_from_string->add( days => 5 );
1269 $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1270 $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1271 $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1272 Koha::Cache::Memory::Lite->flush();
1273 Koha::CirculationRules->set_rules(
1275 categorycode => undef,
1276 branchcode => undef,
1279 norenewalbefore => '10',
1280 no_auto_renewal_after => '15',
1281 no_auto_renewal_after_hard_limit => undef,
1285 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1286 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1287 $five_days_ahead->truncate( to => 'minute' ),
1288 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1290 my $two_days_ahead = dt_from_string->add( days => 2 );
1291 Koha::CirculationRules->set_rules(
1293 categorycode => undef,
1294 branchcode => undef,
1297 norenewalbefore => '10',
1298 no_auto_renewal_after => '',
1299 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1303 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1304 is( $latest_auto_renew_date->truncate( to => 'day' ),
1305 $two_days_ahead->truncate( to => 'day' ),
1306 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1308 Koha::CirculationRules->set_rules(
1310 categorycode => undef,
1311 branchcode => undef,
1314 norenewalbefore => '10',
1315 no_auto_renewal_after => '15',
1316 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1320 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1321 is( $latest_auto_renew_date->truncate( to => 'day' ),
1322 $two_days_ahead->truncate( to => 'day' ),
1323 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1329 # set policy to forbid renewals
1330 Koha::CirculationRules->set_rules(
1332 categorycode => undef,
1333 branchcode => undef,
1336 norenewalbefore => undef,
1337 renewalsallowed => 0,
1342 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1343 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1344 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1346 # Too many unseen renewals
1347 Koha::CirculationRules->set_rules(
1349 categorycode => undef,
1350 branchcode => undef,
1353 unseen_renewals_allowed => 2,
1354 renewalsallowed => 10,
1358 t::lib::Mocks::mock_preference('UnseenRenewals', 1);
1359 $dbh->do('UPDATE issues SET unseen_renewals = 2 where borrowernumber = ? AND itemnumber = ?', undef, ($renewing_borrowernumber, $item_1->itemnumber));
1360 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1361 is( $renewokay, 0, 'Cannot renew, 0 unseen renewals allowed');
1362 is( $error, 'too_unseen', 'Cannot renew, returned code is too_unseen');
1363 Koha::CirculationRules->set_rules(
1365 categorycode => undef,
1366 branchcode => undef,
1369 norenewalbefore => undef,
1370 renewalsallowed => 0,
1374 t::lib::Mocks::mock_preference('UnseenRenewals', 0);
1376 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1377 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1378 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1380 C4::Overdues::UpdateFine(
1382 issue_id => $issue->id(),
1383 itemnumber => $item_1->itemnumber,
1384 borrowernumber => $renewing_borrower->{borrowernumber},
1387 due => Koha::DateUtils::output_pref($datedue)
1391 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
1392 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1393 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1394 is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1395 is( $line->amount+0, 15, 'Account line amount is 15.00' );
1396 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
1398 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1399 is( $offset->type, 'CREATE', 'Account offset type is CREATE' );
1400 is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1402 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1403 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1405 LostItem( $item_1->itemnumber, 'test', 1 );
1407 $line = Koha::Account::Lines->find($line->id);
1408 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1409 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1411 my $item = Koha::Items->find($item_1->itemnumber);
1412 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1413 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1414 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1416 my $total_due = $dbh->selectrow_array(
1417 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1418 undef, $renewing_borrower->{borrowernumber}
1421 is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1423 C4::Context->dbh->do("DELETE FROM accountlines");
1425 C4::Overdues::UpdateFine(
1427 issue_id => $issue2->id(),
1428 itemnumber => $item_2->itemnumber,
1429 borrowernumber => $renewing_borrower->{borrowernumber},
1432 due => Koha::DateUtils::output_pref($datedue)
1436 LostItem( $item_2->itemnumber, 'test', 0 );
1438 my $item2 = Koha::Items->find($item_2->itemnumber);
1439 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1440 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1442 $total_due = $dbh->selectrow_array(
1443 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1444 undef, $renewing_borrower->{borrowernumber}
1447 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1449 my $future = dt_from_string();
1450 $future->add( days => 7 );
1451 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1452 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1454 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1455 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1456 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1457 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1458 LostItem( $item_3->itemnumber, 'test', 0 );
1459 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1460 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1462 $accountline->description,
1463 sprintf( "%s %s %s",
1464 $item_3->biblio->title || '',
1465 $item_3->barcode || '',
1466 $item_3->itemcallnumber || '' ),
1467 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1471 t::lib::Mocks::mock_preference('UseRecalls', 1);
1472 Koha::CirculationRules->set_rules({
1473 categorycode => undef,
1474 branchcode => undef,
1477 recalls_allowed => 10,
1478 renewalsallowed => 5,
1481 my $recall_borrower = $builder->build_object({ class => 'Koha::Patrons' });
1482 my $recall_biblio = $builder->build_object({ class => 'Koha::Biblios' });
1483 my $recall_item1 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $recall_biblio->biblionumber } });
1484 my $recall_item2 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $recall_biblio->biblionumber } });
1486 AddIssue( $renewing_borrower, $recall_item1->barcode );
1488 # item-level and this item: renewal not allowed
1489 my $recall = Koha::Recall->new({
1490 biblio_id => $recall_item1->biblionumber,
1491 item_id => $recall_item1->itemnumber,
1492 patron_id => $recall_borrower->borrowernumber,
1493 pickup_library_id => $recall_borrower->branchcode,
1496 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1497 is( $error, 'recalled', 'Cannot renew item that has been recalled' );
1498 $recall->set_cancelled;
1500 # biblio-level requested recall: renewal not allowed
1501 $recall = Koha::Recall->new({
1502 biblio_id => $recall_item1->biblionumber,
1504 patron_id => $recall_borrower->borrowernumber,
1505 pickup_library_id => $recall_borrower->branchcode,
1508 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1509 is( $error, 'recalled', 'Cannot renew item if biblio is recalled and has no item allocated' );
1510 $recall->set_cancelled;
1512 # item-level and not this item: renewal allowed
1513 $recall = Koha::Recall->new({
1514 biblio_id => $recall_item2->biblionumber,
1515 item_id => $recall_item2->itemnumber,
1516 patron_id => $recall_borrower->borrowernumber,
1517 pickup_library_id => $recall_borrower->branchcode,
1520 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1521 is( $renewokay, 1, 'Can renew item if item-level recall on biblio is not on this item' );
1522 $recall->set_cancelled;
1524 # biblio-level waiting recall: renewal allowed
1525 $recall = Koha::Recall->new({
1526 biblio_id => $recall_item1->biblionumber,
1528 patron_id => $recall_borrower->borrowernumber,
1529 pickup_library_id => $recall_borrower->branchcode,
1532 $recall->set_waiting({ item => $recall_item1 });
1533 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1534 is( $renewokay, 1, 'Can renew item if biblio-level recall has already been allocated an item' );
1535 $recall->set_cancelled;
1538 subtest "GetUpcomingDueIssues" => sub {
1541 my $branch = $library2->{branchcode};
1543 #Create another record
1544 my $biblio2 = $builder->build_sample_biblio();
1547 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1548 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1549 my $item_3 = $builder->build_sample_item(
1551 biblionumber => $biblio2->biblionumber,
1559 my %a_borrower_data = (
1560 firstname => 'Fridolyn',
1561 surname => 'SOMERS',
1562 categorycode => $patron_category->{categorycode},
1563 branchcode => $branch,
1566 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1567 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1569 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1570 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1571 my $today = DateTime->today(time_zone => C4::Context->tz());
1573 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1574 my $datedue = dt_from_string( $issue->date_due() );
1575 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1576 my $datedue2 = dt_from_string( $issue->date_due() );
1580 # GetUpcomingDueIssues tests
1582 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1583 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1586 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1587 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1588 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1591 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1592 is ( scalar( @$upcoming_dues ), 1,
1593 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1596 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1598 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1600 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1601 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1603 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1604 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1606 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1607 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1609 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1610 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1612 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1613 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1615 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1616 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1620 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1621 my $branch = $library2->{branchcode};
1623 my $biblio = $builder->build_sample_biblio();
1626 my $item = $builder->build_sample_item(
1628 biblionumber => $biblio->biblionumber,
1635 my %a_borrower_data = (
1636 firstname => 'Kyle',
1638 categorycode => $patron_category->{categorycode},
1639 branchcode => $branch,
1642 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1644 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1645 my $issue = AddIssue( $borrower, $item->barcode );
1648 issue_id => $issue->id(),
1649 itemnumber => $item->itemnumber,
1650 borrowernumber => $borrowernumber,
1656 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1657 my $count = $hr->{count};
1659 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1662 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1664 my $biblio = $builder->build_sample_biblio();
1665 my $item_1 = $builder->build_sample_item(
1667 biblionumber => $biblio->biblionumber,
1668 library => $library2->{branchcode},
1671 my $item_2= $builder->build_sample_item(
1673 biblionumber => $biblio->biblionumber,
1674 library => $library2->{branchcode},
1675 itype => $item_1->effective_itemtype,
1679 Koha::CirculationRules->set_rules(
1681 categorycode => undef,
1682 itemtype => $item_1->effective_itemtype,
1683 branchcode => undef,
1685 reservesallowed => 25,
1686 holds_per_record => 25,
1688 lengthunit => 'days',
1689 renewalsallowed => 1,
1691 norenewalbefore => undef,
1701 my $borrowernumber1 = Koha::Patron->new({
1702 firstname => 'Kyle',
1704 categorycode => $patron_category->{categorycode},
1705 branchcode => $library2->{branchcode},
1706 })->store->borrowernumber;
1707 my $borrowernumber2 = Koha::Patron->new({
1708 firstname => 'Chelsea',
1710 categorycode => $patron_category->{categorycode},
1711 branchcode => $library2->{branchcode},
1712 })->store->borrowernumber;
1713 my $patron_category_2 = $builder->build(
1715 source => 'Category',
1717 category_type => 'P',
1719 BlockExpiredPatronOpacActions => -1, # Pick the pref value
1723 my $borrowernumber3 = Koha::Patron->new({
1724 firstname => 'Carnegie',
1726 categorycode => $patron_category_2->{categorycode},
1727 branchcode => $library2->{branchcode},
1728 })->store->borrowernumber;
1730 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1731 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1733 my $issue = AddIssue( $borrower1, $item_1->barcode );
1735 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1736 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1740 branchcode => $library2->{branchcode},
1741 borrowernumber => $borrowernumber2,
1742 biblionumber => $biblio->biblionumber,
1747 Koha::CirculationRules->set_rules(
1749 categorycode => undef,
1750 itemtype => $item_1->effective_itemtype,
1751 branchcode => undef,
1757 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1758 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1759 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1761 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1762 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1763 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1765 Koha::CirculationRules->set_rules(
1767 categorycode => undef,
1768 itemtype => $item_1->effective_itemtype,
1769 branchcode => undef,
1775 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1776 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1777 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1779 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1780 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1781 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1785 branchcode => $library2->{branchcode},
1786 borrowernumber => $borrowernumber3,
1787 biblionumber => $biblio->biblionumber,
1792 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1793 is( $renewokay, 0, 'Verify the borrower cannot renew with 2 holds on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled and one other item on record' );
1795 my $item_3= $builder->build_sample_item(
1797 biblionumber => $biblio->biblionumber,
1798 library => $library2->{branchcode},
1799 itype => $item_1->effective_itemtype,
1803 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1804 is( $renewokay, 1, 'Verify the borrower cannot renew with 2 holds on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled and two other items on record' );
1806 Koha::CirculationRules->set_rules(
1808 categorycode => $patron_category_2->{categorycode},
1809 itemtype => $item_1->effective_itemtype,
1810 branchcode => undef,
1812 reservesallowed => 0,
1817 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1818 is( $renewokay, 0, 'Verify the borrower cannot renew with 2 holds on the record, but only one of those holds can be filled when AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled and two other items on record' );
1820 Koha::CirculationRules->set_rules(
1822 categorycode => $patron_category_2->{categorycode},
1823 itemtype => $item_1->effective_itemtype,
1824 branchcode => undef,
1826 reservesallowed => 25,
1831 # Setting item not checked out to be not for loan but holdable
1832 $item_2->notforloan(-1)->store;
1834 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1835 is( $renewokay, 0, 'Bug 14337 - Verify the borrower can not renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled but the only available item is notforloan' );
1837 my $mock_circ = Test::MockModule->new("C4::Circulation");
1838 $mock_circ->mock( CanItemBeReserved => sub {
1840 return { status => 'no' }
1843 $item_2->notforloan(0)->store;
1845 # Two items total, one item available, one issued, two holds on record
1848 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1849 } [], "CanItemBeReserved not called when there are more possible holds than available items";
1850 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1852 $item_3 = $builder->build_sample_item(
1854 biblionumber => $biblio->biblionumber,
1855 library => $library2->{branchcode},
1856 itype => $item_1->effective_itemtype,
1860 Koha::CirculationRules->set_rules(
1862 categorycode => undef,
1863 itemtype => $item_1->effective_itemtype,
1864 branchcode => undef,
1866 reservesallowed => 0,
1872 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1873 } ["Checked","Checked"], "CanItemBeReserved only called once per available item if it returns a negative result for all items for a borrower";
1874 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1879 # Don't allow renewing onsite checkout
1880 my $branch = $library->{branchcode};
1882 #Create another record
1883 my $biblio = $builder->build_sample_biblio();
1885 my $item = $builder->build_sample_item(
1887 biblionumber => $biblio->biblionumber,
1893 my $borrowernumber = Koha::Patron->new({
1896 categorycode => $patron_category->{categorycode},
1897 branchcode => $branch,
1898 })->store->borrowernumber;
1900 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1902 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1903 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1904 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1905 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1909 my $library = $builder->build({ source => 'Branch' });
1911 my $biblio = $builder->build_sample_biblio();
1913 my $item = $builder->build_sample_item(
1915 biblionumber => $biblio->biblionumber,
1916 library => $library->{branchcode},
1921 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1923 my $issue = AddIssue( $patron, $item->barcode );
1926 issue_id => $issue->id(),
1927 itemnumber => $item->itemnumber,
1928 borrowernumber => $patron->{borrowernumber},
1935 issue_id => $issue->id(),
1936 itemnumber => $item->itemnumber,
1937 borrowernumber => $patron->{borrowernumber},
1942 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1945 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1948 my $homebranch = $builder->build( { source => 'Branch' } );
1949 my $holdingbranch = $builder->build( { source => 'Branch' } );
1950 my $otherbranch = $builder->build( { source => 'Branch' } );
1951 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1952 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1954 my $item = $builder->build_sample_item(
1956 homebranch => $homebranch->{branchcode},
1957 holdingbranch => $holdingbranch->{branchcode},
1960 Koha::CirculationRules->set_rules(
1962 categorycode => undef,
1963 itemtype => $item->effective_itemtype,
1964 branchcode => undef,
1966 reservesallowed => 25,
1968 lengthunit => 'days',
1969 renewalsallowed => 1,
1971 norenewalbefore => undef,
1980 set_userenv($holdingbranch);
1982 my $issue = AddIssue( $patron_1->unblessed, $item->barcode );
1983 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1985 my ( $error, $question, $alerts );
1987 # AllowReturnToBranch == anywhere
1988 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1989 ## Test that unknown barcodes don't generate internal server errors
1990 set_userenv($homebranch);
1991 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1992 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1993 ## Can be issued from homebranch
1994 set_userenv($homebranch);
1995 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1996 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1997 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1998 ## Can be issued from holdingbranch
1999 set_userenv($holdingbranch);
2000 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2001 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2002 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2003 ## Can be issued from another branch
2004 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2005 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2006 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2008 # AllowReturnToBranch == holdingbranch
2009 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2010 ## Cannot be issued from homebranch
2011 set_userenv($homebranch);
2012 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2013 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2014 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2015 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
2016 ## Can be issued from holdinbranch
2017 set_userenv($holdingbranch);
2018 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2019 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2020 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2021 ## Cannot be issued from another branch
2022 set_userenv($otherbranch);
2023 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2024 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2025 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2026 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
2028 # AllowReturnToBranch == homebranch
2029 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2030 ## Can be issued from holdinbranch
2031 set_userenv($homebranch);
2032 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2033 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2034 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2035 ## Cannot be issued from holdinbranch
2036 set_userenv($holdingbranch);
2037 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2038 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2039 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2040 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2041 ## Cannot be issued from holdinbranch
2042 set_userenv($otherbranch);
2043 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2044 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2045 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2046 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2048 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2051 subtest 'AddIssue & AllowReturnToBranch' => sub {
2054 my $homebranch = $builder->build( { source => 'Branch' } );
2055 my $holdingbranch = $builder->build( { source => 'Branch' } );
2056 my $otherbranch = $builder->build( { source => 'Branch' } );
2057 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2058 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2060 my $item = $builder->build_sample_item(
2062 homebranch => $homebranch->{branchcode},
2063 holdingbranch => $holdingbranch->{branchcode},
2067 set_userenv($holdingbranch);
2069 my $ref_issue = 'Koha::Checkout';
2070 my $issue = AddIssue( $patron_1, $item->barcode );
2072 my ( $error, $question, $alerts );
2074 # AllowReturnToBranch == homebranch
2075 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2076 ## Can be issued from homebranch
2077 set_userenv($homebranch);
2078 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
2079 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2080 ## Can be issued from holdinbranch
2081 set_userenv($holdingbranch);
2082 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
2083 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2084 ## Can be issued from another branch
2085 set_userenv($otherbranch);
2086 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
2087 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2089 # AllowReturnToBranch == holdinbranch
2090 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2091 ## Cannot be issued from homebranch
2092 set_userenv($homebranch);
2093 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
2094 ## Can be issued from holdingbranch
2095 set_userenv($holdingbranch);
2096 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
2097 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2098 ## Cannot be issued from another branch
2099 set_userenv($otherbranch);
2100 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
2102 # AllowReturnToBranch == homebranch
2103 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2104 ## Can be issued from homebranch
2105 set_userenv($homebranch);
2106 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
2107 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2108 ## Cannot be issued from holdinbranch
2109 set_userenv($holdingbranch);
2110 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
2111 ## Cannot be issued from another branch
2112 set_userenv($otherbranch);
2113 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
2114 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2117 subtest 'AddIssue | recalls' => sub {
2120 t::lib::Mocks::mock_preference("UseRecalls", 1);
2121 t::lib::Mocks::mock_preference("item-level_itypes", 1);
2122 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2123 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2124 my $item = $builder->build_sample_item;
2125 Koha::CirculationRules->set_rules({
2126 branchcode => undef,
2128 categorycode => undef,
2130 recalls_allowed => 10,
2134 # checking out item that they have recalled
2135 my $recall1 = Koha::Recall->new(
2136 { patron_id => $patron1->borrowernumber,
2137 biblio_id => $item->biblionumber,
2138 item_id => $item->itemnumber,
2140 pickup_library_id => $patron1->branchcode,
2143 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall1->id } );
2144 $recall1 = Koha::Recalls->find( $recall1->id );
2145 is( $recall1->fulfilled, 1, 'Recall was fulfilled when patron checked out item' );
2146 AddReturn( $item->barcode, $item->homebranch );
2148 # this item is has a recall request. cancel recall
2149 my $recall2 = Koha::Recall->new(
2150 { patron_id => $patron2->borrowernumber,
2151 biblio_id => $item->biblionumber,
2152 item_id => $item->itemnumber,
2154 pickup_library_id => $patron2->branchcode,
2157 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall2->id, cancel_recall => 'cancel' } );
2158 $recall2 = Koha::Recalls->find( $recall2->id );
2159 is( $recall2->cancelled, 1, 'Recall was cancelled when patron checked out item' );
2160 AddReturn( $item->barcode, $item->homebranch );
2162 # this item is waiting to fulfill a recall. revert recall
2163 my $recall3 = Koha::Recall->new(
2164 { patron_id => $patron2->borrowernumber,
2165 biblio_id => $item->biblionumber,
2166 item_id => $item->itemnumber,
2168 pickup_library_id => $patron2->branchcode,
2171 $recall3->set_waiting;
2172 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall3->id, cancel_recall => 'revert' } );
2173 $recall3 = Koha::Recalls->find( $recall3->id );
2174 is( $recall3->requested, 1, 'Recall was reverted from waiting when patron checked out item' );
2175 AddReturn( $item->barcode, $item->homebranch );
2178 subtest 'AddIssue & illrequests.due_date' => sub {
2181 t::lib::Mocks::mock_preference( 'ILLModule', 1 );
2182 my $library = $builder->build( { source => 'Branch' } );
2183 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2184 my $item = $builder->build_sample_item();
2186 set_userenv($library);
2188 my $custom_date_due = '9999-12-18 12:34:56';
2189 my $expected_date_due = '9999-12-18 23:59:00';
2190 my $illrequest = Koha::Illrequest->new({
2191 borrowernumber => $patron->borrowernumber,
2192 biblio_id => $item->biblionumber,
2193 branchcode => $library->{'branchcode'},
2194 due_date => $custom_date_due,
2197 my $issue = AddIssue( $patron->unblessed, $item->barcode );
2198 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2200 $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2201 $item = $builder->build_sample_item();
2202 $custom_date_due = '9999-12-19';
2203 $expected_date_due = '9999-12-19 23:59:00';
2204 $illrequest = Koha::Illrequest->new({
2205 borrowernumber => $patron->borrowernumber,
2206 biblio_id => $item->biblionumber,
2207 branchcode => $library->{'branchcode'},
2208 due_date => $custom_date_due,
2211 $issue = AddIssue( $patron->unblessed, $item->barcode );
2212 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2215 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
2218 my $library = $builder->build( { source => 'Branch' } );
2219 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2220 my $item_1 = $builder->build_sample_item(
2222 library => $library->{branchcode},
2225 my $item_2 = $builder->build_sample_item(
2227 library => $library->{branchcode},
2230 Koha::CirculationRules->set_rules(
2232 categorycode => undef,
2234 branchcode => $library->{branchcode},
2236 reservesallowed => 25,
2238 lengthunit => 'days',
2239 renewalsallowed => 1,
2241 norenewalbefore => undef,
2251 my ( $error, $question, $alerts );
2253 # Patron cannot issue item_1, they have overdues
2254 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
2255 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, $yesterday ); # Add an overdue
2257 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
2258 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2259 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
2260 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
2262 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
2263 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2264 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2265 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
2267 # Patron cannot issue item_1, they are debarred
2268 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
2269 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
2270 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2271 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2272 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
2274 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
2275 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2276 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2277 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
2280 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
2283 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2284 my $patron_category_x = $builder->build_object(
2286 class => 'Koha::Patron::Categories',
2287 value => { category_type => 'X' }
2290 my $patron = $builder->build_object(
2292 class => 'Koha::Patrons',
2294 categorycode => $patron_category_x->categorycode,
2295 gonenoaddress => undef,
2302 my $item_1 = $builder->build_sample_item(
2304 library => $library->{branchcode},
2308 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
2309 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
2311 # TODO There are other tests to provide here
2314 subtest 'MultipleReserves' => sub {
2317 my $biblio = $builder->build_sample_biblio();
2319 my $branch = $library2->{branchcode};
2321 my $item_1 = $builder->build_sample_item(
2323 biblionumber => $biblio->biblionumber,
2325 replacementprice => 12.00,
2330 my $item_2 = $builder->build_sample_item(
2332 biblionumber => $biblio->biblionumber,
2334 replacementprice => 12.00,
2341 my $resdate = undef;
2342 my $expdate = undef;
2344 my $checkitem = undef;
2347 my %renewing_borrower_data = (
2348 firstname => 'John',
2349 surname => 'Renewal',
2350 categorycode => $patron_category->{categorycode},
2351 branchcode => $branch,
2353 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
2354 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
2355 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
2356 my $datedue = dt_from_string( $issue->date_due() );
2357 is (defined $issue->date_due(), 1, "item 1 checked out");
2358 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
2360 my %reserving_borrower_data1 = (
2361 firstname => 'Katrin',
2362 surname => 'Reservation',
2363 categorycode => $patron_category->{categorycode},
2364 branchcode => $branch,
2366 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
2369 branchcode => $branch,
2370 borrowernumber => $reserving_borrowernumber1,
2371 biblionumber => $biblio->biblionumber,
2372 priority => $priority,
2373 reservation_date => $resdate,
2374 expiration_date => $expdate,
2376 itemnumber => $checkitem,
2381 my %reserving_borrower_data2 = (
2382 firstname => 'Kirk',
2383 surname => 'Reservation',
2384 categorycode => $patron_category->{categorycode},
2385 branchcode => $branch,
2387 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
2390 branchcode => $branch,
2391 borrowernumber => $reserving_borrowernumber2,
2392 biblionumber => $biblio->biblionumber,
2393 priority => $priority,
2394 reservation_date => $resdate,
2395 expiration_date => $expdate,
2397 itemnumber => $checkitem,
2403 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2404 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2407 my $item_3 = $builder->build_sample_item(
2409 biblionumber => $biblio->biblionumber,
2411 replacementprice => 12.00,
2417 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2418 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2422 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2425 my $library = $builder->build( { source => 'Branch' } );
2426 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2428 my $biblionumber = $builder->build_sample_biblio(
2430 branchcode => $library->{branchcode},
2433 my $item_1 = $builder->build_sample_item(
2435 biblionumber => $biblionumber,
2436 library => $library->{branchcode},
2440 my $item_2 = $builder->build_sample_item(
2442 biblionumber => $biblionumber,
2443 library => $library->{branchcode},
2447 Koha::CirculationRules->set_rules(
2449 categorycode => undef,
2451 branchcode => $library->{branchcode},
2453 reservesallowed => 25,
2455 lengthunit => 'days',
2456 renewalsallowed => 1,
2458 norenewalbefore => undef,
2467 my ( $error, $question, $alerts );
2468 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, dt_from_string->add( days => 1 ) );
2470 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2471 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2473 { error => $error, alerts => $alerts },
2474 { error => {}, alerts => {} },
2475 'No error or alert should be raised'
2477 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2479 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2480 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2482 { error => $error, question => $question, alerts => $alerts },
2483 { error => {}, question => {}, alerts => {} },
2484 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2487 # Add a subscription
2488 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2490 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2491 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2493 { error => $error, question => $question, alerts => $alerts },
2494 { error => {}, question => {}, alerts => {} },
2495 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2498 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2499 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2501 { error => $error, question => $question, alerts => $alerts },
2502 { error => {}, question => {}, alerts => {} },
2503 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2507 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2510 my $library = $builder->build( { source => 'Branch' } );
2511 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2514 my $biblionumber = $builder->build_sample_biblio(
2516 branchcode => $library->{branchcode},
2519 my $item_1 = $builder->build_sample_item(
2521 biblionumber => $biblionumber,
2522 library => $library->{branchcode},
2525 my $item_2 = $builder->build_sample_item(
2527 biblionumber => $biblionumber,
2528 library => $library->{branchcode},
2532 # And the circulation rule
2533 Koha::CirculationRules->search->delete;
2534 Koha::CirculationRules->set_rules(
2536 categorycode => undef,
2538 branchcode => undef,
2541 firstremind => 1, # 1 day of grace
2542 finedays => 2, # 2 days of fine per day of overdue
2543 lengthunit => 'days',
2548 # Patron cannot issue item_1, they have overdues
2549 my $now = dt_from_string;
2550 my $five_days_ago = $now->clone->subtract( days => 5 );
2551 my $ten_days_ago = $now->clone->subtract( days => 10 );
2552 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2553 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2554 ; # Add another overdue
2556 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2557 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2558 my $debarments = Koha::Patron::Debarments::GetDebarments(
2559 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2560 is( scalar(@$debarments), 1 );
2562 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2563 # Same for the others
2564 my $expected_expiration = output_pref(
2566 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2567 dateformat => 'sql',
2571 is( $debarments->[0]->{expiration}, $expected_expiration );
2573 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2574 $debarments = Koha::Patron::Debarments::GetDebarments(
2575 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2576 is( scalar(@$debarments), 1 );
2577 $expected_expiration = output_pref(
2579 dt => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2580 dateformat => 'sql',
2584 is( $debarments->[0]->{expiration}, $expected_expiration );
2586 Koha::Patron::Debarments::DelUniqueDebarment(
2587 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2589 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2590 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2591 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2592 ; # Add another overdue
2593 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2594 $debarments = Koha::Patron::Debarments::GetDebarments(
2595 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2596 is( scalar(@$debarments), 1 );
2597 $expected_expiration = output_pref(
2599 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2600 dateformat => 'sql',
2604 is( $debarments->[0]->{expiration}, $expected_expiration );
2606 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2607 $debarments = Koha::Patron::Debarments::GetDebarments(
2608 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2609 is( scalar(@$debarments), 1 );
2610 $expected_expiration = output_pref(
2612 dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2613 dateformat => 'sql',
2617 is( $debarments->[0]->{expiration}, $expected_expiration );
2620 subtest 'AddReturn + suspension_chargeperiod' => sub {
2623 my $library = $builder->build( { source => 'Branch' } );
2624 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2626 my $biblionumber = $builder->build_sample_biblio(
2628 branchcode => $library->{branchcode},
2631 my $item_1 = $builder->build_sample_item(
2633 biblionumber => $biblionumber,
2634 library => $library->{branchcode},
2638 # And the issuing rule
2639 Koha::CirculationRules->search->delete;
2640 Koha::CirculationRules->set_rules(
2642 categorycode => '*',
2647 firstremind => 0, # 0 day of grace
2648 finedays => 2, # 2 days of fine per day of overdue
2649 suspension_chargeperiod => 1,
2650 lengthunit => 'days',
2655 my $now = dt_from_string;
2656 my $five_days_ago = $now->clone->subtract( days => 5 );
2657 # We want to charge 2 days every day, without grace
2658 # With 5 days of overdue: 5 * Z
2659 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2660 test_debarment_on_checkout(
2663 library => $library,
2665 due_date => $five_days_ago,
2666 expiration_date => $expected_expiration,
2670 # Same with undef firstremind
2671 Koha::CirculationRules->search->delete;
2672 Koha::CirculationRules->set_rules(
2674 categorycode => '*',
2679 firstremind => undef, # 0 day of grace
2680 finedays => 2, # 2 days of fine per day of overdue
2681 suspension_chargeperiod => 1,
2682 lengthunit => 'days',
2687 my $now = dt_from_string;
2688 my $five_days_ago = $now->clone->subtract( days => 5 );
2689 # We want to charge 2 days every day, without grace
2690 # With 5 days of overdue: 5 * Z
2691 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2692 test_debarment_on_checkout(
2695 library => $library,
2697 due_date => $five_days_ago,
2698 expiration_date => $expected_expiration,
2702 # We want to charge 2 days every 2 days, without grace
2703 # With 5 days of overdue: (5 * 2) / 2
2704 Koha::CirculationRules->set_rule(
2706 categorycode => undef,
2707 branchcode => undef,
2709 rule_name => 'suspension_chargeperiod',
2714 $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2715 test_debarment_on_checkout(
2718 library => $library,
2720 due_date => $five_days_ago,
2721 expiration_date => $expected_expiration,
2725 # We want to charge 2 days every 3 days, with 1 day of grace
2726 # With 5 days of overdue: ((5-1) / 3 ) * 2
2727 Koha::CirculationRules->set_rules(
2729 categorycode => undef,
2730 branchcode => undef,
2733 suspension_chargeperiod => 3,
2738 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2739 test_debarment_on_checkout(
2742 library => $library,
2744 due_date => $five_days_ago,
2745 expiration_date => $expected_expiration,
2749 # Use finesCalendar to know if holiday must be skipped to calculate the due date
2750 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2751 Koha::CirculationRules->set_rules(
2753 categorycode => undef,
2754 branchcode => undef,
2758 suspension_chargeperiod => 1,
2763 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2764 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2766 # Adding a holiday 2 days ago
2767 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2768 my $two_days_ago = $now->clone->subtract( days => 2 );
2769 $calendar->insert_single_holiday(
2770 day => $two_days_ago->day,
2771 month => $two_days_ago->month,
2772 year => $two_days_ago->year,
2773 title => 'holidayTest-2d',
2774 description => 'holidayDesc 2 days ago'
2776 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2777 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2778 test_debarment_on_checkout(
2781 library => $library,
2783 due_date => $five_days_ago,
2784 expiration_date => $expected_expiration,
2788 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2789 my $two_days_ahead = $now->clone->add( days => 2 );
2790 $calendar->insert_single_holiday(
2791 day => $two_days_ahead->day,
2792 month => $two_days_ahead->month,
2793 year => $two_days_ahead->year,
2794 title => 'holidayTest+2d',
2795 description => 'holidayDesc 2 days ahead'
2798 # Same as above, but we should skip D+2
2799 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2800 test_debarment_on_checkout(
2803 library => $library,
2805 due_date => $five_days_ago,
2806 expiration_date => $expected_expiration,
2810 # Adding another holiday, day of expiration date
2811 my $expected_expiration_dt = dt_from_string($expected_expiration);
2812 $calendar->insert_single_holiday(
2813 day => $expected_expiration_dt->day,
2814 month => $expected_expiration_dt->month,
2815 year => $expected_expiration_dt->year,
2816 title => 'holidayTest_exp',
2817 description => 'holidayDesc on expiration date'
2819 # Expiration date will be the day after
2820 test_debarment_on_checkout(
2823 library => $library,
2825 due_date => $five_days_ago,
2826 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2830 test_debarment_on_checkout(
2833 library => $library,
2835 return_date => $now->clone->add(days => 5),
2836 expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2840 test_debarment_on_checkout(
2843 library => $library,
2845 due_date => $now->clone->add(days => 1),
2846 return_date => $now->clone->add(days => 5),
2847 expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2853 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2856 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2857 my $patron1 = $builder->build_object(
2859 class => 'Koha::Patrons',
2861 library => $library->branchcode,
2862 categorycode => $patron_category->{categorycode}
2866 my $patron2 = $builder->build_object(
2868 class => 'Koha::Patrons',
2870 library => $library->branchcode,
2871 categorycode => $patron_category->{categorycode}
2876 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2878 my $item = $builder->build_sample_item(
2880 library => $library->branchcode,
2884 my ( $error, $question, $alerts );
2885 my $issue = AddIssue( $patron1->unblessed, $item->barcode );
2887 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2888 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2889 is( $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER question flag should be set if AutoReturnCheckedOutItems is disabled and item is checked out to another' );
2891 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2892 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2893 is( $alerts->{RETURNED_FROM_ANOTHER}->{patron}->borrowernumber, $patron1->borrowernumber, 'RETURNED_FROM_ANOTHER alert flag should be set if AutoReturnCheckedOutItems is enabled and item is checked out to another' );
2895 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2899 subtest 'AddReturn | is_overdue' => sub {
2902 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2903 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2904 t::lib::Mocks::mock_preference('finesMode', 'production');
2905 t::lib::Mocks::mock_preference('MaxFine', '100');
2907 my $library = $builder->build( { source => 'Branch' } );
2908 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2909 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2910 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2912 my $item = $builder->build_sample_item(
2914 library => $library->{branchcode},
2915 replacementprice => 7
2919 Koha::CirculationRules->search->delete;
2920 Koha::CirculationRules->set_rules(
2922 categorycode => undef,
2924 branchcode => undef,
2927 lengthunit => 'days',
2928 fine => 1, # Charge 1 every day of overdue
2934 my $now = dt_from_string;
2935 my $one_day_ago = $now->clone->subtract( days => 1 );
2936 my $two_days_ago = $now->clone->subtract( days => 2 );
2937 my $five_days_ago = $now->clone->subtract( days => 5 );
2938 my $ten_days_ago = $now->clone->subtract( days => 10 );
2939 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2941 # No return date specified, today will be used => 10 days overdue charged
2942 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2943 AddReturn( $item->barcode, $library->{branchcode} );
2944 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2945 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2947 # specify return date 5 days before => no overdue charged
2948 AddIssue( $patron->unblessed, $item->barcode, $five_days_ago ); # date due was 5d ago
2949 AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
2950 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2951 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2953 # specify return date 5 days later => 5 days overdue charged
2954 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2955 AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
2956 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2957 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2959 # specify return date 5 days later, specify exemptfine => no overdue charge
2960 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2961 AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago );
2962 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2963 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2965 subtest 'bug 22877 | Lost item return' => sub {
2969 my $issue = AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2971 # Fake fines cronjob on this checkout
2973 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2974 $ten_days_ago, $now );
2977 issue_id => $issue->issue_id,
2978 itemnumber => $item->itemnumber,
2979 borrowernumber => $patron->borrowernumber,
2981 due => output_pref($ten_days_ago)
2984 is( int( $patron->account->balance() ),
2985 10, "Overdue fine of 10 days overdue" );
2987 # Fake longoverdue with charge and not marking returned
2988 LostItem( $item->itemnumber, 'cronjob', 0 );
2989 is( int( $patron->account->balance() ),
2990 17, "Lost fine of 7 plus 10 days overdue" );
2992 # Now we return it today
2993 AddReturn( $item->barcode, $library->{branchcode} );
2994 is( int( $patron->account->balance() ),
2995 17, "Should have a single 10 days overdue fine and lost charge" );
2998 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3001 subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
3005 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3007 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
3009 # Fake fines cronjob on this checkout
3011 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3012 $one_day_ago, $now );
3015 issue_id => $issue->issue_id,
3016 itemnumber => $item->itemnumber,
3017 borrowernumber => $patron->borrowernumber,
3019 due => output_pref($one_day_ago)
3022 is( int( $patron->account->balance() ),
3023 1, "Overdue fine of 1 day overdue" );
3025 # Backdated return (dropbox mode example - charge should be removed)
3026 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3027 is( int( $patron->account->balance() ),
3028 0, "Overdue fine should be annulled" );
3029 my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3030 is( $lines->count, 0, "Overdue fine accountline has been removed");
3032 $issue = AddIssue( $patron->unblessed, $item->barcode, $two_days_ago ); # date due was 2d ago
3034 # Fake fines cronjob on this checkout
3036 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3037 $two_days_ago, $now );
3040 issue_id => $issue->issue_id,
3041 itemnumber => $item->itemnumber,
3042 borrowernumber => $patron->borrowernumber,
3044 due => output_pref($one_day_ago)
3047 is( int( $patron->account->balance() ),
3048 2, "Overdue fine of 2 days overdue" );
3050 # Payment made against fine
3051 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3052 my $debit = $lines->next;
3053 my $credit = $patron->account->add_credit(
3057 interface => 'test',
3060 $credit->apply( { debits => [$debit] } );
3062 is( int( $patron->account->balance() ),
3063 0, "Overdue fine should be paid off" );
3064 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3065 is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
3066 my $line = $lines->next;
3067 is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
3068 is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
3070 # Backdated return (dropbox mode example - charge should be removed)
3071 AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
3072 is( int( $patron->account->balance() ),
3073 -1, "Refund credit has been applied" );
3074 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
3075 is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
3077 $line = $lines->next;
3078 is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
3079 is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
3080 is($line->status,'RETURNED', "Overdue fine is fixed");
3081 $line = $lines->next;
3082 is($line->amount+0,-2, "Original payment amount remains as 2");
3083 is($line->amountoutstanding+0,0, "Original payment remains applied");
3084 $line = $lines->next;
3085 is($line->amount+0,-1, "Refund amount correctly set to 1");
3086 is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
3089 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3092 subtest 'bug 25417 | backdated return + exemptfine' => sub {
3096 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3098 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
3100 # Fake fines cronjob on this checkout
3102 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3103 $one_day_ago, $now );
3106 issue_id => $issue->issue_id,
3107 itemnumber => $item->itemnumber,
3108 borrowernumber => $patron->borrowernumber,
3110 due => output_pref($one_day_ago)
3113 is( int( $patron->account->balance() ),
3114 1, "Overdue fine of 1 day overdue" );
3116 # Backdated return (dropbox mode example - charge should no longer exist)
3117 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3118 is( int( $patron->account->balance() ),
3119 0, "Overdue fine should be annulled" );
3122 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3125 subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
3128 t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
3130 my $due_date = dt_from_string;
3131 my $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
3136 issue_id => $issue->issue_id,
3137 itemnumber => $item->itemnumber,
3138 borrowernumber => $patron->borrowernumber,
3140 due => output_pref($due_date)
3143 is( $patron->account->balance(),
3144 0.25, 'Overdue fine of $0.25 recorded' );
3146 # Backdate return to exact due date and time
3147 my ( undef, $message ) =
3148 AddReturn( $item->barcode, $library->{branchcode},
3152 Koha::Account::Lines->find( { issue_id => $issue->id } );
3153 ok( !$accountline, 'accountline removed as expected' );
3156 $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
3161 issue_id => $issue->issue_id,
3162 itemnumber => $item->itemnumber,
3163 borrowernumber => $patron->borrowernumber,
3165 due => output_pref($due_date)
3168 is( $patron->account->balance(),
3169 0.25, 'Overdue fine of $0.25 recorded' );
3171 # Partial pay accruing fine
3172 my $lines = Koha::Account::Lines->search(
3174 borrowernumber => $patron->borrowernumber,
3175 issue_id => $issue->id
3178 my $debit = $lines->next;
3179 my $credit = $patron->account->add_credit(
3183 interface => 'test',
3186 $credit->apply( { debits => [$debit] } );
3188 is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
3190 # Backdate return to exact due date and time
3191 ( undef, $message ) =
3192 AddReturn( $item->barcode, $library->{branchcode},
3195 $lines = Koha::Account::Lines->search(
3197 borrowernumber => $patron->borrowernumber,
3198 issue_id => $issue->id
3201 $accountline = $lines->next;
3202 is( $accountline->amountoutstanding + 0,
3203 0, 'Partially paid fee amount outstanding was reduced to 0' );
3204 is( $accountline->amount + 0,
3205 0, 'Partially paid fee amount was reduced to 0' );
3206 is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
3209 Koha::Account::Lines->search(
3210 { borrowernumber => $patron->borrowernumber } )->delete;
3213 subtest 'enh 23091 | Lost item return policies' => sub {
3216 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3218 my $branchcode_false =
3219 $builder->build( { source => 'Branch' } )->{branchcode};
3220 my $specific_rule_false = $builder->build(
3222 source => 'CirculationRule',
3224 branchcode => $branchcode_false,
3225 categorycode => undef,
3227 rule_name => 'lostreturn',
3232 my $branchcode_refund =
3233 $builder->build( { source => 'Branch' } )->{branchcode};
3234 my $specific_rule_refund = $builder->build(
3236 source => 'CirculationRule',
3238 branchcode => $branchcode_refund,
3239 categorycode => undef,
3241 rule_name => 'lostreturn',
3242 rule_value => 'refund'
3246 my $branchcode_restore =
3247 $builder->build( { source => 'Branch' } )->{branchcode};
3248 my $specific_rule_restore = $builder->build(
3250 source => 'CirculationRule',
3252 branchcode => $branchcode_restore,
3253 categorycode => undef,
3255 rule_name => 'lostreturn',
3256 rule_value => 'restore'
3260 my $branchcode_charge =
3261 $builder->build( { source => 'Branch' } )->{branchcode};
3262 my $specific_rule_charge = $builder->build(
3264 source => 'CirculationRule',
3266 branchcode => $branchcode_charge,
3267 categorycode => undef,
3269 rule_name => 'lostreturn',
3270 rule_value => 'charge'
3275 my $branchcode_refund_unpaid =
3276 $builder->build( { source => 'Branch' } )->{branchcode};
3277 my $specific_rule_refund_unpaid = $builder->build(
3279 source => 'CirculationRule',
3281 branchcode => $branchcode_refund_unpaid,
3282 categorycode => undef,
3284 rule_name => 'lostreturn',
3285 rule_value => 'refund_unpaid'
3290 my $replacement_amount = 99.00;
3291 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
3292 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
3293 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
3294 t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 );
3295 t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
3297 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
3300 subtest 'lostreturn | refund_unpaid' => sub {
3303 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund_unpaid });
3305 my $item = $builder->build_sample_item(
3307 replacementprice => $replacement_amount
3312 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode );
3315 $item->itemlost(3)->store;
3316 C4::Circulation::LostItem( $item->itemnumber, 1 );
3318 my $lost_fee_lines = Koha::Account::Lines->search(
3320 borrowernumber => $patron->id,
3321 itemnumber => $item->itemnumber,
3322 debit_type_code => 'LOST'
3325 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3326 my $lost_fee_line = $lost_fee_lines->next;
3327 is( int($lost_fee_line->amount),
3328 $replacement_amount, 'The right LOST amount is generated' );
3329 is( int($lost_fee_line->amountoutstanding),
3330 $replacement_amount,
3331 'The right LOST amountoutstanding is generated' );
3332 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3335 int($patron->account->balance),
3336 $replacement_amount ,
3337 "Account balance equals the replacement amount after being charged lost fee when no payments has been made"
3340 # Return lost item without any payments having been made
3341 my ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3343 $lost_fee_line->discard_changes;
3345 is( int($lost_fee_line->amount), $replacement_amount, 'The LOST amount is left intact' );
3346 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero' );
3347 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set' );
3349 int($patron->account->balance),
3351 'Account balance should be zero after returning item with lost fee when no payments has been made'
3354 # Create a second item
3355 $item = $builder->build_sample_item(
3357 replacementprice => $replacement_amount
3362 $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode );
3365 $item->itemlost(3)->store;
3366 C4::Circulation::LostItem( $item->itemnumber, 1 );
3368 $lost_fee_lines = Koha::Account::Lines->search(
3370 borrowernumber => $patron->id,
3371 itemnumber => $item->itemnumber,
3372 debit_type_code => 'LOST'
3375 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3376 $lost_fee_line = $lost_fee_lines->next;
3378 # Make partial payment
3379 $patron->account->payin_amount({
3381 interface => 'intranet',
3382 payment_type => 'CASH',
3383 user_id => $patron->borrowernumber,
3385 debits => [$lost_fee_line]
3388 $lost_fee_line->discard_changes;
3390 is( int($lost_fee_line->amountoutstanding),
3392 'The LOST amountoutstanding is the expected amount after partial payment of lost fee'
3396 int($patron->account->balance),
3398 'Account balance is the expected amount after partial payment of lost fee'
3401 # Return lost item with partial payment having been made
3402 ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3404 $lost_fee_line->discard_changes;
3406 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero after returning lost item with partial payment' );
3407 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set for lost item with partial payment' );
3409 int($patron->account->balance),
3411 'Account balance should be zero after returning item with lost fee when partial payment has been made'
3414 # Create a third item
3415 $item = $builder->build_sample_item(
3417 replacementprice => $replacement_amount
3422 $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode );
3425 $item->itemlost(3)->store;
3426 C4::Circulation::LostItem( $item->itemnumber, 1 );
3428 $lost_fee_lines = Koha::Account::Lines->search(
3430 borrowernumber => $patron->id,
3431 itemnumber => $item->itemnumber,
3432 debit_type_code => 'LOST'
3435 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3436 $lost_fee_line = $lost_fee_lines->next;
3439 $patron->account->payin_amount({
3441 interface => 'intranet',
3442 payment_type => 'CASH',
3443 user_id => $patron->borrowernumber,
3444 amount => $replacement_amount,
3445 debits => [$lost_fee_line]
3448 $lost_fee_line->discard_changes;
3450 is( int($lost_fee_line->amountoutstanding),
3452 'The LOST amountoutstanding is the expected amount after partial payment of lost fee'
3456 int($patron->account->balance),
3458 'Account balance is the expected amount after partial payment of lost fee'
3461 # Return lost item with partial payment having been made
3462 ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3464 $lost_fee_line->discard_changes;
3466 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero after returning lost item with full payment' );
3467 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set for lost item with partial payment' );
3469 int($patron->account->balance),
3471 'Account balance should be zero after returning item with lost fee when full payment has been made'
3475 subtest 'lostreturn | false' => sub {
3478 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
3480 my $item = $builder->build_sample_item(
3482 replacementprice => $replacement_amount
3487 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3489 # Fake fines cronjob on this checkout
3491 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3492 $ten_days_ago, $now );
3495 issue_id => $issue->issue_id,
3496 itemnumber => $item->itemnumber,
3497 borrowernumber => $patron->borrowernumber,
3499 due => output_pref($ten_days_ago)
3502 my $overdue_fees = Koha::Account::Lines->search(
3504 borrowernumber => $patron->id,
3505 itemnumber => $item->itemnumber,
3506 debit_type_code => 'OVERDUE'
3509 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3510 my $overdue_fee = $overdue_fees->next;
3511 is( $overdue_fee->amount + 0,
3512 10, 'The right OVERDUE amount is generated' );
3513 is( $overdue_fee->amountoutstanding + 0,
3515 'The right OVERDUE amountoutstanding is generated' );
3517 # Simulate item marked as lost
3518 $item->itemlost(3)->store;
3519 C4::Circulation::LostItem( $item->itemnumber, 1 );
3521 my $lost_fee_lines = Koha::Account::Lines->search(
3523 borrowernumber => $patron->id,
3524 itemnumber => $item->itemnumber,
3525 debit_type_code => 'LOST'
3528 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3529 my $lost_fee_line = $lost_fee_lines->next;
3530 is( $lost_fee_line->amount + 0,
3531 $replacement_amount, 'The right LOST amount is generated' );
3532 is( $lost_fee_line->amountoutstanding + 0,
3533 $replacement_amount,
3534 'The right LOST amountoutstanding is generated' );
3535 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3538 my ( $returned, $message ) =
3539 AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
3541 $overdue_fee->discard_changes;
3542 is( $overdue_fee->amount + 0,
3543 10, 'The OVERDUE amount is left intact' );
3544 is( $overdue_fee->amountoutstanding + 0,
3546 'The OVERDUE amountoutstanding is left intact' );
3548 $lost_fee_line->discard_changes;
3549 is( $lost_fee_line->amount + 0,
3550 $replacement_amount, 'The LOST amount is left intact' );
3551 is( $lost_fee_line->amountoutstanding + 0,
3552 $replacement_amount,
3553 'The LOST amountoutstanding is left intact' );
3554 # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
3555 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3558 subtest 'lostreturn | refund' => sub {
3561 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
3563 my $item = $builder->build_sample_item(
3565 replacementprice => $replacement_amount
3570 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3572 # Fake fines cronjob on this checkout
3574 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3575 $ten_days_ago, $now );
3578 issue_id => $issue->issue_id,
3579 itemnumber => $item->itemnumber,
3580 borrowernumber => $patron->borrowernumber,
3582 due => output_pref($ten_days_ago)
3585 my $overdue_fees = Koha::Account::Lines->search(
3587 borrowernumber => $patron->id,
3588 itemnumber => $item->itemnumber,
3589 debit_type_code => 'OVERDUE'
3592 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3593 my $overdue_fee = $overdue_fees->next;
3594 is( $overdue_fee->amount + 0,
3595 10, 'The right OVERDUE amount is generated' );
3596 is( $overdue_fee->amountoutstanding + 0,
3598 'The right OVERDUE amountoutstanding is generated' );
3600 # Simulate item marked as lost
3601 $item->itemlost(3)->store;
3602 C4::Circulation::LostItem( $item->itemnumber, 1 );
3604 my $lost_fee_lines = Koha::Account::Lines->search(
3606 borrowernumber => $patron->id,
3607 itemnumber => $item->itemnumber,
3608 debit_type_code => 'LOST'
3611 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3612 my $lost_fee_line = $lost_fee_lines->next;
3613 is( $lost_fee_line->amount + 0,
3614 $replacement_amount, 'The right LOST amount is generated' );
3615 is( $lost_fee_line->amountoutstanding + 0,
3616 $replacement_amount,
3617 'The right LOST amountoutstanding is generated' );
3618 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3620 # Return the lost item
3621 my ( undef, $message ) =
3622 AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
3624 $overdue_fee->discard_changes;
3625 is( $overdue_fee->amount + 0,
3626 10, 'The OVERDUE amount is left intact' );
3627 is( $overdue_fee->amountoutstanding + 0,
3629 'The OVERDUE amountoutstanding is left intact' );
3631 $lost_fee_line->discard_changes;
3632 is( $lost_fee_line->amount + 0,
3633 $replacement_amount, 'The LOST amount is left intact' );
3634 is( $lost_fee_line->amountoutstanding + 0,
3636 'The LOST amountoutstanding is refunded' );
3637 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3640 subtest 'lostreturn | restore' => sub {
3643 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
3645 my $item = $builder->build_sample_item(
3647 replacementprice => $replacement_amount
3652 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode , $ten_days_ago);
3654 # Fake fines cronjob on this checkout
3656 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3657 $ten_days_ago, $now );
3660 issue_id => $issue->issue_id,
3661 itemnumber => $item->itemnumber,
3662 borrowernumber => $patron->borrowernumber,
3664 due => output_pref($ten_days_ago)
3667 my $overdue_fees = Koha::Account::Lines->search(
3669 borrowernumber => $patron->id,
3670 itemnumber => $item->itemnumber,
3671 debit_type_code => 'OVERDUE'
3674 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3675 my $overdue_fee = $overdue_fees->next;
3676 is( $overdue_fee->amount + 0,
3677 10, 'The right OVERDUE amount is generated' );
3678 is( $overdue_fee->amountoutstanding + 0,
3680 'The right OVERDUE amountoutstanding is generated' );
3682 # Simulate item marked as lost
3683 $item->itemlost(3)->store;
3684 C4::Circulation::LostItem( $item->itemnumber, 1 );
3686 my $lost_fee_lines = Koha::Account::Lines->search(
3688 borrowernumber => $patron->id,
3689 itemnumber => $item->itemnumber,
3690 debit_type_code => 'LOST'
3693 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3694 my $lost_fee_line = $lost_fee_lines->next;
3695 is( $lost_fee_line->amount + 0,
3696 $replacement_amount, 'The right LOST amount is generated' );
3697 is( $lost_fee_line->amountoutstanding + 0,
3698 $replacement_amount,
3699 'The right LOST amountoutstanding is generated' );
3700 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3702 # Simulate refunding overdue fees upon marking item as lost
3703 my $overdue_forgive = $patron->account->add_credit(
3706 user_id => $manager->borrowernumber,
3707 library_id => $branchcode_restore,
3708 interface => 'test',
3710 item_id => $item->itemnumber
3713 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3714 $overdue_fee->discard_changes;
3715 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3718 my ( undef, $message ) =
3719 AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
3721 $overdue_fee->discard_changes;
3722 is( $overdue_fee->amount + 0,
3723 10, 'The OVERDUE amount is left intact' );
3724 is( $overdue_fee->amountoutstanding + 0,
3726 'The OVERDUE amountoutstanding is restored' );
3728 $lost_fee_line->discard_changes;
3729 is( $lost_fee_line->amount + 0,
3730 $replacement_amount, 'The LOST amount is left intact' );
3731 is( $lost_fee_line->amountoutstanding + 0,
3733 'The LOST amountoutstanding is refunded' );
3734 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3737 subtest 'lostreturn | charge' => sub {
3740 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
3742 my $item = $builder->build_sample_item(
3744 replacementprice => $replacement_amount
3749 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3751 # Fake fines cronjob on this checkout
3753 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3754 $ten_days_ago, $now );
3757 issue_id => $issue->issue_id,
3758 itemnumber => $item->itemnumber,
3759 borrowernumber => $patron->borrowernumber,
3761 due => output_pref($ten_days_ago)
3764 my $overdue_fees = Koha::Account::Lines->search(
3766 borrowernumber => $patron->id,
3767 itemnumber => $item->itemnumber,
3768 debit_type_code => 'OVERDUE'
3771 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3772 my $overdue_fee = $overdue_fees->next;
3773 is( $overdue_fee->amount + 0,
3774 10, 'The right OVERDUE amount is generated' );
3775 is( $overdue_fee->amountoutstanding + 0,
3777 'The right OVERDUE amountoutstanding is generated' );
3779 # Simulate item marked as lost
3780 $item->itemlost(3)->store;
3781 C4::Circulation::LostItem( $item->itemnumber, 1 );
3783 my $lost_fee_lines = Koha::Account::Lines->search(
3785 borrowernumber => $patron->id,
3786 itemnumber => $item->itemnumber,
3787 debit_type_code => 'LOST'
3790 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3791 my $lost_fee_line = $lost_fee_lines->next;
3792 is( $lost_fee_line->amount + 0,
3793 $replacement_amount, 'The right LOST amount is generated' );
3794 is( $lost_fee_line->amountoutstanding + 0,
3795 $replacement_amount,
3796 'The right LOST amountoutstanding is generated' );
3797 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3799 # Simulate refunding overdue fees upon marking item as lost
3800 my $overdue_forgive = $patron->account->add_credit(
3803 user_id => $manager->borrowernumber,
3804 library_id => $branchcode_charge,
3805 interface => 'test',
3807 item_id => $item->itemnumber
3810 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3811 $overdue_fee->discard_changes;
3812 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3815 my ( undef, $message ) =
3816 AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
3818 $lost_fee_line->discard_changes;
3819 is( $lost_fee_line->amount + 0,
3820 $replacement_amount, 'The LOST amount is left intact' );
3821 is( $lost_fee_line->amountoutstanding + 0,
3823 'The LOST amountoutstanding is refunded' );
3824 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3826 $overdue_fees = Koha::Account::Lines->search(
3828 borrowernumber => $patron->id,
3829 itemnumber => $item->itemnumber,
3830 debit_type_code => 'OVERDUE'
3833 order_by => { '-asc' => 'accountlines_id'}
3836 is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
3837 $overdue_fee = $overdue_fees->next;
3838 is( $overdue_fee->amount + 0,
3839 10, 'The original OVERDUE amount is left intact' );
3840 is( $overdue_fee->amountoutstanding + 0,
3842 'The original OVERDUE amountoutstanding is left as forgiven' );
3843 $overdue_fee = $overdue_fees->next;
3844 is( $overdue_fee->amount + 0,
3845 5, 'The new OVERDUE amount is correct for the backdated return' );
3846 is( $overdue_fee->amountoutstanding + 0,
3848 'The new OVERDUE amountoutstanding is correct for the backdated return' );
3853 subtest '_FixOverduesOnReturn' => sub {
3856 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3857 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3859 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3861 my $branchcode = $library2->{branchcode};
3863 my $item = $builder->build_sample_item(
3865 biblionumber => $biblio->biblionumber,
3866 library => $branchcode,
3867 replacementprice => 99.00,
3872 my $patron = $builder->build( { source => 'Borrower' } );
3874 ## Start with basic call, should just close out the open fine
3875 my $accountline = Koha::Account::Line->new(
3877 borrowernumber => $patron->{borrowernumber},
3878 debit_type_code => 'OVERDUE',
3879 status => 'UNRETURNED',
3880 itemnumber => $item->itemnumber,
3882 amountoutstanding => 99.00,
3883 interface => 'test',
3887 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
3889 $accountline->_result()->discard_changes();
3891 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
3892 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3893 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3895 ## Run again, with exemptfine enabled
3898 debit_type_code => 'OVERDUE',
3899 status => 'UNRETURNED',
3900 amountoutstanding => 99.00,
3904 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3906 $accountline->_result()->discard_changes();
3907 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'APPLY' })->next();
3909 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
3910 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3911 is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
3912 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
3913 is( $offset->amount + 0, -99, "Amount of offset is correct" );
3914 my $credit = $offset->credit;
3915 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
3916 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
3917 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
3919 # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
3922 debit_type_code => 'OVERDUE',
3923 status => 'UNRETURNED',
3924 amountoutstanding => 0.00,
3929 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3931 $accountline->_result()->discard_changes();
3932 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'CREATE' })->next();
3933 is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
3934 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3935 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3938 subtest 'Set waiting flag' => sub {
3941 my $library_1 = $builder->build( { source => 'Branch' } );
3942 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3943 my $library_2 = $builder->build( { source => 'Branch' } );
3944 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3946 my $item = $builder->build_sample_item(
3948 library => $library_1->{branchcode},
3952 set_userenv( $library_2 );
3953 my $reserve_id = AddReserve(
3955 branchcode => $library_2->{branchcode},
3956 borrowernumber => $patron_2->{borrowernumber},
3957 biblionumber => $item->biblionumber,
3959 itemnumber => $item->itemnumber,
3963 set_userenv( $library_1 );
3964 my $do_transfer = 1;
3965 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3966 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3967 my $hold = Koha::Holds->find( $reserve_id );
3968 is( $hold->found, 'T', 'Hold is in transit' );
3970 my ( $status ) = CheckReserves($item->itemnumber);
3971 is( $status, 'Transferred', 'Hold is not waiting yet');
3973 set_userenv( $library_2 );
3975 AddReturn( $item->barcode, $library_2->{branchcode} );
3976 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3977 $hold = Koha::Holds->find( $reserve_id );
3978 is( $hold->found, 'W', 'Hold is waiting' );
3979 ( $status ) = CheckReserves($item->itemnumber);
3980 is( $status, 'Waiting', 'Now the hold is waiting');
3982 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
3983 set_userenv( $library_1 );
3984 (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
3985 $hold = Koha::Holds->find( $reserve_id );
3986 is( $hold->found, undef, 'Hold is no longer marked waiting' );
3987 is( $hold->priority, 1, "Hold is now priority one again");
3988 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
3989 is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
3990 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
3991 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
3992 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
3995 subtest 'Cancel transfers on lost items' => sub {
3998 my $library_to = $builder->build_object( { class => 'Koha::Libraries' } );
3999 my $item = $builder->build_sample_item();
4000 my $holdingbranch = $item->holdingbranch;
4001 # Historic transfer (datearrived is defined)
4002 my $old_transfer = $builder->build_object(
4004 class => 'Koha::Item::Transfers',
4006 itemnumber => $item->itemnumber,
4007 frombranch => $holdingbranch,
4008 tobranch => $library_to->branchcode,
4010 datesent => \'NOW()',
4011 datearrived => \'NOW()',
4012 datecancelled => undef,
4013 daterequested => \'NOW()'
4017 # Queued transfer (datesent is undefined)
4018 my $transfer_1 = $builder->build_object(
4020 class => 'Koha::Item::Transfers',
4022 itemnumber => $item->itemnumber,
4023 frombranch => $holdingbranch,
4024 tobranch => $library_to->branchcode,
4027 datearrived => undef,
4028 datecancelled => undef,
4029 daterequested => \'NOW()'
4033 # In transit transfer (datesent is defined, datearrived and datecancelled are both undefined)
4034 my $transfer_2 = $builder->build_object(
4036 class => 'Koha::Item::Transfers',
4038 itemnumber => $item->itemnumber,
4039 frombranch => $holdingbranch,
4040 tobranch => $library_to->branchcode,
4042 datesent => \'NOW()',
4043 datearrived => undef,
4044 datecancelled => undef,
4045 daterequested => \'NOW()'
4050 # Simulate item being marked as lost
4051 $item->itemlost(1)->store;
4052 LostItem( $item->itemnumber, 'test', 1 );
4054 $transfer_1->discard_changes;
4055 isnt($transfer_1->datecancelled, undef, "Queud transfer was cancelled upon item lost");
4056 is($transfer_1->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
4057 $transfer_2->discard_changes;
4058 isnt($transfer_2->datecancelled, undef, "Active transfer was cancelled upon item lost");
4059 is($transfer_2->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
4060 $old_transfer->discard_changes;
4061 is($old_transfer->datecancelled, undef, "Old transfers are unaffected");
4062 $item->discard_changes;
4063 is($item->holdingbranch, $holdingbranch, "Items holding branch remains unchanged");
4066 subtest 'CanBookBeIssued | is_overdue' => sub {
4069 # Set a simple circ policy
4070 Koha::CirculationRules->set_rules(
4072 categorycode => undef,
4073 branchcode => undef,
4077 reservesallowed => 25,
4079 lengthunit => 'days',
4080 renewalsallowed => 1,
4082 norenewalbefore => undef,
4090 my $now = dt_from_string()->truncate( to => 'day' );
4091 my $five_days_go = $now->clone->add( days => 5 );
4092 my $ten_days_go = $now->clone->add( days => 10);
4093 my $library = $builder->build( { source => 'Branch' } );
4094 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
4096 my $item = $builder->build_sample_item(
4098 library => $library->{branchcode},
4102 my $issue = AddIssue( $patron->unblessed, $item->barcode, $five_days_go ); # date due was 10d ago
4103 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
4104 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), output_pref({ str => $five_days_go, dateonly => 1}), "First issue works");
4105 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->barcode,$ten_days_go, undef, undef, undef);
4106 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
4107 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
4110 subtest 'ItemsDeniedRenewal preference' => sub {
4113 C4::Context->set_preference('ItemsDeniedRenewal','');
4115 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
4116 Koha::CirculationRules->set_rules(
4118 categorycode => '*',
4120 branchcode => $idr_lib->branchcode,
4122 reservesallowed => 25,
4124 lengthunit => 'days',
4125 renewalsallowed => 10,
4127 norenewalbefore => undef,
4135 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
4136 homebranch => $idr_lib->branchcode,
4140 itemcallnumber => undef,
4144 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
4145 homebranch => $idr_lib->branchcode,
4148 location => 'NOPROC'
4152 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
4153 branchcode => $idr_lib->branchcode,
4156 my $future = dt_from_string->add( days => 1 );
4157 my $deny_issue = $builder->build_object(
4159 class => 'Koha::Checkouts',
4161 returndate => undef,
4162 renewals_count => 0,
4164 borrowernumber => $idr_borrower->borrowernumber,
4165 itemnumber => $deny_book->itemnumber,
4166 onsite_checkout => 0,
4167 date_due => $future,
4171 my $allow_issue = $builder->build_object(
4173 class => 'Koha::Checkouts',
4175 returndate => undef,
4176 renewals_count => 0,
4178 borrowernumber => $idr_borrower->borrowernumber,
4179 itemnumber => $allow_book->itemnumber,
4180 onsite_checkout => 0,
4181 date_due => $future,
4188 my ( $idr_mayrenew, $idr_error ) =
4189 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4190 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
4191 is( $idr_error, undef, 'Renewal allowed when no rules' );
4193 $idr_rules="withdrawn: [1]";
4195 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4196 ( $idr_mayrenew, $idr_error ) =
4197 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4198 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
4199 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
4200 ( $idr_mayrenew, $idr_error ) =
4201 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
4202 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
4203 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
4205 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
4207 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4208 ( $idr_mayrenew, $idr_error ) =
4209 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4210 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
4211 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
4212 ( $idr_mayrenew, $idr_error ) =
4213 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
4214 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
4215 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
4217 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
4219 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4220 ( $idr_mayrenew, $idr_error ) =
4221 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4222 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
4223 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
4224 ( $idr_mayrenew, $idr_error ) =
4225 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
4226 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
4227 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
4229 $idr_rules="itemcallnumber: [NULL]";
4230 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4231 ( $idr_mayrenew, $idr_error ) =
4232 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4233 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
4234 $idr_rules="itemcallnumber: ['']";
4235 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4236 ( $idr_mayrenew, $idr_error ) =
4237 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4238 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
4240 $idr_rules="itemnotes: [NULL]";
4241 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4242 ( $idr_mayrenew, $idr_error ) =
4243 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4244 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
4245 $idr_rules="itemnotes: ['']";
4246 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4247 ( $idr_mayrenew, $idr_error ) =
4248 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4249 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
4252 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
4255 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4256 my $library = $builder->build( { source => 'Branch' } );
4257 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4259 my $item = $builder->build_sample_item(
4261 library => $library->{branchcode},
4265 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4266 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4267 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4270 subtest 'CanBookBeIssued | notforloan' => sub {
4273 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
4275 my $library = $builder->build( { source => 'Branch' } );
4276 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4278 my $itemtype = $builder->build(
4280 source => 'Itemtype',
4281 value => { notforloan => undef, }
4284 my $item = $builder->build_sample_item(
4286 library => $library->{branchcode},
4287 itype => $itemtype->{itemtype},
4290 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4292 my ( $issuingimpossible, $needsconfirmation );
4295 subtest 'item-level_itypes = 1' => sub {
4298 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
4299 # Is for loan at item type and item level
4300 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4301 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4302 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4304 # not for loan at item type level
4305 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4306 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4307 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4310 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4311 'Item can not be issued, not for loan at item type level'
4314 # not for loan at item level
4315 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4316 $item->notforloan( 1 )->store;
4317 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4318 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4321 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4322 'Item can not be issued, not for loan at item type level'
4326 subtest 'item-level_itypes = 0' => sub {
4329 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4331 # We set another itemtype for biblioitem
4332 my $itemtype = $builder->build(
4334 source => 'Itemtype',
4335 value => { notforloan => undef, }
4339 # for loan at item type and item level
4340 $item->notforloan(0)->store;
4341 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4342 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4343 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4344 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4346 # not for loan at item type level
4347 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4348 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4349 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4352 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4353 'Item can not be issued, not for loan at item type level'
4356 # not for loan at item level
4357 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4358 $item->notforloan( 1 )->store;
4359 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4360 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4363 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4364 'Item can not be issued, not for loan at item type level'
4368 # TODO test with AllowNotForLoanOverride = 1
4371 subtest 'CanBookBeIssued | recalls' => sub {
4374 t::lib::Mocks::mock_preference("UseRecalls", 1);
4375 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4376 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4377 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4378 my $item = $builder->build_sample_item;
4379 Koha::CirculationRules->set_rules({
4380 branchcode => undef,
4382 categorycode => undef,
4384 recalls_allowed => 10,
4389 my $recall = Koha::Recall->new(
4390 { patron_id => $patron1->borrowernumber,
4391 biblio_id => $item->biblionumber,
4392 item_id => $item->itemnumber,
4394 pickup_library_id => $patron1->branchcode,
4398 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4399 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed an item-level recall on this item" );
4401 $recall->set_cancelled;
4403 # biblio-level recall
4404 $recall = Koha::Recall->new(
4405 { patron_id => $patron1->borrowernumber,
4406 biblio_id => $item->biblionumber,
4409 pickup_library_id => $patron1->branchcode,
4413 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4414 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed a biblio-level recall and this item is eligible to fill it" );
4416 $recall->set_cancelled;
4418 # biblio-level recall
4419 $recall = Koha::Recall->new(
4420 { patron_id => $patron1->borrowernumber,
4421 biblio_id => $item->biblionumber,
4424 pickup_library_id => $patron1->branchcode,
4427 $recall->set_waiting( { item => $item, expirationdate => dt_from_string() } );
4429 my ( undef, undef, undef, $messages ) = CanBookBeIssued( $patron1, $item->barcode, undef, undef, undef, undef );
4430 is( $messages->{RECALLED}, $recall->id, "This book can be issued by this patron and they have placed a recall" );
4432 $recall->set_cancelled;
4435 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
4438 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
4439 my $item = $builder->build_sample_item(
4441 onloan => '2018-01-01',
4445 AddReturn( $item->barcode, $item->homebranch );
4446 $item->discard_changes; # refresh
4447 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
4450 subtest 'AddReturn | recalls' => sub {
4453 t::lib::Mocks::mock_preference("UseRecalls", 1);
4454 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4455 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4456 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4457 my $item1 = $builder->build_sample_item;
4458 Koha::CirculationRules->set_rules({
4459 branchcode => undef,
4461 categorycode => undef,
4463 recalls_allowed => 10,
4467 # this item can fill a recall with pickup at this branch
4468 AddIssue( $patron1->unblessed, $item1->barcode );
4469 my $recall1 = Koha::Recall->new(
4470 { patron_id => $patron2->borrowernumber,
4471 biblio_id => $item1->biblionumber,
4472 item_id => $item1->itemnumber,
4474 pickup_library_id => $item1->homebranch,
4477 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4478 is( $messages->{RecallFound}->id, $recall1->id, "Recall found" );
4479 $recall1->set_cancelled;
4481 # this item can fill a recall but needs transfer
4482 AddIssue( $patron1->unblessed, $item1->barcode );
4483 $recall1 = Koha::Recall->new(
4484 { patron_id => $patron2->borrowernumber,
4485 biblio_id => $item1->biblionumber,
4486 item_id => $item1->itemnumber,
4488 pickup_library_id => $patron2->branchcode,
4491 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4492 is( $messages->{RecallNeedsTransfer}, $item1->homebranch, "Recall requiring transfer found" );
4493 $recall1->set_cancelled;
4495 # this item is already in transit, do not ask to transfer
4496 AddIssue( $patron1->unblessed, $item1->barcode );
4497 $recall1 = Koha::Recall->new(
4498 { patron_id => $patron2->borrowernumber,
4499 biblio_id => $item1->biblionumber,
4500 item_id => $item1->itemnumber,
4502 pickup_library_id => $patron2->branchcode,
4505 $recall1->start_transfer;
4506 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $patron2->branchcode );
4507 is( $messages->{TransferredRecall}->id, $recall1->id, "In transit recall found" );
4508 $recall1->set_cancelled;
4511 subtest 'AddReturn | bundles' => sub {
4514 my $schema = Koha::Database->schema;
4515 $schema->storage->txn_begin;
4517 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4518 my $host_item1 = $builder->build_sample_item;
4519 my $bundle_item1 = $builder->build_sample_item;
4520 $schema->resultset('ItemBundle')
4522 { host => $host_item1->itemnumber, item => $bundle_item1->itemnumber } );
4524 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $bundle_item1->barcode, $bundle_item1->homebranch );
4525 is($messages->{InBundle}->id, $host_item1->id, 'AddReturn returns InBundle host item when item is part of a bundle');
4527 $schema->storage->txn_rollback;
4530 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
4535 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4537 my $issuing_charges = 15;
4538 my $title = 'A title';
4539 my $author = 'Author, An';
4540 my $barcode = 'WHATARETHEODDS';
4542 my $circ = Test::MockModule->new('C4::Circulation');
4544 'GetIssuingCharges',
4546 return $issuing_charges;
4550 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4551 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
4552 my $patron = $builder->build_object({
4553 class => 'Koha::Patrons',
4554 value => { branchcode => $library->id }
4557 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
4558 my $item_id = Koha::Item->new(
4560 biblionumber => $biblio->biblionumber,
4561 homebranch => $library->id,
4562 holdingbranch => $library->id,
4563 barcode => $barcode,
4564 replacementprice => 23.00,
4565 itype => $itemtype->id
4567 )->store->itemnumber;
4568 my $item = Koha::Items->find( $item_id );
4570 my $context = Test::MockModule->new('C4::Context');
4571 $context->mock( userenv => { branch => $library->id } );
4573 # Check the item out
4574 AddIssue( $patron->unblessed, $item->barcode );
4577 AddRenewal( $patron->borrowernumber, $item->itemnumber, $library->id, undef, {break=>"the_renewal"} );
4578 } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
4580 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
4581 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
4582 my %params_renewal = (
4583 timestamp => { -like => $date . "%" },
4584 module => "CIRCULATION",
4585 action => "RENEWAL",
4587 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
4588 AddRenewal( $patron->id, $item->id, $library->id );
4589 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4590 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
4592 my $checkouts = $patron->checkouts;
4593 # The following will fail if run on 00:00:00
4594 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
4596 my $lines = Koha::Account::Lines->search({
4597 borrowernumber => $patron->id,
4598 itemnumber => $item->id
4601 is( $lines->count, 2 );
4603 my $line = $lines->next;
4604 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
4605 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
4606 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
4608 $line = $lines->next;
4609 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
4610 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
4611 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
4613 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
4615 $context = Test::MockModule->new('C4::Context');
4616 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
4618 my $now = dt_from_string;
4619 $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
4620 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
4621 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
4622 $sth->execute($item->id, $library->id);
4623 my ($old_stats_size) = $sth->fetchrow_array;
4624 AddRenewal( $patron->id, $item->id, $library->id );
4625 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4626 $sth->execute($item->id, $library->id);
4627 my ($new_stats_size) = $sth->fetchrow_array;
4628 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
4629 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
4631 AddReturn( $item->id, $library->id, undef, $date );
4632 AddIssue( $patron->unblessed, $item->barcode, $now );
4633 AddRenewal( $patron->id, $item->id, $library->id, undef, undef, 1 );
4634 my $lines_skipped = Koha::Account::Lines->search({
4635 borrowernumber => $patron->id,
4636 itemnumber => $item->id
4638 is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
4642 subtest 'AddRenewal() adds to renewals' => sub {
4645 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4646 my $patron = $builder->build_object({
4647 class => 'Koha::Patrons',
4648 value => { branchcode => $library->id }
4651 my $item = $builder->build_sample_item();
4653 set_userenv( $library->unblessed );
4655 # Check the item out
4656 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4657 is(ref($issue), 'Koha::Checkout', 'Issue added');
4660 my $duedate = AddRenewal( $patron->id, $item->id, $library->id );
4662 ok( $duedate, "Renewal added" );
4664 my $renewals = Koha::Checkouts::Renewals->search({ checkout_id => $issue->issue_id });
4665 is($renewals->count, 1, 'One renewal added');
4666 my $THE_renewal = $renewals->next;
4667 is( $THE_renewal->renewer_id, C4::Context->userenv->{'number'}, 'Renewer recorded from context' );
4670 subtest 'ProcessOfflinePayment() tests' => sub {
4677 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
4678 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4679 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
4681 is( $result, 'Success.', 'The right string is returned' );
4683 my $lines = $patron->account->lines;
4684 is( $lines->count, 1, 'line created correctly');
4686 my $line = $lines->next;
4687 is( $line->amount+0, $amount * -1, 'amount picked from params' );
4688 is( $line->branchcode, $library->id, 'branchcode set correctly' );
4692 subtest 'Incremented fee tests' => sub {
4695 my $dt = dt_from_string();
4696 Time::Fake->offset( $dt->epoch );
4698 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
4701 $builder->build_object( { class => 'Koha::Libraries' } )->store;
4703 $module->mock( 'userenv', sub { { branch => $library->id } } );
4705 my $patron = $builder->build_object(
4707 class => 'Koha::Patrons',
4708 value => { categorycode => $patron_category->{categorycode} }
4712 my $itemtype = $builder->build_object(
4714 class => 'Koha::ItemTypes',
4716 notforloan => undef,
4718 rentalcharge_daily => 1,
4719 rentalcharge_daily_calendar => 0
4724 my $item = $builder->build_sample_item(
4726 library => $library->{branchcode},
4727 itype => $itemtype->id,
4731 is( $itemtype->rentalcharge_daily+0,
4732 1, 'Daily rental charge stored and retreived correctly' );
4733 is( $item->effective_itemtype, $itemtype->id,
4734 "Itemtype set correctly for item" );
4736 my $now = dt_from_string;
4737 my $dt_from = $now->clone;
4738 my $dt_to = $now->clone->add( days => 7 );
4739 my $dt_to_renew = $now->clone->add( days => 13 );
4743 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4744 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4745 is( $accountline->amount+0, 7,
4746 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
4748 $accountline->delete();
4749 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4750 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4751 is( $accountline->amount+0, 6,
4752 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
4754 $accountline->delete();
4757 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
4758 $itemtype->rentalcharge_daily_calendar(1)->store();
4760 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4761 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4762 is( $accountline->amount+0, 7,
4763 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
4765 $accountline->delete();
4766 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4767 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4768 is( $accountline->amount+0, 6,
4769 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
4771 $accountline->delete();
4774 my $calendar = C4::Calendar->new( branchcode => $library->id );
4775 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
4777 ( $dt_from->day_of_week == 6 ) ? 0
4778 : ( $dt_from->day_of_week == 7 ) ? 1
4779 : $dt_from->day_of_week + 1;
4780 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
4781 $calendar->insert_week_day_holiday(
4782 weekday => $closed_day,
4783 title => 'Test holiday',
4784 description => 'Test holiday'
4787 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4788 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4789 is( $accountline->amount+0, 6,
4790 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
4792 $accountline->delete();
4793 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4794 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4795 is( $accountline->amount+0, 5,
4796 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
4798 $accountline->delete();
4801 $itemtype->rentalcharge(2)->store;
4802 is( $itemtype->rentalcharge+0, 2,
4803 'Rental charge updated and retreived correctly' );
4805 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4807 Koha::Account::Lines->search( { itemnumber => $item->id } );
4808 is( $accountlines->count, '2',
4809 "Fixed charge and accrued charge recorded distinctly" );
4810 $accountlines->delete();
4811 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4812 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
4813 is( $accountlines->count, '2',
4814 "Fixed charge and accrued charge recorded distinctly, for renewal" );
4815 $accountlines->delete();
4817 $itemtype->rentalcharge(0)->store;
4818 is( $itemtype->rentalcharge+0, 0,
4819 'Rental charge reset and retreived correctly' );
4822 Koha::CirculationRules->set_rule(
4824 categorycode => $patron->categorycode,
4825 itemtype => $itemtype->id,
4826 branchcode => $library->id,
4827 rule_name => 'lengthunit',
4828 rule_value => 'hours',
4832 $itemtype->rentalcharge_hourly('0.25')->store();
4833 is( $itemtype->rentalcharge_hourly,
4834 '0.25', 'Hourly rental charge stored and retreived correctly' );
4836 $dt_to = $now->clone->add( hours => 168 );
4837 $dt_to_renew = $now->clone->add( hours => 312 );
4839 $itemtype->rentalcharge_hourly_calendar(0)->store();
4841 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4842 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4843 is( $accountline->amount + 0, 42,
4844 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)" );
4845 $accountline->delete();
4846 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4847 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4848 is( $accountline->amount + 0, 36,
4849 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)" );
4850 $accountline->delete();
4853 $itemtype->rentalcharge_hourly_calendar(1)->store();
4855 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4856 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4857 is( $accountline->amount + 0, 36,
4858 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)" );
4859 $accountline->delete();
4860 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4861 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4862 is( $accountline->amount + 0, 30,
4863 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
4864 $accountline->delete();
4867 $calendar->delete_holiday( weekday => $closed_day );
4869 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4870 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4871 is( $accountline->amount + 0, 42,
4872 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u" );
4873 $accountline->delete();
4874 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4875 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4876 is( $accountline->amount + 0, 36,
4877 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)" );
4878 $accountline->delete();
4883 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
4886 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
4887 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4890 $builder->build_object( { class => 'Koha::Libraries' } )->store;
4891 my $patron = $builder->build_object(
4893 class => 'Koha::Patrons',
4894 value => { categorycode => $patron_category->{categorycode} }
4898 my $itemtype = $builder->build_object(
4900 class => 'Koha::ItemTypes',
4904 rentalcharge_daily => 0
4909 my $item = $builder->build_sample_item(
4911 library => $library->id,
4915 itype => $itemtype->id,
4919 my ( $issuingimpossible, $needsconfirmation );
4920 my $dt_from = dt_from_string();
4921 my $dt_due = $dt_from->clone->add( days => 3 );
4923 $itemtype->rentalcharge(1)->store;
4924 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4925 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
4926 $itemtype->rentalcharge('0')->store;
4927 $itemtype->rentalcharge_daily(1)->store;
4928 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4929 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
4930 $itemtype->rentalcharge_daily('0')->store;
4933 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
4936 t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
4938 my $patron = $builder->build_object(
4940 class => 'Koha::Patrons',
4941 value => { categorycode => $patron_category->{categorycode} }
4945 my $item = $builder->build_sample_item(
4947 materials => 'includes DVD',
4951 my $dt_due = dt_from_string->add( days => 3 );
4953 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4954 is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
4957 subtest 'Do not return on renewal (LOST charge)' => sub {
4960 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
4961 my $library = $builder->build_object( { class => "Koha::Libraries" } );
4962 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
4963 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
4965 my $biblio = $builder->build_sample_biblio;
4967 my $item = $builder->build_sample_item(
4969 biblionumber => $biblio->biblionumber,
4970 library => $library->branchcode,
4971 replacementprice => 99.00,
4976 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
4977 AddIssue( $patron->unblessed, $item->barcode );
4979 my $accountline = Koha::Account::Line->new(
4981 borrowernumber => $patron->borrowernumber,
4982 debit_type_code => 'LOST',
4984 itemnumber => $item->itemnumber,
4986 amountoutstanding => 12,
4987 interface => 'something',
4991 # AddRenewal doesn't call _FixAccountForLostAndFound
4992 AddIssue( $patron->unblessed, $item->barcode );
4994 is( $patron->checkouts->count, 1,
4995 'Renewal should not return the item even if a LOST payment has been made earlier'
4999 subtest 'Filling a hold should cancel existing transfer' => sub {
5002 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
5004 my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
5005 my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
5006 my $patron = $builder->build_object(
5008 class => 'Koha::Patrons',
5010 categorycode => $patron_category->{categorycode},
5011 branchcode => $libraryA->branchcode,
5016 my $item = $builder->build_sample_item({
5017 homebranch => $libraryB->branchcode,
5020 my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
5021 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
5023 branchcode => $libraryA->branchcode,
5024 borrowernumber => $patron->borrowernumber,
5025 biblionumber => $item->biblionumber,
5026 itemnumber => $item->itemnumber
5028 my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
5029 is( $reserves->count, 1, "Reserve is placed");
5030 ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
5031 my $reserve = $reserves->next;
5032 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
5033 $reserve->discard_changes;
5034 ok( $reserve->found eq 'W', "Reserve is marked waiting" );
5035 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
5038 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
5042 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
5043 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5044 my $patron = $builder->build_object(
5046 class => 'Koha::Patrons',
5047 value => { categorycode => $patron_category->{categorycode} }
5051 my $biblionumber = $builder->build_sample_biblio(
5053 branchcode => $library->branchcode,
5057 # And the circulation rule
5058 Koha::CirculationRules->search->delete;
5059 Koha::CirculationRules->set_rules(
5061 categorycode => undef,
5063 branchcode => undef,
5066 lengthunit => 'days',
5072 source => 'CirculationRule',
5074 branchcode => undef,
5075 categorycode => undef,
5077 rule_name => 'lostreturn',
5078 rule_value => 'refund'
5083 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5086 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5087 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5089 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5091 my $item = $builder->build_sample_item(
5093 biblionumber => $biblionumber,
5094 library => $library->branchcode,
5095 replacementprice => '42',
5098 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5099 LostItem( $item->itemnumber, 'cli', 0 );
5100 $item->_result->itemlost(1);
5101 $item->_result->itemlost_on( $lost_on );
5102 $item->_result->update();
5104 my $a = Koha::Account::Lines->search(
5106 itemnumber => $item->id,
5107 borrowernumber => $patron->borrowernumber
5110 ok( $a, "Found accountline for lost fee" );
5111 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5112 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5113 $a = $a->get_from_storage;
5114 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5118 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5121 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5122 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5124 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5126 my $item = $builder->build_sample_item(
5128 biblionumber => $biblionumber,
5129 library => $library->branchcode,
5130 replacementprice => '42',
5133 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5134 LostItem( $item->itemnumber, 'cli', 0 );
5135 $item->_result->itemlost(1);
5136 $item->_result->itemlost_on( $lost_on );
5137 $item->_result->update();
5139 my $a = Koha::Account::Lines->search(
5141 itemnumber => $item->id,
5142 borrowernumber => $patron->borrowernumber
5145 ok( $a, "Found accountline for lost fee" );
5146 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5147 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5148 $a = $a->get_from_storage;
5149 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5153 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5156 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5157 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5159 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5161 my $item = $builder->build_sample_item(
5163 biblionumber => $biblionumber,
5164 library => $library->branchcode,
5165 replacementprice => '42',
5168 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5169 LostItem( $item->itemnumber, 'cli', 0 );
5170 $item->_result->itemlost(1);
5171 $item->_result->itemlost_on( $lost_on );
5172 $item->_result->update();
5174 my $a = Koha::Account::Lines->search(
5176 itemnumber => $item->id,
5177 borrowernumber => $patron->borrowernumber
5180 ok( $a, "Found accountline for lost fee" );
5181 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5182 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5183 $a = $a->get_from_storage;
5184 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5188 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5191 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5192 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5194 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5196 my $item = $builder->build_sample_item(
5198 biblionumber => $biblionumber,
5199 library => $library->branchcode,
5200 replacementprice => '42',
5203 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5204 LostItem( $item->itemnumber, 'cli', 0 );
5205 $item->_result->itemlost(1);
5206 $item->_result->itemlost_on( $lost_on );
5207 $item->_result->update();
5209 my $a = Koha::Account::Lines->search(
5211 itemnumber => $item->id,
5212 borrowernumber => $patron->borrowernumber
5216 ok( $a, "Found accountline for lost fee" );
5217 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5218 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5219 $a = $a->get_from_storage;
5220 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5225 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
5229 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
5230 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5231 my $patron = $builder->build_object(
5233 class => 'Koha::Patrons',
5234 value => { categorycode => $patron_category->{categorycode} }
5237 my $patron2 = $builder->build_object(
5239 class => 'Koha::Patrons',
5240 value => { categorycode => $patron_category->{categorycode} }
5244 my $biblionumber = $builder->build_sample_biblio(
5246 branchcode => $library->branchcode,
5250 # And the circulation rule
5251 Koha::CirculationRules->search->delete;
5252 Koha::CirculationRules->set_rules(
5254 categorycode => undef,
5256 branchcode => undef,
5259 lengthunit => 'days',
5265 source => 'CirculationRule',
5267 branchcode => undef,
5268 categorycode => undef,
5270 rule_name => 'lostreturn',
5271 rule_value => 'refund'
5276 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5279 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5280 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5282 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5284 my $item = $builder->build_sample_item(
5286 biblionumber => $biblionumber,
5287 library => $library->branchcode,
5288 replacementprice => '42',
5291 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5292 LostItem( $item->itemnumber, 'cli', 0 );
5293 $item->_result->itemlost(1);
5294 $item->_result->itemlost_on( $lost_on );
5295 $item->_result->update();
5297 my $a = Koha::Account::Lines->search(
5299 itemnumber => $item->id,
5300 borrowernumber => $patron->borrowernumber
5303 ok( $a, "Found accountline for lost fee" );
5304 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5305 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5306 $a = $a->get_from_storage;
5307 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5312 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5315 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5316 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5318 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5320 my $item = $builder->build_sample_item(
5322 biblionumber => $biblionumber,
5323 library => $library->branchcode,
5324 replacementprice => '42',
5327 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5328 LostItem( $item->itemnumber, 'cli', 0 );
5329 $item->_result->itemlost(1);
5330 $item->_result->itemlost_on( $lost_on );
5331 $item->_result->update();
5333 my $a = Koha::Account::Lines->search(
5335 itemnumber => $item->id,
5336 borrowernumber => $patron->borrowernumber
5339 ok( $a, "Found accountline for lost fee" );
5340 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5341 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5342 $a = $a->get_from_storage;
5343 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5347 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5350 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5351 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5353 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5355 my $item = $builder->build_sample_item(
5357 biblionumber => $biblionumber,
5358 library => $library->branchcode,
5359 replacementprice => '42',
5362 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5363 LostItem( $item->itemnumber, 'cli', 0 );
5364 $item->_result->itemlost(1);
5365 $item->_result->itemlost_on( $lost_on );
5366 $item->_result->update();
5368 my $a = Koha::Account::Lines->search(
5370 itemnumber => $item->id,
5371 borrowernumber => $patron->borrowernumber
5374 ok( $a, "Found accountline for lost fee" );
5375 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5376 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5377 $a = $a->get_from_storage;
5378 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5382 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5385 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5386 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5388 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5390 my $item = $builder->build_sample_item(
5392 biblionumber => $biblionumber,
5393 library => $library->branchcode,
5394 replacementprice => '42',
5397 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5398 LostItem( $item->itemnumber, 'cli', 0 );
5399 $item->_result->itemlost(1);
5400 $item->_result->itemlost_on( $lost_on );
5401 $item->_result->update();
5403 my $a = Koha::Account::Lines->search(
5405 itemnumber => $item->id,
5406 borrowernumber => $patron->borrowernumber
5410 ok( $a, "Found accountline for lost fee" );
5411 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5412 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5413 $a = $a->get_from_storage;
5414 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5419 subtest 'transferbook tests' => sub {
5423 { C4::Circulation::transferbook({}); }
5424 'Koha::Exceptions::MissingParameter',
5425 'Koha::Patron->store raises an exception on missing params';
5428 { C4::Circulation::transferbook({to_branch=>'anything'}); }
5429 'Koha::Exceptions::MissingParameter',
5430 'Koha::Patron->store raises an exception on missing params';
5433 { C4::Circulation::transferbook({from_branch=>'anything'}); }
5434 'Koha::Exceptions::MissingParameter',
5435 'Koha::Patron->store raises an exception on missing params';
5437 my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
5438 is( $doreturn, 0, "No return without barcode");
5439 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5440 is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
5442 ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
5443 is( $doreturn, 0, "No return without barcode");
5444 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5445 is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
5449 subtest 'Checkout should correctly terminate a transfer' => sub {
5452 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5453 my $patron_1 = $builder->build_object(
5455 class => 'Koha::Patrons',
5456 value => { branchcode => $library_1->branchcode }
5459 my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
5460 my $patron_2 = $builder->build_object(
5462 class => 'Koha::Patrons',
5463 value => { branchcode => $library_2->branchcode }
5467 my $item = $builder->build_sample_item(
5469 library => $library_1->branchcode,
5473 t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
5474 my $reserve_id = AddReserve(
5476 branchcode => $library_2->branchcode,
5477 borrowernumber => $patron_2->borrowernumber,
5478 biblionumber => $item->biblionumber,
5479 itemnumber => $item->itemnumber,
5484 my $do_transfer = 1;
5485 ModItemTransfer( $item->itemnumber, $library_1->branchcode,
5486 $library_2->branchcode, 'Manual' );
5487 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
5488 GetOtherReserves( $item->itemnumber )
5489 ; # To put the Reason, it's what does returns.pl...
5490 my $hold = Koha::Holds->find($reserve_id);
5491 is( $hold->found, 'T', 'Hold is in transit' );
5492 my $transfer = $item->get_transfer;
5493 is( $transfer->frombranch, $library_1->branchcode );
5494 is( $transfer->tobranch, $library_2->branchcode );
5495 is( $transfer->reason, 'Reserve' );
5497 t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
5498 AddIssue( $patron_1->unblessed, $item->barcode );
5499 $transfer = $transfer->get_from_storage;
5500 isnt( $transfer->datearrived, undef );
5501 $hold = $hold->get_from_storage;
5502 is( $hold->found, undef, 'Hold is waiting' );
5503 is( $hold->priority, 1, );
5506 subtest 'AddIssue records staff who checked out item if appropriate' => sub {
5509 $module->mock( 'userenv', sub { { branch => $library->{id} } } );
5511 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5512 my $patron = $builder->build_object(
5514 class => 'Koha::Patrons',
5515 value => { categorycode => $patron_category->{categorycode} }
5518 my $issuer = $builder->build_object(
5520 class => 'Koha::Patrons',
5521 value => { categorycode => $patron_category->{categorycode} }
5524 my $item = $builder->build_sample_item(
5526 library => $library->{branchcode}
5530 $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->{borrowernumber} } } );
5532 my $dt_from = dt_from_string();
5533 my $dt_to = dt_from_string()->add( days => 7 );
5535 my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
5537 is( $issue->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
5539 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
5542 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
5544 is( $issue->issuer, $issuer->{borrowernumber}, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
5547 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
5550 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5551 my $patron_1 = $builder->build_object(
5553 class => 'Koha::Patrons',
5554 value => { branchcode => $library_1->branchcode }
5557 my $patron_2 = $builder->build_object(
5559 class => 'Koha::Patrons',
5560 value => { branchcode => $library_1->branchcode }
5564 my $item = $builder->build_sample_item(
5566 library => $library_1->branchcode,
5570 AddIssue( $patron_1->unblessed, $item->barcode );
5571 ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
5572 AddIssue( $patron_2->unblessed, $item->barcode );
5573 ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
5576 subtest "updateWrongTransfer tests" => sub {
5579 my $library1 = $builder->build_object( { class => 'Koha::Libraries' } );
5580 my $library2 = $builder->build_object( { class => 'Koha::Libraries' } );
5581 my $library3 = $builder->build_object( { class => 'Koha::Libraries' } );
5582 my $item = $builder->build_sample_item(
5584 homebranch => $library1->branchcode,
5585 holdingbranch => $library2->branchcode,
5586 datelastseen => undef
5590 my $transfer = $builder->build_object(
5592 class => 'Koha::Item::Transfers',
5594 itemnumber => $item->itemnumber,
5595 frombranch => $library2->branchcode,
5596 tobranch => $library1->branchcode,
5597 daterequested => dt_from_string,
5598 datesent => dt_from_string,
5599 datecancelled => undef,
5600 datearrived => undef,
5605 is( ref($transfer), 'Koha::Item::Transfer', 'Mock transfer added' );
5607 my $new_transfer = C4::Circulation::updateWrongTransfer($item->itemnumber, $library1->branchcode);
5608 is(ref($new_transfer), 'Koha::Item::Transfer', "updateWrongTransfer returns a 'Koha::Item::Transfer' object");
5609 ok( !$new_transfer->in_transit, "New transfer is NOT created as in transit (or cancelled)");
5611 my $original_transfer = $transfer->get_from_storage;
5612 ok( defined($original_transfer->datecancelled), "Original transfer was cancelled");
5613 is( $original_transfer->cancellation_reason, 'WrongTransfer', "Original transfer cancellation reason is 'WrongTransfer'");
5616 subtest "SendCirculationAlert" => sub {
5619 # When you would unsuspectingly call this unit test (with perl, not prove), you will be bitten by LOCK.
5620 # LOCK will commit changes and ruin your data
5621 # In order to prevent that, we will add KOHA_TESTING to $ENV; see further Circulation.pm
5622 $ENV{KOHA_TESTING} = 1;
5624 # Setup branch, borrowr, and notice
5625 my $library = $builder->build_object({ class => 'Koha::Libraries' });
5626 set_userenv( $library->unblessed);
5627 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5628 C4::Members::Messaging::SetMessagingPreference({
5629 borrowernumber => $patron->id,
5630 message_transport_types => ['sms'],
5631 message_attribute_id => 5
5633 my $item = $builder->build_sample_item();
5634 my $checkin_notice = $builder->build_object({
5635 class => 'Koha::Notice::Templates',
5637 module => 'circulation',
5639 branchcode => $library->branchcode,
5640 name => 'Test Checkin',
5642 content => "Checkins:\n----\n[% biblio.title %]-[% old_checkout.issue_id %]\n----Thank you.",
5643 message_transport_type => 'sms',
5648 # Checkout an item, mark it returned, generate a notice
5649 my $issue_1 = AddIssue( $patron->unblessed, $item->barcode);
5650 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5651 C4::Circulation::SendCirculationAlert({
5653 item => $item->unblessed,
5654 borrower => $patron->unblessed,
5655 branch => $library->branchcode,
5658 my $notice = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'CHECKIN' });
5659 is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\nThank you.", 'Letter generated with expected output on first checkin' );
5660 is($notice->to_address, $patron->smsalertnumber, "Letter has the correct to_address set to smsalertnumber for SMS type notices");
5662 # Checkout an item, mark it returned, generate a notice
5663 my $issue_2 = AddIssue( $patron->unblessed, $item->barcode);
5664 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5665 C4::Circulation::SendCirculationAlert({
5667 item => $item->unblessed,
5668 borrower => $patron->unblessed,
5669 branch => $library->branchcode,
5672 $notice->discard_changes();
5673 is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\n".$item->biblio->title."-".$issue_2->id."\nThank you.", 'Letter appended with expected output on second checkin' );
5677 subtest "GetSoonestRenewDate tests" => sub {
5679 Koha::CirculationRules->set_rule(
5681 categorycode => undef,
5682 branchcode => undef,
5684 rule_name => 'norenewalbefore',
5688 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5689 my $item = $builder->build_sample_item();
5690 my $issue = AddIssue( $patron->unblessed, $item->barcode);
5691 my $datedue = dt_from_string( $issue->date_due() );
5694 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
5695 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
5697 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5698 $datedue->clone->add( days => -7 ),
5699 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5703 # Test 'date' setting for syspref NoRenewalBeforePrecision
5704 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5706 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5707 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
5708 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5712 Koha::CirculationRules->set_rule(
5714 categorycode => undef,
5715 branchcode => undef,
5717 rule_name => 'norenewalbefore',
5718 rule_value => undef,
5723 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5725 'Checkouts without auto-renewal can be renewed immediately if no norenewalbefore'
5728 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5729 $issue->auto_renew(1)->store;
5731 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5732 $datedue->clone->truncate( to => 'day' ),
5733 'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5735 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact' );
5737 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5739 'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5743 $schema->storage->txn_rollback;
5744 C4::Context->clear_syspref_cache();
5745 $branches = Koha::Libraries->search();
5746 for my $branch ( $branches->next ) {
5747 my $key = $branch->branchcode . "_holidays";
5748 $cache->clear_from_cache($key);