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 => 61;
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 );
2154 subtest 'AddIssue & illrequests.date_due' => sub {
2157 t::lib::Mocks::mock_preference( 'ILLModule', 1 );
2158 my $library = $builder->build( { source => 'Branch' } );
2159 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2160 my $item = $builder->build_sample_item();
2162 set_userenv($library);
2164 my $custom_date_due = '9999-12-18 12:34:56';
2165 my $expected_date_due = '9999-12-18 23:59:00';
2166 my $illrequest = Koha::Illrequest->new({
2167 borrowernumber => $patron->borrowernumber,
2168 biblio_id => $item->biblionumber,
2169 branchcode => $library->{'branchcode'},
2170 date_due => $custom_date_due,
2173 my $issue = AddIssue( $patron->unblessed, $item->barcode );
2174 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2176 $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2177 $item = $builder->build_sample_item();
2178 $custom_date_due = '9999-12-19';
2179 $expected_date_due = '9999-12-19 23:59:00';
2180 $illrequest = Koha::Illrequest->new({
2181 borrowernumber => $patron->borrowernumber,
2182 biblio_id => $item->biblionumber,
2183 branchcode => $library->{'branchcode'},
2184 date_due => $custom_date_due,
2187 $issue = AddIssue( $patron->unblessed, $item->barcode );
2188 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2191 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
2194 my $library = $builder->build( { source => 'Branch' } );
2195 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2196 my $item_1 = $builder->build_sample_item(
2198 library => $library->{branchcode},
2201 my $item_2 = $builder->build_sample_item(
2203 library => $library->{branchcode},
2206 Koha::CirculationRules->set_rules(
2208 categorycode => undef,
2210 branchcode => $library->{branchcode},
2212 reservesallowed => 25,
2214 lengthunit => 'days',
2215 renewalsallowed => 1,
2217 norenewalbefore => undef,
2227 my ( $error, $question, $alerts );
2229 # Patron cannot issue item_1, they have overdues
2230 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
2231 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, $yesterday ); # Add an overdue
2233 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
2234 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2235 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
2236 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
2238 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
2239 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2240 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2241 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
2243 # Patron cannot issue item_1, they are debarred
2244 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
2245 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
2246 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2247 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2248 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
2250 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
2251 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2252 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2253 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
2256 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
2259 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2260 my $patron_category_x = $builder->build_object(
2262 class => 'Koha::Patron::Categories',
2263 value => { category_type => 'X' }
2266 my $patron = $builder->build_object(
2268 class => 'Koha::Patrons',
2270 categorycode => $patron_category_x->categorycode,
2271 gonenoaddress => undef,
2278 my $item_1 = $builder->build_sample_item(
2280 library => $library->{branchcode},
2284 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
2285 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
2287 # TODO There are other tests to provide here
2290 subtest 'MultipleReserves' => sub {
2293 my $biblio = $builder->build_sample_biblio();
2295 my $branch = $library2->{branchcode};
2297 my $item_1 = $builder->build_sample_item(
2299 biblionumber => $biblio->biblionumber,
2301 replacementprice => 12.00,
2306 my $item_2 = $builder->build_sample_item(
2308 biblionumber => $biblio->biblionumber,
2310 replacementprice => 12.00,
2317 my $resdate = undef;
2318 my $expdate = undef;
2320 my $checkitem = undef;
2323 my %renewing_borrower_data = (
2324 firstname => 'John',
2325 surname => 'Renewal',
2326 categorycode => $patron_category->{categorycode},
2327 branchcode => $branch,
2329 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
2330 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
2331 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
2332 my $datedue = dt_from_string( $issue->date_due() );
2333 is (defined $issue->date_due(), 1, "item 1 checked out");
2334 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
2336 my %reserving_borrower_data1 = (
2337 firstname => 'Katrin',
2338 surname => 'Reservation',
2339 categorycode => $patron_category->{categorycode},
2340 branchcode => $branch,
2342 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
2345 branchcode => $branch,
2346 borrowernumber => $reserving_borrowernumber1,
2347 biblionumber => $biblio->biblionumber,
2348 priority => $priority,
2349 reservation_date => $resdate,
2350 expiration_date => $expdate,
2352 itemnumber => $checkitem,
2357 my %reserving_borrower_data2 = (
2358 firstname => 'Kirk',
2359 surname => 'Reservation',
2360 categorycode => $patron_category->{categorycode},
2361 branchcode => $branch,
2363 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
2366 branchcode => $branch,
2367 borrowernumber => $reserving_borrowernumber2,
2368 biblionumber => $biblio->biblionumber,
2369 priority => $priority,
2370 reservation_date => $resdate,
2371 expiration_date => $expdate,
2373 itemnumber => $checkitem,
2379 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2380 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2383 my $item_3 = $builder->build_sample_item(
2385 biblionumber => $biblio->biblionumber,
2387 replacementprice => 12.00,
2393 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2394 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2398 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2401 my $library = $builder->build( { source => 'Branch' } );
2402 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2404 my $biblionumber = $builder->build_sample_biblio(
2406 branchcode => $library->{branchcode},
2409 my $item_1 = $builder->build_sample_item(
2411 biblionumber => $biblionumber,
2412 library => $library->{branchcode},
2416 my $item_2 = $builder->build_sample_item(
2418 biblionumber => $biblionumber,
2419 library => $library->{branchcode},
2423 Koha::CirculationRules->set_rules(
2425 categorycode => undef,
2427 branchcode => $library->{branchcode},
2429 reservesallowed => 25,
2431 lengthunit => 'days',
2432 renewalsallowed => 1,
2434 norenewalbefore => undef,
2443 my ( $error, $question, $alerts );
2444 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, dt_from_string->add( days => 1 ) );
2446 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2447 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2449 { error => $error, alerts => $alerts },
2450 { error => {}, alerts => {} },
2451 'No error or alert should be raised'
2453 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2455 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2456 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2458 { error => $error, question => $question, alerts => $alerts },
2459 { error => {}, question => {}, alerts => {} },
2460 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2463 # Add a subscription
2464 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2466 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2467 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2469 { error => $error, question => $question, alerts => $alerts },
2470 { error => {}, question => {}, alerts => {} },
2471 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2474 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2475 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2477 { error => $error, question => $question, alerts => $alerts },
2478 { error => {}, question => {}, alerts => {} },
2479 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2483 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2486 my $library = $builder->build( { source => 'Branch' } );
2487 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2490 my $biblionumber = $builder->build_sample_biblio(
2492 branchcode => $library->{branchcode},
2495 my $item_1 = $builder->build_sample_item(
2497 biblionumber => $biblionumber,
2498 library => $library->{branchcode},
2501 my $item_2 = $builder->build_sample_item(
2503 biblionumber => $biblionumber,
2504 library => $library->{branchcode},
2508 # And the circulation rule
2509 Koha::CirculationRules->search->delete;
2510 Koha::CirculationRules->set_rules(
2512 categorycode => undef,
2514 branchcode => undef,
2517 firstremind => 1, # 1 day of grace
2518 finedays => 2, # 2 days of fine per day of overdue
2519 lengthunit => 'days',
2524 # Patron cannot issue item_1, they have overdues
2525 my $now = dt_from_string;
2526 my $five_days_ago = $now->clone->subtract( days => 5 );
2527 my $ten_days_ago = $now->clone->subtract( days => 10 );
2528 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2529 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2530 ; # Add another overdue
2532 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2533 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2534 my $debarments = Koha::Patron::Debarments::GetDebarments(
2535 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2536 is( scalar(@$debarments), 1 );
2538 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2539 # Same for the others
2540 my $expected_expiration = output_pref(
2542 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2543 dateformat => 'sql',
2547 is( $debarments->[0]->{expiration}, $expected_expiration );
2549 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2550 $debarments = Koha::Patron::Debarments::GetDebarments(
2551 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2552 is( scalar(@$debarments), 1 );
2553 $expected_expiration = output_pref(
2555 dt => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2556 dateformat => 'sql',
2560 is( $debarments->[0]->{expiration}, $expected_expiration );
2562 Koha::Patron::Debarments::DelUniqueDebarment(
2563 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2565 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2566 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2567 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2568 ; # Add another overdue
2569 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2570 $debarments = Koha::Patron::Debarments::GetDebarments(
2571 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2572 is( scalar(@$debarments), 1 );
2573 $expected_expiration = output_pref(
2575 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2576 dateformat => 'sql',
2580 is( $debarments->[0]->{expiration}, $expected_expiration );
2582 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2583 $debarments = Koha::Patron::Debarments::GetDebarments(
2584 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2585 is( scalar(@$debarments), 1 );
2586 $expected_expiration = output_pref(
2588 dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2589 dateformat => 'sql',
2593 is( $debarments->[0]->{expiration}, $expected_expiration );
2596 subtest 'AddReturn + suspension_chargeperiod' => sub {
2599 my $library = $builder->build( { source => 'Branch' } );
2600 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2602 my $biblionumber = $builder->build_sample_biblio(
2604 branchcode => $library->{branchcode},
2607 my $item_1 = $builder->build_sample_item(
2609 biblionumber => $biblionumber,
2610 library => $library->{branchcode},
2614 # And the issuing rule
2615 Koha::CirculationRules->search->delete;
2616 Koha::CirculationRules->set_rules(
2618 categorycode => '*',
2623 firstremind => 0, # 0 day of grace
2624 finedays => 2, # 2 days of fine per day of overdue
2625 suspension_chargeperiod => 1,
2626 lengthunit => 'days',
2631 my $now = dt_from_string;
2632 my $five_days_ago = $now->clone->subtract( days => 5 );
2633 # We want to charge 2 days every day, without grace
2634 # With 5 days of overdue: 5 * Z
2635 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2636 test_debarment_on_checkout(
2639 library => $library,
2641 due_date => $five_days_ago,
2642 expiration_date => $expected_expiration,
2646 # Same with undef firstremind
2647 Koha::CirculationRules->search->delete;
2648 Koha::CirculationRules->set_rules(
2650 categorycode => '*',
2655 firstremind => undef, # 0 day of grace
2656 finedays => 2, # 2 days of fine per day of overdue
2657 suspension_chargeperiod => 1,
2658 lengthunit => 'days',
2663 my $now = dt_from_string;
2664 my $five_days_ago = $now->clone->subtract( days => 5 );
2665 # We want to charge 2 days every day, without grace
2666 # With 5 days of overdue: 5 * Z
2667 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2668 test_debarment_on_checkout(
2671 library => $library,
2673 due_date => $five_days_ago,
2674 expiration_date => $expected_expiration,
2678 # We want to charge 2 days every 2 days, without grace
2679 # With 5 days of overdue: (5 * 2) / 2
2680 Koha::CirculationRules->set_rule(
2682 categorycode => undef,
2683 branchcode => undef,
2685 rule_name => 'suspension_chargeperiod',
2690 $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2691 test_debarment_on_checkout(
2694 library => $library,
2696 due_date => $five_days_ago,
2697 expiration_date => $expected_expiration,
2701 # We want to charge 2 days every 3 days, with 1 day of grace
2702 # With 5 days of overdue: ((5-1) / 3 ) * 2
2703 Koha::CirculationRules->set_rules(
2705 categorycode => undef,
2706 branchcode => undef,
2709 suspension_chargeperiod => 3,
2714 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2715 test_debarment_on_checkout(
2718 library => $library,
2720 due_date => $five_days_ago,
2721 expiration_date => $expected_expiration,
2725 # Use finesCalendar to know if holiday must be skipped to calculate the due date
2726 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2727 Koha::CirculationRules->set_rules(
2729 categorycode => undef,
2730 branchcode => undef,
2734 suspension_chargeperiod => 1,
2739 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2740 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2742 # Adding a holiday 2 days ago
2743 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2744 my $two_days_ago = $now->clone->subtract( days => 2 );
2745 $calendar->insert_single_holiday(
2746 day => $two_days_ago->day,
2747 month => $two_days_ago->month,
2748 year => $two_days_ago->year,
2749 title => 'holidayTest-2d',
2750 description => 'holidayDesc 2 days ago'
2752 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2753 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2754 test_debarment_on_checkout(
2757 library => $library,
2759 due_date => $five_days_ago,
2760 expiration_date => $expected_expiration,
2764 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2765 my $two_days_ahead = $now->clone->add( days => 2 );
2766 $calendar->insert_single_holiday(
2767 day => $two_days_ahead->day,
2768 month => $two_days_ahead->month,
2769 year => $two_days_ahead->year,
2770 title => 'holidayTest+2d',
2771 description => 'holidayDesc 2 days ahead'
2774 # Same as above, but we should skip D+2
2775 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2776 test_debarment_on_checkout(
2779 library => $library,
2781 due_date => $five_days_ago,
2782 expiration_date => $expected_expiration,
2786 # Adding another holiday, day of expiration date
2787 my $expected_expiration_dt = dt_from_string($expected_expiration);
2788 $calendar->insert_single_holiday(
2789 day => $expected_expiration_dt->day,
2790 month => $expected_expiration_dt->month,
2791 year => $expected_expiration_dt->year,
2792 title => 'holidayTest_exp',
2793 description => 'holidayDesc on expiration date'
2795 # Expiration date will be the day after
2796 test_debarment_on_checkout(
2799 library => $library,
2801 due_date => $five_days_ago,
2802 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2806 test_debarment_on_checkout(
2809 library => $library,
2811 return_date => $now->clone->add(days => 5),
2812 expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2816 test_debarment_on_checkout(
2819 library => $library,
2821 due_date => $now->clone->add(days => 1),
2822 return_date => $now->clone->add(days => 5),
2823 expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2829 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2832 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2833 my $patron1 = $builder->build_object(
2835 class => 'Koha::Patrons',
2837 library => $library->branchcode,
2838 categorycode => $patron_category->{categorycode}
2842 my $patron2 = $builder->build_object(
2844 class => 'Koha::Patrons',
2846 library => $library->branchcode,
2847 categorycode => $patron_category->{categorycode}
2852 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2854 my $item = $builder->build_sample_item(
2856 library => $library->branchcode,
2860 my ( $error, $question, $alerts );
2861 my $issue = AddIssue( $patron1->unblessed, $item->barcode );
2863 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2864 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2865 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' );
2867 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2868 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2869 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' );
2871 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2875 subtest 'AddReturn | is_overdue' => sub {
2878 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2879 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2880 t::lib::Mocks::mock_preference('finesMode', 'production');
2881 t::lib::Mocks::mock_preference('MaxFine', '100');
2883 my $library = $builder->build( { source => 'Branch' } );
2884 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2885 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2886 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2888 my $item = $builder->build_sample_item(
2890 library => $library->{branchcode},
2891 replacementprice => 7
2895 Koha::CirculationRules->search->delete;
2896 Koha::CirculationRules->set_rules(
2898 categorycode => undef,
2900 branchcode => undef,
2903 lengthunit => 'days',
2904 fine => 1, # Charge 1 every day of overdue
2910 my $now = dt_from_string;
2911 my $one_day_ago = $now->clone->subtract( days => 1 );
2912 my $two_days_ago = $now->clone->subtract( days => 2 );
2913 my $five_days_ago = $now->clone->subtract( days => 5 );
2914 my $ten_days_ago = $now->clone->subtract( days => 10 );
2915 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2917 # No return date specified, today will be used => 10 days overdue charged
2918 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2919 AddReturn( $item->barcode, $library->{branchcode} );
2920 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2921 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2923 # specify return date 5 days before => no overdue charged
2924 AddIssue( $patron->unblessed, $item->barcode, $five_days_ago ); # date due was 5d ago
2925 AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
2926 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2927 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2929 # specify return date 5 days later => 5 days overdue charged
2930 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2931 AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
2932 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2933 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2935 # specify return date 5 days later, specify exemptfine => no overdue charge
2936 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2937 AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago );
2938 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2939 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2941 subtest 'bug 22877 | Lost item return' => sub {
2945 my $issue = AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2947 # Fake fines cronjob on this checkout
2949 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2950 $ten_days_ago, $now );
2953 issue_id => $issue->issue_id,
2954 itemnumber => $item->itemnumber,
2955 borrowernumber => $patron->borrowernumber,
2957 due => output_pref($ten_days_ago)
2960 is( int( $patron->account->balance() ),
2961 10, "Overdue fine of 10 days overdue" );
2963 # Fake longoverdue with charge and not marking returned
2964 LostItem( $item->itemnumber, 'cronjob', 0 );
2965 is( int( $patron->account->balance() ),
2966 17, "Lost fine of 7 plus 10 days overdue" );
2968 # Now we return it today
2969 AddReturn( $item->barcode, $library->{branchcode} );
2970 is( int( $patron->account->balance() ),
2971 17, "Should have a single 10 days overdue fine and lost charge" );
2974 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2977 subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
2981 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2983 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
2985 # Fake fines cronjob on this checkout
2987 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2988 $one_day_ago, $now );
2991 issue_id => $issue->issue_id,
2992 itemnumber => $item->itemnumber,
2993 borrowernumber => $patron->borrowernumber,
2995 due => output_pref($one_day_ago)
2998 is( int( $patron->account->balance() ),
2999 1, "Overdue fine of 1 day overdue" );
3001 # Backdated return (dropbox mode example - charge should be removed)
3002 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3003 is( int( $patron->account->balance() ),
3004 0, "Overdue fine should be annulled" );
3005 my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3006 is( $lines->count, 0, "Overdue fine accountline has been removed");
3008 $issue = AddIssue( $patron->unblessed, $item->barcode, $two_days_ago ); # date due was 2d ago
3010 # Fake fines cronjob on this checkout
3012 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3013 $two_days_ago, $now );
3016 issue_id => $issue->issue_id,
3017 itemnumber => $item->itemnumber,
3018 borrowernumber => $patron->borrowernumber,
3020 due => output_pref($one_day_ago)
3023 is( int( $patron->account->balance() ),
3024 2, "Overdue fine of 2 days overdue" );
3026 # Payment made against fine
3027 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3028 my $debit = $lines->next;
3029 my $credit = $patron->account->add_credit(
3033 interface => 'test',
3036 $credit->apply( { debits => [$debit] } );
3038 is( int( $patron->account->balance() ),
3039 0, "Overdue fine should be paid off" );
3040 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3041 is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
3042 my $line = $lines->next;
3043 is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
3044 is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
3046 # Backdated return (dropbox mode example - charge should be removed)
3047 AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
3048 is( int( $patron->account->balance() ),
3049 -1, "Refund credit has been applied" );
3050 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
3051 is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
3053 $line = $lines->next;
3054 is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
3055 is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
3056 is($line->status,'RETURNED', "Overdue fine is fixed");
3057 $line = $lines->next;
3058 is($line->amount+0,-2, "Original payment amount remains as 2");
3059 is($line->amountoutstanding+0,0, "Original payment remains applied");
3060 $line = $lines->next;
3061 is($line->amount+0,-1, "Refund amount correctly set to 1");
3062 is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
3065 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3068 subtest 'bug 25417 | backdated return + exemptfine' => sub {
3072 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3074 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
3076 # Fake fines cronjob on this checkout
3078 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3079 $one_day_ago, $now );
3082 issue_id => $issue->issue_id,
3083 itemnumber => $item->itemnumber,
3084 borrowernumber => $patron->borrowernumber,
3086 due => output_pref($one_day_ago)
3089 is( int( $patron->account->balance() ),
3090 1, "Overdue fine of 1 day overdue" );
3092 # Backdated return (dropbox mode example - charge should no longer exist)
3093 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3094 is( int( $patron->account->balance() ),
3095 0, "Overdue fine should be annulled" );
3098 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3101 subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
3104 t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
3106 my $due_date = dt_from_string;
3107 my $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
3112 issue_id => $issue->issue_id,
3113 itemnumber => $item->itemnumber,
3114 borrowernumber => $patron->borrowernumber,
3116 due => output_pref($due_date)
3119 is( $patron->account->balance(),
3120 0.25, 'Overdue fine of $0.25 recorded' );
3122 # Backdate return to exact due date and time
3123 my ( undef, $message ) =
3124 AddReturn( $item->barcode, $library->{branchcode},
3128 Koha::Account::Lines->find( { issue_id => $issue->id } );
3129 ok( !$accountline, 'accountline removed as expected' );
3132 $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
3137 issue_id => $issue->issue_id,
3138 itemnumber => $item->itemnumber,
3139 borrowernumber => $patron->borrowernumber,
3141 due => output_pref($due_date)
3144 is( $patron->account->balance(),
3145 0.25, 'Overdue fine of $0.25 recorded' );
3147 # Partial pay accruing fine
3148 my $lines = Koha::Account::Lines->search(
3150 borrowernumber => $patron->borrowernumber,
3151 issue_id => $issue->id
3154 my $debit = $lines->next;
3155 my $credit = $patron->account->add_credit(
3159 interface => 'test',
3162 $credit->apply( { debits => [$debit] } );
3164 is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
3166 # Backdate return to exact due date and time
3167 ( undef, $message ) =
3168 AddReturn( $item->barcode, $library->{branchcode},
3171 $lines = Koha::Account::Lines->search(
3173 borrowernumber => $patron->borrowernumber,
3174 issue_id => $issue->id
3177 $accountline = $lines->next;
3178 is( $accountline->amountoutstanding + 0,
3179 0, 'Partially paid fee amount outstanding was reduced to 0' );
3180 is( $accountline->amount + 0,
3181 0, 'Partially paid fee amount was reduced to 0' );
3182 is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
3185 Koha::Account::Lines->search(
3186 { borrowernumber => $patron->borrowernumber } )->delete;
3189 subtest 'enh 23091 | Lost item return policies' => sub {
3192 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3194 my $branchcode_false =
3195 $builder->build( { source => 'Branch' } )->{branchcode};
3196 my $specific_rule_false = $builder->build(
3198 source => 'CirculationRule',
3200 branchcode => $branchcode_false,
3201 categorycode => undef,
3203 rule_name => 'lostreturn',
3208 my $branchcode_refund =
3209 $builder->build( { source => 'Branch' } )->{branchcode};
3210 my $specific_rule_refund = $builder->build(
3212 source => 'CirculationRule',
3214 branchcode => $branchcode_refund,
3215 categorycode => undef,
3217 rule_name => 'lostreturn',
3218 rule_value => 'refund'
3222 my $branchcode_restore =
3223 $builder->build( { source => 'Branch' } )->{branchcode};
3224 my $specific_rule_restore = $builder->build(
3226 source => 'CirculationRule',
3228 branchcode => $branchcode_restore,
3229 categorycode => undef,
3231 rule_name => 'lostreturn',
3232 rule_value => 'restore'
3236 my $branchcode_charge =
3237 $builder->build( { source => 'Branch' } )->{branchcode};
3238 my $specific_rule_charge = $builder->build(
3240 source => 'CirculationRule',
3242 branchcode => $branchcode_charge,
3243 categorycode => undef,
3245 rule_name => 'lostreturn',
3246 rule_value => 'charge'
3251 my $replacement_amount = 99.00;
3252 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
3253 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
3254 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
3255 t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 );
3256 t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
3258 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
3261 subtest 'lostreturn | false' => sub {
3264 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
3266 my $item = $builder->build_sample_item(
3268 replacementprice => $replacement_amount
3273 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3275 # Fake fines cronjob on this checkout
3277 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3278 $ten_days_ago, $now );
3281 issue_id => $issue->issue_id,
3282 itemnumber => $item->itemnumber,
3283 borrowernumber => $patron->borrowernumber,
3285 due => output_pref($ten_days_ago)
3288 my $overdue_fees = Koha::Account::Lines->search(
3290 borrowernumber => $patron->id,
3291 itemnumber => $item->itemnumber,
3292 debit_type_code => 'OVERDUE'
3295 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3296 my $overdue_fee = $overdue_fees->next;
3297 is( $overdue_fee->amount + 0,
3298 10, 'The right OVERDUE amount is generated' );
3299 is( $overdue_fee->amountoutstanding + 0,
3301 'The right OVERDUE amountoutstanding is generated' );
3303 # Simulate item marked as lost
3304 $item->itemlost(3)->store;
3305 C4::Circulation::LostItem( $item->itemnumber, 1 );
3307 my $lost_fee_lines = Koha::Account::Lines->search(
3309 borrowernumber => $patron->id,
3310 itemnumber => $item->itemnumber,
3311 debit_type_code => 'LOST'
3314 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3315 my $lost_fee_line = $lost_fee_lines->next;
3316 is( $lost_fee_line->amount + 0,
3317 $replacement_amount, 'The right LOST amount is generated' );
3318 is( $lost_fee_line->amountoutstanding + 0,
3319 $replacement_amount,
3320 'The right LOST amountoutstanding is generated' );
3321 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3324 my ( $returned, $message ) =
3325 AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
3327 $overdue_fee->discard_changes;
3328 is( $overdue_fee->amount + 0,
3329 10, 'The OVERDUE amount is left intact' );
3330 is( $overdue_fee->amountoutstanding + 0,
3332 'The OVERDUE amountoutstanding is left intact' );
3334 $lost_fee_line->discard_changes;
3335 is( $lost_fee_line->amount + 0,
3336 $replacement_amount, 'The LOST amount is left intact' );
3337 is( $lost_fee_line->amountoutstanding + 0,
3338 $replacement_amount,
3339 'The LOST amountoutstanding is left intact' );
3340 # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
3341 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3344 subtest 'lostreturn | refund' => sub {
3347 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
3349 my $item = $builder->build_sample_item(
3351 replacementprice => $replacement_amount
3356 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3358 # Fake fines cronjob on this checkout
3360 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3361 $ten_days_ago, $now );
3364 issue_id => $issue->issue_id,
3365 itemnumber => $item->itemnumber,
3366 borrowernumber => $patron->borrowernumber,
3368 due => output_pref($ten_days_ago)
3371 my $overdue_fees = Koha::Account::Lines->search(
3373 borrowernumber => $patron->id,
3374 itemnumber => $item->itemnumber,
3375 debit_type_code => 'OVERDUE'
3378 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3379 my $overdue_fee = $overdue_fees->next;
3380 is( $overdue_fee->amount + 0,
3381 10, 'The right OVERDUE amount is generated' );
3382 is( $overdue_fee->amountoutstanding + 0,
3384 'The right OVERDUE amountoutstanding is generated' );
3386 # Simulate item marked as lost
3387 $item->itemlost(3)->store;
3388 C4::Circulation::LostItem( $item->itemnumber, 1 );
3390 my $lost_fee_lines = Koha::Account::Lines->search(
3392 borrowernumber => $patron->id,
3393 itemnumber => $item->itemnumber,
3394 debit_type_code => 'LOST'
3397 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3398 my $lost_fee_line = $lost_fee_lines->next;
3399 is( $lost_fee_line->amount + 0,
3400 $replacement_amount, 'The right LOST amount is generated' );
3401 is( $lost_fee_line->amountoutstanding + 0,
3402 $replacement_amount,
3403 'The right LOST amountoutstanding is generated' );
3404 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3406 # Return the lost item
3407 my ( undef, $message ) =
3408 AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
3410 $overdue_fee->discard_changes;
3411 is( $overdue_fee->amount + 0,
3412 10, 'The OVERDUE amount is left intact' );
3413 is( $overdue_fee->amountoutstanding + 0,
3415 'The OVERDUE amountoutstanding is left intact' );
3417 $lost_fee_line->discard_changes;
3418 is( $lost_fee_line->amount + 0,
3419 $replacement_amount, 'The LOST amount is left intact' );
3420 is( $lost_fee_line->amountoutstanding + 0,
3422 'The LOST amountoutstanding is refunded' );
3423 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3426 subtest 'lostreturn | restore' => sub {
3429 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
3431 my $item = $builder->build_sample_item(
3433 replacementprice => $replacement_amount
3438 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode , $ten_days_ago);
3440 # Fake fines cronjob on this checkout
3442 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3443 $ten_days_ago, $now );
3446 issue_id => $issue->issue_id,
3447 itemnumber => $item->itemnumber,
3448 borrowernumber => $patron->borrowernumber,
3450 due => output_pref($ten_days_ago)
3453 my $overdue_fees = Koha::Account::Lines->search(
3455 borrowernumber => $patron->id,
3456 itemnumber => $item->itemnumber,
3457 debit_type_code => 'OVERDUE'
3460 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3461 my $overdue_fee = $overdue_fees->next;
3462 is( $overdue_fee->amount + 0,
3463 10, 'The right OVERDUE amount is generated' );
3464 is( $overdue_fee->amountoutstanding + 0,
3466 'The right OVERDUE amountoutstanding is generated' );
3468 # Simulate item marked as lost
3469 $item->itemlost(3)->store;
3470 C4::Circulation::LostItem( $item->itemnumber, 1 );
3472 my $lost_fee_lines = Koha::Account::Lines->search(
3474 borrowernumber => $patron->id,
3475 itemnumber => $item->itemnumber,
3476 debit_type_code => 'LOST'
3479 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3480 my $lost_fee_line = $lost_fee_lines->next;
3481 is( $lost_fee_line->amount + 0,
3482 $replacement_amount, 'The right LOST amount is generated' );
3483 is( $lost_fee_line->amountoutstanding + 0,
3484 $replacement_amount,
3485 'The right LOST amountoutstanding is generated' );
3486 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3488 # Simulate refunding overdue fees upon marking item as lost
3489 my $overdue_forgive = $patron->account->add_credit(
3492 user_id => $manager->borrowernumber,
3493 library_id => $branchcode_restore,
3494 interface => 'test',
3496 item_id => $item->itemnumber
3499 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3500 $overdue_fee->discard_changes;
3501 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3504 my ( undef, $message ) =
3505 AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
3507 $overdue_fee->discard_changes;
3508 is( $overdue_fee->amount + 0,
3509 10, 'The OVERDUE amount is left intact' );
3510 is( $overdue_fee->amountoutstanding + 0,
3512 'The OVERDUE amountoutstanding is restored' );
3514 $lost_fee_line->discard_changes;
3515 is( $lost_fee_line->amount + 0,
3516 $replacement_amount, 'The LOST amount is left intact' );
3517 is( $lost_fee_line->amountoutstanding + 0,
3519 'The LOST amountoutstanding is refunded' );
3520 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3523 subtest 'lostreturn | charge' => sub {
3526 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
3528 my $item = $builder->build_sample_item(
3530 replacementprice => $replacement_amount
3535 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3537 # Fake fines cronjob on this checkout
3539 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3540 $ten_days_ago, $now );
3543 issue_id => $issue->issue_id,
3544 itemnumber => $item->itemnumber,
3545 borrowernumber => $patron->borrowernumber,
3547 due => output_pref($ten_days_ago)
3550 my $overdue_fees = Koha::Account::Lines->search(
3552 borrowernumber => $patron->id,
3553 itemnumber => $item->itemnumber,
3554 debit_type_code => 'OVERDUE'
3557 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3558 my $overdue_fee = $overdue_fees->next;
3559 is( $overdue_fee->amount + 0,
3560 10, 'The right OVERDUE amount is generated' );
3561 is( $overdue_fee->amountoutstanding + 0,
3563 'The right OVERDUE amountoutstanding is generated' );
3565 # Simulate item marked as lost
3566 $item->itemlost(3)->store;
3567 C4::Circulation::LostItem( $item->itemnumber, 1 );
3569 my $lost_fee_lines = Koha::Account::Lines->search(
3571 borrowernumber => $patron->id,
3572 itemnumber => $item->itemnumber,
3573 debit_type_code => 'LOST'
3576 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3577 my $lost_fee_line = $lost_fee_lines->next;
3578 is( $lost_fee_line->amount + 0,
3579 $replacement_amount, 'The right LOST amount is generated' );
3580 is( $lost_fee_line->amountoutstanding + 0,
3581 $replacement_amount,
3582 'The right LOST amountoutstanding is generated' );
3583 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3585 # Simulate refunding overdue fees upon marking item as lost
3586 my $overdue_forgive = $patron->account->add_credit(
3589 user_id => $manager->borrowernumber,
3590 library_id => $branchcode_charge,
3591 interface => 'test',
3593 item_id => $item->itemnumber
3596 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3597 $overdue_fee->discard_changes;
3598 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3601 my ( undef, $message ) =
3602 AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
3604 $lost_fee_line->discard_changes;
3605 is( $lost_fee_line->amount + 0,
3606 $replacement_amount, 'The LOST amount is left intact' );
3607 is( $lost_fee_line->amountoutstanding + 0,
3609 'The LOST amountoutstanding is refunded' );
3610 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3612 $overdue_fees = Koha::Account::Lines->search(
3614 borrowernumber => $patron->id,
3615 itemnumber => $item->itemnumber,
3616 debit_type_code => 'OVERDUE'
3619 order_by => { '-asc' => 'accountlines_id'}
3622 is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
3623 $overdue_fee = $overdue_fees->next;
3624 is( $overdue_fee->amount + 0,
3625 10, 'The original OVERDUE amount is left intact' );
3626 is( $overdue_fee->amountoutstanding + 0,
3628 'The original OVERDUE amountoutstanding is left as forgiven' );
3629 $overdue_fee = $overdue_fees->next;
3630 is( $overdue_fee->amount + 0,
3631 5, 'The new OVERDUE amount is correct for the backdated return' );
3632 is( $overdue_fee->amountoutstanding + 0,
3634 'The new OVERDUE amountoutstanding is correct for the backdated return' );
3639 subtest '_FixOverduesOnReturn' => sub {
3642 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3643 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3645 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3647 my $branchcode = $library2->{branchcode};
3649 my $item = $builder->build_sample_item(
3651 biblionumber => $biblio->biblionumber,
3652 library => $branchcode,
3653 replacementprice => 99.00,
3658 my $patron = $builder->build( { source => 'Borrower' } );
3660 ## Start with basic call, should just close out the open fine
3661 my $accountline = Koha::Account::Line->new(
3663 borrowernumber => $patron->{borrowernumber},
3664 debit_type_code => 'OVERDUE',
3665 status => 'UNRETURNED',
3666 itemnumber => $item->itemnumber,
3668 amountoutstanding => 99.00,
3669 interface => 'test',
3673 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
3675 $accountline->_result()->discard_changes();
3677 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
3678 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3679 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3681 ## Run again, with exemptfine enabled
3684 debit_type_code => 'OVERDUE',
3685 status => 'UNRETURNED',
3686 amountoutstanding => 99.00,
3690 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3692 $accountline->_result()->discard_changes();
3693 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'APPLY' })->next();
3695 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
3696 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3697 is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
3698 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
3699 is( $offset->amount + 0, -99, "Amount of offset is correct" );
3700 my $credit = $offset->credit;
3701 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
3702 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
3703 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
3705 # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
3708 debit_type_code => 'OVERDUE',
3709 status => 'UNRETURNED',
3710 amountoutstanding => 0.00,
3715 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3717 $accountline->_result()->discard_changes();
3718 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'CREATE' })->next();
3719 is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
3720 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3721 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3724 subtest 'Set waiting flag' => sub {
3727 my $library_1 = $builder->build( { source => 'Branch' } );
3728 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3729 my $library_2 = $builder->build( { source => 'Branch' } );
3730 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3732 my $item = $builder->build_sample_item(
3734 library => $library_1->{branchcode},
3738 set_userenv( $library_2 );
3739 my $reserve_id = AddReserve(
3741 branchcode => $library_2->{branchcode},
3742 borrowernumber => $patron_2->{borrowernumber},
3743 biblionumber => $item->biblionumber,
3745 itemnumber => $item->itemnumber,
3749 set_userenv( $library_1 );
3750 my $do_transfer = 1;
3751 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3752 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3753 my $hold = Koha::Holds->find( $reserve_id );
3754 is( $hold->found, 'T', 'Hold is in transit' );
3756 my ( $status ) = CheckReserves($item->itemnumber);
3757 is( $status, 'Transferred', 'Hold is not waiting yet');
3759 set_userenv( $library_2 );
3761 AddReturn( $item->barcode, $library_2->{branchcode} );
3762 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3763 $hold = Koha::Holds->find( $reserve_id );
3764 is( $hold->found, 'W', 'Hold is waiting' );
3765 ( $status ) = CheckReserves($item->itemnumber);
3766 is( $status, 'Waiting', 'Now the hold is waiting');
3768 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
3769 set_userenv( $library_1 );
3770 (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
3771 $hold = Koha::Holds->find( $reserve_id );
3772 is( $hold->found, undef, 'Hold is no longer marked waiting' );
3773 is( $hold->priority, 1, "Hold is now priority one again");
3774 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
3775 is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
3776 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
3777 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
3778 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
3781 subtest 'Cancel transfers on lost items' => sub {
3784 my $library_to = $builder->build_object( { class => 'Koha::Libraries' } );
3785 my $item = $builder->build_sample_item();
3786 my $holdingbranch = $item->holdingbranch;
3787 # Historic transfer (datearrived is defined)
3788 my $old_transfer = $builder->build_object(
3790 class => 'Koha::Item::Transfers',
3792 itemnumber => $item->itemnumber,
3793 frombranch => $holdingbranch,
3794 tobranch => $library_to->branchcode,
3796 datesent => \'NOW()',
3797 datearrived => \'NOW()',
3798 datecancelled => undef,
3799 daterequested => \'NOW()'
3803 # Queued transfer (datesent is undefined)
3804 my $transfer_1 = $builder->build_object(
3806 class => 'Koha::Item::Transfers',
3808 itemnumber => $item->itemnumber,
3809 frombranch => $holdingbranch,
3810 tobranch => $library_to->branchcode,
3813 datearrived => undef,
3814 datecancelled => undef,
3815 daterequested => \'NOW()'
3819 # In transit transfer (datesent is defined, datearrived and datecancelled are both undefined)
3820 my $transfer_2 = $builder->build_object(
3822 class => 'Koha::Item::Transfers',
3824 itemnumber => $item->itemnumber,
3825 frombranch => $holdingbranch,
3826 tobranch => $library_to->branchcode,
3828 datesent => \'NOW()',
3829 datearrived => undef,
3830 datecancelled => undef,
3831 daterequested => \'NOW()'
3836 # Simulate item being marked as lost
3837 $item->itemlost(1)->store;
3838 LostItem( $item->itemnumber, 'test', 1 );
3840 $transfer_1->discard_changes;
3841 isnt($transfer_1->datecancelled, undef, "Queud transfer was cancelled upon item lost");
3842 is($transfer_1->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
3843 $transfer_2->discard_changes;
3844 isnt($transfer_2->datecancelled, undef, "Active transfer was cancelled upon item lost");
3845 is($transfer_2->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
3846 $old_transfer->discard_changes;
3847 is($old_transfer->datecancelled, undef, "Old transfers are unaffected");
3848 $item->discard_changes;
3849 is($item->holdingbranch, $holdingbranch, "Items holding branch remains unchanged");
3852 subtest 'CanBookBeIssued | is_overdue' => sub {
3855 # Set a simple circ policy
3856 Koha::CirculationRules->set_rules(
3858 categorycode => undef,
3859 branchcode => undef,
3863 reservesallowed => 25,
3865 lengthunit => 'days',
3866 renewalsallowed => 1,
3868 norenewalbefore => undef,
3876 my $now = dt_from_string()->truncate( to => 'day' );
3877 my $five_days_go = $now->clone->add( days => 5 );
3878 my $ten_days_go = $now->clone->add( days => 10);
3879 my $library = $builder->build( { source => 'Branch' } );
3880 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
3882 my $item = $builder->build_sample_item(
3884 library => $library->{branchcode},
3888 my $issue = AddIssue( $patron->unblessed, $item->barcode, $five_days_go ); # date due was 10d ago
3889 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
3890 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), output_pref({ str => $five_days_go, dateonly => 1}), "First issue works");
3891 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->barcode,$ten_days_go, undef, undef, undef);
3892 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
3893 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
3896 subtest 'ItemsDeniedRenewal preference' => sub {
3899 C4::Context->set_preference('ItemsDeniedRenewal','');
3901 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
3902 Koha::CirculationRules->set_rules(
3904 categorycode => '*',
3906 branchcode => $idr_lib->branchcode,
3908 reservesallowed => 25,
3910 lengthunit => 'days',
3911 renewalsallowed => 10,
3913 norenewalbefore => undef,
3921 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
3922 homebranch => $idr_lib->branchcode,
3926 itemcallnumber => undef,
3930 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
3931 homebranch => $idr_lib->branchcode,
3934 location => 'NOPROC'
3938 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
3939 branchcode => $idr_lib->branchcode,
3942 my $future = dt_from_string->add( days => 1 );
3943 my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3944 returndate => undef,
3947 borrowernumber => $idr_borrower->borrowernumber,
3948 itemnumber => $deny_book->itemnumber,
3949 onsite_checkout => 0,
3950 date_due => $future,
3953 my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3954 returndate => undef,
3957 borrowernumber => $idr_borrower->borrowernumber,
3958 itemnumber => $allow_book->itemnumber,
3959 onsite_checkout => 0,
3960 date_due => $future,
3966 my ( $idr_mayrenew, $idr_error ) =
3967 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3968 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3969 is( $idr_error, undef, 'Renewal allowed when no rules' );
3971 $idr_rules="withdrawn: [1]";
3973 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3974 ( $idr_mayrenew, $idr_error ) =
3975 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3976 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3977 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3978 ( $idr_mayrenew, $idr_error ) =
3979 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3980 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3981 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3983 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
3985 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3986 ( $idr_mayrenew, $idr_error ) =
3987 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3988 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
3989 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
3990 ( $idr_mayrenew, $idr_error ) =
3991 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3992 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3993 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3995 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
3997 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3998 ( $idr_mayrenew, $idr_error ) =
3999 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4000 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
4001 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
4002 ( $idr_mayrenew, $idr_error ) =
4003 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
4004 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
4005 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
4007 $idr_rules="itemcallnumber: [NULL]";
4008 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4009 ( $idr_mayrenew, $idr_error ) =
4010 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4011 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
4012 $idr_rules="itemcallnumber: ['']";
4013 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4014 ( $idr_mayrenew, $idr_error ) =
4015 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4016 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
4018 $idr_rules="itemnotes: [NULL]";
4019 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4020 ( $idr_mayrenew, $idr_error ) =
4021 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4022 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
4023 $idr_rules="itemnotes: ['']";
4024 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4025 ( $idr_mayrenew, $idr_error ) =
4026 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4027 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
4030 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
4033 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4034 my $library = $builder->build( { source => 'Branch' } );
4035 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4037 my $item = $builder->build_sample_item(
4039 library => $library->{branchcode},
4043 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4044 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4045 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4048 subtest 'CanBookBeIssued | notforloan' => sub {
4051 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
4053 my $library = $builder->build( { source => 'Branch' } );
4054 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4056 my $itemtype = $builder->build(
4058 source => 'Itemtype',
4059 value => { notforloan => undef, }
4062 my $item = $builder->build_sample_item(
4064 library => $library->{branchcode},
4065 itype => $itemtype->{itemtype},
4068 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4070 my ( $issuingimpossible, $needsconfirmation );
4073 subtest 'item-level_itypes = 1' => sub {
4076 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
4077 # Is for loan at item type and item level
4078 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4079 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4080 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4082 # not for loan at item type level
4083 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4084 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4085 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4088 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4089 'Item can not be issued, not for loan at item type level'
4092 # not for loan at item level
4093 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4094 $item->notforloan( 1 )->store;
4095 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4096 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4099 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4100 'Item can not be issued, not for loan at item type level'
4104 subtest 'item-level_itypes = 0' => sub {
4107 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4109 # We set another itemtype for biblioitem
4110 my $itemtype = $builder->build(
4112 source => 'Itemtype',
4113 value => { notforloan => undef, }
4117 # for loan at item type and item level
4118 $item->notforloan(0)->store;
4119 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4120 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4121 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4122 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4124 # not for loan at item type level
4125 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4126 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4127 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4130 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4131 'Item can not be issued, not for loan at item type level'
4134 # not for loan at item level
4135 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4136 $item->notforloan( 1 )->store;
4137 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4138 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4141 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4142 'Item can not be issued, not for loan at item type level'
4146 # TODO test with AllowNotForLoanOverride = 1
4149 subtest 'CanBookBeIssued | recalls' => sub {
4152 t::lib::Mocks::mock_preference("UseRecalls", 1);
4153 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4154 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4155 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4156 my $item = $builder->build_sample_item;
4157 Koha::CirculationRules->set_rules({
4158 branchcode => undef,
4160 categorycode => undef,
4162 recalls_allowed => 10,
4167 my $recall = Koha::Recall->new(
4168 { patron_id => $patron1->borrowernumber,
4169 biblio_id => $item->biblionumber,
4170 item_id => $item->itemnumber,
4172 pickup_library_id => $patron1->branchcode,
4176 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4177 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed an item-level recall on this item" );
4179 $recall->set_cancelled;
4181 # biblio-level recall
4182 $recall = Koha::Recall->new(
4183 { patron_id => $patron1->borrowernumber,
4184 biblio_id => $item->biblionumber,
4187 pickup_library_id => $patron1->branchcode,
4191 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4192 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed a biblio-level recall and this item is eligible to fill it" );
4194 $recall->set_cancelled;
4196 # biblio-level recall
4197 $recall = Koha::Recall->new(
4198 { patron_id => $patron1->borrowernumber,
4199 biblio_id => $item->biblionumber,
4202 pickup_library_id => $patron1->branchcode,
4205 $recall->set_waiting( { item => $item, expirationdate => dt_from_string() } );
4207 my ( undef, undef, undef, $messages ) = CanBookBeIssued( $patron1, $item->barcode, undef, undef, undef, undef );
4208 is( $messages->{RECALLED}, $recall->id, "This book can be issued by this patron and they have placed a recall" );
4210 $recall->set_cancelled;
4213 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
4216 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
4217 my $item = $builder->build_sample_item(
4219 onloan => '2018-01-01',
4223 AddReturn( $item->barcode, $item->homebranch );
4224 $item->discard_changes; # refresh
4225 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
4228 subtest 'AddReturn | recalls' => sub {
4231 t::lib::Mocks::mock_preference("UseRecalls", 1);
4232 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4233 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4234 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4235 my $item1 = $builder->build_sample_item;
4236 Koha::CirculationRules->set_rules({
4237 branchcode => undef,
4239 categorycode => undef,
4241 recalls_allowed => 10,
4245 # this item can fill a recall with pickup at this branch
4246 AddIssue( $patron1->unblessed, $item1->barcode );
4247 my $recall1 = Koha::Recall->new(
4248 { patron_id => $patron2->borrowernumber,
4249 biblio_id => $item1->biblionumber,
4250 item_id => $item1->itemnumber,
4252 pickup_library_id => $item1->homebranch,
4255 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4256 is( $messages->{RecallFound}->id, $recall1->id, "Recall found" );
4257 $recall1->set_cancelled;
4259 # this item can fill a recall but needs transfer
4260 AddIssue( $patron1->unblessed, $item1->barcode );
4261 $recall1 = Koha::Recall->new(
4262 { patron_id => $patron2->borrowernumber,
4263 biblio_id => $item1->biblionumber,
4264 item_id => $item1->itemnumber,
4266 pickup_library_id => $patron2->branchcode,
4269 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4270 is( $messages->{RecallNeedsTransfer}, $item1->homebranch, "Recall requiring transfer found" );
4271 $recall1->set_cancelled;
4273 # this item is already in transit, do not ask to transfer
4274 AddIssue( $patron1->unblessed, $item1->barcode );
4275 $recall1 = Koha::Recall->new(
4276 { patron_id => $patron2->borrowernumber,
4277 biblio_id => $item1->biblionumber,
4278 item_id => $item1->itemnumber,
4280 pickup_library_id => $patron2->branchcode,
4283 $recall1->start_transfer;
4284 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $patron2->branchcode );
4285 is( $messages->{TransferredRecall}->id, $recall1->id, "In transit recall found" );
4286 $recall1->set_cancelled;
4289 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
4294 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4296 my $issuing_charges = 15;
4297 my $title = 'A title';
4298 my $author = 'Author, An';
4299 my $barcode = 'WHATARETHEODDS';
4301 my $circ = Test::MockModule->new('C4::Circulation');
4303 'GetIssuingCharges',
4305 return $issuing_charges;
4309 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4310 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
4311 my $patron = $builder->build_object({
4312 class => 'Koha::Patrons',
4313 value => { branchcode => $library->id }
4316 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
4317 my $item_id = Koha::Item->new(
4319 biblionumber => $biblio->biblionumber,
4320 homebranch => $library->id,
4321 holdingbranch => $library->id,
4322 barcode => $barcode,
4323 replacementprice => 23.00,
4324 itype => $itemtype->id
4326 )->store->itemnumber;
4327 my $item = Koha::Items->find( $item_id );
4329 my $context = Test::MockModule->new('C4::Context');
4330 $context->mock( userenv => { branch => $library->id } );
4332 # Check the item out
4333 AddIssue( $patron->unblessed, $item->barcode );
4336 AddRenewal( $patron->borrowernumber, $item->itemnumber, $library->id, undef, {break=>"the_renewal"} );
4337 } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
4339 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
4340 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
4341 my %params_renewal = (
4342 timestamp => { -like => $date . "%" },
4343 module => "CIRCULATION",
4344 action => "RENEWAL",
4346 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
4347 AddRenewal( $patron->id, $item->id, $library->id );
4348 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4349 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
4351 my $checkouts = $patron->checkouts;
4352 # The following will fail if run on 00:00:00
4353 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
4355 my $lines = Koha::Account::Lines->search({
4356 borrowernumber => $patron->id,
4357 itemnumber => $item->id
4360 is( $lines->count, 2 );
4362 my $line = $lines->next;
4363 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
4364 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
4365 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
4367 $line = $lines->next;
4368 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
4369 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
4370 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
4372 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
4374 $context = Test::MockModule->new('C4::Context');
4375 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
4377 my $now = dt_from_string;
4378 $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
4379 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
4380 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
4381 $sth->execute($item->id, $library->id);
4382 my ($old_stats_size) = $sth->fetchrow_array;
4383 AddRenewal( $patron->id, $item->id, $library->id );
4384 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4385 $sth->execute($item->id, $library->id);
4386 my ($new_stats_size) = $sth->fetchrow_array;
4387 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
4388 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
4390 AddReturn( $item->id, $library->id, undef, $date );
4391 AddIssue( $patron->unblessed, $item->barcode, $now );
4392 AddRenewal( $patron->id, $item->id, $library->id, undef, undef, 1 );
4393 my $lines_skipped = Koha::Account::Lines->search({
4394 borrowernumber => $patron->id,
4395 itemnumber => $item->id
4397 is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
4401 subtest 'ProcessOfflinePayment() tests' => sub {
4408 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
4409 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4410 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
4412 is( $result, 'Success.', 'The right string is returned' );
4414 my $lines = $patron->account->lines;
4415 is( $lines->count, 1, 'line created correctly');
4417 my $line = $lines->next;
4418 is( $line->amount+0, $amount * -1, 'amount picked from params' );
4419 is( $line->branchcode, $library->id, 'branchcode set correctly' );
4423 subtest 'Incremented fee tests' => sub {
4426 my $dt = dt_from_string();
4427 Time::Fake->offset( $dt->epoch );
4429 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
4432 $builder->build_object( { class => 'Koha::Libraries' } )->store;
4434 $module->mock( 'userenv', sub { { branch => $library->id } } );
4436 my $patron = $builder->build_object(
4438 class => 'Koha::Patrons',
4439 value => { categorycode => $patron_category->{categorycode} }
4443 my $itemtype = $builder->build_object(
4445 class => 'Koha::ItemTypes',
4447 notforloan => undef,
4449 rentalcharge_daily => 1,
4450 rentalcharge_daily_calendar => 0
4455 my $item = $builder->build_sample_item(
4457 library => $library->{branchcode},
4458 itype => $itemtype->id,
4462 is( $itemtype->rentalcharge_daily+0,
4463 1, 'Daily rental charge stored and retreived correctly' );
4464 is( $item->effective_itemtype, $itemtype->id,
4465 "Itemtype set correctly for item" );
4467 my $now = dt_from_string;
4468 my $dt_from = $now->clone;
4469 my $dt_to = $now->clone->add( days => 7 );
4470 my $dt_to_renew = $now->clone->add( days => 13 );
4474 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4475 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4476 is( $accountline->amount+0, 7,
4477 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
4479 $accountline->delete();
4480 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4481 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4482 is( $accountline->amount+0, 6,
4483 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
4485 $accountline->delete();
4488 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
4489 $itemtype->rentalcharge_daily_calendar(1)->store();
4491 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4492 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4493 is( $accountline->amount+0, 7,
4494 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
4496 $accountline->delete();
4497 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4498 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4499 is( $accountline->amount+0, 6,
4500 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
4502 $accountline->delete();
4505 my $calendar = C4::Calendar->new( branchcode => $library->id );
4506 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
4508 ( $dt_from->day_of_week == 6 ) ? 0
4509 : ( $dt_from->day_of_week == 7 ) ? 1
4510 : $dt_from->day_of_week + 1;
4511 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
4512 $calendar->insert_week_day_holiday(
4513 weekday => $closed_day,
4514 title => 'Test holiday',
4515 description => 'Test holiday'
4518 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4519 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4520 is( $accountline->amount+0, 6,
4521 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
4523 $accountline->delete();
4524 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4525 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4526 is( $accountline->amount+0, 5,
4527 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
4529 $accountline->delete();
4532 $itemtype->rentalcharge(2)->store;
4533 is( $itemtype->rentalcharge+0, 2,
4534 'Rental charge updated and retreived correctly' );
4536 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4538 Koha::Account::Lines->search( { itemnumber => $item->id } );
4539 is( $accountlines->count, '2',
4540 "Fixed charge and accrued charge recorded distinctly" );
4541 $accountlines->delete();
4542 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4543 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
4544 is( $accountlines->count, '2',
4545 "Fixed charge and accrued charge recorded distinctly, for renewal" );
4546 $accountlines->delete();
4548 $itemtype->rentalcharge(0)->store;
4549 is( $itemtype->rentalcharge+0, 0,
4550 'Rental charge reset and retreived correctly' );
4553 Koha::CirculationRules->set_rule(
4555 categorycode => $patron->categorycode,
4556 itemtype => $itemtype->id,
4557 branchcode => $library->id,
4558 rule_name => 'lengthunit',
4559 rule_value => 'hours',
4563 $itemtype->rentalcharge_hourly('0.25')->store();
4564 is( $itemtype->rentalcharge_hourly,
4565 '0.25', 'Hourly rental charge stored and retreived correctly' );
4567 $dt_to = $now->clone->add( hours => 168 );
4568 $dt_to_renew = $now->clone->add( hours => 312 );
4570 $itemtype->rentalcharge_hourly_calendar(0)->store();
4572 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4573 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4574 is( $accountline->amount + 0, 42,
4575 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)" );
4576 $accountline->delete();
4577 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4578 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4579 is( $accountline->amount + 0, 36,
4580 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)" );
4581 $accountline->delete();
4584 $itemtype->rentalcharge_hourly_calendar(1)->store();
4586 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4587 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4588 is( $accountline->amount + 0, 36,
4589 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)" );
4590 $accountline->delete();
4591 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4592 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4593 is( $accountline->amount + 0, 30,
4594 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
4595 $accountline->delete();
4598 $calendar->delete_holiday( weekday => $closed_day );
4600 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4601 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4602 is( $accountline->amount + 0, 42,
4603 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u" );
4604 $accountline->delete();
4605 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4606 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4607 is( $accountline->amount + 0, 36,
4608 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)" );
4609 $accountline->delete();
4614 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
4617 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
4618 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4621 $builder->build_object( { class => 'Koha::Libraries' } )->store;
4622 my $patron = $builder->build_object(
4624 class => 'Koha::Patrons',
4625 value => { categorycode => $patron_category->{categorycode} }
4629 my $itemtype = $builder->build_object(
4631 class => 'Koha::ItemTypes',
4635 rentalcharge_daily => 0
4640 my $item = $builder->build_sample_item(
4642 library => $library->id,
4646 itype => $itemtype->id,
4650 my ( $issuingimpossible, $needsconfirmation );
4651 my $dt_from = dt_from_string();
4652 my $dt_due = $dt_from->clone->add( days => 3 );
4654 $itemtype->rentalcharge(1)->store;
4655 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4656 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
4657 $itemtype->rentalcharge('0')->store;
4658 $itemtype->rentalcharge_daily(1)->store;
4659 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4660 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
4661 $itemtype->rentalcharge_daily('0')->store;
4664 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
4667 t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
4669 my $patron = $builder->build_object(
4671 class => 'Koha::Patrons',
4672 value => { categorycode => $patron_category->{categorycode} }
4676 my $item = $builder->build_sample_item(
4678 materials => 'includes DVD',
4682 my $dt_due = dt_from_string->add( days => 3 );
4684 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4685 is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
4688 subtest 'Do not return on renewal (LOST charge)' => sub {
4691 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
4692 my $library = $builder->build_object( { class => "Koha::Libraries" } );
4693 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
4694 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
4696 my $biblio = $builder->build_sample_biblio;
4698 my $item = $builder->build_sample_item(
4700 biblionumber => $biblio->biblionumber,
4701 library => $library->branchcode,
4702 replacementprice => 99.00,
4707 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
4708 AddIssue( $patron->unblessed, $item->barcode );
4710 my $accountline = Koha::Account::Line->new(
4712 borrowernumber => $patron->borrowernumber,
4713 debit_type_code => 'LOST',
4715 itemnumber => $item->itemnumber,
4717 amountoutstanding => 12,
4718 interface => 'something',
4722 # AddRenewal doesn't call _FixAccountForLostAndFound
4723 AddIssue( $patron->unblessed, $item->barcode );
4725 is( $patron->checkouts->count, 1,
4726 'Renewal should not return the item even if a LOST payment has been made earlier'
4730 subtest 'Filling a hold should cancel existing transfer' => sub {
4733 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
4735 my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
4736 my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
4737 my $patron = $builder->build_object(
4739 class => 'Koha::Patrons',
4741 categorycode => $patron_category->{categorycode},
4742 branchcode => $libraryA->branchcode,
4747 my $item = $builder->build_sample_item({
4748 homebranch => $libraryB->branchcode,
4751 my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4752 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
4754 branchcode => $libraryA->branchcode,
4755 borrowernumber => $patron->borrowernumber,
4756 biblionumber => $item->biblionumber,
4757 itemnumber => $item->itemnumber
4759 my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
4760 is( $reserves->count, 1, "Reserve is placed");
4761 ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4762 my $reserve = $reserves->next;
4763 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
4764 $reserve->discard_changes;
4765 ok( $reserve->found eq 'W', "Reserve is marked waiting" );
4766 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
4769 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
4773 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4774 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4775 my $patron = $builder->build_object(
4777 class => 'Koha::Patrons',
4778 value => { categorycode => $patron_category->{categorycode} }
4782 my $biblionumber = $builder->build_sample_biblio(
4784 branchcode => $library->branchcode,
4788 # And the circulation rule
4789 Koha::CirculationRules->search->delete;
4790 Koha::CirculationRules->set_rules(
4792 categorycode => undef,
4794 branchcode => undef,
4797 lengthunit => 'days',
4803 source => 'CirculationRule',
4805 branchcode => undef,
4806 categorycode => undef,
4808 rule_name => 'lostreturn',
4809 rule_value => 'refund'
4814 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4817 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4818 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4820 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4822 my $item = $builder->build_sample_item(
4824 biblionumber => $biblionumber,
4825 library => $library->branchcode,
4826 replacementprice => '42',
4829 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4830 LostItem( $item->itemnumber, 'cli', 0 );
4831 $item->_result->itemlost(1);
4832 $item->_result->itemlost_on( $lost_on );
4833 $item->_result->update();
4835 my $a = Koha::Account::Lines->search(
4837 itemnumber => $item->id,
4838 borrowernumber => $patron->borrowernumber
4841 ok( $a, "Found accountline for lost fee" );
4842 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4843 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4844 $a = $a->get_from_storage;
4845 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4849 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4852 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4853 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4855 my $lost_on = dt_from_string->subtract( days => 6 )->date;
4857 my $item = $builder->build_sample_item(
4859 biblionumber => $biblionumber,
4860 library => $library->branchcode,
4861 replacementprice => '42',
4864 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4865 LostItem( $item->itemnumber, 'cli', 0 );
4866 $item->_result->itemlost(1);
4867 $item->_result->itemlost_on( $lost_on );
4868 $item->_result->update();
4870 my $a = Koha::Account::Lines->search(
4872 itemnumber => $item->id,
4873 borrowernumber => $patron->borrowernumber
4876 ok( $a, "Found accountline for lost fee" );
4877 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4878 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4879 $a = $a->get_from_storage;
4880 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4884 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4887 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4888 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4890 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4892 my $item = $builder->build_sample_item(
4894 biblionumber => $biblionumber,
4895 library => $library->branchcode,
4896 replacementprice => '42',
4899 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4900 LostItem( $item->itemnumber, 'cli', 0 );
4901 $item->_result->itemlost(1);
4902 $item->_result->itemlost_on( $lost_on );
4903 $item->_result->update();
4905 my $a = Koha::Account::Lines->search(
4907 itemnumber => $item->id,
4908 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" );
4919 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4922 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4923 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4925 my $lost_on = dt_from_string->subtract( days => 8 )->date;
4927 my $item = $builder->build_sample_item(
4929 biblionumber => $biblionumber,
4930 library => $library->branchcode,
4931 replacementprice => '42',
4934 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4935 LostItem( $item->itemnumber, 'cli', 0 );
4936 $item->_result->itemlost(1);
4937 $item->_result->itemlost_on( $lost_on );
4938 $item->_result->update();
4940 my $a = Koha::Account::Lines->search(
4942 itemnumber => $item->id,
4943 borrowernumber => $patron->borrowernumber
4947 ok( $a, "Found accountline for lost fee" );
4948 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4949 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4950 $a = $a->get_from_storage;
4951 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4956 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
4960 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4961 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4962 my $patron = $builder->build_object(
4964 class => 'Koha::Patrons',
4965 value => { categorycode => $patron_category->{categorycode} }
4968 my $patron2 = $builder->build_object(
4970 class => 'Koha::Patrons',
4971 value => { categorycode => $patron_category->{categorycode} }
4975 my $biblionumber = $builder->build_sample_biblio(
4977 branchcode => $library->branchcode,
4981 # And the circulation rule
4982 Koha::CirculationRules->search->delete;
4983 Koha::CirculationRules->set_rules(
4985 categorycode => undef,
4987 branchcode => undef,
4990 lengthunit => 'days',
4996 source => 'CirculationRule',
4998 branchcode => undef,
4999 categorycode => undef,
5001 rule_name => 'lostreturn',
5002 rule_value => 'refund'
5007 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5010 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5011 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5013 my $lost_on = dt_from_string->subtract( days => 7 )->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" );
5043 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5046 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5047 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5049 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5051 my $item = $builder->build_sample_item(
5053 biblionumber => $biblionumber,
5054 library => $library->branchcode,
5055 replacementprice => '42',
5058 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5059 LostItem( $item->itemnumber, 'cli', 0 );
5060 $item->_result->itemlost(1);
5061 $item->_result->itemlost_on( $lost_on );
5062 $item->_result->update();
5064 my $a = Koha::Account::Lines->search(
5066 itemnumber => $item->id,
5067 borrowernumber => $patron->borrowernumber
5070 ok( $a, "Found accountline for lost fee" );
5071 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5072 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5073 $a = $a->get_from_storage;
5074 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5078 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5081 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5082 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5084 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5086 my $item = $builder->build_sample_item(
5088 biblionumber => $biblionumber,
5089 library => $library->branchcode,
5090 replacementprice => '42',
5093 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5094 LostItem( $item->itemnumber, 'cli', 0 );
5095 $item->_result->itemlost(1);
5096 $item->_result->itemlost_on( $lost_on );
5097 $item->_result->update();
5099 my $a = Koha::Account::Lines->search(
5101 itemnumber => $item->id,
5102 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" );
5113 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5116 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5117 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5119 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5121 my $item = $builder->build_sample_item(
5123 biblionumber => $biblionumber,
5124 library => $library->branchcode,
5125 replacementprice => '42',
5128 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5129 LostItem( $item->itemnumber, 'cli', 0 );
5130 $item->_result->itemlost(1);
5131 $item->_result->itemlost_on( $lost_on );
5132 $item->_result->update();
5134 my $a = Koha::Account::Lines->search(
5136 itemnumber => $item->id,
5137 borrowernumber => $patron->borrowernumber
5141 ok( $a, "Found accountline for lost fee" );
5142 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5143 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5144 $a = $a->get_from_storage;
5145 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5150 subtest 'transferbook tests' => sub {
5154 { C4::Circulation::transferbook({}); }
5155 'Koha::Exceptions::MissingParameter',
5156 'Koha::Patron->store raises an exception on missing params';
5159 { C4::Circulation::transferbook({to_branch=>'anything'}); }
5160 'Koha::Exceptions::MissingParameter',
5161 'Koha::Patron->store raises an exception on missing params';
5164 { C4::Circulation::transferbook({from_branch=>'anything'}); }
5165 'Koha::Exceptions::MissingParameter',
5166 'Koha::Patron->store raises an exception on missing params';
5168 my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
5169 is( $doreturn, 0, "No return without barcode");
5170 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5171 is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
5173 ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
5174 is( $doreturn, 0, "No return without barcode");
5175 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5176 is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
5180 subtest 'Checkout should correctly terminate a transfer' => sub {
5183 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5184 my $patron_1 = $builder->build_object(
5186 class => 'Koha::Patrons',
5187 value => { branchcode => $library_1->branchcode }
5190 my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
5191 my $patron_2 = $builder->build_object(
5193 class => 'Koha::Patrons',
5194 value => { branchcode => $library_2->branchcode }
5198 my $item = $builder->build_sample_item(
5200 library => $library_1->branchcode,
5204 t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
5205 my $reserve_id = AddReserve(
5207 branchcode => $library_2->branchcode,
5208 borrowernumber => $patron_2->borrowernumber,
5209 biblionumber => $item->biblionumber,
5210 itemnumber => $item->itemnumber,
5215 my $do_transfer = 1;
5216 ModItemTransfer( $item->itemnumber, $library_1->branchcode,
5217 $library_2->branchcode, 'Manual' );
5218 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
5219 GetOtherReserves( $item->itemnumber )
5220 ; # To put the Reason, it's what does returns.pl...
5221 my $hold = Koha::Holds->find($reserve_id);
5222 is( $hold->found, 'T', 'Hold is in transit' );
5223 my $transfer = $item->get_transfer;
5224 is( $transfer->frombranch, $library_1->branchcode );
5225 is( $transfer->tobranch, $library_2->branchcode );
5226 is( $transfer->reason, 'Reserve' );
5228 t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
5229 AddIssue( $patron_1->unblessed, $item->barcode );
5230 $transfer = $transfer->get_from_storage;
5231 isnt( $transfer->datearrived, undef );
5232 $hold = $hold->get_from_storage;
5233 is( $hold->found, undef, 'Hold is waiting' );
5234 is( $hold->priority, 1, );
5237 subtest 'AddIssue records staff who checked out item if appropriate' => sub {
5240 $module->mock( 'userenv', sub { { branch => $library->{id} } } );
5242 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5243 my $patron = $builder->build_object(
5245 class => 'Koha::Patrons',
5246 value => { categorycode => $patron_category->{categorycode} }
5249 my $issuer = $builder->build_object(
5251 class => 'Koha::Patrons',
5252 value => { categorycode => $patron_category->{categorycode} }
5255 my $item = $builder->build_sample_item(
5257 library => $library->{branchcode}
5261 $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->{borrowernumber} } } );
5263 my $dt_from = dt_from_string();
5264 my $dt_to = dt_from_string()->add( days => 7 );
5266 my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
5268 is( $issue->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
5270 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
5273 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
5275 is( $issue->issuer, $issuer->{borrowernumber}, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
5278 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
5281 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5282 my $patron_1 = $builder->build_object(
5284 class => 'Koha::Patrons',
5285 value => { branchcode => $library_1->branchcode }
5288 my $patron_2 = $builder->build_object(
5290 class => 'Koha::Patrons',
5291 value => { branchcode => $library_1->branchcode }
5295 my $item = $builder->build_sample_item(
5297 library => $library_1->branchcode,
5301 AddIssue( $patron_1->unblessed, $item->barcode );
5302 ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
5303 AddIssue( $patron_2->unblessed, $item->barcode );
5304 ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
5307 subtest "updateWrongTransfer tests" => sub {
5310 my $library1 = $builder->build_object( { class => 'Koha::Libraries' } );
5311 my $library2 = $builder->build_object( { class => 'Koha::Libraries' } );
5312 my $library3 = $builder->build_object( { class => 'Koha::Libraries' } );
5313 my $item = $builder->build_sample_item(
5315 homebranch => $library1->branchcode,
5316 holdingbranch => $library2->branchcode,
5317 datelastseen => undef
5321 my $transfer = $builder->build_object(
5323 class => 'Koha::Item::Transfers',
5325 itemnumber => $item->itemnumber,
5326 frombranch => $library2->branchcode,
5327 tobranch => $library1->branchcode,
5328 daterequested => dt_from_string,
5329 datesent => dt_from_string,
5330 datecancelled => undef,
5331 datearrived => undef,
5336 is( ref($transfer), 'Koha::Item::Transfer', 'Mock transfer added' );
5338 my $new_transfer = C4::Circulation::updateWrongTransfer($item->itemnumber, $library1->branchcode);
5339 is(ref($new_transfer), 'Koha::Item::Transfer', "updateWrongTransfer returns a 'Koha::Item::Transfer' object");
5340 ok( !$new_transfer->in_transit, "New transfer is NOT created as in transit (or cancelled)");
5342 my $original_transfer = $transfer->get_from_storage;
5343 ok( defined($original_transfer->datecancelled), "Original transfer was cancelled");
5344 is( $original_transfer->cancellation_reason, 'WrongTransfer', "Original transfer cancellation reason is 'WrongTransfer'");
5347 subtest "SendCirculationAlert" => sub {
5350 # When you would unsuspectingly call this unit test (with perl, not prove), you will be bitten by LOCK.
5351 # LOCK will commit changes and ruin your data
5352 # In order to prevent that, we will add KOHA_TESTING to $ENV; see further Circulation.pm
5353 $ENV{KOHA_TESTING} = 1;
5355 # Setup branch, borrowr, and notice
5356 my $library = $builder->build_object({ class => 'Koha::Libraries' });
5357 set_userenv( $library->unblessed);
5358 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5359 C4::Members::Messaging::SetMessagingPreference({
5360 borrowernumber => $patron->id,
5361 message_transport_types => ['email'],
5362 message_attribute_id => 5
5364 my $item = $builder->build_sample_item();
5365 my $checkin_notice = $builder->build_object({
5366 class => 'Koha::Notice::Templates',
5368 module => 'circulation',
5370 branchcode => $library->branchcode,
5371 name => 'Test Checkin',
5373 content => "Checkins:\n----\n[% biblio.title %]-[% old_checkout.issue_id %]\n----Thank you.",
5374 message_transport_type => 'email',
5379 # Checkout an item, mark it returned, generate a notice
5380 my $issue_1 = AddIssue( $patron->unblessed, $item->barcode);
5381 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5382 C4::Circulation::SendCirculationAlert({
5384 item => $item->unblessed,
5385 borrower => $patron->unblessed,
5386 branch => $library->branchcode,
5389 my $notice = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'CHECKIN' });
5390 is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\nThank you.", 'Letter generated with expected output on first checkin' );
5392 # Checkout an item, mark it returned, generate a notice
5393 my $issue_2 = AddIssue( $patron->unblessed, $item->barcode);
5394 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5395 C4::Circulation::SendCirculationAlert({
5397 item => $item->unblessed,
5398 borrower => $patron->unblessed,
5399 branch => $library->branchcode,
5402 $notice->discard_changes();
5403 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' );
5407 subtest "GetSoonestRenewDate tests" => sub {
5409 Koha::CirculationRules->set_rule(
5411 categorycode => undef,
5412 branchcode => undef,
5414 rule_name => 'norenewalbefore',
5418 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5419 my $item = $builder->build_sample_item();
5420 my $issue = AddIssue( $patron->unblessed, $item->barcode);
5421 my $datedue = dt_from_string( $issue->date_due() );
5424 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
5425 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
5427 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5428 $datedue->clone->add( days => -7 ),
5429 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5433 # Test 'date' setting for syspref NoRenewalBeforePrecision
5434 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5436 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5437 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
5438 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5442 Koha::CirculationRules->set_rule(
5444 categorycode => undef,
5445 branchcode => undef,
5447 rule_name => 'norenewalbefore',
5448 rule_value => undef,
5453 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5455 'Checkouts without auto-renewal can be renewed immediately if no norenewalbefore'
5458 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5459 $issue->auto_renew(1)->store;
5461 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5462 $datedue->clone->truncate( to => 'day' ),
5463 'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5465 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact' );
5467 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5469 'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5473 $schema->storage->txn_rollback;
5474 C4::Context->clear_syspref_cache();
5475 $branches = Koha::Libraries->search();
5476 for my $branch ( $branches->next ) {
5477 my $key = $branch->branchcode . "_holidays";
5478 $cache->clear_from_cache($key);