3 # This file is part of Koha.
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21 use Test::More tests => 63;
24 use Test::Deep qw( cmp_deeply );
30 use POSIX qw( floor );
32 use t::lib::TestBuilder;
35 use C4::Calendar qw( new insert_single_holiday insert_week_day_holiday delete_holiday );
36 use C4::Circulation qw( AddIssue AddReturn CanBookBeRenewed GetIssuingCharges AddRenewal GetSoonestRenewDate GetLatestAutoRenewDate LostItem GetUpcomingDueIssues CanBookBeIssued AddIssuingCharge MarkIssueReturned ProcessOfflinePayment transferbook updateWrongTransfer );
38 use C4::Items qw( ModItemTransfer );
40 use C4::Reserves qw( AddReserve ModReserve ModReserveCancelAll ModReserveAffect CheckReserves GetOtherReserves );
41 use C4::Overdues qw( CalcFine UpdateFine get_chargeable_units );
42 use C4::Members::Messaging qw( SetMessagingPreference );
43 use Koha::DateUtils qw( dt_from_string output_pref );
46 use Koha::Item::Transfers;
49 use Koha::Patron::Debarments qw( GetDebarments AddDebarment DelUniqueDebarment );
51 use Koha::CirculationRules;
52 use Koha::Subscriptions;
53 use Koha::Account::Lines;
54 use Koha::Account::Offsets;
56 use Koha::Notice::Messages;
57 use Koha::Cache::Memory::Lite;
59 my $builder = t::lib::TestBuilder->new;
62 my $staff = $builder->build_object({ class => "Koha::Patrons" });
63 t::lib::Mocks::mock_userenv({ patron => $staff, branchcode => $library->{branchcode} });
67 my ( $error, $question, $alert ) = @_;
69 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
70 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
71 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
75 sub test_debarment_on_checkout {
77 my $item = $params->{item};
78 my $library = $params->{library};
79 my $patron = $params->{patron};
80 my $due_date = $params->{due_date} || dt_from_string;
81 my $return_date = $params->{return_date} || dt_from_string;
82 my $expected_expiration_date = $params->{expiration_date};
84 $expected_expiration_date = output_pref(
86 dt => $expected_expiration_date,
92 my $line_number = $caller[2];
93 AddIssue( $patron, $item->barcode, $due_date );
95 my ( undef, $message ) = AddReturn( $item->barcode, $library->{branchcode}, undef, $return_date );
96 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
97 or diag('AddReturn returned message ' . Dumper $message );
98 my $debarments = Koha::Patron::Debarments::GetDebarments(
99 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
100 is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
102 is( $debarments->[0]->{expiration},
103 $expected_expiration_date, 'Test at line ' . $line_number );
104 Koha::Patron::Debarments::DelUniqueDebarment(
105 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
108 my $schema = Koha::Database->schema;
109 $schema->storage->txn_begin;
110 my $dbh = C4::Context->dbh;
112 # Prevent random failures by mocking ->now
113 my $now_value = dt_from_string;
114 my $mocked_datetime = Test::MockModule->new('DateTime');
115 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
117 my $cache = Koha::Caches->get_instance();
118 $dbh->do(q|DELETE FROM special_holidays|);
119 $dbh->do(q|DELETE FROM repeatable_holidays|);
120 my $branches = Koha::Libraries->search();
121 for my $branch ( $branches->next ) {
122 my $key = $branch->branchcode . "_holidays";
123 $cache->clear_from_cache($key);
126 # Start with a clean slate
127 $dbh->do('DELETE FROM issues');
128 $dbh->do('DELETE FROM borrowers');
130 # Disable recording of the staff who checked out an item until we're ready for it
131 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 0);
133 my $module = Test::MockModule->new('C4::Context');
135 my $library = $builder->build({
138 my $library2 = $builder->build({
141 my $itemtype = $builder->build(
143 source => 'Itemtype',
147 rentalcharge_daily => 0,
148 defaultreplacecost => undef,
153 my $patron_category = $builder->build(
155 source => 'Category',
157 category_type => 'P',
159 BlockExpiredPatronOpacActions => -1, # Pick the pref value
164 my $CircControl = C4::Context->preference('CircControl');
165 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
168 homebranch => $library2->{branchcode},
169 holdingbranch => $library2->{branchcode}
173 branchcode => $library2->{branchcode}
176 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
178 # No userenv, PickupLibrary
179 t::lib::Mocks::mock_preference('IndependentBranches', '0');
180 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
182 C4::Context->preference('CircControl'),
184 'CircControl changed to PickupLibrary'
187 C4::Circulation::_GetCircControlBranch($item, $borrower),
188 $item->{$HomeOrHoldingBranch},
189 '_GetCircControlBranch returned item branch (no userenv defined)'
192 # No userenv, PatronLibrary
193 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
195 C4::Context->preference('CircControl'),
197 'CircControl changed to PatronLibrary'
200 C4::Circulation::_GetCircControlBranch($item, $borrower),
201 $borrower->{branchcode},
202 '_GetCircControlBranch returned borrower branch'
205 # No userenv, ItemHomeLibrary
206 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
208 C4::Context->preference('CircControl'),
210 'CircControl changed to ItemHomeLibrary'
213 $item->{$HomeOrHoldingBranch},
214 C4::Circulation::_GetCircControlBranch($item, $borrower),
215 '_GetCircControlBranch returned item branch'
219 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
220 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
222 # Userenv set, PickupLibrary
223 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
225 C4::Context->preference('CircControl'),
227 'CircControl changed to PickupLibrary'
230 C4::Circulation::_GetCircControlBranch($item, $borrower),
231 $library2->{branchcode},
232 '_GetCircControlBranch returned current branch'
235 # Userenv set, PatronLibrary
236 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
238 C4::Context->preference('CircControl'),
240 'CircControl changed to PatronLibrary'
243 C4::Circulation::_GetCircControlBranch($item, $borrower),
244 $borrower->{branchcode},
245 '_GetCircControlBranch returned borrower branch'
248 # Userenv set, ItemHomeLibrary
249 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
251 C4::Context->preference('CircControl'),
253 'CircControl changed to ItemHomeLibrary'
256 C4::Circulation::_GetCircControlBranch($item, $borrower),
257 $item->{$HomeOrHoldingBranch},
258 '_GetCircControlBranch returned item branch'
261 # Reset initial configuration
262 t::lib::Mocks::mock_preference('CircControl', $CircControl);
264 C4::Context->preference('CircControl'),
266 'CircControl reset to its initial value'
269 # Set a simple circ policy
270 $dbh->do('DELETE FROM circulation_rules');
271 Koha::CirculationRules->set_rules(
273 categorycode => undef,
277 reservesallowed => 25,
279 lengthunit => 'days',
280 renewalsallowed => 1,
282 norenewalbefore => undef,
290 subtest "CanBookBeRenewed AllowRenewalIfOtherItemsAvailable multiple borrowers and items tests" => sub {
293 #Can only reserve from home branch
294 Koha::CirculationRules->set_rule(
298 rule_name => 'holdallowed',
302 Koha::CirculationRules->set_rule(
305 categorycode => undef,
307 rule_name => 'onshelfholds',
312 # Patrons from three different branches
313 my $patron_borrower = $builder->build_object({ class => 'Koha::Patrons' });
314 my $patron_hold_1 = $builder->build_object({ class => 'Koha::Patrons' });
315 my $patron_hold_2 = $builder->build_object({ class => 'Koha::Patrons' });
316 my $biblio = $builder->build_sample_biblio();
318 # Item at each patron branch
319 my $item_1 = $builder->build_sample_item({
320 biblionumber => $biblio->biblionumber,
321 homebranch => $patron_borrower->branchcode
323 my $item_2 = $builder->build_sample_item({
324 biblionumber => $biblio->biblionumber,
325 homebranch => $patron_hold_2->branchcode
327 my $item_3 = $builder->build_sample_item({
328 biblionumber => $biblio->biblionumber,
329 homebranch => $patron_hold_1->branchcode
332 my $issue = AddIssue( $patron_borrower->unblessed, $item_1->barcode);
333 my $datedue = dt_from_string( $issue->date_due() );
334 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
339 branchcode => $patron_hold_1->branchcode,
340 borrowernumber => $patron_hold_1->borrowernumber,
341 biblionumber => $biblio->biblionumber,
343 reservation_date => dt_from_string(),
344 expiration_date => undef,
351 branchcode => $patron_hold_2->branchcode,
352 borrowernumber => $patron_hold_2->borrowernumber,
353 biblionumber => $biblio->biblionumber,
355 reservation_date => dt_from_string(),
356 expiration_date => undef,
361 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
363 my ( $renewokay, $error ) = CanBookBeRenewed($patron_borrower->borrowernumber, $item_1->itemnumber);
364 is( $renewokay, 0, 'Cannot renew, reserved');
365 is( $error, 'on_reserve', 'Cannot renew, reserved (returned error is on_reserve)');
367 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
369 ( $renewokay, $error ) = CanBookBeRenewed($patron_borrower->borrowernumber, $item_1->itemnumber);
370 is( $renewokay, 1, 'Can renew, two items available for two holds');
371 is( $error, undef, 'Can renew, each reserve has an item');
376 subtest "GetIssuingCharges tests" => sub {
378 my $branch_discount = $builder->build_object({ class => 'Koha::Libraries' });
379 my $branch_no_discount = $builder->build_object({ class => 'Koha::Libraries' });
380 Koha::CirculationRules->set_rule(
382 categorycode => undef,
383 branchcode => $branch_discount->branchcode,
385 rule_name => 'rentaldiscount',
389 my $itype_charge = $builder->build_object({
390 class => 'Koha::ItemTypes',
395 my $itype_no_charge = $builder->build_object({
396 class => 'Koha::ItemTypes',
401 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
402 my $item_1 = $builder->build_sample_item({ itype => $itype_charge->itemtype });
403 my $item_2 = $builder->build_sample_item({ itype => $itype_no_charge->itemtype });
405 t::lib::Mocks::mock_userenv({ branchcode => $branch_no_discount->branchcode });
406 # For now the sub always uses the env branch, this should follow CircControl instead
407 my ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
408 is( $charge + 0, 10.00, "Charge fetched correctly when no discount exists");
409 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
410 is( $charge + 0, 0.00, "Charge fetched correctly when no discount exists and no charge");
412 t::lib::Mocks::mock_userenv({ branchcode => $branch_discount->branchcode });
413 # For now the sub always uses the env branch, this should follow CircControl instead
414 ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
415 is( $charge + 0, 8.50, "Charge fetched correctly when discount exists");
416 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
417 is( $charge + 0, 0.00, "Charge fetched correctly when discount exists and no charge");
421 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
422 subtest "CanBookBeRenewed tests" => sub {
425 C4::Context->set_preference('ItemsDeniedRenewal','');
426 # Generate test biblio
427 my $biblio = $builder->build_sample_biblio();
429 my $branch = $library2->{branchcode};
431 my $item_1 = $builder->build_sample_item(
433 biblionumber => $biblio->biblionumber,
435 replacementprice => 12.00,
439 $reused_itemnumber_1 = $item_1->itemnumber;
441 my $item_2 = $builder->build_sample_item(
443 biblionumber => $biblio->biblionumber,
445 replacementprice => 23.00,
449 $reused_itemnumber_2 = $item_2->itemnumber;
451 my $item_3 = $builder->build_sample_item(
453 biblionumber => $biblio->biblionumber,
455 replacementprice => 23.00,
461 my %renewing_borrower_data = (
463 surname => 'Renewal',
464 categorycode => $patron_category->{categorycode},
465 branchcode => $branch,
468 my %reserving_borrower_data = (
469 firstname => 'Katrin',
470 surname => 'Reservation',
471 categorycode => $patron_category->{categorycode},
472 branchcode => $branch,
475 my %hold_waiting_borrower_data = (
477 surname => 'Reservation',
478 categorycode => $patron_category->{categorycode},
479 branchcode => $branch,
482 my %restricted_borrower_data = (
483 firstname => 'Alice',
484 surname => 'Reservation',
485 categorycode => $patron_category->{categorycode},
486 debarred => '3228-01-01',
487 branchcode => $branch,
490 my %expired_borrower_data = (
493 categorycode => $patron_category->{categorycode},
494 branchcode => $branch,
495 dateexpiry => dt_from_string->subtract( months => 1 ),
498 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
499 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
500 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
501 my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
502 my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
504 my $renewing_borrower_obj = Koha::Patrons->find( $renewing_borrowernumber );
505 my $renewing_borrower = $renewing_borrower_obj->unblessed;
506 my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
507 my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
514 my $checkitem = undef;
517 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
518 my $datedue = dt_from_string( $issue->date_due() );
519 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
521 my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
522 $datedue = dt_from_string( $issue->date_due() );
523 is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
526 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
527 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
529 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
530 is( $renewokay, 1, 'Can renew, no holds for this title or item');
533 # Biblio-level hold, renewal test
536 branchcode => $branch,
537 borrowernumber => $reserving_borrowernumber,
538 biblionumber => $biblio->biblionumber,
539 priority => $priority,
540 reservation_date => $resdate,
541 expiration_date => $expdate,
543 itemnumber => $checkitem,
548 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
549 Koha::CirculationRules->set_rule(
551 categorycode => undef,
554 rule_name => 'onshelfholds',
558 Koha::CirculationRules->set_rule(
560 categorycode => undef,
563 rule_name => 'renewalsallowed',
567 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
568 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
569 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
570 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
571 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
573 # Now let's add an item level hold, we should no longer be able to renew the item
574 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
576 borrowernumber => $hold_waiting_borrowernumber,
577 biblionumber => $biblio->biblionumber,
578 itemnumber => $item_1->itemnumber,
579 branchcode => $branch,
583 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
584 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
587 # 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
588 # be able to renew these items
589 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
591 borrowernumber => $hold_waiting_borrowernumber,
592 biblionumber => $biblio->biblionumber,
593 itemnumber => $item_3->itemnumber,
594 branchcode => $branch,
599 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
600 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
601 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
602 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
603 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
605 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
606 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
607 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
609 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
610 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
611 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
613 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
614 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
615 AddIssue($reserving_borrower, $item_3->barcode);
616 my $reserve = $dbh->selectrow_hashref(
617 'SELECT * FROM old_reserves WHERE reserve_id = ?',
621 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
623 # Item-level hold, renewal test
626 branchcode => $branch,
627 borrowernumber => $reserving_borrowernumber,
628 biblionumber => $biblio->biblionumber,
629 priority => $priority,
630 reservation_date => $resdate,
631 expiration_date => $expdate,
633 itemnumber => $item_1->itemnumber,
638 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
639 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
640 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
642 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
643 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
645 # Items can't fill hold for reasons
646 $item_1->notforloan(1)->store;
647 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
648 is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
649 $item_1->set({notforloan => 0, itype => $itemtype })->store;
651 # FIXME: Add more for itemtype not for loan etc.
653 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
654 my $item_5 = $builder->build_sample_item(
656 biblionumber => $biblio->biblionumber,
658 replacementprice => 23.00,
662 my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
663 is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
665 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
666 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
667 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
668 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
669 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
670 is( $error, 'restriction', "Correct error returned");
672 # Users cannot renew an overdue item
673 my $item_6 = $builder->build_sample_item(
675 biblionumber => $biblio->biblionumber,
677 replacementprice => 23.00,
682 my $item_7 = $builder->build_sample_item(
684 biblionumber => $biblio->biblionumber,
686 replacementprice => 23.00,
691 my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
692 is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
694 my $now = dt_from_string();
695 my $five_weeks = DateTime::Duration->new(weeks => 5);
696 my $five_weeks_ago = $now - $five_weeks;
697 t::lib::Mocks::mock_preference('finesMode', 'production');
699 my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
700 is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
702 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
703 C4::Overdues::UpdateFine(
705 issue_id => $passeddatedue1->id(),
706 itemnumber => $item_7->itemnumber,
707 borrowernumber => $renewing_borrower->{borrowernumber},
709 due => Koha::DateUtils::output_pref($five_weeks_ago)
713 # Make sure fine calculation isn't skipped when adding renewal
714 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
716 my $staff = $builder->build_object({ class => "Koha::Patrons" });
717 t::lib::Mocks::mock_userenv({ patron => $staff });
719 t::lib::Mocks::mock_preference('RenewalLog', 0);
720 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
721 my %params_renewal = (
722 timestamp => { -like => $date . "%" },
723 module => "CIRCULATION",
727 timestamp => { -like => $date . "%" },
728 module => "CIRCULATION",
731 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
732 my $dt = dt_from_string();
733 Time::Fake->offset( $dt->epoch );
734 my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
735 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
736 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
737 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
740 t::lib::Mocks::mock_preference('RenewalLog', 1);
741 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
742 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
743 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
744 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
745 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
747 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
748 is( $fines->count, 2, 'AddRenewal left both fines' );
749 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
750 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
753 t::lib::Mocks::mock_preference('OverduesBlockRenewing','allow');
754 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
755 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
756 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
757 is( $renewokay, 1, '(Bug 8236), Can renew, this item is overdue but not pref does not block');
759 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
760 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
761 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is not overdue but patron has overdues');
762 is( $error, 'overdue', "Correct error returned");
763 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
764 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue so patron has overdues');
765 is( $error, 'overdue', "Correct error returned");
767 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
768 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
769 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
770 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
771 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
772 is( $error, 'overdue', "Correct error returned");
775 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
776 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
777 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
778 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
779 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
780 $new_log_size = Koha::ActionLogs->count( \%params_issue );
781 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
783 $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
786 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
790 # Test automatic renewal before value for "norenewalbefore" in policy is set
791 # In this case automatic renewal is not permitted prior to due date
792 my $item_4 = $builder->build_sample_item(
794 biblionumber => $biblio->biblionumber,
796 replacementprice => 16.00,
801 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
803 ( $renewokay, $error, $info ) =
804 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
805 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
806 is( $error, 'auto_too_soon',
807 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
808 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'" );
811 branchcode => $branch,
812 borrowernumber => $reserving_borrowernumber,
813 biblionumber => $biblio->biblionumber,
814 itemnumber => $bibitems,
815 priority => $priority,
816 reservation_date => $resdate,
817 expiration_date => $expdate,
820 itemnumber => $item_4->itemnumber,
824 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
825 is( $renewokay, 0, 'Still should not be able to renew' );
826 is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' );
827 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, undef, 1 );
828 is( $renewokay, 0, 'Still should not be able to renew' );
829 is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' );
830 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due), "Due date is returned as earliest renewal date when error is 'auto_too_soon'" );
831 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
832 is( $renewokay, 0, 'Still should not be able to renew' );
833 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
834 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1, 1 );
835 is( $renewokay, 0, 'Still should not be able to renew' );
836 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
837 $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
838 Koha::Cache::Memory::Lite->flush();
839 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
840 is( $renewokay, 0, 'Still should not be able to renew' );
841 is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
842 ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
846 $renewing_borrower_obj->autorenew_checkouts(0)->store;
847 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
848 is( $renewokay, 1, 'No renewal before is undef, but patron opted out of auto_renewal' );
849 $renewing_borrower_obj->autorenew_checkouts(1)->store;
853 # Test premature manual renewal
854 Koha::CirculationRules->set_rule(
856 categorycode => undef,
859 rule_name => 'norenewalbefore',
864 ( $renewokay, $error, $info ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
865 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
866 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
867 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
870 # Test premature automatic renewal
871 ( $renewokay, $error, $info ) =
872 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
873 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
874 is( $error, 'auto_too_soon',
875 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
877 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'auto_too_soon'");
879 $renewing_borrower_obj->autorenew_checkouts(0)->store;
880 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
881 is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' );
882 is( $error, 'too_soon', 'Error is too_soon, no auto' );
883 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
884 $renewing_borrower_obj->autorenew_checkouts(1)->store;
886 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
887 # and test automatic renewal again
888 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
889 Koha::Cache::Memory::Lite->flush();
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, "No renewal before" = 0 (returned code is auto_too_soon)'
896 is( $info->{soonest_renew_date}, dt_from_string($issue->date_due), "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 0, 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), "Soonest renew date returned when error is 'auto_too_soon'");
903 $renewing_borrower_obj->autorenew_checkouts(1)->store;
905 # Change policy so that loans can be renewed 99 days prior to the due date
906 # and test automatic renewal again
907 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
908 Koha::Cache::Memory::Lite->flush();
909 ( $renewokay, $error ) =
910 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
911 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
912 is( $error, 'auto_renew',
913 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
916 $renewing_borrower_obj->autorenew_checkouts(0)->store;
917 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
918 is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' );
919 $renewing_borrower_obj->autorenew_checkouts(1)->store;
921 subtest "too_late_renewal / no_auto_renewal_after" => sub {
923 my $item_to_auto_renew = $builder->build_sample_item(
925 biblionumber => $biblio->biblionumber,
930 my $ten_days_before = dt_from_string->add( days => -10 );
931 my $ten_days_ahead = dt_from_string->add( days => 10 );
932 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
934 Koha::CirculationRules->set_rules(
936 categorycode => undef,
940 norenewalbefore => '7',
941 no_auto_renewal_after => '9',
945 ( $renewokay, $error ) =
946 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
947 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
948 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
950 Koha::CirculationRules->set_rules(
952 categorycode => undef,
956 norenewalbefore => '7',
957 no_auto_renewal_after => '10',
961 ( $renewokay, $error ) =
962 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
963 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
964 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
966 Koha::CirculationRules->set_rules(
968 categorycode => undef,
972 norenewalbefore => '7',
973 no_auto_renewal_after => '11',
977 ( $renewokay, $error ) =
978 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
979 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
980 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
982 Koha::CirculationRules->set_rules(
984 categorycode => undef,
988 norenewalbefore => '10',
989 no_auto_renewal_after => '11',
993 ( $renewokay, $error ) =
994 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
995 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
996 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
998 Koha::CirculationRules->set_rules(
1000 categorycode => undef,
1001 branchcode => undef,
1004 norenewalbefore => '10',
1005 no_auto_renewal_after => undef,
1006 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1010 ( $renewokay, $error ) =
1011 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1012 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1013 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1015 Koha::CirculationRules->set_rules(
1017 categorycode => undef,
1018 branchcode => undef,
1021 norenewalbefore => '7',
1022 no_auto_renewal_after => '15',
1023 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1027 ( $renewokay, $error ) =
1028 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1029 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1030 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1032 Koha::CirculationRules->set_rules(
1034 categorycode => undef,
1035 branchcode => undef,
1038 norenewalbefore => '10',
1039 no_auto_renewal_after => undef,
1040 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
1044 ( $renewokay, $error ) =
1045 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1046 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1047 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1050 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
1052 my $item_to_auto_renew = $builder->build_sample_item(
1054 biblionumber => $biblio->biblionumber,
1059 my $ten_days_before = dt_from_string->add( days => -10 );
1060 my $ten_days_ahead = dt_from_string->add( days => 10 );
1061 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1063 Koha::CirculationRules->set_rules(
1065 categorycode => undef,
1066 branchcode => undef,
1069 norenewalbefore => '10',
1070 no_auto_renewal_after => '11',
1074 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
1075 C4::Context->set_preference('OPACFineNoRenewals','10');
1076 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1077 my $fines_amount = 5;
1078 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
1079 $account->add_debit(
1081 amount => $fines_amount,
1082 interface => 'test',
1084 item_id => $item_to_auto_renew->itemnumber,
1085 description => "Some fines"
1087 )->status('RETURNED')->store;
1088 ( $renewokay, $error ) =
1089 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1090 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1091 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
1093 $account->add_debit(
1095 amount => $fines_amount,
1096 interface => 'test',
1098 item_id => $item_to_auto_renew->itemnumber,
1099 description => "Some fines"
1101 )->status('RETURNED')->store;
1102 ( $renewokay, $error ) =
1103 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1104 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1105 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
1107 $account->add_debit(
1109 amount => $fines_amount,
1110 interface => 'test',
1112 item_id => $item_to_auto_renew->itemnumber,
1113 description => "Some fines"
1115 )->status('RETURNED')->store;
1116 ( $renewokay, $error ) =
1117 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1118 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1119 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
1121 $account->add_credit(
1123 amount => $fines_amount,
1124 interface => 'test',
1126 description => "Some payment"
1129 ( $renewokay, $error ) =
1130 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1131 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1132 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1134 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
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, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1140 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
1141 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1144 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
1146 my $item_to_auto_renew = $builder->build_sample_item(
1148 biblionumber => $biblio->biblionumber,
1153 Koha::CirculationRules->set_rules(
1155 categorycode => undef,
1156 branchcode => undef,
1159 norenewalbefore => 10,
1160 no_auto_renewal_after => 11,
1165 my $ten_days_before = dt_from_string->add( days => -10 );
1166 my $ten_days_ahead = dt_from_string->add( days => 10 );
1168 # Patron is expired and BlockExpiredPatronOpacActions=0
1169 # => auto renew is allowed
1170 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
1171 my $patron = $expired_borrower;
1172 my $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1173 ( $renewokay, $error ) =
1174 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1175 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1176 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
1177 Koha::Checkouts->find( $checkout->issue_id )->delete;
1180 # Patron is expired and BlockExpiredPatronOpacActions=1
1181 # => auto renew is not allowed
1182 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1183 $patron = $expired_borrower;
1184 $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1185 ( $renewokay, $error ) =
1186 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1187 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1188 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
1189 Koha::Checkouts->find( $checkout->issue_id )->delete;
1192 # Patron is not expired and BlockExpiredPatronOpacActions=1
1193 # => auto renew is allowed
1194 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1195 $patron = $renewing_borrower;
1196 $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1197 ( $renewokay, $error ) =
1198 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1199 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1200 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1201 Koha::Checkouts->find( $checkout->issue_id )->delete;
1204 subtest "GetLatestAutoRenewDate" => sub {
1206 my $item_to_auto_renew = $builder->build_sample_item(
1208 biblionumber => $biblio->biblionumber,
1213 my $ten_days_before = dt_from_string->add( days => -10 );
1214 my $ten_days_ahead = dt_from_string->add( days => 10 );
1215 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1216 Koha::CirculationRules->set_rules(
1218 categorycode => undef,
1219 branchcode => undef,
1222 norenewalbefore => '7',
1223 no_auto_renewal_after => '',
1224 no_auto_renewal_after_hard_limit => undef,
1228 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1229 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' );
1230 my $five_days_before = dt_from_string->add( days => -5 );
1231 Koha::CirculationRules->set_rules(
1233 categorycode => undef,
1234 branchcode => undef,
1237 norenewalbefore => '10',
1238 no_auto_renewal_after => '5',
1239 no_auto_renewal_after_hard_limit => undef,
1243 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1244 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1245 $five_days_before->truncate( to => 'minute' ),
1246 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1248 my $five_days_ahead = dt_from_string->add( days => 5 );
1249 $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1250 $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1251 $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1252 Koha::Cache::Memory::Lite->flush();
1253 Koha::CirculationRules->set_rules(
1255 categorycode => undef,
1256 branchcode => undef,
1259 norenewalbefore => '10',
1260 no_auto_renewal_after => '15',
1261 no_auto_renewal_after_hard_limit => undef,
1265 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1266 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1267 $five_days_ahead->truncate( to => 'minute' ),
1268 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1270 my $two_days_ahead = dt_from_string->add( days => 2 );
1271 Koha::CirculationRules->set_rules(
1273 categorycode => undef,
1274 branchcode => undef,
1277 norenewalbefore => '10',
1278 no_auto_renewal_after => '',
1279 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1283 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1284 is( $latest_auto_renew_date->truncate( to => 'day' ),
1285 $two_days_ahead->truncate( to => 'day' ),
1286 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1288 Koha::CirculationRules->set_rules(
1290 categorycode => undef,
1291 branchcode => undef,
1294 norenewalbefore => '10',
1295 no_auto_renewal_after => '15',
1296 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1300 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1301 is( $latest_auto_renew_date->truncate( to => 'day' ),
1302 $two_days_ahead->truncate( to => 'day' ),
1303 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1309 # set policy to forbid renewals
1310 Koha::CirculationRules->set_rules(
1312 categorycode => undef,
1313 branchcode => undef,
1316 norenewalbefore => undef,
1317 renewalsallowed => 0,
1322 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1323 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1324 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1326 # Too many unseen renewals
1327 Koha::CirculationRules->set_rules(
1329 categorycode => undef,
1330 branchcode => undef,
1333 unseen_renewals_allowed => 2,
1334 renewalsallowed => 10,
1338 t::lib::Mocks::mock_preference('UnseenRenewals', 1);
1339 $dbh->do('UPDATE issues SET unseen_renewals = 2 where borrowernumber = ? AND itemnumber = ?', undef, ($renewing_borrowernumber, $item_1->itemnumber));
1340 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1341 is( $renewokay, 0, 'Cannot renew, 0 unseen renewals allowed');
1342 is( $error, 'too_unseen', 'Cannot renew, returned code is too_unseen');
1343 Koha::CirculationRules->set_rules(
1345 categorycode => undef,
1346 branchcode => undef,
1349 norenewalbefore => undef,
1350 renewalsallowed => 0,
1354 t::lib::Mocks::mock_preference('UnseenRenewals', 0);
1356 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1357 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1358 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1360 C4::Overdues::UpdateFine(
1362 issue_id => $issue->id(),
1363 itemnumber => $item_1->itemnumber,
1364 borrowernumber => $renewing_borrower->{borrowernumber},
1367 due => Koha::DateUtils::output_pref($datedue)
1371 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
1372 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1373 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1374 is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1375 is( $line->amount+0, 15, 'Account line amount is 15.00' );
1376 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
1378 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1379 is( $offset->type, 'CREATE', 'Account offset type is CREATE' );
1380 is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1382 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1383 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1385 LostItem( $item_1->itemnumber, 'test', 1 );
1387 $line = Koha::Account::Lines->find($line->id);
1388 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1389 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1391 my $item = Koha::Items->find($item_1->itemnumber);
1392 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1393 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1394 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1396 my $total_due = $dbh->selectrow_array(
1397 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1398 undef, $renewing_borrower->{borrowernumber}
1401 is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1403 C4::Context->dbh->do("DELETE FROM accountlines");
1405 C4::Overdues::UpdateFine(
1407 issue_id => $issue2->id(),
1408 itemnumber => $item_2->itemnumber,
1409 borrowernumber => $renewing_borrower->{borrowernumber},
1412 due => Koha::DateUtils::output_pref($datedue)
1416 LostItem( $item_2->itemnumber, 'test', 0 );
1418 my $item2 = Koha::Items->find($item_2->itemnumber);
1419 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1420 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1422 $total_due = $dbh->selectrow_array(
1423 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1424 undef, $renewing_borrower->{borrowernumber}
1427 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1429 my $future = dt_from_string();
1430 $future->add( days => 7 );
1431 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1432 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1434 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1435 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1436 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1437 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1438 LostItem( $item_3->itemnumber, 'test', 0 );
1439 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1440 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1442 $accountline->description,
1443 sprintf( "%s %s %s",
1444 $item_3->biblio->title || '',
1445 $item_3->barcode || '',
1446 $item_3->itemcallnumber || '' ),
1447 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1451 t::lib::Mocks::mock_preference('UseRecalls', 1);
1452 Koha::CirculationRules->set_rules({
1453 categorycode => undef,
1454 branchcode => undef,
1457 recalls_allowed => 10,
1458 renewalsallowed => 5,
1461 my $recall_borrower = $builder->build_object({ class => 'Koha::Patrons' });
1462 my $recall_biblio = $builder->build_object({ class => 'Koha::Biblios' });
1463 my $recall_item1 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $recall_biblio->biblionumber } });
1464 my $recall_item2 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $recall_biblio->biblionumber } });
1466 AddIssue( $renewing_borrower, $recall_item1->barcode );
1468 # item-level and this item: renewal not allowed
1469 my $recall = Koha::Recall->new({
1470 biblio_id => $recall_item1->biblionumber,
1471 item_id => $recall_item1->itemnumber,
1472 patron_id => $recall_borrower->borrowernumber,
1473 pickup_library_id => $recall_borrower->branchcode,
1476 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1477 is( $error, 'recalled', 'Cannot renew item that has been recalled' );
1478 $recall->set_cancelled;
1480 # biblio-level requested recall: renewal not allowed
1481 $recall = Koha::Recall->new({
1482 biblio_id => $recall_item1->biblionumber,
1484 patron_id => $recall_borrower->borrowernumber,
1485 pickup_library_id => $recall_borrower->branchcode,
1488 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1489 is( $error, 'recalled', 'Cannot renew item if biblio is recalled and has no item allocated' );
1490 $recall->set_cancelled;
1492 # item-level and not this item: renewal allowed
1493 $recall = Koha::Recall->new({
1494 biblio_id => $recall_item2->biblionumber,
1495 item_id => $recall_item2->itemnumber,
1496 patron_id => $recall_borrower->borrowernumber,
1497 pickup_library_id => $recall_borrower->branchcode,
1500 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1501 is( $renewokay, 1, 'Can renew item if item-level recall on biblio is not on this item' );
1502 $recall->set_cancelled;
1504 # biblio-level waiting recall: renewal allowed
1505 $recall = Koha::Recall->new({
1506 biblio_id => $recall_item1->biblionumber,
1508 patron_id => $recall_borrower->borrowernumber,
1509 pickup_library_id => $recall_borrower->branchcode,
1512 $recall->set_waiting({ item => $recall_item1 });
1513 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1514 is( $renewokay, 1, 'Can renew item if biblio-level recall has already been allocated an item' );
1515 $recall->set_cancelled;
1518 subtest "GetUpcomingDueIssues" => sub {
1521 my $branch = $library2->{branchcode};
1523 #Create another record
1524 my $biblio2 = $builder->build_sample_biblio();
1527 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1528 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1529 my $item_3 = $builder->build_sample_item(
1531 biblionumber => $biblio2->biblionumber,
1539 my %a_borrower_data = (
1540 firstname => 'Fridolyn',
1541 surname => 'SOMERS',
1542 categorycode => $patron_category->{categorycode},
1543 branchcode => $branch,
1546 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1547 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1549 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1550 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1551 my $today = DateTime->today(time_zone => C4::Context->tz());
1553 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1554 my $datedue = dt_from_string( $issue->date_due() );
1555 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1556 my $datedue2 = dt_from_string( $issue->date_due() );
1560 # GetUpcomingDueIssues tests
1562 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1563 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1566 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1567 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1568 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1571 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1572 is ( scalar( @$upcoming_dues ), 1,
1573 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1576 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1578 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1580 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1581 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1583 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1584 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1586 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1587 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1589 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1590 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1592 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1593 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1595 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1596 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1600 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1601 my $branch = $library2->{branchcode};
1603 my $biblio = $builder->build_sample_biblio();
1606 my $item = $builder->build_sample_item(
1608 biblionumber => $biblio->biblionumber,
1615 my %a_borrower_data = (
1616 firstname => 'Kyle',
1618 categorycode => $patron_category->{categorycode},
1619 branchcode => $branch,
1622 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1624 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1625 my $issue = AddIssue( $borrower, $item->barcode );
1628 issue_id => $issue->id(),
1629 itemnumber => $item->itemnumber,
1630 borrowernumber => $borrowernumber,
1636 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1637 my $count = $hr->{count};
1639 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1642 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1644 my $biblio = $builder->build_sample_biblio();
1645 my $item_1 = $builder->build_sample_item(
1647 biblionumber => $biblio->biblionumber,
1648 library => $library2->{branchcode},
1651 my $item_2= $builder->build_sample_item(
1653 biblionumber => $biblio->biblionumber,
1654 library => $library2->{branchcode},
1655 itype => $item_1->effective_itemtype,
1659 Koha::CirculationRules->set_rules(
1661 categorycode => undef,
1662 itemtype => $item_1->effective_itemtype,
1663 branchcode => undef,
1665 reservesallowed => 25,
1666 holds_per_record => 25,
1668 lengthunit => 'days',
1669 renewalsallowed => 1,
1671 norenewalbefore => undef,
1681 my $borrowernumber1 = Koha::Patron->new({
1682 firstname => 'Kyle',
1684 categorycode => $patron_category->{categorycode},
1685 branchcode => $library2->{branchcode},
1686 })->store->borrowernumber;
1687 my $borrowernumber2 = Koha::Patron->new({
1688 firstname => 'Chelsea',
1690 categorycode => $patron_category->{categorycode},
1691 branchcode => $library2->{branchcode},
1692 })->store->borrowernumber;
1693 my $patron_category_2 = $builder->build(
1695 source => 'Category',
1697 category_type => 'P',
1699 BlockExpiredPatronOpacActions => -1, # Pick the pref value
1703 my $borrowernumber3 = Koha::Patron->new({
1704 firstname => 'Carnegie',
1706 categorycode => $patron_category_2->{categorycode},
1707 branchcode => $library2->{branchcode},
1708 })->store->borrowernumber;
1710 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1711 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1713 my $issue = AddIssue( $borrower1, $item_1->barcode );
1715 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1716 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1720 branchcode => $library2->{branchcode},
1721 borrowernumber => $borrowernumber2,
1722 biblionumber => $biblio->biblionumber,
1727 Koha::CirculationRules->set_rules(
1729 categorycode => undef,
1730 itemtype => $item_1->effective_itemtype,
1731 branchcode => undef,
1737 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1738 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1739 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1741 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1742 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1743 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1745 Koha::CirculationRules->set_rules(
1747 categorycode => undef,
1748 itemtype => $item_1->effective_itemtype,
1749 branchcode => undef,
1755 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1756 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1757 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1759 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1760 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1761 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1765 branchcode => $library2->{branchcode},
1766 borrowernumber => $borrowernumber3,
1767 biblionumber => $biblio->biblionumber,
1772 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1773 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' );
1775 my $item_3= $builder->build_sample_item(
1777 biblionumber => $biblio->biblionumber,
1778 library => $library2->{branchcode},
1779 itype => $item_1->effective_itemtype,
1783 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1784 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' );
1786 Koha::CirculationRules->set_rules(
1788 categorycode => $patron_category_2->{categorycode},
1789 itemtype => $item_1->effective_itemtype,
1790 branchcode => undef,
1792 reservesallowed => 0,
1797 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1798 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' );
1800 Koha::CirculationRules->set_rules(
1802 categorycode => $patron_category_2->{categorycode},
1803 itemtype => $item_1->effective_itemtype,
1804 branchcode => undef,
1806 reservesallowed => 25,
1811 # Setting item not checked out to be not for loan but holdable
1812 $item_2->notforloan(-1)->store;
1814 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1815 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' );
1817 my $mock_circ = Test::MockModule->new("C4::Circulation");
1818 $mock_circ->mock( CanItemBeReserved => sub {
1820 return { status => 'no' }
1823 $item_2->notforloan(0)->store;
1825 # Two items total, one item available, one issued, two holds on record
1828 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1829 } [], "CanItemBeReserved not called when there are more possible holds than available items";
1830 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1832 $item_3 = $builder->build_sample_item(
1834 biblionumber => $biblio->biblionumber,
1835 library => $library2->{branchcode},
1836 itype => $item_1->effective_itemtype,
1840 Koha::CirculationRules->set_rules(
1842 categorycode => undef,
1843 itemtype => $item_1->effective_itemtype,
1844 branchcode => undef,
1846 reservesallowed => 0,
1852 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1853 } ["Checked","Checked"], "CanItemBeReserved only called once per available item if it returns a negative result for all items for a borrower";
1854 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1859 # Don't allow renewing onsite checkout
1860 my $branch = $library->{branchcode};
1862 #Create another record
1863 my $biblio = $builder->build_sample_biblio();
1865 my $item = $builder->build_sample_item(
1867 biblionumber => $biblio->biblionumber,
1873 my $borrowernumber = Koha::Patron->new({
1876 categorycode => $patron_category->{categorycode},
1877 branchcode => $branch,
1878 })->store->borrowernumber;
1880 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1882 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1883 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1884 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1885 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1889 my $library = $builder->build({ source => 'Branch' });
1891 my $biblio = $builder->build_sample_biblio();
1893 my $item = $builder->build_sample_item(
1895 biblionumber => $biblio->biblionumber,
1896 library => $library->{branchcode},
1901 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1903 my $issue = AddIssue( $patron, $item->barcode );
1906 issue_id => $issue->id(),
1907 itemnumber => $item->itemnumber,
1908 borrowernumber => $patron->{borrowernumber},
1915 issue_id => $issue->id(),
1916 itemnumber => $item->itemnumber,
1917 borrowernumber => $patron->{borrowernumber},
1922 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1925 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1928 my $homebranch = $builder->build( { source => 'Branch' } );
1929 my $holdingbranch = $builder->build( { source => 'Branch' } );
1930 my $otherbranch = $builder->build( { source => 'Branch' } );
1931 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1932 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1934 my $item = $builder->build_sample_item(
1936 homebranch => $homebranch->{branchcode},
1937 holdingbranch => $holdingbranch->{branchcode},
1940 Koha::CirculationRules->set_rules(
1942 categorycode => undef,
1943 itemtype => $item->effective_itemtype,
1944 branchcode => undef,
1946 reservesallowed => 25,
1948 lengthunit => 'days',
1949 renewalsallowed => 1,
1951 norenewalbefore => undef,
1960 set_userenv($holdingbranch);
1962 my $issue = AddIssue( $patron_1->unblessed, $item->barcode );
1963 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1965 my ( $error, $question, $alerts );
1967 # AllowReturnToBranch == anywhere
1968 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1969 ## Test that unknown barcodes don't generate internal server errors
1970 set_userenv($homebranch);
1971 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1972 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1973 ## Can be issued from homebranch
1974 set_userenv($homebranch);
1975 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1976 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1977 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1978 ## Can be issued from holdingbranch
1979 set_userenv($holdingbranch);
1980 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1981 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1982 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1983 ## Can be issued from another branch
1984 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1985 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1986 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1988 # AllowReturnToBranch == holdingbranch
1989 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1990 ## Cannot be issued from homebranch
1991 set_userenv($homebranch);
1992 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1993 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1994 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1995 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1996 ## Can be issued from holdinbranch
1997 set_userenv($holdingbranch);
1998 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1999 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2000 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2001 ## Cannot be issued from another branch
2002 set_userenv($otherbranch);
2003 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2004 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2005 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2006 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
2008 # AllowReturnToBranch == homebranch
2009 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2010 ## Can be issued from holdinbranch
2011 set_userenv($homebranch);
2012 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2013 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2014 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2015 ## Cannot be issued from holdinbranch
2016 set_userenv($holdingbranch);
2017 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2018 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2019 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2020 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2021 ## Cannot be issued from holdinbranch
2022 set_userenv($otherbranch);
2023 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2024 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2025 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2026 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2028 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2031 subtest 'AddIssue & AllowReturnToBranch' => sub {
2034 my $homebranch = $builder->build( { source => 'Branch' } );
2035 my $holdingbranch = $builder->build( { source => 'Branch' } );
2036 my $otherbranch = $builder->build( { source => 'Branch' } );
2037 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2038 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2040 my $item = $builder->build_sample_item(
2042 homebranch => $homebranch->{branchcode},
2043 holdingbranch => $holdingbranch->{branchcode},
2047 set_userenv($holdingbranch);
2049 my $ref_issue = 'Koha::Checkout';
2050 my $issue = AddIssue( $patron_1, $item->barcode );
2052 my ( $error, $question, $alerts );
2054 # AllowReturnToBranch == homebranch
2055 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2056 ## Can be issued from homebranch
2057 set_userenv($homebranch);
2058 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
2059 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2060 ## Can be issued from holdinbranch
2061 set_userenv($holdingbranch);
2062 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
2063 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2064 ## Can be issued from another branch
2065 set_userenv($otherbranch);
2066 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
2067 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2069 # AllowReturnToBranch == holdinbranch
2070 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2071 ## Cannot be issued from homebranch
2072 set_userenv($homebranch);
2073 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
2074 ## Can be issued from holdingbranch
2075 set_userenv($holdingbranch);
2076 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
2077 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2078 ## Cannot be issued from another branch
2079 set_userenv($otherbranch);
2080 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
2082 # AllowReturnToBranch == homebranch
2083 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2084 ## Can be issued from homebranch
2085 set_userenv($homebranch);
2086 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
2087 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2088 ## Cannot be issued from holdinbranch
2089 set_userenv($holdingbranch);
2090 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
2091 ## Cannot be issued from another branch
2092 set_userenv($otherbranch);
2093 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
2094 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2097 subtest 'AddIssue | recalls' => sub {
2100 t::lib::Mocks::mock_preference("UseRecalls", 1);
2101 t::lib::Mocks::mock_preference("item-level_itypes", 1);
2102 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2103 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2104 my $item = $builder->build_sample_item;
2105 Koha::CirculationRules->set_rules({
2106 branchcode => undef,
2108 categorycode => undef,
2110 recalls_allowed => 10,
2114 # checking out item that they have recalled
2115 my $recall1 = Koha::Recall->new(
2116 { patron_id => $patron1->borrowernumber,
2117 biblio_id => $item->biblionumber,
2118 item_id => $item->itemnumber,
2120 pickup_library_id => $patron1->branchcode,
2123 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall1->id } );
2124 $recall1 = Koha::Recalls->find( $recall1->id );
2125 is( $recall1->fulfilled, 1, 'Recall was fulfilled when patron checked out item' );
2126 AddReturn( $item->barcode, $item->homebranch );
2128 # this item is has a recall request. cancel recall
2129 my $recall2 = Koha::Recall->new(
2130 { patron_id => $patron2->borrowernumber,
2131 biblio_id => $item->biblionumber,
2132 item_id => $item->itemnumber,
2134 pickup_library_id => $patron2->branchcode,
2137 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall2->id, cancel_recall => 'cancel' } );
2138 $recall2 = Koha::Recalls->find( $recall2->id );
2139 is( $recall2->cancelled, 1, 'Recall was cancelled when patron checked out item' );
2140 AddReturn( $item->barcode, $item->homebranch );
2142 # this item is waiting to fulfill a recall. revert recall
2143 my $recall3 = Koha::Recall->new(
2144 { patron_id => $patron2->borrowernumber,
2145 biblio_id => $item->biblionumber,
2146 item_id => $item->itemnumber,
2148 pickup_library_id => $patron2->branchcode,
2151 $recall3->set_waiting;
2152 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall3->id, cancel_recall => 'revert' } );
2153 $recall3 = Koha::Recalls->find( $recall3->id );
2154 is( $recall3->requested, 1, 'Recall was reverted from waiting when patron checked out item' );
2155 AddReturn( $item->barcode, $item->homebranch );
2158 subtest 'AddIssue & illrequests.due_date' => sub {
2161 t::lib::Mocks::mock_preference( 'ILLModule', 1 );
2162 my $library = $builder->build( { source => 'Branch' } );
2163 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2164 my $item = $builder->build_sample_item();
2166 set_userenv($library);
2168 my $custom_date_due = '9999-12-18 12:34:56';
2169 my $expected_date_due = '9999-12-18 23:59:00';
2170 my $illrequest = Koha::Illrequest->new({
2171 borrowernumber => $patron->borrowernumber,
2172 biblio_id => $item->biblionumber,
2173 branchcode => $library->{'branchcode'},
2174 due_date => $custom_date_due,
2177 my $issue = AddIssue( $patron->unblessed, $item->barcode );
2178 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2180 $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2181 $item = $builder->build_sample_item();
2182 $custom_date_due = '9999-12-19';
2183 $expected_date_due = '9999-12-19 23:59:00';
2184 $illrequest = Koha::Illrequest->new({
2185 borrowernumber => $patron->borrowernumber,
2186 biblio_id => $item->biblionumber,
2187 branchcode => $library->{'branchcode'},
2188 due_date => $custom_date_due,
2191 $issue = AddIssue( $patron->unblessed, $item->barcode );
2192 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2195 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
2198 my $library = $builder->build( { source => 'Branch' } );
2199 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2200 my $item_1 = $builder->build_sample_item(
2202 library => $library->{branchcode},
2205 my $item_2 = $builder->build_sample_item(
2207 library => $library->{branchcode},
2210 Koha::CirculationRules->set_rules(
2212 categorycode => undef,
2214 branchcode => $library->{branchcode},
2216 reservesallowed => 25,
2218 lengthunit => 'days',
2219 renewalsallowed => 1,
2221 norenewalbefore => undef,
2231 my ( $error, $question, $alerts );
2233 # Patron cannot issue item_1, they have overdues
2234 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
2235 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, $yesterday ); # Add an overdue
2237 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
2238 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2239 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
2240 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
2242 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
2243 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2244 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2245 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
2247 # Patron cannot issue item_1, they are debarred
2248 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
2249 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
2250 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2251 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2252 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
2254 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
2255 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2256 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2257 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
2260 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
2263 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2264 my $patron_category_x = $builder->build_object(
2266 class => 'Koha::Patron::Categories',
2267 value => { category_type => 'X' }
2270 my $patron = $builder->build_object(
2272 class => 'Koha::Patrons',
2274 categorycode => $patron_category_x->categorycode,
2275 gonenoaddress => undef,
2282 my $item_1 = $builder->build_sample_item(
2284 library => $library->{branchcode},
2288 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
2289 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
2291 # TODO There are other tests to provide here
2294 subtest 'MultipleReserves' => sub {
2297 my $biblio = $builder->build_sample_biblio();
2299 my $branch = $library2->{branchcode};
2301 my $item_1 = $builder->build_sample_item(
2303 biblionumber => $biblio->biblionumber,
2305 replacementprice => 12.00,
2310 my $item_2 = $builder->build_sample_item(
2312 biblionumber => $biblio->biblionumber,
2314 replacementprice => 12.00,
2321 my $resdate = undef;
2322 my $expdate = undef;
2324 my $checkitem = undef;
2327 my %renewing_borrower_data = (
2328 firstname => 'John',
2329 surname => 'Renewal',
2330 categorycode => $patron_category->{categorycode},
2331 branchcode => $branch,
2333 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
2334 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
2335 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
2336 my $datedue = dt_from_string( $issue->date_due() );
2337 is (defined $issue->date_due(), 1, "item 1 checked out");
2338 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
2340 my %reserving_borrower_data1 = (
2341 firstname => 'Katrin',
2342 surname => 'Reservation',
2343 categorycode => $patron_category->{categorycode},
2344 branchcode => $branch,
2346 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
2349 branchcode => $branch,
2350 borrowernumber => $reserving_borrowernumber1,
2351 biblionumber => $biblio->biblionumber,
2352 priority => $priority,
2353 reservation_date => $resdate,
2354 expiration_date => $expdate,
2356 itemnumber => $checkitem,
2361 my %reserving_borrower_data2 = (
2362 firstname => 'Kirk',
2363 surname => 'Reservation',
2364 categorycode => $patron_category->{categorycode},
2365 branchcode => $branch,
2367 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
2370 branchcode => $branch,
2371 borrowernumber => $reserving_borrowernumber2,
2372 biblionumber => $biblio->biblionumber,
2373 priority => $priority,
2374 reservation_date => $resdate,
2375 expiration_date => $expdate,
2377 itemnumber => $checkitem,
2383 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2384 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2387 my $item_3 = $builder->build_sample_item(
2389 biblionumber => $biblio->biblionumber,
2391 replacementprice => 12.00,
2397 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2398 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2402 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2405 my $library = $builder->build( { source => 'Branch' } );
2406 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2408 my $biblionumber = $builder->build_sample_biblio(
2410 branchcode => $library->{branchcode},
2413 my $item_1 = $builder->build_sample_item(
2415 biblionumber => $biblionumber,
2416 library => $library->{branchcode},
2420 my $item_2 = $builder->build_sample_item(
2422 biblionumber => $biblionumber,
2423 library => $library->{branchcode},
2427 Koha::CirculationRules->set_rules(
2429 categorycode => undef,
2431 branchcode => $library->{branchcode},
2433 reservesallowed => 25,
2435 lengthunit => 'days',
2436 renewalsallowed => 1,
2438 norenewalbefore => undef,
2447 my ( $error, $question, $alerts );
2448 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, dt_from_string->add( days => 1 ) );
2450 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2451 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2453 { error => $error, alerts => $alerts },
2454 { error => {}, alerts => {} },
2455 'No error or alert should be raised'
2457 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2459 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2460 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2462 { error => $error, question => $question, alerts => $alerts },
2463 { error => {}, question => {}, alerts => {} },
2464 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2467 # Add a subscription
2468 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2470 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2471 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2473 { error => $error, question => $question, alerts => $alerts },
2474 { error => {}, question => {}, alerts => {} },
2475 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
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 it is a subscription'
2487 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2490 my $library = $builder->build( { source => 'Branch' } );
2491 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2494 my $biblionumber = $builder->build_sample_biblio(
2496 branchcode => $library->{branchcode},
2499 my $item_1 = $builder->build_sample_item(
2501 biblionumber => $biblionumber,
2502 library => $library->{branchcode},
2505 my $item_2 = $builder->build_sample_item(
2507 biblionumber => $biblionumber,
2508 library => $library->{branchcode},
2512 # And the circulation rule
2513 Koha::CirculationRules->search->delete;
2514 Koha::CirculationRules->set_rules(
2516 categorycode => undef,
2518 branchcode => undef,
2521 firstremind => 1, # 1 day of grace
2522 finedays => 2, # 2 days of fine per day of overdue
2523 lengthunit => 'days',
2528 # Patron cannot issue item_1, they have overdues
2529 my $now = dt_from_string;
2530 my $five_days_ago = $now->clone->subtract( days => 5 );
2531 my $ten_days_ago = $now->clone->subtract( days => 10 );
2532 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2533 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2534 ; # Add another overdue
2536 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2537 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2538 my $debarments = Koha::Patron::Debarments::GetDebarments(
2539 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2540 is( scalar(@$debarments), 1 );
2542 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2543 # Same for the others
2544 my $expected_expiration = output_pref(
2546 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2547 dateformat => 'sql',
2551 is( $debarments->[0]->{expiration}, $expected_expiration );
2553 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2554 $debarments = Koha::Patron::Debarments::GetDebarments(
2555 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2556 is( scalar(@$debarments), 1 );
2557 $expected_expiration = output_pref(
2559 dt => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2560 dateformat => 'sql',
2564 is( $debarments->[0]->{expiration}, $expected_expiration );
2566 Koha::Patron::Debarments::DelUniqueDebarment(
2567 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2569 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2570 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2571 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2572 ; # Add another overdue
2573 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2574 $debarments = Koha::Patron::Debarments::GetDebarments(
2575 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2576 is( scalar(@$debarments), 1 );
2577 $expected_expiration = output_pref(
2579 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2580 dateformat => 'sql',
2584 is( $debarments->[0]->{expiration}, $expected_expiration );
2586 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2587 $debarments = Koha::Patron::Debarments::GetDebarments(
2588 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2589 is( scalar(@$debarments), 1 );
2590 $expected_expiration = output_pref(
2592 dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2593 dateformat => 'sql',
2597 is( $debarments->[0]->{expiration}, $expected_expiration );
2600 subtest 'AddReturn + suspension_chargeperiod' => sub {
2603 my $library = $builder->build( { source => 'Branch' } );
2604 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2606 my $biblionumber = $builder->build_sample_biblio(
2608 branchcode => $library->{branchcode},
2611 my $item_1 = $builder->build_sample_item(
2613 biblionumber => $biblionumber,
2614 library => $library->{branchcode},
2618 # And the issuing rule
2619 Koha::CirculationRules->search->delete;
2620 Koha::CirculationRules->set_rules(
2622 categorycode => '*',
2627 firstremind => 0, # 0 day of grace
2628 finedays => 2, # 2 days of fine per day of overdue
2629 suspension_chargeperiod => 1,
2630 lengthunit => 'days',
2635 my $now = dt_from_string;
2636 my $five_days_ago = $now->clone->subtract( days => 5 );
2637 # We want to charge 2 days every day, without grace
2638 # With 5 days of overdue: 5 * Z
2639 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2640 test_debarment_on_checkout(
2643 library => $library,
2645 due_date => $five_days_ago,
2646 expiration_date => $expected_expiration,
2650 # Same with undef firstremind
2651 Koha::CirculationRules->search->delete;
2652 Koha::CirculationRules->set_rules(
2654 categorycode => '*',
2659 firstremind => undef, # 0 day of grace
2660 finedays => 2, # 2 days of fine per day of overdue
2661 suspension_chargeperiod => 1,
2662 lengthunit => 'days',
2667 my $now = dt_from_string;
2668 my $five_days_ago = $now->clone->subtract( days => 5 );
2669 # We want to charge 2 days every day, without grace
2670 # With 5 days of overdue: 5 * Z
2671 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2672 test_debarment_on_checkout(
2675 library => $library,
2677 due_date => $five_days_ago,
2678 expiration_date => $expected_expiration,
2682 # We want to charge 2 days every 2 days, without grace
2683 # With 5 days of overdue: (5 * 2) / 2
2684 Koha::CirculationRules->set_rule(
2686 categorycode => undef,
2687 branchcode => undef,
2689 rule_name => 'suspension_chargeperiod',
2694 $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2695 test_debarment_on_checkout(
2698 library => $library,
2700 due_date => $five_days_ago,
2701 expiration_date => $expected_expiration,
2705 # We want to charge 2 days every 3 days, with 1 day of grace
2706 # With 5 days of overdue: ((5-1) / 3 ) * 2
2707 Koha::CirculationRules->set_rules(
2709 categorycode => undef,
2710 branchcode => undef,
2713 suspension_chargeperiod => 3,
2718 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2719 test_debarment_on_checkout(
2722 library => $library,
2724 due_date => $five_days_ago,
2725 expiration_date => $expected_expiration,
2729 # Use finesCalendar to know if holiday must be skipped to calculate the due date
2730 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2731 Koha::CirculationRules->set_rules(
2733 categorycode => undef,
2734 branchcode => undef,
2738 suspension_chargeperiod => 1,
2743 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2744 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2746 # Adding a holiday 2 days ago
2747 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2748 my $two_days_ago = $now->clone->subtract( days => 2 );
2749 $calendar->insert_single_holiday(
2750 day => $two_days_ago->day,
2751 month => $two_days_ago->month,
2752 year => $two_days_ago->year,
2753 title => 'holidayTest-2d',
2754 description => 'holidayDesc 2 days ago'
2756 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2757 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2758 test_debarment_on_checkout(
2761 library => $library,
2763 due_date => $five_days_ago,
2764 expiration_date => $expected_expiration,
2768 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2769 my $two_days_ahead = $now->clone->add( days => 2 );
2770 $calendar->insert_single_holiday(
2771 day => $two_days_ahead->day,
2772 month => $two_days_ahead->month,
2773 year => $two_days_ahead->year,
2774 title => 'holidayTest+2d',
2775 description => 'holidayDesc 2 days ahead'
2778 # Same as above, but we should skip D+2
2779 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2780 test_debarment_on_checkout(
2783 library => $library,
2785 due_date => $five_days_ago,
2786 expiration_date => $expected_expiration,
2790 # Adding another holiday, day of expiration date
2791 my $expected_expiration_dt = dt_from_string($expected_expiration);
2792 $calendar->insert_single_holiday(
2793 day => $expected_expiration_dt->day,
2794 month => $expected_expiration_dt->month,
2795 year => $expected_expiration_dt->year,
2796 title => 'holidayTest_exp',
2797 description => 'holidayDesc on expiration date'
2799 # Expiration date will be the day after
2800 test_debarment_on_checkout(
2803 library => $library,
2805 due_date => $five_days_ago,
2806 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2810 test_debarment_on_checkout(
2813 library => $library,
2815 return_date => $now->clone->add(days => 5),
2816 expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2820 test_debarment_on_checkout(
2823 library => $library,
2825 due_date => $now->clone->add(days => 1),
2826 return_date => $now->clone->add(days => 5),
2827 expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2833 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2836 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2837 my $patron1 = $builder->build_object(
2839 class => 'Koha::Patrons',
2841 library => $library->branchcode,
2842 categorycode => $patron_category->{categorycode}
2846 my $patron2 = $builder->build_object(
2848 class => 'Koha::Patrons',
2850 library => $library->branchcode,
2851 categorycode => $patron_category->{categorycode}
2856 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2858 my $item = $builder->build_sample_item(
2860 library => $library->branchcode,
2864 my ( $error, $question, $alerts );
2865 my $issue = AddIssue( $patron1->unblessed, $item->barcode );
2867 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2868 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2869 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' );
2871 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2872 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2873 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' );
2875 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2879 subtest 'AddReturn | is_overdue' => sub {
2882 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2883 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2884 t::lib::Mocks::mock_preference('finesMode', 'production');
2885 t::lib::Mocks::mock_preference('MaxFine', '100');
2887 my $library = $builder->build( { source => 'Branch' } );
2888 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2889 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2890 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2892 my $item = $builder->build_sample_item(
2894 library => $library->{branchcode},
2895 replacementprice => 7
2899 Koha::CirculationRules->search->delete;
2900 Koha::CirculationRules->set_rules(
2902 categorycode => undef,
2904 branchcode => undef,
2907 lengthunit => 'days',
2908 fine => 1, # Charge 1 every day of overdue
2914 my $now = dt_from_string;
2915 my $one_day_ago = $now->clone->subtract( days => 1 );
2916 my $two_days_ago = $now->clone->subtract( days => 2 );
2917 my $five_days_ago = $now->clone->subtract( days => 5 );
2918 my $ten_days_ago = $now->clone->subtract( days => 10 );
2919 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2921 # No return date specified, today will be used => 10 days overdue charged
2922 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2923 AddReturn( $item->barcode, $library->{branchcode} );
2924 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2925 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2927 # specify return date 5 days before => no overdue charged
2928 AddIssue( $patron->unblessed, $item->barcode, $five_days_ago ); # date due was 5d ago
2929 AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
2930 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2931 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2933 # specify return date 5 days later => 5 days overdue charged
2934 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2935 AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
2936 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2937 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2939 # specify return date 5 days later, specify exemptfine => no overdue charge
2940 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2941 AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago );
2942 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2943 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2945 subtest 'bug 22877 | Lost item return' => sub {
2949 my $issue = AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2951 # Fake fines cronjob on this checkout
2953 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2954 $ten_days_ago, $now );
2957 issue_id => $issue->issue_id,
2958 itemnumber => $item->itemnumber,
2959 borrowernumber => $patron->borrowernumber,
2961 due => output_pref($ten_days_ago)
2964 is( int( $patron->account->balance() ),
2965 10, "Overdue fine of 10 days overdue" );
2967 # Fake longoverdue with charge and not marking returned
2968 LostItem( $item->itemnumber, 'cronjob', 0 );
2969 is( int( $patron->account->balance() ),
2970 17, "Lost fine of 7 plus 10 days overdue" );
2972 # Now we return it today
2973 AddReturn( $item->barcode, $library->{branchcode} );
2974 is( int( $patron->account->balance() ),
2975 17, "Should have a single 10 days overdue fine and lost charge" );
2978 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2981 subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
2985 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2987 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
2989 # Fake fines cronjob on this checkout
2991 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2992 $one_day_ago, $now );
2995 issue_id => $issue->issue_id,
2996 itemnumber => $item->itemnumber,
2997 borrowernumber => $patron->borrowernumber,
2999 due => output_pref($one_day_ago)
3002 is( int( $patron->account->balance() ),
3003 1, "Overdue fine of 1 day overdue" );
3005 # Backdated return (dropbox mode example - charge should be removed)
3006 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3007 is( int( $patron->account->balance() ),
3008 0, "Overdue fine should be annulled" );
3009 my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3010 is( $lines->count, 0, "Overdue fine accountline has been removed");
3012 $issue = AddIssue( $patron->unblessed, $item->barcode, $two_days_ago ); # date due was 2d ago
3014 # Fake fines cronjob on this checkout
3016 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3017 $two_days_ago, $now );
3020 issue_id => $issue->issue_id,
3021 itemnumber => $item->itemnumber,
3022 borrowernumber => $patron->borrowernumber,
3024 due => output_pref($one_day_ago)
3027 is( int( $patron->account->balance() ),
3028 2, "Overdue fine of 2 days overdue" );
3030 # Payment made against fine
3031 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3032 my $debit = $lines->next;
3033 my $credit = $patron->account->add_credit(
3037 interface => 'test',
3040 $credit->apply( { debits => [$debit] } );
3042 is( int( $patron->account->balance() ),
3043 0, "Overdue fine should be paid off" );
3044 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3045 is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
3046 my $line = $lines->next;
3047 is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
3048 is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
3050 # Backdated return (dropbox mode example - charge should be removed)
3051 AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
3052 is( int( $patron->account->balance() ),
3053 -1, "Refund credit has been applied" );
3054 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
3055 is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
3057 $line = $lines->next;
3058 is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
3059 is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
3060 is($line->status,'RETURNED', "Overdue fine is fixed");
3061 $line = $lines->next;
3062 is($line->amount+0,-2, "Original payment amount remains as 2");
3063 is($line->amountoutstanding+0,0, "Original payment remains applied");
3064 $line = $lines->next;
3065 is($line->amount+0,-1, "Refund amount correctly set to 1");
3066 is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
3069 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3072 subtest 'bug 25417 | backdated return + exemptfine' => sub {
3076 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3078 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
3080 # Fake fines cronjob on this checkout
3082 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3083 $one_day_ago, $now );
3086 issue_id => $issue->issue_id,
3087 itemnumber => $item->itemnumber,
3088 borrowernumber => $patron->borrowernumber,
3090 due => output_pref($one_day_ago)
3093 is( int( $patron->account->balance() ),
3094 1, "Overdue fine of 1 day overdue" );
3096 # Backdated return (dropbox mode example - charge should no longer exist)
3097 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3098 is( int( $patron->account->balance() ),
3099 0, "Overdue fine should be annulled" );
3102 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3105 subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
3108 t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
3110 my $due_date = dt_from_string;
3111 my $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
3116 issue_id => $issue->issue_id,
3117 itemnumber => $item->itemnumber,
3118 borrowernumber => $patron->borrowernumber,
3120 due => output_pref($due_date)
3123 is( $patron->account->balance(),
3124 0.25, 'Overdue fine of $0.25 recorded' );
3126 # Backdate return to exact due date and time
3127 my ( undef, $message ) =
3128 AddReturn( $item->barcode, $library->{branchcode},
3132 Koha::Account::Lines->find( { issue_id => $issue->id } );
3133 ok( !$accountline, 'accountline removed as expected' );
3136 $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
3141 issue_id => $issue->issue_id,
3142 itemnumber => $item->itemnumber,
3143 borrowernumber => $patron->borrowernumber,
3145 due => output_pref($due_date)
3148 is( $patron->account->balance(),
3149 0.25, 'Overdue fine of $0.25 recorded' );
3151 # Partial pay accruing fine
3152 my $lines = Koha::Account::Lines->search(
3154 borrowernumber => $patron->borrowernumber,
3155 issue_id => $issue->id
3158 my $debit = $lines->next;
3159 my $credit = $patron->account->add_credit(
3163 interface => 'test',
3166 $credit->apply( { debits => [$debit] } );
3168 is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
3170 # Backdate return to exact due date and time
3171 ( undef, $message ) =
3172 AddReturn( $item->barcode, $library->{branchcode},
3175 $lines = Koha::Account::Lines->search(
3177 borrowernumber => $patron->borrowernumber,
3178 issue_id => $issue->id
3181 $accountline = $lines->next;
3182 is( $accountline->amountoutstanding + 0,
3183 0, 'Partially paid fee amount outstanding was reduced to 0' );
3184 is( $accountline->amount + 0,
3185 0, 'Partially paid fee amount was reduced to 0' );
3186 is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
3189 Koha::Account::Lines->search(
3190 { borrowernumber => $patron->borrowernumber } )->delete;
3193 subtest 'enh 23091 | Lost item return policies' => sub {
3196 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3198 my $branchcode_false =
3199 $builder->build( { source => 'Branch' } )->{branchcode};
3200 my $specific_rule_false = $builder->build(
3202 source => 'CirculationRule',
3204 branchcode => $branchcode_false,
3205 categorycode => undef,
3207 rule_name => 'lostreturn',
3212 my $branchcode_refund =
3213 $builder->build( { source => 'Branch' } )->{branchcode};
3214 my $specific_rule_refund = $builder->build(
3216 source => 'CirculationRule',
3218 branchcode => $branchcode_refund,
3219 categorycode => undef,
3221 rule_name => 'lostreturn',
3222 rule_value => 'refund'
3226 my $branchcode_restore =
3227 $builder->build( { source => 'Branch' } )->{branchcode};
3228 my $specific_rule_restore = $builder->build(
3230 source => 'CirculationRule',
3232 branchcode => $branchcode_restore,
3233 categorycode => undef,
3235 rule_name => 'lostreturn',
3236 rule_value => 'restore'
3240 my $branchcode_charge =
3241 $builder->build( { source => 'Branch' } )->{branchcode};
3242 my $specific_rule_charge = $builder->build(
3244 source => 'CirculationRule',
3246 branchcode => $branchcode_charge,
3247 categorycode => undef,
3249 rule_name => 'lostreturn',
3250 rule_value => 'charge'
3255 my $replacement_amount = 99.00;
3256 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
3257 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
3258 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
3259 t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 );
3260 t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
3262 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
3265 subtest 'lostreturn | false' => sub {
3268 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
3270 my $item = $builder->build_sample_item(
3272 replacementprice => $replacement_amount
3277 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3279 # Fake fines cronjob on this checkout
3281 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3282 $ten_days_ago, $now );
3285 issue_id => $issue->issue_id,
3286 itemnumber => $item->itemnumber,
3287 borrowernumber => $patron->borrowernumber,
3289 due => output_pref($ten_days_ago)
3292 my $overdue_fees = Koha::Account::Lines->search(
3294 borrowernumber => $patron->id,
3295 itemnumber => $item->itemnumber,
3296 debit_type_code => 'OVERDUE'
3299 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3300 my $overdue_fee = $overdue_fees->next;
3301 is( $overdue_fee->amount + 0,
3302 10, 'The right OVERDUE amount is generated' );
3303 is( $overdue_fee->amountoutstanding + 0,
3305 'The right OVERDUE amountoutstanding is generated' );
3307 # Simulate item marked as lost
3308 $item->itemlost(3)->store;
3309 C4::Circulation::LostItem( $item->itemnumber, 1 );
3311 my $lost_fee_lines = Koha::Account::Lines->search(
3313 borrowernumber => $patron->id,
3314 itemnumber => $item->itemnumber,
3315 debit_type_code => 'LOST'
3318 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3319 my $lost_fee_line = $lost_fee_lines->next;
3320 is( $lost_fee_line->amount + 0,
3321 $replacement_amount, 'The right LOST amount is generated' );
3322 is( $lost_fee_line->amountoutstanding + 0,
3323 $replacement_amount,
3324 'The right LOST amountoutstanding is generated' );
3325 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3328 my ( $returned, $message ) =
3329 AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
3331 $overdue_fee->discard_changes;
3332 is( $overdue_fee->amount + 0,
3333 10, 'The OVERDUE amount is left intact' );
3334 is( $overdue_fee->amountoutstanding + 0,
3336 'The OVERDUE amountoutstanding is left intact' );
3338 $lost_fee_line->discard_changes;
3339 is( $lost_fee_line->amount + 0,
3340 $replacement_amount, 'The LOST amount is left intact' );
3341 is( $lost_fee_line->amountoutstanding + 0,
3342 $replacement_amount,
3343 'The LOST amountoutstanding is left intact' );
3344 # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
3345 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3348 subtest 'lostreturn | refund' => sub {
3351 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
3353 my $item = $builder->build_sample_item(
3355 replacementprice => $replacement_amount
3360 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3362 # Fake fines cronjob on this checkout
3364 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3365 $ten_days_ago, $now );
3368 issue_id => $issue->issue_id,
3369 itemnumber => $item->itemnumber,
3370 borrowernumber => $patron->borrowernumber,
3372 due => output_pref($ten_days_ago)
3375 my $overdue_fees = Koha::Account::Lines->search(
3377 borrowernumber => $patron->id,
3378 itemnumber => $item->itemnumber,
3379 debit_type_code => 'OVERDUE'
3382 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3383 my $overdue_fee = $overdue_fees->next;
3384 is( $overdue_fee->amount + 0,
3385 10, 'The right OVERDUE amount is generated' );
3386 is( $overdue_fee->amountoutstanding + 0,
3388 'The right OVERDUE amountoutstanding is generated' );
3390 # Simulate item marked as lost
3391 $item->itemlost(3)->store;
3392 C4::Circulation::LostItem( $item->itemnumber, 1 );
3394 my $lost_fee_lines = Koha::Account::Lines->search(
3396 borrowernumber => $patron->id,
3397 itemnumber => $item->itemnumber,
3398 debit_type_code => 'LOST'
3401 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3402 my $lost_fee_line = $lost_fee_lines->next;
3403 is( $lost_fee_line->amount + 0,
3404 $replacement_amount, 'The right LOST amount is generated' );
3405 is( $lost_fee_line->amountoutstanding + 0,
3406 $replacement_amount,
3407 'The right LOST amountoutstanding is generated' );
3408 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3410 # Return the lost item
3411 my ( undef, $message ) =
3412 AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
3414 $overdue_fee->discard_changes;
3415 is( $overdue_fee->amount + 0,
3416 10, 'The OVERDUE amount is left intact' );
3417 is( $overdue_fee->amountoutstanding + 0,
3419 'The OVERDUE amountoutstanding is left intact' );
3421 $lost_fee_line->discard_changes;
3422 is( $lost_fee_line->amount + 0,
3423 $replacement_amount, 'The LOST amount is left intact' );
3424 is( $lost_fee_line->amountoutstanding + 0,
3426 'The LOST amountoutstanding is refunded' );
3427 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3430 subtest 'lostreturn | restore' => sub {
3433 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
3435 my $item = $builder->build_sample_item(
3437 replacementprice => $replacement_amount
3442 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode , $ten_days_ago);
3444 # Fake fines cronjob on this checkout
3446 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3447 $ten_days_ago, $now );
3450 issue_id => $issue->issue_id,
3451 itemnumber => $item->itemnumber,
3452 borrowernumber => $patron->borrowernumber,
3454 due => output_pref($ten_days_ago)
3457 my $overdue_fees = Koha::Account::Lines->search(
3459 borrowernumber => $patron->id,
3460 itemnumber => $item->itemnumber,
3461 debit_type_code => 'OVERDUE'
3464 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3465 my $overdue_fee = $overdue_fees->next;
3466 is( $overdue_fee->amount + 0,
3467 10, 'The right OVERDUE amount is generated' );
3468 is( $overdue_fee->amountoutstanding + 0,
3470 'The right OVERDUE amountoutstanding is generated' );
3472 # Simulate item marked as lost
3473 $item->itemlost(3)->store;
3474 C4::Circulation::LostItem( $item->itemnumber, 1 );
3476 my $lost_fee_lines = Koha::Account::Lines->search(
3478 borrowernumber => $patron->id,
3479 itemnumber => $item->itemnumber,
3480 debit_type_code => 'LOST'
3483 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3484 my $lost_fee_line = $lost_fee_lines->next;
3485 is( $lost_fee_line->amount + 0,
3486 $replacement_amount, 'The right LOST amount is generated' );
3487 is( $lost_fee_line->amountoutstanding + 0,
3488 $replacement_amount,
3489 'The right LOST amountoutstanding is generated' );
3490 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3492 # Simulate refunding overdue fees upon marking item as lost
3493 my $overdue_forgive = $patron->account->add_credit(
3496 user_id => $manager->borrowernumber,
3497 library_id => $branchcode_restore,
3498 interface => 'test',
3500 item_id => $item->itemnumber
3503 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3504 $overdue_fee->discard_changes;
3505 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3508 my ( undef, $message ) =
3509 AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
3511 $overdue_fee->discard_changes;
3512 is( $overdue_fee->amount + 0,
3513 10, 'The OVERDUE amount is left intact' );
3514 is( $overdue_fee->amountoutstanding + 0,
3516 'The OVERDUE amountoutstanding is restored' );
3518 $lost_fee_line->discard_changes;
3519 is( $lost_fee_line->amount + 0,
3520 $replacement_amount, 'The LOST amount is left intact' );
3521 is( $lost_fee_line->amountoutstanding + 0,
3523 'The LOST amountoutstanding is refunded' );
3524 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3527 subtest 'lostreturn | charge' => sub {
3530 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
3532 my $item = $builder->build_sample_item(
3534 replacementprice => $replacement_amount
3539 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3541 # Fake fines cronjob on this checkout
3543 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3544 $ten_days_ago, $now );
3547 issue_id => $issue->issue_id,
3548 itemnumber => $item->itemnumber,
3549 borrowernumber => $patron->borrowernumber,
3551 due => output_pref($ten_days_ago)
3554 my $overdue_fees = Koha::Account::Lines->search(
3556 borrowernumber => $patron->id,
3557 itemnumber => $item->itemnumber,
3558 debit_type_code => 'OVERDUE'
3561 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3562 my $overdue_fee = $overdue_fees->next;
3563 is( $overdue_fee->amount + 0,
3564 10, 'The right OVERDUE amount is generated' );
3565 is( $overdue_fee->amountoutstanding + 0,
3567 'The right OVERDUE amountoutstanding is generated' );
3569 # Simulate item marked as lost
3570 $item->itemlost(3)->store;
3571 C4::Circulation::LostItem( $item->itemnumber, 1 );
3573 my $lost_fee_lines = Koha::Account::Lines->search(
3575 borrowernumber => $patron->id,
3576 itemnumber => $item->itemnumber,
3577 debit_type_code => 'LOST'
3580 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3581 my $lost_fee_line = $lost_fee_lines->next;
3582 is( $lost_fee_line->amount + 0,
3583 $replacement_amount, 'The right LOST amount is generated' );
3584 is( $lost_fee_line->amountoutstanding + 0,
3585 $replacement_amount,
3586 'The right LOST amountoutstanding is generated' );
3587 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3589 # Simulate refunding overdue fees upon marking item as lost
3590 my $overdue_forgive = $patron->account->add_credit(
3593 user_id => $manager->borrowernumber,
3594 library_id => $branchcode_charge,
3595 interface => 'test',
3597 item_id => $item->itemnumber
3600 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3601 $overdue_fee->discard_changes;
3602 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3605 my ( undef, $message ) =
3606 AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
3608 $lost_fee_line->discard_changes;
3609 is( $lost_fee_line->amount + 0,
3610 $replacement_amount, 'The LOST amount is left intact' );
3611 is( $lost_fee_line->amountoutstanding + 0,
3613 'The LOST amountoutstanding is refunded' );
3614 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3616 $overdue_fees = Koha::Account::Lines->search(
3618 borrowernumber => $patron->id,
3619 itemnumber => $item->itemnumber,
3620 debit_type_code => 'OVERDUE'
3623 order_by => { '-asc' => 'accountlines_id'}
3626 is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
3627 $overdue_fee = $overdue_fees->next;
3628 is( $overdue_fee->amount + 0,
3629 10, 'The original OVERDUE amount is left intact' );
3630 is( $overdue_fee->amountoutstanding + 0,
3632 'The original OVERDUE amountoutstanding is left as forgiven' );
3633 $overdue_fee = $overdue_fees->next;
3634 is( $overdue_fee->amount + 0,
3635 5, 'The new OVERDUE amount is correct for the backdated return' );
3636 is( $overdue_fee->amountoutstanding + 0,
3638 'The new OVERDUE amountoutstanding is correct for the backdated return' );
3643 subtest '_FixOverduesOnReturn' => sub {
3646 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3647 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3649 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3651 my $branchcode = $library2->{branchcode};
3653 my $item = $builder->build_sample_item(
3655 biblionumber => $biblio->biblionumber,
3656 library => $branchcode,
3657 replacementprice => 99.00,
3662 my $patron = $builder->build( { source => 'Borrower' } );
3664 ## Start with basic call, should just close out the open fine
3665 my $accountline = Koha::Account::Line->new(
3667 borrowernumber => $patron->{borrowernumber},
3668 debit_type_code => 'OVERDUE',
3669 status => 'UNRETURNED',
3670 itemnumber => $item->itemnumber,
3672 amountoutstanding => 99.00,
3673 interface => 'test',
3677 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
3679 $accountline->_result()->discard_changes();
3681 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
3682 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3683 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3685 ## Run again, with exemptfine enabled
3688 debit_type_code => 'OVERDUE',
3689 status => 'UNRETURNED',
3690 amountoutstanding => 99.00,
3694 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3696 $accountline->_result()->discard_changes();
3697 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'APPLY' })->next();
3699 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
3700 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3701 is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
3702 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
3703 is( $offset->amount + 0, -99, "Amount of offset is correct" );
3704 my $credit = $offset->credit;
3705 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
3706 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
3707 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
3709 # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
3712 debit_type_code => 'OVERDUE',
3713 status => 'UNRETURNED',
3714 amountoutstanding => 0.00,
3719 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3721 $accountline->_result()->discard_changes();
3722 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'CREATE' })->next();
3723 is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
3724 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3725 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3728 subtest 'Set waiting flag' => sub {
3731 my $library_1 = $builder->build( { source => 'Branch' } );
3732 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3733 my $library_2 = $builder->build( { source => 'Branch' } );
3734 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3736 my $item = $builder->build_sample_item(
3738 library => $library_1->{branchcode},
3742 set_userenv( $library_2 );
3743 my $reserve_id = AddReserve(
3745 branchcode => $library_2->{branchcode},
3746 borrowernumber => $patron_2->{borrowernumber},
3747 biblionumber => $item->biblionumber,
3749 itemnumber => $item->itemnumber,
3753 set_userenv( $library_1 );
3754 my $do_transfer = 1;
3755 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3756 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3757 my $hold = Koha::Holds->find( $reserve_id );
3758 is( $hold->found, 'T', 'Hold is in transit' );
3760 my ( $status ) = CheckReserves($item->itemnumber);
3761 is( $status, 'Transferred', 'Hold is not waiting yet');
3763 set_userenv( $library_2 );
3765 AddReturn( $item->barcode, $library_2->{branchcode} );
3766 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3767 $hold = Koha::Holds->find( $reserve_id );
3768 is( $hold->found, 'W', 'Hold is waiting' );
3769 ( $status ) = CheckReserves($item->itemnumber);
3770 is( $status, 'Waiting', 'Now the hold is waiting');
3772 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
3773 set_userenv( $library_1 );
3774 (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
3775 $hold = Koha::Holds->find( $reserve_id );
3776 is( $hold->found, undef, 'Hold is no longer marked waiting' );
3777 is( $hold->priority, 1, "Hold is now priority one again");
3778 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
3779 is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
3780 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
3781 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
3782 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
3785 subtest 'Cancel transfers on lost items' => sub {
3788 my $library_to = $builder->build_object( { class => 'Koha::Libraries' } );
3789 my $item = $builder->build_sample_item();
3790 my $holdingbranch = $item->holdingbranch;
3791 # Historic transfer (datearrived is defined)
3792 my $old_transfer = $builder->build_object(
3794 class => 'Koha::Item::Transfers',
3796 itemnumber => $item->itemnumber,
3797 frombranch => $holdingbranch,
3798 tobranch => $library_to->branchcode,
3800 datesent => \'NOW()',
3801 datearrived => \'NOW()',
3802 datecancelled => undef,
3803 daterequested => \'NOW()'
3807 # Queued transfer (datesent is undefined)
3808 my $transfer_1 = $builder->build_object(
3810 class => 'Koha::Item::Transfers',
3812 itemnumber => $item->itemnumber,
3813 frombranch => $holdingbranch,
3814 tobranch => $library_to->branchcode,
3817 datearrived => undef,
3818 datecancelled => undef,
3819 daterequested => \'NOW()'
3823 # In transit transfer (datesent is defined, datearrived and datecancelled are both undefined)
3824 my $transfer_2 = $builder->build_object(
3826 class => 'Koha::Item::Transfers',
3828 itemnumber => $item->itemnumber,
3829 frombranch => $holdingbranch,
3830 tobranch => $library_to->branchcode,
3832 datesent => \'NOW()',
3833 datearrived => undef,
3834 datecancelled => undef,
3835 daterequested => \'NOW()'
3840 # Simulate item being marked as lost
3841 $item->itemlost(1)->store;
3842 LostItem( $item->itemnumber, 'test', 1 );
3844 $transfer_1->discard_changes;
3845 isnt($transfer_1->datecancelled, undef, "Queud transfer was cancelled upon item lost");
3846 is($transfer_1->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
3847 $transfer_2->discard_changes;
3848 isnt($transfer_2->datecancelled, undef, "Active transfer was cancelled upon item lost");
3849 is($transfer_2->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
3850 $old_transfer->discard_changes;
3851 is($old_transfer->datecancelled, undef, "Old transfers are unaffected");
3852 $item->discard_changes;
3853 is($item->holdingbranch, $holdingbranch, "Items holding branch remains unchanged");
3856 subtest 'CanBookBeIssued | is_overdue' => sub {
3859 # Set a simple circ policy
3860 Koha::CirculationRules->set_rules(
3862 categorycode => undef,
3863 branchcode => undef,
3867 reservesallowed => 25,
3869 lengthunit => 'days',
3870 renewalsallowed => 1,
3872 norenewalbefore => undef,
3880 my $now = dt_from_string()->truncate( to => 'day' );
3881 my $five_days_go = $now->clone->add( days => 5 );
3882 my $ten_days_go = $now->clone->add( days => 10);
3883 my $library = $builder->build( { source => 'Branch' } );
3884 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
3886 my $item = $builder->build_sample_item(
3888 library => $library->{branchcode},
3892 my $issue = AddIssue( $patron->unblessed, $item->barcode, $five_days_go ); # date due was 10d ago
3893 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
3894 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), output_pref({ str => $five_days_go, dateonly => 1}), "First issue works");
3895 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->barcode,$ten_days_go, undef, undef, undef);
3896 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
3897 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
3900 subtest 'ItemsDeniedRenewal preference' => sub {
3903 C4::Context->set_preference('ItemsDeniedRenewal','');
3905 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
3906 Koha::CirculationRules->set_rules(
3908 categorycode => '*',
3910 branchcode => $idr_lib->branchcode,
3912 reservesallowed => 25,
3914 lengthunit => 'days',
3915 renewalsallowed => 10,
3917 norenewalbefore => undef,
3925 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
3926 homebranch => $idr_lib->branchcode,
3930 itemcallnumber => undef,
3934 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
3935 homebranch => $idr_lib->branchcode,
3938 location => 'NOPROC'
3942 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
3943 branchcode => $idr_lib->branchcode,
3946 my $future = dt_from_string->add( days => 1 );
3947 my $deny_issue = $builder->build_object(
3949 class => 'Koha::Checkouts',
3951 returndate => undef,
3952 renewals_count => 0,
3954 borrowernumber => $idr_borrower->borrowernumber,
3955 itemnumber => $deny_book->itemnumber,
3956 onsite_checkout => 0,
3957 date_due => $future,
3961 my $allow_issue = $builder->build_object(
3963 class => 'Koha::Checkouts',
3965 returndate => undef,
3966 renewals_count => 0,
3968 borrowernumber => $idr_borrower->borrowernumber,
3969 itemnumber => $allow_book->itemnumber,
3970 onsite_checkout => 0,
3971 date_due => $future,
3978 my ( $idr_mayrenew, $idr_error ) =
3979 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3980 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3981 is( $idr_error, undef, 'Renewal allowed when no rules' );
3983 $idr_rules="withdrawn: [1]";
3985 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3986 ( $idr_mayrenew, $idr_error ) =
3987 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3988 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3989 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3990 ( $idr_mayrenew, $idr_error ) =
3991 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3992 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3993 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3995 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
3997 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3998 ( $idr_mayrenew, $idr_error ) =
3999 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4000 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
4001 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
4002 ( $idr_mayrenew, $idr_error ) =
4003 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
4004 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
4005 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
4007 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
4009 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4010 ( $idr_mayrenew, $idr_error ) =
4011 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4012 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
4013 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
4014 ( $idr_mayrenew, $idr_error ) =
4015 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
4016 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
4017 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
4019 $idr_rules="itemcallnumber: [NULL]";
4020 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4021 ( $idr_mayrenew, $idr_error ) =
4022 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4023 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
4024 $idr_rules="itemcallnumber: ['']";
4025 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4026 ( $idr_mayrenew, $idr_error ) =
4027 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4028 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
4030 $idr_rules="itemnotes: [NULL]";
4031 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4032 ( $idr_mayrenew, $idr_error ) =
4033 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4034 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
4035 $idr_rules="itemnotes: ['']";
4036 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
4037 ( $idr_mayrenew, $idr_error ) =
4038 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
4039 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
4042 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
4045 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4046 my $library = $builder->build( { source => 'Branch' } );
4047 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4049 my $item = $builder->build_sample_item(
4051 library => $library->{branchcode},
4055 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4056 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4057 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4060 subtest 'CanBookBeIssued | notforloan' => sub {
4063 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
4065 my $library = $builder->build( { source => 'Branch' } );
4066 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4068 my $itemtype = $builder->build(
4070 source => 'Itemtype',
4071 value => { notforloan => undef, }
4074 my $item = $builder->build_sample_item(
4076 library => $library->{branchcode},
4077 itype => $itemtype->{itemtype},
4080 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4082 my ( $issuingimpossible, $needsconfirmation );
4085 subtest 'item-level_itypes = 1' => sub {
4088 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
4089 # Is for loan at item type and item level
4090 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4091 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4092 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4094 # not for loan at item type level
4095 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4096 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4097 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4100 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4101 'Item can not be issued, not for loan at item type level'
4104 # not for loan at item level
4105 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4106 $item->notforloan( 1 )->store;
4107 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4108 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4111 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4112 'Item can not be issued, not for loan at item type level'
4116 subtest 'item-level_itypes = 0' => sub {
4119 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4121 # We set another itemtype for biblioitem
4122 my $itemtype = $builder->build(
4124 source => 'Itemtype',
4125 value => { notforloan => undef, }
4129 # for loan at item type and item level
4130 $item->notforloan(0)->store;
4131 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4132 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4133 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4134 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4136 # not for loan at item type level
4137 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4138 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4139 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4142 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4143 'Item can not be issued, not for loan at item type level'
4146 # not for loan at item level
4147 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4148 $item->notforloan( 1 )->store;
4149 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4150 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4153 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4154 'Item can not be issued, not for loan at item type level'
4158 # TODO test with AllowNotForLoanOverride = 1
4161 subtest 'CanBookBeIssued | recalls' => sub {
4164 t::lib::Mocks::mock_preference("UseRecalls", 1);
4165 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4166 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4167 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4168 my $item = $builder->build_sample_item;
4169 Koha::CirculationRules->set_rules({
4170 branchcode => undef,
4172 categorycode => undef,
4174 recalls_allowed => 10,
4179 my $recall = Koha::Recall->new(
4180 { patron_id => $patron1->borrowernumber,
4181 biblio_id => $item->biblionumber,
4182 item_id => $item->itemnumber,
4184 pickup_library_id => $patron1->branchcode,
4188 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4189 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed an item-level recall on this item" );
4191 $recall->set_cancelled;
4193 # biblio-level recall
4194 $recall = Koha::Recall->new(
4195 { patron_id => $patron1->borrowernumber,
4196 biblio_id => $item->biblionumber,
4199 pickup_library_id => $patron1->branchcode,
4203 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4204 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed a biblio-level recall and this item is eligible to fill it" );
4206 $recall->set_cancelled;
4208 # biblio-level recall
4209 $recall = Koha::Recall->new(
4210 { patron_id => $patron1->borrowernumber,
4211 biblio_id => $item->biblionumber,
4214 pickup_library_id => $patron1->branchcode,
4217 $recall->set_waiting( { item => $item, expirationdate => dt_from_string() } );
4219 my ( undef, undef, undef, $messages ) = CanBookBeIssued( $patron1, $item->barcode, undef, undef, undef, undef );
4220 is( $messages->{RECALLED}, $recall->id, "This book can be issued by this patron and they have placed a recall" );
4222 $recall->set_cancelled;
4225 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
4228 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
4229 my $item = $builder->build_sample_item(
4231 onloan => '2018-01-01',
4235 AddReturn( $item->barcode, $item->homebranch );
4236 $item->discard_changes; # refresh
4237 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
4240 subtest 'AddReturn | recalls' => sub {
4243 t::lib::Mocks::mock_preference("UseRecalls", 1);
4244 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4245 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4246 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4247 my $item1 = $builder->build_sample_item;
4248 Koha::CirculationRules->set_rules({
4249 branchcode => undef,
4251 categorycode => undef,
4253 recalls_allowed => 10,
4257 # this item can fill a recall with pickup at this branch
4258 AddIssue( $patron1->unblessed, $item1->barcode );
4259 my $recall1 = Koha::Recall->new(
4260 { patron_id => $patron2->borrowernumber,
4261 biblio_id => $item1->biblionumber,
4262 item_id => $item1->itemnumber,
4264 pickup_library_id => $item1->homebranch,
4267 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4268 is( $messages->{RecallFound}->id, $recall1->id, "Recall found" );
4269 $recall1->set_cancelled;
4271 # this item can fill a recall but needs transfer
4272 AddIssue( $patron1->unblessed, $item1->barcode );
4273 $recall1 = Koha::Recall->new(
4274 { patron_id => $patron2->borrowernumber,
4275 biblio_id => $item1->biblionumber,
4276 item_id => $item1->itemnumber,
4278 pickup_library_id => $patron2->branchcode,
4281 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4282 is( $messages->{RecallNeedsTransfer}, $item1->homebranch, "Recall requiring transfer found" );
4283 $recall1->set_cancelled;
4285 # this item is already in transit, do not ask to transfer
4286 AddIssue( $patron1->unblessed, $item1->barcode );
4287 $recall1 = Koha::Recall->new(
4288 { patron_id => $patron2->borrowernumber,
4289 biblio_id => $item1->biblionumber,
4290 item_id => $item1->itemnumber,
4292 pickup_library_id => $patron2->branchcode,
4295 $recall1->start_transfer;
4296 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $patron2->branchcode );
4297 is( $messages->{TransferredRecall}->id, $recall1->id, "In transit recall found" );
4298 $recall1->set_cancelled;
4301 subtest 'AddReturn | bundles' => sub {
4304 my $schema = Koha::Database->schema;
4305 $schema->storage->txn_begin;
4307 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4308 my $host_item1 = $builder->build_sample_item;
4309 my $bundle_item1 = $builder->build_sample_item;
4310 $schema->resultset('ItemBundle')
4312 { host => $host_item1->itemnumber, item => $bundle_item1->itemnumber } );
4314 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $bundle_item1->barcode, $bundle_item1->homebranch );
4315 is($messages->{InBundle}->id, $host_item1->id, 'AddReturn returns InBundle host item when item is part of a bundle');
4317 $schema->storage->txn_rollback;
4320 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
4325 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4327 my $issuing_charges = 15;
4328 my $title = 'A title';
4329 my $author = 'Author, An';
4330 my $barcode = 'WHATARETHEODDS';
4332 my $circ = Test::MockModule->new('C4::Circulation');
4334 'GetIssuingCharges',
4336 return $issuing_charges;
4340 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4341 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
4342 my $patron = $builder->build_object({
4343 class => 'Koha::Patrons',
4344 value => { branchcode => $library->id }
4347 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
4348 my $item_id = Koha::Item->new(
4350 biblionumber => $biblio->biblionumber,
4351 homebranch => $library->id,
4352 holdingbranch => $library->id,
4353 barcode => $barcode,
4354 replacementprice => 23.00,
4355 itype => $itemtype->id
4357 )->store->itemnumber;
4358 my $item = Koha::Items->find( $item_id );
4360 my $context = Test::MockModule->new('C4::Context');
4361 $context->mock( userenv => { branch => $library->id } );
4363 # Check the item out
4364 AddIssue( $patron->unblessed, $item->barcode );
4367 AddRenewal( $patron->borrowernumber, $item->itemnumber, $library->id, undef, {break=>"the_renewal"} );
4368 } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
4370 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
4371 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
4372 my %params_renewal = (
4373 timestamp => { -like => $date . "%" },
4374 module => "CIRCULATION",
4375 action => "RENEWAL",
4377 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
4378 AddRenewal( $patron->id, $item->id, $library->id );
4379 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4380 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
4382 my $checkouts = $patron->checkouts;
4383 # The following will fail if run on 00:00:00
4384 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
4386 my $lines = Koha::Account::Lines->search({
4387 borrowernumber => $patron->id,
4388 itemnumber => $item->id
4391 is( $lines->count, 2 );
4393 my $line = $lines->next;
4394 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
4395 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
4396 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
4398 $line = $lines->next;
4399 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
4400 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
4401 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
4403 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
4405 $context = Test::MockModule->new('C4::Context');
4406 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
4408 my $now = dt_from_string;
4409 $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
4410 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
4411 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
4412 $sth->execute($item->id, $library->id);
4413 my ($old_stats_size) = $sth->fetchrow_array;
4414 AddRenewal( $patron->id, $item->id, $library->id );
4415 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4416 $sth->execute($item->id, $library->id);
4417 my ($new_stats_size) = $sth->fetchrow_array;
4418 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
4419 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
4421 AddReturn( $item->id, $library->id, undef, $date );
4422 AddIssue( $patron->unblessed, $item->barcode, $now );
4423 AddRenewal( $patron->id, $item->id, $library->id, undef, undef, 1 );
4424 my $lines_skipped = Koha::Account::Lines->search({
4425 borrowernumber => $patron->id,
4426 itemnumber => $item->id
4428 is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
4432 subtest 'AddRenewal() adds to renewals' => sub {
4435 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4436 my $patron = $builder->build_object({
4437 class => 'Koha::Patrons',
4438 value => { branchcode => $library->id }
4441 my $item = $builder->build_sample_item();
4443 set_userenv( $library->unblessed );
4445 # Check the item out
4446 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4447 is(ref($issue), 'Koha::Checkout', 'Issue added');
4450 my $duedate = AddRenewal( $patron->id, $item->id, $library->id );
4452 ok( $duedate, "Renewal added" );
4454 my $renewals = Koha::Checkouts::Renewals->search({ checkout_id => $issue->issue_id });
4455 is($renewals->count, 1, 'One renewal added');
4456 my $THE_renewal = $renewals->next;
4457 is( $THE_renewal->renewer_id, C4::Context->userenv->{'number'}, 'Renewer recorded from context' );
4460 subtest 'ProcessOfflinePayment() tests' => sub {
4467 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
4468 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4469 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
4471 is( $result, 'Success.', 'The right string is returned' );
4473 my $lines = $patron->account->lines;
4474 is( $lines->count, 1, 'line created correctly');
4476 my $line = $lines->next;
4477 is( $line->amount+0, $amount * -1, 'amount picked from params' );
4478 is( $line->branchcode, $library->id, 'branchcode set correctly' );
4482 subtest 'Incremented fee tests' => sub {
4485 my $dt = dt_from_string();
4486 Time::Fake->offset( $dt->epoch );
4488 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
4491 $builder->build_object( { class => 'Koha::Libraries' } )->store;
4493 $module->mock( 'userenv', sub { { branch => $library->id } } );
4495 my $patron = $builder->build_object(
4497 class => 'Koha::Patrons',
4498 value => { categorycode => $patron_category->{categorycode} }
4502 my $itemtype = $builder->build_object(
4504 class => 'Koha::ItemTypes',
4506 notforloan => undef,
4508 rentalcharge_daily => 1,
4509 rentalcharge_daily_calendar => 0
4514 my $item = $builder->build_sample_item(
4516 library => $library->{branchcode},
4517 itype => $itemtype->id,
4521 is( $itemtype->rentalcharge_daily+0,
4522 1, 'Daily rental charge stored and retreived correctly' );
4523 is( $item->effective_itemtype, $itemtype->id,
4524 "Itemtype set correctly for item" );
4526 my $now = dt_from_string;
4527 my $dt_from = $now->clone;
4528 my $dt_to = $now->clone->add( days => 7 );
4529 my $dt_to_renew = $now->clone->add( days => 13 );
4533 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4534 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4535 is( $accountline->amount+0, 7,
4536 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
4538 $accountline->delete();
4539 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4540 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4541 is( $accountline->amount+0, 6,
4542 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
4544 $accountline->delete();
4547 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
4548 $itemtype->rentalcharge_daily_calendar(1)->store();
4550 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4551 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4552 is( $accountline->amount+0, 7,
4553 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
4555 $accountline->delete();
4556 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4557 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4558 is( $accountline->amount+0, 6,
4559 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
4561 $accountline->delete();
4564 my $calendar = C4::Calendar->new( branchcode => $library->id );
4565 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
4567 ( $dt_from->day_of_week == 6 ) ? 0
4568 : ( $dt_from->day_of_week == 7 ) ? 1
4569 : $dt_from->day_of_week + 1;
4570 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
4571 $calendar->insert_week_day_holiday(
4572 weekday => $closed_day,
4573 title => 'Test holiday',
4574 description => 'Test holiday'
4577 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4578 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4579 is( $accountline->amount+0, 6,
4580 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
4582 $accountline->delete();
4583 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4584 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4585 is( $accountline->amount+0, 5,
4586 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
4588 $accountline->delete();
4591 $itemtype->rentalcharge(2)->store;
4592 is( $itemtype->rentalcharge+0, 2,
4593 'Rental charge updated and retreived correctly' );
4595 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4597 Koha::Account::Lines->search( { itemnumber => $item->id } );
4598 is( $accountlines->count, '2',
4599 "Fixed charge and accrued charge recorded distinctly" );
4600 $accountlines->delete();
4601 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4602 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
4603 is( $accountlines->count, '2',
4604 "Fixed charge and accrued charge recorded distinctly, for renewal" );
4605 $accountlines->delete();
4607 $itemtype->rentalcharge(0)->store;
4608 is( $itemtype->rentalcharge+0, 0,
4609 'Rental charge reset and retreived correctly' );
4612 Koha::CirculationRules->set_rule(
4614 categorycode => $patron->categorycode,
4615 itemtype => $itemtype->id,
4616 branchcode => $library->id,
4617 rule_name => 'lengthunit',
4618 rule_value => 'hours',
4622 $itemtype->rentalcharge_hourly('0.25')->store();
4623 is( $itemtype->rentalcharge_hourly,
4624 '0.25', 'Hourly rental charge stored and retreived correctly' );
4626 $dt_to = $now->clone->add( hours => 168 );
4627 $dt_to_renew = $now->clone->add( hours => 312 );
4629 $itemtype->rentalcharge_hourly_calendar(0)->store();
4631 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4632 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4633 is( $accountline->amount + 0, 42,
4634 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)" );
4635 $accountline->delete();
4636 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4637 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4638 is( $accountline->amount + 0, 36,
4639 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)" );
4640 $accountline->delete();
4643 $itemtype->rentalcharge_hourly_calendar(1)->store();
4645 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4646 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4647 is( $accountline->amount + 0, 36,
4648 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)" );
4649 $accountline->delete();
4650 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4651 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4652 is( $accountline->amount + 0, 30,
4653 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
4654 $accountline->delete();
4657 $calendar->delete_holiday( weekday => $closed_day );
4659 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4660 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4661 is( $accountline->amount + 0, 42,
4662 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u" );
4663 $accountline->delete();
4664 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4665 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4666 is( $accountline->amount + 0, 36,
4667 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)" );
4668 $accountline->delete();
4673 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
4676 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
4677 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4680 $builder->build_object( { class => 'Koha::Libraries' } )->store;
4681 my $patron = $builder->build_object(
4683 class => 'Koha::Patrons',
4684 value => { categorycode => $patron_category->{categorycode} }
4688 my $itemtype = $builder->build_object(
4690 class => 'Koha::ItemTypes',
4694 rentalcharge_daily => 0
4699 my $item = $builder->build_sample_item(
4701 library => $library->id,
4705 itype => $itemtype->id,
4709 my ( $issuingimpossible, $needsconfirmation );
4710 my $dt_from = dt_from_string();
4711 my $dt_due = $dt_from->clone->add( days => 3 );
4713 $itemtype->rentalcharge(1)->store;
4714 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4715 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
4716 $itemtype->rentalcharge('0')->store;
4717 $itemtype->rentalcharge_daily(1)->store;
4718 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4719 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
4720 $itemtype->rentalcharge_daily('0')->store;
4723 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
4726 t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
4728 my $patron = $builder->build_object(
4730 class => 'Koha::Patrons',
4731 value => { categorycode => $patron_category->{categorycode} }
4735 my $item = $builder->build_sample_item(
4737 materials => 'includes DVD',
4741 my $dt_due = dt_from_string->add( days => 3 );
4743 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4744 is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
4747 subtest 'Do not return on renewal (LOST charge)' => sub {
4750 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
4751 my $library = $builder->build_object( { class => "Koha::Libraries" } );
4752 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
4753 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
4755 my $biblio = $builder->build_sample_biblio;
4757 my $item = $builder->build_sample_item(
4759 biblionumber => $biblio->biblionumber,
4760 library => $library->branchcode,
4761 replacementprice => 99.00,
4766 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
4767 AddIssue( $patron->unblessed, $item->barcode );
4769 my $accountline = Koha::Account::Line->new(
4771 borrowernumber => $patron->borrowernumber,
4772 debit_type_code => 'LOST',
4774 itemnumber => $item->itemnumber,
4776 amountoutstanding => 12,
4777 interface => 'something',
4781 # AddRenewal doesn't call _FixAccountForLostAndFound
4782 AddIssue( $patron->unblessed, $item->barcode );
4784 is( $patron->checkouts->count, 1,
4785 'Renewal should not return the item even if a LOST payment has been made earlier'
4789 subtest 'Filling a hold should cancel existing transfer' => sub {
4792 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
4794 my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
4795 my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
4796 my $patron = $builder->build_object(
4798 class => 'Koha::Patrons',
4800 categorycode => $patron_category->{categorycode},
4801 branchcode => $libraryA->branchcode,
4806 my $item = $builder->build_sample_item({
4807 homebranch => $libraryB->branchcode,
4810 my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4811 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
4813 branchcode => $libraryA->branchcode,
4814 borrowernumber => $patron->borrowernumber,
4815 biblionumber => $item->biblionumber,
4816 itemnumber => $item->itemnumber
4818 my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
4819 is( $reserves->count, 1, "Reserve is placed");
4820 ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4821 my $reserve = $reserves->next;
4822 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
4823 $reserve->discard_changes;
4824 ok( $reserve->found eq 'W', "Reserve is marked waiting" );
4825 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
4828 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
4832 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4833 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4834 my $patron = $builder->build_object(
4836 class => 'Koha::Patrons',
4837 value => { categorycode => $patron_category->{categorycode} }
4841 my $biblionumber = $builder->build_sample_biblio(
4843 branchcode => $library->branchcode,
4847 # And the circulation rule
4848 Koha::CirculationRules->search->delete;
4849 Koha::CirculationRules->set_rules(
4851 categorycode => undef,
4853 branchcode => undef,
4856 lengthunit => 'days',
4862 source => 'CirculationRule',
4864 branchcode => undef,
4865 categorycode => undef,
4867 rule_name => 'lostreturn',
4868 rule_value => 'refund'
4873 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4876 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4877 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4879 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4881 my $item = $builder->build_sample_item(
4883 biblionumber => $biblionumber,
4884 library => $library->branchcode,
4885 replacementprice => '42',
4888 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4889 LostItem( $item->itemnumber, 'cli', 0 );
4890 $item->_result->itemlost(1);
4891 $item->_result->itemlost_on( $lost_on );
4892 $item->_result->update();
4894 my $a = Koha::Account::Lines->search(
4896 itemnumber => $item->id,
4897 borrowernumber => $patron->borrowernumber
4900 ok( $a, "Found accountline for lost fee" );
4901 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4902 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4903 $a = $a->get_from_storage;
4904 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4908 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4911 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4912 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4914 my $lost_on = dt_from_string->subtract( days => 6 )->date;
4916 my $item = $builder->build_sample_item(
4918 biblionumber => $biblionumber,
4919 library => $library->branchcode,
4920 replacementprice => '42',
4923 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4924 LostItem( $item->itemnumber, 'cli', 0 );
4925 $item->_result->itemlost(1);
4926 $item->_result->itemlost_on( $lost_on );
4927 $item->_result->update();
4929 my $a = Koha::Account::Lines->search(
4931 itemnumber => $item->id,
4932 borrowernumber => $patron->borrowernumber
4935 ok( $a, "Found accountline for lost fee" );
4936 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4937 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4938 $a = $a->get_from_storage;
4939 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4943 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4946 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4947 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4949 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4951 my $item = $builder->build_sample_item(
4953 biblionumber => $biblionumber,
4954 library => $library->branchcode,
4955 replacementprice => '42',
4958 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4959 LostItem( $item->itemnumber, 'cli', 0 );
4960 $item->_result->itemlost(1);
4961 $item->_result->itemlost_on( $lost_on );
4962 $item->_result->update();
4964 my $a = Koha::Account::Lines->search(
4966 itemnumber => $item->id,
4967 borrowernumber => $patron->borrowernumber
4970 ok( $a, "Found accountline for lost fee" );
4971 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4972 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4973 $a = $a->get_from_storage;
4974 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4978 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4981 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4982 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4984 my $lost_on = dt_from_string->subtract( days => 8 )->date;
4986 my $item = $builder->build_sample_item(
4988 biblionumber => $biblionumber,
4989 library => $library->branchcode,
4990 replacementprice => '42',
4993 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4994 LostItem( $item->itemnumber, 'cli', 0 );
4995 $item->_result->itemlost(1);
4996 $item->_result->itemlost_on( $lost_on );
4997 $item->_result->update();
4999 my $a = Koha::Account::Lines->search(
5001 itemnumber => $item->id,
5002 borrowernumber => $patron->borrowernumber
5006 ok( $a, "Found accountline for lost fee" );
5007 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5008 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5009 $a = $a->get_from_storage;
5010 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5015 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
5019 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
5020 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5021 my $patron = $builder->build_object(
5023 class => 'Koha::Patrons',
5024 value => { categorycode => $patron_category->{categorycode} }
5027 my $patron2 = $builder->build_object(
5029 class => 'Koha::Patrons',
5030 value => { categorycode => $patron_category->{categorycode} }
5034 my $biblionumber = $builder->build_sample_biblio(
5036 branchcode => $library->branchcode,
5040 # And the circulation rule
5041 Koha::CirculationRules->search->delete;
5042 Koha::CirculationRules->set_rules(
5044 categorycode => undef,
5046 branchcode => undef,
5049 lengthunit => 'days',
5055 source => 'CirculationRule',
5057 branchcode => undef,
5058 categorycode => undef,
5060 rule_name => 'lostreturn',
5061 rule_value => 'refund'
5066 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5069 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5070 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5072 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5074 my $item = $builder->build_sample_item(
5076 biblionumber => $biblionumber,
5077 library => $library->branchcode,
5078 replacementprice => '42',
5081 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5082 LostItem( $item->itemnumber, 'cli', 0 );
5083 $item->_result->itemlost(1);
5084 $item->_result->itemlost_on( $lost_on );
5085 $item->_result->update();
5087 my $a = Koha::Account::Lines->search(
5089 itemnumber => $item->id,
5090 borrowernumber => $patron->borrowernumber
5093 ok( $a, "Found accountline for lost fee" );
5094 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5095 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5096 $a = $a->get_from_storage;
5097 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5102 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5105 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5106 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5108 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5110 my $item = $builder->build_sample_item(
5112 biblionumber => $biblionumber,
5113 library => $library->branchcode,
5114 replacementprice => '42',
5117 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5118 LostItem( $item->itemnumber, 'cli', 0 );
5119 $item->_result->itemlost(1);
5120 $item->_result->itemlost_on( $lost_on );
5121 $item->_result->update();
5123 my $a = Koha::Account::Lines->search(
5125 itemnumber => $item->id,
5126 borrowernumber => $patron->borrowernumber
5129 ok( $a, "Found accountline for lost fee" );
5130 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5131 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5132 $a = $a->get_from_storage;
5133 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5137 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5140 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5141 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5143 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5145 my $item = $builder->build_sample_item(
5147 biblionumber => $biblionumber,
5148 library => $library->branchcode,
5149 replacementprice => '42',
5152 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5153 LostItem( $item->itemnumber, 'cli', 0 );
5154 $item->_result->itemlost(1);
5155 $item->_result->itemlost_on( $lost_on );
5156 $item->_result->update();
5158 my $a = Koha::Account::Lines->search(
5160 itemnumber => $item->id,
5161 borrowernumber => $patron->borrowernumber
5164 ok( $a, "Found accountline for lost fee" );
5165 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5166 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5167 $a = $a->get_from_storage;
5168 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5172 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5175 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5176 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5178 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5180 my $item = $builder->build_sample_item(
5182 biblionumber => $biblionumber,
5183 library => $library->branchcode,
5184 replacementprice => '42',
5187 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5188 LostItem( $item->itemnumber, 'cli', 0 );
5189 $item->_result->itemlost(1);
5190 $item->_result->itemlost_on( $lost_on );
5191 $item->_result->update();
5193 my $a = Koha::Account::Lines->search(
5195 itemnumber => $item->id,
5196 borrowernumber => $patron->borrowernumber
5200 ok( $a, "Found accountline for lost fee" );
5201 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5202 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5203 $a = $a->get_from_storage;
5204 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5209 subtest 'transferbook tests' => sub {
5213 { C4::Circulation::transferbook({}); }
5214 'Koha::Exceptions::MissingParameter',
5215 'Koha::Patron->store raises an exception on missing params';
5218 { C4::Circulation::transferbook({to_branch=>'anything'}); }
5219 'Koha::Exceptions::MissingParameter',
5220 'Koha::Patron->store raises an exception on missing params';
5223 { C4::Circulation::transferbook({from_branch=>'anything'}); }
5224 'Koha::Exceptions::MissingParameter',
5225 'Koha::Patron->store raises an exception on missing params';
5227 my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
5228 is( $doreturn, 0, "No return without barcode");
5229 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5230 is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
5232 ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
5233 is( $doreturn, 0, "No return without barcode");
5234 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5235 is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
5239 subtest 'Checkout should correctly terminate a transfer' => sub {
5242 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5243 my $patron_1 = $builder->build_object(
5245 class => 'Koha::Patrons',
5246 value => { branchcode => $library_1->branchcode }
5249 my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
5250 my $patron_2 = $builder->build_object(
5252 class => 'Koha::Patrons',
5253 value => { branchcode => $library_2->branchcode }
5257 my $item = $builder->build_sample_item(
5259 library => $library_1->branchcode,
5263 t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
5264 my $reserve_id = AddReserve(
5266 branchcode => $library_2->branchcode,
5267 borrowernumber => $patron_2->borrowernumber,
5268 biblionumber => $item->biblionumber,
5269 itemnumber => $item->itemnumber,
5274 my $do_transfer = 1;
5275 ModItemTransfer( $item->itemnumber, $library_1->branchcode,
5276 $library_2->branchcode, 'Manual' );
5277 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
5278 GetOtherReserves( $item->itemnumber )
5279 ; # To put the Reason, it's what does returns.pl...
5280 my $hold = Koha::Holds->find($reserve_id);
5281 is( $hold->found, 'T', 'Hold is in transit' );
5282 my $transfer = $item->get_transfer;
5283 is( $transfer->frombranch, $library_1->branchcode );
5284 is( $transfer->tobranch, $library_2->branchcode );
5285 is( $transfer->reason, 'Reserve' );
5287 t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
5288 AddIssue( $patron_1->unblessed, $item->barcode );
5289 $transfer = $transfer->get_from_storage;
5290 isnt( $transfer->datearrived, undef );
5291 $hold = $hold->get_from_storage;
5292 is( $hold->found, undef, 'Hold is waiting' );
5293 is( $hold->priority, 1, );
5296 subtest 'AddIssue records staff who checked out item if appropriate' => sub {
5299 $module->mock( 'userenv', sub { { branch => $library->{id} } } );
5301 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5302 my $patron = $builder->build_object(
5304 class => 'Koha::Patrons',
5305 value => { categorycode => $patron_category->{categorycode} }
5308 my $issuer = $builder->build_object(
5310 class => 'Koha::Patrons',
5311 value => { categorycode => $patron_category->{categorycode} }
5314 my $item = $builder->build_sample_item(
5316 library => $library->{branchcode}
5320 $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->{borrowernumber} } } );
5322 my $dt_from = dt_from_string();
5323 my $dt_to = dt_from_string()->add( days => 7 );
5325 my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
5327 is( $issue->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
5329 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
5332 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
5334 is( $issue->issuer, $issuer->{borrowernumber}, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
5337 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
5340 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5341 my $patron_1 = $builder->build_object(
5343 class => 'Koha::Patrons',
5344 value => { branchcode => $library_1->branchcode }
5347 my $patron_2 = $builder->build_object(
5349 class => 'Koha::Patrons',
5350 value => { branchcode => $library_1->branchcode }
5354 my $item = $builder->build_sample_item(
5356 library => $library_1->branchcode,
5360 AddIssue( $patron_1->unblessed, $item->barcode );
5361 ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
5362 AddIssue( $patron_2->unblessed, $item->barcode );
5363 ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
5366 subtest "updateWrongTransfer tests" => sub {
5369 my $library1 = $builder->build_object( { class => 'Koha::Libraries' } );
5370 my $library2 = $builder->build_object( { class => 'Koha::Libraries' } );
5371 my $library3 = $builder->build_object( { class => 'Koha::Libraries' } );
5372 my $item = $builder->build_sample_item(
5374 homebranch => $library1->branchcode,
5375 holdingbranch => $library2->branchcode,
5376 datelastseen => undef
5380 my $transfer = $builder->build_object(
5382 class => 'Koha::Item::Transfers',
5384 itemnumber => $item->itemnumber,
5385 frombranch => $library2->branchcode,
5386 tobranch => $library1->branchcode,
5387 daterequested => dt_from_string,
5388 datesent => dt_from_string,
5389 datecancelled => undef,
5390 datearrived => undef,
5395 is( ref($transfer), 'Koha::Item::Transfer', 'Mock transfer added' );
5397 my $new_transfer = C4::Circulation::updateWrongTransfer($item->itemnumber, $library1->branchcode);
5398 is(ref($new_transfer), 'Koha::Item::Transfer', "updateWrongTransfer returns a 'Koha::Item::Transfer' object");
5399 ok( !$new_transfer->in_transit, "New transfer is NOT created as in transit (or cancelled)");
5401 my $original_transfer = $transfer->get_from_storage;
5402 ok( defined($original_transfer->datecancelled), "Original transfer was cancelled");
5403 is( $original_transfer->cancellation_reason, 'WrongTransfer', "Original transfer cancellation reason is 'WrongTransfer'");
5406 subtest "SendCirculationAlert" => sub {
5409 # When you would unsuspectingly call this unit test (with perl, not prove), you will be bitten by LOCK.
5410 # LOCK will commit changes and ruin your data
5411 # In order to prevent that, we will add KOHA_TESTING to $ENV; see further Circulation.pm
5412 $ENV{KOHA_TESTING} = 1;
5414 # Setup branch, borrowr, and notice
5415 my $library = $builder->build_object({ class => 'Koha::Libraries' });
5416 set_userenv( $library->unblessed);
5417 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5418 C4::Members::Messaging::SetMessagingPreference({
5419 borrowernumber => $patron->id,
5420 message_transport_types => ['sms'],
5421 message_attribute_id => 5
5423 my $item = $builder->build_sample_item();
5424 my $checkin_notice = $builder->build_object({
5425 class => 'Koha::Notice::Templates',
5427 module => 'circulation',
5429 branchcode => $library->branchcode,
5430 name => 'Test Checkin',
5432 content => "Checkins:\n----\n[% biblio.title %]-[% old_checkout.issue_id %]\n----Thank you.",
5433 message_transport_type => 'sms',
5438 # Checkout an item, mark it returned, generate a notice
5439 my $issue_1 = AddIssue( $patron->unblessed, $item->barcode);
5440 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5441 C4::Circulation::SendCirculationAlert({
5443 item => $item->unblessed,
5444 borrower => $patron->unblessed,
5445 branch => $library->branchcode,
5448 my $notice = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'CHECKIN' });
5449 is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\nThank you.", 'Letter generated with expected output on first checkin' );
5450 is($notice->to_address, $patron->smsalertnumber, "Letter has the correct to_address set to smsalertnumber for SMS type notices");
5452 # Checkout an item, mark it returned, generate a notice
5453 my $issue_2 = AddIssue( $patron->unblessed, $item->barcode);
5454 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5455 C4::Circulation::SendCirculationAlert({
5457 item => $item->unblessed,
5458 borrower => $patron->unblessed,
5459 branch => $library->branchcode,
5462 $notice->discard_changes();
5463 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' );
5467 subtest "GetSoonestRenewDate tests" => sub {
5469 Koha::CirculationRules->set_rule(
5471 categorycode => undef,
5472 branchcode => undef,
5474 rule_name => 'norenewalbefore',
5478 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5479 my $item = $builder->build_sample_item();
5480 my $issue = AddIssue( $patron->unblessed, $item->barcode);
5481 my $datedue = dt_from_string( $issue->date_due() );
5484 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
5485 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
5487 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5488 $datedue->clone->add( days => -7 ),
5489 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5493 # Test 'date' setting for syspref NoRenewalBeforePrecision
5494 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5496 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5497 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
5498 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5502 Koha::CirculationRules->set_rule(
5504 categorycode => undef,
5505 branchcode => undef,
5507 rule_name => 'norenewalbefore',
5508 rule_value => undef,
5513 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5515 'Checkouts without auto-renewal can be renewed immediately if no norenewalbefore'
5518 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5519 $issue->auto_renew(1)->store;
5521 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5522 $datedue->clone->truncate( to => 'day' ),
5523 'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5525 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact' );
5527 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5529 'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5533 $schema->storage->txn_rollback;
5534 C4::Context->clear_syspref_cache();
5535 $branches = Koha::Libraries->search();
5536 for my $branch ( $branches->next ) {
5537 my $key = $branch->branchcode . "_holidays";
5538 $cache->clear_from_cache($key);