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 => 60;
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;
61 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
65 my ( $error, $question, $alert ) = @_;
67 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
68 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
69 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
73 sub test_debarment_on_checkout {
75 my $item = $params->{item};
76 my $library = $params->{library};
77 my $patron = $params->{patron};
78 my $due_date = $params->{due_date} || dt_from_string;
79 my $return_date = $params->{return_date} || dt_from_string;
80 my $expected_expiration_date = $params->{expiration_date};
82 $expected_expiration_date = output_pref(
84 dt => $expected_expiration_date,
90 my $line_number = $caller[2];
91 AddIssue( $patron, $item->barcode, $due_date );
93 my ( undef, $message ) = AddReturn( $item->barcode, $library->{branchcode}, undef, $return_date );
94 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
95 or diag('AddReturn returned message ' . Dumper $message );
96 my $debarments = Koha::Patron::Debarments::GetDebarments(
97 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
98 is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
100 is( $debarments->[0]->{expiration},
101 $expected_expiration_date, 'Test at line ' . $line_number );
102 Koha::Patron::Debarments::DelUniqueDebarment(
103 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
106 my $schema = Koha::Database->schema;
107 $schema->storage->txn_begin;
108 my $builder = t::lib::TestBuilder->new;
109 my $dbh = C4::Context->dbh;
111 # Prevent random failures by mocking ->now
112 my $now_value = dt_from_string;
113 my $mocked_datetime = Test::MockModule->new('DateTime');
114 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
116 my $cache = Koha::Caches->get_instance();
117 $dbh->do(q|DELETE FROM special_holidays|);
118 $dbh->do(q|DELETE FROM repeatable_holidays|);
119 my $branches = Koha::Libraries->search();
120 for my $branch ( $branches->next ) {
121 my $key = $branch->branchcode . "_holidays";
122 $cache->clear_from_cache($key);
125 # Start with a clean slate
126 $dbh->do('DELETE FROM issues');
127 $dbh->do('DELETE FROM borrowers');
129 # Disable recording of the staff who checked out an item until we're ready for it
130 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 0);
132 my $module = Test::MockModule->new('C4::Context');
134 my $library = $builder->build({
137 my $library2 = $builder->build({
140 my $itemtype = $builder->build(
142 source => 'Itemtype',
146 rentalcharge_daily => 0,
147 defaultreplacecost => undef,
152 my $patron_category = $builder->build(
154 source => 'Category',
156 category_type => 'P',
158 BlockExpiredPatronOpacActions => -1, # Pick the pref value
163 my $CircControl = C4::Context->preference('CircControl');
164 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
167 homebranch => $library2->{branchcode},
168 holdingbranch => $library2->{branchcode}
172 branchcode => $library2->{branchcode}
175 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
177 # No userenv, PickupLibrary
178 t::lib::Mocks::mock_preference('IndependentBranches', '0');
179 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
181 C4::Context->preference('CircControl'),
183 'CircControl changed to PickupLibrary'
186 C4::Circulation::_GetCircControlBranch($item, $borrower),
187 $item->{$HomeOrHoldingBranch},
188 '_GetCircControlBranch returned item branch (no userenv defined)'
191 # No userenv, PatronLibrary
192 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
194 C4::Context->preference('CircControl'),
196 'CircControl changed to PatronLibrary'
199 C4::Circulation::_GetCircControlBranch($item, $borrower),
200 $borrower->{branchcode},
201 '_GetCircControlBranch returned borrower branch'
204 # No userenv, ItemHomeLibrary
205 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
207 C4::Context->preference('CircControl'),
209 'CircControl changed to ItemHomeLibrary'
212 $item->{$HomeOrHoldingBranch},
213 C4::Circulation::_GetCircControlBranch($item, $borrower),
214 '_GetCircControlBranch returned item branch'
218 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
219 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
221 # Userenv set, PickupLibrary
222 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
224 C4::Context->preference('CircControl'),
226 'CircControl changed to PickupLibrary'
229 C4::Circulation::_GetCircControlBranch($item, $borrower),
230 $library2->{branchcode},
231 '_GetCircControlBranch returned current branch'
234 # Userenv set, PatronLibrary
235 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
237 C4::Context->preference('CircControl'),
239 'CircControl changed to PatronLibrary'
242 C4::Circulation::_GetCircControlBranch($item, $borrower),
243 $borrower->{branchcode},
244 '_GetCircControlBranch returned borrower branch'
247 # Userenv set, ItemHomeLibrary
248 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
250 C4::Context->preference('CircControl'),
252 'CircControl changed to ItemHomeLibrary'
255 C4::Circulation::_GetCircControlBranch($item, $borrower),
256 $item->{$HomeOrHoldingBranch},
257 '_GetCircControlBranch returned item branch'
260 # Reset initial configuration
261 t::lib::Mocks::mock_preference('CircControl', $CircControl);
263 C4::Context->preference('CircControl'),
265 'CircControl reset to its initial value'
268 # Set a simple circ policy
269 $dbh->do('DELETE FROM circulation_rules');
270 Koha::CirculationRules->set_rules(
272 categorycode => undef,
276 reservesallowed => 25,
278 lengthunit => 'days',
279 renewalsallowed => 1,
281 norenewalbefore => undef,
289 subtest "CanBookBeRenewed AllowRenewalIfOtherItemsAvailable multiple borrowers and items tests" => sub {
292 #Can only reserve from home branch
293 Koha::CirculationRules->set_rule(
297 rule_name => 'holdallowed',
301 Koha::CirculationRules->set_rule(
304 categorycode => undef,
306 rule_name => 'onshelfholds',
311 # Patrons from three different branches
312 my $patron_borrower = $builder->build_object({ class => 'Koha::Patrons' });
313 my $patron_hold_1 = $builder->build_object({ class => 'Koha::Patrons' });
314 my $patron_hold_2 = $builder->build_object({ class => 'Koha::Patrons' });
315 my $biblio = $builder->build_sample_biblio();
317 # Item at each patron branch
318 my $item_1 = $builder->build_sample_item({
319 biblionumber => $biblio->biblionumber,
320 homebranch => $patron_borrower->branchcode
322 my $item_2 = $builder->build_sample_item({
323 biblionumber => $biblio->biblionumber,
324 homebranch => $patron_hold_2->branchcode
326 my $item_3 = $builder->build_sample_item({
327 biblionumber => $biblio->biblionumber,
328 homebranch => $patron_hold_1->branchcode
331 my $issue = AddIssue( $patron_borrower->unblessed, $item_1->barcode);
332 my $datedue = dt_from_string( $issue->date_due() );
333 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
338 branchcode => $patron_hold_1->branchcode,
339 borrowernumber => $patron_hold_1->borrowernumber,
340 biblionumber => $biblio->biblionumber,
342 reservation_date => dt_from_string(),
343 expiration_date => undef,
350 branchcode => $patron_hold_2->branchcode,
351 borrowernumber => $patron_hold_2->borrowernumber,
352 biblionumber => $biblio->biblionumber,
354 reservation_date => dt_from_string(),
355 expiration_date => undef,
360 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
362 my ( $renewokay, $error ) = CanBookBeRenewed($patron_borrower->borrowernumber, $item_1->itemnumber);
363 is( $renewokay, 0, 'Cannot renew, reserved');
364 is( $error, 'on_reserve', 'Cannot renew, reserved (returned error is on_reserve)');
366 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
368 ( $renewokay, $error ) = CanBookBeRenewed($patron_borrower->borrowernumber, $item_1->itemnumber);
369 is( $renewokay, 1, 'Can renew, two items available for two holds');
370 is( $error, undef, 'Can renew, each reserve has an item');
375 subtest "GetIssuingCharges tests" => sub {
377 my $branch_discount = $builder->build_object({ class => 'Koha::Libraries' });
378 my $branch_no_discount = $builder->build_object({ class => 'Koha::Libraries' });
379 Koha::CirculationRules->set_rule(
381 categorycode => undef,
382 branchcode => $branch_discount->branchcode,
384 rule_name => 'rentaldiscount',
388 my $itype_charge = $builder->build_object({
389 class => 'Koha::ItemTypes',
394 my $itype_no_charge = $builder->build_object({
395 class => 'Koha::ItemTypes',
400 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
401 my $item_1 = $builder->build_sample_item({ itype => $itype_charge->itemtype });
402 my $item_2 = $builder->build_sample_item({ itype => $itype_no_charge->itemtype });
404 t::lib::Mocks::mock_userenv({ branchcode => $branch_no_discount->branchcode });
405 # For now the sub always uses the env branch, this should follow CircControl instead
406 my ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
407 is( $charge + 0, 10.00, "Charge fetched correctly when no discount exists");
408 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
409 is( $charge + 0, 0.00, "Charge fetched correctly when no discount exists and no charge");
411 t::lib::Mocks::mock_userenv({ branchcode => $branch_discount->branchcode });
412 # For now the sub always uses the env branch, this should follow CircControl instead
413 ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
414 is( $charge + 0, 8.50, "Charge fetched correctly when discount exists");
415 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
416 is( $charge + 0, 0.00, "Charge fetched correctly when discount exists and no charge");
420 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
421 subtest "CanBookBeRenewed tests" => sub {
424 C4::Context->set_preference('ItemsDeniedRenewal','');
425 # Generate test biblio
426 my $biblio = $builder->build_sample_biblio();
428 my $branch = $library2->{branchcode};
430 my $item_1 = $builder->build_sample_item(
432 biblionumber => $biblio->biblionumber,
434 replacementprice => 12.00,
438 $reused_itemnumber_1 = $item_1->itemnumber;
440 my $item_2 = $builder->build_sample_item(
442 biblionumber => $biblio->biblionumber,
444 replacementprice => 23.00,
448 $reused_itemnumber_2 = $item_2->itemnumber;
450 my $item_3 = $builder->build_sample_item(
452 biblionumber => $biblio->biblionumber,
454 replacementprice => 23.00,
460 my %renewing_borrower_data = (
462 surname => 'Renewal',
463 categorycode => $patron_category->{categorycode},
464 branchcode => $branch,
467 my %reserving_borrower_data = (
468 firstname => 'Katrin',
469 surname => 'Reservation',
470 categorycode => $patron_category->{categorycode},
471 branchcode => $branch,
474 my %hold_waiting_borrower_data = (
476 surname => 'Reservation',
477 categorycode => $patron_category->{categorycode},
478 branchcode => $branch,
481 my %restricted_borrower_data = (
482 firstname => 'Alice',
483 surname => 'Reservation',
484 categorycode => $patron_category->{categorycode},
485 debarred => '3228-01-01',
486 branchcode => $branch,
489 my %expired_borrower_data = (
492 categorycode => $patron_category->{categorycode},
493 branchcode => $branch,
494 dateexpiry => dt_from_string->subtract( months => 1 ),
497 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
498 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
499 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
500 my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
501 my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
503 my $renewing_borrower_obj = Koha::Patrons->find( $renewing_borrowernumber );
504 my $renewing_borrower = $renewing_borrower_obj->unblessed;
505 my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
506 my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
513 my $checkitem = undef;
516 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
517 my $datedue = dt_from_string( $issue->date_due() );
518 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
520 my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
521 $datedue = dt_from_string( $issue->date_due() );
522 is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
525 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
526 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
528 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
529 is( $renewokay, 1, 'Can renew, no holds for this title or item');
532 # Biblio-level hold, renewal test
535 branchcode => $branch,
536 borrowernumber => $reserving_borrowernumber,
537 biblionumber => $biblio->biblionumber,
538 priority => $priority,
539 reservation_date => $resdate,
540 expiration_date => $expdate,
542 itemnumber => $checkitem,
547 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
548 Koha::CirculationRules->set_rule(
550 categorycode => undef,
553 rule_name => 'onshelfholds',
557 Koha::CirculationRules->set_rule(
559 categorycode => undef,
562 rule_name => 'renewalsallowed',
566 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
567 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
568 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
569 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
570 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
572 # Now let's add an item level hold, we should no longer be able to renew the item
573 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
575 borrowernumber => $hold_waiting_borrowernumber,
576 biblionumber => $biblio->biblionumber,
577 itemnumber => $item_1->itemnumber,
578 branchcode => $branch,
582 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
583 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
586 # 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
587 # be able to renew these items
588 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
590 borrowernumber => $hold_waiting_borrowernumber,
591 biblionumber => $biblio->biblionumber,
592 itemnumber => $item_3->itemnumber,
593 branchcode => $branch,
598 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
599 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
600 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
601 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
602 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
604 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
605 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
606 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
608 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
609 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
610 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
612 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
613 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
614 AddIssue($reserving_borrower, $item_3->barcode);
615 my $reserve = $dbh->selectrow_hashref(
616 'SELECT * FROM old_reserves WHERE reserve_id = ?',
620 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
622 # Item-level hold, renewal test
625 branchcode => $branch,
626 borrowernumber => $reserving_borrowernumber,
627 biblionumber => $biblio->biblionumber,
628 priority => $priority,
629 reservation_date => $resdate,
630 expiration_date => $expdate,
632 itemnumber => $item_1->itemnumber,
637 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
638 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
639 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
641 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
642 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
644 # Items can't fill hold for reasons
645 $item_1->notforloan(1)->store;
646 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
647 is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
648 $item_1->set({notforloan => 0, itype => $itemtype })->store;
650 # FIXME: Add more for itemtype not for loan etc.
652 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
653 my $item_5 = $builder->build_sample_item(
655 biblionumber => $biblio->biblionumber,
657 replacementprice => 23.00,
661 my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
662 is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
664 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
665 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
666 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
667 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
668 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
669 is( $error, 'restriction', "Correct error returned");
671 # Users cannot renew an overdue item
672 my $item_6 = $builder->build_sample_item(
674 biblionumber => $biblio->biblionumber,
676 replacementprice => 23.00,
681 my $item_7 = $builder->build_sample_item(
683 biblionumber => $biblio->biblionumber,
685 replacementprice => 23.00,
690 my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
691 is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
693 my $now = dt_from_string();
694 my $five_weeks = DateTime::Duration->new(weeks => 5);
695 my $five_weeks_ago = $now - $five_weeks;
696 t::lib::Mocks::mock_preference('finesMode', 'production');
698 my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
699 is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
701 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
702 C4::Overdues::UpdateFine(
704 issue_id => $passeddatedue1->id(),
705 itemnumber => $item_7->itemnumber,
706 borrowernumber => $renewing_borrower->{borrowernumber},
708 due => Koha::DateUtils::output_pref($five_weeks_ago)
712 # Make sure fine calculation isn't skipped when adding renewal
713 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
715 t::lib::Mocks::mock_preference('RenewalLog', 0);
716 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
717 my %params_renewal = (
718 timestamp => { -like => $date . "%" },
719 module => "CIRCULATION",
723 timestamp => { -like => $date . "%" },
724 module => "CIRCULATION",
727 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
728 my $dt = dt_from_string();
729 Time::Fake->offset( $dt->epoch );
730 my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
731 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
732 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
733 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
736 t::lib::Mocks::mock_preference('RenewalLog', 1);
737 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
738 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
739 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
740 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
741 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
743 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
744 is( $fines->count, 2, 'AddRenewal left both fines' );
745 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
746 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
749 t::lib::Mocks::mock_preference('OverduesBlockRenewing','allow');
750 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
751 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
752 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
753 is( $renewokay, 1, '(Bug 8236), Can renew, this item is overdue but not pref does not block');
755 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
756 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
757 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is not overdue but patron has overdues');
758 is( $error, 'overdue', "Correct error returned");
759 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
760 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue so patron has overdues');
761 is( $error, 'overdue', "Correct error returned");
763 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
764 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
765 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
766 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
767 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
768 is( $error, 'overdue', "Correct error returned");
771 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
772 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
773 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
774 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
775 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
776 $new_log_size = Koha::ActionLogs->count( \%params_issue );
777 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
779 $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
782 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
786 # Test automatic renewal before value for "norenewalbefore" in policy is set
787 # In this case automatic renewal is not permitted prior to due date
788 my $item_4 = $builder->build_sample_item(
790 biblionumber => $biblio->biblionumber,
792 replacementprice => 16.00,
797 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
799 ( $renewokay, $error, $info ) =
800 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
801 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
802 is( $error, 'auto_too_soon',
803 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
804 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'" );
807 branchcode => $branch,
808 borrowernumber => $reserving_borrowernumber,
809 biblionumber => $biblio->biblionumber,
810 itemnumber => $bibitems,
811 priority => $priority,
812 reservation_date => $resdate,
813 expiration_date => $expdate,
816 itemnumber => $item_4->itemnumber,
820 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
821 is( $renewokay, 0, 'Still should not be able to renew' );
822 is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' );
823 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, undef, 1 );
824 is( $renewokay, 0, 'Still should not be able to renew' );
825 is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' );
826 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'" );
827 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
828 is( $renewokay, 0, 'Still should not be able to renew' );
829 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
830 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1, 1 );
831 is( $renewokay, 0, 'Still should not be able to renew' );
832 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
833 $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
834 Koha::Cache::Memory::Lite->flush();
835 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
836 is( $renewokay, 0, 'Still should not be able to renew' );
837 is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
838 ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
842 $renewing_borrower_obj->autorenew_checkouts(0)->store;
843 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
844 is( $renewokay, 1, 'No renewal before is undef, but patron opted out of auto_renewal' );
845 $renewing_borrower_obj->autorenew_checkouts(1)->store;
849 # Test premature manual renewal
850 Koha::CirculationRules->set_rule(
852 categorycode => undef,
855 rule_name => 'norenewalbefore',
860 ( $renewokay, $error, $info ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
861 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
862 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
863 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
866 # Test premature automatic renewal
867 ( $renewokay, $error, $info ) =
868 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
869 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
870 is( $error, 'auto_too_soon',
871 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
873 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'auto_too_soon'");
875 $renewing_borrower_obj->autorenew_checkouts(0)->store;
876 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
877 is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' );
878 is( $error, 'too_soon', 'Error is too_soon, no auto' );
879 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
880 $renewing_borrower_obj->autorenew_checkouts(1)->store;
882 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
883 # and test automatic renewal again
884 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
885 Koha::Cache::Memory::Lite->flush();
886 ( $renewokay, $error, $info ) =
887 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
888 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
889 is( $error, 'auto_too_soon',
890 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
892 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
894 $renewing_borrower_obj->autorenew_checkouts(0)->store;
895 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
896 is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' );
897 is( $error, 'too_soon', 'Error is too_soon, no auto' );
898 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
899 $renewing_borrower_obj->autorenew_checkouts(1)->store;
901 # Change policy so that loans can be renewed 99 days prior to the due date
902 # and test automatic renewal again
903 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
904 Koha::Cache::Memory::Lite->flush();
905 ( $renewokay, $error ) =
906 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
907 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
908 is( $error, 'auto_renew',
909 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
912 $renewing_borrower_obj->autorenew_checkouts(0)->store;
913 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
914 is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' );
915 $renewing_borrower_obj->autorenew_checkouts(1)->store;
917 subtest "too_late_renewal / no_auto_renewal_after" => sub {
919 my $item_to_auto_renew = $builder->build_sample_item(
921 biblionumber => $biblio->biblionumber,
926 my $ten_days_before = dt_from_string->add( days => -10 );
927 my $ten_days_ahead = dt_from_string->add( days => 10 );
928 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
930 Koha::CirculationRules->set_rules(
932 categorycode => undef,
936 norenewalbefore => '7',
937 no_auto_renewal_after => '9',
941 ( $renewokay, $error ) =
942 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
943 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
944 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
946 Koha::CirculationRules->set_rules(
948 categorycode => undef,
952 norenewalbefore => '7',
953 no_auto_renewal_after => '10',
957 ( $renewokay, $error ) =
958 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
959 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
960 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
962 Koha::CirculationRules->set_rules(
964 categorycode => undef,
968 norenewalbefore => '7',
969 no_auto_renewal_after => '11',
973 ( $renewokay, $error ) =
974 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
975 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
976 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
978 Koha::CirculationRules->set_rules(
980 categorycode => undef,
984 norenewalbefore => '10',
985 no_auto_renewal_after => '11',
989 ( $renewokay, $error ) =
990 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
991 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
992 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
994 Koha::CirculationRules->set_rules(
996 categorycode => undef,
1000 norenewalbefore => '10',
1001 no_auto_renewal_after => undef,
1002 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1006 ( $renewokay, $error ) =
1007 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1008 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1009 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1011 Koha::CirculationRules->set_rules(
1013 categorycode => undef,
1014 branchcode => undef,
1017 norenewalbefore => '7',
1018 no_auto_renewal_after => '15',
1019 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1023 ( $renewokay, $error ) =
1024 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1025 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1026 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1028 Koha::CirculationRules->set_rules(
1030 categorycode => undef,
1031 branchcode => undef,
1034 norenewalbefore => '10',
1035 no_auto_renewal_after => undef,
1036 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
1040 ( $renewokay, $error ) =
1041 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1042 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1043 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1046 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
1048 my $item_to_auto_renew = $builder->build_sample_item(
1050 biblionumber => $biblio->biblionumber,
1055 my $ten_days_before = dt_from_string->add( days => -10 );
1056 my $ten_days_ahead = dt_from_string->add( days => 10 );
1057 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1059 Koha::CirculationRules->set_rules(
1061 categorycode => undef,
1062 branchcode => undef,
1065 norenewalbefore => '10',
1066 no_auto_renewal_after => '11',
1070 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
1071 C4::Context->set_preference('OPACFineNoRenewals','10');
1072 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1073 my $fines_amount = 5;
1074 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
1075 $account->add_debit(
1077 amount => $fines_amount,
1078 interface => 'test',
1080 item_id => $item_to_auto_renew->itemnumber,
1081 description => "Some fines"
1083 )->status('RETURNED')->store;
1084 ( $renewokay, $error ) =
1085 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1086 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1087 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
1089 $account->add_debit(
1091 amount => $fines_amount,
1092 interface => 'test',
1094 item_id => $item_to_auto_renew->itemnumber,
1095 description => "Some fines"
1097 )->status('RETURNED')->store;
1098 ( $renewokay, $error ) =
1099 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1100 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1101 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
1103 $account->add_debit(
1105 amount => $fines_amount,
1106 interface => 'test',
1108 item_id => $item_to_auto_renew->itemnumber,
1109 description => "Some fines"
1111 )->status('RETURNED')->store;
1112 ( $renewokay, $error ) =
1113 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1114 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1115 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
1117 $account->add_credit(
1119 amount => $fines_amount,
1120 interface => 'test',
1122 description => "Some payment"
1125 ( $renewokay, $error ) =
1126 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1127 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1128 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1130 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
1131 ( $renewokay, $error ) =
1132 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1133 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1134 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1136 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
1137 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1140 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
1142 my $item_to_auto_renew = $builder->build_sample_item(
1144 biblionumber => $biblio->biblionumber,
1149 Koha::CirculationRules->set_rules(
1151 categorycode => undef,
1152 branchcode => undef,
1155 norenewalbefore => 10,
1156 no_auto_renewal_after => 11,
1161 my $ten_days_before = dt_from_string->add( days => -10 );
1162 my $ten_days_ahead = dt_from_string->add( days => 10 );
1164 # Patron is expired and BlockExpiredPatronOpacActions=0
1165 # => auto renew is allowed
1166 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
1167 my $patron = $expired_borrower;
1168 my $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1169 ( $renewokay, $error ) =
1170 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1171 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1172 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
1173 Koha::Checkouts->find( $checkout->issue_id )->delete;
1176 # Patron is expired and BlockExpiredPatronOpacActions=1
1177 # => auto renew is not allowed
1178 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1179 $patron = $expired_borrower;
1180 $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1181 ( $renewokay, $error ) =
1182 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1183 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1184 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
1185 Koha::Checkouts->find( $checkout->issue_id )->delete;
1188 # Patron is not expired and BlockExpiredPatronOpacActions=1
1189 # => auto renew is allowed
1190 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1191 $patron = $renewing_borrower;
1192 $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, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1197 Koha::Checkouts->find( $checkout->issue_id )->delete;
1200 subtest "GetLatestAutoRenewDate" => sub {
1202 my $item_to_auto_renew = $builder->build_sample_item(
1204 biblionumber => $biblio->biblionumber,
1209 my $ten_days_before = dt_from_string->add( days => -10 );
1210 my $ten_days_ahead = dt_from_string->add( days => 10 );
1211 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1212 Koha::CirculationRules->set_rules(
1214 categorycode => undef,
1215 branchcode => undef,
1218 norenewalbefore => '7',
1219 no_auto_renewal_after => '',
1220 no_auto_renewal_after_hard_limit => undef,
1224 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1225 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' );
1226 my $five_days_before = dt_from_string->add( days => -5 );
1227 Koha::CirculationRules->set_rules(
1229 categorycode => undef,
1230 branchcode => undef,
1233 norenewalbefore => '10',
1234 no_auto_renewal_after => '5',
1235 no_auto_renewal_after_hard_limit => undef,
1239 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1240 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1241 $five_days_before->truncate( to => 'minute' ),
1242 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1244 my $five_days_ahead = dt_from_string->add( days => 5 );
1245 $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1246 $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1247 $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1248 Koha::Cache::Memory::Lite->flush();
1249 Koha::CirculationRules->set_rules(
1251 categorycode => undef,
1252 branchcode => undef,
1255 norenewalbefore => '10',
1256 no_auto_renewal_after => '15',
1257 no_auto_renewal_after_hard_limit => undef,
1261 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1262 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1263 $five_days_ahead->truncate( to => 'minute' ),
1264 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1266 my $two_days_ahead = dt_from_string->add( days => 2 );
1267 Koha::CirculationRules->set_rules(
1269 categorycode => undef,
1270 branchcode => undef,
1273 norenewalbefore => '10',
1274 no_auto_renewal_after => '',
1275 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1279 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1280 is( $latest_auto_renew_date->truncate( to => 'day' ),
1281 $two_days_ahead->truncate( to => 'day' ),
1282 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1284 Koha::CirculationRules->set_rules(
1286 categorycode => undef,
1287 branchcode => undef,
1290 norenewalbefore => '10',
1291 no_auto_renewal_after => '15',
1292 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1296 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1297 is( $latest_auto_renew_date->truncate( to => 'day' ),
1298 $two_days_ahead->truncate( to => 'day' ),
1299 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1305 # set policy to forbid renewals
1306 Koha::CirculationRules->set_rules(
1308 categorycode => undef,
1309 branchcode => undef,
1312 norenewalbefore => undef,
1313 renewalsallowed => 0,
1318 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1319 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1320 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1322 # Too many unseen renewals
1323 Koha::CirculationRules->set_rules(
1325 categorycode => undef,
1326 branchcode => undef,
1329 unseen_renewals_allowed => 2,
1330 renewalsallowed => 10,
1334 t::lib::Mocks::mock_preference('UnseenRenewals', 1);
1335 $dbh->do('UPDATE issues SET unseen_renewals = 2 where borrowernumber = ? AND itemnumber = ?', undef, ($renewing_borrowernumber, $item_1->itemnumber));
1336 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1337 is( $renewokay, 0, 'Cannot renew, 0 unseen renewals allowed');
1338 is( $error, 'too_unseen', 'Cannot renew, returned code is too_unseen');
1339 Koha::CirculationRules->set_rules(
1341 categorycode => undef,
1342 branchcode => undef,
1345 norenewalbefore => undef,
1346 renewalsallowed => 0,
1350 t::lib::Mocks::mock_preference('UnseenRenewals', 0);
1352 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1353 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1354 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1356 C4::Overdues::UpdateFine(
1358 issue_id => $issue->id(),
1359 itemnumber => $item_1->itemnumber,
1360 borrowernumber => $renewing_borrower->{borrowernumber},
1363 due => Koha::DateUtils::output_pref($datedue)
1367 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
1368 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1369 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1370 is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1371 is( $line->amount+0, 15, 'Account line amount is 15.00' );
1372 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
1374 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1375 is( $offset->type, 'CREATE', 'Account offset type is CREATE' );
1376 is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1378 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1379 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1381 LostItem( $item_1->itemnumber, 'test', 1 );
1383 $line = Koha::Account::Lines->find($line->id);
1384 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1385 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1387 my $item = Koha::Items->find($item_1->itemnumber);
1388 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1389 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1390 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1392 my $total_due = $dbh->selectrow_array(
1393 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1394 undef, $renewing_borrower->{borrowernumber}
1397 is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1399 C4::Context->dbh->do("DELETE FROM accountlines");
1401 C4::Overdues::UpdateFine(
1403 issue_id => $issue2->id(),
1404 itemnumber => $item_2->itemnumber,
1405 borrowernumber => $renewing_borrower->{borrowernumber},
1408 due => Koha::DateUtils::output_pref($datedue)
1412 LostItem( $item_2->itemnumber, 'test', 0 );
1414 my $item2 = Koha::Items->find($item_2->itemnumber);
1415 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1416 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1418 $total_due = $dbh->selectrow_array(
1419 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1420 undef, $renewing_borrower->{borrowernumber}
1423 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1425 my $future = dt_from_string();
1426 $future->add( days => 7 );
1427 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1428 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1430 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1431 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1432 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1433 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1434 LostItem( $item_3->itemnumber, 'test', 0 );
1435 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1436 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1438 $accountline->description,
1439 sprintf( "%s %s %s",
1440 $item_3->biblio->title || '',
1441 $item_3->barcode || '',
1442 $item_3->itemcallnumber || '' ),
1443 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1447 t::lib::Mocks::mock_preference('UseRecalls', 1);
1448 Koha::CirculationRules->set_rules({
1449 categorycode => undef,
1450 branchcode => undef,
1453 recalls_allowed => 10,
1454 renewalsallowed => 5,
1457 my $recall_borrower = $builder->build_object({ class => 'Koha::Patrons' });
1458 my $recall_biblio = $builder->build_object({ class => 'Koha::Biblios' });
1459 my $recall_item1 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $recall_biblio->biblionumber } });
1460 my $recall_item2 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $recall_biblio->biblionumber } });
1462 AddIssue( $renewing_borrower, $recall_item1->barcode );
1464 # item-level and this item: renewal not allowed
1465 my $recall = Koha::Recall->new({
1466 biblio_id => $recall_item1->biblionumber,
1467 item_id => $recall_item1->itemnumber,
1468 patron_id => $recall_borrower->borrowernumber,
1469 pickup_library_id => $recall_borrower->branchcode,
1472 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1473 is( $error, 'recalled', 'Cannot renew item that has been recalled' );
1474 $recall->set_cancelled;
1476 # biblio-level requested recall: renewal not allowed
1477 $recall = Koha::Recall->new({
1478 biblio_id => $recall_item1->biblionumber,
1480 patron_id => $recall_borrower->borrowernumber,
1481 pickup_library_id => $recall_borrower->branchcode,
1484 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1485 is( $error, 'recalled', 'Cannot renew item if biblio is recalled and has no item allocated' );
1486 $recall->set_cancelled;
1488 # item-level and not this item: renewal allowed
1489 $recall = Koha::Recall->new({
1490 biblio_id => $recall_item2->biblionumber,
1491 item_id => $recall_item2->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( $renewokay, 1, 'Can renew item if item-level recall on biblio is not on this item' );
1498 $recall->set_cancelled;
1500 # biblio-level waiting recall: renewal 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 $recall->set_waiting({ item => $recall_item1 });
1509 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1510 is( $renewokay, 1, 'Can renew item if biblio-level recall has already been allocated an item' );
1511 $recall->set_cancelled;
1514 subtest "GetUpcomingDueIssues" => sub {
1517 my $branch = $library2->{branchcode};
1519 #Create another record
1520 my $biblio2 = $builder->build_sample_biblio();
1523 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1524 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1525 my $item_3 = $builder->build_sample_item(
1527 biblionumber => $biblio2->biblionumber,
1535 my %a_borrower_data = (
1536 firstname => 'Fridolyn',
1537 surname => 'SOMERS',
1538 categorycode => $patron_category->{categorycode},
1539 branchcode => $branch,
1542 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1543 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1545 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1546 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1547 my $today = DateTime->today(time_zone => C4::Context->tz());
1549 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1550 my $datedue = dt_from_string( $issue->date_due() );
1551 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1552 my $datedue2 = dt_from_string( $issue->date_due() );
1556 # GetUpcomingDueIssues tests
1558 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1559 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1562 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1563 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1564 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1567 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1568 is ( scalar( @$upcoming_dues ), 1,
1569 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1572 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1574 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1576 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1577 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1579 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1580 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1582 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1583 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1585 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1586 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1588 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1589 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1591 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1592 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1596 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1597 my $branch = $library2->{branchcode};
1599 my $biblio = $builder->build_sample_biblio();
1602 my $item = $builder->build_sample_item(
1604 biblionumber => $biblio->biblionumber,
1611 my %a_borrower_data = (
1612 firstname => 'Kyle',
1614 categorycode => $patron_category->{categorycode},
1615 branchcode => $branch,
1618 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1620 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1621 my $issue = AddIssue( $borrower, $item->barcode );
1624 issue_id => $issue->id(),
1625 itemnumber => $item->itemnumber,
1626 borrowernumber => $borrowernumber,
1632 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1633 my $count = $hr->{count};
1635 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1638 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1640 my $biblio = $builder->build_sample_biblio();
1641 my $item_1 = $builder->build_sample_item(
1643 biblionumber => $biblio->biblionumber,
1644 library => $library2->{branchcode},
1647 my $item_2= $builder->build_sample_item(
1649 biblionumber => $biblio->biblionumber,
1650 library => $library2->{branchcode},
1651 itype => $item_1->effective_itemtype,
1655 Koha::CirculationRules->set_rules(
1657 categorycode => undef,
1658 itemtype => $item_1->effective_itemtype,
1659 branchcode => undef,
1661 reservesallowed => 25,
1662 holds_per_record => 25,
1664 lengthunit => 'days',
1665 renewalsallowed => 1,
1667 norenewalbefore => undef,
1677 my $borrowernumber1 = Koha::Patron->new({
1678 firstname => 'Kyle',
1680 categorycode => $patron_category->{categorycode},
1681 branchcode => $library2->{branchcode},
1682 })->store->borrowernumber;
1683 my $borrowernumber2 = Koha::Patron->new({
1684 firstname => 'Chelsea',
1686 categorycode => $patron_category->{categorycode},
1687 branchcode => $library2->{branchcode},
1688 })->store->borrowernumber;
1689 my $patron_category_2 = $builder->build(
1691 source => 'Category',
1693 category_type => 'P',
1695 BlockExpiredPatronOpacActions => -1, # Pick the pref value
1699 my $borrowernumber3 = Koha::Patron->new({
1700 firstname => 'Carnegie',
1702 categorycode => $patron_category_2->{categorycode},
1703 branchcode => $library2->{branchcode},
1704 })->store->borrowernumber;
1706 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1707 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1709 my $issue = AddIssue( $borrower1, $item_1->barcode );
1711 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1712 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1716 branchcode => $library2->{branchcode},
1717 borrowernumber => $borrowernumber2,
1718 biblionumber => $biblio->biblionumber,
1723 Koha::CirculationRules->set_rules(
1725 categorycode => undef,
1726 itemtype => $item_1->effective_itemtype,
1727 branchcode => undef,
1733 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1734 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1735 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1737 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1738 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1739 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1741 Koha::CirculationRules->set_rules(
1743 categorycode => undef,
1744 itemtype => $item_1->effective_itemtype,
1745 branchcode => undef,
1751 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1752 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1753 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1755 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1756 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1757 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1761 branchcode => $library2->{branchcode},
1762 borrowernumber => $borrowernumber3,
1763 biblionumber => $biblio->biblionumber,
1768 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1769 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' );
1771 my $item_3= $builder->build_sample_item(
1773 biblionumber => $biblio->biblionumber,
1774 library => $library2->{branchcode},
1775 itype => $item_1->effective_itemtype,
1779 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1780 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' );
1782 Koha::CirculationRules->set_rules(
1784 categorycode => $patron_category_2->{categorycode},
1785 itemtype => $item_1->effective_itemtype,
1786 branchcode => undef,
1788 reservesallowed => 0,
1793 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1794 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' );
1796 Koha::CirculationRules->set_rules(
1798 categorycode => $patron_category_2->{categorycode},
1799 itemtype => $item_1->effective_itemtype,
1800 branchcode => undef,
1802 reservesallowed => 25,
1807 # Setting item not checked out to be not for loan but holdable
1808 $item_2->notforloan(-1)->store;
1810 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1811 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' );
1813 my $mock_circ = Test::MockModule->new("C4::Circulation");
1814 $mock_circ->mock( CanItemBeReserved => sub {
1816 return { status => 'no' }
1819 $item_2->notforloan(0)->store;
1821 # Two items total, one item available, one issued, two holds on record
1824 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1825 } [], "CanItemBeReserved not called when there are more possible holds than available items";
1826 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1828 $item_3 = $builder->build_sample_item(
1830 biblionumber => $biblio->biblionumber,
1831 library => $library2->{branchcode},
1832 itype => $item_1->effective_itemtype,
1836 Koha::CirculationRules->set_rules(
1838 categorycode => undef,
1839 itemtype => $item_1->effective_itemtype,
1840 branchcode => undef,
1842 reservesallowed => 0,
1848 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1849 } ["Checked","Checked"], "CanItemBeReserved only called once per available item if it returns a negative result for all items for a borrower";
1850 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1855 # Don't allow renewing onsite checkout
1856 my $branch = $library->{branchcode};
1858 #Create another record
1859 my $biblio = $builder->build_sample_biblio();
1861 my $item = $builder->build_sample_item(
1863 biblionumber => $biblio->biblionumber,
1869 my $borrowernumber = Koha::Patron->new({
1872 categorycode => $patron_category->{categorycode},
1873 branchcode => $branch,
1874 })->store->borrowernumber;
1876 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1878 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1879 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1880 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1881 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1885 my $library = $builder->build({ source => 'Branch' });
1887 my $biblio = $builder->build_sample_biblio();
1889 my $item = $builder->build_sample_item(
1891 biblionumber => $biblio->biblionumber,
1892 library => $library->{branchcode},
1897 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1899 my $issue = AddIssue( $patron, $item->barcode );
1902 issue_id => $issue->id(),
1903 itemnumber => $item->itemnumber,
1904 borrowernumber => $patron->{borrowernumber},
1911 issue_id => $issue->id(),
1912 itemnumber => $item->itemnumber,
1913 borrowernumber => $patron->{borrowernumber},
1918 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1921 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1924 my $homebranch = $builder->build( { source => 'Branch' } );
1925 my $holdingbranch = $builder->build( { source => 'Branch' } );
1926 my $otherbranch = $builder->build( { source => 'Branch' } );
1927 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1928 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1930 my $item = $builder->build_sample_item(
1932 homebranch => $homebranch->{branchcode},
1933 holdingbranch => $holdingbranch->{branchcode},
1936 Koha::CirculationRules->set_rules(
1938 categorycode => undef,
1939 itemtype => $item->effective_itemtype,
1940 branchcode => undef,
1942 reservesallowed => 25,
1944 lengthunit => 'days',
1945 renewalsallowed => 1,
1947 norenewalbefore => undef,
1956 set_userenv($holdingbranch);
1958 my $issue = AddIssue( $patron_1->unblessed, $item->barcode );
1959 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1961 my ( $error, $question, $alerts );
1963 # AllowReturnToBranch == anywhere
1964 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1965 ## Test that unknown barcodes don't generate internal server errors
1966 set_userenv($homebranch);
1967 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1968 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1969 ## Can be issued from homebranch
1970 set_userenv($homebranch);
1971 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1972 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1973 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1974 ## Can be issued from holdingbranch
1975 set_userenv($holdingbranch);
1976 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1977 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1978 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1979 ## Can be issued from another branch
1980 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1981 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1982 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1984 # AllowReturnToBranch == holdingbranch
1985 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1986 ## Cannot be issued from homebranch
1987 set_userenv($homebranch);
1988 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1989 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1990 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1991 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1992 ## Can be issued from holdinbranch
1993 set_userenv($holdingbranch);
1994 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1995 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1996 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1997 ## Cannot be issued from another branch
1998 set_userenv($otherbranch);
1999 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2000 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2001 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2002 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
2004 # AllowReturnToBranch == homebranch
2005 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2006 ## Can be issued from holdinbranch
2007 set_userenv($homebranch);
2008 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2009 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2010 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2011 ## Cannot be issued from holdinbranch
2012 set_userenv($holdingbranch);
2013 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2014 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2015 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2016 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2017 ## Cannot be issued from holdinbranch
2018 set_userenv($otherbranch);
2019 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2020 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2021 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2022 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2024 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2027 subtest 'AddIssue & AllowReturnToBranch' => sub {
2030 my $homebranch = $builder->build( { source => 'Branch' } );
2031 my $holdingbranch = $builder->build( { source => 'Branch' } );
2032 my $otherbranch = $builder->build( { source => 'Branch' } );
2033 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2034 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2036 my $item = $builder->build_sample_item(
2038 homebranch => $homebranch->{branchcode},
2039 holdingbranch => $holdingbranch->{branchcode},
2043 set_userenv($holdingbranch);
2045 my $ref_issue = 'Koha::Checkout';
2046 my $issue = AddIssue( $patron_1, $item->barcode );
2048 my ( $error, $question, $alerts );
2050 # AllowReturnToBranch == homebranch
2051 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2052 ## Can be issued from homebranch
2053 set_userenv($homebranch);
2054 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
2055 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2056 ## Can be issued from holdinbranch
2057 set_userenv($holdingbranch);
2058 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
2059 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2060 ## Can be issued from another branch
2061 set_userenv($otherbranch);
2062 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
2063 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2065 # AllowReturnToBranch == holdinbranch
2066 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2067 ## Cannot be issued from homebranch
2068 set_userenv($homebranch);
2069 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
2070 ## Can be issued from holdingbranch
2071 set_userenv($holdingbranch);
2072 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
2073 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2074 ## Cannot be issued from another branch
2075 set_userenv($otherbranch);
2076 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
2078 # AllowReturnToBranch == homebranch
2079 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2080 ## Can be issued from homebranch
2081 set_userenv($homebranch);
2082 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
2083 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2084 ## Cannot be issued from holdinbranch
2085 set_userenv($holdingbranch);
2086 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
2087 ## Cannot be issued from another branch
2088 set_userenv($otherbranch);
2089 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
2090 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2093 subtest 'AddIssue | recalls' => sub {
2096 t::lib::Mocks::mock_preference("UseRecalls", 1);
2097 t::lib::Mocks::mock_preference("item-level_itypes", 1);
2098 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2099 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2100 my $item = $builder->build_sample_item;
2101 Koha::CirculationRules->set_rules({
2102 branchcode => undef,
2104 categorycode => undef,
2106 recalls_allowed => 10,
2110 # checking out item that they have recalled
2111 my $recall1 = Koha::Recall->new(
2112 { patron_id => $patron1->borrowernumber,
2113 biblio_id => $item->biblionumber,
2114 item_id => $item->itemnumber,
2116 pickup_library_id => $patron1->branchcode,
2119 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall1->id } );
2120 $recall1 = Koha::Recalls->find( $recall1->id );
2121 is( $recall1->fulfilled, 1, 'Recall was fulfilled when patron checked out item' );
2122 AddReturn( $item->barcode, $item->homebranch );
2124 # this item is has a recall request. cancel recall
2125 my $recall2 = Koha::Recall->new(
2126 { patron_id => $patron2->borrowernumber,
2127 biblio_id => $item->biblionumber,
2128 item_id => $item->itemnumber,
2130 pickup_library_id => $patron2->branchcode,
2133 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall2->id, cancel_recall => 'cancel' } );
2134 $recall2 = Koha::Recalls->find( $recall2->id );
2135 is( $recall2->cancelled, 1, 'Recall was cancelled when patron checked out item' );
2136 AddReturn( $item->barcode, $item->homebranch );
2138 # this item is waiting to fulfill a recall. revert recall
2139 my $recall3 = Koha::Recall->new(
2140 { patron_id => $patron2->borrowernumber,
2141 biblio_id => $item->biblionumber,
2142 item_id => $item->itemnumber,
2144 pickup_library_id => $patron2->branchcode,
2147 $recall3->set_waiting;
2148 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall3->id, cancel_recall => 'revert' } );
2149 $recall3 = Koha::Recalls->find( $recall3->id );
2150 is( $recall3->requested, 1, 'Recall was reverted from waiting when patron checked out item' );
2151 AddReturn( $item->barcode, $item->homebranch );
2155 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
2158 my $library = $builder->build( { source => 'Branch' } );
2159 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2160 my $item_1 = $builder->build_sample_item(
2162 library => $library->{branchcode},
2165 my $item_2 = $builder->build_sample_item(
2167 library => $library->{branchcode},
2170 Koha::CirculationRules->set_rules(
2172 categorycode => undef,
2174 branchcode => $library->{branchcode},
2176 reservesallowed => 25,
2178 lengthunit => 'days',
2179 renewalsallowed => 1,
2181 norenewalbefore => undef,
2191 my ( $error, $question, $alerts );
2193 # Patron cannot issue item_1, they have overdues
2194 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
2195 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, $yesterday ); # Add an overdue
2197 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
2198 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2199 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
2200 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
2202 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
2203 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2204 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2205 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
2207 # Patron cannot issue item_1, they are debarred
2208 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
2209 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
2210 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2211 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2212 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
2214 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
2215 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2216 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2217 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
2220 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
2223 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2224 my $patron_category_x = $builder->build_object(
2226 class => 'Koha::Patron::Categories',
2227 value => { category_type => 'X' }
2230 my $patron = $builder->build_object(
2232 class => 'Koha::Patrons',
2234 categorycode => $patron_category_x->categorycode,
2235 gonenoaddress => undef,
2242 my $item_1 = $builder->build_sample_item(
2244 library => $library->{branchcode},
2248 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
2249 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
2251 # TODO There are other tests to provide here
2254 subtest 'MultipleReserves' => sub {
2257 my $biblio = $builder->build_sample_biblio();
2259 my $branch = $library2->{branchcode};
2261 my $item_1 = $builder->build_sample_item(
2263 biblionumber => $biblio->biblionumber,
2265 replacementprice => 12.00,
2270 my $item_2 = $builder->build_sample_item(
2272 biblionumber => $biblio->biblionumber,
2274 replacementprice => 12.00,
2281 my $resdate = undef;
2282 my $expdate = undef;
2284 my $checkitem = undef;
2287 my %renewing_borrower_data = (
2288 firstname => 'John',
2289 surname => 'Renewal',
2290 categorycode => $patron_category->{categorycode},
2291 branchcode => $branch,
2293 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
2294 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
2295 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
2296 my $datedue = dt_from_string( $issue->date_due() );
2297 is (defined $issue->date_due(), 1, "item 1 checked out");
2298 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
2300 my %reserving_borrower_data1 = (
2301 firstname => 'Katrin',
2302 surname => 'Reservation',
2303 categorycode => $patron_category->{categorycode},
2304 branchcode => $branch,
2306 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
2309 branchcode => $branch,
2310 borrowernumber => $reserving_borrowernumber1,
2311 biblionumber => $biblio->biblionumber,
2312 priority => $priority,
2313 reservation_date => $resdate,
2314 expiration_date => $expdate,
2316 itemnumber => $checkitem,
2321 my %reserving_borrower_data2 = (
2322 firstname => 'Kirk',
2323 surname => 'Reservation',
2324 categorycode => $patron_category->{categorycode},
2325 branchcode => $branch,
2327 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
2330 branchcode => $branch,
2331 borrowernumber => $reserving_borrowernumber2,
2332 biblionumber => $biblio->biblionumber,
2333 priority => $priority,
2334 reservation_date => $resdate,
2335 expiration_date => $expdate,
2337 itemnumber => $checkitem,
2343 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2344 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2347 my $item_3 = $builder->build_sample_item(
2349 biblionumber => $biblio->biblionumber,
2351 replacementprice => 12.00,
2357 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2358 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2362 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2365 my $library = $builder->build( { source => 'Branch' } );
2366 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2368 my $biblionumber = $builder->build_sample_biblio(
2370 branchcode => $library->{branchcode},
2373 my $item_1 = $builder->build_sample_item(
2375 biblionumber => $biblionumber,
2376 library => $library->{branchcode},
2380 my $item_2 = $builder->build_sample_item(
2382 biblionumber => $biblionumber,
2383 library => $library->{branchcode},
2387 Koha::CirculationRules->set_rules(
2389 categorycode => undef,
2391 branchcode => $library->{branchcode},
2393 reservesallowed => 25,
2395 lengthunit => 'days',
2396 renewalsallowed => 1,
2398 norenewalbefore => undef,
2407 my ( $error, $question, $alerts );
2408 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, dt_from_string->add( days => 1 ) );
2410 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2411 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2413 { error => $error, alerts => $alerts },
2414 { error => {}, alerts => {} },
2415 'No error or alert should be raised'
2417 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2419 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2420 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2422 { error => $error, question => $question, alerts => $alerts },
2423 { error => {}, question => {}, alerts => {} },
2424 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2427 # Add a subscription
2428 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2430 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2431 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2433 { error => $error, question => $question, alerts => $alerts },
2434 { error => {}, question => {}, alerts => {} },
2435 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2438 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2439 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2441 { error => $error, question => $question, alerts => $alerts },
2442 { error => {}, question => {}, alerts => {} },
2443 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2447 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2450 my $library = $builder->build( { source => 'Branch' } );
2451 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2454 my $biblionumber = $builder->build_sample_biblio(
2456 branchcode => $library->{branchcode},
2459 my $item_1 = $builder->build_sample_item(
2461 biblionumber => $biblionumber,
2462 library => $library->{branchcode},
2465 my $item_2 = $builder->build_sample_item(
2467 biblionumber => $biblionumber,
2468 library => $library->{branchcode},
2472 # And the circulation rule
2473 Koha::CirculationRules->search->delete;
2474 Koha::CirculationRules->set_rules(
2476 categorycode => undef,
2478 branchcode => undef,
2481 firstremind => 1, # 1 day of grace
2482 finedays => 2, # 2 days of fine per day of overdue
2483 lengthunit => 'days',
2488 # Patron cannot issue item_1, they have overdues
2489 my $now = dt_from_string;
2490 my $five_days_ago = $now->clone->subtract( days => 5 );
2491 my $ten_days_ago = $now->clone->subtract( days => 10 );
2492 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2493 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2494 ; # Add another overdue
2496 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2497 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2498 my $debarments = Koha::Patron::Debarments::GetDebarments(
2499 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2500 is( scalar(@$debarments), 1 );
2502 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2503 # Same for the others
2504 my $expected_expiration = output_pref(
2506 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2507 dateformat => 'sql',
2511 is( $debarments->[0]->{expiration}, $expected_expiration );
2513 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2514 $debarments = Koha::Patron::Debarments::GetDebarments(
2515 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2516 is( scalar(@$debarments), 1 );
2517 $expected_expiration = output_pref(
2519 dt => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2520 dateformat => 'sql',
2524 is( $debarments->[0]->{expiration}, $expected_expiration );
2526 Koha::Patron::Debarments::DelUniqueDebarment(
2527 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2529 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2530 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2531 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2532 ; # Add another overdue
2533 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2534 $debarments = Koha::Patron::Debarments::GetDebarments(
2535 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2536 is( scalar(@$debarments), 1 );
2537 $expected_expiration = output_pref(
2539 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2540 dateformat => 'sql',
2544 is( $debarments->[0]->{expiration}, $expected_expiration );
2546 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2547 $debarments = Koha::Patron::Debarments::GetDebarments(
2548 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2549 is( scalar(@$debarments), 1 );
2550 $expected_expiration = output_pref(
2552 dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2553 dateformat => 'sql',
2557 is( $debarments->[0]->{expiration}, $expected_expiration );
2560 subtest 'AddReturn + suspension_chargeperiod' => sub {
2563 my $library = $builder->build( { source => 'Branch' } );
2564 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2566 my $biblionumber = $builder->build_sample_biblio(
2568 branchcode => $library->{branchcode},
2571 my $item_1 = $builder->build_sample_item(
2573 biblionumber => $biblionumber,
2574 library => $library->{branchcode},
2578 # And the issuing rule
2579 Koha::CirculationRules->search->delete;
2580 Koha::CirculationRules->set_rules(
2582 categorycode => '*',
2587 firstremind => 0, # 0 day of grace
2588 finedays => 2, # 2 days of fine per day of overdue
2589 suspension_chargeperiod => 1,
2590 lengthunit => 'days',
2595 my $now = dt_from_string;
2596 my $five_days_ago = $now->clone->subtract( days => 5 );
2597 # We want to charge 2 days every day, without grace
2598 # With 5 days of overdue: 5 * Z
2599 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2600 test_debarment_on_checkout(
2603 library => $library,
2605 due_date => $five_days_ago,
2606 expiration_date => $expected_expiration,
2610 # Same with undef firstremind
2611 Koha::CirculationRules->search->delete;
2612 Koha::CirculationRules->set_rules(
2614 categorycode => '*',
2619 firstremind => undef, # 0 day of grace
2620 finedays => 2, # 2 days of fine per day of overdue
2621 suspension_chargeperiod => 1,
2622 lengthunit => 'days',
2627 my $now = dt_from_string;
2628 my $five_days_ago = $now->clone->subtract( days => 5 );
2629 # We want to charge 2 days every day, without grace
2630 # With 5 days of overdue: 5 * Z
2631 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2632 test_debarment_on_checkout(
2635 library => $library,
2637 due_date => $five_days_ago,
2638 expiration_date => $expected_expiration,
2642 # We want to charge 2 days every 2 days, without grace
2643 # With 5 days of overdue: (5 * 2) / 2
2644 Koha::CirculationRules->set_rule(
2646 categorycode => undef,
2647 branchcode => undef,
2649 rule_name => 'suspension_chargeperiod',
2654 $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2655 test_debarment_on_checkout(
2658 library => $library,
2660 due_date => $five_days_ago,
2661 expiration_date => $expected_expiration,
2665 # We want to charge 2 days every 3 days, with 1 day of grace
2666 # With 5 days of overdue: ((5-1) / 3 ) * 2
2667 Koha::CirculationRules->set_rules(
2669 categorycode => undef,
2670 branchcode => undef,
2673 suspension_chargeperiod => 3,
2678 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2679 test_debarment_on_checkout(
2682 library => $library,
2684 due_date => $five_days_ago,
2685 expiration_date => $expected_expiration,
2689 # Use finesCalendar to know if holiday must be skipped to calculate the due date
2690 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2691 Koha::CirculationRules->set_rules(
2693 categorycode => undef,
2694 branchcode => undef,
2698 suspension_chargeperiod => 1,
2703 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2704 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2706 # Adding a holiday 2 days ago
2707 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2708 my $two_days_ago = $now->clone->subtract( days => 2 );
2709 $calendar->insert_single_holiday(
2710 day => $two_days_ago->day,
2711 month => $two_days_ago->month,
2712 year => $two_days_ago->year,
2713 title => 'holidayTest-2d',
2714 description => 'holidayDesc 2 days ago'
2716 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2717 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2718 test_debarment_on_checkout(
2721 library => $library,
2723 due_date => $five_days_ago,
2724 expiration_date => $expected_expiration,
2728 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2729 my $two_days_ahead = $now->clone->add( days => 2 );
2730 $calendar->insert_single_holiday(
2731 day => $two_days_ahead->day,
2732 month => $two_days_ahead->month,
2733 year => $two_days_ahead->year,
2734 title => 'holidayTest+2d',
2735 description => 'holidayDesc 2 days ahead'
2738 # Same as above, but we should skip D+2
2739 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2740 test_debarment_on_checkout(
2743 library => $library,
2745 due_date => $five_days_ago,
2746 expiration_date => $expected_expiration,
2750 # Adding another holiday, day of expiration date
2751 my $expected_expiration_dt = dt_from_string($expected_expiration);
2752 $calendar->insert_single_holiday(
2753 day => $expected_expiration_dt->day,
2754 month => $expected_expiration_dt->month,
2755 year => $expected_expiration_dt->year,
2756 title => 'holidayTest_exp',
2757 description => 'holidayDesc on expiration date'
2759 # Expiration date will be the day after
2760 test_debarment_on_checkout(
2763 library => $library,
2765 due_date => $five_days_ago,
2766 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2770 test_debarment_on_checkout(
2773 library => $library,
2775 return_date => $now->clone->add(days => 5),
2776 expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2780 test_debarment_on_checkout(
2783 library => $library,
2785 due_date => $now->clone->add(days => 1),
2786 return_date => $now->clone->add(days => 5),
2787 expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2793 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2796 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2797 my $patron1 = $builder->build_object(
2799 class => 'Koha::Patrons',
2801 library => $library->branchcode,
2802 categorycode => $patron_category->{categorycode}
2806 my $patron2 = $builder->build_object(
2808 class => 'Koha::Patrons',
2810 library => $library->branchcode,
2811 categorycode => $patron_category->{categorycode}
2816 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2818 my $item = $builder->build_sample_item(
2820 library => $library->branchcode,
2824 my ( $error, $question, $alerts );
2825 my $issue = AddIssue( $patron1->unblessed, $item->barcode );
2827 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2828 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2829 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' );
2831 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2832 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2833 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' );
2835 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2839 subtest 'AddReturn | is_overdue' => sub {
2842 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2843 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2844 t::lib::Mocks::mock_preference('finesMode', 'production');
2845 t::lib::Mocks::mock_preference('MaxFine', '100');
2847 my $library = $builder->build( { source => 'Branch' } );
2848 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2849 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2850 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2852 my $item = $builder->build_sample_item(
2854 library => $library->{branchcode},
2855 replacementprice => 7
2859 Koha::CirculationRules->search->delete;
2860 Koha::CirculationRules->set_rules(
2862 categorycode => undef,
2864 branchcode => undef,
2867 lengthunit => 'days',
2868 fine => 1, # Charge 1 every day of overdue
2874 my $now = dt_from_string;
2875 my $one_day_ago = $now->clone->subtract( days => 1 );
2876 my $two_days_ago = $now->clone->subtract( days => 2 );
2877 my $five_days_ago = $now->clone->subtract( days => 5 );
2878 my $ten_days_ago = $now->clone->subtract( days => 10 );
2879 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2881 # No return date specified, today will be used => 10 days overdue charged
2882 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2883 AddReturn( $item->barcode, $library->{branchcode} );
2884 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2885 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2887 # specify return date 5 days before => no overdue charged
2888 AddIssue( $patron->unblessed, $item->barcode, $five_days_ago ); # date due was 5d ago
2889 AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
2890 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2891 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2893 # specify return date 5 days later => 5 days overdue charged
2894 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2895 AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
2896 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2897 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2899 # specify return date 5 days later, specify exemptfine => no overdue charge
2900 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2901 AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago );
2902 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2903 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2905 subtest 'bug 22877 | Lost item return' => sub {
2909 my $issue = AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2911 # Fake fines cronjob on this checkout
2913 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2914 $ten_days_ago, $now );
2917 issue_id => $issue->issue_id,
2918 itemnumber => $item->itemnumber,
2919 borrowernumber => $patron->borrowernumber,
2921 due => output_pref($ten_days_ago)
2924 is( int( $patron->account->balance() ),
2925 10, "Overdue fine of 10 days overdue" );
2927 # Fake longoverdue with charge and not marking returned
2928 LostItem( $item->itemnumber, 'cronjob', 0 );
2929 is( int( $patron->account->balance() ),
2930 17, "Lost fine of 7 plus 10 days overdue" );
2932 # Now we return it today
2933 AddReturn( $item->barcode, $library->{branchcode} );
2934 is( int( $patron->account->balance() ),
2935 17, "Should have a single 10 days overdue fine and lost charge" );
2938 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2941 subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
2945 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2947 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
2949 # Fake fines cronjob on this checkout
2951 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2952 $one_day_ago, $now );
2955 issue_id => $issue->issue_id,
2956 itemnumber => $item->itemnumber,
2957 borrowernumber => $patron->borrowernumber,
2959 due => output_pref($one_day_ago)
2962 is( int( $patron->account->balance() ),
2963 1, "Overdue fine of 1 day overdue" );
2965 # Backdated return (dropbox mode example - charge should be removed)
2966 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
2967 is( int( $patron->account->balance() ),
2968 0, "Overdue fine should be annulled" );
2969 my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2970 is( $lines->count, 0, "Overdue fine accountline has been removed");
2972 $issue = AddIssue( $patron->unblessed, $item->barcode, $two_days_ago ); # date due was 2d ago
2974 # Fake fines cronjob on this checkout
2976 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2977 $two_days_ago, $now );
2980 issue_id => $issue->issue_id,
2981 itemnumber => $item->itemnumber,
2982 borrowernumber => $patron->borrowernumber,
2984 due => output_pref($one_day_ago)
2987 is( int( $patron->account->balance() ),
2988 2, "Overdue fine of 2 days overdue" );
2990 # Payment made against fine
2991 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2992 my $debit = $lines->next;
2993 my $credit = $patron->account->add_credit(
2997 interface => 'test',
3000 $credit->apply( { debits => [$debit] } );
3002 is( int( $patron->account->balance() ),
3003 0, "Overdue fine should be paid off" );
3004 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3005 is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
3006 my $line = $lines->next;
3007 is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
3008 is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
3010 # Backdated return (dropbox mode example - charge should be removed)
3011 AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
3012 is( int( $patron->account->balance() ),
3013 -1, "Refund credit has been applied" );
3014 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
3015 is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
3017 $line = $lines->next;
3018 is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
3019 is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
3020 is($line->status,'RETURNED', "Overdue fine is fixed");
3021 $line = $lines->next;
3022 is($line->amount+0,-2, "Original payment amount remains as 2");
3023 is($line->amountoutstanding+0,0, "Original payment remains applied");
3024 $line = $lines->next;
3025 is($line->amount+0,-1, "Refund amount correctly set to 1");
3026 is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
3029 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3032 subtest 'bug 25417 | backdated return + exemptfine' => sub {
3036 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3038 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
3040 # Fake fines cronjob on this checkout
3042 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3043 $one_day_ago, $now );
3046 issue_id => $issue->issue_id,
3047 itemnumber => $item->itemnumber,
3048 borrowernumber => $patron->borrowernumber,
3050 due => output_pref($one_day_ago)
3053 is( int( $patron->account->balance() ),
3054 1, "Overdue fine of 1 day overdue" );
3056 # Backdated return (dropbox mode example - charge should no longer exist)
3057 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3058 is( int( $patron->account->balance() ),
3059 0, "Overdue fine should be annulled" );
3062 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3065 subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
3068 t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
3070 my $due_date = dt_from_string;
3071 my $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
3076 issue_id => $issue->issue_id,
3077 itemnumber => $item->itemnumber,
3078 borrowernumber => $patron->borrowernumber,
3080 due => output_pref($due_date)
3083 is( $patron->account->balance(),
3084 0.25, 'Overdue fine of $0.25 recorded' );
3086 # Backdate return to exact due date and time
3087 my ( undef, $message ) =
3088 AddReturn( $item->barcode, $library->{branchcode},
3092 Koha::Account::Lines->find( { issue_id => $issue->id } );
3093 ok( !$accountline, 'accountline removed as expected' );
3096 $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
3101 issue_id => $issue->issue_id,
3102 itemnumber => $item->itemnumber,
3103 borrowernumber => $patron->borrowernumber,
3105 due => output_pref($due_date)
3108 is( $patron->account->balance(),
3109 0.25, 'Overdue fine of $0.25 recorded' );
3111 # Partial pay accruing fine
3112 my $lines = Koha::Account::Lines->search(
3114 borrowernumber => $patron->borrowernumber,
3115 issue_id => $issue->id
3118 my $debit = $lines->next;
3119 my $credit = $patron->account->add_credit(
3123 interface => 'test',
3126 $credit->apply( { debits => [$debit] } );
3128 is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
3130 # Backdate return to exact due date and time
3131 ( undef, $message ) =
3132 AddReturn( $item->barcode, $library->{branchcode},
3135 $lines = Koha::Account::Lines->search(
3137 borrowernumber => $patron->borrowernumber,
3138 issue_id => $issue->id
3141 $accountline = $lines->next;
3142 is( $accountline->amountoutstanding + 0,
3143 0, 'Partially paid fee amount outstanding was reduced to 0' );
3144 is( $accountline->amount + 0,
3145 0, 'Partially paid fee amount was reduced to 0' );
3146 is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
3149 Koha::Account::Lines->search(
3150 { borrowernumber => $patron->borrowernumber } )->delete;
3153 subtest 'enh 23091 | Lost item return policies' => sub {
3156 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3158 my $branchcode_false =
3159 $builder->build( { source => 'Branch' } )->{branchcode};
3160 my $specific_rule_false = $builder->build(
3162 source => 'CirculationRule',
3164 branchcode => $branchcode_false,
3165 categorycode => undef,
3167 rule_name => 'lostreturn',
3172 my $branchcode_refund =
3173 $builder->build( { source => 'Branch' } )->{branchcode};
3174 my $specific_rule_refund = $builder->build(
3176 source => 'CirculationRule',
3178 branchcode => $branchcode_refund,
3179 categorycode => undef,
3181 rule_name => 'lostreturn',
3182 rule_value => 'refund'
3186 my $branchcode_restore =
3187 $builder->build( { source => 'Branch' } )->{branchcode};
3188 my $specific_rule_restore = $builder->build(
3190 source => 'CirculationRule',
3192 branchcode => $branchcode_restore,
3193 categorycode => undef,
3195 rule_name => 'lostreturn',
3196 rule_value => 'restore'
3200 my $branchcode_charge =
3201 $builder->build( { source => 'Branch' } )->{branchcode};
3202 my $specific_rule_charge = $builder->build(
3204 source => 'CirculationRule',
3206 branchcode => $branchcode_charge,
3207 categorycode => undef,
3209 rule_name => 'lostreturn',
3210 rule_value => 'charge'
3215 my $replacement_amount = 99.00;
3216 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
3217 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
3218 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
3219 t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 );
3220 t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
3222 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
3225 subtest 'lostreturn | false' => sub {
3228 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
3230 my $item = $builder->build_sample_item(
3232 replacementprice => $replacement_amount
3237 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3239 # Fake fines cronjob on this checkout
3241 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3242 $ten_days_ago, $now );
3245 issue_id => $issue->issue_id,
3246 itemnumber => $item->itemnumber,
3247 borrowernumber => $patron->borrowernumber,
3249 due => output_pref($ten_days_ago)
3252 my $overdue_fees = Koha::Account::Lines->search(
3254 borrowernumber => $patron->id,
3255 itemnumber => $item->itemnumber,
3256 debit_type_code => 'OVERDUE'
3259 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3260 my $overdue_fee = $overdue_fees->next;
3261 is( $overdue_fee->amount + 0,
3262 10, 'The right OVERDUE amount is generated' );
3263 is( $overdue_fee->amountoutstanding + 0,
3265 'The right OVERDUE amountoutstanding is generated' );
3267 # Simulate item marked as lost
3268 $item->itemlost(3)->store;
3269 C4::Circulation::LostItem( $item->itemnumber, 1 );
3271 my $lost_fee_lines = Koha::Account::Lines->search(
3273 borrowernumber => $patron->id,
3274 itemnumber => $item->itemnumber,
3275 debit_type_code => 'LOST'
3278 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3279 my $lost_fee_line = $lost_fee_lines->next;
3280 is( $lost_fee_line->amount + 0,
3281 $replacement_amount, 'The right LOST amount is generated' );
3282 is( $lost_fee_line->amountoutstanding + 0,
3283 $replacement_amount,
3284 'The right LOST amountoutstanding is generated' );
3285 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3288 my ( $returned, $message ) =
3289 AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
3291 $overdue_fee->discard_changes;
3292 is( $overdue_fee->amount + 0,
3293 10, 'The OVERDUE amount is left intact' );
3294 is( $overdue_fee->amountoutstanding + 0,
3296 'The OVERDUE amountoutstanding is left intact' );
3298 $lost_fee_line->discard_changes;
3299 is( $lost_fee_line->amount + 0,
3300 $replacement_amount, 'The LOST amount is left intact' );
3301 is( $lost_fee_line->amountoutstanding + 0,
3302 $replacement_amount,
3303 'The LOST amountoutstanding is left intact' );
3304 # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
3305 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3308 subtest 'lostreturn | refund' => sub {
3311 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
3313 my $item = $builder->build_sample_item(
3315 replacementprice => $replacement_amount
3320 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3322 # Fake fines cronjob on this checkout
3324 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3325 $ten_days_ago, $now );
3328 issue_id => $issue->issue_id,
3329 itemnumber => $item->itemnumber,
3330 borrowernumber => $patron->borrowernumber,
3332 due => output_pref($ten_days_ago)
3335 my $overdue_fees = Koha::Account::Lines->search(
3337 borrowernumber => $patron->id,
3338 itemnumber => $item->itemnumber,
3339 debit_type_code => 'OVERDUE'
3342 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3343 my $overdue_fee = $overdue_fees->next;
3344 is( $overdue_fee->amount + 0,
3345 10, 'The right OVERDUE amount is generated' );
3346 is( $overdue_fee->amountoutstanding + 0,
3348 'The right OVERDUE amountoutstanding is generated' );
3350 # Simulate item marked as lost
3351 $item->itemlost(3)->store;
3352 C4::Circulation::LostItem( $item->itemnumber, 1 );
3354 my $lost_fee_lines = Koha::Account::Lines->search(
3356 borrowernumber => $patron->id,
3357 itemnumber => $item->itemnumber,
3358 debit_type_code => 'LOST'
3361 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3362 my $lost_fee_line = $lost_fee_lines->next;
3363 is( $lost_fee_line->amount + 0,
3364 $replacement_amount, 'The right LOST amount is generated' );
3365 is( $lost_fee_line->amountoutstanding + 0,
3366 $replacement_amount,
3367 'The right LOST amountoutstanding is generated' );
3368 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3370 # Return the lost item
3371 my ( undef, $message ) =
3372 AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
3374 $overdue_fee->discard_changes;
3375 is( $overdue_fee->amount + 0,
3376 10, 'The OVERDUE amount is left intact' );
3377 is( $overdue_fee->amountoutstanding + 0,
3379 'The OVERDUE amountoutstanding is left intact' );
3381 $lost_fee_line->discard_changes;
3382 is( $lost_fee_line->amount + 0,
3383 $replacement_amount, 'The LOST amount is left intact' );
3384 is( $lost_fee_line->amountoutstanding + 0,
3386 'The LOST amountoutstanding is refunded' );
3387 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3390 subtest 'lostreturn | restore' => sub {
3393 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
3395 my $item = $builder->build_sample_item(
3397 replacementprice => $replacement_amount
3402 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode , $ten_days_ago);
3404 # Fake fines cronjob on this checkout
3406 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3407 $ten_days_ago, $now );
3410 issue_id => $issue->issue_id,
3411 itemnumber => $item->itemnumber,
3412 borrowernumber => $patron->borrowernumber,
3414 due => output_pref($ten_days_ago)
3417 my $overdue_fees = Koha::Account::Lines->search(
3419 borrowernumber => $patron->id,
3420 itemnumber => $item->itemnumber,
3421 debit_type_code => 'OVERDUE'
3424 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3425 my $overdue_fee = $overdue_fees->next;
3426 is( $overdue_fee->amount + 0,
3427 10, 'The right OVERDUE amount is generated' );
3428 is( $overdue_fee->amountoutstanding + 0,
3430 'The right OVERDUE amountoutstanding is generated' );
3432 # Simulate item marked as lost
3433 $item->itemlost(3)->store;
3434 C4::Circulation::LostItem( $item->itemnumber, 1 );
3436 my $lost_fee_lines = Koha::Account::Lines->search(
3438 borrowernumber => $patron->id,
3439 itemnumber => $item->itemnumber,
3440 debit_type_code => 'LOST'
3443 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3444 my $lost_fee_line = $lost_fee_lines->next;
3445 is( $lost_fee_line->amount + 0,
3446 $replacement_amount, 'The right LOST amount is generated' );
3447 is( $lost_fee_line->amountoutstanding + 0,
3448 $replacement_amount,
3449 'The right LOST amountoutstanding is generated' );
3450 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3452 # Simulate refunding overdue fees upon marking item as lost
3453 my $overdue_forgive = $patron->account->add_credit(
3456 user_id => $manager->borrowernumber,
3457 library_id => $branchcode_restore,
3458 interface => 'test',
3460 item_id => $item->itemnumber
3463 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3464 $overdue_fee->discard_changes;
3465 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3468 my ( undef, $message ) =
3469 AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
3471 $overdue_fee->discard_changes;
3472 is( $overdue_fee->amount + 0,
3473 10, 'The OVERDUE amount is left intact' );
3474 is( $overdue_fee->amountoutstanding + 0,
3476 'The OVERDUE amountoutstanding is restored' );
3478 $lost_fee_line->discard_changes;
3479 is( $lost_fee_line->amount + 0,
3480 $replacement_amount, 'The LOST amount is left intact' );
3481 is( $lost_fee_line->amountoutstanding + 0,
3483 'The LOST amountoutstanding is refunded' );
3484 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3487 subtest 'lostreturn | charge' => sub {
3490 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
3492 my $item = $builder->build_sample_item(
3494 replacementprice => $replacement_amount
3499 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3501 # Fake fines cronjob on this checkout
3503 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3504 $ten_days_ago, $now );
3507 issue_id => $issue->issue_id,
3508 itemnumber => $item->itemnumber,
3509 borrowernumber => $patron->borrowernumber,
3511 due => output_pref($ten_days_ago)
3514 my $overdue_fees = Koha::Account::Lines->search(
3516 borrowernumber => $patron->id,
3517 itemnumber => $item->itemnumber,
3518 debit_type_code => 'OVERDUE'
3521 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3522 my $overdue_fee = $overdue_fees->next;
3523 is( $overdue_fee->amount + 0,
3524 10, 'The right OVERDUE amount is generated' );
3525 is( $overdue_fee->amountoutstanding + 0,
3527 'The right OVERDUE amountoutstanding is generated' );
3529 # Simulate item marked as lost
3530 $item->itemlost(3)->store;
3531 C4::Circulation::LostItem( $item->itemnumber, 1 );
3533 my $lost_fee_lines = Koha::Account::Lines->search(
3535 borrowernumber => $patron->id,
3536 itemnumber => $item->itemnumber,
3537 debit_type_code => 'LOST'
3540 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3541 my $lost_fee_line = $lost_fee_lines->next;
3542 is( $lost_fee_line->amount + 0,
3543 $replacement_amount, 'The right LOST amount is generated' );
3544 is( $lost_fee_line->amountoutstanding + 0,
3545 $replacement_amount,
3546 'The right LOST amountoutstanding is generated' );
3547 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3549 # Simulate refunding overdue fees upon marking item as lost
3550 my $overdue_forgive = $patron->account->add_credit(
3553 user_id => $manager->borrowernumber,
3554 library_id => $branchcode_charge,
3555 interface => 'test',
3557 item_id => $item->itemnumber
3560 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3561 $overdue_fee->discard_changes;
3562 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3565 my ( undef, $message ) =
3566 AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
3568 $lost_fee_line->discard_changes;
3569 is( $lost_fee_line->amount + 0,
3570 $replacement_amount, 'The LOST amount is left intact' );
3571 is( $lost_fee_line->amountoutstanding + 0,
3573 'The LOST amountoutstanding is refunded' );
3574 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3576 $overdue_fees = Koha::Account::Lines->search(
3578 borrowernumber => $patron->id,
3579 itemnumber => $item->itemnumber,
3580 debit_type_code => 'OVERDUE'
3583 order_by => { '-asc' => 'accountlines_id'}
3586 is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
3587 $overdue_fee = $overdue_fees->next;
3588 is( $overdue_fee->amount + 0,
3589 10, 'The original OVERDUE amount is left intact' );
3590 is( $overdue_fee->amountoutstanding + 0,
3592 'The original OVERDUE amountoutstanding is left as forgiven' );
3593 $overdue_fee = $overdue_fees->next;
3594 is( $overdue_fee->amount + 0,
3595 5, 'The new OVERDUE amount is correct for the backdated return' );
3596 is( $overdue_fee->amountoutstanding + 0,
3598 'The new OVERDUE amountoutstanding is correct for the backdated return' );
3603 subtest '_FixOverduesOnReturn' => sub {
3606 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3607 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3609 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3611 my $branchcode = $library2->{branchcode};
3613 my $item = $builder->build_sample_item(
3615 biblionumber => $biblio->biblionumber,
3616 library => $branchcode,
3617 replacementprice => 99.00,
3622 my $patron = $builder->build( { source => 'Borrower' } );
3624 ## Start with basic call, should just close out the open fine
3625 my $accountline = Koha::Account::Line->new(
3627 borrowernumber => $patron->{borrowernumber},
3628 debit_type_code => 'OVERDUE',
3629 status => 'UNRETURNED',
3630 itemnumber => $item->itemnumber,
3632 amountoutstanding => 99.00,
3633 interface => 'test',
3637 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
3639 $accountline->_result()->discard_changes();
3641 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
3642 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3643 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3645 ## Run again, with exemptfine enabled
3648 debit_type_code => 'OVERDUE',
3649 status => 'UNRETURNED',
3650 amountoutstanding => 99.00,
3654 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3656 $accountline->_result()->discard_changes();
3657 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'APPLY' })->next();
3659 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
3660 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3661 is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
3662 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
3663 is( $offset->amount + 0, -99, "Amount of offset is correct" );
3664 my $credit = $offset->credit;
3665 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
3666 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
3667 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
3669 # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
3672 debit_type_code => 'OVERDUE',
3673 status => 'UNRETURNED',
3674 amountoutstanding => 0.00,
3679 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3681 $accountline->_result()->discard_changes();
3682 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'CREATE' })->next();
3683 is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
3684 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3685 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3688 subtest 'Set waiting flag' => sub {
3691 my $library_1 = $builder->build( { source => 'Branch' } );
3692 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3693 my $library_2 = $builder->build( { source => 'Branch' } );
3694 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3696 my $item = $builder->build_sample_item(
3698 library => $library_1->{branchcode},
3702 set_userenv( $library_2 );
3703 my $reserve_id = AddReserve(
3705 branchcode => $library_2->{branchcode},
3706 borrowernumber => $patron_2->{borrowernumber},
3707 biblionumber => $item->biblionumber,
3709 itemnumber => $item->itemnumber,
3713 set_userenv( $library_1 );
3714 my $do_transfer = 1;
3715 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3716 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3717 my $hold = Koha::Holds->find( $reserve_id );
3718 is( $hold->found, 'T', 'Hold is in transit' );
3720 my ( $status ) = CheckReserves($item->itemnumber);
3721 is( $status, 'Transferred', 'Hold is not waiting yet');
3723 set_userenv( $library_2 );
3725 AddReturn( $item->barcode, $library_2->{branchcode} );
3726 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3727 $hold = Koha::Holds->find( $reserve_id );
3728 is( $hold->found, 'W', 'Hold is waiting' );
3729 ( $status ) = CheckReserves($item->itemnumber);
3730 is( $status, 'Waiting', 'Now the hold is waiting');
3732 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
3733 set_userenv( $library_1 );
3734 (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
3735 $hold = Koha::Holds->find( $reserve_id );
3736 is( $hold->found, undef, 'Hold is no longer marked waiting' );
3737 is( $hold->priority, 1, "Hold is now priority one again");
3738 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
3739 is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
3740 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
3741 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
3742 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
3745 subtest 'Cancel transfers on lost items' => sub {
3748 my $library_to = $builder->build_object( { class => 'Koha::Libraries' } );
3749 my $item = $builder->build_sample_item();
3750 my $holdingbranch = $item->holdingbranch;
3751 # Historic transfer (datearrived is defined)
3752 my $old_transfer = $builder->build_object(
3754 class => 'Koha::Item::Transfers',
3756 itemnumber => $item->itemnumber,
3757 frombranch => $holdingbranch,
3758 tobranch => $library_to->branchcode,
3760 datesent => \'NOW()',
3761 datearrived => \'NOW()',
3762 datecancelled => undef,
3763 daterequested => \'NOW()'
3767 # Queued transfer (datesent is undefined)
3768 my $transfer_1 = $builder->build_object(
3770 class => 'Koha::Item::Transfers',
3772 itemnumber => $item->itemnumber,
3773 frombranch => $holdingbranch,
3774 tobranch => $library_to->branchcode,
3777 datearrived => undef,
3778 datecancelled => undef,
3779 daterequested => \'NOW()'
3783 # In transit transfer (datesent is defined, datearrived and datecancelled are both undefined)
3784 my $transfer_2 = $builder->build_object(
3786 class => 'Koha::Item::Transfers',
3788 itemnumber => $item->itemnumber,
3789 frombranch => $holdingbranch,
3790 tobranch => $library_to->branchcode,
3792 datesent => \'NOW()',
3793 datearrived => undef,
3794 datecancelled => undef,
3795 daterequested => \'NOW()'
3800 # Simulate item being marked as lost
3801 $item->itemlost(1)->store;
3802 LostItem( $item->itemnumber, 'test', 1 );
3804 $transfer_1->discard_changes;
3805 isnt($transfer_1->datecancelled, undef, "Queud transfer was cancelled upon item lost");
3806 is($transfer_1->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
3807 $transfer_2->discard_changes;
3808 isnt($transfer_2->datecancelled, undef, "Active transfer was cancelled upon item lost");
3809 is($transfer_2->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
3810 $old_transfer->discard_changes;
3811 is($old_transfer->datecancelled, undef, "Old transfers are unaffected");
3812 $item->discard_changes;
3813 is($item->holdingbranch, $holdingbranch, "Items holding branch remains unchanged");
3816 subtest 'CanBookBeIssued | is_overdue' => sub {
3819 # Set a simple circ policy
3820 Koha::CirculationRules->set_rules(
3822 categorycode => undef,
3823 branchcode => undef,
3827 reservesallowed => 25,
3829 lengthunit => 'days',
3830 renewalsallowed => 1,
3832 norenewalbefore => undef,
3840 my $now = dt_from_string;
3841 my $five_days_go = output_pref({ dt => $now->clone->add( days => 5 ), dateonly => 1});
3842 my $ten_days_go = output_pref({ dt => $now->clone->add( days => 10), dateonly => 1 });
3843 my $library = $builder->build( { source => 'Branch' } );
3844 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
3846 my $item = $builder->build_sample_item(
3848 library => $library->{branchcode},
3852 my $issue = AddIssue( $patron->unblessed, $item->barcode, $five_days_go ); # date due was 10d ago
3853 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
3854 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
3855 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->barcode,$ten_days_go, undef, undef, undef);
3856 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
3857 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
3860 subtest 'ItemsDeniedRenewal preference' => sub {
3863 C4::Context->set_preference('ItemsDeniedRenewal','');
3865 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
3866 Koha::CirculationRules->set_rules(
3868 categorycode => '*',
3870 branchcode => $idr_lib->branchcode,
3872 reservesallowed => 25,
3874 lengthunit => 'days',
3875 renewalsallowed => 10,
3877 norenewalbefore => undef,
3885 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
3886 homebranch => $idr_lib->branchcode,
3890 itemcallnumber => undef,
3894 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
3895 homebranch => $idr_lib->branchcode,
3898 location => 'NOPROC'
3902 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
3903 branchcode => $idr_lib->branchcode,
3906 my $future = dt_from_string->add( days => 1 );
3907 my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3908 returndate => undef,
3911 borrowernumber => $idr_borrower->borrowernumber,
3912 itemnumber => $deny_book->itemnumber,
3913 onsite_checkout => 0,
3914 date_due => $future,
3917 my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3918 returndate => undef,
3921 borrowernumber => $idr_borrower->borrowernumber,
3922 itemnumber => $allow_book->itemnumber,
3923 onsite_checkout => 0,
3924 date_due => $future,
3930 my ( $idr_mayrenew, $idr_error ) =
3931 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3932 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3933 is( $idr_error, undef, 'Renewal allowed when no rules' );
3935 $idr_rules="withdrawn: [1]";
3937 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3938 ( $idr_mayrenew, $idr_error ) =
3939 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3940 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3941 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3942 ( $idr_mayrenew, $idr_error ) =
3943 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3944 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3945 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3947 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
3949 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3950 ( $idr_mayrenew, $idr_error ) =
3951 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3952 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
3953 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
3954 ( $idr_mayrenew, $idr_error ) =
3955 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3956 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3957 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3959 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
3961 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3962 ( $idr_mayrenew, $idr_error ) =
3963 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3964 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
3965 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
3966 ( $idr_mayrenew, $idr_error ) =
3967 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3968 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3969 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3971 $idr_rules="itemcallnumber: [NULL]";
3972 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3973 ( $idr_mayrenew, $idr_error ) =
3974 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3975 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
3976 $idr_rules="itemcallnumber: ['']";
3977 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3978 ( $idr_mayrenew, $idr_error ) =
3979 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3980 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
3982 $idr_rules="itemnotes: [NULL]";
3983 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3984 ( $idr_mayrenew, $idr_error ) =
3985 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3986 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
3987 $idr_rules="itemnotes: ['']";
3988 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3989 ( $idr_mayrenew, $idr_error ) =
3990 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3991 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
3994 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
3997 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3998 my $library = $builder->build( { source => 'Branch' } );
3999 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4001 my $item = $builder->build_sample_item(
4003 library => $library->{branchcode},
4007 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4008 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4009 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4012 subtest 'CanBookBeIssued | notforloan' => sub {
4015 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
4017 my $library = $builder->build( { source => 'Branch' } );
4018 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4020 my $itemtype = $builder->build(
4022 source => 'Itemtype',
4023 value => { notforloan => undef, }
4026 my $item = $builder->build_sample_item(
4028 library => $library->{branchcode},
4029 itype => $itemtype->{itemtype},
4032 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4034 my ( $issuingimpossible, $needsconfirmation );
4037 subtest 'item-level_itypes = 1' => sub {
4040 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
4041 # Is for loan at item type and item level
4042 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4043 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4044 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4046 # not for loan at item type level
4047 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4048 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4049 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4052 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4053 'Item can not be issued, not for loan at item type level'
4056 # not for loan at item level
4057 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4058 $item->notforloan( 1 )->store;
4059 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4060 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4063 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4064 'Item can not be issued, not for loan at item type level'
4068 subtest 'item-level_itypes = 0' => sub {
4071 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4073 # We set another itemtype for biblioitem
4074 my $itemtype = $builder->build(
4076 source => 'Itemtype',
4077 value => { notforloan => undef, }
4081 # for loan at item type and item level
4082 $item->notforloan(0)->store;
4083 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4084 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4085 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4086 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4088 # not for loan at item type level
4089 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4090 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4091 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4094 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4095 'Item can not be issued, not for loan at item type level'
4098 # not for loan at item level
4099 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4100 $item->notforloan( 1 )->store;
4101 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4102 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4105 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4106 'Item can not be issued, not for loan at item type level'
4110 # TODO test with AllowNotForLoanOverride = 1
4113 subtest 'CanBookBeIssued | recalls' => sub {
4116 t::lib::Mocks::mock_preference("UseRecalls", 1);
4117 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4118 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4119 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4120 my $item = $builder->build_sample_item;
4121 Koha::CirculationRules->set_rules({
4122 branchcode => undef,
4124 categorycode => undef,
4126 recalls_allowed => 10,
4131 my $recall = Koha::Recall->new(
4132 { patron_id => $patron1->borrowernumber,
4133 biblio_id => $item->biblionumber,
4134 item_id => $item->itemnumber,
4136 pickup_library_id => $patron1->branchcode,
4140 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4141 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed an item-level recall on this item" );
4143 $recall->set_cancelled;
4145 # biblio-level recall
4146 $recall = Koha::Recall->new(
4147 { patron_id => $patron1->borrowernumber,
4148 biblio_id => $item->biblionumber,
4151 pickup_library_id => $patron1->branchcode,
4155 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4156 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed a biblio-level recall and this item is eligible to fill it" );
4158 $recall->set_cancelled;
4160 # biblio-level recall
4161 $recall = Koha::Recall->new(
4162 { patron_id => $patron1->borrowernumber,
4163 biblio_id => $item->biblionumber,
4166 pickup_library_id => $patron1->branchcode,
4169 $recall->set_waiting( { item => $item, expirationdate => dt_from_string() } );
4171 my ( undef, undef, undef, $messages ) = CanBookBeIssued( $patron1, $item->barcode, undef, undef, undef, undef );
4172 is( $messages->{RECALLED}, $recall->id, "This book can be issued by this patron and they have placed a recall" );
4174 $recall->set_cancelled;
4177 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
4180 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
4181 my $item = $builder->build_sample_item(
4183 onloan => '2018-01-01',
4187 AddReturn( $item->barcode, $item->homebranch );
4188 $item->discard_changes; # refresh
4189 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
4192 subtest 'AddReturn | recalls' => sub {
4195 t::lib::Mocks::mock_preference("UseRecalls", 1);
4196 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4197 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4198 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4199 my $item1 = $builder->build_sample_item;
4200 Koha::CirculationRules->set_rules({
4201 branchcode => undef,
4203 categorycode => undef,
4205 recalls_allowed => 10,
4209 # this item can fill a recall with pickup at this branch
4210 AddIssue( $patron1->unblessed, $item1->barcode );
4211 my $recall1 = Koha::Recall->new(
4212 { patron_id => $patron2->borrowernumber,
4213 biblio_id => $item1->biblionumber,
4214 item_id => $item1->itemnumber,
4216 pickup_library_id => $item1->homebranch,
4219 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4220 is( $messages->{RecallFound}->id, $recall1->id, "Recall found" );
4221 $recall1->set_cancelled;
4223 # this item can fill a recall but needs transfer
4224 AddIssue( $patron1->unblessed, $item1->barcode );
4225 $recall1 = Koha::Recall->new(
4226 { patron_id => $patron2->borrowernumber,
4227 biblio_id => $item1->biblionumber,
4228 item_id => $item1->itemnumber,
4230 pickup_library_id => $patron2->branchcode,
4233 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4234 is( $messages->{RecallNeedsTransfer}, $item1->homebranch, "Recall requiring transfer found" );
4235 $recall1->set_cancelled;
4237 # this item is already in transit, do not ask to transfer
4238 AddIssue( $patron1->unblessed, $item1->barcode );
4239 $recall1 = Koha::Recall->new(
4240 { patron_id => $patron2->borrowernumber,
4241 biblio_id => $item1->biblionumber,
4242 item_id => $item1->itemnumber,
4244 pickup_library_id => $patron2->branchcode,
4247 $recall1->start_transfer;
4248 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $patron2->branchcode );
4249 is( $messages->{TransferredRecall}->id, $recall1->id, "In transit recall found" );
4250 $recall1->set_cancelled;
4253 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
4258 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4260 my $issuing_charges = 15;
4261 my $title = 'A title';
4262 my $author = 'Author, An';
4263 my $barcode = 'WHATARETHEODDS';
4265 my $circ = Test::MockModule->new('C4::Circulation');
4267 'GetIssuingCharges',
4269 return $issuing_charges;
4273 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4274 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
4275 my $patron = $builder->build_object({
4276 class => 'Koha::Patrons',
4277 value => { branchcode => $library->id }
4280 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
4281 my $item_id = Koha::Item->new(
4283 biblionumber => $biblio->biblionumber,
4284 homebranch => $library->id,
4285 holdingbranch => $library->id,
4286 barcode => $barcode,
4287 replacementprice => 23.00,
4288 itype => $itemtype->id
4290 )->store->itemnumber;
4291 my $item = Koha::Items->find( $item_id );
4293 my $context = Test::MockModule->new('C4::Context');
4294 $context->mock( userenv => { branch => $library->id } );
4296 # Check the item out
4297 AddIssue( $patron->unblessed, $item->barcode );
4300 AddRenewal( $patron->borrowernumber, $item->itemnumber, $library->id, undef, {break=>"the_renewal"} );
4301 } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
4303 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
4304 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
4305 my %params_renewal = (
4306 timestamp => { -like => $date . "%" },
4307 module => "CIRCULATION",
4308 action => "RENEWAL",
4310 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
4311 AddRenewal( $patron->id, $item->id, $library->id );
4312 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4313 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
4315 my $checkouts = $patron->checkouts;
4316 # The following will fail if run on 00:00:00
4317 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
4319 my $lines = Koha::Account::Lines->search({
4320 borrowernumber => $patron->id,
4321 itemnumber => $item->id
4324 is( $lines->count, 2 );
4326 my $line = $lines->next;
4327 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
4328 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
4329 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
4331 $line = $lines->next;
4332 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
4333 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
4334 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
4336 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
4338 $context = Test::MockModule->new('C4::Context');
4339 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
4341 my $now = dt_from_string;
4342 $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
4343 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
4344 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
4345 $sth->execute($item->id, $library->id);
4346 my ($old_stats_size) = $sth->fetchrow_array;
4347 AddRenewal( $patron->id, $item->id, $library->id );
4348 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4349 $sth->execute($item->id, $library->id);
4350 my ($new_stats_size) = $sth->fetchrow_array;
4351 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
4352 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
4354 AddReturn( $item->id, $library->id, undef, $date );
4355 AddIssue( $patron->unblessed, $item->barcode, $now );
4356 AddRenewal( $patron->id, $item->id, $library->id, undef, undef, 1 );
4357 my $lines_skipped = Koha::Account::Lines->search({
4358 borrowernumber => $patron->id,
4359 itemnumber => $item->id
4361 is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
4365 subtest 'ProcessOfflinePayment() tests' => sub {
4372 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
4373 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4374 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
4376 is( $result, 'Success.', 'The right string is returned' );
4378 my $lines = $patron->account->lines;
4379 is( $lines->count, 1, 'line created correctly');
4381 my $line = $lines->next;
4382 is( $line->amount+0, $amount * -1, 'amount picked from params' );
4383 is( $line->branchcode, $library->id, 'branchcode set correctly' );
4387 subtest 'Incremented fee tests' => sub {
4390 my $dt = dt_from_string();
4391 Time::Fake->offset( $dt->epoch );
4393 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
4396 $builder->build_object( { class => 'Koha::Libraries' } )->store;
4398 $module->mock( 'userenv', sub { { branch => $library->id } } );
4400 my $patron = $builder->build_object(
4402 class => 'Koha::Patrons',
4403 value => { categorycode => $patron_category->{categorycode} }
4407 my $itemtype = $builder->build_object(
4409 class => 'Koha::ItemTypes',
4411 notforloan => undef,
4413 rentalcharge_daily => 1,
4414 rentalcharge_daily_calendar => 0
4419 my $item = $builder->build_sample_item(
4421 library => $library->{branchcode},
4422 itype => $itemtype->id,
4426 is( $itemtype->rentalcharge_daily+0,
4427 1, 'Daily rental charge stored and retreived correctly' );
4428 is( $item->effective_itemtype, $itemtype->id,
4429 "Itemtype set correctly for item" );
4431 my $now = dt_from_string;
4432 my $dt_from = $now->clone;
4433 my $dt_to = $now->clone->add( days => 7 );
4434 my $dt_to_renew = $now->clone->add( days => 13 );
4438 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4439 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4440 is( $accountline->amount+0, 7,
4441 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
4443 $accountline->delete();
4444 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4445 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4446 is( $accountline->amount+0, 6,
4447 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
4449 $accountline->delete();
4452 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
4453 $itemtype->rentalcharge_daily_calendar(1)->store();
4455 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4456 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4457 is( $accountline->amount+0, 7,
4458 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
4460 $accountline->delete();
4461 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4462 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4463 is( $accountline->amount+0, 6,
4464 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
4466 $accountline->delete();
4469 my $calendar = C4::Calendar->new( branchcode => $library->id );
4470 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
4472 ( $dt_from->day_of_week == 6 ) ? 0
4473 : ( $dt_from->day_of_week == 7 ) ? 1
4474 : $dt_from->day_of_week + 1;
4475 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
4476 $calendar->insert_week_day_holiday(
4477 weekday => $closed_day,
4478 title => 'Test holiday',
4479 description => 'Test holiday'
4482 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4483 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4484 is( $accountline->amount+0, 6,
4485 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
4487 $accountline->delete();
4488 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4489 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4490 is( $accountline->amount+0, 5,
4491 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
4493 $accountline->delete();
4496 $itemtype->rentalcharge(2)->store;
4497 is( $itemtype->rentalcharge+0, 2,
4498 'Rental charge updated and retreived correctly' );
4500 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4502 Koha::Account::Lines->search( { itemnumber => $item->id } );
4503 is( $accountlines->count, '2',
4504 "Fixed charge and accrued charge recorded distinctly" );
4505 $accountlines->delete();
4506 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4507 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
4508 is( $accountlines->count, '2',
4509 "Fixed charge and accrued charge recorded distinctly, for renewal" );
4510 $accountlines->delete();
4512 $itemtype->rentalcharge(0)->store;
4513 is( $itemtype->rentalcharge+0, 0,
4514 'Rental charge reset and retreived correctly' );
4517 Koha::CirculationRules->set_rule(
4519 categorycode => $patron->categorycode,
4520 itemtype => $itemtype->id,
4521 branchcode => $library->id,
4522 rule_name => 'lengthunit',
4523 rule_value => 'hours',
4527 $itemtype->rentalcharge_hourly('0.25')->store();
4528 is( $itemtype->rentalcharge_hourly,
4529 '0.25', 'Hourly rental charge stored and retreived correctly' );
4531 $dt_to = $now->clone->add( hours => 168 );
4532 $dt_to_renew = $now->clone->add( hours => 312 );
4534 $itemtype->rentalcharge_hourly_calendar(0)->store();
4536 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4537 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4538 is( $accountline->amount + 0, 42,
4539 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)" );
4540 $accountline->delete();
4541 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4542 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4543 is( $accountline->amount + 0, 36,
4544 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)" );
4545 $accountline->delete();
4548 $itemtype->rentalcharge_hourly_calendar(1)->store();
4550 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4551 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4552 is( $accountline->amount + 0, 36,
4553 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)" );
4554 $accountline->delete();
4555 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4556 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4557 is( $accountline->amount + 0, 30,
4558 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
4559 $accountline->delete();
4562 $calendar->delete_holiday( weekday => $closed_day );
4564 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4565 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4566 is( $accountline->amount + 0, 42,
4567 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u" );
4568 $accountline->delete();
4569 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4570 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4571 is( $accountline->amount + 0, 36,
4572 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)" );
4573 $accountline->delete();
4578 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
4581 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
4582 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4585 $builder->build_object( { class => 'Koha::Libraries' } )->store;
4586 my $patron = $builder->build_object(
4588 class => 'Koha::Patrons',
4589 value => { categorycode => $patron_category->{categorycode} }
4593 my $itemtype = $builder->build_object(
4595 class => 'Koha::ItemTypes',
4599 rentalcharge_daily => 0
4604 my $item = $builder->build_sample_item(
4606 library => $library->id,
4610 itype => $itemtype->id,
4614 my ( $issuingimpossible, $needsconfirmation );
4615 my $dt_from = dt_from_string();
4616 my $dt_due = $dt_from->clone->add( days => 3 );
4618 $itemtype->rentalcharge(1)->store;
4619 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4620 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
4621 $itemtype->rentalcharge('0')->store;
4622 $itemtype->rentalcharge_daily(1)->store;
4623 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4624 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
4625 $itemtype->rentalcharge_daily('0')->store;
4628 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
4631 t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
4633 my $patron = $builder->build_object(
4635 class => 'Koha::Patrons',
4636 value => { categorycode => $patron_category->{categorycode} }
4640 my $item = $builder->build_sample_item(
4642 materials => 'includes DVD',
4646 my $dt_due = dt_from_string->add( days => 3 );
4648 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4649 is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
4652 subtest 'Do not return on renewal (LOST charge)' => sub {
4655 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
4656 my $library = $builder->build_object( { class => "Koha::Libraries" } );
4657 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
4658 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
4660 my $biblio = $builder->build_sample_biblio;
4662 my $item = $builder->build_sample_item(
4664 biblionumber => $biblio->biblionumber,
4665 library => $library->branchcode,
4666 replacementprice => 99.00,
4671 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
4672 AddIssue( $patron->unblessed, $item->barcode );
4674 my $accountline = Koha::Account::Line->new(
4676 borrowernumber => $patron->borrowernumber,
4677 debit_type_code => 'LOST',
4679 itemnumber => $item->itemnumber,
4681 amountoutstanding => 12,
4682 interface => 'something',
4686 # AddRenewal doesn't call _FixAccountForLostAndFound
4687 AddIssue( $patron->unblessed, $item->barcode );
4689 is( $patron->checkouts->count, 1,
4690 'Renewal should not return the item even if a LOST payment has been made earlier'
4694 subtest 'Filling a hold should cancel existing transfer' => sub {
4697 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
4699 my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
4700 my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
4701 my $patron = $builder->build_object(
4703 class => 'Koha::Patrons',
4705 categorycode => $patron_category->{categorycode},
4706 branchcode => $libraryA->branchcode,
4711 my $item = $builder->build_sample_item({
4712 homebranch => $libraryB->branchcode,
4715 my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4716 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
4718 branchcode => $libraryA->branchcode,
4719 borrowernumber => $patron->borrowernumber,
4720 biblionumber => $item->biblionumber,
4721 itemnumber => $item->itemnumber
4723 my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
4724 is( $reserves->count, 1, "Reserve is placed");
4725 ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4726 my $reserve = $reserves->next;
4727 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
4728 $reserve->discard_changes;
4729 ok( $reserve->found eq 'W', "Reserve is marked waiting" );
4730 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
4733 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
4737 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4738 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4739 my $patron = $builder->build_object(
4741 class => 'Koha::Patrons',
4742 value => { categorycode => $patron_category->{categorycode} }
4746 my $biblionumber = $builder->build_sample_biblio(
4748 branchcode => $library->branchcode,
4752 # And the circulation rule
4753 Koha::CirculationRules->search->delete;
4754 Koha::CirculationRules->set_rules(
4756 categorycode => undef,
4758 branchcode => undef,
4761 lengthunit => 'days',
4767 source => 'CirculationRule',
4769 branchcode => undef,
4770 categorycode => undef,
4772 rule_name => 'lostreturn',
4773 rule_value => 'refund'
4778 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4781 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4782 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4784 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4786 my $item = $builder->build_sample_item(
4788 biblionumber => $biblionumber,
4789 library => $library->branchcode,
4790 replacementprice => '42',
4793 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4794 LostItem( $item->itemnumber, 'cli', 0 );
4795 $item->_result->itemlost(1);
4796 $item->_result->itemlost_on( $lost_on );
4797 $item->_result->update();
4799 my $a = Koha::Account::Lines->search(
4801 itemnumber => $item->id,
4802 borrowernumber => $patron->borrowernumber
4805 ok( $a, "Found accountline for lost fee" );
4806 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4807 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4808 $a = $a->get_from_storage;
4809 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4813 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4816 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4817 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4819 my $lost_on = dt_from_string->subtract( days => 6 )->date;
4821 my $item = $builder->build_sample_item(
4823 biblionumber => $biblionumber,
4824 library => $library->branchcode,
4825 replacementprice => '42',
4828 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4829 LostItem( $item->itemnumber, 'cli', 0 );
4830 $item->_result->itemlost(1);
4831 $item->_result->itemlost_on( $lost_on );
4832 $item->_result->update();
4834 my $a = Koha::Account::Lines->search(
4836 itemnumber => $item->id,
4837 borrowernumber => $patron->borrowernumber
4840 ok( $a, "Found accountline for lost fee" );
4841 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4842 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4843 $a = $a->get_from_storage;
4844 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4848 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4851 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4852 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4854 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4856 my $item = $builder->build_sample_item(
4858 biblionumber => $biblionumber,
4859 library => $library->branchcode,
4860 replacementprice => '42',
4863 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4864 LostItem( $item->itemnumber, 'cli', 0 );
4865 $item->_result->itemlost(1);
4866 $item->_result->itemlost_on( $lost_on );
4867 $item->_result->update();
4869 my $a = Koha::Account::Lines->search(
4871 itemnumber => $item->id,
4872 borrowernumber => $patron->borrowernumber
4875 ok( $a, "Found accountline for lost fee" );
4876 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4877 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4878 $a = $a->get_from_storage;
4879 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4883 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4886 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4887 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4889 my $lost_on = dt_from_string->subtract( days => 8 )->date;
4891 my $item = $builder->build_sample_item(
4893 biblionumber => $biblionumber,
4894 library => $library->branchcode,
4895 replacementprice => '42',
4898 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4899 LostItem( $item->itemnumber, 'cli', 0 );
4900 $item->_result->itemlost(1);
4901 $item->_result->itemlost_on( $lost_on );
4902 $item->_result->update();
4904 my $a = Koha::Account::Lines->search(
4906 itemnumber => $item->id,
4907 borrowernumber => $patron->borrowernumber
4911 ok( $a, "Found accountline for lost fee" );
4912 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4913 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4914 $a = $a->get_from_storage;
4915 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4920 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
4924 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4925 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4926 my $patron = $builder->build_object(
4928 class => 'Koha::Patrons',
4929 value => { categorycode => $patron_category->{categorycode} }
4932 my $patron2 = $builder->build_object(
4934 class => 'Koha::Patrons',
4935 value => { categorycode => $patron_category->{categorycode} }
4939 my $biblionumber = $builder->build_sample_biblio(
4941 branchcode => $library->branchcode,
4945 # And the circulation rule
4946 Koha::CirculationRules->search->delete;
4947 Koha::CirculationRules->set_rules(
4949 categorycode => undef,
4951 branchcode => undef,
4954 lengthunit => 'days',
4960 source => 'CirculationRule',
4962 branchcode => undef,
4963 categorycode => undef,
4965 rule_name => 'lostreturn',
4966 rule_value => 'refund'
4971 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4974 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4975 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4977 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4979 my $item = $builder->build_sample_item(
4981 biblionumber => $biblionumber,
4982 library => $library->branchcode,
4983 replacementprice => '42',
4986 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4987 LostItem( $item->itemnumber, 'cli', 0 );
4988 $item->_result->itemlost(1);
4989 $item->_result->itemlost_on( $lost_on );
4990 $item->_result->update();
4992 my $a = Koha::Account::Lines->search(
4994 itemnumber => $item->id,
4995 borrowernumber => $patron->borrowernumber
4998 ok( $a, "Found accountline for lost fee" );
4999 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5000 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5001 $a = $a->get_from_storage;
5002 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5007 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5010 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5011 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5013 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5015 my $item = $builder->build_sample_item(
5017 biblionumber => $biblionumber,
5018 library => $library->branchcode,
5019 replacementprice => '42',
5022 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5023 LostItem( $item->itemnumber, 'cli', 0 );
5024 $item->_result->itemlost(1);
5025 $item->_result->itemlost_on( $lost_on );
5026 $item->_result->update();
5028 my $a = Koha::Account::Lines->search(
5030 itemnumber => $item->id,
5031 borrowernumber => $patron->borrowernumber
5034 ok( $a, "Found accountline for lost fee" );
5035 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5036 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5037 $a = $a->get_from_storage;
5038 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5042 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5045 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5046 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5048 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5050 my $item = $builder->build_sample_item(
5052 biblionumber => $biblionumber,
5053 library => $library->branchcode,
5054 replacementprice => '42',
5057 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5058 LostItem( $item->itemnumber, 'cli', 0 );
5059 $item->_result->itemlost(1);
5060 $item->_result->itemlost_on( $lost_on );
5061 $item->_result->update();
5063 my $a = Koha::Account::Lines->search(
5065 itemnumber => $item->id,
5066 borrowernumber => $patron->borrowernumber
5069 ok( $a, "Found accountline for lost fee" );
5070 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5071 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5072 $a = $a->get_from_storage;
5073 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5077 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5080 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5081 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5083 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5085 my $item = $builder->build_sample_item(
5087 biblionumber => $biblionumber,
5088 library => $library->branchcode,
5089 replacementprice => '42',
5092 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5093 LostItem( $item->itemnumber, 'cli', 0 );
5094 $item->_result->itemlost(1);
5095 $item->_result->itemlost_on( $lost_on );
5096 $item->_result->update();
5098 my $a = Koha::Account::Lines->search(
5100 itemnumber => $item->id,
5101 borrowernumber => $patron->borrowernumber
5105 ok( $a, "Found accountline for lost fee" );
5106 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5107 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5108 $a = $a->get_from_storage;
5109 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5114 subtest 'transferbook tests' => sub {
5118 { C4::Circulation::transferbook({}); }
5119 'Koha::Exceptions::MissingParameter',
5120 'Koha::Patron->store raises an exception on missing params';
5123 { C4::Circulation::transferbook({to_branch=>'anything'}); }
5124 'Koha::Exceptions::MissingParameter',
5125 'Koha::Patron->store raises an exception on missing params';
5128 { C4::Circulation::transferbook({from_branch=>'anything'}); }
5129 'Koha::Exceptions::MissingParameter',
5130 'Koha::Patron->store raises an exception on missing params';
5132 my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
5133 is( $doreturn, 0, "No return without barcode");
5134 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5135 is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
5137 ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
5138 is( $doreturn, 0, "No return without barcode");
5139 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5140 is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
5144 subtest 'Checkout should correctly terminate a transfer' => sub {
5147 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5148 my $patron_1 = $builder->build_object(
5150 class => 'Koha::Patrons',
5151 value => { branchcode => $library_1->branchcode }
5154 my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
5155 my $patron_2 = $builder->build_object(
5157 class => 'Koha::Patrons',
5158 value => { branchcode => $library_2->branchcode }
5162 my $item = $builder->build_sample_item(
5164 library => $library_1->branchcode,
5168 t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
5169 my $reserve_id = AddReserve(
5171 branchcode => $library_2->branchcode,
5172 borrowernumber => $patron_2->borrowernumber,
5173 biblionumber => $item->biblionumber,
5174 itemnumber => $item->itemnumber,
5179 my $do_transfer = 1;
5180 ModItemTransfer( $item->itemnumber, $library_1->branchcode,
5181 $library_2->branchcode, 'Manual' );
5182 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
5183 GetOtherReserves( $item->itemnumber )
5184 ; # To put the Reason, it's what does returns.pl...
5185 my $hold = Koha::Holds->find($reserve_id);
5186 is( $hold->found, 'T', 'Hold is in transit' );
5187 my $transfer = $item->get_transfer;
5188 is( $transfer->frombranch, $library_1->branchcode );
5189 is( $transfer->tobranch, $library_2->branchcode );
5190 is( $transfer->reason, 'Reserve' );
5192 t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
5193 AddIssue( $patron_1->unblessed, $item->barcode );
5194 $transfer = $transfer->get_from_storage;
5195 isnt( $transfer->datearrived, undef );
5196 $hold = $hold->get_from_storage;
5197 is( $hold->found, undef, 'Hold is waiting' );
5198 is( $hold->priority, 1, );
5201 subtest 'AddIssue records staff who checked out item if appropriate' => sub {
5204 $module->mock( 'userenv', sub { { branch => $library->{id} } } );
5206 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5207 my $patron = $builder->build_object(
5209 class => 'Koha::Patrons',
5210 value => { categorycode => $patron_category->{categorycode} }
5213 my $issuer = $builder->build_object(
5215 class => 'Koha::Patrons',
5216 value => { categorycode => $patron_category->{categorycode} }
5219 my $item = $builder->build_sample_item(
5221 library => $library->{branchcode}
5225 $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->{borrowernumber} } } );
5227 my $dt_from = dt_from_string();
5228 my $dt_to = dt_from_string()->add( days => 7 );
5230 my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
5232 is( $issue->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
5234 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
5237 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
5239 is( $issue->issuer, $issuer->{borrowernumber}, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
5242 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
5245 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5246 my $patron_1 = $builder->build_object(
5248 class => 'Koha::Patrons',
5249 value => { branchcode => $library_1->branchcode }
5252 my $patron_2 = $builder->build_object(
5254 class => 'Koha::Patrons',
5255 value => { branchcode => $library_1->branchcode }
5259 my $item = $builder->build_sample_item(
5261 library => $library_1->branchcode,
5265 AddIssue( $patron_1->unblessed, $item->barcode );
5266 ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
5267 AddIssue( $patron_2->unblessed, $item->barcode );
5268 ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
5271 subtest "updateWrongTransfer tests" => sub {
5274 my $library1 = $builder->build_object( { class => 'Koha::Libraries' } );
5275 my $library2 = $builder->build_object( { class => 'Koha::Libraries' } );
5276 my $library3 = $builder->build_object( { class => 'Koha::Libraries' } );
5277 my $item = $builder->build_sample_item(
5279 homebranch => $library1->branchcode,
5280 holdingbranch => $library2->branchcode,
5281 datelastseen => undef
5285 my $transfer = $builder->build_object(
5287 class => 'Koha::Item::Transfers',
5289 itemnumber => $item->itemnumber,
5290 frombranch => $library2->branchcode,
5291 tobranch => $library1->branchcode,
5292 daterequested => dt_from_string,
5293 datesent => dt_from_string,
5294 datecancelled => undef,
5295 datearrived => undef,
5300 is( ref($transfer), 'Koha::Item::Transfer', 'Mock transfer added' );
5302 my $new_transfer = C4::Circulation::updateWrongTransfer($item->itemnumber, $library1->branchcode);
5303 is(ref($new_transfer), 'Koha::Item::Transfer', "updateWrongTransfer returns a 'Koha::Item::Transfer' object");
5304 ok( !$new_transfer->in_transit, "New transfer is NOT created as in transit (or cancelled)");
5306 my $original_transfer = $transfer->get_from_storage;
5307 ok( defined($original_transfer->datecancelled), "Original transfer was cancelled");
5308 is( $original_transfer->cancellation_reason, 'WrongTransfer', "Original transfer cancellation reason is 'WrongTransfer'");
5311 subtest "SendCirculationAlert" => sub {
5314 # When you would unsuspectingly call this unit test (with perl, not prove), you will be bitten by LOCK.
5315 # LOCK will commit changes and ruin your data
5316 # In order to prevent that, we will add KOHA_TESTING to $ENV; see further Circulation.pm
5317 $ENV{KOHA_TESTING} = 1;
5319 # Setup branch, borrowr, and notice
5320 my $library = $builder->build_object({ class => 'Koha::Libraries' });
5321 set_userenv( $library->unblessed);
5322 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5323 C4::Members::Messaging::SetMessagingPreference({
5324 borrowernumber => $patron->id,
5325 message_transport_types => ['email'],
5326 message_attribute_id => 5
5328 my $item = $builder->build_sample_item();
5329 my $checkin_notice = $builder->build_object({
5330 class => 'Koha::Notice::Templates',
5332 module => 'circulation',
5334 branchcode => $library->branchcode,
5335 name => 'Test Checkin',
5337 content => "Checkins:\n----\n[% biblio.title %]-[% old_checkout.issue_id %]\n----Thank you.",
5338 message_transport_type => 'email',
5343 # Checkout an item, mark it returned, generate a notice
5344 my $issue_1 = AddIssue( $patron->unblessed, $item->barcode);
5345 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5346 C4::Circulation::SendCirculationAlert({
5348 item => $item->unblessed,
5349 borrower => $patron->unblessed,
5350 branch => $library->branchcode,
5353 my $notice = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'CHECKIN' });
5354 is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\nThank you.", 'Letter generated with expected output on first checkin' );
5356 # Checkout an item, mark it returned, generate a notice
5357 my $issue_2 = AddIssue( $patron->unblessed, $item->barcode);
5358 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5359 C4::Circulation::SendCirculationAlert({
5361 item => $item->unblessed,
5362 borrower => $patron->unblessed,
5363 branch => $library->branchcode,
5366 $notice->discard_changes();
5367 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' );
5371 subtest "GetSoonestRenewDate tests" => sub {
5373 Koha::CirculationRules->set_rule(
5375 categorycode => undef,
5376 branchcode => undef,
5378 rule_name => 'norenewalbefore',
5382 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5383 my $item = $builder->build_sample_item();
5384 my $issue = AddIssue( $patron->unblessed, $item->barcode);
5385 my $datedue = dt_from_string( $issue->date_due() );
5388 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
5389 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
5391 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5392 $datedue->clone->add( days => -7 ),
5393 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5397 # Test 'date' setting for syspref NoRenewalBeforePrecision
5398 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5400 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5401 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
5402 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5406 Koha::CirculationRules->set_rule(
5408 categorycode => undef,
5409 branchcode => undef,
5411 rule_name => 'norenewalbefore',
5412 rule_value => undef,
5417 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5419 'Checkouts without auto-renewal can be renewed immediately if no norenewalbefore'
5422 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5423 $issue->auto_renew(1)->store;
5425 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5426 $datedue->clone->truncate( to => 'day' ),
5427 'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5429 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact' );
5431 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5433 'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5437 $schema->storage->txn_rollback;
5438 C4::Context->clear_syspref_cache();
5439 $branches = Koha::Libraries->search();
5440 for my $branch ( $branches->next ) {
5441 my $key = $branch->branchcode . "_holidays";
5442 $cache->clear_from_cache($key);