3 # This file is part of Koha.
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21 use Test::More tests => 60;
24 use Test::Deep qw( cmp_deeply );
30 use POSIX qw( floor );
32 use t::lib::TestBuilder;
35 use C4::Calendar qw( new insert_single_holiday insert_week_day_holiday delete_holiday );
36 use C4::Circulation qw( AddIssue AddReturn CanBookBeRenewed GetIssuingCharges AddRenewal GetSoonestRenewDate GetLatestAutoRenewDate LostItem GetUpcomingDueIssues CanBookBeIssued AddIssuingCharge MarkIssueReturned ProcessOfflinePayment transferbook updateWrongTransfer );
38 use C4::Items qw( ModItemTransfer );
40 use C4::Reserves qw( AddReserve ModReserve ModReserveCancelAll ModReserveAffect CheckReserves GetOtherReserves );
41 use C4::Overdues qw( CalcFine UpdateFine get_chargeable_units );
42 use C4::Members::Messaging qw( SetMessagingPreference );
43 use Koha::DateUtils qw( dt_from_string output_pref );
46 use Koha::Item::Transfers;
49 use Koha::Patron::Debarments qw( GetDebarments AddDebarment DelUniqueDebarment );
51 use Koha::CirculationRules;
52 use Koha::Subscriptions;
53 use Koha::Account::Lines;
54 use Koha::Account::Offsets;
56 use Koha::Notice::Messages;
60 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
64 my ( $error, $question, $alert ) = @_;
66 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
67 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
68 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
72 sub test_debarment_on_checkout {
74 my $item = $params->{item};
75 my $library = $params->{library};
76 my $patron = $params->{patron};
77 my $due_date = $params->{due_date} || dt_from_string;
78 my $return_date = $params->{return_date} || dt_from_string;
79 my $expected_expiration_date = $params->{expiration_date};
81 $expected_expiration_date = output_pref(
83 dt => $expected_expiration_date,
89 my $line_number = $caller[2];
90 AddIssue( $patron, $item->barcode, $due_date );
92 my ( undef, $message ) = AddReturn( $item->barcode, $library->{branchcode}, undef, $return_date );
93 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
94 or diag('AddReturn returned message ' . Dumper $message );
95 my $debarments = Koha::Patron::Debarments::GetDebarments(
96 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
97 is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
99 is( $debarments->[0]->{expiration},
100 $expected_expiration_date, 'Test at line ' . $line_number );
101 Koha::Patron::Debarments::DelUniqueDebarment(
102 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
105 my $schema = Koha::Database->schema;
106 $schema->storage->txn_begin;
107 my $builder = t::lib::TestBuilder->new;
108 my $dbh = C4::Context->dbh;
110 # Prevent random failures by mocking ->now
111 my $now_value = dt_from_string;
112 my $mocked_datetime = Test::MockModule->new('DateTime');
113 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
115 my $cache = Koha::Caches->get_instance();
116 $dbh->do(q|DELETE FROM special_holidays|);
117 $dbh->do(q|DELETE FROM repeatable_holidays|);
118 my $branches = Koha::Libraries->search();
119 for my $branch ( $branches->next ) {
120 my $key = $branch->branchcode . "_holidays";
121 $cache->clear_from_cache($key);
124 # Start with a clean slate
125 $dbh->do('DELETE FROM issues');
126 $dbh->do('DELETE FROM borrowers');
128 # Disable recording of the staff who checked out an item until we're ready for it
129 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 0);
131 my $module = Test::MockModule->new('C4::Context');
133 my $library = $builder->build({
136 my $library2 = $builder->build({
139 my $itemtype = $builder->build(
141 source => 'Itemtype',
145 rentalcharge_daily => 0,
146 defaultreplacecost => undef,
151 my $patron_category = $builder->build(
153 source => 'Category',
155 category_type => 'P',
157 BlockExpiredPatronOpacActions => -1, # Pick the pref value
162 my $CircControl = C4::Context->preference('CircControl');
163 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
166 homebranch => $library2->{branchcode},
167 holdingbranch => $library2->{branchcode}
171 branchcode => $library2->{branchcode}
174 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
176 # No userenv, PickupLibrary
177 t::lib::Mocks::mock_preference('IndependentBranches', '0');
178 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
180 C4::Context->preference('CircControl'),
182 'CircControl changed to PickupLibrary'
185 C4::Circulation::_GetCircControlBranch($item, $borrower),
186 $item->{$HomeOrHoldingBranch},
187 '_GetCircControlBranch returned item branch (no userenv defined)'
190 # No userenv, PatronLibrary
191 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
193 C4::Context->preference('CircControl'),
195 'CircControl changed to PatronLibrary'
198 C4::Circulation::_GetCircControlBranch($item, $borrower),
199 $borrower->{branchcode},
200 '_GetCircControlBranch returned borrower branch'
203 # No userenv, ItemHomeLibrary
204 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
206 C4::Context->preference('CircControl'),
208 'CircControl changed to ItemHomeLibrary'
211 $item->{$HomeOrHoldingBranch},
212 C4::Circulation::_GetCircControlBranch($item, $borrower),
213 '_GetCircControlBranch returned item branch'
217 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
218 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
220 # Userenv set, PickupLibrary
221 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
223 C4::Context->preference('CircControl'),
225 'CircControl changed to PickupLibrary'
228 C4::Circulation::_GetCircControlBranch($item, $borrower),
229 $library2->{branchcode},
230 '_GetCircControlBranch returned current branch'
233 # Userenv set, PatronLibrary
234 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
236 C4::Context->preference('CircControl'),
238 'CircControl changed to PatronLibrary'
241 C4::Circulation::_GetCircControlBranch($item, $borrower),
242 $borrower->{branchcode},
243 '_GetCircControlBranch returned borrower branch'
246 # Userenv set, ItemHomeLibrary
247 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
249 C4::Context->preference('CircControl'),
251 'CircControl changed to ItemHomeLibrary'
254 C4::Circulation::_GetCircControlBranch($item, $borrower),
255 $item->{$HomeOrHoldingBranch},
256 '_GetCircControlBranch returned item branch'
259 # Reset initial configuration
260 t::lib::Mocks::mock_preference('CircControl', $CircControl);
262 C4::Context->preference('CircControl'),
264 'CircControl reset to its initial value'
267 # Set a simple circ policy
268 $dbh->do('DELETE FROM circulation_rules');
269 Koha::CirculationRules->set_rules(
271 categorycode => undef,
275 reservesallowed => 25,
277 lengthunit => 'days',
278 renewalsallowed => 1,
280 norenewalbefore => undef,
288 subtest "CanBookBeRenewed AllowRenewalIfOtherItemsAvailable multiple borrowers and items tests" => sub {
291 #Can only reserve from home branch
292 Koha::CirculationRules->set_rule(
296 rule_name => 'holdallowed',
300 Koha::CirculationRules->set_rule(
303 categorycode => undef,
305 rule_name => 'onshelfholds',
310 # Patrons from three different branches
311 my $patron_borrower = $builder->build_object({ class => 'Koha::Patrons' });
312 my $patron_hold_1 = $builder->build_object({ class => 'Koha::Patrons' });
313 my $patron_hold_2 = $builder->build_object({ class => 'Koha::Patrons' });
314 my $biblio = $builder->build_sample_biblio();
316 # Item at each patron branch
317 my $item_1 = $builder->build_sample_item({
318 biblionumber => $biblio->biblionumber,
319 homebranch => $patron_borrower->branchcode
321 my $item_2 = $builder->build_sample_item({
322 biblionumber => $biblio->biblionumber,
323 homebranch => $patron_hold_2->branchcode
325 my $item_3 = $builder->build_sample_item({
326 biblionumber => $biblio->biblionumber,
327 homebranch => $patron_hold_1->branchcode
330 my $issue = AddIssue( $patron_borrower->unblessed, $item_1->barcode);
331 my $datedue = dt_from_string( $issue->date_due() );
332 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
337 branchcode => $patron_hold_1->branchcode,
338 borrowernumber => $patron_hold_1->borrowernumber,
339 biblionumber => $biblio->biblionumber,
341 reservation_date => dt_from_string(),
342 expiration_date => undef,
349 branchcode => $patron_hold_2->branchcode,
350 borrowernumber => $patron_hold_2->borrowernumber,
351 biblionumber => $biblio->biblionumber,
353 reservation_date => dt_from_string(),
354 expiration_date => undef,
359 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
361 my ( $renewokay, $error ) = CanBookBeRenewed($patron_borrower->borrowernumber, $item_1->itemnumber);
362 is( $renewokay, 0, 'Cannot renew, reserved');
363 is( $error, 'on_reserve', 'Cannot renew, reserved (returned error is on_reserve)');
365 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
367 ( $renewokay, $error ) = CanBookBeRenewed($patron_borrower->borrowernumber, $item_1->itemnumber);
368 is( $renewokay, 1, 'Can renew, two items available for two holds');
369 is( $error, undef, 'Can renew, each reserve has an item');
374 subtest "GetIssuingCharges tests" => sub {
376 my $branch_discount = $builder->build_object({ class => 'Koha::Libraries' });
377 my $branch_no_discount = $builder->build_object({ class => 'Koha::Libraries' });
378 Koha::CirculationRules->set_rule(
380 categorycode => undef,
381 branchcode => $branch_discount->branchcode,
383 rule_name => 'rentaldiscount',
387 my $itype_charge = $builder->build_object({
388 class => 'Koha::ItemTypes',
393 my $itype_no_charge = $builder->build_object({
394 class => 'Koha::ItemTypes',
399 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
400 my $item_1 = $builder->build_sample_item({ itype => $itype_charge->itemtype });
401 my $item_2 = $builder->build_sample_item({ itype => $itype_no_charge->itemtype });
403 t::lib::Mocks::mock_userenv({ branchcode => $branch_no_discount->branchcode });
404 # For now the sub always uses the env branch, this should follow CircControl instead
405 my ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
406 is( $charge + 0, 10.00, "Charge fetched correctly when no discount exists");
407 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
408 is( $charge + 0, 0.00, "Charge fetched correctly when no discount exists and no charge");
410 t::lib::Mocks::mock_userenv({ branchcode => $branch_discount->branchcode });
411 # For now the sub always uses the env branch, this should follow CircControl instead
412 ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
413 is( $charge + 0, 8.50, "Charge fetched correctly when discount exists");
414 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
415 is( $charge + 0, 0.00, "Charge fetched correctly when discount exists and no charge");
419 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
420 subtest "CanBookBeRenewed tests" => sub {
423 C4::Context->set_preference('ItemsDeniedRenewal','');
424 # Generate test biblio
425 my $biblio = $builder->build_sample_biblio();
427 my $branch = $library2->{branchcode};
429 my $item_1 = $builder->build_sample_item(
431 biblionumber => $biblio->biblionumber,
433 replacementprice => 12.00,
437 $reused_itemnumber_1 = $item_1->itemnumber;
439 my $item_2 = $builder->build_sample_item(
441 biblionumber => $biblio->biblionumber,
443 replacementprice => 23.00,
447 $reused_itemnumber_2 = $item_2->itemnumber;
449 my $item_3 = $builder->build_sample_item(
451 biblionumber => $biblio->biblionumber,
453 replacementprice => 23.00,
459 my %renewing_borrower_data = (
461 surname => 'Renewal',
462 categorycode => $patron_category->{categorycode},
463 branchcode => $branch,
466 my %reserving_borrower_data = (
467 firstname => 'Katrin',
468 surname => 'Reservation',
469 categorycode => $patron_category->{categorycode},
470 branchcode => $branch,
473 my %hold_waiting_borrower_data = (
475 surname => 'Reservation',
476 categorycode => $patron_category->{categorycode},
477 branchcode => $branch,
480 my %restricted_borrower_data = (
481 firstname => 'Alice',
482 surname => 'Reservation',
483 categorycode => $patron_category->{categorycode},
484 debarred => '3228-01-01',
485 branchcode => $branch,
488 my %expired_borrower_data = (
491 categorycode => $patron_category->{categorycode},
492 branchcode => $branch,
493 dateexpiry => dt_from_string->subtract( months => 1 ),
496 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
497 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
498 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
499 my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
500 my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
502 my $renewing_borrower_obj = Koha::Patrons->find( $renewing_borrowernumber );
503 my $renewing_borrower = $renewing_borrower_obj->unblessed;
504 my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
505 my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
512 my $checkitem = undef;
515 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
516 my $datedue = dt_from_string( $issue->date_due() );
517 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
519 my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
520 $datedue = dt_from_string( $issue->date_due() );
521 is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
524 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
525 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
527 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
528 is( $renewokay, 1, 'Can renew, no holds for this title or item');
531 # Biblio-level hold, renewal test
534 branchcode => $branch,
535 borrowernumber => $reserving_borrowernumber,
536 biblionumber => $biblio->biblionumber,
537 priority => $priority,
538 reservation_date => $resdate,
539 expiration_date => $expdate,
541 itemnumber => $checkitem,
546 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
547 Koha::CirculationRules->set_rule(
549 categorycode => undef,
552 rule_name => 'onshelfholds',
556 Koha::CirculationRules->set_rule(
558 categorycode => undef,
561 rule_name => 'renewalsallowed',
565 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
566 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
567 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
568 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
569 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
571 # Now let's add an item level hold, we should no longer be able to renew the item
572 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
574 borrowernumber => $hold_waiting_borrowernumber,
575 biblionumber => $biblio->biblionumber,
576 itemnumber => $item_1->itemnumber,
577 branchcode => $branch,
581 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
582 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
585 # 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
586 # be able to renew these items
587 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
589 borrowernumber => $hold_waiting_borrowernumber,
590 biblionumber => $biblio->biblionumber,
591 itemnumber => $item_3->itemnumber,
592 branchcode => $branch,
597 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
598 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
599 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
600 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
601 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
603 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
604 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
605 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
607 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
608 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
609 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
611 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
612 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
613 AddIssue($reserving_borrower, $item_3->barcode);
614 my $reserve = $dbh->selectrow_hashref(
615 'SELECT * FROM old_reserves WHERE reserve_id = ?',
619 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
621 # Item-level hold, renewal test
624 branchcode => $branch,
625 borrowernumber => $reserving_borrowernumber,
626 biblionumber => $biblio->biblionumber,
627 priority => $priority,
628 reservation_date => $resdate,
629 expiration_date => $expdate,
631 itemnumber => $item_1->itemnumber,
636 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
637 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
638 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
640 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
641 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
643 # Items can't fill hold for reasons
644 $item_1->notforloan(1)->store;
645 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
646 is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
647 $item_1->set({notforloan => 0, itype => $itemtype })->store;
649 # FIXME: Add more for itemtype not for loan etc.
651 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
652 my $item_5 = $builder->build_sample_item(
654 biblionumber => $biblio->biblionumber,
656 replacementprice => 23.00,
660 my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
661 is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
663 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
664 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
665 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
666 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
667 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
668 is( $error, 'restriction', "Correct error returned");
670 # Users cannot renew an overdue item
671 my $item_6 = $builder->build_sample_item(
673 biblionumber => $biblio->biblionumber,
675 replacementprice => 23.00,
680 my $item_7 = $builder->build_sample_item(
682 biblionumber => $biblio->biblionumber,
684 replacementprice => 23.00,
689 my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
690 is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
692 my $now = dt_from_string();
693 my $five_weeks = DateTime::Duration->new(weeks => 5);
694 my $five_weeks_ago = $now - $five_weeks;
695 t::lib::Mocks::mock_preference('finesMode', 'production');
697 my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
698 is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
700 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
701 C4::Overdues::UpdateFine(
703 issue_id => $passeddatedue1->id(),
704 itemnumber => $item_7->itemnumber,
705 borrowernumber => $renewing_borrower->{borrowernumber},
707 due => Koha::DateUtils::output_pref($five_weeks_ago)
711 # Make sure fine calculation isn't skipped when adding renewal
712 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
714 t::lib::Mocks::mock_preference('RenewalLog', 0);
715 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
716 my %params_renewal = (
717 timestamp => { -like => $date . "%" },
718 module => "CIRCULATION",
722 timestamp => { -like => $date . "%" },
723 module => "CIRCULATION",
726 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
727 my $dt = dt_from_string();
728 Time::Fake->offset( $dt->epoch );
729 my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
730 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
731 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
732 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
735 t::lib::Mocks::mock_preference('RenewalLog', 1);
736 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
737 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
738 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
739 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
740 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
742 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
743 is( $fines->count, 2, 'AddRenewal left both fines' );
744 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
745 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
748 t::lib::Mocks::mock_preference('OverduesBlockRenewing','allow');
749 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
750 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
751 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
752 is( $renewokay, 1, '(Bug 8236), Can renew, this item is overdue but not pref does not block');
754 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
755 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
756 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is not overdue but patron has overdues');
757 is( $error, 'overdue', "Correct error returned");
758 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
759 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue so patron has overdues');
760 is( $error, 'overdue', "Correct error returned");
762 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
763 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
764 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
765 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
766 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
767 is( $error, 'overdue', "Correct error returned");
770 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
771 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
772 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
773 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
774 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
775 $new_log_size = Koha::ActionLogs->count( \%params_issue );
776 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
778 $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
781 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
785 # Test automatic renewal before value for "norenewalbefore" in policy is set
786 # In this case automatic renewal is not permitted prior to due date
787 my $item_4 = $builder->build_sample_item(
789 biblionumber => $biblio->biblionumber,
791 replacementprice => 16.00,
796 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
797 ( $renewokay, $error ) =
798 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
799 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
800 is( $error, 'auto_too_soon',
801 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
804 branchcode => $branch,
805 borrowernumber => $reserving_borrowernumber,
806 biblionumber => $biblio->biblionumber,
807 itemnumber => $bibitems,
808 priority => $priority,
809 reservation_date => $resdate,
810 expiration_date => $expdate,
813 itemnumber => $item_4->itemnumber,
817 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
818 is( $renewokay, 0, 'Still should not be able to renew' );
819 is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' );
820 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, undef, 1 );
821 is( $renewokay, 0, 'Still should not be able to renew' );
822 is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' );
823 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
824 is( $renewokay, 0, 'Still should not be able to renew' );
825 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
826 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1, 1 );
827 is( $renewokay, 0, 'Still should not be able to renew' );
828 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
829 $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
830 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
831 is( $renewokay, 0, 'Still should not be able to renew' );
832 is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
833 ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
837 $renewing_borrower_obj->autorenew_checkouts(0)->store;
838 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
839 is( $renewokay, 1, 'No renewal before is undef, but patron opted out of auto_renewal' );
840 $renewing_borrower_obj->autorenew_checkouts(1)->store;
844 # Test premature manual renewal
845 Koha::CirculationRules->set_rule(
847 categorycode => undef,
850 rule_name => 'norenewalbefore',
855 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
856 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
857 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
860 # Test premature automatic renewal
861 ( $renewokay, $error ) =
862 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
863 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
864 is( $error, 'auto_too_soon',
865 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
868 $renewing_borrower_obj->autorenew_checkouts(0)->store;
869 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
870 is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' );
871 is( $error, 'too_soon', 'Error is too_soon, no auto' );
872 $renewing_borrower_obj->autorenew_checkouts(1)->store;
874 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
875 # and test automatic renewal again
876 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
877 ( $renewokay, $error ) =
878 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
879 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
880 is( $error, 'auto_too_soon',
881 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
884 $renewing_borrower_obj->autorenew_checkouts(0)->store;
885 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
886 is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' );
887 is( $error, 'too_soon', 'Error is too_soon, no auto' );
888 $renewing_borrower_obj->autorenew_checkouts(1)->store;
890 # Change policy so that loans can be renewed 99 days prior to the due date
891 # and test automatic renewal again
892 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
893 ( $renewokay, $error ) =
894 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
895 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
896 is( $error, 'auto_renew',
897 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
900 $renewing_borrower_obj->autorenew_checkouts(0)->store;
901 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
902 is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' );
903 $renewing_borrower_obj->autorenew_checkouts(1)->store;
905 subtest "too_late_renewal / no_auto_renewal_after" => sub {
907 my $item_to_auto_renew = $builder->build_sample_item(
909 biblionumber => $biblio->biblionumber,
914 my $ten_days_before = dt_from_string->add( days => -10 );
915 my $ten_days_ahead = dt_from_string->add( days => 10 );
916 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
918 Koha::CirculationRules->set_rules(
920 categorycode => undef,
924 norenewalbefore => '7',
925 no_auto_renewal_after => '9',
929 ( $renewokay, $error ) =
930 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
931 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
932 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
934 Koha::CirculationRules->set_rules(
936 categorycode => undef,
940 norenewalbefore => '7',
941 no_auto_renewal_after => '10',
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 auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
950 Koha::CirculationRules->set_rules(
952 categorycode => undef,
956 norenewalbefore => '7',
957 no_auto_renewal_after => '11',
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_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
966 Koha::CirculationRules->set_rules(
968 categorycode => undef,
972 norenewalbefore => '10',
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_renew', 'Cannot renew, renew is automatic' );
982 Koha::CirculationRules->set_rules(
984 categorycode => undef,
988 norenewalbefore => '10',
989 no_auto_renewal_after => undef,
990 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
994 ( $renewokay, $error ) =
995 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
996 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
997 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
999 Koha::CirculationRules->set_rules(
1001 categorycode => undef,
1002 branchcode => undef,
1005 norenewalbefore => '7',
1006 no_auto_renewal_after => '15',
1007 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1011 ( $renewokay, $error ) =
1012 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1013 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1014 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1016 Koha::CirculationRules->set_rules(
1018 categorycode => undef,
1019 branchcode => undef,
1022 norenewalbefore => '10',
1023 no_auto_renewal_after => undef,
1024 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
1028 ( $renewokay, $error ) =
1029 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1030 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1031 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1034 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
1036 my $item_to_auto_renew = $builder->build_sample_item(
1038 biblionumber => $biblio->biblionumber,
1043 my $ten_days_before = dt_from_string->add( days => -10 );
1044 my $ten_days_ahead = dt_from_string->add( days => 10 );
1045 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1047 Koha::CirculationRules->set_rules(
1049 categorycode => undef,
1050 branchcode => undef,
1053 norenewalbefore => '10',
1054 no_auto_renewal_after => '11',
1058 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
1059 C4::Context->set_preference('OPACFineNoRenewals','10');
1060 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1061 my $fines_amount = 5;
1062 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
1063 $account->add_debit(
1065 amount => $fines_amount,
1066 interface => 'test',
1068 item_id => $item_to_auto_renew->itemnumber,
1069 description => "Some fines"
1071 )->status('RETURNED')->store;
1072 ( $renewokay, $error ) =
1073 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1074 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1075 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
1077 $account->add_debit(
1079 amount => $fines_amount,
1080 interface => 'test',
1082 item_id => $item_to_auto_renew->itemnumber,
1083 description => "Some fines"
1085 )->status('RETURNED')->store;
1086 ( $renewokay, $error ) =
1087 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1088 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1089 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
1091 $account->add_debit(
1093 amount => $fines_amount,
1094 interface => 'test',
1096 item_id => $item_to_auto_renew->itemnumber,
1097 description => "Some fines"
1099 )->status('RETURNED')->store;
1100 ( $renewokay, $error ) =
1101 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1102 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1103 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
1105 $account->add_credit(
1107 amount => $fines_amount,
1108 interface => 'test',
1110 description => "Some payment"
1113 ( $renewokay, $error ) =
1114 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1115 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1116 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1118 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
1119 ( $renewokay, $error ) =
1120 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1121 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1122 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1124 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
1125 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1128 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
1130 my $item_to_auto_renew = $builder->build_sample_item(
1132 biblionumber => $biblio->biblionumber,
1137 Koha::CirculationRules->set_rules(
1139 categorycode => undef,
1140 branchcode => undef,
1143 norenewalbefore => 10,
1144 no_auto_renewal_after => 11,
1149 my $ten_days_before = dt_from_string->add( days => -10 );
1150 my $ten_days_ahead = dt_from_string->add( days => 10 );
1152 # Patron is expired and BlockExpiredPatronOpacActions=0
1153 # => auto renew is allowed
1154 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
1155 my $patron = $expired_borrower;
1156 my $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1157 ( $renewokay, $error ) =
1158 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1159 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1160 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
1161 Koha::Checkouts->find( $checkout->issue_id )->delete;
1164 # Patron is expired and BlockExpiredPatronOpacActions=1
1165 # => auto renew is not allowed
1166 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1167 $patron = $expired_borrower;
1168 $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1169 ( $renewokay, $error ) =
1170 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1171 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1172 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
1173 Koha::Checkouts->find( $checkout->issue_id )->delete;
1176 # Patron is not expired and BlockExpiredPatronOpacActions=1
1177 # => auto renew is allowed
1178 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1179 $patron = $renewing_borrower;
1180 $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1181 ( $renewokay, $error ) =
1182 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1183 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1184 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1185 Koha::Checkouts->find( $checkout->issue_id )->delete;
1188 subtest "GetLatestAutoRenewDate" => sub {
1190 my $item_to_auto_renew = $builder->build_sample_item(
1192 biblionumber => $biblio->biblionumber,
1197 my $ten_days_before = dt_from_string->add( days => -10 );
1198 my $ten_days_ahead = dt_from_string->add( days => 10 );
1199 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1200 Koha::CirculationRules->set_rules(
1202 categorycode => undef,
1203 branchcode => undef,
1206 norenewalbefore => '7',
1207 no_auto_renewal_after => '',
1208 no_auto_renewal_after_hard_limit => undef,
1212 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1213 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' );
1214 my $five_days_before = dt_from_string->add( days => -5 );
1215 Koha::CirculationRules->set_rules(
1217 categorycode => undef,
1218 branchcode => undef,
1221 norenewalbefore => '10',
1222 no_auto_renewal_after => '5',
1223 no_auto_renewal_after_hard_limit => undef,
1227 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1228 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1229 $five_days_before->truncate( to => 'minute' ),
1230 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1232 my $five_days_ahead = dt_from_string->add( days => 5 );
1233 $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1234 $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1235 $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1236 Koha::CirculationRules->set_rules(
1238 categorycode => undef,
1239 branchcode => undef,
1242 norenewalbefore => '10',
1243 no_auto_renewal_after => '15',
1244 no_auto_renewal_after_hard_limit => undef,
1248 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1249 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1250 $five_days_ahead->truncate( to => 'minute' ),
1251 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1253 my $two_days_ahead = dt_from_string->add( days => 2 );
1254 Koha::CirculationRules->set_rules(
1256 categorycode => undef,
1257 branchcode => undef,
1260 norenewalbefore => '10',
1261 no_auto_renewal_after => '',
1262 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1266 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1267 is( $latest_auto_renew_date->truncate( to => 'day' ),
1268 $two_days_ahead->truncate( to => 'day' ),
1269 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1271 Koha::CirculationRules->set_rules(
1273 categorycode => undef,
1274 branchcode => undef,
1277 norenewalbefore => '10',
1278 no_auto_renewal_after => '15',
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 < no_auto_renewal_after'
1292 # set policy to forbid renewals
1293 Koha::CirculationRules->set_rules(
1295 categorycode => undef,
1296 branchcode => undef,
1299 norenewalbefore => undef,
1300 renewalsallowed => 0,
1305 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1306 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1307 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1309 # Too many unseen renewals
1310 Koha::CirculationRules->set_rules(
1312 categorycode => undef,
1313 branchcode => undef,
1316 unseen_renewals_allowed => 2,
1317 renewalsallowed => 10,
1321 t::lib::Mocks::mock_preference('UnseenRenewals', 1);
1322 $dbh->do('UPDATE issues SET unseen_renewals = 2 where borrowernumber = ? AND itemnumber = ?', undef, ($renewing_borrowernumber, $item_1->itemnumber));
1323 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1324 is( $renewokay, 0, 'Cannot renew, 0 unseen renewals allowed');
1325 is( $error, 'too_unseen', 'Cannot renew, returned code is too_unseen');
1326 Koha::CirculationRules->set_rules(
1328 categorycode => undef,
1329 branchcode => undef,
1332 norenewalbefore => undef,
1333 renewalsallowed => 0,
1337 t::lib::Mocks::mock_preference('UnseenRenewals', 0);
1339 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1340 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1341 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1343 C4::Overdues::UpdateFine(
1345 issue_id => $issue->id(),
1346 itemnumber => $item_1->itemnumber,
1347 borrowernumber => $renewing_borrower->{borrowernumber},
1350 due => Koha::DateUtils::output_pref($datedue)
1354 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
1355 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1356 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1357 is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1358 is( $line->amount+0, 15, 'Account line amount is 15.00' );
1359 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
1361 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1362 is( $offset->type, 'CREATE', 'Account offset type is CREATE' );
1363 is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1365 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1366 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1368 LostItem( $item_1->itemnumber, 'test', 1 );
1370 $line = Koha::Account::Lines->find($line->id);
1371 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1372 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1374 my $item = Koha::Items->find($item_1->itemnumber);
1375 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1376 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1377 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1379 my $total_due = $dbh->selectrow_array(
1380 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1381 undef, $renewing_borrower->{borrowernumber}
1384 is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1386 C4::Context->dbh->do("DELETE FROM accountlines");
1388 C4::Overdues::UpdateFine(
1390 issue_id => $issue2->id(),
1391 itemnumber => $item_2->itemnumber,
1392 borrowernumber => $renewing_borrower->{borrowernumber},
1395 due => Koha::DateUtils::output_pref($datedue)
1399 LostItem( $item_2->itemnumber, 'test', 0 );
1401 my $item2 = Koha::Items->find($item_2->itemnumber);
1402 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1403 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1405 $total_due = $dbh->selectrow_array(
1406 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1407 undef, $renewing_borrower->{borrowernumber}
1410 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1412 my $future = dt_from_string();
1413 $future->add( days => 7 );
1414 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1415 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1417 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1418 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1419 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1420 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1421 LostItem( $item_3->itemnumber, 'test', 0 );
1422 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1423 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1425 $accountline->description,
1426 sprintf( "%s %s %s",
1427 $item_3->biblio->title || '',
1428 $item_3->barcode || '',
1429 $item_3->itemcallnumber || '' ),
1430 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1434 t::lib::Mocks::mock_preference('UseRecalls', 1);
1435 Koha::CirculationRules->set_rules({
1436 categorycode => undef,
1437 branchcode => undef,
1440 recalls_allowed => 10,
1441 renewalsallowed => 5,
1444 my $recall_borrower = $builder->build_object({ class => 'Koha::Patrons' });
1445 my $recall_biblio = $builder->build_object({ class => 'Koha::Biblios' });
1446 my $recall_item1 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $recall_biblio->biblionumber } });
1447 my $recall_item2 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $recall_biblio->biblionumber } });
1449 AddIssue( $renewing_borrower, $recall_item1->barcode );
1451 # item-level and this item: renewal not allowed
1452 my $recall = Koha::Recall->new({
1453 biblionumber => $recall_item1->biblionumber,
1454 itemnumber => $recall_item1->itemnumber,
1455 borrowernumber => $recall_borrower->borrowernumber,
1456 branchcode => $recall_borrower->branchcode,
1457 item_level_recall => 1,
1459 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1460 is( $error, 'recalled', 'Cannot renew item that has been recalled' );
1461 $recall->set_cancelled;
1463 # biblio-level requested recall: renewal not allowed
1464 $recall = Koha::Recall->new({
1465 biblionumber => $recall_item1->biblionumber,
1466 itemnumber => undef,
1467 borrowernumber => $recall_borrower->borrowernumber,
1468 branchcode => $recall_borrower->branchcode,
1469 item_level_recall => 0,
1471 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1472 is( $error, 'recalled', 'Cannot renew item if biblio is recalled and has no item allocated' );
1473 $recall->set_cancelled;
1475 # item-level and not this item: renewal allowed
1476 $recall = Koha::Recall->new({
1477 biblionumber => $recall_item2->biblionumber,
1478 itemnumber => $recall_item2->itemnumber,
1479 borrowernumber => $recall_borrower->borrowernumber,
1480 branchcode => $recall_borrower->branchcode,
1481 item_level_recall => 1,
1483 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1484 is( $renewokay, 1, 'Can renew item if item-level recall on biblio is not on this item' );
1485 $recall->set_cancelled;
1487 # biblio-level waiting recall: renewal allowed
1488 $recall = Koha::Recall->new({
1489 biblionumber => $recall_item1->biblionumber,
1490 itemnumber => undef,
1491 borrowernumber => $recall_borrower->borrowernumber,
1492 branchcode => $recall_borrower->branchcode,
1493 item_level_recall => 0,
1495 $recall->set_waiting({ item => $recall_item1 });
1496 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $recall_item1->itemnumber );
1497 is( $renewokay, 1, 'Can renew item if biblio-level recall has already been allocated an item' );
1498 $recall->set_cancelled;
1501 subtest "GetUpcomingDueIssues" => sub {
1504 my $branch = $library2->{branchcode};
1506 #Create another record
1507 my $biblio2 = $builder->build_sample_biblio();
1510 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1511 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1512 my $item_3 = $builder->build_sample_item(
1514 biblionumber => $biblio2->biblionumber,
1522 my %a_borrower_data = (
1523 firstname => 'Fridolyn',
1524 surname => 'SOMERS',
1525 categorycode => $patron_category->{categorycode},
1526 branchcode => $branch,
1529 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1530 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1532 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1533 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1534 my $today = DateTime->today(time_zone => C4::Context->tz());
1536 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1537 my $datedue = dt_from_string( $issue->date_due() );
1538 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1539 my $datedue2 = dt_from_string( $issue->date_due() );
1543 # GetUpcomingDueIssues tests
1545 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1546 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1549 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1550 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1551 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1554 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1555 is ( scalar( @$upcoming_dues ), 1,
1556 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1559 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1561 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1563 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1564 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1566 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1567 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1569 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1570 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1572 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1573 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1575 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1576 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1578 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1579 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1583 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1584 my $branch = $library2->{branchcode};
1586 my $biblio = $builder->build_sample_biblio();
1589 my $item = $builder->build_sample_item(
1591 biblionumber => $biblio->biblionumber,
1598 my %a_borrower_data = (
1599 firstname => 'Kyle',
1601 categorycode => $patron_category->{categorycode},
1602 branchcode => $branch,
1605 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1607 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1608 my $issue = AddIssue( $borrower, $item->barcode );
1611 issue_id => $issue->id(),
1612 itemnumber => $item->itemnumber,
1613 borrowernumber => $borrowernumber,
1619 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1620 my $count = $hr->{count};
1622 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1625 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1627 my $biblio = $builder->build_sample_biblio();
1628 my $item_1 = $builder->build_sample_item(
1630 biblionumber => $biblio->biblionumber,
1631 library => $library2->{branchcode},
1634 my $item_2= $builder->build_sample_item(
1636 biblionumber => $biblio->biblionumber,
1637 library => $library2->{branchcode},
1638 itype => $item_1->effective_itemtype,
1642 Koha::CirculationRules->set_rules(
1644 categorycode => undef,
1645 itemtype => $item_1->effective_itemtype,
1646 branchcode => undef,
1648 reservesallowed => 25,
1649 holds_per_record => 25,
1651 lengthunit => 'days',
1652 renewalsallowed => 1,
1654 norenewalbefore => undef,
1664 my $borrowernumber1 = Koha::Patron->new({
1665 firstname => 'Kyle',
1667 categorycode => $patron_category->{categorycode},
1668 branchcode => $library2->{branchcode},
1669 })->store->borrowernumber;
1670 my $borrowernumber2 = Koha::Patron->new({
1671 firstname => 'Chelsea',
1673 categorycode => $patron_category->{categorycode},
1674 branchcode => $library2->{branchcode},
1675 })->store->borrowernumber;
1676 my $patron_category_2 = $builder->build(
1678 source => 'Category',
1680 category_type => 'P',
1682 BlockExpiredPatronOpacActions => -1, # Pick the pref value
1686 my $borrowernumber3 = Koha::Patron->new({
1687 firstname => 'Carnegie',
1689 categorycode => $patron_category_2->{categorycode},
1690 branchcode => $library2->{branchcode},
1691 })->store->borrowernumber;
1693 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1694 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1696 my $issue = AddIssue( $borrower1, $item_1->barcode );
1698 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1699 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1703 branchcode => $library2->{branchcode},
1704 borrowernumber => $borrowernumber2,
1705 biblionumber => $biblio->biblionumber,
1710 Koha::CirculationRules->set_rules(
1712 categorycode => undef,
1713 itemtype => $item_1->effective_itemtype,
1714 branchcode => undef,
1720 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1721 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1722 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1724 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1725 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1726 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1728 Koha::CirculationRules->set_rules(
1730 categorycode => undef,
1731 itemtype => $item_1->effective_itemtype,
1732 branchcode => undef,
1738 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1739 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1740 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1742 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1743 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1744 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1748 branchcode => $library2->{branchcode},
1749 borrowernumber => $borrowernumber3,
1750 biblionumber => $biblio->biblionumber,
1755 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1756 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' );
1758 my $item_3= $builder->build_sample_item(
1760 biblionumber => $biblio->biblionumber,
1761 library => $library2->{branchcode},
1762 itype => $item_1->effective_itemtype,
1766 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1767 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' );
1769 Koha::CirculationRules->set_rules(
1771 categorycode => $patron_category_2->{categorycode},
1772 itemtype => $item_1->effective_itemtype,
1773 branchcode => undef,
1775 reservesallowed => 0,
1780 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1781 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' );
1783 # Setting item not checked out to be not for loan but holdable
1784 $item_2->notforloan(-1)->store;
1786 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1787 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' );
1792 # Don't allow renewing onsite checkout
1793 my $branch = $library->{branchcode};
1795 #Create another record
1796 my $biblio = $builder->build_sample_biblio();
1798 my $item = $builder->build_sample_item(
1800 biblionumber => $biblio->biblionumber,
1806 my $borrowernumber = Koha::Patron->new({
1809 categorycode => $patron_category->{categorycode},
1810 branchcode => $branch,
1811 })->store->borrowernumber;
1813 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1815 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1816 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1817 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1818 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1822 my $library = $builder->build({ source => 'Branch' });
1824 my $biblio = $builder->build_sample_biblio();
1826 my $item = $builder->build_sample_item(
1828 biblionumber => $biblio->biblionumber,
1829 library => $library->{branchcode},
1834 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1836 my $issue = AddIssue( $patron, $item->barcode );
1839 issue_id => $issue->id(),
1840 itemnumber => $item->itemnumber,
1841 borrowernumber => $patron->{borrowernumber},
1848 issue_id => $issue->id(),
1849 itemnumber => $item->itemnumber,
1850 borrowernumber => $patron->{borrowernumber},
1855 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1858 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1861 my $homebranch = $builder->build( { source => 'Branch' } );
1862 my $holdingbranch = $builder->build( { source => 'Branch' } );
1863 my $otherbranch = $builder->build( { source => 'Branch' } );
1864 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1865 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1867 my $item = $builder->build_sample_item(
1869 homebranch => $homebranch->{branchcode},
1870 holdingbranch => $holdingbranch->{branchcode},
1873 Koha::CirculationRules->set_rules(
1875 categorycode => undef,
1876 itemtype => $item->effective_itemtype,
1877 branchcode => undef,
1879 reservesallowed => 25,
1881 lengthunit => 'days',
1882 renewalsallowed => 1,
1884 norenewalbefore => undef,
1893 set_userenv($holdingbranch);
1895 my $issue = AddIssue( $patron_1->unblessed, $item->barcode );
1896 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1898 my ( $error, $question, $alerts );
1900 # AllowReturnToBranch == anywhere
1901 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1902 ## Test that unknown barcodes don't generate internal server errors
1903 set_userenv($homebranch);
1904 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1905 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1906 ## Can be issued from homebranch
1907 set_userenv($homebranch);
1908 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1909 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1910 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1911 ## Can be issued from holdingbranch
1912 set_userenv($holdingbranch);
1913 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1914 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1915 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1916 ## Can be issued from another branch
1917 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1918 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1919 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1921 # AllowReturnToBranch == holdingbranch
1922 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1923 ## Cannot be issued from homebranch
1924 set_userenv($homebranch);
1925 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1926 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1927 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1928 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1929 ## Can be issued from holdinbranch
1930 set_userenv($holdingbranch);
1931 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1932 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1933 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1934 ## Cannot be issued from another branch
1935 set_userenv($otherbranch);
1936 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1937 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1938 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1939 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
1941 # AllowReturnToBranch == homebranch
1942 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1943 ## Can be issued from holdinbranch
1944 set_userenv($homebranch);
1945 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1946 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1947 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1948 ## Cannot be issued from holdinbranch
1949 set_userenv($holdingbranch);
1950 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1951 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1952 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1953 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1954 ## Cannot be issued from holdinbranch
1955 set_userenv($otherbranch);
1956 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1957 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1958 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1959 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1961 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1964 subtest 'AddIssue & AllowReturnToBranch' => sub {
1967 my $homebranch = $builder->build( { source => 'Branch' } );
1968 my $holdingbranch = $builder->build( { source => 'Branch' } );
1969 my $otherbranch = $builder->build( { source => 'Branch' } );
1970 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1971 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1973 my $item = $builder->build_sample_item(
1975 homebranch => $homebranch->{branchcode},
1976 holdingbranch => $holdingbranch->{branchcode},
1980 set_userenv($holdingbranch);
1982 my $ref_issue = 'Koha::Checkout';
1983 my $issue = AddIssue( $patron_1, $item->barcode );
1985 my ( $error, $question, $alerts );
1987 # AllowReturnToBranch == homebranch
1988 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1989 ## Can be issued from homebranch
1990 set_userenv($homebranch);
1991 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
1992 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1993 ## Can be issued from holdinbranch
1994 set_userenv($holdingbranch);
1995 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
1996 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1997 ## Can be issued from another branch
1998 set_userenv($otherbranch);
1999 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
2000 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2002 # AllowReturnToBranch == holdinbranch
2003 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2004 ## Cannot be issued from homebranch
2005 set_userenv($homebranch);
2006 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
2007 ## Can be issued from holdingbranch
2008 set_userenv($holdingbranch);
2009 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
2010 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2011 ## Cannot be issued from another branch
2012 set_userenv($otherbranch);
2013 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
2015 # AllowReturnToBranch == homebranch
2016 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2017 ## Can be issued from homebranch
2018 set_userenv($homebranch);
2019 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
2020 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2021 ## Cannot be issued from holdinbranch
2022 set_userenv($holdingbranch);
2023 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
2024 ## Cannot be issued from another branch
2025 set_userenv($otherbranch);
2026 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
2027 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2030 subtest 'AddIssue | recalls' => sub {
2033 t::lib::Mocks::mock_preference("UseRecalls", 1);
2034 t::lib::Mocks::mock_preference("item-level_itypes", 1);
2035 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2036 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2037 my $item = $builder->build_sample_item;
2038 Koha::CirculationRules->set_rules({
2039 branchcode => undef,
2041 categorycode => undef,
2043 recalls_allowed => 10,
2047 # checking out item that they have recalled
2048 my $recall1 = Koha::Recall->new(
2049 { borrowernumber => $patron1->borrowernumber,
2050 biblionumber => $item->biblionumber,
2051 itemnumber => $item->itemnumber,
2052 item_level_recall => 1,
2053 branchcode => $patron1->branchcode,
2056 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall1->recall_id } );
2057 $recall1 = Koha::Recalls->find( $recall1->recall_id );
2058 is( $recall1->fulfilled, 1, 'Recall was fulfilled when patron checked out item' );
2059 AddReturn( $item->barcode, $item->homebranch );
2061 # this item is has a recall request. cancel recall
2062 my $recall2 = Koha::Recall->new(
2063 { borrowernumber => $patron2->borrowernumber,
2064 biblionumber => $item->biblionumber,
2065 itemnumber => $item->itemnumber,
2066 item_level_recall => 1,
2067 branchcode => $patron2->branchcode,
2070 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall2->recall_id, cancel_recall => 'cancel' } );
2071 $recall2 = Koha::Recalls->find( $recall2->recall_id );
2072 is( $recall2->cancelled, 1, 'Recall was cancelled when patron checked out item' );
2073 AddReturn( $item->barcode, $item->homebranch );
2075 # this item is waiting to fulfill a recall. revert recall
2076 my $recall3 = Koha::Recall->new(
2077 { borrowernumber => $patron2->borrowernumber,
2078 biblionumber => $item->biblionumber,
2079 itemnumber => $item->itemnumber,
2080 item_level_recall => 1,
2081 branchcode => $patron2->branchcode,
2084 $recall3->set_waiting;
2085 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall3->recall_id, cancel_recall => 'revert' } );
2086 $recall3 = Koha::Recalls->find( $recall3->recall_id );
2087 is( $recall3->requested, 1, 'Recall was reverted from waiting when patron checked out item' );
2088 AddReturn( $item->barcode, $item->homebranch );
2092 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
2095 my $library = $builder->build( { source => 'Branch' } );
2096 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2097 my $item_1 = $builder->build_sample_item(
2099 library => $library->{branchcode},
2102 my $item_2 = $builder->build_sample_item(
2104 library => $library->{branchcode},
2107 Koha::CirculationRules->set_rules(
2109 categorycode => undef,
2111 branchcode => $library->{branchcode},
2113 reservesallowed => 25,
2115 lengthunit => 'days',
2116 renewalsallowed => 1,
2118 norenewalbefore => undef,
2128 my ( $error, $question, $alerts );
2130 # Patron cannot issue item_1, they have overdues
2131 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
2132 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, $yesterday ); # Add an overdue
2134 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
2135 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2136 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
2137 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
2139 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
2140 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2141 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2142 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
2144 # Patron cannot issue item_1, they are debarred
2145 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
2146 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
2147 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2148 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2149 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
2151 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
2152 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2153 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2154 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
2157 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
2160 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2161 my $patron_category_x = $builder->build_object(
2163 class => 'Koha::Patron::Categories',
2164 value => { category_type => 'X' }
2167 my $patron = $builder->build_object(
2169 class => 'Koha::Patrons',
2171 categorycode => $patron_category_x->categorycode,
2172 gonenoaddress => undef,
2179 my $item_1 = $builder->build_sample_item(
2181 library => $library->{branchcode},
2185 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
2186 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
2188 # TODO There are other tests to provide here
2191 subtest 'MultipleReserves' => sub {
2194 my $biblio = $builder->build_sample_biblio();
2196 my $branch = $library2->{branchcode};
2198 my $item_1 = $builder->build_sample_item(
2200 biblionumber => $biblio->biblionumber,
2202 replacementprice => 12.00,
2207 my $item_2 = $builder->build_sample_item(
2209 biblionumber => $biblio->biblionumber,
2211 replacementprice => 12.00,
2218 my $resdate = undef;
2219 my $expdate = undef;
2221 my $checkitem = undef;
2224 my %renewing_borrower_data = (
2225 firstname => 'John',
2226 surname => 'Renewal',
2227 categorycode => $patron_category->{categorycode},
2228 branchcode => $branch,
2230 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
2231 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
2232 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
2233 my $datedue = dt_from_string( $issue->date_due() );
2234 is (defined $issue->date_due(), 1, "item 1 checked out");
2235 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
2237 my %reserving_borrower_data1 = (
2238 firstname => 'Katrin',
2239 surname => 'Reservation',
2240 categorycode => $patron_category->{categorycode},
2241 branchcode => $branch,
2243 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
2246 branchcode => $branch,
2247 borrowernumber => $reserving_borrowernumber1,
2248 biblionumber => $biblio->biblionumber,
2249 priority => $priority,
2250 reservation_date => $resdate,
2251 expiration_date => $expdate,
2253 itemnumber => $checkitem,
2258 my %reserving_borrower_data2 = (
2259 firstname => 'Kirk',
2260 surname => 'Reservation',
2261 categorycode => $patron_category->{categorycode},
2262 branchcode => $branch,
2264 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
2267 branchcode => $branch,
2268 borrowernumber => $reserving_borrowernumber2,
2269 biblionumber => $biblio->biblionumber,
2270 priority => $priority,
2271 reservation_date => $resdate,
2272 expiration_date => $expdate,
2274 itemnumber => $checkitem,
2280 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2281 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2284 my $item_3 = $builder->build_sample_item(
2286 biblionumber => $biblio->biblionumber,
2288 replacementprice => 12.00,
2294 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2295 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2299 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2302 my $library = $builder->build( { source => 'Branch' } );
2303 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2305 my $biblionumber = $builder->build_sample_biblio(
2307 branchcode => $library->{branchcode},
2310 my $item_1 = $builder->build_sample_item(
2312 biblionumber => $biblionumber,
2313 library => $library->{branchcode},
2317 my $item_2 = $builder->build_sample_item(
2319 biblionumber => $biblionumber,
2320 library => $library->{branchcode},
2324 Koha::CirculationRules->set_rules(
2326 categorycode => undef,
2328 branchcode => $library->{branchcode},
2330 reservesallowed => 25,
2332 lengthunit => 'days',
2333 renewalsallowed => 1,
2335 norenewalbefore => undef,
2344 my ( $error, $question, $alerts );
2345 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, dt_from_string->add( days => 1 ) );
2347 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2348 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2350 { error => $error, alerts => $alerts },
2351 { error => {}, alerts => {} },
2352 'No error or alert should be raised'
2354 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2356 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2357 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2359 { error => $error, question => $question, alerts => $alerts },
2360 { error => {}, question => {}, alerts => {} },
2361 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2364 # Add a subscription
2365 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2367 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2368 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2370 { error => $error, question => $question, alerts => $alerts },
2371 { error => {}, question => {}, alerts => {} },
2372 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2375 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2376 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2378 { error => $error, question => $question, alerts => $alerts },
2379 { error => {}, question => {}, alerts => {} },
2380 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2384 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2387 my $library = $builder->build( { source => 'Branch' } );
2388 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2391 my $biblionumber = $builder->build_sample_biblio(
2393 branchcode => $library->{branchcode},
2396 my $item_1 = $builder->build_sample_item(
2398 biblionumber => $biblionumber,
2399 library => $library->{branchcode},
2402 my $item_2 = $builder->build_sample_item(
2404 biblionumber => $biblionumber,
2405 library => $library->{branchcode},
2409 # And the circulation rule
2410 Koha::CirculationRules->search->delete;
2411 Koha::CirculationRules->set_rules(
2413 categorycode => undef,
2415 branchcode => undef,
2418 firstremind => 1, # 1 day of grace
2419 finedays => 2, # 2 days of fine per day of overdue
2420 lengthunit => 'days',
2425 # Patron cannot issue item_1, they have overdues
2426 my $now = dt_from_string;
2427 my $five_days_ago = $now->clone->subtract( days => 5 );
2428 my $ten_days_ago = $now->clone->subtract( days => 10 );
2429 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2430 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2431 ; # Add another overdue
2433 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2434 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2435 my $debarments = Koha::Patron::Debarments::GetDebarments(
2436 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2437 is( scalar(@$debarments), 1 );
2439 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2440 # Same for the others
2441 my $expected_expiration = output_pref(
2443 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2444 dateformat => 'sql',
2448 is( $debarments->[0]->{expiration}, $expected_expiration );
2450 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2451 $debarments = Koha::Patron::Debarments::GetDebarments(
2452 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2453 is( scalar(@$debarments), 1 );
2454 $expected_expiration = output_pref(
2456 dt => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2457 dateformat => 'sql',
2461 is( $debarments->[0]->{expiration}, $expected_expiration );
2463 Koha::Patron::Debarments::DelUniqueDebarment(
2464 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2466 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2467 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2468 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2469 ; # Add another overdue
2470 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2471 $debarments = Koha::Patron::Debarments::GetDebarments(
2472 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2473 is( scalar(@$debarments), 1 );
2474 $expected_expiration = output_pref(
2476 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2477 dateformat => 'sql',
2481 is( $debarments->[0]->{expiration}, $expected_expiration );
2483 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2484 $debarments = Koha::Patron::Debarments::GetDebarments(
2485 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2486 is( scalar(@$debarments), 1 );
2487 $expected_expiration = output_pref(
2489 dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2490 dateformat => 'sql',
2494 is( $debarments->[0]->{expiration}, $expected_expiration );
2497 subtest 'AddReturn + suspension_chargeperiod' => sub {
2500 my $library = $builder->build( { source => 'Branch' } );
2501 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2503 my $biblionumber = $builder->build_sample_biblio(
2505 branchcode => $library->{branchcode},
2508 my $item_1 = $builder->build_sample_item(
2510 biblionumber => $biblionumber,
2511 library => $library->{branchcode},
2515 # And the issuing rule
2516 Koha::CirculationRules->search->delete;
2517 Koha::CirculationRules->set_rules(
2519 categorycode => '*',
2524 firstremind => 0, # 0 day of grace
2525 finedays => 2, # 2 days of fine per day of overdue
2526 suspension_chargeperiod => 1,
2527 lengthunit => 'days',
2532 my $now = dt_from_string;
2533 my $five_days_ago = $now->clone->subtract( days => 5 );
2534 # We want to charge 2 days every day, without grace
2535 # With 5 days of overdue: 5 * Z
2536 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2537 test_debarment_on_checkout(
2540 library => $library,
2542 due_date => $five_days_ago,
2543 expiration_date => $expected_expiration,
2547 # Same with undef firstremind
2548 Koha::CirculationRules->search->delete;
2549 Koha::CirculationRules->set_rules(
2551 categorycode => '*',
2556 firstremind => undef, # 0 day of grace
2557 finedays => 2, # 2 days of fine per day of overdue
2558 suspension_chargeperiod => 1,
2559 lengthunit => 'days',
2564 my $now = dt_from_string;
2565 my $five_days_ago = $now->clone->subtract( days => 5 );
2566 # We want to charge 2 days every day, without grace
2567 # With 5 days of overdue: 5 * Z
2568 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2569 test_debarment_on_checkout(
2572 library => $library,
2574 due_date => $five_days_ago,
2575 expiration_date => $expected_expiration,
2579 # We want to charge 2 days every 2 days, without grace
2580 # With 5 days of overdue: (5 * 2) / 2
2581 Koha::CirculationRules->set_rule(
2583 categorycode => undef,
2584 branchcode => undef,
2586 rule_name => 'suspension_chargeperiod',
2591 $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2592 test_debarment_on_checkout(
2595 library => $library,
2597 due_date => $five_days_ago,
2598 expiration_date => $expected_expiration,
2602 # We want to charge 2 days every 3 days, with 1 day of grace
2603 # With 5 days of overdue: ((5-1) / 3 ) * 2
2604 Koha::CirculationRules->set_rules(
2606 categorycode => undef,
2607 branchcode => undef,
2610 suspension_chargeperiod => 3,
2615 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2616 test_debarment_on_checkout(
2619 library => $library,
2621 due_date => $five_days_ago,
2622 expiration_date => $expected_expiration,
2626 # Use finesCalendar to know if holiday must be skipped to calculate the due date
2627 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2628 Koha::CirculationRules->set_rules(
2630 categorycode => undef,
2631 branchcode => undef,
2635 suspension_chargeperiod => 1,
2640 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2641 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2643 # Adding a holiday 2 days ago
2644 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2645 my $two_days_ago = $now->clone->subtract( days => 2 );
2646 $calendar->insert_single_holiday(
2647 day => $two_days_ago->day,
2648 month => $two_days_ago->month,
2649 year => $two_days_ago->year,
2650 title => 'holidayTest-2d',
2651 description => 'holidayDesc 2 days ago'
2653 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2654 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2655 test_debarment_on_checkout(
2658 library => $library,
2660 due_date => $five_days_ago,
2661 expiration_date => $expected_expiration,
2665 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2666 my $two_days_ahead = $now->clone->add( days => 2 );
2667 $calendar->insert_single_holiday(
2668 day => $two_days_ahead->day,
2669 month => $two_days_ahead->month,
2670 year => $two_days_ahead->year,
2671 title => 'holidayTest+2d',
2672 description => 'holidayDesc 2 days ahead'
2675 # Same as above, but we should skip D+2
2676 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2677 test_debarment_on_checkout(
2680 library => $library,
2682 due_date => $five_days_ago,
2683 expiration_date => $expected_expiration,
2687 # Adding another holiday, day of expiration date
2688 my $expected_expiration_dt = dt_from_string($expected_expiration);
2689 $calendar->insert_single_holiday(
2690 day => $expected_expiration_dt->day,
2691 month => $expected_expiration_dt->month,
2692 year => $expected_expiration_dt->year,
2693 title => 'holidayTest_exp',
2694 description => 'holidayDesc on expiration date'
2696 # Expiration date will be the day after
2697 test_debarment_on_checkout(
2700 library => $library,
2702 due_date => $five_days_ago,
2703 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2707 test_debarment_on_checkout(
2710 library => $library,
2712 return_date => $now->clone->add(days => 5),
2713 expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2717 test_debarment_on_checkout(
2720 library => $library,
2722 due_date => $now->clone->add(days => 1),
2723 return_date => $now->clone->add(days => 5),
2724 expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2730 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2733 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2734 my $patron1 = $builder->build_object(
2736 class => 'Koha::Patrons',
2738 library => $library->branchcode,
2739 categorycode => $patron_category->{categorycode}
2743 my $patron2 = $builder->build_object(
2745 class => 'Koha::Patrons',
2747 library => $library->branchcode,
2748 categorycode => $patron_category->{categorycode}
2753 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2755 my $item = $builder->build_sample_item(
2757 library => $library->branchcode,
2761 my ( $error, $question, $alerts );
2762 my $issue = AddIssue( $patron1->unblessed, $item->barcode );
2764 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2765 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2766 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' );
2768 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2769 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2770 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' );
2772 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2776 subtest 'AddReturn | is_overdue' => sub {
2779 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2780 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2781 t::lib::Mocks::mock_preference('finesMode', 'production');
2782 t::lib::Mocks::mock_preference('MaxFine', '100');
2784 my $library = $builder->build( { source => 'Branch' } );
2785 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2786 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2787 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2789 my $item = $builder->build_sample_item(
2791 library => $library->{branchcode},
2792 replacementprice => 7
2796 Koha::CirculationRules->search->delete;
2797 Koha::CirculationRules->set_rules(
2799 categorycode => undef,
2801 branchcode => undef,
2804 lengthunit => 'days',
2805 fine => 1, # Charge 1 every day of overdue
2811 my $now = dt_from_string;
2812 my $one_day_ago = $now->clone->subtract( days => 1 );
2813 my $two_days_ago = $now->clone->subtract( days => 2 );
2814 my $five_days_ago = $now->clone->subtract( days => 5 );
2815 my $ten_days_ago = $now->clone->subtract( days => 10 );
2816 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2818 # No return date specified, today will be used => 10 days overdue charged
2819 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2820 AddReturn( $item->barcode, $library->{branchcode} );
2821 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2822 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2824 # specify return date 5 days before => no overdue charged
2825 AddIssue( $patron->unblessed, $item->barcode, $five_days_ago ); # date due was 5d ago
2826 AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
2827 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2828 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2830 # specify return date 5 days later => 5 days overdue charged
2831 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2832 AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
2833 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2834 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2836 # specify return date 5 days later, specify exemptfine => no overdue charge
2837 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2838 AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago );
2839 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2840 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2842 subtest 'bug 22877 | Lost item return' => sub {
2846 my $issue = AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2848 # Fake fines cronjob on this checkout
2850 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2851 $ten_days_ago, $now );
2854 issue_id => $issue->issue_id,
2855 itemnumber => $item->itemnumber,
2856 borrowernumber => $patron->borrowernumber,
2858 due => output_pref($ten_days_ago)
2861 is( int( $patron->account->balance() ),
2862 10, "Overdue fine of 10 days overdue" );
2864 # Fake longoverdue with charge and not marking returned
2865 LostItem( $item->itemnumber, 'cronjob', 0 );
2866 is( int( $patron->account->balance() ),
2867 17, "Lost fine of 7 plus 10 days overdue" );
2869 # Now we return it today
2870 AddReturn( $item->barcode, $library->{branchcode} );
2871 is( int( $patron->account->balance() ),
2872 17, "Should have a single 10 days overdue fine and lost charge" );
2875 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2878 subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
2882 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2884 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
2886 # Fake fines cronjob on this checkout
2888 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2889 $one_day_ago, $now );
2892 issue_id => $issue->issue_id,
2893 itemnumber => $item->itemnumber,
2894 borrowernumber => $patron->borrowernumber,
2896 due => output_pref($one_day_ago)
2899 is( int( $patron->account->balance() ),
2900 1, "Overdue fine of 1 day overdue" );
2902 # Backdated return (dropbox mode example - charge should be removed)
2903 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
2904 is( int( $patron->account->balance() ),
2905 0, "Overdue fine should be annulled" );
2906 my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2907 is( $lines->count, 0, "Overdue fine accountline has been removed");
2909 $issue = AddIssue( $patron->unblessed, $item->barcode, $two_days_ago ); # date due was 2d ago
2911 # Fake fines cronjob on this checkout
2913 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2914 $two_days_ago, $now );
2917 issue_id => $issue->issue_id,
2918 itemnumber => $item->itemnumber,
2919 borrowernumber => $patron->borrowernumber,
2921 due => output_pref($one_day_ago)
2924 is( int( $patron->account->balance() ),
2925 2, "Overdue fine of 2 days overdue" );
2927 # Payment made against fine
2928 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2929 my $debit = $lines->next;
2930 my $credit = $patron->account->add_credit(
2934 interface => 'test',
2937 $credit->apply( { debits => [$debit] } );
2939 is( int( $patron->account->balance() ),
2940 0, "Overdue fine should be paid off" );
2941 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2942 is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
2943 my $line = $lines->next;
2944 is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
2945 is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
2947 # Backdated return (dropbox mode example - charge should be removed)
2948 AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
2949 is( int( $patron->account->balance() ),
2950 -1, "Refund credit has been applied" );
2951 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
2952 is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
2954 $line = $lines->next;
2955 is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
2956 is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
2957 is($line->status,'RETURNED', "Overdue fine is fixed");
2958 $line = $lines->next;
2959 is($line->amount+0,-2, "Original payment amount remains as 2");
2960 is($line->amountoutstanding+0,0, "Original payment remains applied");
2961 $line = $lines->next;
2962 is($line->amount+0,-1, "Refund amount correctly set to 1");
2963 is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
2966 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2969 subtest 'bug 25417 | backdated return + exemptfine' => sub {
2973 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2975 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
2977 # Fake fines cronjob on this checkout
2979 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2980 $one_day_ago, $now );
2983 issue_id => $issue->issue_id,
2984 itemnumber => $item->itemnumber,
2985 borrowernumber => $patron->borrowernumber,
2987 due => output_pref($one_day_ago)
2990 is( int( $patron->account->balance() ),
2991 1, "Overdue fine of 1 day overdue" );
2993 # Backdated return (dropbox mode example - charge should no longer exist)
2994 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
2995 is( int( $patron->account->balance() ),
2996 0, "Overdue fine should be annulled" );
2999 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3002 subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
3005 t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
3007 my $due_date = dt_from_string;
3008 my $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
3013 issue_id => $issue->issue_id,
3014 itemnumber => $item->itemnumber,
3015 borrowernumber => $patron->borrowernumber,
3017 due => output_pref($due_date)
3020 is( $patron->account->balance(),
3021 0.25, 'Overdue fine of $0.25 recorded' );
3023 # Backdate return to exact due date and time
3024 my ( undef, $message ) =
3025 AddReturn( $item->barcode, $library->{branchcode},
3029 Koha::Account::Lines->find( { issue_id => $issue->id } );
3030 ok( !$accountline, 'accountline removed as expected' );
3033 $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
3038 issue_id => $issue->issue_id,
3039 itemnumber => $item->itemnumber,
3040 borrowernumber => $patron->borrowernumber,
3042 due => output_pref($due_date)
3045 is( $patron->account->balance(),
3046 0.25, 'Overdue fine of $0.25 recorded' );
3048 # Partial pay accruing fine
3049 my $lines = Koha::Account::Lines->search(
3051 borrowernumber => $patron->borrowernumber,
3052 issue_id => $issue->id
3055 my $debit = $lines->next;
3056 my $credit = $patron->account->add_credit(
3060 interface => 'test',
3063 $credit->apply( { debits => [$debit] } );
3065 is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
3067 # Backdate return to exact due date and time
3068 ( undef, $message ) =
3069 AddReturn( $item->barcode, $library->{branchcode},
3072 $lines = Koha::Account::Lines->search(
3074 borrowernumber => $patron->borrowernumber,
3075 issue_id => $issue->id
3078 $accountline = $lines->next;
3079 is( $accountline->amountoutstanding + 0,
3080 0, 'Partially paid fee amount outstanding was reduced to 0' );
3081 is( $accountline->amount + 0,
3082 0, 'Partially paid fee amount was reduced to 0' );
3083 is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
3086 Koha::Account::Lines->search(
3087 { borrowernumber => $patron->borrowernumber } )->delete;
3090 subtest 'enh 23091 | Lost item return policies' => sub {
3093 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3095 my $branchcode_false =
3096 $builder->build( { source => 'Branch' } )->{branchcode};
3097 my $specific_rule_false = $builder->build(
3099 source => 'CirculationRule',
3101 branchcode => $branchcode_false,
3102 categorycode => undef,
3104 rule_name => 'lostreturn',
3109 my $branchcode_refund =
3110 $builder->build( { source => 'Branch' } )->{branchcode};
3111 my $specific_rule_refund = $builder->build(
3113 source => 'CirculationRule',
3115 branchcode => $branchcode_refund,
3116 categorycode => undef,
3118 rule_name => 'lostreturn',
3119 rule_value => 'refund'
3123 my $branchcode_restore =
3124 $builder->build( { source => 'Branch' } )->{branchcode};
3125 my $specific_rule_restore = $builder->build(
3127 source => 'CirculationRule',
3129 branchcode => $branchcode_restore,
3130 categorycode => undef,
3132 rule_name => 'lostreturn',
3133 rule_value => 'restore'
3137 my $branchcode_charge =
3138 $builder->build( { source => 'Branch' } )->{branchcode};
3139 my $specific_rule_charge = $builder->build(
3141 source => 'CirculationRule',
3143 branchcode => $branchcode_charge,
3144 categorycode => undef,
3146 rule_name => 'lostreturn',
3147 rule_value => 'charge'
3152 my $replacement_amount = 99.00;
3153 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
3154 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
3155 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
3156 t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 );
3157 t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
3159 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
3162 subtest 'lostreturn | false' => sub {
3165 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
3167 my $item = $builder->build_sample_item(
3169 replacementprice => $replacement_amount
3174 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3176 # Fake fines cronjob on this checkout
3178 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3179 $ten_days_ago, $now );
3182 issue_id => $issue->issue_id,
3183 itemnumber => $item->itemnumber,
3184 borrowernumber => $patron->borrowernumber,
3186 due => output_pref($ten_days_ago)
3189 my $overdue_fees = Koha::Account::Lines->search(
3191 borrowernumber => $patron->id,
3192 itemnumber => $item->itemnumber,
3193 debit_type_code => 'OVERDUE'
3196 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3197 my $overdue_fee = $overdue_fees->next;
3198 is( $overdue_fee->amount + 0,
3199 10, 'The right OVERDUE amount is generated' );
3200 is( $overdue_fee->amountoutstanding + 0,
3202 'The right OVERDUE amountoutstanding is generated' );
3204 # Simulate item marked as lost
3205 $item->itemlost(3)->store;
3206 C4::Circulation::LostItem( $item->itemnumber, 1 );
3208 my $lost_fee_lines = Koha::Account::Lines->search(
3210 borrowernumber => $patron->id,
3211 itemnumber => $item->itemnumber,
3212 debit_type_code => 'LOST'
3215 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3216 my $lost_fee_line = $lost_fee_lines->next;
3217 is( $lost_fee_line->amount + 0,
3218 $replacement_amount, 'The right LOST amount is generated' );
3219 is( $lost_fee_line->amountoutstanding + 0,
3220 $replacement_amount,
3221 'The right LOST amountoutstanding is generated' );
3222 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3225 my ( $returned, $message ) =
3226 AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
3228 $overdue_fee->discard_changes;
3229 is( $overdue_fee->amount + 0,
3230 10, 'The OVERDUE amount is left intact' );
3231 is( $overdue_fee->amountoutstanding + 0,
3233 'The OVERDUE amountoutstanding is left intact' );
3235 $lost_fee_line->discard_changes;
3236 is( $lost_fee_line->amount + 0,
3237 $replacement_amount, 'The LOST amount is left intact' );
3238 is( $lost_fee_line->amountoutstanding + 0,
3239 $replacement_amount,
3240 'The LOST amountoutstanding is left intact' );
3241 # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
3242 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3245 subtest 'lostreturn | refund' => sub {
3248 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
3250 my $item = $builder->build_sample_item(
3252 replacementprice => $replacement_amount
3257 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3259 # Fake fines cronjob on this checkout
3261 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3262 $ten_days_ago, $now );
3265 issue_id => $issue->issue_id,
3266 itemnumber => $item->itemnumber,
3267 borrowernumber => $patron->borrowernumber,
3269 due => output_pref($ten_days_ago)
3272 my $overdue_fees = Koha::Account::Lines->search(
3274 borrowernumber => $patron->id,
3275 itemnumber => $item->itemnumber,
3276 debit_type_code => 'OVERDUE'
3279 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3280 my $overdue_fee = $overdue_fees->next;
3281 is( $overdue_fee->amount + 0,
3282 10, 'The right OVERDUE amount is generated' );
3283 is( $overdue_fee->amountoutstanding + 0,
3285 'The right OVERDUE amountoutstanding is generated' );
3287 # Simulate item marked as lost
3288 $item->itemlost(3)->store;
3289 C4::Circulation::LostItem( $item->itemnumber, 1 );
3291 my $lost_fee_lines = Koha::Account::Lines->search(
3293 borrowernumber => $patron->id,
3294 itemnumber => $item->itemnumber,
3295 debit_type_code => 'LOST'
3298 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3299 my $lost_fee_line = $lost_fee_lines->next;
3300 is( $lost_fee_line->amount + 0,
3301 $replacement_amount, 'The right LOST amount is generated' );
3302 is( $lost_fee_line->amountoutstanding + 0,
3303 $replacement_amount,
3304 'The right LOST amountoutstanding is generated' );
3305 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3307 # Return the lost item
3308 my ( undef, $message ) =
3309 AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
3311 $overdue_fee->discard_changes;
3312 is( $overdue_fee->amount + 0,
3313 10, 'The OVERDUE amount is left intact' );
3314 is( $overdue_fee->amountoutstanding + 0,
3316 'The OVERDUE amountoutstanding is left intact' );
3318 $lost_fee_line->discard_changes;
3319 is( $lost_fee_line->amount + 0,
3320 $replacement_amount, 'The LOST amount is left intact' );
3321 is( $lost_fee_line->amountoutstanding + 0,
3323 'The LOST amountoutstanding is refunded' );
3324 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3327 subtest 'lostreturn | restore' => sub {
3330 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
3332 my $item = $builder->build_sample_item(
3334 replacementprice => $replacement_amount
3339 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode , $ten_days_ago);
3341 # Fake fines cronjob on this checkout
3343 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3344 $ten_days_ago, $now );
3347 issue_id => $issue->issue_id,
3348 itemnumber => $item->itemnumber,
3349 borrowernumber => $patron->borrowernumber,
3351 due => output_pref($ten_days_ago)
3354 my $overdue_fees = Koha::Account::Lines->search(
3356 borrowernumber => $patron->id,
3357 itemnumber => $item->itemnumber,
3358 debit_type_code => 'OVERDUE'
3361 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3362 my $overdue_fee = $overdue_fees->next;
3363 is( $overdue_fee->amount + 0,
3364 10, 'The right OVERDUE amount is generated' );
3365 is( $overdue_fee->amountoutstanding + 0,
3367 'The right OVERDUE amountoutstanding is generated' );
3369 # Simulate item marked as lost
3370 $item->itemlost(3)->store;
3371 C4::Circulation::LostItem( $item->itemnumber, 1 );
3373 my $lost_fee_lines = Koha::Account::Lines->search(
3375 borrowernumber => $patron->id,
3376 itemnumber => $item->itemnumber,
3377 debit_type_code => 'LOST'
3380 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3381 my $lost_fee_line = $lost_fee_lines->next;
3382 is( $lost_fee_line->amount + 0,
3383 $replacement_amount, 'The right LOST amount is generated' );
3384 is( $lost_fee_line->amountoutstanding + 0,
3385 $replacement_amount,
3386 'The right LOST amountoutstanding is generated' );
3387 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3389 # Simulate refunding overdue fees upon marking item as lost
3390 my $overdue_forgive = $patron->account->add_credit(
3393 user_id => $manager->borrowernumber,
3394 library_id => $branchcode_restore,
3395 interface => 'test',
3397 item_id => $item->itemnumber
3400 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3401 $overdue_fee->discard_changes;
3402 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3405 my ( undef, $message ) =
3406 AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
3408 $overdue_fee->discard_changes;
3409 is( $overdue_fee->amount + 0,
3410 10, 'The OVERDUE amount is left intact' );
3411 is( $overdue_fee->amountoutstanding + 0,
3413 'The OVERDUE amountoutstanding is restored' );
3415 $lost_fee_line->discard_changes;
3416 is( $lost_fee_line->amount + 0,
3417 $replacement_amount, 'The LOST amount is left intact' );
3418 is( $lost_fee_line->amountoutstanding + 0,
3420 'The LOST amountoutstanding is refunded' );
3421 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3424 subtest 'lostreturn | charge' => sub {
3427 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
3429 my $item = $builder->build_sample_item(
3431 replacementprice => $replacement_amount
3436 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3438 # Fake fines cronjob on this checkout
3440 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3441 $ten_days_ago, $now );
3444 issue_id => $issue->issue_id,
3445 itemnumber => $item->itemnumber,
3446 borrowernumber => $patron->borrowernumber,
3448 due => output_pref($ten_days_ago)
3451 my $overdue_fees = Koha::Account::Lines->search(
3453 borrowernumber => $patron->id,
3454 itemnumber => $item->itemnumber,
3455 debit_type_code => 'OVERDUE'
3458 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3459 my $overdue_fee = $overdue_fees->next;
3460 is( $overdue_fee->amount + 0,
3461 10, 'The right OVERDUE amount is generated' );
3462 is( $overdue_fee->amountoutstanding + 0,
3464 'The right OVERDUE amountoutstanding is generated' );
3466 # Simulate item marked as lost
3467 $item->itemlost(3)->store;
3468 C4::Circulation::LostItem( $item->itemnumber, 1 );
3470 my $lost_fee_lines = Koha::Account::Lines->search(
3472 borrowernumber => $patron->id,
3473 itemnumber => $item->itemnumber,
3474 debit_type_code => 'LOST'
3477 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3478 my $lost_fee_line = $lost_fee_lines->next;
3479 is( $lost_fee_line->amount + 0,
3480 $replacement_amount, 'The right LOST amount is generated' );
3481 is( $lost_fee_line->amountoutstanding + 0,
3482 $replacement_amount,
3483 'The right LOST amountoutstanding is generated' );
3484 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3486 # Simulate refunding overdue fees upon marking item as lost
3487 my $overdue_forgive = $patron->account->add_credit(
3490 user_id => $manager->borrowernumber,
3491 library_id => $branchcode_charge,
3492 interface => 'test',
3494 item_id => $item->itemnumber
3497 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3498 $overdue_fee->discard_changes;
3499 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3502 my ( undef, $message ) =
3503 AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
3505 $lost_fee_line->discard_changes;
3506 is( $lost_fee_line->amount + 0,
3507 $replacement_amount, 'The LOST amount is left intact' );
3508 is( $lost_fee_line->amountoutstanding + 0,
3510 'The LOST amountoutstanding is refunded' );
3511 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3513 $overdue_fees = Koha::Account::Lines->search(
3515 borrowernumber => $patron->id,
3516 itemnumber => $item->itemnumber,
3517 debit_type_code => 'OVERDUE'
3520 order_by => { '-asc' => 'accountlines_id'}
3523 is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
3524 $overdue_fee = $overdue_fees->next;
3525 is( $overdue_fee->amount + 0,
3526 10, 'The original OVERDUE amount is left intact' );
3527 is( $overdue_fee->amountoutstanding + 0,
3529 'The original OVERDUE amountoutstanding is left as forgiven' );
3530 $overdue_fee = $overdue_fees->next;
3531 is( $overdue_fee->amount + 0,
3532 5, 'The new OVERDUE amount is correct for the backdated return' );
3533 is( $overdue_fee->amountoutstanding + 0,
3535 'The new OVERDUE amountoutstanding is correct for the backdated return' );
3540 subtest '_FixOverduesOnReturn' => sub {
3543 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3544 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3546 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3548 my $branchcode = $library2->{branchcode};
3550 my $item = $builder->build_sample_item(
3552 biblionumber => $biblio->biblionumber,
3553 library => $branchcode,
3554 replacementprice => 99.00,
3559 my $patron = $builder->build( { source => 'Borrower' } );
3561 ## Start with basic call, should just close out the open fine
3562 my $accountline = Koha::Account::Line->new(
3564 borrowernumber => $patron->{borrowernumber},
3565 debit_type_code => 'OVERDUE',
3566 status => 'UNRETURNED',
3567 itemnumber => $item->itemnumber,
3569 amountoutstanding => 99.00,
3570 interface => 'test',
3574 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
3576 $accountline->_result()->discard_changes();
3578 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
3579 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3580 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3582 ## Run again, with exemptfine enabled
3585 debit_type_code => 'OVERDUE',
3586 status => 'UNRETURNED',
3587 amountoutstanding => 99.00,
3591 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3593 $accountline->_result()->discard_changes();
3594 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'APPLY' })->next();
3596 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
3597 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3598 is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
3599 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
3600 is( $offset->amount + 0, -99, "Amount of offset is correct" );
3601 my $credit = $offset->credit;
3602 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
3603 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
3604 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
3606 # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
3609 debit_type_code => 'OVERDUE',
3610 status => 'UNRETURNED',
3611 amountoutstanding => 0.00,
3616 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3618 $accountline->_result()->discard_changes();
3619 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'CREATE' })->next();
3620 is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
3621 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3622 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3625 subtest 'Set waiting flag' => sub {
3628 my $library_1 = $builder->build( { source => 'Branch' } );
3629 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3630 my $library_2 = $builder->build( { source => 'Branch' } );
3631 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3633 my $item = $builder->build_sample_item(
3635 library => $library_1->{branchcode},
3639 set_userenv( $library_2 );
3640 my $reserve_id = AddReserve(
3642 branchcode => $library_2->{branchcode},
3643 borrowernumber => $patron_2->{borrowernumber},
3644 biblionumber => $item->biblionumber,
3646 itemnumber => $item->itemnumber,
3650 set_userenv( $library_1 );
3651 my $do_transfer = 1;
3652 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3653 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3654 my $hold = Koha::Holds->find( $reserve_id );
3655 is( $hold->found, 'T', 'Hold is in transit' );
3657 my ( $status ) = CheckReserves($item->itemnumber);
3658 is( $status, 'Transferred', 'Hold is not waiting yet');
3660 set_userenv( $library_2 );
3662 AddReturn( $item->barcode, $library_2->{branchcode} );
3663 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3664 $hold = Koha::Holds->find( $reserve_id );
3665 is( $hold->found, 'W', 'Hold is waiting' );
3666 ( $status ) = CheckReserves($item->itemnumber);
3667 is( $status, 'Waiting', 'Now the hold is waiting');
3669 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
3670 set_userenv( $library_1 );
3671 (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
3672 $hold = Koha::Holds->find( $reserve_id );
3673 is( $hold->found, undef, 'Hold is no longer marked waiting' );
3674 is( $hold->priority, 1, "Hold is now priority one again");
3675 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
3676 is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
3677 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
3678 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
3679 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
3682 subtest 'Cancel transfers on lost items' => sub {
3685 my $library_to = $builder->build_object( { class => 'Koha::Libraries' } );
3686 my $item = $builder->build_sample_item();
3687 my $holdingbranch = $item->holdingbranch;
3688 # Historic transfer (datearrived is defined)
3689 my $old_transfer = $builder->build_object(
3691 class => 'Koha::Item::Transfers',
3693 itemnumber => $item->itemnumber,
3694 frombranch => $holdingbranch,
3695 tobranch => $library_to->branchcode,
3697 datesent => \'NOW()',
3698 datearrived => \'NOW()',
3699 datecancelled => undef,
3700 daterequested => \'NOW()'
3704 # Queued transfer (datesent is undefined)
3705 my $transfer_1 = $builder->build_object(
3707 class => 'Koha::Item::Transfers',
3709 itemnumber => $item->itemnumber,
3710 frombranch => $holdingbranch,
3711 tobranch => $library_to->branchcode,
3714 datearrived => undef,
3715 datecancelled => undef,
3716 daterequested => \'NOW()'
3720 # In transit transfer (datesent is defined, datearrived and datecancelled are both undefined)
3721 my $transfer_2 = $builder->build_object(
3723 class => 'Koha::Item::Transfers',
3725 itemnumber => $item->itemnumber,
3726 frombranch => $holdingbranch,
3727 tobranch => $library_to->branchcode,
3729 datesent => \'NOW()',
3730 datearrived => undef,
3731 datecancelled => undef,
3732 daterequested => \'NOW()'
3737 # Simulate item being marked as lost
3738 $item->itemlost(1)->store;
3739 LostItem( $item->itemnumber, 'test', 1 );
3741 $transfer_1->discard_changes;
3742 isnt($transfer_1->datecancelled, undef, "Queud transfer was cancelled upon item lost");
3743 is($transfer_1->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
3744 $transfer_2->discard_changes;
3745 isnt($transfer_2->datecancelled, undef, "Active transfer was cancelled upon item lost");
3746 is($transfer_2->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
3747 $old_transfer->discard_changes;
3748 is($old_transfer->datecancelled, undef, "Old transfers are unaffected");
3749 $item->discard_changes;
3750 is($item->holdingbranch, $holdingbranch, "Items holding branch remains unchanged");
3753 subtest 'CanBookBeIssued | is_overdue' => sub {
3756 # Set a simple circ policy
3757 Koha::CirculationRules->set_rules(
3759 categorycode => undef,
3760 branchcode => undef,
3764 reservesallowed => 25,
3766 lengthunit => 'days',
3767 renewalsallowed => 1,
3769 norenewalbefore => undef,
3777 my $now = dt_from_string;
3778 my $five_days_go = output_pref({ dt => $now->clone->add( days => 5 ), dateonly => 1});
3779 my $ten_days_go = output_pref({ dt => $now->clone->add( days => 10), dateonly => 1 });
3780 my $library = $builder->build( { source => 'Branch' } );
3781 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
3783 my $item = $builder->build_sample_item(
3785 library => $library->{branchcode},
3789 my $issue = AddIssue( $patron->unblessed, $item->barcode, $five_days_go ); # date due was 10d ago
3790 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
3791 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
3792 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->barcode,$ten_days_go, undef, undef, undef);
3793 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
3794 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
3797 subtest 'ItemsDeniedRenewal preference' => sub {
3800 C4::Context->set_preference('ItemsDeniedRenewal','');
3802 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
3803 Koha::CirculationRules->set_rules(
3805 categorycode => '*',
3807 branchcode => $idr_lib->branchcode,
3809 reservesallowed => 25,
3811 lengthunit => 'days',
3812 renewalsallowed => 10,
3814 norenewalbefore => undef,
3822 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
3823 homebranch => $idr_lib->branchcode,
3827 itemcallnumber => undef,
3831 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
3832 homebranch => $idr_lib->branchcode,
3835 location => 'NOPROC'
3839 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
3840 branchcode => $idr_lib->branchcode,
3843 my $future = dt_from_string->add( days => 1 );
3844 my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3845 returndate => undef,
3848 borrowernumber => $idr_borrower->borrowernumber,
3849 itemnumber => $deny_book->itemnumber,
3850 onsite_checkout => 0,
3851 date_due => $future,
3854 my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3855 returndate => undef,
3858 borrowernumber => $idr_borrower->borrowernumber,
3859 itemnumber => $allow_book->itemnumber,
3860 onsite_checkout => 0,
3861 date_due => $future,
3867 my ( $idr_mayrenew, $idr_error ) =
3868 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3869 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3870 is( $idr_error, undef, 'Renewal allowed when no rules' );
3872 $idr_rules="withdrawn: [1]";
3874 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3875 ( $idr_mayrenew, $idr_error ) =
3876 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3877 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3878 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3879 ( $idr_mayrenew, $idr_error ) =
3880 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3881 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3882 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3884 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
3886 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3887 ( $idr_mayrenew, $idr_error ) =
3888 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3889 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
3890 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
3891 ( $idr_mayrenew, $idr_error ) =
3892 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3893 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3894 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3896 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
3898 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3899 ( $idr_mayrenew, $idr_error ) =
3900 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3901 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
3902 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
3903 ( $idr_mayrenew, $idr_error ) =
3904 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3905 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3906 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3908 $idr_rules="itemcallnumber: [NULL]";
3909 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3910 ( $idr_mayrenew, $idr_error ) =
3911 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3912 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
3913 $idr_rules="itemcallnumber: ['']";
3914 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3915 ( $idr_mayrenew, $idr_error ) =
3916 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3917 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
3919 $idr_rules="itemnotes: [NULL]";
3920 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3921 ( $idr_mayrenew, $idr_error ) =
3922 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3923 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
3924 $idr_rules="itemnotes: ['']";
3925 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3926 ( $idr_mayrenew, $idr_error ) =
3927 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3928 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
3931 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
3934 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3935 my $library = $builder->build( { source => 'Branch' } );
3936 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3938 my $item = $builder->build_sample_item(
3940 library => $library->{branchcode},
3944 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3945 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3946 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3949 subtest 'CanBookBeIssued | notforloan' => sub {
3952 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
3954 my $library = $builder->build( { source => 'Branch' } );
3955 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3957 my $itemtype = $builder->build(
3959 source => 'Itemtype',
3960 value => { notforloan => undef, }
3963 my $item = $builder->build_sample_item(
3965 library => $library->{branchcode},
3966 itype => $itemtype->{itemtype},
3969 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3971 my ( $issuingimpossible, $needsconfirmation );
3974 subtest 'item-level_itypes = 1' => sub {
3977 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
3978 # Is for loan at item type and item level
3979 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3980 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3981 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3983 # not for loan at item type level
3984 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3985 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3986 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3989 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3990 'Item can not be issued, not for loan at item type level'
3993 # not for loan at item level
3994 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3995 $item->notforloan( 1 )->store;
3996 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3997 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4000 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4001 'Item can not be issued, not for loan at item type level'
4005 subtest 'item-level_itypes = 0' => sub {
4008 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4010 # We set another itemtype for biblioitem
4011 my $itemtype = $builder->build(
4013 source => 'Itemtype',
4014 value => { notforloan => undef, }
4018 # for loan at item type and item level
4019 $item->notforloan(0)->store;
4020 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4021 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4022 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4023 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4025 # not for loan at item type level
4026 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4027 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4028 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4031 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4032 'Item can not be issued, not for loan at item type level'
4035 # not for loan at item level
4036 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4037 $item->notforloan( 1 )->store;
4038 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4039 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4042 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4043 'Item can not be issued, not for loan at item type level'
4047 # TODO test with AllowNotForLoanOverride = 1
4050 subtest 'CanBookBeIssued | recalls' => sub {
4053 t::lib::Mocks::mock_preference("UseRecalls", 1);
4054 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4055 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4056 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4057 my $item = $builder->build_sample_item;
4058 Koha::CirculationRules->set_rules({
4059 branchcode => undef,
4061 categorycode => undef,
4063 recalls_allowed => 10,
4068 my $recall = Koha::Recall->new(
4069 { borrowernumber => $patron1->borrowernumber,
4070 biblionumber => $item->biblionumber,
4071 itemnumber => $item->itemnumber,
4072 item_level_recall => 1,
4073 branchcode => $patron1->branchcode,
4077 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4078 is( $needsconfirmation->{RECALLED}->recall_id, $recall->recall_id, "Another patron has placed an item-level recall on this item" );
4080 $recall->set_cancelled;
4082 # biblio-level recall
4083 $recall = Koha::Recall->new(
4084 { borrowernumber => $patron1->borrowernumber,
4085 biblionumber => $item->biblionumber,
4086 itemnumber => undef,
4087 item_level_recall => 0,
4088 branchcode => $patron1->branchcode,
4092 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4093 is( $needsconfirmation->{RECALLED}->recall_id, $recall->recall_id, "Another patron has placed a biblio-level recall and this item is eligible to fill it" );
4095 $recall->set_cancelled;
4097 # biblio-level recall
4098 $recall = Koha::Recall->new(
4099 { borrowernumber => $patron1->borrowernumber,
4100 biblionumber => $item->biblionumber,
4101 itemnumber => undef,
4102 item_level_recall => 0,
4103 branchcode => $patron1->branchcode,
4106 $recall->set_waiting( { item => $item, expirationdate => dt_from_string() } );
4108 my ( undef, undef, undef, $messages ) = CanBookBeIssued( $patron1, $item->barcode, undef, undef, undef, undef );
4109 is( $messages->{RECALLED}, $recall->recall_id, "This book can be issued by this patron and they have placed a recall" );
4111 $recall->set_cancelled;
4114 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
4117 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
4118 my $item = $builder->build_sample_item(
4120 onloan => '2018-01-01',
4124 AddReturn( $item->barcode, $item->homebranch );
4125 $item->discard_changes; # refresh
4126 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
4129 subtest 'AddReturn | recalls' => sub {
4132 t::lib::Mocks::mock_preference("UseRecalls", 1);
4133 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4134 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4135 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4136 my $item1 = $builder->build_sample_item;
4137 Koha::CirculationRules->set_rules({
4138 branchcode => undef,
4140 categorycode => undef,
4142 recalls_allowed => 10,
4146 # this item can fill a recall with pickup at this branch
4147 AddIssue( $patron1->unblessed, $item1->barcode );
4148 my $recall1 = Koha::Recall->new(
4149 { borrowernumber => $patron2->borrowernumber,
4150 biblionumber => $item1->biblionumber,
4151 itemnumber => $item1->itemnumber,
4152 item_level_recall => 1,
4153 branchcode => $item1->homebranch,
4156 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4157 is( $messages->{RecallFound}->recall_id, $recall1->recall_id, "Recall found" );
4158 $recall1->set_cancelled;
4160 # this item can fill a recall but needs transfer
4161 AddIssue( $patron1->unblessed, $item1->barcode );
4162 $recall1 = Koha::Recall->new(
4163 { borrowernumber => $patron2->borrowernumber,
4164 biblionumber => $item1->biblionumber,
4165 itemnumber => $item1->itemnumber,
4166 item_level_recall => 1,
4167 branchcode => $patron2->branchcode,
4170 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4171 is( $messages->{RecallNeedsTransfer}, $item1->homebranch, "Recall requiring transfer found" );
4172 $recall1->set_cancelled;
4174 # this item is already in transit, do not ask to transfer
4175 AddIssue( $patron1->unblessed, $item1->barcode );
4176 $recall1 = Koha::Recall->new(
4177 { borrowernumber => $patron2->borrowernumber,
4178 biblionumber => $item1->biblionumber,
4179 itemnumber => $item1->itemnumber,
4180 item_level_recall => 1,
4181 branchcode => $patron2->branchcode,
4184 $recall1->start_transfer;
4185 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $patron2->branchcode );
4186 is( $messages->{TransferredRecall}->recall_id, $recall1->recall_id, "In transit recall found" );
4187 $recall1->set_cancelled;
4190 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
4195 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4197 my $issuing_charges = 15;
4198 my $title = 'A title';
4199 my $author = 'Author, An';
4200 my $barcode = 'WHATARETHEODDS';
4202 my $circ = Test::MockModule->new('C4::Circulation');
4204 'GetIssuingCharges',
4206 return $issuing_charges;
4210 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4211 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
4212 my $patron = $builder->build_object({
4213 class => 'Koha::Patrons',
4214 value => { branchcode => $library->id }
4217 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
4218 my $item_id = Koha::Item->new(
4220 biblionumber => $biblio->biblionumber,
4221 homebranch => $library->id,
4222 holdingbranch => $library->id,
4223 barcode => $barcode,
4224 replacementprice => 23.00,
4225 itype => $itemtype->id
4227 )->store->itemnumber;
4228 my $item = Koha::Items->find( $item_id );
4230 my $context = Test::MockModule->new('C4::Context');
4231 $context->mock( userenv => { branch => $library->id } );
4233 # Check the item out
4234 AddIssue( $patron->unblessed, $item->barcode );
4237 AddRenewal( $patron->borrowernumber, $item->itemnumber, $library->id, undef, {break=>"the_renewal"} );
4238 } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
4240 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
4241 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
4242 my %params_renewal = (
4243 timestamp => { -like => $date . "%" },
4244 module => "CIRCULATION",
4245 action => "RENEWAL",
4247 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
4248 AddRenewal( $patron->id, $item->id, $library->id );
4249 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4250 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
4252 my $checkouts = $patron->checkouts;
4253 # The following will fail if run on 00:00:00
4254 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
4256 my $lines = Koha::Account::Lines->search({
4257 borrowernumber => $patron->id,
4258 itemnumber => $item->id
4261 is( $lines->count, 2 );
4263 my $line = $lines->next;
4264 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
4265 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
4266 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
4268 $line = $lines->next;
4269 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
4270 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
4271 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
4273 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
4275 $context = Test::MockModule->new('C4::Context');
4276 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
4278 my $now = dt_from_string;
4279 $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
4280 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
4281 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
4282 $sth->execute($item->id, $library->id);
4283 my ($old_stats_size) = $sth->fetchrow_array;
4284 AddRenewal( $patron->id, $item->id, $library->id );
4285 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4286 $sth->execute($item->id, $library->id);
4287 my ($new_stats_size) = $sth->fetchrow_array;
4288 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
4289 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
4291 AddReturn( $item->id, $library->id, undef, $date );
4292 AddIssue( $patron->unblessed, $item->barcode, $now );
4293 AddRenewal( $patron->id, $item->id, $library->id, undef, undef, 1 );
4294 my $lines_skipped = Koha::Account::Lines->search({
4295 borrowernumber => $patron->id,
4296 itemnumber => $item->id
4298 is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
4302 subtest 'ProcessOfflinePayment() tests' => sub {
4309 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
4310 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4311 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
4313 is( $result, 'Success.', 'The right string is returned' );
4315 my $lines = $patron->account->lines;
4316 is( $lines->count, 1, 'line created correctly');
4318 my $line = $lines->next;
4319 is( $line->amount+0, $amount * -1, 'amount picked from params' );
4320 is( $line->branchcode, $library->id, 'branchcode set correctly' );
4324 subtest 'Incremented fee tests' => sub {
4327 my $dt = dt_from_string();
4328 Time::Fake->offset( $dt->epoch );
4330 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
4333 $builder->build_object( { class => 'Koha::Libraries' } )->store;
4335 $module->mock( 'userenv', sub { { branch => $library->id } } );
4337 my $patron = $builder->build_object(
4339 class => 'Koha::Patrons',
4340 value => { categorycode => $patron_category->{categorycode} }
4344 my $itemtype = $builder->build_object(
4346 class => 'Koha::ItemTypes',
4348 notforloan => undef,
4350 rentalcharge_daily => 1,
4351 rentalcharge_daily_calendar => 0
4356 my $item = $builder->build_sample_item(
4358 library => $library->{branchcode},
4359 itype => $itemtype->id,
4363 is( $itemtype->rentalcharge_daily+0,
4364 1, 'Daily rental charge stored and retreived correctly' );
4365 is( $item->effective_itemtype, $itemtype->id,
4366 "Itemtype set correctly for item" );
4368 my $now = dt_from_string;
4369 my $dt_from = $now->clone;
4370 my $dt_to = $now->clone->add( days => 7 );
4371 my $dt_to_renew = $now->clone->add( days => 13 );
4375 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4376 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4377 is( $accountline->amount+0, 7,
4378 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
4380 $accountline->delete();
4381 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4382 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4383 is( $accountline->amount+0, 6,
4384 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
4386 $accountline->delete();
4389 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
4390 $itemtype->rentalcharge_daily_calendar(1)->store();
4392 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4393 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4394 is( $accountline->amount+0, 7,
4395 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
4397 $accountline->delete();
4398 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4399 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4400 is( $accountline->amount+0, 6,
4401 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
4403 $accountline->delete();
4406 my $calendar = C4::Calendar->new( branchcode => $library->id );
4407 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
4409 ( $dt_from->day_of_week == 6 ) ? 0
4410 : ( $dt_from->day_of_week == 7 ) ? 1
4411 : $dt_from->day_of_week + 1;
4412 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
4413 $calendar->insert_week_day_holiday(
4414 weekday => $closed_day,
4415 title => 'Test holiday',
4416 description => 'Test holiday'
4419 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4420 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4421 is( $accountline->amount+0, 6,
4422 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
4424 $accountline->delete();
4425 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4426 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4427 is( $accountline->amount+0, 5,
4428 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
4430 $accountline->delete();
4433 $itemtype->rentalcharge(2)->store;
4434 is( $itemtype->rentalcharge+0, 2,
4435 'Rental charge updated and retreived correctly' );
4437 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4439 Koha::Account::Lines->search( { itemnumber => $item->id } );
4440 is( $accountlines->count, '2',
4441 "Fixed charge and accrued charge recorded distinctly" );
4442 $accountlines->delete();
4443 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4444 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
4445 is( $accountlines->count, '2',
4446 "Fixed charge and accrued charge recorded distinctly, for renewal" );
4447 $accountlines->delete();
4449 $itemtype->rentalcharge(0)->store;
4450 is( $itemtype->rentalcharge+0, 0,
4451 'Rental charge reset and retreived correctly' );
4454 Koha::CirculationRules->set_rule(
4456 categorycode => $patron->categorycode,
4457 itemtype => $itemtype->id,
4458 branchcode => $library->id,
4459 rule_name => 'lengthunit',
4460 rule_value => 'hours',
4464 $itemtype->rentalcharge_hourly('0.25')->store();
4465 is( $itemtype->rentalcharge_hourly,
4466 '0.25', 'Hourly rental charge stored and retreived correctly' );
4468 $dt_to = $now->clone->add( hours => 168 );
4469 $dt_to_renew = $now->clone->add( hours => 312 );
4471 $itemtype->rentalcharge_hourly_calendar(0)->store();
4473 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4474 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4475 is( $accountline->amount + 0, 42,
4476 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)" );
4477 $accountline->delete();
4478 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4479 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4480 is( $accountline->amount + 0, 36,
4481 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)" );
4482 $accountline->delete();
4485 $itemtype->rentalcharge_hourly_calendar(1)->store();
4487 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4488 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4489 is( $accountline->amount + 0, 36,
4490 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)" );
4491 $accountline->delete();
4492 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4493 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4494 is( $accountline->amount + 0, 30,
4495 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
4496 $accountline->delete();
4499 $calendar->delete_holiday( weekday => $closed_day );
4501 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4502 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4503 is( $accountline->amount + 0, 42,
4504 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u" );
4505 $accountline->delete();
4506 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4507 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4508 is( $accountline->amount + 0, 36,
4509 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)" );
4510 $accountline->delete();
4515 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
4518 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
4519 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4522 $builder->build_object( { class => 'Koha::Libraries' } )->store;
4523 my $patron = $builder->build_object(
4525 class => 'Koha::Patrons',
4526 value => { categorycode => $patron_category->{categorycode} }
4530 my $itemtype = $builder->build_object(
4532 class => 'Koha::ItemTypes',
4536 rentalcharge_daily => 0
4541 my $item = $builder->build_sample_item(
4543 library => $library->id,
4547 itype => $itemtype->id,
4551 my ( $issuingimpossible, $needsconfirmation );
4552 my $dt_from = dt_from_string();
4553 my $dt_due = $dt_from->clone->add( days => 3 );
4555 $itemtype->rentalcharge(1)->store;
4556 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4557 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
4558 $itemtype->rentalcharge('0')->store;
4559 $itemtype->rentalcharge_daily(1)->store;
4560 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4561 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
4562 $itemtype->rentalcharge_daily('0')->store;
4565 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
4568 t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
4570 my $patron = $builder->build_object(
4572 class => 'Koha::Patrons',
4573 value => { categorycode => $patron_category->{categorycode} }
4577 my $item = $builder->build_sample_item(
4579 materials => 'includes DVD',
4583 my $dt_due = dt_from_string->add( days => 3 );
4585 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4586 is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
4589 subtest 'Do not return on renewal (LOST charge)' => sub {
4592 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
4593 my $library = $builder->build_object( { class => "Koha::Libraries" } );
4594 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
4595 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
4597 my $biblio = $builder->build_sample_biblio;
4599 my $item = $builder->build_sample_item(
4601 biblionumber => $biblio->biblionumber,
4602 library => $library->branchcode,
4603 replacementprice => 99.00,
4608 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
4609 AddIssue( $patron->unblessed, $item->barcode );
4611 my $accountline = Koha::Account::Line->new(
4613 borrowernumber => $patron->borrowernumber,
4614 debit_type_code => 'LOST',
4616 itemnumber => $item->itemnumber,
4618 amountoutstanding => 12,
4619 interface => 'something',
4623 # AddRenewal doesn't call _FixAccountForLostAndFound
4624 AddIssue( $patron->unblessed, $item->barcode );
4626 is( $patron->checkouts->count, 1,
4627 'Renewal should not return the item even if a LOST payment has been made earlier'
4631 subtest 'Filling a hold should cancel existing transfer' => sub {
4634 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
4636 my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
4637 my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
4638 my $patron = $builder->build_object(
4640 class => 'Koha::Patrons',
4642 categorycode => $patron_category->{categorycode},
4643 branchcode => $libraryA->branchcode,
4648 my $item = $builder->build_sample_item({
4649 homebranch => $libraryB->branchcode,
4652 my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4653 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
4655 branchcode => $libraryA->branchcode,
4656 borrowernumber => $patron->borrowernumber,
4657 biblionumber => $item->biblionumber,
4658 itemnumber => $item->itemnumber
4660 my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
4661 is( $reserves->count, 1, "Reserve is placed");
4662 ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4663 my $reserve = $reserves->next;
4664 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
4665 $reserve->discard_changes;
4666 ok( $reserve->found eq 'W', "Reserve is marked waiting" );
4667 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
4670 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
4674 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4675 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4676 my $patron = $builder->build_object(
4678 class => 'Koha::Patrons',
4679 value => { categorycode => $patron_category->{categorycode} }
4683 my $biblionumber = $builder->build_sample_biblio(
4685 branchcode => $library->branchcode,
4689 # And the circulation rule
4690 Koha::CirculationRules->search->delete;
4691 Koha::CirculationRules->set_rules(
4693 categorycode => undef,
4695 branchcode => undef,
4698 lengthunit => 'days',
4704 source => 'CirculationRule',
4706 branchcode => undef,
4707 categorycode => undef,
4709 rule_name => 'lostreturn',
4710 rule_value => 'refund'
4715 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4718 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4719 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4721 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4723 my $item = $builder->build_sample_item(
4725 biblionumber => $biblionumber,
4726 library => $library->branchcode,
4727 replacementprice => '42',
4730 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4731 LostItem( $item->itemnumber, 'cli', 0 );
4732 $item->_result->itemlost(1);
4733 $item->_result->itemlost_on( $lost_on );
4734 $item->_result->update();
4736 my $a = Koha::Account::Lines->search(
4738 itemnumber => $item->id,
4739 borrowernumber => $patron->borrowernumber
4742 ok( $a, "Found accountline for lost fee" );
4743 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4744 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4745 $a = $a->get_from_storage;
4746 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4750 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4753 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4754 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4756 my $lost_on = dt_from_string->subtract( days => 6 )->date;
4758 my $item = $builder->build_sample_item(
4760 biblionumber => $biblionumber,
4761 library => $library->branchcode,
4762 replacementprice => '42',
4765 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4766 LostItem( $item->itemnumber, 'cli', 0 );
4767 $item->_result->itemlost(1);
4768 $item->_result->itemlost_on( $lost_on );
4769 $item->_result->update();
4771 my $a = Koha::Account::Lines->search(
4773 itemnumber => $item->id,
4774 borrowernumber => $patron->borrowernumber
4777 ok( $a, "Found accountline for lost fee" );
4778 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4779 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4780 $a = $a->get_from_storage;
4781 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4785 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4788 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4789 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4791 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4793 my $item = $builder->build_sample_item(
4795 biblionumber => $biblionumber,
4796 library => $library->branchcode,
4797 replacementprice => '42',
4800 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4801 LostItem( $item->itemnumber, 'cli', 0 );
4802 $item->_result->itemlost(1);
4803 $item->_result->itemlost_on( $lost_on );
4804 $item->_result->update();
4806 my $a = Koha::Account::Lines->search(
4808 itemnumber => $item->id,
4809 borrowernumber => $patron->borrowernumber
4812 ok( $a, "Found accountline for lost fee" );
4813 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4814 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4815 $a = $a->get_from_storage;
4816 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4820 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4823 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4824 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4826 my $lost_on = dt_from_string->subtract( days => 8 )->date;
4828 my $item = $builder->build_sample_item(
4830 biblionumber => $biblionumber,
4831 library => $library->branchcode,
4832 replacementprice => '42',
4835 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4836 LostItem( $item->itemnumber, 'cli', 0 );
4837 $item->_result->itemlost(1);
4838 $item->_result->itemlost_on( $lost_on );
4839 $item->_result->update();
4841 my $a = Koha::Account::Lines->search(
4843 itemnumber => $item->id,
4844 borrowernumber => $patron->borrowernumber
4848 ok( $a, "Found accountline for lost fee" );
4849 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4850 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4851 $a = $a->get_from_storage;
4852 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4857 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
4861 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4862 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4863 my $patron = $builder->build_object(
4865 class => 'Koha::Patrons',
4866 value => { categorycode => $patron_category->{categorycode} }
4869 my $patron2 = $builder->build_object(
4871 class => 'Koha::Patrons',
4872 value => { categorycode => $patron_category->{categorycode} }
4876 my $biblionumber = $builder->build_sample_biblio(
4878 branchcode => $library->branchcode,
4882 # And the circulation rule
4883 Koha::CirculationRules->search->delete;
4884 Koha::CirculationRules->set_rules(
4886 categorycode => undef,
4888 branchcode => undef,
4891 lengthunit => 'days',
4897 source => 'CirculationRule',
4899 branchcode => undef,
4900 categorycode => undef,
4902 rule_name => 'lostreturn',
4903 rule_value => 'refund'
4908 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4911 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4912 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4914 my $lost_on = dt_from_string->subtract( days => 7 )->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 $issue = AddIssue( $patron2->unblessed, $item->barcode );
4938 $a = $a->get_from_storage;
4939 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4944 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4947 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4948 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4950 my $lost_on = dt_from_string->subtract( days => 6 )->date;
4952 my $item = $builder->build_sample_item(
4954 biblionumber => $biblionumber,
4955 library => $library->branchcode,
4956 replacementprice => '42',
4959 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4960 LostItem( $item->itemnumber, 'cli', 0 );
4961 $item->_result->itemlost(1);
4962 $item->_result->itemlost_on( $lost_on );
4963 $item->_result->update();
4965 my $a = Koha::Account::Lines->search(
4967 itemnumber => $item->id,
4968 borrowernumber => $patron->borrowernumber
4971 ok( $a, "Found accountline for lost fee" );
4972 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4973 $issue = AddIssue( $patron2->unblessed, $item->barcode );
4974 $a = $a->get_from_storage;
4975 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4979 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4982 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4983 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4985 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4987 my $item = $builder->build_sample_item(
4989 biblionumber => $biblionumber,
4990 library => $library->branchcode,
4991 replacementprice => '42',
4994 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4995 LostItem( $item->itemnumber, 'cli', 0 );
4996 $item->_result->itemlost(1);
4997 $item->_result->itemlost_on( $lost_on );
4998 $item->_result->update();
5000 my $a = Koha::Account::Lines->search(
5002 itemnumber => $item->id,
5003 borrowernumber => $patron->borrowernumber
5006 ok( $a, "Found accountline for lost fee" );
5007 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5008 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5009 $a = $a->get_from_storage;
5010 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5014 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5017 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5018 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5020 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5022 my $item = $builder->build_sample_item(
5024 biblionumber => $biblionumber,
5025 library => $library->branchcode,
5026 replacementprice => '42',
5029 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5030 LostItem( $item->itemnumber, 'cli', 0 );
5031 $item->_result->itemlost(1);
5032 $item->_result->itemlost_on( $lost_on );
5033 $item->_result->update();
5035 my $a = Koha::Account::Lines->search(
5037 itemnumber => $item->id,
5038 borrowernumber => $patron->borrowernumber
5042 ok( $a, "Found accountline for lost fee" );
5043 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5044 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5045 $a = $a->get_from_storage;
5046 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5051 subtest 'transferbook tests' => sub {
5055 { C4::Circulation::transferbook({}); }
5056 'Koha::Exceptions::MissingParameter',
5057 'Koha::Patron->store raises an exception on missing params';
5060 { C4::Circulation::transferbook({to_branch=>'anything'}); }
5061 'Koha::Exceptions::MissingParameter',
5062 'Koha::Patron->store raises an exception on missing params';
5065 { C4::Circulation::transferbook({from_branch=>'anything'}); }
5066 'Koha::Exceptions::MissingParameter',
5067 'Koha::Patron->store raises an exception on missing params';
5069 my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
5070 is( $doreturn, 0, "No return without barcode");
5071 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5072 is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
5074 ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
5075 is( $doreturn, 0, "No return without barcode");
5076 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5077 is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
5081 subtest 'Checkout should correctly terminate a transfer' => sub {
5084 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5085 my $patron_1 = $builder->build_object(
5087 class => 'Koha::Patrons',
5088 value => { branchcode => $library_1->branchcode }
5091 my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
5092 my $patron_2 = $builder->build_object(
5094 class => 'Koha::Patrons',
5095 value => { branchcode => $library_2->branchcode }
5099 my $item = $builder->build_sample_item(
5101 library => $library_1->branchcode,
5105 t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
5106 my $reserve_id = AddReserve(
5108 branchcode => $library_2->branchcode,
5109 borrowernumber => $patron_2->borrowernumber,
5110 biblionumber => $item->biblionumber,
5111 itemnumber => $item->itemnumber,
5116 my $do_transfer = 1;
5117 ModItemTransfer( $item->itemnumber, $library_1->branchcode,
5118 $library_2->branchcode, 'Manual' );
5119 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
5120 GetOtherReserves( $item->itemnumber )
5121 ; # To put the Reason, it's what does returns.pl...
5122 my $hold = Koha::Holds->find($reserve_id);
5123 is( $hold->found, 'T', 'Hold is in transit' );
5124 my $transfer = $item->get_transfer;
5125 is( $transfer->frombranch, $library_1->branchcode );
5126 is( $transfer->tobranch, $library_2->branchcode );
5127 is( $transfer->reason, 'Reserve' );
5129 t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
5130 AddIssue( $patron_1->unblessed, $item->barcode );
5131 $transfer = $transfer->get_from_storage;
5132 isnt( $transfer->datearrived, undef );
5133 $hold = $hold->get_from_storage;
5134 is( $hold->found, undef, 'Hold is waiting' );
5135 is( $hold->priority, 1, );
5138 subtest 'AddIssue records staff who checked out item if appropriate' => sub {
5141 $module->mock( 'userenv', sub { { branch => $library->{id} } } );
5143 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5144 my $patron = $builder->build_object(
5146 class => 'Koha::Patrons',
5147 value => { categorycode => $patron_category->{categorycode} }
5150 my $issuer = $builder->build_object(
5152 class => 'Koha::Patrons',
5153 value => { categorycode => $patron_category->{categorycode} }
5156 my $item = $builder->build_sample_item(
5158 library => $library->{branchcode}
5162 $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->{borrowernumber} } } );
5164 my $dt_from = dt_from_string();
5165 my $dt_to = dt_from_string()->add( days => 7 );
5167 my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
5169 is( $issue->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
5171 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
5174 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
5176 is( $issue->issuer, $issuer->{borrowernumber}, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
5179 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
5182 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5183 my $patron_1 = $builder->build_object(
5185 class => 'Koha::Patrons',
5186 value => { branchcode => $library_1->branchcode }
5189 my $patron_2 = $builder->build_object(
5191 class => 'Koha::Patrons',
5192 value => { branchcode => $library_1->branchcode }
5196 my $item = $builder->build_sample_item(
5198 library => $library_1->branchcode,
5202 AddIssue( $patron_1->unblessed, $item->barcode );
5203 ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
5204 AddIssue( $patron_2->unblessed, $item->barcode );
5205 ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
5208 subtest "updateWrongTransfer tests" => sub {
5211 my $library1 = $builder->build_object( { class => 'Koha::Libraries' } );
5212 my $library2 = $builder->build_object( { class => 'Koha::Libraries' } );
5213 my $library3 = $builder->build_object( { class => 'Koha::Libraries' } );
5214 my $item = $builder->build_sample_item(
5216 homebranch => $library1->branchcode,
5217 holdingbranch => $library2->branchcode,
5218 datelastseen => undef
5222 my $transfer = $builder->build_object(
5224 class => 'Koha::Item::Transfers',
5226 itemnumber => $item->itemnumber,
5227 frombranch => $library2->branchcode,
5228 tobranch => $library1->branchcode,
5229 daterequested => dt_from_string,
5230 datesent => dt_from_string,
5231 datecancelled => undef,
5232 datearrived => undef,
5237 is( ref($transfer), 'Koha::Item::Transfer', 'Mock transfer added' );
5239 my $new_transfer = C4::Circulation::updateWrongTransfer($item->itemnumber, $library1->branchcode);
5240 is(ref($new_transfer), 'Koha::Item::Transfer', "updateWrongTransfer returns a 'Koha::Item::Transfer' object");
5241 ok( !$new_transfer->in_transit, "New transfer is NOT created as in transit (or cancelled)");
5243 my $original_transfer = $transfer->get_from_storage;
5244 ok( defined($original_transfer->datecancelled), "Original transfer was cancelled");
5245 is( $original_transfer->cancellation_reason, 'WrongTransfer', "Original transfer cancellation reason is 'WrongTransfer'");
5248 subtest "SendCirculationAlert" => sub {
5251 # When you would unsuspectingly call this unit test (with perl, not prove), you will be bitten by LOCK.
5252 # LOCK will commit changes and ruin your data
5253 # In order to prevent that, we will add KOHA_TESTING to $ENV; see further Circulation.pm
5254 $ENV{KOHA_TESTING} = 1;
5256 # Setup branch, borrowr, and notice
5257 my $library = $builder->build_object({ class => 'Koha::Libraries' });
5258 set_userenv( $library->unblessed);
5259 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5260 C4::Members::Messaging::SetMessagingPreference({
5261 borrowernumber => $patron->id,
5262 message_transport_types => ['email'],
5263 message_attribute_id => 5
5265 my $item = $builder->build_sample_item();
5266 my $checkin_notice = $builder->build_object({
5267 class => 'Koha::Notice::Templates',
5269 module => 'circulation',
5271 branchcode => $library->branchcode,
5272 name => 'Test Checkin',
5274 content => "Checkins:\n----\n[% biblio.title %]-[% old_checkout.issue_id %]\n----Thank you.",
5275 message_transport_type => 'email',
5280 # Checkout an item, mark it returned, generate a notice
5281 my $issue_1 = AddIssue( $patron->unblessed, $item->barcode);
5282 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5283 C4::Circulation::SendCirculationAlert({
5285 item => $item->unblessed,
5286 borrower => $patron->unblessed,
5287 branch => $library->branchcode,
5290 my $notice = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'CHECKIN' });
5291 is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\nThank you.", 'Letter generated with expected output on first checkin' );
5293 # Checkout an item, mark it returned, generate a notice
5294 my $issue_2 = AddIssue( $patron->unblessed, $item->barcode);
5295 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5296 C4::Circulation::SendCirculationAlert({
5298 item => $item->unblessed,
5299 borrower => $patron->unblessed,
5300 branch => $library->branchcode,
5303 $notice->discard_changes();
5304 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' );
5308 subtest "GetSoonestRenewDate tests" => sub {
5310 Koha::CirculationRules->set_rule(
5312 categorycode => undef,
5313 branchcode => undef,
5315 rule_name => 'norenewalbefore',
5319 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5320 my $item = $builder->build_sample_item();
5321 my $issue = AddIssue( $patron->unblessed, $item->barcode);
5322 my $datedue = dt_from_string( $issue->date_due() );
5325 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
5326 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
5328 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5329 $datedue->clone->add( days => -7 ),
5330 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5334 # Test 'date' setting for syspref NoRenewalBeforePrecision
5335 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5337 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5338 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
5339 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5343 Koha::CirculationRules->set_rule(
5345 categorycode => undef,
5346 branchcode => undef,
5348 rule_name => 'norenewalbefore',
5349 rule_value => undef,
5354 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5356 'Checkouts without auto-renewal can be renewed immediately if no norenewalbefore'
5359 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5360 $issue->auto_renew(1)->store;
5362 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5363 $datedue->clone->truncate( to => 'day' ),
5364 'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5366 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact' );
5368 GetSoonestRenewDate( $patron->id, $item->itemnumber ),
5370 'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5374 $schema->storage->txn_rollback;
5375 C4::Context->clear_syspref_cache();
5376 $branches = Koha::Libraries->search();
5377 for my $branch ( $branches->next ) {
5378 my $key = $branch->branchcode . "_holidays";
5379 $cache->clear_from_cache($key);