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 => 70;
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 );
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 );
47 use Koha::Item::Transfers;
50 use Koha::Patron::Debarments qw( AddDebarment DelUniqueDebarment );
52 use Koha::CirculationRules;
53 use Koha::Subscriptions;
54 use Koha::Account::Lines;
55 use Koha::Account::Offsets;
57 use Koha::Notice::Messages;
58 use Koha::Cache::Memory::Lite;
60 my $builder = t::lib::TestBuilder->new;
63 my $staff = $builder->build_object({ class => "Koha::Patrons" });
64 t::lib::Mocks::mock_userenv({ patron => $staff, branchcode => $library->{branchcode} });
68 my ( $error, $question, $alert ) = @_;
70 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
71 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
72 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
76 sub test_debarment_on_checkout {
78 my $item = $params->{item};
79 my $library = $params->{library};
80 my $patron = $params->{patron};
81 my $due_date = $params->{due_date} || dt_from_string;
82 my $return_date = $params->{return_date} || dt_from_string;
83 my $expected_expiration_date = $params->{expiration_date};
85 $expected_expiration_date = output_pref(
87 dt => $expected_expiration_date,
93 my $line_number = $caller[2];
94 AddIssue( $patron, $item->barcode, $due_date );
96 my ( undef, $message ) = AddReturn( $item->barcode, $library->{branchcode}, undef, $return_date );
97 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
98 or diag('AddReturn returned message ' . Dumper $message );
99 my $suspensions = $patron->restrictions->search({ type => 'SUSPENSION' } );
100 is( $suspensions->count, 1, 'Test at line ' . $line_number );
102 my $THE_suspension = $suspensions->next;
103 is( $THE_suspension->expiration,
104 $expected_expiration_date, 'Test at line ' . $line_number );
105 Koha::Patron::Debarments::DelUniqueDebarment(
106 { borrowernumber => $patron->borrowernumber, type => 'SUSPENSION' } );
109 my $schema = Koha::Database->schema;
110 $schema->storage->txn_begin;
111 my $dbh = C4::Context->dbh;
113 # Prevent random failures by mocking ->now
114 my $now_value = dt_from_string;
115 my $mocked_datetime = Test::MockModule->new('DateTime');
116 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
118 my $cache = Koha::Caches->get_instance();
119 $dbh->do(q|DELETE FROM special_holidays|);
120 $dbh->do(q|DELETE FROM repeatable_holidays|);
121 my $branches = Koha::Libraries->search();
122 for my $branch ( $branches->next ) {
123 my $key = $branch->branchcode . "_holidays";
124 $cache->clear_from_cache($key);
127 # Start with a clean slate
128 $dbh->do('DELETE FROM issues');
129 $dbh->do('DELETE FROM borrowers');
131 # Disable recording of the staff who checked out an item until we're ready for it
132 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 0);
134 my $module = Test::MockModule->new('C4::Context');
136 my $library = $builder->build({
139 my $library2 = $builder->build({
142 my $itemtype = $builder->build(
144 source => 'Itemtype',
148 rentalcharge_daily => 0,
149 defaultreplacecost => undef,
154 my $patron_category = $builder->build(
156 source => 'Category',
158 category_type => 'P',
160 BlockExpiredPatronOpacActions => -1, # Pick the pref value
165 my $CircControl = C4::Context->preference('CircControl');
166 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
168 my $item = $builder->build_object({
169 class => 'Koha::Items',
171 homebranch => $library2->{branchcode},
172 holdingbranch => $library2->{branchcode}
176 my $borrower = $builder->build_object({
177 class => 'Koha::Patrons',
178 value => { branchcode => $library2->{branchcode} }
181 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
183 # No userenv, PickupLibrary
184 t::lib::Mocks::mock_preference('IndependentBranches', '0');
185 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
187 C4::Context->preference('CircControl'),
189 'CircControl changed to PickupLibrary'
192 C4::Circulation::_GetCircControlBranch($item, $borrower),
193 $item->get_column($HomeOrHoldingBranch),
194 '_GetCircControlBranch returned item branch (no userenv defined)'
197 # No userenv, PatronLibrary
198 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
200 C4::Context->preference('CircControl'),
202 'CircControl changed to PatronLibrary'
205 C4::Circulation::_GetCircControlBranch($item, $borrower),
206 $borrower->branchcode,
207 '_GetCircControlBranch returned borrower branch'
210 # No userenv, ItemHomeLibrary
211 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
213 C4::Context->preference('CircControl'),
215 'CircControl changed to ItemHomeLibrary'
218 $item->get_column($HomeOrHoldingBranch),
219 C4::Circulation::_GetCircControlBranch($item, $borrower),
220 '_GetCircControlBranch returned item branch'
224 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
225 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
227 # Userenv set, PickupLibrary
228 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
230 C4::Context->preference('CircControl'),
232 'CircControl changed to PickupLibrary'
235 C4::Circulation::_GetCircControlBranch($item, $borrower),
236 $library2->{branchcode},
237 '_GetCircControlBranch returned current branch'
240 # Userenv set, PatronLibrary
241 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
243 C4::Context->preference('CircControl'),
245 'CircControl changed to PatronLibrary'
248 C4::Circulation::_GetCircControlBranch($item, $borrower),
249 $borrower->branchcode,
250 '_GetCircControlBranch returned borrower branch'
253 # Userenv set, ItemHomeLibrary
254 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
256 C4::Context->preference('CircControl'),
258 'CircControl changed to ItemHomeLibrary'
261 C4::Circulation::_GetCircControlBranch($item, $borrower),
262 $item->get_column($HomeOrHoldingBranch),
263 '_GetCircControlBranch returned item branch'
266 # Reset initial configuration
267 t::lib::Mocks::mock_preference('CircControl', $CircControl);
269 C4::Context->preference('CircControl'),
271 'CircControl reset to its initial value'
274 # Set a simple circ policy
275 $dbh->do('DELETE FROM circulation_rules');
276 Koha::CirculationRules->set_rules(
278 categorycode => undef,
282 reservesallowed => 25,
284 lengthunit => 'days',
285 renewalsallowed => 1,
287 norenewalbefore => undef,
288 noautorenewalbefore => undef,
296 subtest "CanBookBeRenewed AllowRenewalIfOtherItemsAvailable multiple borrowers and items tests" => sub {
299 #Can only reserve from home branch
300 Koha::CirculationRules->set_rule(
304 rule_name => 'holdallowed',
308 Koha::CirculationRules->set_rule(
311 categorycode => undef,
313 rule_name => 'onshelfholds',
318 # Patrons from three different branches
319 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
320 my $patron_hold_1 = $builder->build_object({ class => 'Koha::Patrons' });
321 my $patron_hold_2 = $builder->build_object({ class => 'Koha::Patrons' });
322 my $biblio = $builder->build_sample_biblio();
324 # Item at each patron branch
325 my $item_1 = $builder->build_sample_item({
326 biblionumber => $biblio->biblionumber,
327 homebranch => $patron->branchcode
329 my $item_2 = $builder->build_sample_item({
330 biblionumber => $biblio->biblionumber,
331 homebranch => $patron_hold_2->branchcode
333 my $item_3 = $builder->build_sample_item({
334 biblionumber => $biblio->biblionumber,
335 homebranch => $patron_hold_1->branchcode
338 my $issue = AddIssue( $patron, $item_1->barcode);
339 my $datedue = dt_from_string( $issue->date_due() );
340 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
343 my $reserve_1 = AddReserve(
345 branchcode => $patron_hold_1->branchcode,
346 borrowernumber => $patron_hold_1->borrowernumber,
347 biblionumber => $biblio->biblionumber,
349 reservation_date => dt_from_string(),
350 expiration_date => undef,
357 branchcode => $patron_hold_2->branchcode,
358 borrowernumber => $patron_hold_2->borrowernumber,
359 biblionumber => $biblio->biblionumber,
361 reservation_date => dt_from_string(),
362 expiration_date => undef,
367 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
369 my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue);
370 is( $renewokay, 0, 'Cannot renew, reserved');
371 is( $error, 'on_reserve', 'Cannot renew, reserved (returned error is on_reserve)');
373 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
375 ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue);
376 is( $renewokay, 1, 'Can renew, two items available for two holds');
377 is( $error, undef, 'Can renew, each reserve has an item');
380 my $hold = Koha::Holds->find( $reserve_1 );
381 $hold->itemnumber( $item_1->itemnumber )->store;
383 ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue);
384 is( $renewokay, 0, 'Cannot renew when there is an item specific hold');
385 is( $error, 'on_reserve', 'Cannot renew, only this item can fill the reserve');
388 subtest "GetIssuingCharges tests" => sub {
390 my $branch_discount = $builder->build_object({ class => 'Koha::Libraries' });
391 my $branch_no_discount = $builder->build_object({ class => 'Koha::Libraries' });
392 Koha::CirculationRules->set_rule(
394 categorycode => undef,
395 branchcode => $branch_discount->branchcode,
397 rule_name => 'rentaldiscount',
401 my $itype_charge = $builder->build_object({
402 class => 'Koha::ItemTypes',
407 my $itype_no_charge = $builder->build_object({
408 class => 'Koha::ItemTypes',
413 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
414 my $item_1 = $builder->build_sample_item({ itype => $itype_charge->itemtype });
415 my $item_2 = $builder->build_sample_item({ itype => $itype_no_charge->itemtype });
417 t::lib::Mocks::mock_userenv({ branchcode => $branch_no_discount->branchcode });
418 # For now the sub always uses the env branch, this should follow CircControl instead
419 my ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
420 is( $charge + 0, 10.00, "Charge fetched correctly when no discount exists");
421 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
422 is( $charge + 0, 0.00, "Charge fetched correctly when no discount exists and no charge");
424 t::lib::Mocks::mock_userenv({ branchcode => $branch_discount->branchcode });
425 # For now the sub always uses the env branch, this should follow CircControl instead
426 ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
427 is( $charge + 0, 8.50, "Charge fetched correctly when discount exists");
428 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
429 is( $charge + 0, 0.00, "Charge fetched correctly when discount exists and no charge");
433 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
434 subtest "CanBookBeRenewed tests" => sub {
437 C4::Context->set_preference('ItemsDeniedRenewal','');
438 # Generate test biblio
439 my $biblio = $builder->build_sample_biblio();
441 my $branch = $library2->{branchcode};
443 my $item_1 = $builder->build_sample_item(
445 biblionumber => $biblio->biblionumber,
447 replacementprice => 12.00,
451 $reused_itemnumber_1 = $item_1->itemnumber;
453 my $item_2 = $builder->build_sample_item(
455 biblionumber => $biblio->biblionumber,
457 replacementprice => 23.00,
461 $reused_itemnumber_2 = $item_2->itemnumber;
463 my $item_3 = $builder->build_sample_item(
465 biblionumber => $biblio->biblionumber,
467 replacementprice => 23.00,
474 my $renewing_borrower_obj = $builder->build_object(
476 class => 'Koha::Patrons',
479 surname => 'Renewal',
480 categorycode => $patron_category->{categorycode},
481 branchcode => $branch,
482 autorenew_checkouts => 1,
486 my $renewing_borrowernumber = $renewing_borrower_obj->borrowernumber;
488 my $reserving_borrowernumber = $builder->build_object(
490 class => 'Koha::Patrons',
492 firstname => 'Katrin',
493 surname => 'Reservation',
494 categorycode => $patron_category->{categorycode},
495 branchcode => $branch,
498 )->store->borrowernumber;
500 my $hold_waiting_borrowernumber = $builder->build_object(
502 class => 'Koha::Patrons',
505 surname => 'Reservation',
506 categorycode => $patron_category->{categorycode},
507 branchcode => $branch,
510 )->store->borrowernumber;
512 my $restricted_borrower_obj = $builder->build_object(
514 class => 'Koha::Patrons',
516 firstname => 'Alice',
517 surname => 'Reservation',
518 categorycode => $patron_category->{categorycode},
519 debarred => '3228-01-01',
520 branchcode => $branch,
525 my $expired_borrower_obj = $builder->build_object(
527 class => 'Koha::Patrons',
531 categorycode => $patron_category->{categorycode},
532 branchcode => $branch,
533 dateexpiry => dt_from_string->subtract( months => 1 ),
534 autorenew_checkouts => 1,
544 my $checkitem = undef;
547 my $issue_1 = AddIssue( $renewing_borrower_obj, $item_1->barcode);
548 my $datedue = dt_from_string( $issue_1->date_due() );
549 is (defined $issue_1->date_due(), 1, "Item 1 checked out, due date: " . $issue_1->date_due() );
551 my $issue_2 = AddIssue( $renewing_borrower_obj, $item_2->barcode);
552 is (defined $issue_2, 1, "Item 2 checked out, due date: " . $issue_2->date_due());
554 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
555 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to ".$renewing_borrower_obj->firstname." ".$renewing_borrower_obj->surname);
557 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1, 1);
558 is( $renewokay, 1, 'Can renew, no holds for this title or item');
561 # Biblio-level hold, renewal test
564 branchcode => $branch,
565 borrowernumber => $reserving_borrowernumber,
566 biblionumber => $biblio->biblionumber,
567 priority => $priority,
568 reservation_date => $resdate,
569 expiration_date => $expdate,
571 itemnumber => $checkitem,
576 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
577 Koha::CirculationRules->set_rule(
579 categorycode => undef,
582 rule_name => 'onshelfholds',
586 Koha::CirculationRules->set_rule(
588 categorycode => undef,
591 rule_name => 'renewalsallowed',
595 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
596 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
597 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
598 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2);
599 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
602 # Second biblio-level hold
603 my $reserve_id = AddReserve(
605 branchcode => $branch,
606 borrowernumber => $reserving_borrowernumber,
607 biblionumber => $biblio->biblionumber,
608 priority => $priority,
609 reservation_date => $resdate,
610 expiration_date => $expdate,
612 itemnumber => $checkitem,
616 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
617 is( $renewokay, 0, 'Renewal not possible when single patron\'s holds exceed the number of available items');
618 Koha::Holds->find($reserve_id)->delete;
620 # Now let's add an item level hold, we should no longer be able to renew the item
621 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
623 borrowernumber => $hold_waiting_borrowernumber,
624 biblionumber => $biblio->biblionumber,
625 itemnumber => $item_1->itemnumber,
626 branchcode => $branch,
628 reservedate => '1999-01-01',
631 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
632 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
635 # 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
636 # be able to renew these items
637 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
639 borrowernumber => $hold_waiting_borrowernumber,
640 biblionumber => $biblio->biblionumber,
641 itemnumber => $item_3->itemnumber,
642 branchcode => $branch,
647 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
648 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
649 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2);
650 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
651 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
653 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
654 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
655 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
657 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2);
658 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
659 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
661 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
662 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber );
663 AddIssue($reserving_borrower, $item_3->barcode);
664 my $reserve = $dbh->selectrow_hashref(
665 'SELECT * FROM old_reserves WHERE reserve_id = ?',
669 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
671 # Item-level hold, renewal test
674 branchcode => $branch,
675 borrowernumber => $reserving_borrowernumber,
676 biblionumber => $biblio->biblionumber,
677 priority => $priority,
678 reservation_date => $resdate,
679 expiration_date => $expdate,
681 itemnumber => $item_1->itemnumber,
686 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1, 1);
687 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
688 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
690 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2, 1);
691 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
693 # Items can't fill hold for reasons
694 $issue_1->item->notforloan(1)->store;
695 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1, 1);
696 is( $renewokay, 0, 'Cannot renew, item is marked not for loan, but an item specific hold always blocks');
697 $item_1->set({notforloan => 0, itype => $itemtype })->store;
699 # FIXME: Add more for itemtype not for loan etc.
701 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
702 my $item_5 = $builder->build_sample_item(
704 biblionumber => $biblio->biblionumber,
706 replacementprice => 23.00,
710 my $issue_5 = AddIssue($restricted_borrower_obj, $item_5->barcode);
711 is (defined $issue_5, 1, "Item with date due checked out, due date: ". $issue_5->date_due);
713 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
714 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2);
715 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
716 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrower_obj, $issue_5);
717 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
718 is( $error, 'restriction', "Correct error returned");
720 # Users cannot renew an overdue item
721 my $item_6 = $builder->build_sample_item(
723 biblionumber => $biblio->biblionumber,
725 replacementprice => 23.00,
730 my $item_7 = $builder->build_sample_item(
732 biblionumber => $biblio->biblionumber,
734 replacementprice => 23.00,
739 my $issue_6 = AddIssue( $renewing_borrower_obj, $item_6->barcode);
740 is (defined $issue_6, 1, "Item 2 checked out, due date: ".$issue_6->date_due);
742 my $now = dt_from_string();
743 my $five_weeks = DateTime::Duration->new(weeks => 5);
744 my $five_weeks_ago = $now - $five_weeks;
745 t::lib::Mocks::mock_preference('finesMode', 'production');
747 my $issue_7 = AddIssue($renewing_borrower_obj, $item_7->barcode, $five_weeks_ago);
748 is (defined $issue_7, 1, "Item with passed date due checked out, due date: " . $issue_7->date_due);
750 t::lib::Mocks::mock_preference('OverduesBlockRenewing','allow');
751 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_6);
752 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
753 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_7);
754 is( $renewokay, 1, '(Bug 8236), Can renew, this item is overdue but not pref does not block');
756 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
757 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_6);
758 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is not overdue but patron has overdues');
759 is( $error, 'overdue', "Correct error returned");
760 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_7);
761 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue so patron has overdues');
762 is( $error, 'overdue', "Correct error returned");
764 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
765 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_6);
766 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
767 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_7);
768 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
769 is( $error, 'overdue', "Correct error returned");
771 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower_obj->categorycode, $branch, $five_weeks_ago, $now );
772 C4::Overdues::UpdateFine(
774 issue_id => $issue_7->id(),
775 itemnumber => $item_7->itemnumber,
776 borrowernumber => $renewing_borrower_obj->borrowernumber,
778 due => Koha::DateUtils::output_pref($five_weeks_ago)
782 # Make sure fine calculation isn't skipped when adding renewal
783 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
785 # Calculate new due-date based on the present date not to incur
787 t::lib::Mocks::mock_preference('RenewalPeriodBase', 'now');
789 my $staff = $builder->build_object({ class => "Koha::Patrons" });
790 t::lib::Mocks::mock_userenv({ patron => $staff });
792 t::lib::Mocks::mock_preference('RenewalLog', 0);
793 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
794 my %params_renewal = (
795 timestamp => { -like => $date . "%" },
796 module => "CIRCULATION",
800 timestamp => { -like => $date . "%" },
801 module => "CIRCULATION",
804 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
805 my $dt = dt_from_string();
806 Time::Fake->offset( $dt->epoch );
807 my $datedue1 = AddRenewal(
809 borrowernumber => $renewing_borrower_obj->borrowernumber,
810 itemnumber => $item_7->itemnumber,
814 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
815 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
816 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
819 t::lib::Mocks::mock_preference('RenewalLog', 1);
820 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
821 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
824 borrowernumber => $renewing_borrower_obj->borrowernumber,
825 itemnumber => $item_7->itemnumber,
829 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
830 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
832 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower_obj->borrowernumber, itemnumber => $item_7->itemnumber } );
833 is( $fines->count, 1, 'AddRenewal left fine' );
834 is( $fines->next->status, 'RENEWED', 'Fine on renewed item is closed out properly' );
837 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
838 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
840 $renewing_borrower_obj,
842 Koha::DateUtils::output_pref({str=>$issue_6->date_due, dateformat =>'iso'}),
847 ); # TODO: Already issued???
848 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
849 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
850 $new_log_size = Koha::ActionLogs->count( \%params_issue );
851 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
853 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
857 # Test automatic renewal before value for "norenewalbefore" in policy is set
858 # In this case automatic renewal should still be permitted
859 my $item_4 = $builder->build_sample_item(
861 biblionumber => $biblio->biblionumber,
863 replacementprice => 16.00,
868 my $auto_renew_issue =
869 AddIssue( $renewing_borrower_obj, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
871 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
872 is( $info->{soonest_renew_date}, undef, "soonest_renew_date is not returned because this issue can be renewed" );
873 is( $renewokay, 1, 'Bug 25393: Can do a manual renew, even if renewal is automatic and premature' );
875 $error, 'auto_renew',
876 'Bug 25393: Can do a manual renew, even if renewal is automatic and premature, norenewalbefore = undef -> manual renewals are allowed at any time'
879 my ( $renewokay_cron, $error_cron, $info_cron ) =
880 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 );
882 $info_cron->{soonest_renew_date}, dt_from_string( $auto_renew_issue->date_due ),
883 "Due date is returned as earliest renewal date when the CanBookBeRenewed check is done by cron and error is 'auto_too_soon'"
887 branchcode => $branch,
888 borrowernumber => $reserving_borrowernumber,
889 biblionumber => $biblio->biblionumber,
890 itemnumber => $bibitems,
891 priority => $priority,
892 reservation_date => $resdate,
893 expiration_date => $expdate,
896 itemnumber => $item_4->itemnumber,
900 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
901 is( $renewokay, 0, 'Still should not be able to renew' );
902 is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' );
903 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 );
904 is( $renewokay, 0, 'Still should not be able to renew' );
905 is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' );
906 is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due), "Due date is returned as earliest renewal date when error is 'auto_too_soon'" );
907 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, 1 );
908 is( $renewokay, 0, 'Still should not be able to renew' );
909 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
910 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, 1, 1 );
911 is( $renewokay, 0, 'Still should not be able to renew' );
912 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
913 $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
914 Koha::Cache::Memory::Lite->flush();
915 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, 1 );
916 is( $renewokay, 0, 'Still should not be able to renew' );
917 is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
918 ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
920 $renewing_borrower_obj = Koha::Patrons->find($renewing_borrower_obj->borrowernumber);
921 $renewing_borrower_obj->autorenew_checkouts(0)->store;
922 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
923 is( $renewokay, 1, 'No renewal before is undef, but patron opted out of auto_renewal' );
924 $renewing_borrower_obj->autorenew_checkouts(1)->store;
928 # Test premature manual renewal
929 Koha::CirculationRules->set_rule(
931 categorycode => undef,
934 rule_name => 'norenewalbefore',
939 ( $renewokay, $error, $info ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
940 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
941 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
942 is( $info->{soonest_renew_date}, dt_from_string($issue_1->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
945 # Test premature automatic renewal
946 Koha::CirculationRules->set_rule(
948 categorycode => undef,
951 rule_name => 'noautorenewalbefore',
956 ( $renewokay, $error, $info ) =
957 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
958 is( $renewokay, 0, 'Bug 25393: Cannot renew, renewal is premature' );
959 is( $error, 'too_soon',
960 'Bug 25393: Cannot renew, renewal is premature (returned code is too_soon)'
963 $info->{soonest_renew_date}, dt_from_string( $auto_renew_issue->date_due )->subtract( days => 7 ),
964 "Soonest renew date returned when error is 'auto_too_soon'"
967 ( $renewokay_cron, $error_cron, $info_cron ) =
968 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 );
970 $error_cron, 'auto_too_soon',
971 'Bug 25393: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
973 $renewing_borrower_obj->autorenew_checkouts(0)->store;
974 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
975 is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' );
976 is( $error, 'too_soon', 'Error is too_soon, no auto' );
977 is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
978 $renewing_borrower_obj->autorenew_checkouts(1)->store;
980 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
981 # and test automatic renewal again
982 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
983 Koha::Cache::Memory::Lite->flush();
984 ( $renewokay, $error, $info ) =
985 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
986 is( $renewokay, 0, 'Bug 25393: Cannot manual renew, renewal is too soon' );
987 is( $error, 'too_soon',
988 'Bug 25393: Cannot manual renew, renewal is too soon, even though it\'s also scheduled for auto renewal'
990 is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
992 # Now we test for noautorenewalbefore if cron
993 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'noautorenewalbefore'});
994 Koha::Cache::Memory::Lite->flush();
995 ( $renewokay, $error, $info ) =
996 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 );
997 is( $renewokay, 0, 'Bug 25393: Cannot auto renew, renewal is too soon' );
998 is( $error, 'auto_too_soon',
999 'Bug 25393: Cannot auto renew, auto renewal is too soon'
1001 is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
1003 $renewing_borrower_obj->autorenew_checkouts(0)->store;
1004 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
1005 is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' );
1006 is( $error, 'too_soon', 'Error is too_soon, no auto' );
1007 is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
1008 $renewing_borrower_obj->autorenew_checkouts(1)->store;
1010 # Change policy so that loans can be renewed 99 days prior to the due date
1011 # and test automatic renewal again
1012 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
1013 Koha::Cache::Memory::Lite->flush();
1014 ( $renewokay, $error ) =
1015 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
1016 is( $renewokay, 1, 'Bug 25393: Can do a manual renew, even if renewal is automatic and premature' );
1017 is( $error, 'auto_renew',
1018 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
1021 # Now we test for noautorenewalbefore if cron
1022 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'noautorenewalbefore'});
1023 Koha::Cache::Memory::Lite->flush();
1024 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 );
1025 is( $renewokay, 1, 'Bug 25393: Can auto renew' );
1026 is( $error, 'auto_renew', 'Bug 25393: Can auto renew' );
1027 is( $info->{soonest_renew_date}, undef, "soonest_renew_date is not returned because this issue can be renewed" );
1029 $renewing_borrower_obj->autorenew_checkouts(0)->store;
1030 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
1031 is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' );
1032 $renewing_borrower_obj->autorenew_checkouts(1)->store;
1036 # Ensure autorenewal errors always take highest precedence
1037 subtest "auto_renewal errors first" => sub {
1040 my $auto_renew_item = $builder->build_sample_item(
1042 biblionumber => $biblio->biblionumber,
1047 my $ten_days_ahead = dt_from_string->add( days => 10 );
1048 my $issue = AddIssue(
1049 $renewing_borrower_obj, $auto_renew_item->barcode, $ten_days_ahead, undef, undef, undef,
1053 Koha::CirculationRules->set_rules(
1055 categorycode => undef,
1056 branchcode => undef,
1059 noautorenewalbefore => 7,
1060 renewalsallowed => 2,
1064 my ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue, undef, 'cron' );
1065 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1066 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - returned code is auto_too_soon' );
1068 $issue->renewals_count(2)->store;
1069 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue, undef, 'cron' );
1070 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1072 $error, 'auto_too_soon',
1073 'Cannot auto renew, too soon - auto renewal error takes precedence over non-autorenewal error too_many'
1077 subtest "too_late_renewal / no_auto_renewal_after" => sub {
1079 my $item_to_auto_renew = $builder->build_sample_item(
1081 biblionumber => $biblio->biblionumber,
1086 my $ten_days_before = dt_from_string->add( days => -10 );
1087 my $ten_days_ahead = dt_from_string->add( days => 10 );
1088 my $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1090 Koha::CirculationRules->set_rules(
1092 categorycode => undef,
1093 branchcode => undef,
1096 norenewalbefore => '7',
1097 no_auto_renewal_after => '9',
1101 ( $renewokay, $error ) =
1102 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1103 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1104 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1106 Koha::CirculationRules->set_rules(
1108 categorycode => undef,
1109 branchcode => undef,
1112 norenewalbefore => '7',
1113 no_auto_renewal_after => '10',
1117 ( $renewokay, $error ) =
1118 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1119 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1120 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
1122 Koha::CirculationRules->set_rules(
1124 categorycode => undef,
1125 branchcode => undef,
1128 norenewalbefore => '7',
1129 no_auto_renewal_after => '11',
1133 ( $renewokay, $error ) =
1134 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1135 is( $renewokay, 0, 'Do not renew, too_soon' );
1136 is( $error, 'too_soon', 'Cannot renew, too_soon - no_auto_renewal_after is defined(returned code is too_soon)' );
1138 # Now check for cron
1139 Koha::CirculationRules->set_rules(
1141 categorycode => undef,
1142 branchcode => undef,
1145 noautorenewalbefore => '9',
1146 no_auto_renewal_after => '11',
1150 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue, undef, 1 );
1151 is( $renewokay, 0, 'Do not renew, too_soon' );
1153 $error, 'auto_too_soon',
1154 'Cannot renew, too_soon - no_auto_renewal_after is defined(returned code is too_soon)'
1157 Koha::CirculationRules->set_rules(
1159 categorycode => undef,
1160 branchcode => undef,
1163 norenewalbefore => '10',
1164 no_auto_renewal_after => '11',
1168 ( $renewokay, $error ) =
1169 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1170 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1171 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1173 Koha::CirculationRules->set_rules(
1175 categorycode => undef,
1176 branchcode => undef,
1179 norenewalbefore => '10',
1180 no_auto_renewal_after => undef,
1181 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1185 ( $renewokay, $error ) =
1186 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1187 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1188 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1190 Koha::CirculationRules->set_rules(
1192 categorycode => undef,
1193 branchcode => undef,
1196 norenewalbefore => '7',
1197 no_auto_renewal_after => '15',
1198 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1202 ( $renewokay, $error ) =
1203 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1204 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1205 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1207 Koha::CirculationRules->set_rules(
1209 categorycode => undef,
1210 branchcode => undef,
1213 norenewalbefore => '10',
1214 no_auto_renewal_after => undef,
1215 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
1219 ( $renewokay, $error ) =
1220 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1221 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1222 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1225 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
1227 my $item_to_auto_renew = $builder->build_sample_item(
1229 biblionumber => $biblio->biblionumber,
1234 my $ten_days_before = dt_from_string->add( days => -10 );
1235 my $ten_days_ahead = dt_from_string->add( days => 10 );
1236 my $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1238 Koha::CirculationRules->set_rules(
1240 categorycode => undef,
1241 branchcode => undef,
1244 norenewalbefore => '10',
1245 no_auto_renewal_after => '11',
1249 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
1250 C4::Context->set_preference('OPACFineNoRenewals','10');
1251 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1252 my $fines_amount = 5;
1253 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
1254 $account->add_debit(
1256 amount => $fines_amount,
1257 interface => 'test',
1259 item_id => $item_to_auto_renew->itemnumber,
1260 description => "Some fines"
1262 )->status('RETURNED')->store;
1263 ( $renewokay, $error ) =
1264 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1265 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1266 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
1268 $account->add_debit(
1270 amount => $fines_amount,
1271 interface => 'test',
1273 item_id => $item_to_auto_renew->itemnumber,
1274 description => "Some fines"
1276 )->status('RETURNED')->store;
1277 ( $renewokay, $error ) =
1278 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1279 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1280 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
1282 $account->add_debit(
1284 amount => $fines_amount,
1285 interface => 'test',
1287 item_id => $item_to_auto_renew->itemnumber,
1288 description => "Some fines"
1290 )->status('RETURNED')->store;
1291 ( $renewokay, $error ) =
1292 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1293 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1294 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
1296 $account->add_credit(
1298 amount => $fines_amount,
1299 interface => 'test',
1301 description => "Some payment"
1304 ( $renewokay, $error ) =
1305 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1306 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1307 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1309 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
1310 ( $renewokay, $error ) =
1311 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1312 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1313 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1315 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
1316 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1319 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
1321 my $item_to_auto_renew = $builder->build_sample_item(
1323 biblionumber => $biblio->biblionumber,
1328 Koha::CirculationRules->set_rules(
1330 categorycode => undef,
1331 branchcode => undef,
1334 norenewalbefore => 10,
1335 no_auto_renewal_after => 11,
1340 my $ten_days_before = dt_from_string->add( days => -10 );
1341 my $ten_days_ahead = dt_from_string->add( days => 10 );
1343 # Patron is expired and BlockExpiredPatronOpacActions=0
1344 # => auto renew is allowed
1345 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
1346 my $issue = AddIssue( $expired_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1347 ( $renewokay, $error ) =
1348 CanBookBeRenewed( $expired_borrower_obj, $issue );
1349 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1350 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
1351 Koha::Checkouts->find( $issue->issue_id )->delete;
1354 # Patron is expired and BlockExpiredPatronOpacActions=1
1355 # => auto renew is not allowed
1356 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1357 $issue = AddIssue( $expired_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1358 ( $renewokay, $error ) =
1359 CanBookBeRenewed( $expired_borrower_obj, $issue );
1360 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1361 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
1364 # Patron is not expired and BlockExpiredPatronOpacActions=1
1365 # => auto renew is allowed
1366 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1367 $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1368 ( $renewokay, $error ) =
1369 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1370 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1371 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1375 subtest "GetLatestAutoRenewDate" => sub {
1377 my $item_to_auto_renew = $builder->build_sample_item(
1379 biblionumber => $biblio->biblionumber,
1384 my $ten_days_before = dt_from_string->add( days => -10 );
1385 my $ten_days_ahead = dt_from_string->add( days => 10 );
1386 my $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1387 Koha::CirculationRules->set_rules(
1389 categorycode => undef,
1390 branchcode => undef,
1393 norenewalbefore => '7',
1394 no_auto_renewal_after => '',
1395 no_auto_renewal_after_hard_limit => undef,
1399 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1400 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' );
1401 my $five_days_before = dt_from_string->add( days => -5 );
1402 Koha::CirculationRules->set_rules(
1404 categorycode => undef,
1405 branchcode => undef,
1408 norenewalbefore => '10',
1409 no_auto_renewal_after => '5',
1410 no_auto_renewal_after_hard_limit => undef,
1414 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj,, $issue );
1415 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1416 $five_days_before->truncate( to => 'minute' ),
1417 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1419 my $five_days_ahead = dt_from_string->add( days => 5 );
1420 $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1421 $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1422 $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1423 Koha::Cache::Memory::Lite->flush();
1424 Koha::CirculationRules->set_rules(
1426 categorycode => undef,
1427 branchcode => undef,
1430 norenewalbefore => '10',
1431 no_auto_renewal_after => '15',
1432 no_auto_renewal_after_hard_limit => undef,
1436 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1437 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1438 $five_days_ahead->truncate( to => 'minute' ),
1439 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1441 my $two_days_ahead = dt_from_string->add( days => 2 );
1442 Koha::CirculationRules->set_rules(
1444 categorycode => undef,
1445 branchcode => undef,
1448 norenewalbefore => '10',
1449 no_auto_renewal_after => '',
1450 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1454 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1455 is( $latest_auto_renew_date->truncate( to => 'day' ),
1456 $two_days_ahead->truncate( to => 'day' ),
1457 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1459 Koha::CirculationRules->set_rules(
1461 categorycode => undef,
1462 branchcode => undef,
1465 norenewalbefore => '10',
1466 no_auto_renewal_after => '15',
1467 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1471 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1472 is( $latest_auto_renew_date->truncate( to => 'day' ),
1473 $two_days_ahead->truncate( to => 'day' ),
1474 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1479 subtest "auto_renew_final" => sub {
1481 my $item_to_auto_renew = $builder->build_sample_item();
1482 Koha::CirculationRules->set_rules(
1484 categorycode => undef,
1485 branchcode => undef,
1486 itemtype => $item_to_auto_renew->itype,
1488 norenewalbefore => undef,
1489 renewalsallowed => 1,
1494 my $ten_days_before = dt_from_string->add( days => -10 );
1495 my $ten_days_ahead = dt_from_string->add( days => 10 );
1496 my $issue = AddIssue(
1497 $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before,
1498 undef, { auto_renew => 1 }
1500 $issue->renewals_count(0)->store;
1502 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue );
1503 is( $renewokay, 1, 'Success for auto_renewal' );
1504 is( $error, 'auto_renew_final', 'Auto renewal allowed, but it is the last one' );
1506 # Final unseen renewal
1507 Koha::CirculationRules->set_rules(
1509 categorycode => undef,
1510 branchcode => undef,
1511 itemtype => $item_to_auto_renew->itype,
1513 unseen_renewals_allowed => 2,
1514 renewalsallowed => 10,
1518 t::lib::Mocks::mock_preference( 'UnseenRenewals', 1 );
1519 $issue->unseen_renewals(1)->renewals_count(1)->store;
1521 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue );
1522 is( $renewokay, 1, 'Success for auto_renewal' );
1523 is( $error, 'auto_unseen_final', 'Final unseen renewal reported, not final overall' );
1525 # Final unseen renewal
1526 Koha::CirculationRules->set_rules(
1528 categorycode => undef,
1529 branchcode => undef,
1530 itemtype => $item_to_auto_renew->itype,
1532 unseen_renewals_allowed => 2,
1533 renewalsallowed => 2,
1537 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue );
1538 is( $renewokay, 1, 'Success for auto_renewal' );
1539 is( $error, 'auto_renew_final', 'Final auto renewal reported' );
1544 # set policy to forbid renewals
1545 Koha::CirculationRules->set_rules(
1547 categorycode => undef,
1548 branchcode => undef,
1551 norenewalbefore => undef,
1552 renewalsallowed => 0,
1557 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
1558 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1559 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1561 # Too many unseen renewals
1562 Koha::CirculationRules->set_rules(
1564 categorycode => undef,
1565 branchcode => undef,
1568 unseen_renewals_allowed => 2,
1569 renewalsallowed => 10,
1573 t::lib::Mocks::mock_preference('UnseenRenewals', 1);
1575 $issue_1->unseen_renewals(2)->store;
1577 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
1578 is( $renewokay, 0, 'Cannot renew, 0 unseen renewals allowed');
1579 is( $error, 'too_unseen', 'Cannot renew, returned code is too_unseen');
1580 Koha::CirculationRules->set_rules(
1582 categorycode => undef,
1583 branchcode => undef,
1586 norenewalbefore => undef,
1587 renewalsallowed => 0,
1591 t::lib::Mocks::mock_preference('UnseenRenewals', 0);
1593 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1594 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1595 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1597 C4::Overdues::UpdateFine(
1599 issue_id => $issue_1->id(),
1600 itemnumber => $item_1->itemnumber,
1601 borrowernumber => $renewing_borrower_obj->borrowernumber,
1604 due => Koha::DateUtils::output_pref($datedue)
1608 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower_obj->borrowernumber })->next();
1609 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1610 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1611 is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1612 is( $line->amount+0, 15, 'Account line amount is 15.00' );
1613 is( $line->issue_id, $issue_1->id, 'Account line issue id matches' );
1615 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1616 is( $offset->type, 'CREATE', 'Account offset type is CREATE' );
1617 is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1619 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1620 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1622 LostItem( $item_1->itemnumber, 'test', 1 );
1624 $line = Koha::Account::Lines->find($line->id);
1625 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1626 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1628 my $item = Koha::Items->find($item_1->itemnumber);
1629 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1630 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1631 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1633 my $total_due = $dbh->selectrow_array(
1634 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1635 undef, $renewing_borrower_obj->borrowernumber
1638 is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1640 C4::Context->dbh->do("DELETE FROM accountlines");
1642 C4::Overdues::UpdateFine(
1644 issue_id => $issue_2->id(),
1645 itemnumber => $item_2->itemnumber,
1646 borrowernumber => $renewing_borrower_obj->borrowernumber,
1649 due => Koha::DateUtils::output_pref($datedue)
1653 LostItem( $item_2->itemnumber, 'test', 0 );
1655 my $item2 = Koha::Items->find($item_2->itemnumber);
1656 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1657 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1659 $total_due = $dbh->selectrow_array(
1660 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1661 undef, $renewing_borrower_obj->borrowernumber
1664 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1666 my $future = dt_from_string();
1667 $future->add( days => 7 );
1668 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1669 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1671 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1672 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1673 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1674 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1675 LostItem( $item_3->itemnumber, 'test', 0 );
1676 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1677 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1679 $accountline->description,
1680 sprintf( "%s %s %s",
1681 $item_3->biblio->title || '',
1682 $item_3->barcode || '',
1683 $item_3->itemcallnumber || '' ),
1684 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1688 t::lib::Mocks::mock_preference('UseRecalls', 1);
1689 Koha::CirculationRules->set_rules({
1690 categorycode => undef,
1691 branchcode => undef,
1694 recalls_allowed => 10,
1695 renewalsallowed => 5,
1698 my $recall_borrower = $builder->build_object({ class => 'Koha::Patrons' });
1699 my $recall_biblio = $builder->build_sample_biblio();
1700 my $recall_item1 = $builder->build_sample_item({ biblionumber => $recall_biblio->biblionumber });
1701 my $recall_item2 = $builder->build_sample_item({ biblionumber => $recall_biblio->biblionumber });
1703 my $recall_issue = AddIssue( $renewing_borrower_obj, $recall_item1->barcode );
1705 # item-level and this item: renewal not allowed
1706 my $recall = Koha::Recall->new({
1707 biblio_id => $recall_item1->biblionumber,
1708 item_id => $recall_item1->itemnumber,
1709 patron_id => $recall_borrower->borrowernumber,
1710 pickup_library_id => $recall_borrower->branchcode,
1713 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1714 is( $error, 'recalled', 'Cannot renew item that has been recalled' );
1715 $recall->set_cancelled;
1717 # biblio-level requested recall: renewal not allowed
1718 $recall = Koha::Recall->new({
1719 biblio_id => $recall_item1->biblionumber,
1721 patron_id => $recall_borrower->borrowernumber,
1722 pickup_library_id => $recall_borrower->branchcode,
1725 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1726 is( $error, 'recalled', 'Cannot renew item if biblio is recalled and has no item allocated' );
1727 $recall->set_cancelled;
1729 # item-level and not this item: renewal allowed
1730 $recall = Koha::Recall->new({
1731 biblio_id => $recall_item2->biblionumber,
1732 item_id => $recall_item2->itemnumber,
1733 patron_id => $recall_borrower->borrowernumber,
1734 pickup_library_id => $recall_borrower->branchcode,
1737 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1738 is( $renewokay, 1, 'Can renew item if item-level recall on biblio is not on this item' );
1739 $recall->set_cancelled;
1741 # biblio-level waiting recall: renewal allowed
1742 $recall = Koha::Recall->new({
1743 biblio_id => $recall_item1->biblionumber,
1745 patron_id => $recall_borrower->borrowernumber,
1746 pickup_library_id => $recall_borrower->branchcode,
1749 $recall->set_waiting({ item => $recall_item1 });
1750 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1751 is( $renewokay, 1, 'Can renew item if biblio-level recall has already been allocated an item' );
1752 $recall->set_cancelled;
1755 subtest "CanBookBeRenewed | bookings" => sub {
1758 my $schema = Koha::Database->schema;
1759 $schema->storage->txn_begin;
1761 t::lib::Mocks::mock_preference( 'RenewalPeriodBase', 'date_due' );
1763 my $renewing_patron = $builder->build_object( { class => 'Koha::Patrons' } );
1764 my $booked_patron = $builder->build_object( { class => 'Koha::Patrons' } );
1765 my $item = $builder->build_sample_item( { bookable => 1 } );
1768 my $issue = AddIssue( $renewing_patron, $item->barcode );
1769 my $datedue = dt_from_string( $issue->date_due() );
1770 is( defined $issue->date_due(), 1, "Item checked out, due date: " . $issue->date_due() );
1772 # item-level booking
1773 my $booking = Koha::Booking->new(
1775 patron_id => $booked_patron->borrowernumber,
1776 item_id => $item->itemnumber,
1777 biblio_id => $item->biblio->biblionumber,
1778 start_date => $datedue->clone()->add( days => 2 ),
1779 end_date => $datedue->clone()->add( days => 10 ),
1783 # Proposed renewal would encroach on booking
1784 my ( $renewok, $error ) = CanBookBeRenewed( $renewing_patron, $issue, 0 );
1785 is( $renewok, 0, "Renewal not allowed as it would mean the item was not returned before the next booking" );
1786 is( $error, 'booked', "Error is 'booked'" );
1788 $schema->storage->txn_rollback;
1791 subtest "GetUpcomingDueIssues" => sub {
1794 my $branch = $library2->{branchcode};
1796 #Create another record
1797 my $biblio2 = $builder->build_sample_biblio();
1800 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1801 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1802 my $item_3 = $builder->build_sample_item(
1804 biblionumber => $biblio2->biblionumber,
1812 my %a_borrower_data = (
1813 firstname => 'Fridolyn',
1814 surname => 'SOMERS',
1815 categorycode => $patron_category->{categorycode},
1816 branchcode => $branch,
1819 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1820 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber );
1822 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1823 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1824 my $today = DateTime->today(time_zone => C4::Context->tz());
1826 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1827 my $datedue = dt_from_string( $issue->date_due() );
1828 my $issue_2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1829 my $datedue2 = dt_from_string( $issue->date_due() );
1833 # GetUpcomingDueIssues tests
1835 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1836 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1839 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1840 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1841 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1844 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1845 is ( scalar( @$upcoming_dues ), 1,
1846 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1849 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1851 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1853 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1854 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1856 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1857 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1859 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1860 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1862 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1863 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1865 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1866 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1868 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1869 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1873 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1874 my $branch = $library2->{branchcode};
1876 my $biblio = $builder->build_sample_biblio();
1879 my $item = $builder->build_sample_item(
1881 biblionumber => $biblio->biblionumber,
1888 my %a_borrower_data = (
1889 firstname => 'Kyle',
1891 categorycode => $patron_category->{categorycode},
1892 branchcode => $branch,
1895 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1897 my $borrower = Koha::Patrons->find( $borrowernumber );
1898 my $issue = AddIssue( $borrower, $item->barcode );
1901 issue_id => $issue->id(),
1902 itemnumber => $item->itemnumber,
1903 borrowernumber => $borrowernumber,
1909 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1910 my $count = $hr->{count};
1912 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1915 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1917 my $biblio = $builder->build_sample_biblio();
1918 my $item_1 = $builder->build_sample_item(
1920 biblionumber => $biblio->biblionumber,
1921 library => $library2->{branchcode},
1924 my $item_2= $builder->build_sample_item(
1926 biblionumber => $biblio->biblionumber,
1927 library => $library2->{branchcode},
1928 itype => $item_1->effective_itemtype,
1932 Koha::CirculationRules->set_rules(
1934 categorycode => undef,
1935 itemtype => $item_1->effective_itemtype,
1936 branchcode => undef,
1938 reservesallowed => 25,
1939 holds_per_record => 25,
1941 lengthunit => 'days',
1942 renewalsallowed => 1,
1944 norenewalbefore => undef,
1953 my $borrower1 = $builder->build_object(
1955 class => 'Koha::Patrons',
1957 firstname => 'Kyle',
1959 categorycode => $patron_category->{categorycode},
1960 branchcode => $library2->{branchcode},
1965 my $borrowernumber2 = $builder->build_object(
1967 class => 'Koha::Patrons',
1969 firstname => 'Chelsea',
1971 categorycode => $patron_category->{categorycode},
1972 branchcode => $library2->{branchcode},
1978 my $patron_category_2 = $builder->build(
1980 source => 'Category',
1982 category_type => 'P',
1984 BlockExpiredPatronOpacActions => -1, # Pick the pref value
1989 my $borrowernumber3 = $builder->build_object(
1991 class => 'Koha::Patrons',
1993 firstname => 'Carnegie',
1995 categorycode => $patron_category_2->{categorycode},
1996 branchcode => $library2->{branchcode},
2001 my $issue = AddIssue( $borrower1, $item_1->barcode );
2003 my ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
2004 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
2008 branchcode => $library2->{branchcode},
2009 borrowernumber => $borrowernumber2,
2010 biblionumber => $biblio->biblionumber,
2015 Koha::CirculationRules->set_rules(
2017 categorycode => undef,
2018 itemtype => $item_1->effective_itemtype,
2019 branchcode => undef,
2025 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
2026 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
2027 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
2029 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
2030 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
2031 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
2033 Koha::CirculationRules->set_rules(
2035 categorycode => undef,
2036 itemtype => $item_1->effective_itemtype,
2037 branchcode => undef,
2043 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
2044 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
2045 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
2047 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
2048 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
2049 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
2053 branchcode => $library2->{branchcode},
2054 borrowernumber => $borrowernumber3,
2055 biblionumber => $biblio->biblionumber,
2060 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
2061 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' );
2063 my $item_3= $builder->build_sample_item(
2065 biblionumber => $biblio->biblionumber,
2066 library => $library2->{branchcode},
2067 itype => $item_1->effective_itemtype,
2071 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
2072 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' );
2074 Koha::CirculationRules->set_rules(
2076 categorycode => $patron_category_2->{categorycode},
2077 itemtype => $item_1->effective_itemtype,
2078 branchcode => undef,
2080 reservesallowed => 0,
2085 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
2086 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' );
2088 Koha::CirculationRules->set_rules(
2090 categorycode => $patron_category_2->{categorycode},
2091 itemtype => $item_1->effective_itemtype,
2092 branchcode => undef,
2094 reservesallowed => 25,
2099 # Setting item not checked out to be not for loan but holdable
2100 $item_2->notforloan(-1)->store;
2102 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
2103 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' );
2105 my $mock_circ = Test::MockModule->new("C4::Circulation");
2106 $mock_circ->mock( CanItemBeReserved => sub {
2108 return { status => 'no' }
2111 $item_2->notforloan(0)->store;
2113 # Two items total, one item available, one issued, two holds on record
2116 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
2117 } [], "CanItemBeReserved not called when there are more possible holds than available items";
2118 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
2120 $item_3 = $builder->build_sample_item(
2122 biblionumber => $biblio->biblionumber,
2123 library => $library2->{branchcode},
2124 itype => $item_1->effective_itemtype,
2128 Koha::CirculationRules->set_rules(
2130 categorycode => undef,
2131 itemtype => $item_1->effective_itemtype,
2132 branchcode => undef,
2134 reservesallowed => 0,
2140 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
2141 } ["Checked","Checked"], "CanItemBeReserved only called once per available item if it returns a negative result for all items for a borrower";
2142 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
2147 # Don't allow renewing onsite checkout
2148 my $branch = $library->{branchcode};
2150 #Create another record
2151 my $biblio = $builder->build_sample_biblio();
2153 my $item = $builder->build_sample_item(
2155 biblionumber => $biblio->biblionumber,
2161 my $borrower = $builder->build_object(
2163 class => 'Koha::Patrons',
2167 categorycode => $patron_category->{categorycode},
2168 branchcode => $branch,
2173 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
2174 my ( $renewed, $error ) = CanBookBeRenewed( $borrower, $issue );
2175 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
2176 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
2180 my $library = $builder->build({ source => 'Branch' });
2182 my $biblio = $builder->build_sample_biblio();
2184 my $item = $builder->build_sample_item(
2186 biblionumber => $biblio->biblionumber,
2187 library => $library->{branchcode},
2191 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2193 my $issue = AddIssue( $patron, $item->barcode );
2196 issue_id => $issue->id,
2197 itemnumber => $item->itemnumber,
2198 borrowernumber => $patron->borrowernumber,
2205 issue_id => $issue->id,
2206 itemnumber => $item->itemnumber,
2207 borrowernumber => $patron->borrowernumber,
2212 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
2215 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
2218 my $homebranch = $builder->build( { source => 'Branch' } );
2219 my $holdingbranch = $builder->build( { source => 'Branch' } );
2220 my $otherbranch = $builder->build( { source => 'Branch' } );
2221 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2222 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2224 my $item = $builder->build_sample_item(
2226 homebranch => $homebranch->{branchcode},
2227 holdingbranch => $holdingbranch->{branchcode},
2230 Koha::CirculationRules->set_rules(
2232 categorycode => undef,
2233 itemtype => $item->effective_itemtype,
2234 branchcode => undef,
2236 reservesallowed => 25,
2238 lengthunit => 'days',
2239 renewalsallowed => 1,
2241 norenewalbefore => undef,
2250 set_userenv($holdingbranch);
2252 my $issue = AddIssue( $patron_1, $item->barcode );
2253 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
2255 my ( $error, $question, $alerts );
2257 # AllowReturnToBranch == anywhere
2258 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2259 ## Test that unknown barcodes don't generate internal server errors
2260 set_userenv($homebranch);
2261 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
2262 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
2263 ## Can be issued from homebranch
2264 set_userenv($homebranch);
2265 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2266 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2267 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2268 ## Can be issued from holdingbranch
2269 set_userenv($holdingbranch);
2270 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2271 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2272 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2273 ## Can be issued from another branch
2274 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2275 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2276 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2278 # AllowReturnToBranch == holdingbranch
2279 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2280 ## Cannot be issued from homebranch
2281 set_userenv($homebranch);
2282 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2283 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2284 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2285 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
2286 ## Can be issued from holdinbranch
2287 set_userenv($holdingbranch);
2288 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2289 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2290 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2291 ## Cannot be issued from another branch
2292 set_userenv($otherbranch);
2293 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2294 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2295 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2296 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
2298 # AllowReturnToBranch == homebranch
2299 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2300 ## Can be issued from holdinbranch
2301 set_userenv($homebranch);
2302 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2303 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2304 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2305 ## Cannot be issued from holdinbranch
2306 set_userenv($holdingbranch);
2307 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2308 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2309 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2310 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2311 ## Cannot be issued from holdinbranch
2312 set_userenv($otherbranch);
2313 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2314 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2315 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2316 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2318 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2321 subtest 'AddIssue & AllowReturnToBranch' => sub {
2324 my $homebranch = $builder->build( { source => 'Branch' } );
2325 my $holdingbranch = $builder->build( { source => 'Branch' } );
2326 my $otherbranch = $builder->build( { source => 'Branch' } );
2328 my $patron_1 = $builder->build_object({
2329 class => 'Koha::Patrons',
2330 value => { categorycode => $patron_category->{categorycode} }
2333 my $patron_2 = $builder->build_object({
2334 class => 'Koha::Patrons',
2335 value => { categorycode => $patron_category->{categorycode} }
2339 my $item = $builder->build_sample_item(
2341 homebranch => $homebranch->{branchcode},
2342 holdingbranch => $holdingbranch->{branchcode},
2346 set_userenv($holdingbranch);
2348 my $ref_issue = 'Koha::Checkout';
2349 my $issue = AddIssue( $patron_1, $item->barcode );
2351 my ( $error, $question, $alerts );
2353 # AllowReturnToBranch == homebranch
2354 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2355 ## Can be issued from homebranch
2356 set_userenv($homebranch);
2357 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
2358 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2359 ## Can be issued from holdinbranch
2360 set_userenv($holdingbranch);
2361 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
2362 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2363 ## Can be issued from another branch
2364 set_userenv($otherbranch);
2365 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
2366 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2368 # AllowReturnToBranch == holdinbranch
2369 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2370 ## Cannot be issued from homebranch
2371 set_userenv($homebranch);
2372 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
2373 ## Can be issued from holdingbranch
2374 set_userenv($holdingbranch);
2375 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
2376 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2377 ## Cannot be issued from another branch
2378 set_userenv($otherbranch);
2379 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
2381 # AllowReturnToBranch == homebranch
2382 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2383 ## Can be issued from homebranch
2384 set_userenv($homebranch);
2385 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
2386 AddIssue( $patron_1, $item->barcode ); # Re-issue to patron 1
2387 ## Cannot be issued from holdinbranch
2388 set_userenv($holdingbranch);
2389 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
2390 ## Cannot be issued from another branch
2391 set_userenv($otherbranch);
2392 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
2393 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2396 subtest 'AddIssue | recalls' => sub {
2399 t::lib::Mocks::mock_preference("UseRecalls", 1);
2400 t::lib::Mocks::mock_preference("item-level_itypes", 1);
2401 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2402 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2403 my $item = $builder->build_sample_item;
2404 Koha::CirculationRules->set_rules({
2405 branchcode => undef,
2407 categorycode => undef,
2409 recalls_allowed => 10,
2413 # checking out item that they have recalled
2414 my $recall1 = Koha::Recall->new(
2415 { patron_id => $patron1->borrowernumber,
2416 biblio_id => $item->biblionumber,
2417 item_id => $item->itemnumber,
2419 pickup_library_id => $patron1->branchcode,
2422 AddIssue( $patron1, $item->barcode, undef, undef, undef, undef, { recall_id => $recall1->id } );
2423 $recall1 = Koha::Recalls->find( $recall1->id );
2424 is( $recall1->fulfilled, 1, 'Recall was fulfilled when patron checked out item' );
2425 AddReturn( $item->barcode, $item->homebranch );
2427 # this item is has a recall request. cancel recall
2428 my $recall2 = Koha::Recall->new(
2429 { patron_id => $patron2->borrowernumber,
2430 biblio_id => $item->biblionumber,
2431 item_id => $item->itemnumber,
2433 pickup_library_id => $patron2->branchcode,
2436 AddIssue( $patron1, $item->barcode, undef, undef, undef, undef, { recall_id => $recall2->id, cancel_recall => 'cancel' } );
2437 $recall2 = Koha::Recalls->find( $recall2->id );
2438 is( $recall2->cancelled, 1, 'Recall was cancelled when patron checked out item' );
2439 AddReturn( $item->barcode, $item->homebranch );
2441 # this item is waiting to fulfill a recall. revert recall
2442 my $recall3 = Koha::Recall->new(
2443 { patron_id => $patron2->borrowernumber,
2444 biblio_id => $item->biblionumber,
2445 item_id => $item->itemnumber,
2447 pickup_library_id => $patron2->branchcode,
2450 $recall3->set_waiting;
2451 AddIssue( $patron1, $item->barcode, undef, undef, undef, undef, { recall_id => $recall3->id, cancel_recall => 'revert' } );
2452 $recall3 = Koha::Recalls->find( $recall3->id );
2453 is( $recall3->requested, 1, 'Recall was reverted from waiting when patron checked out item' );
2454 AddReturn( $item->barcode, $item->homebranch );
2457 subtest 'AddIssue & illrequests.due_date' => sub {
2460 t::lib::Mocks::mock_preference( 'ILLModule', 1 );
2461 my $library = $builder->build( { source => 'Branch' } );
2462 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2463 my $item = $builder->build_sample_item();
2465 set_userenv($library);
2467 my $custom_date_due = '4999-12-18 12:34:56';
2468 my $expected_date_due = '4999-12-18 23:59:00';
2469 my $illrequest = Koha::Illrequest->new({
2470 borrowernumber => $patron->borrowernumber,
2471 biblio_id => $item->biblionumber,
2472 branchcode => $library->{'branchcode'},
2473 due_date => $custom_date_due,
2476 my $issue = AddIssue( $patron, $item->barcode );
2477 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2479 $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2480 $item = $builder->build_sample_item();
2481 $custom_date_due = '4999-12-19';
2482 $expected_date_due = '4999-12-19 23:59:00';
2483 $illrequest = Koha::Illrequest->new({
2484 borrowernumber => $patron->borrowernumber,
2485 biblio_id => $item->biblionumber,
2486 branchcode => $library->{'branchcode'},
2487 due_date => $custom_date_due,
2490 $issue = AddIssue( $patron, $item->barcode );
2491 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2494 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
2497 my $library = $builder->build( { source => 'Branch' } );
2498 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2499 my $item_1 = $builder->build_sample_item(
2501 library => $library->{branchcode},
2504 my $item_2 = $builder->build_sample_item(
2506 library => $library->{branchcode},
2509 Koha::CirculationRules->set_rules(
2511 categorycode => undef,
2513 branchcode => $library->{branchcode},
2515 reservesallowed => 25,
2517 lengthunit => 'days',
2518 renewalsallowed => 1,
2520 norenewalbefore => undef,
2529 my ( $error, $question, $alerts );
2531 # Patron cannot issue item_1, they have overdues
2532 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
2533 my $issue = AddIssue( $patron, $item_1->barcode, $yesterday ); # Add an overdue
2535 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
2536 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2537 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
2538 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
2540 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
2541 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2542 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2543 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
2545 # Patron cannot issue item_1, they are debarred
2546 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
2547 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
2548 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2549 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2550 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
2552 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
2553 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2554 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2555 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
2558 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
2561 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2562 my $patron_category_x = $builder->build_object(
2564 class => 'Koha::Patron::Categories',
2565 value => { category_type => 'X' }
2568 my $patron = $builder->build_object(
2570 class => 'Koha::Patrons',
2572 categorycode => $patron_category_x->categorycode,
2573 gonenoaddress => undef,
2580 my $item_1 = $builder->build_sample_item(
2582 library => $library->{branchcode},
2586 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
2589 '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)'
2592 my $stat = Koha::Statistics->search( { itemnumber => $item_1->itemnumber } )->next;
2593 is( $stat->branch, C4::Context->userenv->{'branch'}, 'Recorded a branch' );
2594 is( $stat->type, 'localuse', 'Recorded type as localuse' );
2595 is( $stat->itemnumber, $item_1->itemnumber, 'Recorded an itemnumber' );
2596 is( $stat->itemtype, $item_1->effective_itemtype, 'Recorded an itemtype' );
2597 is( $stat->borrowernumber, $patron->borrowernumber, 'Recorded a borrower number' );
2598 is( $stat->ccode, $item_1->ccode, 'Recorded a collection code' );
2599 is( $stat->categorycode, $patron->categorycode, 'Recorded a categorycode' );
2600 is( $stat->location, $item_1->location, 'Recorded a location' );
2602 t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode } );
2603 my $patron_2 = $builder->build_object(
2604 { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2605 my $item_2 = $builder->build_sample_item( { library => $library->branchcode } );
2606 my $issue = AddIssue( $patron_2, $item_2->barcode );
2607 $item_2->discard_changes;
2608 ok( $item_2->onloan, "Item is checked out" );
2610 my $item_3 = $builder->build_sample_item( { library => $library->branchcode } );
2611 CanBookBeIssued( $patron, $item_3->barcode );
2612 $item_3->discard_changes;
2614 Koha::Statistics->search( { itemnumber => $item_3->itemnumber } )->count, 1,
2615 'Single entry recorded in the stats table'
2618 my $item_4 = $builder->build_sample_item( { library => $library->branchcode } );
2619 AddIssue( $patron_2, $item_4->barcode );
2620 $item_4->discard_changes;
2622 Koha::Statistics->search( { itemnumber => $item_4->itemnumber } )->count, 1,
2623 'Issue should be recorded in statistics table for item 4.'
2625 CanBookBeIssued( $patron, $item_4->barcode );
2626 $item_4->discard_changes;
2628 Koha::Statistics->search( { itemnumber => $item_4->itemnumber } )->count, 2,
2629 'Issue, return, and localuse should be recorded in statistics table for item 4.'
2632 # TODO There are other tests to provide here
2635 subtest 'MultipleReserves' => sub {
2638 my $biblio = $builder->build_sample_biblio();
2640 my $branch = $library2->{branchcode};
2642 my $item_1 = $builder->build_sample_item(
2644 biblionumber => $biblio->biblionumber,
2646 replacementprice => 12.00,
2651 my $item_2 = $builder->build_sample_item(
2653 biblionumber => $biblio->biblionumber,
2655 replacementprice => 12.00,
2662 my $resdate = undef;
2663 my $expdate = undef;
2665 my $checkitem = undef;
2669 my $patron = $builder->build_object(
2671 class => 'Koha::Patrons',
2673 firstname => 'John',
2674 surname => 'Renewal',
2675 categorycode => $patron_category->{categorycode},
2676 branchcode => $branch,
2681 my $issue = AddIssue( $patron, $item_1->barcode);
2682 my $datedue = dt_from_string( $issue->date_due() );
2683 is (defined $issue->date_due(), 1, "item 1 checked out");
2684 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
2686 my $reserving_borrowernumber1 = $builder->build_object(
2688 class => 'Koha::Patrons',
2690 firstname => 'Katrin',
2691 surname => 'Reservation',
2692 categorycode => $patron_category->{categorycode},
2693 branchcode => $branch,
2700 branchcode => $branch,
2701 borrowernumber => $reserving_borrowernumber1,
2702 biblionumber => $biblio->biblionumber,
2703 priority => $priority,
2704 reservation_date => $resdate,
2705 expiration_date => $expdate,
2707 itemnumber => $checkitem,
2712 my $reserving_borrowernumber2 = $builder->build_object(
2714 class => 'Koha::Patrons',
2716 firstname => 'Kirk',
2717 surname => 'Reservation',
2718 categorycode => $patron_category->{categorycode},
2719 branchcode => $branch,
2726 branchcode => $branch,
2727 borrowernumber => $reserving_borrowernumber2,
2728 biblionumber => $biblio->biblionumber,
2729 priority => $priority,
2730 reservation_date => $resdate,
2731 expiration_date => $expdate,
2733 itemnumber => $checkitem,
2739 my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue, 1);
2740 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2743 my $item_3 = $builder->build_sample_item(
2745 biblionumber => $biblio->biblionumber,
2747 replacementprice => 12.00,
2753 my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue, 1);
2754 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2758 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2761 my $library = $builder->build( { source => 'Branch' } );
2762 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2764 my $biblionumber = $builder->build_sample_biblio(
2766 branchcode => $library->{branchcode},
2769 my $item_1 = $builder->build_sample_item(
2771 biblionumber => $biblionumber,
2772 library => $library->{branchcode},
2776 my $item_2 = $builder->build_sample_item(
2778 biblionumber => $biblionumber,
2779 library => $library->{branchcode},
2783 Koha::CirculationRules->set_rules(
2785 categorycode => undef,
2787 branchcode => $library->{branchcode},
2789 reservesallowed => 25,
2791 lengthunit => 'days',
2792 renewalsallowed => 1,
2794 norenewalbefore => undef,
2803 my ( $error, $question, $alerts );
2804 my $issue = AddIssue( $patron, $item_1->barcode, dt_from_string->add( days => 1 ) );
2806 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2807 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2809 { error => $error, alerts => $alerts },
2810 { error => {}, alerts => {} },
2811 'No error or alert should be raised'
2813 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2815 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2816 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2818 { error => $error, question => $question, alerts => $alerts },
2819 { error => {}, question => {}, alerts => {} },
2820 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2823 # Add a subscription
2824 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2826 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2827 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2829 { error => $error, question => $question, alerts => $alerts },
2830 { error => {}, question => {}, alerts => {} },
2831 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2834 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2835 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2837 { error => $error, question => $question, alerts => $alerts },
2838 { error => {}, question => {}, alerts => {} },
2839 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2843 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2846 my $library = $builder->build( { source => 'Branch' } );
2847 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2850 my $biblionumber = $builder->build_sample_biblio(
2852 branchcode => $library->{branchcode},
2855 my $item_1 = $builder->build_sample_item(
2857 biblionumber => $biblionumber,
2858 library => $library->{branchcode},
2861 my $item_2 = $builder->build_sample_item(
2863 biblionumber => $biblionumber,
2864 library => $library->{branchcode},
2868 # And the circulation rule
2869 Koha::CirculationRules->search->delete;
2870 Koha::CirculationRules->set_rules(
2872 categorycode => undef,
2874 branchcode => undef,
2877 firstremind => 1, # 1 day of grace
2878 finedays => 2, # 2 days of fine per day of overdue
2879 lengthunit => 'days',
2884 # Patron cannot issue item_1, they have overdues
2885 my $now = dt_from_string;
2886 my $five_days_ago = $now->clone->subtract( days => 5 );
2887 my $ten_days_ago = $now->clone->subtract( days => 10 );
2888 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2889 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2890 ; # Add another overdue
2892 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2893 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2894 my $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2895 is( $suspensions->count, 1, "Suspension added" );
2896 my $THE_suspension = $suspensions->next;
2898 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2899 # Same for the others
2900 my $expected_expiration = output_pref(
2902 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2903 dateformat => 'sql',
2907 is( $THE_suspension->expiration, $expected_expiration, "Suspesion expiration set" );
2909 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2910 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2911 is( $suspensions->count, 1, "Only one suspension" );
2912 $THE_suspension = $suspensions->next;
2914 $expected_expiration = output_pref(
2916 dt => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2917 dateformat => 'sql',
2921 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2923 Koha::Patron::Debarments::DelUniqueDebarment(
2924 { borrowernumber => $patron->borrowernumber, type => 'SUSPENSION' } );
2926 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2927 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2928 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2929 ; # Add another overdue
2930 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2931 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2932 is( $suspensions->count, 1, "Only one suspension" );
2933 $THE_suspension = $suspensions->next;
2935 $expected_expiration = output_pref(
2937 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2938 dateformat => 'sql',
2942 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2944 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2945 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2946 is( $suspensions->count, 1, "Only one suspension" );
2947 $THE_suspension = $suspensions->next;
2949 $expected_expiration = output_pref(
2951 dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2952 dateformat => 'sql',
2956 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2959 subtest 'AddReturn + suspension_chargeperiod' => sub {
2962 my $library = $builder->build( { source => 'Branch' } );
2963 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2965 my $biblionumber = $builder->build_sample_biblio(
2967 branchcode => $library->{branchcode},
2970 my $item_1 = $builder->build_sample_item(
2972 biblionumber => $biblionumber,
2973 library => $library->{branchcode},
2977 # And the issuing rule
2978 Koha::CirculationRules->search->delete;
2979 Koha::CirculationRules->set_rules(
2981 categorycode => '*',
2986 firstremind => 0, # 0 day of grace
2987 finedays => 2, # 2 days of fine per day of overdue
2988 suspension_chargeperiod => 1,
2989 lengthunit => 'days',
2994 my $now = dt_from_string;
2995 my $five_days_ago = $now->clone->subtract( days => 5 );
2996 # We want to charge 2 days every day, without grace
2997 # With 5 days of overdue: 5 * Z
2998 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2999 test_debarment_on_checkout(
3002 library => $library,
3004 due_date => $five_days_ago,
3005 expiration_date => $expected_expiration,
3009 # Same with undef firstremind
3010 Koha::CirculationRules->search->delete;
3011 Koha::CirculationRules->set_rules(
3013 categorycode => '*',
3018 firstremind => undef, # 0 day of grace
3019 finedays => 2, # 2 days of fine per day of overdue
3020 suspension_chargeperiod => 1,
3021 lengthunit => 'days',
3026 my $now = dt_from_string;
3027 my $five_days_ago = $now->clone->subtract( days => 5 );
3028 # We want to charge 2 days every day, without grace
3029 # With 5 days of overdue: 5 * Z
3030 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
3031 test_debarment_on_checkout(
3034 library => $library,
3036 due_date => $five_days_ago,
3037 expiration_date => $expected_expiration,
3041 # We want to charge 2 days every 2 days, without grace
3042 # With 5 days of overdue: (5 * 2) / 2
3043 Koha::CirculationRules->set_rule(
3045 categorycode => undef,
3046 branchcode => undef,
3048 rule_name => 'suspension_chargeperiod',
3053 $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
3054 test_debarment_on_checkout(
3057 library => $library,
3059 due_date => $five_days_ago,
3060 expiration_date => $expected_expiration,
3064 # We want to charge 2 days every 3 days, with 1 day of grace
3065 # With 5 days of overdue: ((5-1) / 3 ) * 2
3066 Koha::CirculationRules->set_rules(
3068 categorycode => undef,
3069 branchcode => undef,
3072 suspension_chargeperiod => 3,
3077 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
3078 test_debarment_on_checkout(
3081 library => $library,
3083 due_date => $five_days_ago,
3084 expiration_date => $expected_expiration,
3088 # Use finesCalendar to know if holiday must be skipped to calculate the due date
3089 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
3090 Koha::CirculationRules->set_rules(
3092 categorycode => undef,
3093 branchcode => undef,
3097 suspension_chargeperiod => 1,
3102 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
3103 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
3105 # Adding a holiday 2 days ago
3106 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
3107 my $two_days_ago = $now->clone->subtract( days => 2 );
3108 $calendar->insert_single_holiday(
3109 day => $two_days_ago->day,
3110 month => $two_days_ago->month,
3111 year => $two_days_ago->year,
3112 title => 'holidayTest-2d',
3113 description => 'holidayDesc 2 days ago'
3115 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
3116 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
3117 test_debarment_on_checkout(
3120 library => $library,
3122 due_date => $five_days_ago,
3123 expiration_date => $expected_expiration,
3127 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
3128 my $two_days_ahead = $now->clone->add( days => 2 );
3129 $calendar->insert_single_holiday(
3130 day => $two_days_ahead->day,
3131 month => $two_days_ahead->month,
3132 year => $two_days_ahead->year,
3133 title => 'holidayTest+2d',
3134 description => 'holidayDesc 2 days ahead'
3137 # Same as above, but we should skip D+2
3138 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
3139 test_debarment_on_checkout(
3142 library => $library,
3144 due_date => $five_days_ago,
3145 expiration_date => $expected_expiration,
3149 # Adding another holiday, day of expiration date
3150 my $expected_expiration_dt = dt_from_string($expected_expiration);
3151 $calendar->insert_single_holiday(
3152 day => $expected_expiration_dt->day,
3153 month => $expected_expiration_dt->month,
3154 year => $expected_expiration_dt->year,
3155 title => 'holidayTest_exp',
3156 description => 'holidayDesc on expiration date'
3158 # Expiration date will be the day after
3159 test_debarment_on_checkout(
3162 library => $library,
3164 due_date => $five_days_ago,
3165 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
3169 test_debarment_on_checkout(
3172 library => $library,
3174 return_date => $now->clone->add(days => 5),
3175 expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
3179 test_debarment_on_checkout(
3182 library => $library,
3184 due_date => $now->clone->add(days => 1),
3185 return_date => $now->clone->add(days => 5),
3186 expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
3190 Koha::CirculationRules->search->delete;
3191 Koha::CirculationRules->set_rules(
3193 categorycode => undef,
3195 branchcode => undef,
3198 lengthunit => 'days',
3203 Koha::Patron::Debarments::AddDebarment(
3205 borrowernumber => $patron->borrowernumber,
3206 expiration => '9999-12-31',
3211 AddIssue( $patron, $item_1->barcode, $now->clone->subtract( days => 1 ) );
3212 my ( undef, $message ) = AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
3213 is( $message->{WasReturned} && exists $message->{ForeverDebarred}, 1, 'Forever debarred message for Addreturn when overdue');
3215 Koha::Patron::Debarments::DelUniqueDebarment(
3217 borrowernumber => $patron->borrowernumber,
3221 Koha::Patron::Debarments::AddDebarment(
3223 borrowernumber => $patron->borrowernumber,
3224 expiration => $now->clone->add( days => 10 ),
3229 AddIssue( $patron, $item_1->barcode, $now->clone->subtract( days => 1 ) );
3230 (undef, $message) = AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
3231 is( $message->{WasReturned} && exists $message->{PrevDebarred}, 1, 'Previously debarred message for Addreturn when overdue');
3234 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
3237 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
3238 my $patron1 = $builder->build_object(
3240 class => 'Koha::Patrons',
3242 branchcode => $library->branchcode,
3243 categorycode => $patron_category->{categorycode}
3247 my $patron2 = $builder->build_object(
3249 class => 'Koha::Patrons',
3251 branchcode => $library->branchcode,
3252 categorycode => $patron_category->{categorycode}
3257 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
3259 my $item = $builder->build_sample_item(
3261 library => $library->branchcode,
3265 my ( $error, $question, $alerts );
3266 my $issue = AddIssue( $patron1, $item->barcode );
3268 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
3269 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
3270 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' );
3272 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
3273 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
3274 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' );
3276 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
3280 subtest 'AddReturn | is_overdue' => sub {
3283 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
3284 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
3285 t::lib::Mocks::mock_preference('finesMode', 'production');
3286 t::lib::Mocks::mock_preference('MaxFine', '100');
3288 my $library = $builder->build( { source => 'Branch' } );
3289 my $patron = $builder->build_object(
3291 class => 'Koha::Patrons',
3292 value => { categorycode => $patron_category->{categorycode} }
3295 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
3296 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3298 my $item = $builder->build_sample_item(
3300 library => $library->{branchcode},
3301 replacementprice => 7
3305 Koha::CirculationRules->search->delete;
3306 Koha::CirculationRules->set_rules(
3308 categorycode => undef,
3310 branchcode => undef,
3313 lengthunit => 'days',
3314 fine => 1, # Charge 1 every day of overdue
3320 my $now = dt_from_string;
3321 my $one_day_ago = $now->clone->subtract( days => 1 );
3322 my $two_days_ago = $now->clone->subtract( days => 2 );
3323 my $five_days_ago = $now->clone->subtract( days => 5 );
3324 my $ten_days_ago = $now->clone->subtract( days => 10 );
3326 # No return date specified, today will be used => 10 days overdue charged
3327 AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago
3328 AddReturn( $item->barcode, $library->{branchcode} );
3329 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
3330 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3332 # specify return date 5 days before => no overdue charged
3333 AddIssue( $patron, $item->barcode, $five_days_ago ); # date due was 5d ago
3334 AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
3335 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
3336 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3338 # specify return date 5 days later => 5 days overdue charged
3339 AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago
3340 AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
3341 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
3342 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3344 # specify return date 5 days later, specify exemptfine => no overdue charge
3345 AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago
3346 AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago );
3347 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
3348 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3350 subtest 'bug 22877 | Lost item return' => sub {
3354 my $issue = AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago
3356 # Fake fines cronjob on this checkout
3358 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3359 $ten_days_ago, $now );
3362 issue_id => $issue->issue_id,
3363 itemnumber => $item->itemnumber,
3364 borrowernumber => $patron->borrowernumber,
3366 due => output_pref($ten_days_ago)
3369 is( int( $patron->account->balance() ),
3370 10, "Overdue fine of 10 days overdue" );
3372 # Fake longoverdue with charge and not marking returned
3373 LostItem( $item->itemnumber, 'cronjob', 0 );
3374 is( int( $patron->account->balance() ),
3375 17, "Lost fine of 7 plus 10 days overdue" );
3377 # Now we return it today
3378 AddReturn( $item->barcode, $library->{branchcode} );
3379 is( int( $patron->account->balance() ),
3380 17, "Should have a single 10 days overdue fine and lost charge" );
3383 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3386 subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
3390 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3392 my $issue = AddIssue( $patron, $item->barcode, $one_day_ago ); # date due was 1d ago
3394 # Fake fines cronjob on this checkout
3396 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3397 $one_day_ago, $now );
3400 issue_id => $issue->issue_id,
3401 itemnumber => $item->itemnumber,
3402 borrowernumber => $patron->borrowernumber,
3404 due => output_pref($one_day_ago)
3407 is( int( $patron->account->balance() ),
3408 1, "Overdue fine of 1 day overdue" );
3410 # Backdated return (dropbox mode example - charge should be removed)
3411 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3412 is( int( $patron->account->balance() ),
3413 0, "Overdue fine should be annulled" );
3414 my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3415 is( $lines->count, 0, "Overdue fine accountline has been removed");
3417 $issue = AddIssue( $patron, $item->barcode, $two_days_ago ); # date due was 2d ago
3419 # Fake fines cronjob on this checkout
3421 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3422 $two_days_ago, $now );
3425 issue_id => $issue->issue_id,
3426 itemnumber => $item->itemnumber,
3427 borrowernumber => $patron->borrowernumber,
3429 due => output_pref($one_day_ago)
3432 is( int( $patron->account->balance() ),
3433 2, "Overdue fine of 2 days overdue" );
3435 # Payment made against fine
3436 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3437 my $debit = $lines->next;
3438 my $credit = $patron->account->add_credit(
3442 interface => 'test',
3445 $credit->apply( { debits => [$debit] } );
3447 is( int( $patron->account->balance() ),
3448 0, "Overdue fine should be paid off" );
3449 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3450 is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
3451 my $line = $lines->next;
3452 is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
3453 is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
3455 # Backdated return (dropbox mode example - charge should be removed)
3456 AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
3457 is( int( $patron->account->balance() ),
3458 -1, "Refund credit has been applied" );
3459 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
3460 is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
3462 $line = $lines->next;
3463 is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
3464 is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
3465 is($line->status,'RETURNED', "Overdue fine is fixed");
3466 $line = $lines->next;
3467 is($line->amount+0,-2, "Original payment amount remains as 2");
3468 is($line->amountoutstanding+0,0, "Original payment remains applied");
3469 $line = $lines->next;
3470 is($line->amount+0,-1, "Refund amount correctly set to 1");
3471 is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
3474 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3477 subtest 'bug 25417 | backdated return + exemptfine' => sub {
3481 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3483 my $issue = AddIssue( $patron, $item->barcode, $one_day_ago ); # date due was 1d ago
3485 # Fake fines cronjob on this checkout
3487 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3488 $one_day_ago, $now );
3491 issue_id => $issue->issue_id,
3492 itemnumber => $item->itemnumber,
3493 borrowernumber => $patron->borrowernumber,
3495 due => output_pref($one_day_ago)
3498 is( int( $patron->account->balance() ),
3499 1, "Overdue fine of 1 day overdue" );
3501 # Backdated return (dropbox mode example - charge should no longer exist)
3502 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3503 is( int( $patron->account->balance() ),
3504 0, "Overdue fine should be annulled" );
3507 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3510 subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
3513 t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
3515 my $due_date = dt_from_string;
3516 my $issue = AddIssue( $patron, $item->barcode, $due_date );
3521 issue_id => $issue->issue_id,
3522 itemnumber => $item->itemnumber,
3523 borrowernumber => $patron->borrowernumber,
3525 due => output_pref($due_date)
3528 is( $patron->account->balance(),
3529 0.25, 'Overdue fine of $0.25 recorded' );
3531 # Backdate return to exact due date and time
3532 my ( undef, $message ) =
3533 AddReturn( $item->barcode, $library->{branchcode},
3537 Koha::Account::Lines->find( { issue_id => $issue->id } );
3538 ok( !$accountline, 'accountline removed as expected' );
3541 $issue = AddIssue( $patron, $item->barcode, $due_date );
3546 issue_id => $issue->issue_id,
3547 itemnumber => $item->itemnumber,
3548 borrowernumber => $patron->borrowernumber,
3550 due => output_pref($due_date)
3553 is( $patron->account->balance(),
3554 0.25, 'Overdue fine of $0.25 recorded' );
3556 # Partial pay accruing fine
3557 my $lines = Koha::Account::Lines->search(
3559 borrowernumber => $patron->borrowernumber,
3560 issue_id => $issue->id
3563 my $debit = $lines->next;
3564 my $credit = $patron->account->add_credit(
3568 interface => 'test',
3571 $credit->apply( { debits => [$debit] } );
3573 is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
3575 # Backdate return to exact due date and time
3576 ( undef, $message ) =
3577 AddReturn( $item->barcode, $library->{branchcode},
3580 $lines = Koha::Account::Lines->search(
3582 borrowernumber => $patron->borrowernumber,
3583 issue_id => $issue->id
3586 $accountline = $lines->next;
3587 is( $accountline->amountoutstanding + 0,
3588 0, 'Partially paid fee amount outstanding was reduced to 0' );
3589 is( $accountline->amount + 0,
3590 0, 'Partially paid fee amount was reduced to 0' );
3591 is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
3594 Koha::Account::Lines->search(
3595 { borrowernumber => $patron->borrowernumber } )->delete;
3598 subtest 'enh 23091 | Lost item return policies' => sub {
3601 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3603 my $branchcode_false =
3604 $builder->build( { source => 'Branch' } )->{branchcode};
3605 my $specific_rule_false = $builder->build(
3607 source => 'CirculationRule',
3609 branchcode => $branchcode_false,
3610 categorycode => undef,
3612 rule_name => 'lostreturn',
3617 my $branchcode_refund =
3618 $builder->build( { source => 'Branch' } )->{branchcode};
3619 my $specific_rule_refund = $builder->build(
3621 source => 'CirculationRule',
3623 branchcode => $branchcode_refund,
3624 categorycode => undef,
3626 rule_name => 'lostreturn',
3627 rule_value => 'refund'
3631 my $branchcode_restore =
3632 $builder->build( { source => 'Branch' } )->{branchcode};
3633 my $specific_rule_restore = $builder->build(
3635 source => 'CirculationRule',
3637 branchcode => $branchcode_restore,
3638 categorycode => undef,
3640 rule_name => 'lostreturn',
3641 rule_value => 'restore'
3645 my $branchcode_charge =
3646 $builder->build( { source => 'Branch' } )->{branchcode};
3647 my $specific_rule_charge = $builder->build(
3649 source => 'CirculationRule',
3651 branchcode => $branchcode_charge,
3652 categorycode => undef,
3654 rule_name => 'lostreturn',
3655 rule_value => 'charge'
3660 my $branchcode_refund_unpaid =
3661 $builder->build( { source => 'Branch' } )->{branchcode};
3662 my $specific_rule_refund_unpaid = $builder->build(
3664 source => 'CirculationRule',
3666 branchcode => $branchcode_refund_unpaid,
3667 categorycode => undef,
3669 rule_name => 'lostreturn',
3670 rule_value => 'refund_unpaid'
3675 my $replacement_amount = 99.00;
3676 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
3677 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
3678 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
3679 t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 );
3680 t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
3682 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
3685 subtest 'lostreturn | refund_unpaid' => sub {
3688 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund_unpaid });
3690 my $item = $builder->build_sample_item(
3692 replacementprice => $replacement_amount
3697 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode );
3700 $item->itemlost(3)->store;
3701 C4::Circulation::LostItem( $item->itemnumber, 1 );
3703 my $lost_fee_lines = Koha::Account::Lines->search(
3705 borrowernumber => $patron->id,
3706 itemnumber => $item->itemnumber,
3707 debit_type_code => 'LOST'
3710 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3711 my $lost_fee_line = $lost_fee_lines->next;
3712 is( int($lost_fee_line->amount),
3713 $replacement_amount, 'The right LOST amount is generated' );
3714 is( int($lost_fee_line->amountoutstanding),
3715 $replacement_amount,
3716 'The right LOST amountoutstanding is generated' );
3717 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3720 int($patron->account->balance),
3721 $replacement_amount ,
3722 "Account balance equals the replacement amount after being charged lost fee when no payments has been made"
3725 # Return lost item without any payments having been made
3726 my ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3728 $lost_fee_line->discard_changes;
3730 is( int($lost_fee_line->amount), $replacement_amount, 'The LOST amount is left intact' );
3731 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero' );
3732 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set' );
3734 int($patron->account->balance),
3736 'Account balance should be zero after returning item with lost fee when no payments has been made'
3739 # Create a second item
3740 $item = $builder->build_sample_item(
3742 replacementprice => $replacement_amount
3747 $issue = C4::Circulation::AddIssue( $patron, $item->barcode );
3750 $item->itemlost(3)->store;
3751 C4::Circulation::LostItem( $item->itemnumber, 1 );
3753 $lost_fee_lines = Koha::Account::Lines->search(
3755 borrowernumber => $patron->id,
3756 itemnumber => $item->itemnumber,
3757 debit_type_code => 'LOST'
3760 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3761 $lost_fee_line = $lost_fee_lines->next;
3763 # Make partial payment
3764 $patron->account->payin_amount({
3766 interface => 'intranet',
3767 payment_type => 'CASH',
3768 user_id => $patron->borrowernumber,
3770 debits => [$lost_fee_line]
3773 $lost_fee_line->discard_changes;
3775 is( int($lost_fee_line->amountoutstanding),
3777 'The LOST amountoutstanding is the expected amount after partial payment of lost fee'
3781 int($patron->account->balance),
3783 'Account balance is the expected amount after partial payment of lost fee'
3786 # Return lost item with partial payment having been made
3787 ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3789 $lost_fee_line->discard_changes;
3791 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero after returning lost item with partial payment' );
3792 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set for lost item with partial payment' );
3794 int($patron->account->balance),
3796 'Account balance should be zero after returning item with lost fee when partial payment has been made'
3799 # Create a third item
3800 $item = $builder->build_sample_item(
3802 replacementprice => $replacement_amount
3807 $issue = C4::Circulation::AddIssue( $patron, $item->barcode );
3810 $item->itemlost(3)->store;
3811 C4::Circulation::LostItem( $item->itemnumber, 1 );
3813 $lost_fee_lines = Koha::Account::Lines->search(
3815 borrowernumber => $patron->id,
3816 itemnumber => $item->itemnumber,
3817 debit_type_code => 'LOST'
3820 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3821 $lost_fee_line = $lost_fee_lines->next;
3824 $patron->account->payin_amount({
3826 interface => 'intranet',
3827 payment_type => 'CASH',
3828 user_id => $patron->borrowernumber,
3829 amount => $replacement_amount,
3830 debits => [$lost_fee_line]
3833 $lost_fee_line->discard_changes;
3835 is( int($lost_fee_line->amountoutstanding),
3837 'The LOST amountoutstanding is the expected amount after partial payment of lost fee'
3841 int($patron->account->balance),
3843 'Account balance is the expected amount after partial payment of lost fee'
3846 # Return lost item with partial payment having been made
3847 ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3849 $lost_fee_line->discard_changes;
3851 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero after returning lost item with full payment' );
3852 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set for lost item with partial payment' );
3854 int($patron->account->balance),
3856 'Account balance should be zero after returning item with lost fee when full payment has been made'
3860 subtest 'lostreturn | false' => sub {
3863 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
3865 my $item = $builder->build_sample_item(
3867 replacementprice => $replacement_amount
3872 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, $ten_days_ago );
3874 # Fake fines cronjob on this checkout
3876 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3877 $ten_days_ago, $now );
3880 issue_id => $issue->issue_id,
3881 itemnumber => $item->itemnumber,
3882 borrowernumber => $patron->borrowernumber,
3884 due => output_pref($ten_days_ago)
3887 my $overdue_fees = Koha::Account::Lines->search(
3889 borrowernumber => $patron->id,
3890 itemnumber => $item->itemnumber,
3891 debit_type_code => 'OVERDUE'
3894 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3895 my $overdue_fee = $overdue_fees->next;
3896 is( $overdue_fee->amount + 0,
3897 10, 'The right OVERDUE amount is generated' );
3898 is( $overdue_fee->amountoutstanding + 0,
3900 'The right OVERDUE amountoutstanding is generated' );
3902 # Simulate item marked as lost
3903 $item->itemlost(3)->store;
3904 C4::Circulation::LostItem( $item->itemnumber, 1 );
3906 my $lost_fee_lines = Koha::Account::Lines->search(
3908 borrowernumber => $patron->id,
3909 itemnumber => $item->itemnumber,
3910 debit_type_code => 'LOST'
3913 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3914 my $lost_fee_line = $lost_fee_lines->next;
3915 is( $lost_fee_line->amount + 0,
3916 $replacement_amount, 'The right LOST amount is generated' );
3917 is( $lost_fee_line->amountoutstanding + 0,
3918 $replacement_amount,
3919 'The right LOST amountoutstanding is generated' );
3920 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3923 my ( $returned, $message ) =
3924 AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
3926 $overdue_fee->discard_changes;
3927 is( $overdue_fee->amount + 0,
3928 10, 'The OVERDUE amount is left intact' );
3929 is( $overdue_fee->amountoutstanding + 0,
3931 'The OVERDUE amountoutstanding is left intact' );
3933 $lost_fee_line->discard_changes;
3934 is( $lost_fee_line->amount + 0,
3935 $replacement_amount, 'The LOST amount is left intact' );
3936 is( $lost_fee_line->amountoutstanding + 0,
3937 $replacement_amount,
3938 'The LOST amountoutstanding is left intact' );
3939 # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
3940 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3943 subtest 'lostreturn | refund' => sub {
3946 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
3948 my $item = $builder->build_sample_item(
3950 replacementprice => $replacement_amount
3955 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, $ten_days_ago );
3957 # Fake fines cronjob on this checkout
3959 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3960 $ten_days_ago, $now );
3963 issue_id => $issue->issue_id,
3964 itemnumber => $item->itemnumber,
3965 borrowernumber => $patron->borrowernumber,
3967 due => output_pref($ten_days_ago)
3970 my $overdue_fees = Koha::Account::Lines->search(
3972 borrowernumber => $patron->id,
3973 itemnumber => $item->itemnumber,
3974 debit_type_code => 'OVERDUE'
3977 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3978 my $overdue_fee = $overdue_fees->next;
3979 is( $overdue_fee->amount + 0,
3980 10, 'The right OVERDUE amount is generated' );
3981 is( $overdue_fee->amountoutstanding + 0,
3983 'The right OVERDUE amountoutstanding is generated' );
3985 # Simulate item marked as lost
3986 $item->itemlost(3)->store;
3987 C4::Circulation::LostItem( $item->itemnumber, 1 );
3989 my $lost_fee_lines = Koha::Account::Lines->search(
3991 borrowernumber => $patron->id,
3992 itemnumber => $item->itemnumber,
3993 debit_type_code => 'LOST'
3996 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3997 my $lost_fee_line = $lost_fee_lines->next;
3998 is( $lost_fee_line->amount + 0,
3999 $replacement_amount, 'The right LOST amount is generated' );
4000 is( $lost_fee_line->amountoutstanding + 0,
4001 $replacement_amount,
4002 'The right LOST amountoutstanding is generated' );
4003 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
4005 # Return the lost item
4006 my ( undef, $message ) =
4007 AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
4009 $overdue_fee->discard_changes;
4010 is( $overdue_fee->amount + 0,
4011 10, 'The OVERDUE amount is left intact' );
4012 is( $overdue_fee->amountoutstanding + 0,
4014 'The OVERDUE amountoutstanding is left intact' );
4016 $lost_fee_line->discard_changes;
4017 is( $lost_fee_line->amount + 0,
4018 $replacement_amount, 'The LOST amount is left intact' );
4019 is( $lost_fee_line->amountoutstanding + 0,
4021 'The LOST amountoutstanding is refunded' );
4022 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
4025 subtest 'lostreturn | restore' => sub {
4028 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
4030 my $item = $builder->build_sample_item(
4032 replacementprice => $replacement_amount
4037 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode , $ten_days_ago);
4039 # Fake fines cronjob on this checkout
4041 CalcFine( $item, $patron->categorycode, $library->{branchcode},
4042 $ten_days_ago, $now );
4045 issue_id => $issue->issue_id,
4046 itemnumber => $item->itemnumber,
4047 borrowernumber => $patron->borrowernumber,
4049 due => output_pref($ten_days_ago)
4052 my $overdue_fees = Koha::Account::Lines->search(
4054 borrowernumber => $patron->id,
4055 itemnumber => $item->itemnumber,
4056 debit_type_code => 'OVERDUE'
4059 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
4060 my $overdue_fee = $overdue_fees->next;
4061 is( $overdue_fee->amount + 0,
4062 10, 'The right OVERDUE amount is generated' );
4063 is( $overdue_fee->amountoutstanding + 0,
4065 'The right OVERDUE amountoutstanding is generated' );
4067 # Simulate item marked as lost
4068 $item->itemlost(3)->store;
4069 C4::Circulation::LostItem( $item->itemnumber, 1 );
4071 my $lost_fee_lines = Koha::Account::Lines->search(
4073 borrowernumber => $patron->id,
4074 itemnumber => $item->itemnumber,
4075 debit_type_code => 'LOST'
4078 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
4079 my $lost_fee_line = $lost_fee_lines->next;
4080 is( $lost_fee_line->amount + 0,
4081 $replacement_amount, 'The right LOST amount is generated' );
4082 is( $lost_fee_line->amountoutstanding + 0,
4083 $replacement_amount,
4084 'The right LOST amountoutstanding is generated' );
4085 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
4087 # Simulate refunding overdue fees upon marking item as lost
4088 my $overdue_forgive = $patron->account->add_credit(
4091 user_id => $manager->borrowernumber,
4092 library_id => $branchcode_restore,
4093 interface => 'test',
4095 item_id => $item->itemnumber
4098 $overdue_forgive->apply( { debits => [$overdue_fee] } );
4099 $overdue_fee->discard_changes;
4100 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
4103 my ( undef, $message ) =
4104 AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
4106 $overdue_fee->discard_changes;
4107 is( $overdue_fee->amount + 0,
4108 10, 'The OVERDUE amount is left intact' );
4109 is( $overdue_fee->amountoutstanding + 0,
4111 'The OVERDUE amountoutstanding is restored' );
4113 $lost_fee_line->discard_changes;
4114 is( $lost_fee_line->amount + 0,
4115 $replacement_amount, 'The LOST amount is left intact' );
4116 is( $lost_fee_line->amountoutstanding + 0,
4118 'The LOST amountoutstanding is refunded' );
4119 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
4122 subtest 'lostreturn | charge' => sub {
4125 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
4127 my $item = $builder->build_sample_item(
4129 replacementprice => $replacement_amount
4134 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, $ten_days_ago );
4136 # Fake fines cronjob on this checkout
4138 CalcFine( $item, $patron->categorycode, $library->{branchcode},
4139 $ten_days_ago, $now );
4142 issue_id => $issue->issue_id,
4143 itemnumber => $item->itemnumber,
4144 borrowernumber => $patron->borrowernumber,
4146 due => output_pref($ten_days_ago)
4149 my $overdue_fees = Koha::Account::Lines->search(
4151 borrowernumber => $patron->id,
4152 itemnumber => $item->itemnumber,
4153 debit_type_code => 'OVERDUE'
4156 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
4157 my $overdue_fee = $overdue_fees->next;
4158 is( $overdue_fee->amount + 0,
4159 10, 'The right OVERDUE amount is generated' );
4160 is( $overdue_fee->amountoutstanding + 0,
4162 'The right OVERDUE amountoutstanding is generated' );
4164 # Simulate item marked as lost
4165 $item->itemlost(3)->store;
4166 C4::Circulation::LostItem( $item->itemnumber, 1 );
4168 my $lost_fee_lines = Koha::Account::Lines->search(
4170 borrowernumber => $patron->id,
4171 itemnumber => $item->itemnumber,
4172 debit_type_code => 'LOST'
4175 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
4176 my $lost_fee_line = $lost_fee_lines->next;
4177 is( $lost_fee_line->amount + 0,
4178 $replacement_amount, 'The right LOST amount is generated' );
4179 is( $lost_fee_line->amountoutstanding + 0,
4180 $replacement_amount,
4181 'The right LOST amountoutstanding is generated' );
4182 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
4184 # Simulate refunding overdue fees upon marking item as lost
4185 my $overdue_forgive = $patron->account->add_credit(
4188 user_id => $manager->borrowernumber,
4189 library_id => $branchcode_charge,
4190 interface => 'test',
4192 item_id => $item->itemnumber
4195 $overdue_forgive->apply( { debits => [$overdue_fee] } );
4196 $overdue_fee->discard_changes;
4197 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
4200 my ( undef, $message ) =
4201 AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
4203 $lost_fee_line->discard_changes;
4204 is( $lost_fee_line->amount + 0,
4205 $replacement_amount, 'The LOST amount is left intact' );
4206 is( $lost_fee_line->amountoutstanding + 0,
4208 'The LOST amountoutstanding is refunded' );
4209 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
4211 $overdue_fees = Koha::Account::Lines->search(
4213 borrowernumber => $patron->id,
4214 itemnumber => $item->itemnumber,
4215 debit_type_code => 'OVERDUE'
4218 order_by => { '-asc' => 'accountlines_id'}
4221 is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
4222 $overdue_fee = $overdue_fees->next;
4223 is( $overdue_fee->amount + 0,
4224 10, 'The original OVERDUE amount is left intact' );
4225 is( $overdue_fee->amountoutstanding + 0,
4227 'The original OVERDUE amountoutstanding is left as forgiven' );
4228 $overdue_fee = $overdue_fees->next;
4229 is( $overdue_fee->amount + 0,
4230 5, 'The new OVERDUE amount is correct for the backdated return' );
4231 is( $overdue_fee->amountoutstanding + 0,
4233 'The new OVERDUE amountoutstanding is correct for the backdated return' );
4238 subtest '_FixOverduesOnReturn' => sub {
4241 my $manager = $builder->build_object({ class => "Koha::Patrons" });
4242 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
4244 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
4246 my $branchcode = $library2->{branchcode};
4248 my $item = $builder->build_sample_item(
4250 biblionumber => $biblio->biblionumber,
4251 library => $branchcode,
4252 replacementprice => 99.00,
4257 my $patron = $builder->build( { source => 'Borrower' } );
4259 ## Start with basic call, should just close out the open fine
4260 my $accountline = Koha::Account::Line->new(
4262 borrowernumber => $patron->{borrowernumber},
4263 debit_type_code => 'OVERDUE',
4264 status => 'UNRETURNED',
4265 itemnumber => $item->itemnumber,
4267 amountoutstanding => 99.00,
4268 interface => 'test',
4272 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
4274 $accountline->_result()->discard_changes();
4276 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
4277 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
4278 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
4280 ## Run again, with exemptfine enabled
4283 debit_type_code => 'OVERDUE',
4284 status => 'UNRETURNED',
4285 amountoutstanding => 99.00,
4289 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
4291 $accountline->_result()->discard_changes();
4292 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'APPLY' })->next();
4294 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
4295 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
4296 is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
4297 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
4298 is( $offset->amount + 0, -99, "Amount of offset is correct" );
4299 my $credit = $offset->credit;
4300 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
4301 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
4302 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
4304 # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
4307 debit_type_code => 'OVERDUE',
4308 status => 'UNRETURNED',
4309 amountoutstanding => 0.00,
4314 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
4316 $accountline->_result()->discard_changes();
4317 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'CREATE' })->next();
4318 is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
4319 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
4320 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
4323 subtest 'Set waiting flag' => sub {
4326 my $library_1 = $builder->build( { source => 'Branch' } );
4327 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
4328 my $library_2 = $builder->build( { source => 'Branch' } );
4329 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
4331 my $item = $builder->build_sample_item(
4333 library => $library_1->{branchcode},
4337 set_userenv( $library_2 );
4338 my $reserve_id = AddReserve(
4340 branchcode => $library_2->{branchcode},
4341 borrowernumber => $patron_2->{borrowernumber},
4342 biblionumber => $item->biblionumber,
4344 itemnumber => $item->itemnumber,
4348 set_userenv( $library_1 );
4349 my $do_transfer = 1;
4350 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
4351 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
4352 my $hold = Koha::Holds->find( $reserve_id );
4353 is( $hold->found, 'T', 'Hold is in transit' );
4355 my ( $status ) = CheckReserves($item);
4356 is( $status, 'Transferred', 'Hold is not waiting yet');
4358 set_userenv( $library_2 );
4360 AddReturn( $item->barcode, $library_2->{branchcode} );
4361 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
4362 $hold = Koha::Holds->find( $reserve_id );
4363 is( $hold->found, 'W', 'Hold is waiting' );
4364 ( $status ) = CheckReserves($item);
4365 is( $status, 'Waiting', 'Now the hold is waiting');
4367 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
4368 set_userenv( $library_1 );
4369 (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
4370 $hold = Koha::Holds->find( $reserve_id );
4371 is( $hold->found, undef, 'Hold is no longer marked waiting' );
4372 is( $hold->priority, 1, "Hold is now priority one again");
4373 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
4374 is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
4375 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
4376 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
4377 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
4380 subtest 'Cancel transfers on lost items' => sub {
4383 my $library_to = $builder->build_object( { class => 'Koha::Libraries' } );
4384 my $item = $builder->build_sample_item();
4385 my $holdingbranch = $item->holdingbranch;
4386 # Historic transfer (datearrived is defined)
4387 my $old_transfer = $builder->build_object(
4389 class => 'Koha::Item::Transfers',
4391 itemnumber => $item->itemnumber,
4392 frombranch => $holdingbranch,
4393 tobranch => $library_to->branchcode,
4395 datesent => \'NOW()',
4396 datearrived => \'NOW()',
4397 datecancelled => undef,
4398 daterequested => \'NOW()'
4402 # Queued transfer (datesent is undefined)
4403 my $transfer_1 = $builder->build_object(
4405 class => 'Koha::Item::Transfers',
4407 itemnumber => $item->itemnumber,
4408 frombranch => $holdingbranch,
4409 tobranch => $library_to->branchcode,
4412 datearrived => undef,
4413 datecancelled => undef,
4414 daterequested => \'NOW()'
4418 # In transit transfer (datesent is defined, datearrived and datecancelled are both undefined)
4419 my $transfer_2 = $builder->build_object(
4421 class => 'Koha::Item::Transfers',
4423 itemnumber => $item->itemnumber,
4424 frombranch => $holdingbranch,
4425 tobranch => $library_to->branchcode,
4427 datesent => \'NOW()',
4428 datearrived => undef,
4429 datecancelled => undef,
4430 daterequested => \'NOW()'
4435 # Simulate item being marked as lost
4436 $item->itemlost(1)->store;
4437 LostItem( $item->itemnumber, 'test', 1 );
4439 $transfer_1->discard_changes;
4440 isnt($transfer_1->datecancelled, undef, "Queud transfer was cancelled upon item lost");
4441 is($transfer_1->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
4442 $transfer_2->discard_changes;
4443 isnt($transfer_2->datecancelled, undef, "Active transfer was cancelled upon item lost");
4444 is($transfer_2->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
4445 $old_transfer->discard_changes;
4446 is($old_transfer->datecancelled, undef, "Old transfers are unaffected");
4447 $item->discard_changes;
4448 is($item->holdingbranch, $holdingbranch, "Items holding branch remains unchanged");
4451 subtest 'CanBookBeIssued | is_overdue' => sub {
4454 # Set a simple circ policy
4455 Koha::CirculationRules->set_rules(
4457 categorycode => undef,
4458 branchcode => undef,
4462 reservesallowed => 25,
4464 lengthunit => 'days',
4465 renewalsallowed => 1,
4467 norenewalbefore => undef,
4475 my $now = dt_from_string()->truncate( to => 'day' );
4476 my $five_days_go = $now->clone->add( days => 5 );
4477 my $ten_days_go = $now->clone->add( days => 10);
4478 my $library = $builder->build( { source => 'Branch' } );
4479 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
4481 my $item = $builder->build_sample_item(
4483 library => $library->{branchcode},
4487 my $issue = AddIssue( $patron, $item->barcode, $five_days_go ); # date due was 10d ago
4488 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
4489 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), output_pref({ str => $five_days_go, dateonly => 1}), "First issue works");
4490 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron, $item->barcode, $ten_days_go, undef, undef, undef);
4491 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
4492 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
4495 subtest 'ItemsDeniedRenewal rules are checked' => sub {
4498 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
4499 Koha::CirculationRules->set_rules(
4501 categorycode => '*',
4503 branchcode => $idr_lib->branchcode,
4505 reservesallowed => 25,
4507 lengthunit => 'days',
4508 renewalsallowed => 10,
4510 norenewalbefore => undef,
4518 my $allow_book = $builder->build_sample_item({
4519 homebranch => $idr_lib->branchcode,
4520 holdingbranch => $idr_lib->branchcode,
4523 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
4524 branchcode => $idr_lib->branchcode,
4527 my $future = dt_from_string->add( days => 1 );
4528 my $issue = $builder->build_object(
4530 class => 'Koha::Checkouts',
4532 returndate => undef,
4533 renewals_count => 0,
4535 borrowernumber => $idr_borrower->borrowernumber,
4536 itemnumber => $allow_book->itemnumber,
4537 onsite_checkout => 0,
4538 date_due => $future,
4543 my $mock_item_class = Test::MockModule->new("Koha::Item");
4544 $mock_item_class->mock( 'is_denied_renewal', sub { return 1; } );
4546 my ( $mayrenew, $error ) = CanBookBeRenewed( $idr_borrower, $issue );
4547 is( $mayrenew, 0, 'Renewal blocked when $item->is_denied_renewal returns true' );
4548 is( $error, 'item_denied_renewal', 'Renewal blocked when $item->is_denied_renewal returns true' );
4550 $mock_item_class->unmock( 'is_denied_renewal' );
4551 $mock_item_class->mock( 'is_denied_renewal', sub { return 0; } );
4553 ( $mayrenew, $error ) = CanBookBeRenewed( $idr_borrower, $issue );
4554 is( $mayrenew, 1, 'Renewal allowed when $item->is_denied_renewal returns false' );
4555 is( $error, undef, 'Renewal allowed when $item->is_denied_renewal returns false' );
4557 $mock_item_class->unmock( 'is_denied_renewal' );
4560 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
4563 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4564 my $library = $builder->build( { source => 'Branch' } );
4565 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
4567 my $item = $builder->build_sample_item(
4569 library => $library->{branchcode},
4573 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4574 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4575 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4578 subtest 'CanBookBeIssued | notforloan' => sub {
4581 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
4583 my $library = $builder->build( { source => 'Branch' } );
4584 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
4586 my $itemtype = $builder->build(
4588 source => 'Itemtype',
4589 value => { notforloan => undef, }
4592 my $item = $builder->build_sample_item(
4594 library => $library->{branchcode},
4595 itype => $itemtype->{itemtype},
4598 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4600 my ( $issuingimpossible, $needsconfirmation );
4603 subtest 'item-level_itypes = 1' => sub {
4606 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
4607 # Is for loan at item type and item level
4608 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4609 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4610 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4612 # not for loan at item type level
4613 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4614 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4615 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4618 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4619 'Item can not be issued, not for loan at item type level'
4622 # not for loan at item level
4623 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4624 $item->notforloan( 1 )->store;
4625 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4626 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4629 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4630 'Item can not be issued, not for loan at item type level'
4634 subtest 'item-level_itypes = 0' => sub {
4637 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4639 # We set another itemtype for biblioitem
4640 my $itemtype = $builder->build(
4642 source => 'Itemtype',
4643 value => { notforloan => undef, }
4647 # for loan at item type and item level
4648 $item->notforloan(0)->store;
4649 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4650 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4651 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4652 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4654 # not for loan at item type level
4655 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4656 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4657 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4660 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4661 'Item can not be issued, not for loan at item type level'
4664 # not for loan at item level
4665 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4666 $item->notforloan( 1 )->store;
4667 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4668 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4671 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4672 'Item can not be issued, not for loan at item type level'
4676 # TODO test with AllowNotForLoanOverride = 1
4679 subtest 'CanBookBeIssued | recalls' => sub {
4682 t::lib::Mocks::mock_preference("UseRecalls", 1);
4683 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4684 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4685 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4686 my $item = $builder->build_sample_item;
4687 Koha::CirculationRules->set_rules({
4688 branchcode => undef,
4690 categorycode => undef,
4692 recalls_allowed => 10,
4697 my $recall = Koha::Recall->new(
4698 { patron_id => $patron1->borrowernumber,
4699 biblio_id => $item->biblionumber,
4700 item_id => $item->itemnumber,
4702 pickup_library_id => $patron1->branchcode,
4706 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4707 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed an item-level recall on this item" );
4709 $recall->set_cancelled;
4711 # biblio-level recall
4712 $recall = Koha::Recall->new(
4713 { patron_id => $patron1->borrowernumber,
4714 biblio_id => $item->biblionumber,
4717 pickup_library_id => $patron1->branchcode,
4721 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4722 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed a biblio-level recall and this item is eligible to fill it" );
4724 $recall->set_cancelled;
4726 # biblio-level recall
4727 $recall = Koha::Recall->new(
4728 { patron_id => $patron1->borrowernumber,
4729 biblio_id => $item->biblionumber,
4732 pickup_library_id => $patron1->branchcode,
4735 $recall->set_waiting( { item => $item, expirationdate => dt_from_string() } );
4737 my ( undef, undef, undef, $messages ) = CanBookBeIssued( $patron1, $item->barcode, undef, undef, undef, undef );
4738 is( $messages->{RECALLED}, $recall->id, "This book can be issued by this patron and they have placed a recall" );
4740 $recall->set_cancelled;
4743 subtest 'CanBookBeIssued | bookings' => sub {
4746 my $schema = Koha::Database->schema;
4747 $schema->storage->txn_begin;
4749 my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
4750 my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
4751 my $item = $builder->build_sample_item( { bookable => 1 } );
4753 # item-level booking
4754 my $booking = Koha::Booking->new(
4756 patron_id => $patron1->borrowernumber,
4757 item_id => $item->itemnumber,
4758 biblio_id => $item->biblio->biblionumber,
4759 start_date => dt_from_string()->subtract( days => 1 ),
4760 end_date => dt_from_string()->add( days => 6 ),
4764 # Booking encompasses proposed checkout
4765 my ( $issuingimpossible, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued(
4766 $patron2, $item->barcode,
4767 dt_from_string()->add( days => 5 ),
4771 $issuingimpossible->{BOOKED_TO_ANOTHER}->booking_id,
4772 $booking->booking_id,
4773 "Another patron has booked this item with a start date before the proposed due date"
4776 ( $issuingimpossible, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued(
4777 $patron1, $item->barcode,
4778 dt_from_string()->add( days => 5 ),
4782 $alerts->{BOOKED}->booking_id,
4783 $booking->booking_id, "Booked to this user"
4786 # Booking start will clash before issue due
4787 $booking->start_date( dt_from_string()->add( days => 3 ) )->store();
4789 ( $issuingimpossible, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued(
4790 $patron2, $item->barcode,
4791 dt_from_string()->add( days => 5 ),
4795 $needsconfirmation->{BOOKED_TO_ANOTHER}->booking_id,
4796 $booking->booking_id,
4797 "Another patron has booked this item for a period starting before the proposed due date"
4800 ( $issuingimpossible, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued(
4801 $patron1, $item->barcode,
4802 dt_from_string()->add( days => 5 ),
4806 $needsconfirmation->{BOOKED_EARLY}->booking_id,
4807 $booking->booking_id,
4808 "Booked to this user, but they're collecting early"
4811 $schema->storage->txn_rollback;
4814 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
4817 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
4818 my $item = $builder->build_sample_item(
4820 onloan => '2018-01-01',
4824 AddReturn( $item->barcode, $item->homebranch );
4825 $item->discard_changes; # refresh
4826 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
4829 subtest 'AddReturn | recalls' => sub {
4832 t::lib::Mocks::mock_preference("UseRecalls", 1);
4833 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4834 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4835 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4836 my $item1 = $builder->build_sample_item;
4837 Koha::CirculationRules->set_rules({
4838 branchcode => undef,
4840 categorycode => undef,
4842 recalls_allowed => 10,
4846 # this item can fill a recall with pickup at this branch
4847 AddIssue( $patron1, $item1->barcode );
4848 my $recall1 = Koha::Recall->new(
4849 { patron_id => $patron2->borrowernumber,
4850 biblio_id => $item1->biblionumber,
4851 item_id => $item1->itemnumber,
4853 pickup_library_id => $item1->homebranch,
4856 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4857 is( $messages->{RecallFound}->id, $recall1->id, "Recall found" );
4858 $recall1->set_cancelled;
4860 # this item can fill a recall but needs transfer
4861 AddIssue( $patron1, $item1->barcode );
4862 $recall1 = Koha::Recall->new(
4863 { patron_id => $patron2->borrowernumber,
4864 biblio_id => $item1->biblionumber,
4865 item_id => $item1->itemnumber,
4867 pickup_library_id => $patron2->branchcode,
4870 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4871 is( $messages->{RecallNeedsTransfer}, $item1->homebranch, "Recall requiring transfer found" );
4872 $recall1->set_cancelled;
4874 # this item is already in transit, do not ask to transfer
4875 AddIssue( $patron1, $item1->barcode );
4876 $recall1 = Koha::Recall->new(
4877 { patron_id => $patron2->borrowernumber,
4878 biblio_id => $item1->biblionumber,
4879 item_id => $item1->itemnumber,
4881 pickup_library_id => $patron2->branchcode,
4884 $recall1->start_transfer;
4885 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $patron2->branchcode );
4886 is( $messages->{TransferredRecall}->id, $recall1->id, "In transit recall found" );
4887 $recall1->set_cancelled;
4890 subtest 'AddReturn | bundles' => sub {
4893 my $schema = Koha::Database->schema;
4894 $schema->storage->txn_begin;
4896 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4897 my $host_item1 = $builder->build_sample_item;
4898 my $bundle_item1 = $builder->build_sample_item;
4899 $schema->resultset('ItemBundle')
4901 { host => $host_item1->itemnumber, item => $bundle_item1->itemnumber } );
4903 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $bundle_item1->barcode, $bundle_item1->homebranch );
4904 is($messages->{InBundle}->id, $host_item1->id, 'AddReturn returns InBundle host item when item is part of a bundle');
4906 $schema->storage->txn_rollback;
4909 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
4914 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4916 my $issuing_charges = 15;
4917 my $title = 'A title';
4918 my $author = 'Author, An';
4919 my $barcode = 'WHATARETHEODDS';
4921 my $circ = Test::MockModule->new('C4::Circulation');
4923 'GetIssuingCharges',
4925 return $issuing_charges;
4929 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4930 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
4931 my $patron = $builder->build_object({
4932 class => 'Koha::Patrons',
4933 value => { branchcode => $library->id }
4936 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
4937 my $item_id = Koha::Item->new(
4939 biblionumber => $biblio->biblionumber,
4940 homebranch => $library->id,
4941 holdingbranch => $library->id,
4942 barcode => $barcode,
4943 replacementprice => 23.00,
4944 itype => $itemtype->id
4946 )->store->itemnumber;
4947 my $item = Koha::Items->find( $item_id );
4949 my $context = Test::MockModule->new('C4::Context');
4950 $context->mock( userenv => { branch => $library->id } );
4952 # Check the item out
4953 AddIssue( $patron, $item->barcode );
4958 borrowernumber => $patron->borrowernumber,
4959 itemnumber => $item->itemnumber,
4960 branch => $library->id,
4961 lastreneweddate => { break => "the_renewal" }
4964 } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
4966 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
4967 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
4968 my %params_renewal = (
4969 timestamp => { -like => $date . "%" },
4970 module => "CIRCULATION",
4971 action => "RENEWAL",
4973 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
4976 borrowernumber => $patron->id,
4977 itemnumber => $item->id,
4978 branch => $library->id
4981 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4982 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
4984 my $checkouts = $patron->checkouts;
4985 # The following will fail if run on 00:00:00
4986 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
4988 my $lines = Koha::Account::Lines->search({
4989 borrowernumber => $patron->id,
4990 itemnumber => $item->id
4993 is( $lines->count, 2 );
4995 my $line = $lines->next;
4996 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
4997 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
4998 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
5000 $line = $lines->next;
5001 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
5002 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
5003 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
5005 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
5007 $context = Test::MockModule->new('C4::Context');
5008 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
5010 my $now = dt_from_string;
5011 $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
5012 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
5013 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
5014 $sth->execute($item->id, $library->id);
5015 my ($old_stats_size) = $sth->fetchrow_array;
5018 borrowernumber => $patron->id,
5019 itemnumber => $item->id,
5020 branch => $library->id
5023 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
5024 $sth->execute($item->id, $library->id);
5025 my ($new_stats_size) = $sth->fetchrow_array;
5026 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
5027 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
5029 AddReturn( $item->id, $library->id, undef, $date );
5030 AddIssue( $patron, $item->barcode, $now );
5033 borrowernumber => $patron->id,
5034 itemnumber => $item->id,
5035 branch => $library->id,
5039 my $lines_skipped = Koha::Account::Lines->search({
5040 borrowernumber => $patron->id,
5041 itemnumber => $item->id
5043 is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
5047 subtest 'AddRenewal() adds to renewals' => sub {
5050 my $library = $builder->build_object({ class => 'Koha::Libraries' });
5051 my $patron = $builder->build_object({
5052 class => 'Koha::Patrons',
5053 value => { branchcode => $library->id }
5056 my $item = $builder->build_sample_item();
5058 set_userenv( $library->unblessed );
5060 # Check the item out
5061 my $issue = AddIssue( $patron, $item->barcode );
5062 is(ref($issue), 'Koha::Checkout', 'Issue added');
5065 my $duedate = AddRenewal(
5067 borrowernumber => $patron->id,
5068 itemnumber => $item->id,
5069 branch => $library->id,
5074 ok( $duedate, "Renewal added" );
5076 my $renewals = Koha::Checkouts::Renewals->search({ checkout_id => $issue->issue_id });
5077 is($renewals->count, 1, 'One renewal added');
5078 my $THE_renewal = $renewals->next;
5079 is( $THE_renewal->renewer_id, C4::Context->userenv->{'number'}, 'Renewer recorded from context' );
5080 is( $THE_renewal->renewal_type, 'Automatic', 'AddRenewal "automatic" parameter sets renewal type to "Automatic"');
5083 subtest 'ProcessOfflinePayment() tests' => sub {
5090 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5091 my $library = $builder->build_object({ class => 'Koha::Libraries' });
5092 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
5094 is( $result, 'Success.', 'The right string is returned' );
5096 my $lines = $patron->account->lines;
5097 is( $lines->count, 1, 'line created correctly');
5099 my $line = $lines->next;
5100 is( $line->amount+0, $amount * -1, 'amount picked from params' );
5101 is( $line->branchcode, $library->id, 'branchcode set correctly' );
5105 subtest 'Incremented fee tests' => sub {
5108 my $dt = dt_from_string();
5109 Time::Fake->offset( $dt->epoch );
5111 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
5113 my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store;
5115 $module->mock( 'userenv', sub { { branch => $library->id } } );
5117 my $patron = $builder->build_object(
5119 class => 'Koha::Patrons',
5120 value => { categorycode => $patron_category->{categorycode} }
5124 my $itemtype = $builder->build_object(
5126 class => 'Koha::ItemTypes',
5128 notforloan => undef,
5130 rentalcharge_daily => 1,
5131 rentalcharge_daily_calendar => 0
5136 my $item = $builder->build_sample_item(
5138 library => $library->id,
5139 itype => $itemtype->id,
5143 is( $itemtype->rentalcharge_daily + 0,1, 'Daily rental charge stored and retreived correctly' );
5144 is( $item->effective_itemtype, $itemtype->id, "Itemtype set correctly for item" );
5146 my $now = dt_from_string;
5147 my $dt_from = $now->clone;
5148 my $dt_to = $now->clone->add( days => 7 );
5149 my $dt_to_renew = $now->clone->add( days => 13 );
5153 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
5154 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5156 $accountline->amount + 0,
5158 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
5160 $accountline->delete();
5163 borrowernumber => $patron->id,
5164 itemnumber => $item->id,
5165 branch => $library->id,
5166 datedue => $dt_to_renew,
5167 lastreneweddate => $dt_to
5170 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5172 $accountline->amount + 0,
5174 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
5176 $accountline->delete();
5179 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
5180 $itemtype->rentalcharge_daily_calendar(1)->store();
5182 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
5183 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5185 $accountline->amount + 0,
5187 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
5189 $accountline->delete();
5192 borrowernumber => $patron->id,
5193 itemnumber => $item->id,
5194 branch => $library->id,
5195 datedue => $dt_to_renew,
5196 lastreneweddate => $dt_to
5199 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5201 $accountline->amount + 0,
5203 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
5205 $accountline->delete();
5208 my $calendar = C4::Calendar->new( branchcode => $library->id );
5209 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
5211 ( $dt_from->day_of_week == 6 ) ? 0
5212 : ( $dt_from->day_of_week == 7 ) ? 1
5213 : $dt_from->day_of_week + 1;
5214 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
5215 $calendar->insert_week_day_holiday(
5216 weekday => $closed_day,
5217 title => 'Test holiday',
5218 description => 'Test holiday'
5221 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
5222 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5224 $accountline->amount + 0,
5226 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
5228 $accountline->delete();
5231 borrowernumber => $patron->id,
5232 itemnumber => $item->id,
5233 branch => $library->id,
5234 datedue => $dt_to_renew,
5235 lastreneweddate => $dt_to
5238 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5240 $accountline->amount + 0,
5242 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
5244 $accountline->delete();
5247 $itemtype->rentalcharge(2)->store;
5248 is( $itemtype->rentalcharge + 0, 2, 'Rental charge updated and retreived correctly' );
5250 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
5252 Koha::Account::Lines->search( { itemnumber => $item->id } );
5253 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly" );
5254 $accountlines->delete();
5257 borrowernumber => $patron->id,
5258 itemnumber => $item->id,
5259 branch => $library->id,
5260 datedue => $dt_to_renew,
5261 lastreneweddate => $dt_to
5264 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
5265 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly, for renewal" );
5266 $accountlines->delete();
5268 $itemtype->rentalcharge(0)->store;
5269 is( $itemtype->rentalcharge + 0, 0, 'Rental charge reset and retreived correctly' );
5272 Koha::CirculationRules->set_rule(
5274 categorycode => $patron->categorycode,
5275 itemtype => $itemtype->id,
5276 branchcode => $library->id,
5277 rule_name => 'lengthunit',
5278 rule_value => 'hours',
5282 $itemtype->rentalcharge_hourly('0.25')->store();
5283 is( $itemtype->rentalcharge_hourly, '0.25', 'Hourly rental charge stored and retreived correctly' );
5285 $dt_to = $now->clone->add( hours => 168 );
5286 $dt_to_renew = $now->clone->add( hours => 312 );
5288 $itemtype->rentalcharge_hourly_calendar(0)->store();
5290 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
5291 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5293 $accountline->amount + 0,
5295 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)"
5297 $accountline->delete();
5300 borrowernumber => $patron->id,
5301 itemnumber => $item->id,
5302 branch => $library->id,
5303 datedue => $dt_to_renew,
5304 lastreneweddate => $dt_to
5307 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5309 $accountline->amount + 0,
5311 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)"
5313 $accountline->delete();
5316 $itemtype->rentalcharge_hourly_calendar(1)->store();
5318 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
5319 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5321 $accountline->amount + 0,
5323 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)"
5325 $accountline->delete();
5328 borrowernumber => $patron->id,
5329 itemnumber => $item->id,
5330 branch => $library->id,
5331 datedue => $dt_to_renew,
5332 lastreneweddate => $dt_to
5335 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5337 $accountline->amount + 0,
5339 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u"
5341 $accountline->delete();
5344 $calendar->delete_holiday( weekday => $closed_day );
5346 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
5347 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5349 $accountline->amount + 0,
5351 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u"
5353 $accountline->delete();
5356 borrowernumber => $patron->id,
5357 itemnumber => $item->id,
5358 branch => $library->id,
5359 datedue => $dt_to_renew,
5360 lastreneweddate => $dt_to
5363 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5365 $accountline->amount + 0,
5367 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)"
5369 $accountline->delete();
5374 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
5377 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
5378 t::lib::Mocks::mock_preference('item-level_itypes', 1);
5381 $builder->build_object( { class => 'Koha::Libraries' } )->store;
5382 my $patron = $builder->build_object(
5384 class => 'Koha::Patrons',
5385 value => { categorycode => $patron_category->{categorycode} }
5389 my $itemtype = $builder->build_object(
5391 class => 'Koha::ItemTypes',
5395 rentalcharge_daily => 0
5400 my $item = $builder->build_sample_item(
5402 library => $library->id,
5406 itype => $itemtype->id,
5410 my ( $issuingimpossible, $needsconfirmation );
5411 my $dt_from = dt_from_string();
5412 my $dt_due = $dt_from->clone->add( days => 3 );
5414 $itemtype->rentalcharge(1)->store;
5415 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
5416 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
5417 $itemtype->rentalcharge('0')->store;
5418 $itemtype->rentalcharge_daily(1)->store;
5419 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
5420 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
5421 $itemtype->rentalcharge_daily('0')->store;
5424 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
5427 t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
5429 my $patron = $builder->build_object(
5431 class => 'Koha::Patrons',
5432 value => { categorycode => $patron_category->{categorycode} }
5436 my $item = $builder->build_sample_item(
5438 materials => 'includes DVD',
5442 my $dt_due = dt_from_string->add( days => 3 );
5444 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
5445 is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
5448 subtest 'Do not return on renewal (LOST charge)' => sub {
5451 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
5452 my $library = $builder->build_object( { class => "Koha::Libraries" } );
5453 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
5454 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
5456 my $biblio = $builder->build_sample_biblio;
5458 my $item = $builder->build_sample_item(
5460 biblionumber => $biblio->biblionumber,
5461 library => $library->branchcode,
5462 replacementprice => 99.00,
5467 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
5468 AddIssue( $patron, $item->barcode );
5470 my $accountline = Koha::Account::Line->new(
5472 borrowernumber => $patron->borrowernumber,
5473 debit_type_code => 'LOST',
5475 itemnumber => $item->itemnumber,
5477 amountoutstanding => 12,
5478 interface => 'something',
5482 # AddRenewal doesn't call _FixAccountForLostAndFound
5483 AddIssue( $patron, $item->barcode );
5485 is( $patron->checkouts->count, 1,
5486 'Renewal should not return the item even if a LOST payment has been made earlier'
5490 subtest 'Filling a hold should cancel existing transfer' => sub {
5493 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
5495 my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
5496 my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
5497 my $patron = $builder->build_object(
5499 class => 'Koha::Patrons',
5501 categorycode => $patron_category->{categorycode},
5502 branchcode => $libraryA->branchcode,
5507 my $item = $builder->build_sample_item({
5508 homebranch => $libraryB->branchcode,
5511 my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
5512 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
5514 branchcode => $libraryA->branchcode,
5515 borrowernumber => $patron->borrowernumber,
5516 biblionumber => $item->biblionumber,
5517 itemnumber => $item->itemnumber
5519 my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
5520 is( $reserves->count, 1, "Reserve is placed");
5521 ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
5522 my $reserve = $reserves->next;
5523 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
5524 $reserve->discard_changes;
5525 ok( $reserve->found eq 'W', "Reserve is marked waiting" );
5526 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
5529 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
5533 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
5534 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5535 my $patron = $builder->build_object(
5537 class => 'Koha::Patrons',
5538 value => { categorycode => $patron_category->{categorycode} }
5542 my $biblionumber = $builder->build_sample_biblio(
5544 branchcode => $library->branchcode,
5548 # And the circulation rule
5549 Koha::CirculationRules->search->delete;
5550 Koha::CirculationRules->set_rules(
5552 categorycode => undef,
5554 branchcode => undef,
5557 lengthunit => 'days',
5563 source => 'CirculationRule',
5565 branchcode => undef,
5566 categorycode => undef,
5568 rule_name => 'lostreturn',
5569 rule_value => 'refund'
5574 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5577 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5578 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5580 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5582 my $item = $builder->build_sample_item(
5584 biblionumber => $biblionumber,
5585 library => $library->branchcode,
5586 replacementprice => '42',
5589 my $issue = AddIssue( $patron, $item->barcode );
5590 LostItem( $item->itemnumber, 'cli', 0 );
5591 $item->_result->itemlost(1);
5592 $item->_result->itemlost_on( $lost_on );
5593 $item->_result->update();
5595 my $a = Koha::Account::Lines->search(
5597 itemnumber => $item->id,
5598 borrowernumber => $patron->borrowernumber
5601 ok( $a, "Found accountline for lost fee" );
5602 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5603 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5604 $a = $a->get_from_storage;
5605 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5609 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5612 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5613 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5615 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5617 my $item = $builder->build_sample_item(
5619 biblionumber => $biblionumber,
5620 library => $library->branchcode,
5621 replacementprice => '42',
5624 my $issue = AddIssue( $patron, $item->barcode );
5625 LostItem( $item->itemnumber, 'cli', 0 );
5626 $item->_result->itemlost(1);
5627 $item->_result->itemlost_on( $lost_on );
5628 $item->_result->update();
5630 my $a = Koha::Account::Lines->search(
5632 itemnumber => $item->id,
5633 borrowernumber => $patron->borrowernumber
5636 ok( $a, "Found accountline for lost fee" );
5637 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5638 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5639 $a = $a->get_from_storage;
5640 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5644 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5647 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5648 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5650 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5652 my $item = $builder->build_sample_item(
5654 biblionumber => $biblionumber,
5655 library => $library->branchcode,
5656 replacementprice => '42',
5659 my $issue = AddIssue( $patron, $item->barcode );
5660 LostItem( $item->itemnumber, 'cli', 0 );
5661 $item->_result->itemlost(1);
5662 $item->_result->itemlost_on( $lost_on );
5663 $item->_result->update();
5665 my $a = Koha::Account::Lines->search(
5667 itemnumber => $item->id,
5668 borrowernumber => $patron->borrowernumber
5671 ok( $a, "Found accountline for lost fee" );
5672 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5673 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5674 $a = $a->get_from_storage;
5675 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5679 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5682 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5683 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5685 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5687 my $item = $builder->build_sample_item(
5689 biblionumber => $biblionumber,
5690 library => $library->branchcode,
5691 replacementprice => '42',
5694 my $issue = AddIssue( $patron, $item->barcode );
5695 LostItem( $item->itemnumber, 'cli', 0 );
5696 $item->_result->itemlost(1);
5697 $item->_result->itemlost_on( $lost_on );
5698 $item->_result->update();
5700 my $a = Koha::Account::Lines->search(
5702 itemnumber => $item->id,
5703 borrowernumber => $patron->borrowernumber
5707 ok( $a, "Found accountline for lost fee" );
5708 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5709 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5710 $a = $a->get_from_storage;
5711 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5716 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
5720 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
5721 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5722 my $patron = $builder->build_object(
5724 class => 'Koha::Patrons',
5725 value => { categorycode => $patron_category->{categorycode} }
5728 my $patron2 = $builder->build_object(
5730 class => 'Koha::Patrons',
5731 value => { categorycode => $patron_category->{categorycode} }
5735 my $biblionumber = $builder->build_sample_biblio(
5737 branchcode => $library->branchcode,
5741 # And the circulation rule
5742 Koha::CirculationRules->search->delete;
5743 Koha::CirculationRules->set_rules(
5745 categorycode => undef,
5747 branchcode => undef,
5750 lengthunit => 'days',
5756 source => 'CirculationRule',
5758 branchcode => undef,
5759 categorycode => undef,
5761 rule_name => 'lostreturn',
5762 rule_value => 'refund'
5767 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5770 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5771 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5773 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5775 my $item = $builder->build_sample_item(
5777 biblionumber => $biblionumber,
5778 library => $library->branchcode,
5779 replacementprice => '42',
5782 my $issue = AddIssue( $patron, $item->barcode );
5783 LostItem( $item->itemnumber, 'cli', 0 );
5784 $item->_result->itemlost(1);
5785 $item->_result->itemlost_on( $lost_on );
5786 $item->_result->update();
5788 my $a = Koha::Account::Lines->search(
5790 itemnumber => $item->id,
5791 borrowernumber => $patron->borrowernumber
5794 ok( $a, "Found accountline for lost fee" );
5795 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5796 $issue = AddIssue( $patron2, $item->barcode );
5797 $a = $a->get_from_storage;
5798 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5803 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5806 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5807 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5809 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5811 my $item = $builder->build_sample_item(
5813 biblionumber => $biblionumber,
5814 library => $library->branchcode,
5815 replacementprice => '42',
5818 my $issue = AddIssue( $patron, $item->barcode );
5819 LostItem( $item->itemnumber, 'cli', 0 );
5820 $item->_result->itemlost(1);
5821 $item->_result->itemlost_on( $lost_on );
5822 $item->_result->update();
5824 my $a = Koha::Account::Lines->search(
5826 itemnumber => $item->id,
5827 borrowernumber => $patron->borrowernumber
5830 ok( $a, "Found accountline for lost fee" );
5831 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5832 $issue = AddIssue( $patron2, $item->barcode );
5833 $a = $a->get_from_storage;
5834 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5838 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5841 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5842 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5844 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5846 my $item = $builder->build_sample_item(
5848 biblionumber => $biblionumber,
5849 library => $library->branchcode,
5850 replacementprice => '42',
5853 my $issue = AddIssue( $patron, $item->barcode );
5854 LostItem( $item->itemnumber, 'cli', 0 );
5855 $item->_result->itemlost(1);
5856 $item->_result->itemlost_on( $lost_on );
5857 $item->_result->update();
5859 my $a = Koha::Account::Lines->search(
5861 itemnumber => $item->id,
5862 borrowernumber => $patron->borrowernumber
5865 ok( $a, "Found accountline for lost fee" );
5866 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5867 $issue = AddIssue( $patron2, $item->barcode );
5868 $a = $a->get_from_storage;
5869 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5873 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5876 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5877 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5879 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5881 my $item = $builder->build_sample_item(
5883 biblionumber => $biblionumber,
5884 library => $library->branchcode,
5885 replacementprice => '42',
5888 my $issue = AddIssue( $patron, $item->barcode );
5889 LostItem( $item->itemnumber, 'cli', 0 );
5890 $item->_result->itemlost(1);
5891 $item->_result->itemlost_on( $lost_on );
5892 $item->_result->update();
5894 my $a = Koha::Account::Lines->search(
5896 itemnumber => $item->id,
5897 borrowernumber => $patron->borrowernumber
5901 ok( $a, "Found accountline for lost fee" );
5902 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5903 $issue = AddIssue( $patron2, $item->barcode );
5904 $a = $a->get_from_storage;
5905 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5910 subtest 'transferbook tests' => sub {
5914 { C4::Circulation::transferbook({}); }
5915 'Koha::Exceptions::MissingParameter',
5916 'Koha::Patron->store raises an exception on missing params';
5919 { C4::Circulation::transferbook({to_branch=>'anything'}); }
5920 'Koha::Exceptions::MissingParameter',
5921 'Koha::Patron->store raises an exception on missing params';
5924 { C4::Circulation::transferbook({from_branch=>'anything'}); }
5925 'Koha::Exceptions::MissingParameter',
5926 'Koha::Patron->store raises an exception on missing params';
5928 my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
5929 is( $doreturn, 0, "No return without barcode");
5930 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5931 is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
5933 ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
5934 is( $doreturn, 0, "No return without barcode");
5935 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5936 is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
5940 subtest 'Checkout should correctly terminate a transfer' => sub {
5943 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5944 my $patron_1 = $builder->build_object(
5946 class => 'Koha::Patrons',
5947 value => { branchcode => $library_1->branchcode }
5950 my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
5951 my $patron_2 = $builder->build_object(
5953 class => 'Koha::Patrons',
5954 value => { branchcode => $library_2->branchcode }
5958 my $item = $builder->build_sample_item(
5960 library => $library_1->branchcode,
5964 t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
5965 my $reserve_id = AddReserve(
5967 branchcode => $library_2->branchcode,
5968 borrowernumber => $patron_2->borrowernumber,
5969 biblionumber => $item->biblionumber,
5970 itemnumber => $item->itemnumber,
5975 my $do_transfer = 1;
5976 ModItemTransfer( $item->itemnumber, $library_1->branchcode,
5977 $library_2->branchcode, 'Reserve' );
5978 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
5979 my $hold = Koha::Holds->find($reserve_id);
5980 is( $hold->found, 'T', 'Hold is in transit' );
5981 my $transfer = $item->get_transfer;
5982 is( $transfer->frombranch, $library_1->branchcode );
5983 is( $transfer->tobranch, $library_2->branchcode );
5984 is( $transfer->reason, 'Reserve' );
5986 t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
5987 AddIssue( $patron_1, $item->barcode );
5988 $transfer = $transfer->get_from_storage;
5989 isnt( $transfer->datearrived, undef );
5990 $hold = $hold->get_from_storage;
5991 is( $hold->found, undef, 'Hold is not waiting or transit' );
5992 is( $hold->priority, 1, );
5995 subtest 'AddIssue records staff who checked out item if appropriate' => sub {
5998 $module->mock( 'userenv', sub { { branch => $library->{id} } } );
6000 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
6001 my $patron = $builder->build_object(
6003 class => 'Koha::Patrons',
6004 value => { categorycode => $patron_category->{categorycode} }
6007 my $issuer = $builder->build_object(
6009 class => 'Koha::Patrons',
6010 value => { categorycode => $patron_category->{categorycode} }
6013 my $item_1 = $builder->build_sample_item(
6015 library => $library->{branchcode}
6019 my $item_2 = $builder->build_sample_item(
6021 library => $library->branchcode
6025 $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->borrowernumber } } );
6027 my $dt_from = dt_from_string();
6028 my $dt_to = dt_from_string()->add( days => 7 );
6030 my $issue_1 = AddIssue( $patron, $item_1->barcode, $dt_to, undef, $dt_from );
6032 is( $issue_1->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
6034 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
6037 AddIssue( $patron, $item_2->barcode, $dt_to, undef, $dt_from );
6039 is( $issue_2->issuer->borrowernumber, $issuer->borrowernumber, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
6042 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
6045 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
6046 my $patron_1 = $builder->build_object(
6048 class => 'Koha::Patrons',
6049 value => { branchcode => $library_1->branchcode }
6052 my $patron_2 = $builder->build_object(
6054 class => 'Koha::Patrons',
6055 value => { branchcode => $library_1->branchcode }
6059 my $item = $builder->build_sample_item(
6061 library => $library_1->branchcode,
6065 AddIssue( $patron_1, $item->barcode );
6066 ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
6067 AddIssue( $patron_2, $item->barcode );
6068 ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
6071 subtest "updateWrongTransfer tests" => sub {
6074 my $library1 = $builder->build_object( { class => 'Koha::Libraries' } );
6075 my $library2 = $builder->build_object( { class => 'Koha::Libraries' } );
6076 my $library3 = $builder->build_object( { class => 'Koha::Libraries' } );
6077 my $item = $builder->build_sample_item(
6079 homebranch => $library1->branchcode,
6080 holdingbranch => $library2->branchcode,
6081 datelastseen => undef
6085 my $transfer = $builder->build_object(
6087 class => 'Koha::Item::Transfers',
6089 itemnumber => $item->itemnumber,
6090 frombranch => $library2->branchcode,
6091 tobranch => $library1->branchcode,
6092 daterequested => dt_from_string,
6093 datesent => dt_from_string,
6094 datecancelled => undef,
6095 datearrived => undef,
6100 is( ref($transfer), 'Koha::Item::Transfer', 'Mock transfer added' );
6102 my $new_transfer = C4::Circulation::updateWrongTransfer($item->itemnumber, $library1->branchcode);
6103 is(ref($new_transfer), 'Koha::Item::Transfer', "updateWrongTransfer returns a 'Koha::Item::Transfer' object");
6104 ok( !$new_transfer->in_transit, "New transfer is NOT created as in transit (or cancelled)");
6106 my $original_transfer = $transfer->get_from_storage;
6107 ok( defined($original_transfer->datecancelled), "Original transfer was cancelled");
6108 is( $original_transfer->cancellation_reason, 'WrongTransfer', "Original transfer cancellation reason is 'WrongTransfer'");
6111 subtest "SendCirculationAlert" => sub {
6114 # When you would unsuspectingly call this unit test (with perl, not prove), you will be bitten by LOCK.
6115 # LOCK will commit changes and ruin your data
6116 # In order to prevent that, we will add KOHA_TESTING to $ENV; see further Circulation.pm
6117 $ENV{KOHA_TESTING} = 1;
6119 # Setup branch, borrowr, and notice
6120 my $library = $builder->build_object({ class => 'Koha::Libraries' });
6121 set_userenv( $library->unblessed);
6122 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
6123 C4::Members::Messaging::SetMessagingPreference({
6124 borrowernumber => $patron->id,
6125 message_transport_types => ['sms'],
6126 message_attribute_id => 5
6128 my $item = $builder->build_sample_item();
6129 my $checkin_notice = $builder->build_object({
6130 class => 'Koha::Notice::Templates',
6132 module => 'circulation',
6134 branchcode => $library->branchcode,
6135 name => 'Test Checkin',
6137 content => "Checkins:\n----\n[% biblio.title %]-[% old_checkout.issue_id %]\n----Thank you.",
6138 message_transport_type => 'sms',
6143 # Checkout an item, mark it returned, generate a notice
6144 my $issue_1 = AddIssue( $patron, $item->barcode);
6145 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
6146 C4::Circulation::SendCirculationAlert({
6148 item => $item->unblessed,
6149 borrower => $patron->unblessed,
6150 branch => $library->branchcode,
6153 my $notice = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'CHECKIN' });
6154 is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\nThank you.", 'Letter generated with expected output on first checkin' );
6155 is($notice->to_address, $patron->smsalertnumber, "Letter has the correct to_address set to smsalertnumber for SMS type notices");
6157 # Checkout an item, mark it returned, generate a notice
6158 my $issue_2 = AddIssue( $patron, $item->barcode);
6159 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
6160 C4::Circulation::SendCirculationAlert({
6162 item => $item->unblessed,
6163 borrower => $patron->unblessed,
6164 branch => $library->branchcode,
6167 $notice->discard_changes();
6168 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' );
6172 subtest "GetSoonestRenewDate tests" => sub {
6174 Koha::CirculationRules->set_rule(
6176 categorycode => undef,
6177 branchcode => undef,
6179 rule_name => 'norenewalbefore',
6183 my $patron = $builder->build_object(
6185 class => 'Koha::Patrons',
6187 autorenew_checkouts => 1,
6191 my $item = $builder->build_sample_item();
6192 my $issue = AddIssue( $patron, $item->barcode);
6193 my $datedue = dt_from_string( $issue->date_due() );
6196 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
6197 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
6199 GetSoonestRenewDate( $patron, $issue ),
6200 $datedue->clone->add( days => -7 ),
6201 'Bug 14395: Renewals permitted 7 days before due date, as expected'
6205 # Test 'date' setting for syspref NoRenewalBeforePrecision
6206 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
6208 GetSoonestRenewDate( $patron, $issue ),
6209 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
6210 'Bug 14395: Renewals permitted 7 days before due date, as expected'
6214 Koha::CirculationRules->set_rule(
6216 categorycode => undef,
6217 branchcode => undef,
6219 rule_name => 'norenewalbefore',
6220 rule_value => undef,
6225 GetSoonestRenewDate( $patron, $issue ),
6227 'Checkouts without auto-renewal can be renewed immediately if no norenewalbefore'
6230 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
6231 $issue->auto_renew(1)->store;
6233 GetSoonestRenewDate( $patron, $issue, 1 ),
6234 $datedue->clone->truncate( to => 'day' ),
6235 'Checkouts with auto-renewal can be renewed earliest on due date if noautorenewalbefore'
6237 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact' );
6239 GetSoonestRenewDate( $patron, $issue, 1 ),
6241 'Checkouts with auto-renewal can be renewed earliest on due date if noautorenewalbefore'
6244 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
6245 Koha::CirculationRules->set_rule(
6247 categorycode => undef,
6248 branchcode => undef,
6250 rule_name => 'norenewalbefore',
6254 $issue->date_due(dt_from_string)->store;
6256 GetSoonestRenewDate( $patron, $issue ),
6257 dt_from_string->subtract( days => 1 )->truncate( to => 'day' ),
6258 'Checkouts with auto-renewal can be renewed 1 day before due date if no renewalbefore = 1 and precision = "date"'
6263 subtest "CanBookBeIssued + needsconfirmation message" => sub {
6266 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
6267 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
6268 my $biblio = $builder->build_object({ class => 'Koha::Biblios' });
6269 my $biblioitem = $builder->build_object({ class => 'Koha::Biblioitems', value => { biblionumber => $biblio->biblionumber }});
6270 my $item = $builder->build_object({ class => 'Koha::Items' , value => { itype => $itemtype, biblionumber => $biblio->biblionumber }});
6272 my $hold = $builder->build_object({ class => 'Koha::Holds', value => {
6273 biblionumber => $item->biblionumber,
6274 branchcode => $library->branchcode,
6275 itemnumber => undef,
6280 item_group_id => undef
6283 my ( $error, $needsconfirmation, $alerts, $messages );
6285 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
6286 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold exists.");
6288 $hold->priority(0)->store();
6290 $hold->found("W")->store();
6291 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
6292 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is waiting.");
6294 $hold->found("T")->store();
6295 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
6296 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is being transferred.");
6298 $hold->found("P")->store();
6299 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
6300 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is being processed.");
6303 subtest 'Tests for BlockReturnOfWithdrawnItems' => sub {
6307 t::lib::Mocks::mock_preference('BlockReturnOfWithdrawnItems', 1);
6308 t::lib::Mocks::mock_preference('RecordLocalUseOnReturn', 0);
6309 my $item = $builder->build_sample_item();
6310 $item->withdrawn(1)->itemlost(1)->store;
6311 my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef );
6314 [ 0, { NotIssued => $item->barcode, withdrawn => 1 }, undef, {} ], "Item returned as withdrawn, no other messages");
6317 subtest 'Tests for transfer not in transit' => sub {
6322 # These tests are to ensure a 'pending' transfer, generated by
6323 # stock rotation, will be advanced when checked in
6325 my $item = $builder->build_sample_item();
6326 my $transfer = $builder->build_object({ class => 'Koha::Item::Transfers', value => {
6327 itemnumber => $item->id,
6328 reason => 'StockrotationRepatriation',
6330 frombranch => $item->homebranch,
6332 my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef );
6335 [ 0, { WasTransfered => $transfer->tobranch, TransferTrigger => 'StockrotationRepatriation', NotIssued => $item->barcode }, undef, {} ], "Item is reported to have been transferred");
6337 $transfer->discard_changes;
6338 ok( $transfer->datesent, 'The datesent field is populated, i.e. transfer is initiated');
6342 subtest 'Tests for RecordLocalUseOnReturn' => sub {
6346 t::lib::Mocks::mock_preference('RecordLocalUseOnReturn', 0);
6347 my $item = $builder->build_sample_item();
6348 $item->withdrawn(1)->itemlost(1)->store;
6349 my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef );
6352 [ 0, { NotIssued => $item->barcode, withdrawn => 1 }, undef, {} ], "RecordLocalUSeOnReturn is off, no local use recorded");
6354 t::lib::Mocks::mock_preference('RecordLocalUseOnReturn', 1);
6355 my @return2 = AddReturn( $item->barcode, $item->homebranch, 0, undef );
6358 [ 0, { NotIssued => $item->barcode, withdrawn => 1, LocalUse => 1 }, undef, {} ], "Local use is recorded");
6361 subtest 'Test CanBookBeIssued param ignore_reserves (Bug 35322)' => sub {
6364 my $homebranch = $builder->build( { source => 'Branch' } );
6365 my $holdingbranch = $builder->build( { source => 'Branch' } );
6366 my $patron_1 = $builder->build_object(
6367 { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
6368 my $patron_2 = $builder->build_object(
6369 { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
6371 my $item = $builder->build_sample_item(
6373 homebranch => $homebranch->{branchcode},
6374 holdingbranch => $holdingbranch->{branchcode},
6378 Koha::CirculationRules->search()->delete();
6379 Koha::CirculationRules->set_rules(
6381 categorycode => undef,
6383 branchcode => undef,
6385 reservesallowed => 25,
6387 lengthunit => 'days',
6388 renewalsallowed => 1,
6396 my $reserve_id = AddReserve(
6398 branchcode => $homebranch,
6399 borrowernumber => $patron_1->id,
6400 biblionumber => $item->biblionumber,
6402 reservation_date => dt_from_string,
6403 expiration_date => dt_from_string,
6404 itemnumber => $item->id,
6409 set_userenv($holdingbranch);
6411 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode, undef, undef, 0 );
6413 keys(%$error) + keys(%$alerts), 0,
6414 'There should not be any errors or alerts (impossible)' . str( $error, $question, $alerts )
6416 is( exists $question->{RESERVE_WAITING}, 1, 'RESERVE_WAITING is set' );
6418 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode, undef, undef, 1 );
6420 keys(%$error) + keys(%$alerts), 0,
6421 'There should not be any errors or alerts (impossible)' . str( $error, $question, $alerts )
6423 isnt( exists $question->{RESERVE_WAITING}, 1, 'RESERVE_WAITING is not set' );
6428 $schema->storage->txn_rollback;
6429 C4::Context->clear_syspref_cache();
6430 $branches = Koha::Libraries->search();
6431 for my $branch ( $branches->next ) {
6432 my $key = $branch->branchcode . "_holidays";
6433 $cache->clear_from_cache($key);