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 => 65;
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( 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->unblessed, $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 $suspensions = $patron->restrictions->search({ type => 'SUSPENSION' } );
99 is( $suspensions->count, 1, 'Test at line ' . $line_number );
101 my $THE_suspension = $suspensions->next;
102 is( $THE_suspension->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 t::lib::Mocks::mock_preference('OverduesBlockRenewing','allow');
723 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
724 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
725 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
726 is( $renewokay, 1, '(Bug 8236), Can renew, this item is overdue but not pref does not block');
728 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
729 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
730 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is not overdue but patron has overdues');
731 is( $error, 'overdue', "Correct error returned");
732 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
733 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue so patron has overdues');
734 is( $error, 'overdue', "Correct error returned");
736 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
737 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
738 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
739 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
740 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
741 is( $error, 'overdue', "Correct error returned");
743 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
744 C4::Overdues::UpdateFine(
746 issue_id => $passeddatedue1->id(),
747 itemnumber => $item_7->itemnumber,
748 borrowernumber => $renewing_borrower->{borrowernumber},
750 due => Koha::DateUtils::output_pref($five_weeks_ago)
754 # Make sure fine calculation isn't skipped when adding renewal
755 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
757 # Calculate new due-date based on the present date not to incur
759 t::lib::Mocks::mock_preference('RenewalPeriodBase', 'now');
761 my $staff = $builder->build_object({ class => "Koha::Patrons" });
762 t::lib::Mocks::mock_userenv({ patron => $staff });
764 t::lib::Mocks::mock_preference('RenewalLog', 0);
765 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
766 my %params_renewal = (
767 timestamp => { -like => $date . "%" },
768 module => "CIRCULATION",
772 timestamp => { -like => $date . "%" },
773 module => "CIRCULATION",
776 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
777 my $dt = dt_from_string();
778 Time::Fake->offset( $dt->epoch );
779 my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
780 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
781 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
782 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
785 t::lib::Mocks::mock_preference('RenewalLog', 1);
786 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
787 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
788 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
789 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
790 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
792 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
793 is( $fines->count, 1, 'AddRenewal left fine' );
794 is( $fines->next->status, 'RENEWED', 'Fine on renewed item is closed out properly' );
797 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
798 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
799 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
800 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
801 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
802 $new_log_size = Koha::ActionLogs->count( \%params_issue );
803 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
805 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
809 # Test automatic renewal before value for "norenewalbefore" in policy is set
810 # In this case automatic renewal is not permitted prior to due date
811 my $item_4 = $builder->build_sample_item(
813 biblionumber => $biblio->biblionumber,
815 replacementprice => 16.00,
820 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
822 ( $renewokay, $error, $info ) =
823 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
824 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
825 is( $error, 'auto_too_soon',
826 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
827 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'" );
830 branchcode => $branch,
831 borrowernumber => $reserving_borrowernumber,
832 biblionumber => $biblio->biblionumber,
833 itemnumber => $bibitems,
834 priority => $priority,
835 reservation_date => $resdate,
836 expiration_date => $expdate,
839 itemnumber => $item_4->itemnumber,
843 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
844 is( $renewokay, 0, 'Still should not be able to renew' );
845 is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' );
846 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, undef, 1 );
847 is( $renewokay, 0, 'Still should not be able to renew' );
848 is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' );
849 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'" );
850 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
851 is( $renewokay, 0, 'Still should not be able to renew' );
852 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
853 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1, 1 );
854 is( $renewokay, 0, 'Still should not be able to renew' );
855 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
856 $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
857 Koha::Cache::Memory::Lite->flush();
858 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
859 is( $renewokay, 0, 'Still should not be able to renew' );
860 is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
861 ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
865 $renewing_borrower_obj->autorenew_checkouts(0)->store;
866 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
867 is( $renewokay, 1, 'No renewal before is undef, but patron opted out of auto_renewal' );
868 $renewing_borrower_obj->autorenew_checkouts(1)->store;
872 # Test premature manual renewal
873 Koha::CirculationRules->set_rule(
875 categorycode => undef,
878 rule_name => 'norenewalbefore',
883 ( $renewokay, $error, $info ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
884 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
885 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
886 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
889 # Test premature automatic renewal
890 ( $renewokay, $error, $info ) =
891 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
892 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
893 is( $error, 'auto_too_soon',
894 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
896 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'auto_too_soon'");
898 $renewing_borrower_obj->autorenew_checkouts(0)->store;
899 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
900 is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' );
901 is( $error, 'too_soon', 'Error is too_soon, no auto' );
902 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
903 $renewing_borrower_obj->autorenew_checkouts(1)->store;
905 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
906 # and test automatic renewal again
907 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
908 Koha::Cache::Memory::Lite->flush();
909 ( $renewokay, $error, $info ) =
910 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
911 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
912 is( $error, 'auto_too_soon',
913 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
915 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
917 $renewing_borrower_obj->autorenew_checkouts(0)->store;
918 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
919 is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' );
920 is( $error, 'too_soon', 'Error is too_soon, no auto' );
921 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
922 $renewing_borrower_obj->autorenew_checkouts(1)->store;
924 # Change policy so that loans can be renewed 99 days prior to the due date
925 # and test automatic renewal again
926 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
927 Koha::Cache::Memory::Lite->flush();
928 ( $renewokay, $error ) =
929 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
930 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
931 is( $error, 'auto_renew',
932 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
935 $renewing_borrower_obj->autorenew_checkouts(0)->store;
936 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
937 is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' );
938 $renewing_borrower_obj->autorenew_checkouts(1)->store;
940 subtest "too_late_renewal / no_auto_renewal_after" => sub {
942 my $item_to_auto_renew = $builder->build_sample_item(
944 biblionumber => $biblio->biblionumber,
949 my $ten_days_before = dt_from_string->add( days => -10 );
950 my $ten_days_ahead = dt_from_string->add( days => 10 );
951 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
953 Koha::CirculationRules->set_rules(
955 categorycode => undef,
959 norenewalbefore => '7',
960 no_auto_renewal_after => '9',
964 ( $renewokay, $error ) =
965 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
966 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
967 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
969 Koha::CirculationRules->set_rules(
971 categorycode => undef,
975 norenewalbefore => '7',
976 no_auto_renewal_after => '10',
980 ( $renewokay, $error ) =
981 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
982 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
983 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
985 Koha::CirculationRules->set_rules(
987 categorycode => undef,
991 norenewalbefore => '7',
992 no_auto_renewal_after => '11',
996 ( $renewokay, $error ) =
997 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
998 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
999 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
1001 Koha::CirculationRules->set_rules(
1003 categorycode => undef,
1004 branchcode => undef,
1007 norenewalbefore => '10',
1008 no_auto_renewal_after => '11',
1012 ( $renewokay, $error ) =
1013 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1014 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1015 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1017 Koha::CirculationRules->set_rules(
1019 categorycode => undef,
1020 branchcode => undef,
1023 norenewalbefore => '10',
1024 no_auto_renewal_after => undef,
1025 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1029 ( $renewokay, $error ) =
1030 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1031 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1032 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1034 Koha::CirculationRules->set_rules(
1036 categorycode => undef,
1037 branchcode => undef,
1040 norenewalbefore => '7',
1041 no_auto_renewal_after => '15',
1042 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1046 ( $renewokay, $error ) =
1047 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1048 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1049 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1051 Koha::CirculationRules->set_rules(
1053 categorycode => undef,
1054 branchcode => undef,
1057 norenewalbefore => '10',
1058 no_auto_renewal_after => undef,
1059 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
1063 ( $renewokay, $error ) =
1064 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1065 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1066 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1069 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
1071 my $item_to_auto_renew = $builder->build_sample_item(
1073 biblionumber => $biblio->biblionumber,
1078 my $ten_days_before = dt_from_string->add( days => -10 );
1079 my $ten_days_ahead = dt_from_string->add( days => 10 );
1080 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1082 Koha::CirculationRules->set_rules(
1084 categorycode => undef,
1085 branchcode => undef,
1088 norenewalbefore => '10',
1089 no_auto_renewal_after => '11',
1093 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
1094 C4::Context->set_preference('OPACFineNoRenewals','10');
1095 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1096 my $fines_amount = 5;
1097 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
1098 $account->add_debit(
1100 amount => $fines_amount,
1101 interface => 'test',
1103 item_id => $item_to_auto_renew->itemnumber,
1104 description => "Some fines"
1106 )->status('RETURNED')->store;
1107 ( $renewokay, $error ) =
1108 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1109 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1110 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
1112 $account->add_debit(
1114 amount => $fines_amount,
1115 interface => 'test',
1117 item_id => $item_to_auto_renew->itemnumber,
1118 description => "Some fines"
1120 )->status('RETURNED')->store;
1121 ( $renewokay, $error ) =
1122 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1123 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1124 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
1126 $account->add_debit(
1128 amount => $fines_amount,
1129 interface => 'test',
1131 item_id => $item_to_auto_renew->itemnumber,
1132 description => "Some fines"
1134 )->status('RETURNED')->store;
1135 ( $renewokay, $error ) =
1136 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1137 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1138 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
1140 $account->add_credit(
1142 amount => $fines_amount,
1143 interface => 'test',
1145 description => "Some payment"
1148 ( $renewokay, $error ) =
1149 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1150 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1151 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1153 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
1154 ( $renewokay, $error ) =
1155 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1156 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1157 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1159 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
1160 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1163 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
1165 my $item_to_auto_renew = $builder->build_sample_item(
1167 biblionumber => $biblio->biblionumber,
1172 Koha::CirculationRules->set_rules(
1174 categorycode => undef,
1175 branchcode => undef,
1178 norenewalbefore => 10,
1179 no_auto_renewal_after => 11,
1184 my $ten_days_before = dt_from_string->add( days => -10 );
1185 my $ten_days_ahead = dt_from_string->add( days => 10 );
1187 # Patron is expired and BlockExpiredPatronOpacActions=0
1188 # => auto renew is allowed
1189 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
1190 my $patron = $expired_borrower;
1191 my $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1192 ( $renewokay, $error ) =
1193 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1194 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1195 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
1196 Koha::Checkouts->find( $checkout->issue_id )->delete;
1199 # Patron is expired and BlockExpiredPatronOpacActions=1
1200 # => auto renew is not allowed
1201 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1202 $patron = $expired_borrower;
1203 $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1204 ( $renewokay, $error ) =
1205 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1206 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1207 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
1208 Koha::Checkouts->find( $checkout->issue_id )->delete;
1211 # Patron is not expired and BlockExpiredPatronOpacActions=1
1212 # => auto renew is allowed
1213 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1214 $patron = $renewing_borrower;
1215 $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1216 ( $renewokay, $error ) =
1217 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1218 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1219 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1220 Koha::Checkouts->find( $checkout->issue_id )->delete;
1223 subtest "GetLatestAutoRenewDate" => sub {
1225 my $item_to_auto_renew = $builder->build_sample_item(
1227 biblionumber => $biblio->biblionumber,
1232 my $ten_days_before = dt_from_string->add( days => -10 );
1233 my $ten_days_ahead = dt_from_string->add( days => 10 );
1234 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1235 Koha::CirculationRules->set_rules(
1237 categorycode => undef,
1238 branchcode => undef,
1241 norenewalbefore => '7',
1242 no_auto_renewal_after => '',
1243 no_auto_renewal_after_hard_limit => undef,
1247 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1248 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' );
1249 my $five_days_before = dt_from_string->add( days => -5 );
1250 Koha::CirculationRules->set_rules(
1252 categorycode => undef,
1253 branchcode => undef,
1256 norenewalbefore => '10',
1257 no_auto_renewal_after => '5',
1258 no_auto_renewal_after_hard_limit => undef,
1262 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1263 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1264 $five_days_before->truncate( to => 'minute' ),
1265 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1267 my $five_days_ahead = dt_from_string->add( days => 5 );
1268 $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1269 $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1270 $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1271 Koha::Cache::Memory::Lite->flush();
1272 Koha::CirculationRules->set_rules(
1274 categorycode => undef,
1275 branchcode => undef,
1278 norenewalbefore => '10',
1279 no_auto_renewal_after => '15',
1280 no_auto_renewal_after_hard_limit => undef,
1284 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1285 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1286 $five_days_ahead->truncate( to => 'minute' ),
1287 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1289 my $two_days_ahead = dt_from_string->add( days => 2 );
1290 Koha::CirculationRules->set_rules(
1292 categorycode => undef,
1293 branchcode => undef,
1296 norenewalbefore => '10',
1297 no_auto_renewal_after => '',
1298 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1302 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1303 is( $latest_auto_renew_date->truncate( to => 'day' ),
1304 $two_days_ahead->truncate( to => 'day' ),
1305 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1307 Koha::CirculationRules->set_rules(
1309 categorycode => undef,
1310 branchcode => undef,
1313 norenewalbefore => '10',
1314 no_auto_renewal_after => '15',
1315 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1319 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1320 is( $latest_auto_renew_date->truncate( to => 'day' ),
1321 $two_days_ahead->truncate( to => 'day' ),
1322 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1328 # set policy to forbid renewals
1329 Koha::CirculationRules->set_rules(
1331 categorycode => undef,
1332 branchcode => undef,
1335 norenewalbefore => undef,
1336 renewalsallowed => 0,
1341 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1342 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1343 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1345 # Too many unseen renewals
1346 Koha::CirculationRules->set_rules(
1348 categorycode => undef,
1349 branchcode => undef,
1352 unseen_renewals_allowed => 2,
1353 renewalsallowed => 10,
1357 t::lib::Mocks::mock_preference('UnseenRenewals', 1);
1358 $dbh->do('UPDATE issues SET unseen_renewals = 2 where borrowernumber = ? AND itemnumber = ?', undef, ($renewing_borrowernumber, $item_1->itemnumber));
1359 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1360 is( $renewokay, 0, 'Cannot renew, 0 unseen renewals allowed');
1361 is( $error, 'too_unseen', 'Cannot renew, returned code is too_unseen');
1362 Koha::CirculationRules->set_rules(
1364 categorycode => undef,
1365 branchcode => undef,
1368 norenewalbefore => undef,
1369 renewalsallowed => 0,
1373 t::lib::Mocks::mock_preference('UnseenRenewals', 0);
1375 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1376 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1377 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1379 C4::Overdues::UpdateFine(
1381 issue_id => $issue->id(),
1382 itemnumber => $item_1->itemnumber,
1383 borrowernumber => $renewing_borrower->{borrowernumber},
1386 due => Koha::DateUtils::output_pref($datedue)
1390 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
1391 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1392 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1393 is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1394 is( $line->amount+0, 15, 'Account line amount is 15.00' );
1395 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
1397 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1398 is( $offset->type, 'CREATE', 'Account offset type is CREATE' );
1399 is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1401 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1402 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1404 LostItem( $item_1->itemnumber, 'test', 1 );
1406 $line = Koha::Account::Lines->find($line->id);
1407 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1408 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1410 my $item = Koha::Items->find($item_1->itemnumber);
1411 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1412 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1413 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1415 my $total_due = $dbh->selectrow_array(
1416 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1417 undef, $renewing_borrower->{borrowernumber}
1420 is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1422 C4::Context->dbh->do("DELETE FROM accountlines");
1424 C4::Overdues::UpdateFine(
1426 issue_id => $issue2->id(),
1427 itemnumber => $item_2->itemnumber,
1428 borrowernumber => $renewing_borrower->{borrowernumber},
1431 due => Koha::DateUtils::output_pref($datedue)
1435 LostItem( $item_2->itemnumber, 'test', 0 );
1437 my $item2 = Koha::Items->find($item_2->itemnumber);
1438 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1439 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1441 $total_due = $dbh->selectrow_array(
1442 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1443 undef, $renewing_borrower->{borrowernumber}
1446 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1448 my $future = dt_from_string();
1449 $future->add( days => 7 );
1450 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1451 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1453 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1454 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1455 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1456 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1457 LostItem( $item_3->itemnumber, 'test', 0 );
1458 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1459 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1461 $accountline->description,
1462 sprintf( "%s %s %s",
1463 $item_3->biblio->title || '',
1464 $item_3->barcode || '',
1465 $item_3->itemcallnumber || '' ),
1466 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1470 t::lib::Mocks::mock_preference('UseRecalls', 1);
1471 Koha::CirculationRules->set_rules({
1472 categorycode => undef,
1473 branchcode => undef,
1476 recalls_allowed => 10,
1477 renewalsallowed => 5,
1480 my $recall_borrower = $builder->build_object({ class => 'Koha::Patrons' });
1481 my $recall_biblio = $builder->build_object({ class => 'Koha::Biblios' });
1482 my $recall_item1 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $recall_biblio->biblionumber } });
1483 my $recall_item2 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $recall_biblio->biblionumber } });
1485 AddIssue( $renewing_borrower, $recall_item1->barcode );
1487 # item-level and this item: renewal not allowed
1488 my $recall = Koha::Recall->new({
1489 biblio_id => $recall_item1->biblionumber,
1490 item_id => $recall_item1->itemnumber,
1491 patron_id => $recall_borrower->borrowernumber,
1492 pickup_library_id => $recall_borrower->branchcode,
1495 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1496 is( $error, 'recalled', 'Cannot renew item that has been recalled' );
1497 $recall->set_cancelled;
1499 # biblio-level requested recall: renewal not allowed
1500 $recall = Koha::Recall->new({
1501 biblio_id => $recall_item1->biblionumber,
1503 patron_id => $recall_borrower->borrowernumber,
1504 pickup_library_id => $recall_borrower->branchcode,
1507 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1508 is( $error, 'recalled', 'Cannot renew item if biblio is recalled and has no item allocated' );
1509 $recall->set_cancelled;
1511 # item-level and not this item: renewal allowed
1512 $recall = Koha::Recall->new({
1513 biblio_id => $recall_item2->biblionumber,
1514 item_id => $recall_item2->itemnumber,
1515 patron_id => $recall_borrower->borrowernumber,
1516 pickup_library_id => $recall_borrower->branchcode,
1519 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1520 is( $renewokay, 1, 'Can renew item if item-level recall on biblio is not on this item' );
1521 $recall->set_cancelled;
1523 # biblio-level waiting recall: renewal allowed
1524 $recall = Koha::Recall->new({
1525 biblio_id => $recall_item1->biblionumber,
1527 patron_id => $recall_borrower->borrowernumber,
1528 pickup_library_id => $recall_borrower->branchcode,
1531 $recall->set_waiting({ item => $recall_item1 });
1532 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1533 is( $renewokay, 1, 'Can renew item if biblio-level recall has already been allocated an item' );
1534 $recall->set_cancelled;
1537 subtest "GetUpcomingDueIssues" => sub {
1540 my $branch = $library2->{branchcode};
1542 #Create another record
1543 my $biblio2 = $builder->build_sample_biblio();
1546 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1547 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1548 my $item_3 = $builder->build_sample_item(
1550 biblionumber => $biblio2->biblionumber,
1558 my %a_borrower_data = (
1559 firstname => 'Fridolyn',
1560 surname => 'SOMERS',
1561 categorycode => $patron_category->{categorycode},
1562 branchcode => $branch,
1565 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1566 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1568 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1569 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1570 my $today = DateTime->today(time_zone => C4::Context->tz());
1572 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1573 my $datedue = dt_from_string( $issue->date_due() );
1574 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1575 my $datedue2 = dt_from_string( $issue->date_due() );
1579 # GetUpcomingDueIssues tests
1581 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1582 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1585 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1586 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1587 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1590 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1591 is ( scalar( @$upcoming_dues ), 1,
1592 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1595 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1597 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1599 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1600 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1602 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1603 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1605 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1606 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1608 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1609 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1611 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1612 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1614 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1615 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1619 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1620 my $branch = $library2->{branchcode};
1622 my $biblio = $builder->build_sample_biblio();
1625 my $item = $builder->build_sample_item(
1627 biblionumber => $biblio->biblionumber,
1634 my %a_borrower_data = (
1635 firstname => 'Kyle',
1637 categorycode => $patron_category->{categorycode},
1638 branchcode => $branch,
1641 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1643 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1644 my $issue = AddIssue( $borrower, $item->barcode );
1647 issue_id => $issue->id(),
1648 itemnumber => $item->itemnumber,
1649 borrowernumber => $borrowernumber,
1655 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1656 my $count = $hr->{count};
1658 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1661 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1663 my $biblio = $builder->build_sample_biblio();
1664 my $item_1 = $builder->build_sample_item(
1666 biblionumber => $biblio->biblionumber,
1667 library => $library2->{branchcode},
1670 my $item_2= $builder->build_sample_item(
1672 biblionumber => $biblio->biblionumber,
1673 library => $library2->{branchcode},
1674 itype => $item_1->effective_itemtype,
1678 Koha::CirculationRules->set_rules(
1680 categorycode => undef,
1681 itemtype => $item_1->effective_itemtype,
1682 branchcode => undef,
1684 reservesallowed => 25,
1685 holds_per_record => 25,
1687 lengthunit => 'days',
1688 renewalsallowed => 1,
1690 norenewalbefore => undef,
1700 my $borrowernumber1 = Koha::Patron->new({
1701 firstname => 'Kyle',
1703 categorycode => $patron_category->{categorycode},
1704 branchcode => $library2->{branchcode},
1705 })->store->borrowernumber;
1706 my $borrowernumber2 = Koha::Patron->new({
1707 firstname => 'Chelsea',
1709 categorycode => $patron_category->{categorycode},
1710 branchcode => $library2->{branchcode},
1711 })->store->borrowernumber;
1712 my $patron_category_2 = $builder->build(
1714 source => 'Category',
1716 category_type => 'P',
1718 BlockExpiredPatronOpacActions => -1, # Pick the pref value
1722 my $borrowernumber3 = Koha::Patron->new({
1723 firstname => 'Carnegie',
1725 categorycode => $patron_category_2->{categorycode},
1726 branchcode => $library2->{branchcode},
1727 })->store->borrowernumber;
1729 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1730 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1732 my $issue = AddIssue( $borrower1, $item_1->barcode );
1734 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1735 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1739 branchcode => $library2->{branchcode},
1740 borrowernumber => $borrowernumber2,
1741 biblionumber => $biblio->biblionumber,
1746 Koha::CirculationRules->set_rules(
1748 categorycode => undef,
1749 itemtype => $item_1->effective_itemtype,
1750 branchcode => undef,
1756 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1757 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1758 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1760 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1761 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1762 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1764 Koha::CirculationRules->set_rules(
1766 categorycode => undef,
1767 itemtype => $item_1->effective_itemtype,
1768 branchcode => undef,
1774 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1775 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1776 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1778 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1779 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1780 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1784 branchcode => $library2->{branchcode},
1785 borrowernumber => $borrowernumber3,
1786 biblionumber => $biblio->biblionumber,
1791 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1792 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' );
1794 my $item_3= $builder->build_sample_item(
1796 biblionumber => $biblio->biblionumber,
1797 library => $library2->{branchcode},
1798 itype => $item_1->effective_itemtype,
1802 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1803 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' );
1805 Koha::CirculationRules->set_rules(
1807 categorycode => $patron_category_2->{categorycode},
1808 itemtype => $item_1->effective_itemtype,
1809 branchcode => undef,
1811 reservesallowed => 0,
1816 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1817 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' );
1819 Koha::CirculationRules->set_rules(
1821 categorycode => $patron_category_2->{categorycode},
1822 itemtype => $item_1->effective_itemtype,
1823 branchcode => undef,
1825 reservesallowed => 25,
1830 # Setting item not checked out to be not for loan but holdable
1831 $item_2->notforloan(-1)->store;
1833 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1834 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' );
1836 my $mock_circ = Test::MockModule->new("C4::Circulation");
1837 $mock_circ->mock( CanItemBeReserved => sub {
1839 return { status => 'no' }
1842 $item_2->notforloan(0)->store;
1844 # Two items total, one item available, one issued, two holds on record
1847 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1848 } [], "CanItemBeReserved not called when there are more possible holds than available items";
1849 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1851 $item_3 = $builder->build_sample_item(
1853 biblionumber => $biblio->biblionumber,
1854 library => $library2->{branchcode},
1855 itype => $item_1->effective_itemtype,
1859 Koha::CirculationRules->set_rules(
1861 categorycode => undef,
1862 itemtype => $item_1->effective_itemtype,
1863 branchcode => undef,
1865 reservesallowed => 0,
1871 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1872 } ["Checked","Checked"], "CanItemBeReserved only called once per available item if it returns a negative result for all items for a borrower";
1873 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1878 # Don't allow renewing onsite checkout
1879 my $branch = $library->{branchcode};
1881 #Create another record
1882 my $biblio = $builder->build_sample_biblio();
1884 my $item = $builder->build_sample_item(
1886 biblionumber => $biblio->biblionumber,
1892 my $borrowernumber = Koha::Patron->new({
1895 categorycode => $patron_category->{categorycode},
1896 branchcode => $branch,
1897 })->store->borrowernumber;
1899 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1901 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1902 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1903 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1904 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1908 my $library = $builder->build({ source => 'Branch' });
1910 my $biblio = $builder->build_sample_biblio();
1912 my $item = $builder->build_sample_item(
1914 biblionumber => $biblio->biblionumber,
1915 library => $library->{branchcode},
1920 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1922 my $issue = AddIssue( $patron, $item->barcode );
1925 issue_id => $issue->id(),
1926 itemnumber => $item->itemnumber,
1927 borrowernumber => $patron->{borrowernumber},
1934 issue_id => $issue->id(),
1935 itemnumber => $item->itemnumber,
1936 borrowernumber => $patron->{borrowernumber},
1941 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1944 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1947 my $homebranch = $builder->build( { source => 'Branch' } );
1948 my $holdingbranch = $builder->build( { source => 'Branch' } );
1949 my $otherbranch = $builder->build( { source => 'Branch' } );
1950 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1951 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1953 my $item = $builder->build_sample_item(
1955 homebranch => $homebranch->{branchcode},
1956 holdingbranch => $holdingbranch->{branchcode},
1959 Koha::CirculationRules->set_rules(
1961 categorycode => undef,
1962 itemtype => $item->effective_itemtype,
1963 branchcode => undef,
1965 reservesallowed => 25,
1967 lengthunit => 'days',
1968 renewalsallowed => 1,
1970 norenewalbefore => undef,
1979 set_userenv($holdingbranch);
1981 my $issue = AddIssue( $patron_1->unblessed, $item->barcode );
1982 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1984 my ( $error, $question, $alerts );
1986 # AllowReturnToBranch == anywhere
1987 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1988 ## Test that unknown barcodes don't generate internal server errors
1989 set_userenv($homebranch);
1990 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1991 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1992 ## Can be issued from homebranch
1993 set_userenv($homebranch);
1994 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1995 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1996 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1997 ## Can be issued from holdingbranch
1998 set_userenv($holdingbranch);
1999 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2000 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2001 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2002 ## Can be issued from another branch
2003 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2004 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2005 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2007 # AllowReturnToBranch == holdingbranch
2008 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2009 ## Cannot be issued from homebranch
2010 set_userenv($homebranch);
2011 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2012 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2013 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2014 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
2015 ## Can be issued from holdinbranch
2016 set_userenv($holdingbranch);
2017 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2018 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2019 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2020 ## Cannot be issued from another branch
2021 set_userenv($otherbranch);
2022 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2023 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2024 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2025 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
2027 # AllowReturnToBranch == homebranch
2028 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2029 ## Can be issued from holdinbranch
2030 set_userenv($homebranch);
2031 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2032 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2033 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2034 ## Cannot be issued from holdinbranch
2035 set_userenv($holdingbranch);
2036 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2037 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2038 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2039 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2040 ## Cannot be issued from holdinbranch
2041 set_userenv($otherbranch);
2042 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2043 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2044 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2045 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2047 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2050 subtest 'AddIssue & AllowReturnToBranch' => sub {
2053 my $homebranch = $builder->build( { source => 'Branch' } );
2054 my $holdingbranch = $builder->build( { source => 'Branch' } );
2055 my $otherbranch = $builder->build( { source => 'Branch' } );
2056 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2057 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2059 my $item = $builder->build_sample_item(
2061 homebranch => $homebranch->{branchcode},
2062 holdingbranch => $holdingbranch->{branchcode},
2066 set_userenv($holdingbranch);
2068 my $ref_issue = 'Koha::Checkout';
2069 my $issue = AddIssue( $patron_1, $item->barcode );
2071 my ( $error, $question, $alerts );
2073 # AllowReturnToBranch == homebranch
2074 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2075 ## Can be issued from homebranch
2076 set_userenv($homebranch);
2077 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
2078 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2079 ## Can be issued from holdinbranch
2080 set_userenv($holdingbranch);
2081 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
2082 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2083 ## Can be issued from another branch
2084 set_userenv($otherbranch);
2085 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
2086 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2088 # AllowReturnToBranch == holdinbranch
2089 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2090 ## Cannot be issued from homebranch
2091 set_userenv($homebranch);
2092 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
2093 ## Can be issued from holdingbranch
2094 set_userenv($holdingbranch);
2095 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
2096 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2097 ## Cannot be issued from another branch
2098 set_userenv($otherbranch);
2099 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
2101 # AllowReturnToBranch == homebranch
2102 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2103 ## Can be issued from homebranch
2104 set_userenv($homebranch);
2105 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
2106 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2107 ## Cannot be issued from holdinbranch
2108 set_userenv($holdingbranch);
2109 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
2110 ## Cannot be issued from another branch
2111 set_userenv($otherbranch);
2112 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
2113 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2116 subtest 'AddIssue | recalls' => sub {
2119 t::lib::Mocks::mock_preference("UseRecalls", 1);
2120 t::lib::Mocks::mock_preference("item-level_itypes", 1);
2121 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2122 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2123 my $item = $builder->build_sample_item;
2124 Koha::CirculationRules->set_rules({
2125 branchcode => undef,
2127 categorycode => undef,
2129 recalls_allowed => 10,
2133 # checking out item that they have recalled
2134 my $recall1 = Koha::Recall->new(
2135 { patron_id => $patron1->borrowernumber,
2136 biblio_id => $item->biblionumber,
2137 item_id => $item->itemnumber,
2139 pickup_library_id => $patron1->branchcode,
2142 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall1->id } );
2143 $recall1 = Koha::Recalls->find( $recall1->id );
2144 is( $recall1->fulfilled, 1, 'Recall was fulfilled when patron checked out item' );
2145 AddReturn( $item->barcode, $item->homebranch );
2147 # this item is has a recall request. cancel recall
2148 my $recall2 = Koha::Recall->new(
2149 { patron_id => $patron2->borrowernumber,
2150 biblio_id => $item->biblionumber,
2151 item_id => $item->itemnumber,
2153 pickup_library_id => $patron2->branchcode,
2156 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall2->id, cancel_recall => 'cancel' } );
2157 $recall2 = Koha::Recalls->find( $recall2->id );
2158 is( $recall2->cancelled, 1, 'Recall was cancelled when patron checked out item' );
2159 AddReturn( $item->barcode, $item->homebranch );
2161 # this item is waiting to fulfill a recall. revert recall
2162 my $recall3 = Koha::Recall->new(
2163 { patron_id => $patron2->borrowernumber,
2164 biblio_id => $item->biblionumber,
2165 item_id => $item->itemnumber,
2167 pickup_library_id => $patron2->branchcode,
2170 $recall3->set_waiting;
2171 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall3->id, cancel_recall => 'revert' } );
2172 $recall3 = Koha::Recalls->find( $recall3->id );
2173 is( $recall3->requested, 1, 'Recall was reverted from waiting when patron checked out item' );
2174 AddReturn( $item->barcode, $item->homebranch );
2177 subtest 'AddIssue & illrequests.due_date' => sub {
2180 t::lib::Mocks::mock_preference( 'ILLModule', 1 );
2181 my $library = $builder->build( { source => 'Branch' } );
2182 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2183 my $item = $builder->build_sample_item();
2185 set_userenv($library);
2187 my $custom_date_due = '9999-12-18 12:34:56';
2188 my $expected_date_due = '9999-12-18 23:59:00';
2189 my $illrequest = Koha::Illrequest->new({
2190 borrowernumber => $patron->borrowernumber,
2191 biblio_id => $item->biblionumber,
2192 branchcode => $library->{'branchcode'},
2193 due_date => $custom_date_due,
2196 my $issue = AddIssue( $patron->unblessed, $item->barcode );
2197 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2199 $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2200 $item = $builder->build_sample_item();
2201 $custom_date_due = '9999-12-19';
2202 $expected_date_due = '9999-12-19 23:59:00';
2203 $illrequest = Koha::Illrequest->new({
2204 borrowernumber => $patron->borrowernumber,
2205 biblio_id => $item->biblionumber,
2206 branchcode => $library->{'branchcode'},
2207 due_date => $custom_date_due,
2210 $issue = AddIssue( $patron->unblessed, $item->barcode );
2211 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2214 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
2217 my $library = $builder->build( { source => 'Branch' } );
2218 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2219 my $item_1 = $builder->build_sample_item(
2221 library => $library->{branchcode},
2224 my $item_2 = $builder->build_sample_item(
2226 library => $library->{branchcode},
2229 Koha::CirculationRules->set_rules(
2231 categorycode => undef,
2233 branchcode => $library->{branchcode},
2235 reservesallowed => 25,
2237 lengthunit => 'days',
2238 renewalsallowed => 1,
2240 norenewalbefore => undef,
2250 my ( $error, $question, $alerts );
2252 # Patron cannot issue item_1, they have overdues
2253 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
2254 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, $yesterday ); # Add an overdue
2256 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
2257 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2258 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
2259 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
2261 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
2262 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2263 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2264 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
2266 # Patron cannot issue item_1, they are debarred
2267 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
2268 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
2269 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2270 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2271 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
2273 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
2274 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2275 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2276 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
2279 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
2282 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2283 my $patron_category_x = $builder->build_object(
2285 class => 'Koha::Patron::Categories',
2286 value => { category_type => 'X' }
2289 my $patron = $builder->build_object(
2291 class => 'Koha::Patrons',
2293 categorycode => $patron_category_x->categorycode,
2294 gonenoaddress => undef,
2301 my $item_1 = $builder->build_sample_item(
2303 library => $library->{branchcode},
2307 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
2308 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
2310 # TODO There are other tests to provide here
2313 subtest 'MultipleReserves' => sub {
2316 my $biblio = $builder->build_sample_biblio();
2318 my $branch = $library2->{branchcode};
2320 my $item_1 = $builder->build_sample_item(
2322 biblionumber => $biblio->biblionumber,
2324 replacementprice => 12.00,
2329 my $item_2 = $builder->build_sample_item(
2331 biblionumber => $biblio->biblionumber,
2333 replacementprice => 12.00,
2340 my $resdate = undef;
2341 my $expdate = undef;
2343 my $checkitem = undef;
2346 my %renewing_borrower_data = (
2347 firstname => 'John',
2348 surname => 'Renewal',
2349 categorycode => $patron_category->{categorycode},
2350 branchcode => $branch,
2352 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
2353 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
2354 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
2355 my $datedue = dt_from_string( $issue->date_due() );
2356 is (defined $issue->date_due(), 1, "item 1 checked out");
2357 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
2359 my %reserving_borrower_data1 = (
2360 firstname => 'Katrin',
2361 surname => 'Reservation',
2362 categorycode => $patron_category->{categorycode},
2363 branchcode => $branch,
2365 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
2368 branchcode => $branch,
2369 borrowernumber => $reserving_borrowernumber1,
2370 biblionumber => $biblio->biblionumber,
2371 priority => $priority,
2372 reservation_date => $resdate,
2373 expiration_date => $expdate,
2375 itemnumber => $checkitem,
2380 my %reserving_borrower_data2 = (
2381 firstname => 'Kirk',
2382 surname => 'Reservation',
2383 categorycode => $patron_category->{categorycode},
2384 branchcode => $branch,
2386 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
2389 branchcode => $branch,
2390 borrowernumber => $reserving_borrowernumber2,
2391 biblionumber => $biblio->biblionumber,
2392 priority => $priority,
2393 reservation_date => $resdate,
2394 expiration_date => $expdate,
2396 itemnumber => $checkitem,
2402 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2403 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2406 my $item_3 = $builder->build_sample_item(
2408 biblionumber => $biblio->biblionumber,
2410 replacementprice => 12.00,
2416 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2417 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2421 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2424 my $library = $builder->build( { source => 'Branch' } );
2425 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2427 my $biblionumber = $builder->build_sample_biblio(
2429 branchcode => $library->{branchcode},
2432 my $item_1 = $builder->build_sample_item(
2434 biblionumber => $biblionumber,
2435 library => $library->{branchcode},
2439 my $item_2 = $builder->build_sample_item(
2441 biblionumber => $biblionumber,
2442 library => $library->{branchcode},
2446 Koha::CirculationRules->set_rules(
2448 categorycode => undef,
2450 branchcode => $library->{branchcode},
2452 reservesallowed => 25,
2454 lengthunit => 'days',
2455 renewalsallowed => 1,
2457 norenewalbefore => undef,
2466 my ( $error, $question, $alerts );
2467 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, dt_from_string->add( days => 1 ) );
2469 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2470 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2472 { error => $error, alerts => $alerts },
2473 { error => {}, alerts => {} },
2474 'No error or alert should be raised'
2476 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2478 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2479 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2481 { error => $error, question => $question, alerts => $alerts },
2482 { error => {}, question => {}, alerts => {} },
2483 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2486 # Add a subscription
2487 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2489 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2490 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2492 { error => $error, question => $question, alerts => $alerts },
2493 { error => {}, question => {}, alerts => {} },
2494 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2497 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2498 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2500 { error => $error, question => $question, alerts => $alerts },
2501 { error => {}, question => {}, alerts => {} },
2502 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2506 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2509 my $library = $builder->build( { source => 'Branch' } );
2510 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2513 my $biblionumber = $builder->build_sample_biblio(
2515 branchcode => $library->{branchcode},
2518 my $item_1 = $builder->build_sample_item(
2520 biblionumber => $biblionumber,
2521 library => $library->{branchcode},
2524 my $item_2 = $builder->build_sample_item(
2526 biblionumber => $biblionumber,
2527 library => $library->{branchcode},
2531 # And the circulation rule
2532 Koha::CirculationRules->search->delete;
2533 Koha::CirculationRules->set_rules(
2535 categorycode => undef,
2537 branchcode => undef,
2540 firstremind => 1, # 1 day of grace
2541 finedays => 2, # 2 days of fine per day of overdue
2542 lengthunit => 'days',
2547 # Patron cannot issue item_1, they have overdues
2548 my $now = dt_from_string;
2549 my $five_days_ago = $now->clone->subtract( days => 5 );
2550 my $ten_days_ago = $now->clone->subtract( days => 10 );
2551 AddIssue( $patron->unblessed, $item_1->barcode, $five_days_ago ); # Add an overdue
2552 AddIssue( $patron->unblessed, $item_2->barcode, $ten_days_ago )
2553 ; # Add another overdue
2555 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2556 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2557 my $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2558 is( $suspensions->count, 1, "Suspension added" );
2559 my $THE_suspension = $suspensions->next;
2561 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2562 # Same for the others
2563 my $expected_expiration = output_pref(
2565 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2566 dateformat => 'sql',
2570 is( $THE_suspension->expiration, $expected_expiration, "Suspesion expiration set" );
2572 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2573 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2574 is( $suspensions->count, 1, "Only one suspension" );
2575 $THE_suspension = $suspensions->next;
2577 $expected_expiration = output_pref(
2579 dt => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2580 dateformat => 'sql',
2584 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2586 Koha::Patron::Debarments::DelUniqueDebarment(
2587 { borrowernumber => $patron->borrowernumber, type => 'SUSPENSION' } );
2589 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2590 AddIssue( $patron->unblessed, $item_1->barcode, $five_days_ago ); # Add an overdue
2591 AddIssue( $patron->unblessed, $item_2->barcode, $ten_days_ago )
2592 ; # Add another overdue
2593 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2594 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2595 is( $suspensions->count, 1, "Only one suspension" );
2596 $THE_suspension = $suspensions->next;
2598 $expected_expiration = output_pref(
2600 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2601 dateformat => 'sql',
2605 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2607 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2608 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2609 is( $suspensions->count, 1, "Only one suspension" );
2610 $THE_suspension = $suspensions->next;
2612 $expected_expiration = output_pref(
2614 dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2615 dateformat => 'sql',
2619 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2622 subtest 'AddReturn + suspension_chargeperiod' => sub {
2625 my $library = $builder->build( { source => 'Branch' } );
2626 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2628 my $biblionumber = $builder->build_sample_biblio(
2630 branchcode => $library->{branchcode},
2633 my $item_1 = $builder->build_sample_item(
2635 biblionumber => $biblionumber,
2636 library => $library->{branchcode},
2640 # And the issuing rule
2641 Koha::CirculationRules->search->delete;
2642 Koha::CirculationRules->set_rules(
2644 categorycode => '*',
2649 firstremind => 0, # 0 day of grace
2650 finedays => 2, # 2 days of fine per day of overdue
2651 suspension_chargeperiod => 1,
2652 lengthunit => 'days',
2657 my $now = dt_from_string;
2658 my $five_days_ago = $now->clone->subtract( days => 5 );
2659 # We want to charge 2 days every day, without grace
2660 # With 5 days of overdue: 5 * Z
2661 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2662 test_debarment_on_checkout(
2665 library => $library,
2667 due_date => $five_days_ago,
2668 expiration_date => $expected_expiration,
2672 # Same with undef firstremind
2673 Koha::CirculationRules->search->delete;
2674 Koha::CirculationRules->set_rules(
2676 categorycode => '*',
2681 firstremind => undef, # 0 day of grace
2682 finedays => 2, # 2 days of fine per day of overdue
2683 suspension_chargeperiod => 1,
2684 lengthunit => 'days',
2689 my $now = dt_from_string;
2690 my $five_days_ago = $now->clone->subtract( days => 5 );
2691 # We want to charge 2 days every day, without grace
2692 # With 5 days of overdue: 5 * Z
2693 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2694 test_debarment_on_checkout(
2697 library => $library,
2699 due_date => $five_days_ago,
2700 expiration_date => $expected_expiration,
2704 # We want to charge 2 days every 2 days, without grace
2705 # With 5 days of overdue: (5 * 2) / 2
2706 Koha::CirculationRules->set_rule(
2708 categorycode => undef,
2709 branchcode => undef,
2711 rule_name => 'suspension_chargeperiod',
2716 $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2717 test_debarment_on_checkout(
2720 library => $library,
2722 due_date => $five_days_ago,
2723 expiration_date => $expected_expiration,
2727 # We want to charge 2 days every 3 days, with 1 day of grace
2728 # With 5 days of overdue: ((5-1) / 3 ) * 2
2729 Koha::CirculationRules->set_rules(
2731 categorycode => undef,
2732 branchcode => undef,
2735 suspension_chargeperiod => 3,
2740 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2741 test_debarment_on_checkout(
2744 library => $library,
2746 due_date => $five_days_ago,
2747 expiration_date => $expected_expiration,
2751 # Use finesCalendar to know if holiday must be skipped to calculate the due date
2752 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2753 Koha::CirculationRules->set_rules(
2755 categorycode => undef,
2756 branchcode => undef,
2760 suspension_chargeperiod => 1,
2765 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2766 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2768 # Adding a holiday 2 days ago
2769 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2770 my $two_days_ago = $now->clone->subtract( days => 2 );
2771 $calendar->insert_single_holiday(
2772 day => $two_days_ago->day,
2773 month => $two_days_ago->month,
2774 year => $two_days_ago->year,
2775 title => 'holidayTest-2d',
2776 description => 'holidayDesc 2 days ago'
2778 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2779 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2780 test_debarment_on_checkout(
2783 library => $library,
2785 due_date => $five_days_ago,
2786 expiration_date => $expected_expiration,
2790 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2791 my $two_days_ahead = $now->clone->add( days => 2 );
2792 $calendar->insert_single_holiday(
2793 day => $two_days_ahead->day,
2794 month => $two_days_ahead->month,
2795 year => $two_days_ahead->year,
2796 title => 'holidayTest+2d',
2797 description => 'holidayDesc 2 days ahead'
2800 # Same as above, but we should skip D+2
2801 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2802 test_debarment_on_checkout(
2805 library => $library,
2807 due_date => $five_days_ago,
2808 expiration_date => $expected_expiration,
2812 # Adding another holiday, day of expiration date
2813 my $expected_expiration_dt = dt_from_string($expected_expiration);
2814 $calendar->insert_single_holiday(
2815 day => $expected_expiration_dt->day,
2816 month => $expected_expiration_dt->month,
2817 year => $expected_expiration_dt->year,
2818 title => 'holidayTest_exp',
2819 description => 'holidayDesc on expiration date'
2821 # Expiration date will be the day after
2822 test_debarment_on_checkout(
2825 library => $library,
2827 due_date => $five_days_ago,
2828 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2832 test_debarment_on_checkout(
2835 library => $library,
2837 return_date => $now->clone->add(days => 5),
2838 expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2842 test_debarment_on_checkout(
2845 library => $library,
2847 due_date => $now->clone->add(days => 1),
2848 return_date => $now->clone->add(days => 5),
2849 expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2853 Koha::CirculationRules->search->delete;
2854 Koha::CirculationRules->set_rules(
2856 categorycode => undef,
2858 branchcode => undef,
2865 Koha::Patron::Debarments::AddDebarment(
2867 borrowernumber => $patron->{borrowernumber},
2868 expiration => '9999-12-31',
2873 AddIssue( $patron, $item_1->barcode, $now->clone->subtract( days => 1 ) );
2874 my ( undef, $message ) = AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2875 is( $message->{WasReturned} && exists $message->{ForeverDebarred}, 1, 'Forever debarred message for Addreturn when overdue');
2877 Koha::Patron::Debarments::DelUniqueDebarment(
2879 borrowernumber => $patron->{borrowernumber},
2883 Koha::Patron::Debarments::AddDebarment(
2885 borrowernumber => $patron->{borrowernumber},
2886 expiration => $now->clone->add( days => 10 ),
2891 AddIssue( $patron, $item_1->barcode, $now->clone->subtract( days => 1 ) );
2892 (undef, $message) = AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2893 is( $message->{WasReturned} && exists $message->{PrevDebarred}, 1, 'Previously debarred message for Addreturn when overdue');
2896 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2899 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2900 my $patron1 = $builder->build_object(
2902 class => 'Koha::Patrons',
2904 branchcode => $library->branchcode,
2905 categorycode => $patron_category->{categorycode}
2909 my $patron2 = $builder->build_object(
2911 class => 'Koha::Patrons',
2913 branchcode => $library->branchcode,
2914 categorycode => $patron_category->{categorycode}
2919 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2921 my $item = $builder->build_sample_item(
2923 library => $library->branchcode,
2927 my ( $error, $question, $alerts );
2928 my $issue = AddIssue( $patron1->unblessed, $item->barcode );
2930 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2931 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2932 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' );
2934 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2935 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2936 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' );
2938 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2942 subtest 'AddReturn | is_overdue' => sub {
2945 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2946 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2947 t::lib::Mocks::mock_preference('finesMode', 'production');
2948 t::lib::Mocks::mock_preference('MaxFine', '100');
2950 my $library = $builder->build( { source => 'Branch' } );
2951 my $patron = $builder->build_object(
2953 class => 'Koha::Patrons',
2954 value => { categorycode => $patron_category->{categorycode} }
2957 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
2958 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2960 my $item = $builder->build_sample_item(
2962 library => $library->{branchcode},
2963 replacementprice => 7
2967 Koha::CirculationRules->search->delete;
2968 Koha::CirculationRules->set_rules(
2970 categorycode => undef,
2972 branchcode => undef,
2975 lengthunit => 'days',
2976 fine => 1, # Charge 1 every day of overdue
2982 my $now = dt_from_string;
2983 my $one_day_ago = $now->clone->subtract( days => 1 );
2984 my $two_days_ago = $now->clone->subtract( days => 2 );
2985 my $five_days_ago = $now->clone->subtract( days => 5 );
2986 my $ten_days_ago = $now->clone->subtract( days => 10 );
2988 # No return date specified, today will be used => 10 days overdue charged
2989 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2990 AddReturn( $item->barcode, $library->{branchcode} );
2991 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2992 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2994 # specify return date 5 days before => no overdue charged
2995 AddIssue( $patron->unblessed, $item->barcode, $five_days_ago ); # date due was 5d ago
2996 AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
2997 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2998 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3000 # specify return date 5 days later => 5 days overdue charged
3001 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
3002 AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
3003 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
3004 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3006 # specify return date 5 days later, specify exemptfine => no overdue charge
3007 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
3008 AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago );
3009 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
3010 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3012 subtest 'bug 22877 | Lost item return' => sub {
3016 my $issue = AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
3018 # Fake fines cronjob on this checkout
3020 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3021 $ten_days_ago, $now );
3024 issue_id => $issue->issue_id,
3025 itemnumber => $item->itemnumber,
3026 borrowernumber => $patron->borrowernumber,
3028 due => output_pref($ten_days_ago)
3031 is( int( $patron->account->balance() ),
3032 10, "Overdue fine of 10 days overdue" );
3034 # Fake longoverdue with charge and not marking returned
3035 LostItem( $item->itemnumber, 'cronjob', 0 );
3036 is( int( $patron->account->balance() ),
3037 17, "Lost fine of 7 plus 10 days overdue" );
3039 # Now we return it today
3040 AddReturn( $item->barcode, $library->{branchcode} );
3041 is( int( $patron->account->balance() ),
3042 17, "Should have a single 10 days overdue fine and lost charge" );
3045 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3048 subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
3052 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3054 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
3056 # Fake fines cronjob on this checkout
3058 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3059 $one_day_ago, $now );
3062 issue_id => $issue->issue_id,
3063 itemnumber => $item->itemnumber,
3064 borrowernumber => $patron->borrowernumber,
3066 due => output_pref($one_day_ago)
3069 is( int( $patron->account->balance() ),
3070 1, "Overdue fine of 1 day overdue" );
3072 # Backdated return (dropbox mode example - charge should be removed)
3073 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3074 is( int( $patron->account->balance() ),
3075 0, "Overdue fine should be annulled" );
3076 my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3077 is( $lines->count, 0, "Overdue fine accountline has been removed");
3079 $issue = AddIssue( $patron->unblessed, $item->barcode, $two_days_ago ); # date due was 2d ago
3081 # Fake fines cronjob on this checkout
3083 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3084 $two_days_ago, $now );
3087 issue_id => $issue->issue_id,
3088 itemnumber => $item->itemnumber,
3089 borrowernumber => $patron->borrowernumber,
3091 due => output_pref($one_day_ago)
3094 is( int( $patron->account->balance() ),
3095 2, "Overdue fine of 2 days overdue" );
3097 # Payment made against fine
3098 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3099 my $debit = $lines->next;
3100 my $credit = $patron->account->add_credit(
3104 interface => 'test',
3107 $credit->apply( { debits => [$debit] } );
3109 is( int( $patron->account->balance() ),
3110 0, "Overdue fine should be paid off" );
3111 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3112 is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
3113 my $line = $lines->next;
3114 is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
3115 is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
3117 # Backdated return (dropbox mode example - charge should be removed)
3118 AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
3119 is( int( $patron->account->balance() ),
3120 -1, "Refund credit has been applied" );
3121 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
3122 is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
3124 $line = $lines->next;
3125 is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
3126 is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
3127 is($line->status,'RETURNED', "Overdue fine is fixed");
3128 $line = $lines->next;
3129 is($line->amount+0,-2, "Original payment amount remains as 2");
3130 is($line->amountoutstanding+0,0, "Original payment remains applied");
3131 $line = $lines->next;
3132 is($line->amount+0,-1, "Refund amount correctly set to 1");
3133 is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
3136 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3139 subtest 'bug 25417 | backdated return + exemptfine' => sub {
3143 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3145 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
3147 # Fake fines cronjob on this checkout
3149 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3150 $one_day_ago, $now );
3153 issue_id => $issue->issue_id,
3154 itemnumber => $item->itemnumber,
3155 borrowernumber => $patron->borrowernumber,
3157 due => output_pref($one_day_ago)
3160 is( int( $patron->account->balance() ),
3161 1, "Overdue fine of 1 day overdue" );
3163 # Backdated return (dropbox mode example - charge should no longer exist)
3164 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3165 is( int( $patron->account->balance() ),
3166 0, "Overdue fine should be annulled" );
3169 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3172 subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
3175 t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
3177 my $due_date = dt_from_string;
3178 my $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
3183 issue_id => $issue->issue_id,
3184 itemnumber => $item->itemnumber,
3185 borrowernumber => $patron->borrowernumber,
3187 due => output_pref($due_date)
3190 is( $patron->account->balance(),
3191 0.25, 'Overdue fine of $0.25 recorded' );
3193 # Backdate return to exact due date and time
3194 my ( undef, $message ) =
3195 AddReturn( $item->barcode, $library->{branchcode},
3199 Koha::Account::Lines->find( { issue_id => $issue->id } );
3200 ok( !$accountline, 'accountline removed as expected' );
3203 $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
3208 issue_id => $issue->issue_id,
3209 itemnumber => $item->itemnumber,
3210 borrowernumber => $patron->borrowernumber,
3212 due => output_pref($due_date)
3215 is( $patron->account->balance(),
3216 0.25, 'Overdue fine of $0.25 recorded' );
3218 # Partial pay accruing fine
3219 my $lines = Koha::Account::Lines->search(
3221 borrowernumber => $patron->borrowernumber,
3222 issue_id => $issue->id
3225 my $debit = $lines->next;
3226 my $credit = $patron->account->add_credit(
3230 interface => 'test',
3233 $credit->apply( { debits => [$debit] } );
3235 is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
3237 # Backdate return to exact due date and time
3238 ( undef, $message ) =
3239 AddReturn( $item->barcode, $library->{branchcode},
3242 $lines = Koha::Account::Lines->search(
3244 borrowernumber => $patron->borrowernumber,
3245 issue_id => $issue->id
3248 $accountline = $lines->next;
3249 is( $accountline->amountoutstanding + 0,
3250 0, 'Partially paid fee amount outstanding was reduced to 0' );
3251 is( $accountline->amount + 0,
3252 0, 'Partially paid fee amount was reduced to 0' );
3253 is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
3256 Koha::Account::Lines->search(
3257 { borrowernumber => $patron->borrowernumber } )->delete;
3260 subtest 'enh 23091 | Lost item return policies' => sub {
3263 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3265 my $branchcode_false =
3266 $builder->build( { source => 'Branch' } )->{branchcode};
3267 my $specific_rule_false = $builder->build(
3269 source => 'CirculationRule',
3271 branchcode => $branchcode_false,
3272 categorycode => undef,
3274 rule_name => 'lostreturn',
3279 my $branchcode_refund =
3280 $builder->build( { source => 'Branch' } )->{branchcode};
3281 my $specific_rule_refund = $builder->build(
3283 source => 'CirculationRule',
3285 branchcode => $branchcode_refund,
3286 categorycode => undef,
3288 rule_name => 'lostreturn',
3289 rule_value => 'refund'
3293 my $branchcode_restore =
3294 $builder->build( { source => 'Branch' } )->{branchcode};
3295 my $specific_rule_restore = $builder->build(
3297 source => 'CirculationRule',
3299 branchcode => $branchcode_restore,
3300 categorycode => undef,
3302 rule_name => 'lostreturn',
3303 rule_value => 'restore'
3307 my $branchcode_charge =
3308 $builder->build( { source => 'Branch' } )->{branchcode};
3309 my $specific_rule_charge = $builder->build(
3311 source => 'CirculationRule',
3313 branchcode => $branchcode_charge,
3314 categorycode => undef,
3316 rule_name => 'lostreturn',
3317 rule_value => 'charge'
3322 my $branchcode_refund_unpaid =
3323 $builder->build( { source => 'Branch' } )->{branchcode};
3324 my $specific_rule_refund_unpaid = $builder->build(
3326 source => 'CirculationRule',
3328 branchcode => $branchcode_refund_unpaid,
3329 categorycode => undef,
3331 rule_name => 'lostreturn',
3332 rule_value => 'refund_unpaid'
3337 my $replacement_amount = 99.00;
3338 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
3339 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
3340 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
3341 t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 );
3342 t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
3344 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
3347 subtest 'lostreturn | refund_unpaid' => sub {
3350 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund_unpaid });
3352 my $item = $builder->build_sample_item(
3354 replacementprice => $replacement_amount
3359 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode );
3362 $item->itemlost(3)->store;
3363 C4::Circulation::LostItem( $item->itemnumber, 1 );
3365 my $lost_fee_lines = Koha::Account::Lines->search(
3367 borrowernumber => $patron->id,
3368 itemnumber => $item->itemnumber,
3369 debit_type_code => 'LOST'
3372 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3373 my $lost_fee_line = $lost_fee_lines->next;
3374 is( int($lost_fee_line->amount),
3375 $replacement_amount, 'The right LOST amount is generated' );
3376 is( int($lost_fee_line->amountoutstanding),
3377 $replacement_amount,
3378 'The right LOST amountoutstanding is generated' );
3379 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3382 int($patron->account->balance),
3383 $replacement_amount ,
3384 "Account balance equals the replacement amount after being charged lost fee when no payments has been made"
3387 # Return lost item without any payments having been made
3388 my ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3390 $lost_fee_line->discard_changes;
3392 is( int($lost_fee_line->amount), $replacement_amount, 'The LOST amount is left intact' );
3393 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero' );
3394 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set' );
3396 int($patron->account->balance),
3398 'Account balance should be zero after returning item with lost fee when no payments has been made'
3401 # Create a second item
3402 $item = $builder->build_sample_item(
3404 replacementprice => $replacement_amount
3409 $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode );
3412 $item->itemlost(3)->store;
3413 C4::Circulation::LostItem( $item->itemnumber, 1 );
3415 $lost_fee_lines = Koha::Account::Lines->search(
3417 borrowernumber => $patron->id,
3418 itemnumber => $item->itemnumber,
3419 debit_type_code => 'LOST'
3422 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3423 $lost_fee_line = $lost_fee_lines->next;
3425 # Make partial payment
3426 $patron->account->payin_amount({
3428 interface => 'intranet',
3429 payment_type => 'CASH',
3430 user_id => $patron->borrowernumber,
3432 debits => [$lost_fee_line]
3435 $lost_fee_line->discard_changes;
3437 is( int($lost_fee_line->amountoutstanding),
3439 'The LOST amountoutstanding is the expected amount after partial payment of lost fee'
3443 int($patron->account->balance),
3445 'Account balance is the expected amount after partial payment of lost fee'
3448 # Return lost item with partial payment having been made
3449 ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3451 $lost_fee_line->discard_changes;
3453 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero after returning lost item with partial payment' );
3454 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set for lost item with partial payment' );
3456 int($patron->account->balance),
3458 'Account balance should be zero after returning item with lost fee when partial payment has been made'
3461 # Create a third item
3462 $item = $builder->build_sample_item(
3464 replacementprice => $replacement_amount
3469 $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode );
3472 $item->itemlost(3)->store;
3473 C4::Circulation::LostItem( $item->itemnumber, 1 );
3475 $lost_fee_lines = Koha::Account::Lines->search(
3477 borrowernumber => $patron->id,
3478 itemnumber => $item->itemnumber,
3479 debit_type_code => 'LOST'
3482 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3483 $lost_fee_line = $lost_fee_lines->next;
3486 $patron->account->payin_amount({
3488 interface => 'intranet',
3489 payment_type => 'CASH',
3490 user_id => $patron->borrowernumber,
3491 amount => $replacement_amount,
3492 debits => [$lost_fee_line]
3495 $lost_fee_line->discard_changes;
3497 is( int($lost_fee_line->amountoutstanding),
3499 'The LOST amountoutstanding is the expected amount after partial payment of lost fee'
3503 int($patron->account->balance),
3505 'Account balance is the expected amount after partial payment of lost fee'
3508 # Return lost item with partial payment having been made
3509 ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3511 $lost_fee_line->discard_changes;
3513 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero after returning lost item with full payment' );
3514 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set for lost item with partial payment' );
3516 int($patron->account->balance),
3518 'Account balance should be zero after returning item with lost fee when full payment has been made'
3522 subtest 'lostreturn | false' => sub {
3525 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
3527 my $item = $builder->build_sample_item(
3529 replacementprice => $replacement_amount
3534 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3536 # Fake fines cronjob on this checkout
3538 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3539 $ten_days_ago, $now );
3542 issue_id => $issue->issue_id,
3543 itemnumber => $item->itemnumber,
3544 borrowernumber => $patron->borrowernumber,
3546 due => output_pref($ten_days_ago)
3549 my $overdue_fees = Koha::Account::Lines->search(
3551 borrowernumber => $patron->id,
3552 itemnumber => $item->itemnumber,
3553 debit_type_code => 'OVERDUE'
3556 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3557 my $overdue_fee = $overdue_fees->next;
3558 is( $overdue_fee->amount + 0,
3559 10, 'The right OVERDUE amount is generated' );
3560 is( $overdue_fee->amountoutstanding + 0,
3562 'The right OVERDUE amountoutstanding is generated' );
3564 # Simulate item marked as lost
3565 $item->itemlost(3)->store;
3566 C4::Circulation::LostItem( $item->itemnumber, 1 );
3568 my $lost_fee_lines = Koha::Account::Lines->search(
3570 borrowernumber => $patron->id,
3571 itemnumber => $item->itemnumber,
3572 debit_type_code => 'LOST'
3575 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3576 my $lost_fee_line = $lost_fee_lines->next;
3577 is( $lost_fee_line->amount + 0,
3578 $replacement_amount, 'The right LOST amount is generated' );
3579 is( $lost_fee_line->amountoutstanding + 0,
3580 $replacement_amount,
3581 'The right LOST amountoutstanding is generated' );
3582 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3585 my ( $returned, $message ) =
3586 AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
3588 $overdue_fee->discard_changes;
3589 is( $overdue_fee->amount + 0,
3590 10, 'The OVERDUE amount is left intact' );
3591 is( $overdue_fee->amountoutstanding + 0,
3593 'The OVERDUE amountoutstanding is left intact' );
3595 $lost_fee_line->discard_changes;
3596 is( $lost_fee_line->amount + 0,
3597 $replacement_amount, 'The LOST amount is left intact' );
3598 is( $lost_fee_line->amountoutstanding + 0,
3599 $replacement_amount,
3600 'The LOST amountoutstanding is left intact' );
3601 # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
3602 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3605 subtest 'lostreturn | refund' => sub {
3608 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
3610 my $item = $builder->build_sample_item(
3612 replacementprice => $replacement_amount
3617 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3619 # Fake fines cronjob on this checkout
3621 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3622 $ten_days_ago, $now );
3625 issue_id => $issue->issue_id,
3626 itemnumber => $item->itemnumber,
3627 borrowernumber => $patron->borrowernumber,
3629 due => output_pref($ten_days_ago)
3632 my $overdue_fees = Koha::Account::Lines->search(
3634 borrowernumber => $patron->id,
3635 itemnumber => $item->itemnumber,
3636 debit_type_code => 'OVERDUE'
3639 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3640 my $overdue_fee = $overdue_fees->next;
3641 is( $overdue_fee->amount + 0,
3642 10, 'The right OVERDUE amount is generated' );
3643 is( $overdue_fee->amountoutstanding + 0,
3645 'The right OVERDUE amountoutstanding is generated' );
3647 # Simulate item marked as lost
3648 $item->itemlost(3)->store;
3649 C4::Circulation::LostItem( $item->itemnumber, 1 );
3651 my $lost_fee_lines = Koha::Account::Lines->search(
3653 borrowernumber => $patron->id,
3654 itemnumber => $item->itemnumber,
3655 debit_type_code => 'LOST'
3658 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3659 my $lost_fee_line = $lost_fee_lines->next;
3660 is( $lost_fee_line->amount + 0,
3661 $replacement_amount, 'The right LOST amount is generated' );
3662 is( $lost_fee_line->amountoutstanding + 0,
3663 $replacement_amount,
3664 'The right LOST amountoutstanding is generated' );
3665 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3667 # Return the lost item
3668 my ( undef, $message ) =
3669 AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
3671 $overdue_fee->discard_changes;
3672 is( $overdue_fee->amount + 0,
3673 10, 'The OVERDUE amount is left intact' );
3674 is( $overdue_fee->amountoutstanding + 0,
3676 'The OVERDUE amountoutstanding is left intact' );
3678 $lost_fee_line->discard_changes;
3679 is( $lost_fee_line->amount + 0,
3680 $replacement_amount, 'The LOST amount is left intact' );
3681 is( $lost_fee_line->amountoutstanding + 0,
3683 'The LOST amountoutstanding is refunded' );
3684 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3687 subtest 'lostreturn | restore' => sub {
3690 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
3692 my $item = $builder->build_sample_item(
3694 replacementprice => $replacement_amount
3699 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode , $ten_days_ago);
3701 # Fake fines cronjob on this checkout
3703 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3704 $ten_days_ago, $now );
3707 issue_id => $issue->issue_id,
3708 itemnumber => $item->itemnumber,
3709 borrowernumber => $patron->borrowernumber,
3711 due => output_pref($ten_days_ago)
3714 my $overdue_fees = Koha::Account::Lines->search(
3716 borrowernumber => $patron->id,
3717 itemnumber => $item->itemnumber,
3718 debit_type_code => 'OVERDUE'
3721 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3722 my $overdue_fee = $overdue_fees->next;
3723 is( $overdue_fee->amount + 0,
3724 10, 'The right OVERDUE amount is generated' );
3725 is( $overdue_fee->amountoutstanding + 0,
3727 'The right OVERDUE amountoutstanding is generated' );
3729 # Simulate item marked as lost
3730 $item->itemlost(3)->store;
3731 C4::Circulation::LostItem( $item->itemnumber, 1 );
3733 my $lost_fee_lines = Koha::Account::Lines->search(
3735 borrowernumber => $patron->id,
3736 itemnumber => $item->itemnumber,
3737 debit_type_code => 'LOST'
3740 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3741 my $lost_fee_line = $lost_fee_lines->next;
3742 is( $lost_fee_line->amount + 0,
3743 $replacement_amount, 'The right LOST amount is generated' );
3744 is( $lost_fee_line->amountoutstanding + 0,
3745 $replacement_amount,
3746 'The right LOST amountoutstanding is generated' );
3747 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3749 # Simulate refunding overdue fees upon marking item as lost
3750 my $overdue_forgive = $patron->account->add_credit(
3753 user_id => $manager->borrowernumber,
3754 library_id => $branchcode_restore,
3755 interface => 'test',
3757 item_id => $item->itemnumber
3760 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3761 $overdue_fee->discard_changes;
3762 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3765 my ( undef, $message ) =
3766 AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
3768 $overdue_fee->discard_changes;
3769 is( $overdue_fee->amount + 0,
3770 10, 'The OVERDUE amount is left intact' );
3771 is( $overdue_fee->amountoutstanding + 0,
3773 'The OVERDUE amountoutstanding is restored' );
3775 $lost_fee_line->discard_changes;
3776 is( $lost_fee_line->amount + 0,
3777 $replacement_amount, 'The LOST amount is left intact' );
3778 is( $lost_fee_line->amountoutstanding + 0,
3780 'The LOST amountoutstanding is refunded' );
3781 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3784 subtest 'lostreturn | charge' => sub {
3787 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
3789 my $item = $builder->build_sample_item(
3791 replacementprice => $replacement_amount
3796 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3798 # Fake fines cronjob on this checkout
3800 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3801 $ten_days_ago, $now );
3804 issue_id => $issue->issue_id,
3805 itemnumber => $item->itemnumber,
3806 borrowernumber => $patron->borrowernumber,
3808 due => output_pref($ten_days_ago)
3811 my $overdue_fees = Koha::Account::Lines->search(
3813 borrowernumber => $patron->id,
3814 itemnumber => $item->itemnumber,
3815 debit_type_code => 'OVERDUE'
3818 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3819 my $overdue_fee = $overdue_fees->next;
3820 is( $overdue_fee->amount + 0,
3821 10, 'The right OVERDUE amount is generated' );
3822 is( $overdue_fee->amountoutstanding + 0,
3824 'The right OVERDUE amountoutstanding is generated' );
3826 # Simulate item marked as lost
3827 $item->itemlost(3)->store;
3828 C4::Circulation::LostItem( $item->itemnumber, 1 );
3830 my $lost_fee_lines = Koha::Account::Lines->search(
3832 borrowernumber => $patron->id,
3833 itemnumber => $item->itemnumber,
3834 debit_type_code => 'LOST'
3837 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3838 my $lost_fee_line = $lost_fee_lines->next;
3839 is( $lost_fee_line->amount + 0,
3840 $replacement_amount, 'The right LOST amount is generated' );
3841 is( $lost_fee_line->amountoutstanding + 0,
3842 $replacement_amount,
3843 'The right LOST amountoutstanding is generated' );
3844 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3846 # Simulate refunding overdue fees upon marking item as lost
3847 my $overdue_forgive = $patron->account->add_credit(
3850 user_id => $manager->borrowernumber,
3851 library_id => $branchcode_charge,
3852 interface => 'test',
3854 item_id => $item->itemnumber
3857 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3858 $overdue_fee->discard_changes;
3859 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3862 my ( undef, $message ) =
3863 AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
3865 $lost_fee_line->discard_changes;
3866 is( $lost_fee_line->amount + 0,
3867 $replacement_amount, 'The LOST amount is left intact' );
3868 is( $lost_fee_line->amountoutstanding + 0,
3870 'The LOST amountoutstanding is refunded' );
3871 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3873 $overdue_fees = Koha::Account::Lines->search(
3875 borrowernumber => $patron->id,
3876 itemnumber => $item->itemnumber,
3877 debit_type_code => 'OVERDUE'
3880 order_by => { '-asc' => 'accountlines_id'}
3883 is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
3884 $overdue_fee = $overdue_fees->next;
3885 is( $overdue_fee->amount + 0,
3886 10, 'The original OVERDUE amount is left intact' );
3887 is( $overdue_fee->amountoutstanding + 0,
3889 'The original OVERDUE amountoutstanding is left as forgiven' );
3890 $overdue_fee = $overdue_fees->next;
3891 is( $overdue_fee->amount + 0,
3892 5, 'The new OVERDUE amount is correct for the backdated return' );
3893 is( $overdue_fee->amountoutstanding + 0,
3895 'The new OVERDUE amountoutstanding is correct for the backdated return' );
3900 subtest '_FixOverduesOnReturn' => sub {
3903 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3904 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3906 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3908 my $branchcode = $library2->{branchcode};
3910 my $item = $builder->build_sample_item(
3912 biblionumber => $biblio->biblionumber,
3913 library => $branchcode,
3914 replacementprice => 99.00,
3919 my $patron = $builder->build( { source => 'Borrower' } );
3921 ## Start with basic call, should just close out the open fine
3922 my $accountline = Koha::Account::Line->new(
3924 borrowernumber => $patron->{borrowernumber},
3925 debit_type_code => 'OVERDUE',
3926 status => 'UNRETURNED',
3927 itemnumber => $item->itemnumber,
3929 amountoutstanding => 99.00,
3930 interface => 'test',
3934 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
3936 $accountline->_result()->discard_changes();
3938 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
3939 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3940 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3942 ## Run again, with exemptfine enabled
3945 debit_type_code => 'OVERDUE',
3946 status => 'UNRETURNED',
3947 amountoutstanding => 99.00,
3951 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3953 $accountline->_result()->discard_changes();
3954 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'APPLY' })->next();
3956 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
3957 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3958 is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
3959 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
3960 is( $offset->amount + 0, -99, "Amount of offset is correct" );
3961 my $credit = $offset->credit;
3962 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
3963 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
3964 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
3966 # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
3969 debit_type_code => 'OVERDUE',
3970 status => 'UNRETURNED',
3971 amountoutstanding => 0.00,
3976 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3978 $accountline->_result()->discard_changes();
3979 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'CREATE' })->next();
3980 is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
3981 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3982 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3985 subtest 'Set waiting flag' => sub {
3988 my $library_1 = $builder->build( { source => 'Branch' } );
3989 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3990 my $library_2 = $builder->build( { source => 'Branch' } );
3991 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3993 my $item = $builder->build_sample_item(
3995 library => $library_1->{branchcode},
3999 set_userenv( $library_2 );
4000 my $reserve_id = AddReserve(
4002 branchcode => $library_2->{branchcode},
4003 borrowernumber => $patron_2->{borrowernumber},
4004 biblionumber => $item->biblionumber,
4006 itemnumber => $item->itemnumber,
4010 set_userenv( $library_1 );
4011 my $do_transfer = 1;
4012 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
4013 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
4014 my $hold = Koha::Holds->find( $reserve_id );
4015 is( $hold->found, 'T', 'Hold is in transit' );
4017 my ( $status ) = CheckReserves($item->itemnumber);
4018 is( $status, 'Transferred', 'Hold is not waiting yet');
4020 set_userenv( $library_2 );
4022 AddReturn( $item->barcode, $library_2->{branchcode} );
4023 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
4024 $hold = Koha::Holds->find( $reserve_id );
4025 is( $hold->found, 'W', 'Hold is waiting' );
4026 ( $status ) = CheckReserves($item->itemnumber);
4027 is( $status, 'Waiting', 'Now the hold is waiting');
4029 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
4030 set_userenv( $library_1 );
4031 (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
4032 $hold = Koha::Holds->find( $reserve_id );
4033 is( $hold->found, undef, 'Hold is no longer marked waiting' );
4034 is( $hold->priority, 1, "Hold is now priority one again");
4035 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
4036 is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
4037 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
4038 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
4039 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
4042 subtest 'Cancel transfers on lost items' => sub {
4045 my $library_to = $builder->build_object( { class => 'Koha::Libraries' } );
4046 my $item = $builder->build_sample_item();
4047 my $holdingbranch = $item->holdingbranch;
4048 # Historic transfer (datearrived is defined)
4049 my $old_transfer = $builder->build_object(
4051 class => 'Koha::Item::Transfers',
4053 itemnumber => $item->itemnumber,
4054 frombranch => $holdingbranch,
4055 tobranch => $library_to->branchcode,
4057 datesent => \'NOW()',
4058 datearrived => \'NOW()',
4059 datecancelled => undef,
4060 daterequested => \'NOW()'
4064 # Queued transfer (datesent is undefined)
4065 my $transfer_1 = $builder->build_object(
4067 class => 'Koha::Item::Transfers',
4069 itemnumber => $item->itemnumber,
4070 frombranch => $holdingbranch,
4071 tobranch => $library_to->branchcode,
4074 datearrived => undef,
4075 datecancelled => undef,
4076 daterequested => \'NOW()'
4080 # In transit transfer (datesent is defined, datearrived and datecancelled are both undefined)
4081 my $transfer_2 = $builder->build_object(
4083 class => 'Koha::Item::Transfers',
4085 itemnumber => $item->itemnumber,
4086 frombranch => $holdingbranch,
4087 tobranch => $library_to->branchcode,
4089 datesent => \'NOW()',
4090 datearrived => undef,
4091 datecancelled => undef,
4092 daterequested => \'NOW()'
4097 # Simulate item being marked as lost
4098 $item->itemlost(1)->store;
4099 LostItem( $item->itemnumber, 'test', 1 );
4101 $transfer_1->discard_changes;
4102 isnt($transfer_1->datecancelled, undef, "Queud transfer was cancelled upon item lost");
4103 is($transfer_1->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
4104 $transfer_2->discard_changes;
4105 isnt($transfer_2->datecancelled, undef, "Active transfer was cancelled upon item lost");
4106 is($transfer_2->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
4107 $old_transfer->discard_changes;
4108 is($old_transfer->datecancelled, undef, "Old transfers are unaffected");
4109 $item->discard_changes;
4110 is($item->holdingbranch, $holdingbranch, "Items holding branch remains unchanged");
4113 subtest 'CanBookBeIssued | is_overdue' => sub {
4116 # Set a simple circ policy
4117 Koha::CirculationRules->set_rules(
4119 categorycode => undef,
4120 branchcode => undef,
4124 reservesallowed => 25,
4126 lengthunit => 'days',
4127 renewalsallowed => 1,
4129 norenewalbefore => undef,
4137 my $now = dt_from_string()->truncate( to => 'day' );
4138 my $five_days_go = $now->clone->add( days => 5 );
4139 my $ten_days_go = $now->clone->add( days => 10);
4140 my $library = $builder->build( { source => 'Branch' } );
4141 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
4143 my $item = $builder->build_sample_item(
4145 library => $library->{branchcode},
4149 my $issue = AddIssue( $patron->unblessed, $item->barcode, $five_days_go ); # date due was 10d ago
4150 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
4151 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), output_pref({ str => $five_days_go, dateonly => 1}), "First issue works");
4152 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron, $item->barcode, $ten_days_go, undef, undef, undef);
4153 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
4154 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
4157 subtest 'ItemsDeniedRenewal rules are checked' => sub {
4160 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
4161 Koha::CirculationRules->set_rules(
4163 categorycode => '*',
4165 branchcode => $idr_lib->branchcode,
4167 reservesallowed => 25,
4169 lengthunit => 'days',
4170 renewalsallowed => 10,
4172 norenewalbefore => undef,
4180 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
4181 homebranch => $idr_lib->branchcode,
4184 location => 'NOPROC'
4188 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
4189 branchcode => $idr_lib->branchcode,
4192 my $future = dt_from_string->add( days => 1 );
4193 my $issue = $builder->build_object(
4195 class => 'Koha::Checkouts',
4197 returndate => undef,
4198 renewals_count => 0,
4200 borrowernumber => $idr_borrower->borrowernumber,
4201 itemnumber => $allow_book->itemnumber,
4202 onsite_checkout => 0,
4203 date_due => $future,
4208 my $mock_item_class = Test::MockModule->new("Koha::Item");
4209 $mock_item_class->mock( 'is_denied_renewal', sub { return 1; } );
4211 my ( $mayrenew, $error ) = CanBookBeRenewed( $idr_borrower->borrowernumber, $issue->itemnumber );
4212 is( $mayrenew, 0, 'Renewal blocked when $item->is_denied_renewal returns true' );
4213 is( $error, 'item_denied_renewal', 'Renewal blocked when $item->is_denied_renewal returns true' );
4215 $mock_item_class->unmock( 'is_denied_renewal' );
4216 $mock_item_class->mock( 'is_denied_renewal', sub { return 0; } );
4218 ( $mayrenew, $error ) = CanBookBeRenewed( $idr_borrower->borrowernumber, $issue->itemnumber );
4219 is( $mayrenew, 1, 'Renewal allowed when $item->is_denied_renewal returns false' );
4220 is( $error, undef, 'Renewal allowed when $item->is_denied_renewal returns false' );
4222 $mock_item_class->unmock( 'is_denied_renewal' );
4225 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
4228 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4229 my $library = $builder->build( { source => 'Branch' } );
4230 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4232 my $item = $builder->build_sample_item(
4234 library => $library->{branchcode},
4238 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4239 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4240 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4243 subtest 'CanBookBeIssued | notforloan' => sub {
4246 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
4248 my $library = $builder->build( { source => 'Branch' } );
4249 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4251 my $itemtype = $builder->build(
4253 source => 'Itemtype',
4254 value => { notforloan => undef, }
4257 my $item = $builder->build_sample_item(
4259 library => $library->{branchcode},
4260 itype => $itemtype->{itemtype},
4263 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4265 my ( $issuingimpossible, $needsconfirmation );
4268 subtest 'item-level_itypes = 1' => sub {
4271 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
4272 # Is for loan at item type and item level
4273 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4274 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4275 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4277 # not for loan at item type level
4278 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4279 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4280 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4283 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4284 'Item can not be issued, not for loan at item type level'
4287 # not for loan at item level
4288 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4289 $item->notforloan( 1 )->store;
4290 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4291 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4294 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4295 'Item can not be issued, not for loan at item type level'
4299 subtest 'item-level_itypes = 0' => sub {
4302 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4304 # We set another itemtype for biblioitem
4305 my $itemtype = $builder->build(
4307 source => 'Itemtype',
4308 value => { notforloan => undef, }
4312 # for loan at item type and item level
4313 $item->notforloan(0)->store;
4314 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4315 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4316 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4317 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4319 # not for loan at item type level
4320 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4321 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4322 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4325 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4326 'Item can not be issued, not for loan at item type level'
4329 # not for loan at item level
4330 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4331 $item->notforloan( 1 )->store;
4332 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4333 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4336 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4337 'Item can not be issued, not for loan at item type level'
4341 # TODO test with AllowNotForLoanOverride = 1
4344 subtest 'CanBookBeIssued | recalls' => sub {
4347 t::lib::Mocks::mock_preference("UseRecalls", 1);
4348 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4349 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4350 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4351 my $item = $builder->build_sample_item;
4352 Koha::CirculationRules->set_rules({
4353 branchcode => undef,
4355 categorycode => undef,
4357 recalls_allowed => 10,
4362 my $recall = Koha::Recall->new(
4363 { patron_id => $patron1->borrowernumber,
4364 biblio_id => $item->biblionumber,
4365 item_id => $item->itemnumber,
4367 pickup_library_id => $patron1->branchcode,
4371 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4372 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed an item-level recall on this item" );
4374 $recall->set_cancelled;
4376 # biblio-level recall
4377 $recall = Koha::Recall->new(
4378 { patron_id => $patron1->borrowernumber,
4379 biblio_id => $item->biblionumber,
4382 pickup_library_id => $patron1->branchcode,
4386 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4387 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed a biblio-level recall and this item is eligible to fill it" );
4389 $recall->set_cancelled;
4391 # biblio-level recall
4392 $recall = Koha::Recall->new(
4393 { patron_id => $patron1->borrowernumber,
4394 biblio_id => $item->biblionumber,
4397 pickup_library_id => $patron1->branchcode,
4400 $recall->set_waiting( { item => $item, expirationdate => dt_from_string() } );
4402 my ( undef, undef, undef, $messages ) = CanBookBeIssued( $patron1, $item->barcode, undef, undef, undef, undef );
4403 is( $messages->{RECALLED}, $recall->id, "This book can be issued by this patron and they have placed a recall" );
4405 $recall->set_cancelled;
4408 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
4411 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
4412 my $item = $builder->build_sample_item(
4414 onloan => '2018-01-01',
4418 AddReturn( $item->barcode, $item->homebranch );
4419 $item->discard_changes; # refresh
4420 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
4423 subtest 'AddReturn | recalls' => sub {
4426 t::lib::Mocks::mock_preference("UseRecalls", 1);
4427 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4428 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4429 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4430 my $item1 = $builder->build_sample_item;
4431 Koha::CirculationRules->set_rules({
4432 branchcode => undef,
4434 categorycode => undef,
4436 recalls_allowed => 10,
4440 # this item can fill a recall with pickup at this branch
4441 AddIssue( $patron1->unblessed, $item1->barcode );
4442 my $recall1 = Koha::Recall->new(
4443 { patron_id => $patron2->borrowernumber,
4444 biblio_id => $item1->biblionumber,
4445 item_id => $item1->itemnumber,
4447 pickup_library_id => $item1->homebranch,
4450 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4451 is( $messages->{RecallFound}->id, $recall1->id, "Recall found" );
4452 $recall1->set_cancelled;
4454 # this item can fill a recall but needs transfer
4455 AddIssue( $patron1->unblessed, $item1->barcode );
4456 $recall1 = Koha::Recall->new(
4457 { patron_id => $patron2->borrowernumber,
4458 biblio_id => $item1->biblionumber,
4459 item_id => $item1->itemnumber,
4461 pickup_library_id => $patron2->branchcode,
4464 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4465 is( $messages->{RecallNeedsTransfer}, $item1->homebranch, "Recall requiring transfer found" );
4466 $recall1->set_cancelled;
4468 # this item is already in transit, do not ask to transfer
4469 AddIssue( $patron1->unblessed, $item1->barcode );
4470 $recall1 = Koha::Recall->new(
4471 { patron_id => $patron2->borrowernumber,
4472 biblio_id => $item1->biblionumber,
4473 item_id => $item1->itemnumber,
4475 pickup_library_id => $patron2->branchcode,
4478 $recall1->start_transfer;
4479 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $patron2->branchcode );
4480 is( $messages->{TransferredRecall}->id, $recall1->id, "In transit recall found" );
4481 $recall1->set_cancelled;
4484 subtest 'AddReturn | bundles' => sub {
4487 my $schema = Koha::Database->schema;
4488 $schema->storage->txn_begin;
4490 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4491 my $host_item1 = $builder->build_sample_item;
4492 my $bundle_item1 = $builder->build_sample_item;
4493 $schema->resultset('ItemBundle')
4495 { host => $host_item1->itemnumber, item => $bundle_item1->itemnumber } );
4497 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $bundle_item1->barcode, $bundle_item1->homebranch );
4498 is($messages->{InBundle}->id, $host_item1->id, 'AddReturn returns InBundle host item when item is part of a bundle');
4500 $schema->storage->txn_rollback;
4503 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
4508 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4510 my $issuing_charges = 15;
4511 my $title = 'A title';
4512 my $author = 'Author, An';
4513 my $barcode = 'WHATARETHEODDS';
4515 my $circ = Test::MockModule->new('C4::Circulation');
4517 'GetIssuingCharges',
4519 return $issuing_charges;
4523 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4524 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
4525 my $patron = $builder->build_object({
4526 class => 'Koha::Patrons',
4527 value => { branchcode => $library->id }
4530 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
4531 my $item_id = Koha::Item->new(
4533 biblionumber => $biblio->biblionumber,
4534 homebranch => $library->id,
4535 holdingbranch => $library->id,
4536 barcode => $barcode,
4537 replacementprice => 23.00,
4538 itype => $itemtype->id
4540 )->store->itemnumber;
4541 my $item = Koha::Items->find( $item_id );
4543 my $context = Test::MockModule->new('C4::Context');
4544 $context->mock( userenv => { branch => $library->id } );
4546 # Check the item out
4547 AddIssue( $patron->unblessed, $item->barcode );
4550 AddRenewal( $patron->borrowernumber, $item->itemnumber, $library->id, undef, {break=>"the_renewal"} );
4551 } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
4553 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
4554 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
4555 my %params_renewal = (
4556 timestamp => { -like => $date . "%" },
4557 module => "CIRCULATION",
4558 action => "RENEWAL",
4560 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
4561 AddRenewal( $patron->id, $item->id, $library->id );
4562 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4563 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
4565 my $checkouts = $patron->checkouts;
4566 # The following will fail if run on 00:00:00
4567 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
4569 my $lines = Koha::Account::Lines->search({
4570 borrowernumber => $patron->id,
4571 itemnumber => $item->id
4574 is( $lines->count, 2 );
4576 my $line = $lines->next;
4577 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
4578 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
4579 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
4581 $line = $lines->next;
4582 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
4583 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
4584 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
4586 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
4588 $context = Test::MockModule->new('C4::Context');
4589 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
4591 my $now = dt_from_string;
4592 $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
4593 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
4594 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
4595 $sth->execute($item->id, $library->id);
4596 my ($old_stats_size) = $sth->fetchrow_array;
4597 AddRenewal( $patron->id, $item->id, $library->id );
4598 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4599 $sth->execute($item->id, $library->id);
4600 my ($new_stats_size) = $sth->fetchrow_array;
4601 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
4602 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
4604 AddReturn( $item->id, $library->id, undef, $date );
4605 AddIssue( $patron->unblessed, $item->barcode, $now );
4606 AddRenewal( $patron->id, $item->id, $library->id, undef, undef, 1 );
4607 my $lines_skipped = Koha::Account::Lines->search({
4608 borrowernumber => $patron->id,
4609 itemnumber => $item->id
4611 is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
4615 subtest 'AddRenewal() adds to renewals' => sub {
4618 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4619 my $patron = $builder->build_object({
4620 class => 'Koha::Patrons',
4621 value => { branchcode => $library->id }
4624 my $item = $builder->build_sample_item();
4626 set_userenv( $library->unblessed );
4628 # Check the item out
4629 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4630 is(ref($issue), 'Koha::Checkout', 'Issue added');
4633 my $duedate = AddRenewal( $patron->id, $item->id, $library->id );
4635 ok( $duedate, "Renewal added" );
4637 my $renewals = Koha::Checkouts::Renewals->search({ checkout_id => $issue->issue_id });
4638 is($renewals->count, 1, 'One renewal added');
4639 my $THE_renewal = $renewals->next;
4640 is( $THE_renewal->renewer_id, C4::Context->userenv->{'number'}, 'Renewer recorded from context' );
4643 subtest 'ProcessOfflinePayment() tests' => sub {
4650 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
4651 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4652 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
4654 is( $result, 'Success.', 'The right string is returned' );
4656 my $lines = $patron->account->lines;
4657 is( $lines->count, 1, 'line created correctly');
4659 my $line = $lines->next;
4660 is( $line->amount+0, $amount * -1, 'amount picked from params' );
4661 is( $line->branchcode, $library->id, 'branchcode set correctly' );
4665 subtest 'Incremented fee tests' => sub {
4668 my $dt = dt_from_string();
4669 Time::Fake->offset( $dt->epoch );
4671 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
4673 my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store;
4675 $module->mock( 'userenv', sub { { branch => $library->id } } );
4677 my $patron = $builder->build_object(
4679 class => 'Koha::Patrons',
4680 value => { categorycode => $patron_category->{categorycode} }
4684 my $itemtype = $builder->build_object(
4686 class => 'Koha::ItemTypes',
4688 notforloan => undef,
4690 rentalcharge_daily => 1,
4691 rentalcharge_daily_calendar => 0
4696 my $item = $builder->build_sample_item(
4698 library => $library->id,
4699 itype => $itemtype->id,
4703 is( $itemtype->rentalcharge_daily + 0,1, 'Daily rental charge stored and retreived correctly' );
4704 is( $item->effective_itemtype, $itemtype->id, "Itemtype set correctly for item" );
4706 my $now = dt_from_string;
4707 my $dt_from = $now->clone;
4708 my $dt_to = $now->clone->add( days => 7 );
4709 my $dt_to_renew = $now->clone->add( days => 13 );
4713 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4714 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4716 $accountline->amount + 0,
4718 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
4720 $accountline->delete();
4721 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4722 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4724 $accountline->amount + 0,
4726 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
4728 $accountline->delete();
4731 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
4732 $itemtype->rentalcharge_daily_calendar(1)->store();
4734 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4735 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4737 $accountline->amount + 0,
4739 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
4741 $accountline->delete();
4742 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4743 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4745 $accountline->amount + 0,
4747 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
4749 $accountline->delete();
4752 my $calendar = C4::Calendar->new( branchcode => $library->id );
4753 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
4755 ( $dt_from->day_of_week == 6 ) ? 0
4756 : ( $dt_from->day_of_week == 7 ) ? 1
4757 : $dt_from->day_of_week + 1;
4758 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
4759 $calendar->insert_week_day_holiday(
4760 weekday => $closed_day,
4761 title => 'Test holiday',
4762 description => 'Test holiday'
4765 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4766 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4768 $accountline->amount + 0,
4770 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
4772 $accountline->delete();
4773 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4774 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4776 $accountline->amount + 0,
4778 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
4780 $accountline->delete();
4783 $itemtype->rentalcharge(2)->store;
4784 is( $itemtype->rentalcharge + 0, 2, 'Rental charge updated and retreived correctly' );
4786 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4788 Koha::Account::Lines->search( { itemnumber => $item->id } );
4789 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly" );
4790 $accountlines->delete();
4791 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4792 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
4793 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly, for renewal" );
4794 $accountlines->delete();
4796 $itemtype->rentalcharge(0)->store;
4797 is( $itemtype->rentalcharge + 0, 0, 'Rental charge reset and retreived correctly' );
4800 Koha::CirculationRules->set_rule(
4802 categorycode => $patron->categorycode,
4803 itemtype => $itemtype->id,
4804 branchcode => $library->id,
4805 rule_name => 'lengthunit',
4806 rule_value => 'hours',
4810 $itemtype->rentalcharge_hourly('0.25')->store();
4811 is( $itemtype->rentalcharge_hourly, '0.25', 'Hourly rental charge stored and retreived correctly' );
4813 $dt_to = $now->clone->add( hours => 168 );
4814 $dt_to_renew = $now->clone->add( hours => 312 );
4816 $itemtype->rentalcharge_hourly_calendar(0)->store();
4818 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4819 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4821 $accountline->amount + 0,
4823 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)"
4825 $accountline->delete();
4826 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4827 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4829 $accountline->amount + 0,
4831 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)"
4833 $accountline->delete();
4836 $itemtype->rentalcharge_hourly_calendar(1)->store();
4838 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4839 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4841 $accountline->amount + 0,
4843 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)"
4845 $accountline->delete();
4846 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4847 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4849 $accountline->amount + 0,
4851 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u"
4853 $accountline->delete();
4856 $calendar->delete_holiday( weekday => $closed_day );
4858 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4859 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4861 $accountline->amount + 0,
4863 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u"
4865 $accountline->delete();
4866 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4867 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4869 $accountline->amount + 0,
4871 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)"
4873 $accountline->delete();
4878 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
4881 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
4882 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4885 $builder->build_object( { class => 'Koha::Libraries' } )->store;
4886 my $patron = $builder->build_object(
4888 class => 'Koha::Patrons',
4889 value => { categorycode => $patron_category->{categorycode} }
4893 my $itemtype = $builder->build_object(
4895 class => 'Koha::ItemTypes',
4899 rentalcharge_daily => 0
4904 my $item = $builder->build_sample_item(
4906 library => $library->id,
4910 itype => $itemtype->id,
4914 my ( $issuingimpossible, $needsconfirmation );
4915 my $dt_from = dt_from_string();
4916 my $dt_due = $dt_from->clone->add( days => 3 );
4918 $itemtype->rentalcharge(1)->store;
4919 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4920 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
4921 $itemtype->rentalcharge('0')->store;
4922 $itemtype->rentalcharge_daily(1)->store;
4923 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4924 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
4925 $itemtype->rentalcharge_daily('0')->store;
4928 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
4931 t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
4933 my $patron = $builder->build_object(
4935 class => 'Koha::Patrons',
4936 value => { categorycode => $patron_category->{categorycode} }
4940 my $item = $builder->build_sample_item(
4942 materials => 'includes DVD',
4946 my $dt_due = dt_from_string->add( days => 3 );
4948 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4949 is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
4952 subtest 'Do not return on renewal (LOST charge)' => sub {
4955 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
4956 my $library = $builder->build_object( { class => "Koha::Libraries" } );
4957 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
4958 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
4960 my $biblio = $builder->build_sample_biblio;
4962 my $item = $builder->build_sample_item(
4964 biblionumber => $biblio->biblionumber,
4965 library => $library->branchcode,
4966 replacementprice => 99.00,
4971 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
4972 AddIssue( $patron->unblessed, $item->barcode );
4974 my $accountline = Koha::Account::Line->new(
4976 borrowernumber => $patron->borrowernumber,
4977 debit_type_code => 'LOST',
4979 itemnumber => $item->itemnumber,
4981 amountoutstanding => 12,
4982 interface => 'something',
4986 # AddRenewal doesn't call _FixAccountForLostAndFound
4987 AddIssue( $patron->unblessed, $item->barcode );
4989 is( $patron->checkouts->count, 1,
4990 'Renewal should not return the item even if a LOST payment has been made earlier'
4994 subtest 'Filling a hold should cancel existing transfer' => sub {
4997 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
4999 my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
5000 my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
5001 my $patron = $builder->build_object(
5003 class => 'Koha::Patrons',
5005 categorycode => $patron_category->{categorycode},
5006 branchcode => $libraryA->branchcode,
5011 my $item = $builder->build_sample_item({
5012 homebranch => $libraryB->branchcode,
5015 my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
5016 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
5018 branchcode => $libraryA->branchcode,
5019 borrowernumber => $patron->borrowernumber,
5020 biblionumber => $item->biblionumber,
5021 itemnumber => $item->itemnumber
5023 my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
5024 is( $reserves->count, 1, "Reserve is placed");
5025 ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
5026 my $reserve = $reserves->next;
5027 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
5028 $reserve->discard_changes;
5029 ok( $reserve->found eq 'W', "Reserve is marked waiting" );
5030 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
5033 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
5037 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
5038 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5039 my $patron = $builder->build_object(
5041 class => 'Koha::Patrons',
5042 value => { categorycode => $patron_category->{categorycode} }
5046 my $biblionumber = $builder->build_sample_biblio(
5048 branchcode => $library->branchcode,
5052 # And the circulation rule
5053 Koha::CirculationRules->search->delete;
5054 Koha::CirculationRules->set_rules(
5056 categorycode => undef,
5058 branchcode => undef,
5061 lengthunit => 'days',
5067 source => 'CirculationRule',
5069 branchcode => undef,
5070 categorycode => undef,
5072 rule_name => 'lostreturn',
5073 rule_value => 'refund'
5078 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5081 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5082 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5084 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5086 my $item = $builder->build_sample_item(
5088 biblionumber => $biblionumber,
5089 library => $library->branchcode,
5090 replacementprice => '42',
5093 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5094 LostItem( $item->itemnumber, 'cli', 0 );
5095 $item->_result->itemlost(1);
5096 $item->_result->itemlost_on( $lost_on );
5097 $item->_result->update();
5099 my $a = Koha::Account::Lines->search(
5101 itemnumber => $item->id,
5102 borrowernumber => $patron->borrowernumber
5105 ok( $a, "Found accountline for lost fee" );
5106 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5107 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5108 $a = $a->get_from_storage;
5109 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5113 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5116 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5117 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5119 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5121 my $item = $builder->build_sample_item(
5123 biblionumber => $biblionumber,
5124 library => $library->branchcode,
5125 replacementprice => '42',
5128 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5129 LostItem( $item->itemnumber, 'cli', 0 );
5130 $item->_result->itemlost(1);
5131 $item->_result->itemlost_on( $lost_on );
5132 $item->_result->update();
5134 my $a = Koha::Account::Lines->search(
5136 itemnumber => $item->id,
5137 borrowernumber => $patron->borrowernumber
5140 ok( $a, "Found accountline for lost fee" );
5141 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5142 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5143 $a = $a->get_from_storage;
5144 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5148 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5151 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5152 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5154 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5156 my $item = $builder->build_sample_item(
5158 biblionumber => $biblionumber,
5159 library => $library->branchcode,
5160 replacementprice => '42',
5163 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5164 LostItem( $item->itemnumber, 'cli', 0 );
5165 $item->_result->itemlost(1);
5166 $item->_result->itemlost_on( $lost_on );
5167 $item->_result->update();
5169 my $a = Koha::Account::Lines->search(
5171 itemnumber => $item->id,
5172 borrowernumber => $patron->borrowernumber
5175 ok( $a, "Found accountline for lost fee" );
5176 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5177 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5178 $a = $a->get_from_storage;
5179 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5183 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5186 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5187 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5189 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5191 my $item = $builder->build_sample_item(
5193 biblionumber => $biblionumber,
5194 library => $library->branchcode,
5195 replacementprice => '42',
5198 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5199 LostItem( $item->itemnumber, 'cli', 0 );
5200 $item->_result->itemlost(1);
5201 $item->_result->itemlost_on( $lost_on );
5202 $item->_result->update();
5204 my $a = Koha::Account::Lines->search(
5206 itemnumber => $item->id,
5207 borrowernumber => $patron->borrowernumber
5211 ok( $a, "Found accountline for lost fee" );
5212 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5213 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5214 $a = $a->get_from_storage;
5215 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5220 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
5224 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
5225 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5226 my $patron = $builder->build_object(
5228 class => 'Koha::Patrons',
5229 value => { categorycode => $patron_category->{categorycode} }
5232 my $patron2 = $builder->build_object(
5234 class => 'Koha::Patrons',
5235 value => { categorycode => $patron_category->{categorycode} }
5239 my $biblionumber = $builder->build_sample_biblio(
5241 branchcode => $library->branchcode,
5245 # And the circulation rule
5246 Koha::CirculationRules->search->delete;
5247 Koha::CirculationRules->set_rules(
5249 categorycode => undef,
5251 branchcode => undef,
5254 lengthunit => 'days',
5260 source => 'CirculationRule',
5262 branchcode => undef,
5263 categorycode => undef,
5265 rule_name => 'lostreturn',
5266 rule_value => 'refund'
5271 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5274 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5275 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5277 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5279 my $item = $builder->build_sample_item(
5281 biblionumber => $biblionumber,
5282 library => $library->branchcode,
5283 replacementprice => '42',
5286 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5287 LostItem( $item->itemnumber, 'cli', 0 );
5288 $item->_result->itemlost(1);
5289 $item->_result->itemlost_on( $lost_on );
5290 $item->_result->update();
5292 my $a = Koha::Account::Lines->search(
5294 itemnumber => $item->id,
5295 borrowernumber => $patron->borrowernumber
5298 ok( $a, "Found accountline for lost fee" );
5299 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5300 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5301 $a = $a->get_from_storage;
5302 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5307 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5310 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5311 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5313 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5315 my $item = $builder->build_sample_item(
5317 biblionumber => $biblionumber,
5318 library => $library->branchcode,
5319 replacementprice => '42',
5322 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5323 LostItem( $item->itemnumber, 'cli', 0 );
5324 $item->_result->itemlost(1);
5325 $item->_result->itemlost_on( $lost_on );
5326 $item->_result->update();
5328 my $a = Koha::Account::Lines->search(
5330 itemnumber => $item->id,
5331 borrowernumber => $patron->borrowernumber
5334 ok( $a, "Found accountline for lost fee" );
5335 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5336 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5337 $a = $a->get_from_storage;
5338 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5342 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5345 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5346 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5348 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5350 my $item = $builder->build_sample_item(
5352 biblionumber => $biblionumber,
5353 library => $library->branchcode,
5354 replacementprice => '42',
5357 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5358 LostItem( $item->itemnumber, 'cli', 0 );
5359 $item->_result->itemlost(1);
5360 $item->_result->itemlost_on( $lost_on );
5361 $item->_result->update();
5363 my $a = Koha::Account::Lines->search(
5365 itemnumber => $item->id,
5366 borrowernumber => $patron->borrowernumber
5369 ok( $a, "Found accountline for lost fee" );
5370 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5371 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5372 $a = $a->get_from_storage;
5373 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5377 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5380 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5381 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5383 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5385 my $item = $builder->build_sample_item(
5387 biblionumber => $biblionumber,
5388 library => $library->branchcode,
5389 replacementprice => '42',
5392 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5393 LostItem( $item->itemnumber, 'cli', 0 );
5394 $item->_result->itemlost(1);
5395 $item->_result->itemlost_on( $lost_on );
5396 $item->_result->update();
5398 my $a = Koha::Account::Lines->search(
5400 itemnumber => $item->id,
5401 borrowernumber => $patron->borrowernumber
5405 ok( $a, "Found accountline for lost fee" );
5406 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5407 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5408 $a = $a->get_from_storage;
5409 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5414 subtest 'transferbook tests' => sub {
5418 { C4::Circulation::transferbook({}); }
5419 'Koha::Exceptions::MissingParameter',
5420 'Koha::Patron->store raises an exception on missing params';
5423 { C4::Circulation::transferbook({to_branch=>'anything'}); }
5424 'Koha::Exceptions::MissingParameter',
5425 'Koha::Patron->store raises an exception on missing params';
5428 { C4::Circulation::transferbook({from_branch=>'anything'}); }
5429 'Koha::Exceptions::MissingParameter',
5430 'Koha::Patron->store raises an exception on missing params';
5432 my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
5433 is( $doreturn, 0, "No return without barcode");
5434 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5435 is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
5437 ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
5438 is( $doreturn, 0, "No return without barcode");
5439 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5440 is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
5444 subtest 'Checkout should correctly terminate a transfer' => sub {
5447 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5448 my $patron_1 = $builder->build_object(
5450 class => 'Koha::Patrons',
5451 value => { branchcode => $library_1->branchcode }
5454 my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
5455 my $patron_2 = $builder->build_object(
5457 class => 'Koha::Patrons',
5458 value => { branchcode => $library_2->branchcode }
5462 my $item = $builder->build_sample_item(
5464 library => $library_1->branchcode,
5468 t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
5469 my $reserve_id = AddReserve(
5471 branchcode => $library_2->branchcode,
5472 borrowernumber => $patron_2->borrowernumber,
5473 biblionumber => $item->biblionumber,
5474 itemnumber => $item->itemnumber,
5479 my $do_transfer = 1;
5480 ModItemTransfer( $item->itemnumber, $library_1->branchcode,
5481 $library_2->branchcode, 'Manual' );
5482 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
5483 GetOtherReserves( $item->itemnumber )
5484 ; # To put the Reason, it's what does returns.pl...
5485 my $hold = Koha::Holds->find($reserve_id);
5486 is( $hold->found, 'T', 'Hold is in transit' );
5487 my $transfer = $item->get_transfer;
5488 is( $transfer->frombranch, $library_1->branchcode );
5489 is( $transfer->tobranch, $library_2->branchcode );
5490 is( $transfer->reason, 'Reserve' );
5492 t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
5493 AddIssue( $patron_1->unblessed, $item->barcode );
5494 $transfer = $transfer->get_from_storage;
5495 isnt( $transfer->datearrived, undef );
5496 $hold = $hold->get_from_storage;
5497 is( $hold->found, undef, 'Hold is waiting' );
5498 is( $hold->priority, 1, );
5501 subtest 'AddIssue records staff who checked out item if appropriate' => sub {
5504 $module->mock( 'userenv', sub { { branch => $library->{id} } } );
5506 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5507 my $patron = $builder->build_object(
5509 class => 'Koha::Patrons',
5510 value => { categorycode => $patron_category->{categorycode} }
5513 my $issuer = $builder->build_object(
5515 class => 'Koha::Patrons',
5516 value => { categorycode => $patron_category->{categorycode} }
5519 my $item_1 = $builder->build_sample_item(
5521 library => $library->{branchcode}
5525 my $item_2 = $builder->build_sample_item(
5527 library => $library->branchcode
5531 $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->borrowernumber } } );
5533 my $dt_from = dt_from_string();
5534 my $dt_to = dt_from_string()->add( days => 7 );
5536 my $issue_1 = AddIssue( $patron->unblessed, $item_1->barcode, $dt_to, undef, $dt_from );
5538 is( $issue_1->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
5540 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
5543 AddIssue( $patron->unblessed, $item_2->barcode, $dt_to, undef, $dt_from );
5545 is( $issue_2->issuer->borrowernumber, $issuer->borrowernumber, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
5548 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
5551 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5552 my $patron_1 = $builder->build_object(
5554 class => 'Koha::Patrons',
5555 value => { branchcode => $library_1->branchcode }
5558 my $patron_2 = $builder->build_object(
5560 class => 'Koha::Patrons',
5561 value => { branchcode => $library_1->branchcode }
5565 my $item = $builder->build_sample_item(
5567 library => $library_1->branchcode,
5571 AddIssue( $patron_1->unblessed, $item->barcode );
5572 ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
5573 AddIssue( $patron_2->unblessed, $item->barcode );
5574 ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
5577 subtest "updateWrongTransfer tests" => sub {
5580 my $library1 = $builder->build_object( { class => 'Koha::Libraries' } );
5581 my $library2 = $builder->build_object( { class => 'Koha::Libraries' } );
5582 my $library3 = $builder->build_object( { class => 'Koha::Libraries' } );
5583 my $item = $builder->build_sample_item(
5585 homebranch => $library1->branchcode,
5586 holdingbranch => $library2->branchcode,
5587 datelastseen => undef
5591 my $transfer = $builder->build_object(
5593 class => 'Koha::Item::Transfers',
5595 itemnumber => $item->itemnumber,
5596 frombranch => $library2->branchcode,
5597 tobranch => $library1->branchcode,
5598 daterequested => dt_from_string,
5599 datesent => dt_from_string,
5600 datecancelled => undef,
5601 datearrived => undef,
5606 is( ref($transfer), 'Koha::Item::Transfer', 'Mock transfer added' );
5608 my $new_transfer = C4::Circulation::updateWrongTransfer($item->itemnumber, $library1->branchcode);
5609 is(ref($new_transfer), 'Koha::Item::Transfer', "updateWrongTransfer returns a 'Koha::Item::Transfer' object");
5610 ok( !$new_transfer->in_transit, "New transfer is NOT created as in transit (or cancelled)");
5612 my $original_transfer = $transfer->get_from_storage;
5613 ok( defined($original_transfer->datecancelled), "Original transfer was cancelled");
5614 is( $original_transfer->cancellation_reason, 'WrongTransfer', "Original transfer cancellation reason is 'WrongTransfer'");
5617 subtest "SendCirculationAlert" => sub {
5620 # When you would unsuspectingly call this unit test (with perl, not prove), you will be bitten by LOCK.
5621 # LOCK will commit changes and ruin your data
5622 # In order to prevent that, we will add KOHA_TESTING to $ENV; see further Circulation.pm
5623 $ENV{KOHA_TESTING} = 1;
5625 # Setup branch, borrowr, and notice
5626 my $library = $builder->build_object({ class => 'Koha::Libraries' });
5627 set_userenv( $library->unblessed);
5628 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5629 C4::Members::Messaging::SetMessagingPreference({
5630 borrowernumber => $patron->id,
5631 message_transport_types => ['sms'],
5632 message_attribute_id => 5
5634 my $item = $builder->build_sample_item();
5635 my $checkin_notice = $builder->build_object({
5636 class => 'Koha::Notice::Templates',
5638 module => 'circulation',
5640 branchcode => $library->branchcode,
5641 name => 'Test Checkin',
5643 content => "Checkins:\n----\n[% biblio.title %]-[% old_checkout.issue_id %]\n----Thank you.",
5644 message_transport_type => 'sms',
5649 # Checkout an item, mark it returned, generate a notice
5650 my $issue_1 = AddIssue( $patron->unblessed, $item->barcode);
5651 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5652 C4::Circulation::SendCirculationAlert({
5654 item => $item->unblessed,
5655 borrower => $patron->unblessed,
5656 branch => $library->branchcode,
5659 my $notice = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'CHECKIN' });
5660 is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\nThank you.", 'Letter generated with expected output on first checkin' );
5661 is($notice->to_address, $patron->smsalertnumber, "Letter has the correct to_address set to smsalertnumber for SMS type notices");
5663 # Checkout an item, mark it returned, generate a notice
5664 my $issue_2 = AddIssue( $patron->unblessed, $item->barcode);
5665 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5666 C4::Circulation::SendCirculationAlert({
5668 item => $item->unblessed,
5669 borrower => $patron->unblessed,
5670 branch => $library->branchcode,
5673 $notice->discard_changes();
5674 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' );
5678 subtest "GetSoonestRenewDate tests" => sub {
5680 Koha::CirculationRules->set_rule(
5682 categorycode => undef,
5683 branchcode => undef,
5685 rule_name => 'norenewalbefore',
5689 my $patron = $builder->build_object(
5691 class => 'Koha::Patrons',
5693 autorenew_checkouts => 1,
5697 my $item = $builder->build_sample_item();
5698 my $issue = AddIssue( $patron->unblessed, $item->barcode);
5699 my $datedue = dt_from_string( $issue->date_due() );
5702 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
5703 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
5705 GetSoonestRenewDate( $issue ),
5706 $datedue->clone->add( days => -7 ),
5707 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5711 # Test 'date' setting for syspref NoRenewalBeforePrecision
5712 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5714 GetSoonestRenewDate( $issue ),
5715 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
5716 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5720 Koha::CirculationRules->set_rule(
5722 categorycode => undef,
5723 branchcode => undef,
5725 rule_name => 'norenewalbefore',
5726 rule_value => undef,
5731 GetSoonestRenewDate( $issue ),
5733 'Checkouts without auto-renewal can be renewed immediately if no norenewalbefore'
5736 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5737 $issue->auto_renew(1)->store;
5739 GetSoonestRenewDate( $issue ),
5740 $datedue->clone->truncate( to => 'day' ),
5741 'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5743 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact' );
5745 GetSoonestRenewDate( $issue ),
5747 'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5751 subtest "CanBookBeIssued + needsconfirmation message" => sub {
5754 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
5755 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5756 my $biblio = $builder->build_object({ class => 'Koha::Biblios' });
5757 my $biblioitem = $builder->build_object({ class => 'Koha::Biblioitems', value => { biblionumber => $biblio->biblionumber }});
5758 my $item = $builder->build_object({ class => 'Koha::Items' , value => { biblionumber => $biblio->biblionumber }});
5760 my $hold = $builder->build_object({ class => 'Koha::Holds', value => {
5761 biblionumber => $item->biblionumber,
5762 branchcode => $library->branchcode,
5763 itemnumber => undef,
5768 item_group_id => $item->item_group
5771 my ( $error, $needsconfirmation, $alerts, $messages );
5773 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5774 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold exists.");
5776 $hold->priority(0)->store();
5778 $hold->found("W")->store();
5779 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5780 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is waiting.");
5782 $hold->found("T")->store();
5783 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5784 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is being transferred.");
5786 $hold->found("P")->store();
5787 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5788 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is being processed.");
5791 subtest 'Tests for BlockReturnOfWithdrawnItems' => sub {
5795 t::lib::Mocks::mock_preference('BlockReturnOfWithdrawnItems', 1);
5796 my $item = $builder->build_sample_item();
5797 $item->withdrawn(1)->itemlost(1)->store;
5798 my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef );
5801 [ 0, { NotIssued => $item->barcode, withdrawn => 1 }, undef, {} ], "Item returned as withdrawn, no other messages");
5804 $schema->storage->txn_rollback;
5805 C4::Context->clear_syspref_cache();
5806 $branches = Koha::Libraries->search();
5807 for my $branch ( $branches->next ) {
5808 my $key = $branch->branchcode . "_holidays";
5809 $cache->clear_from_cache($key);