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