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 => 67;
24 use Test::Deep qw( cmp_deeply );
30 use POSIX qw( floor );
32 use t::lib::TestBuilder;
35 use C4::Calendar qw( new insert_single_holiday insert_week_day_holiday delete_holiday );
36 use C4::Circulation qw( AddIssue AddReturn CanBookBeRenewed GetIssuingCharges AddRenewal GetSoonestRenewDate GetLatestAutoRenewDate LostItem GetUpcomingDueIssues CanBookBeIssued AddIssuingCharge MarkIssueReturned ProcessOfflinePayment transferbook updateWrongTransfer );
38 use C4::Items qw( ModItemTransfer );
40 use C4::Reserves qw( AddReserve ModReserve ModReserveCancelAll ModReserveAffect CheckReserves GetOtherReserves );
41 use C4::Overdues qw( CalcFine UpdateFine get_chargeable_units );
42 use C4::Members::Messaging qw( SetMessagingPreference );
43 use Koha::DateUtils qw( dt_from_string output_pref );
46 use Koha::Item::Transfers;
49 use Koha::Patron::Debarments qw( AddDebarment DelUniqueDebarment );
51 use Koha::CirculationRules;
52 use Koha::Subscriptions;
53 use Koha::Account::Lines;
54 use Koha::Account::Offsets;
56 use Koha::Notice::Messages;
57 use Koha::Cache::Memory::Lite;
59 my $builder = t::lib::TestBuilder->new;
62 my $staff = $builder->build_object({ class => "Koha::Patrons" });
63 t::lib::Mocks::mock_userenv({ patron => $staff, branchcode => $library->{branchcode} });
67 my ( $error, $question, $alert ) = @_;
69 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
70 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
71 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
75 sub test_debarment_on_checkout {
77 my $item = $params->{item};
78 my $library = $params->{library};
79 my $patron = $params->{patron};
80 my $due_date = $params->{due_date} || dt_from_string;
81 my $return_date = $params->{return_date} || dt_from_string;
82 my $expected_expiration_date = $params->{expiration_date};
84 $expected_expiration_date = output_pref(
86 dt => $expected_expiration_date,
92 my $line_number = $caller[2];
93 AddIssue( $patron, $item->barcode, $due_date );
95 my ( undef, $message ) = AddReturn( $item->barcode, $library->{branchcode}, undef, $return_date );
96 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
97 or diag('AddReturn returned message ' . Dumper $message );
98 my $suspensions = $patron->restrictions->search({ type => 'SUSPENSION' } );
99 is( $suspensions->count, 1, 'Test at line ' . $line_number );
101 my $THE_suspension = $suspensions->next;
102 is( $THE_suspension->expiration,
103 $expected_expiration_date, 'Test at line ' . $line_number );
104 Koha::Patron::Debarments::DelUniqueDebarment(
105 { borrowernumber => $patron->borrowernumber, type => 'SUSPENSION' } );
108 my $schema = Koha::Database->schema;
109 $schema->storage->txn_begin;
110 my $dbh = C4::Context->dbh;
112 # Prevent random failures by mocking ->now
113 my $now_value = dt_from_string;
114 my $mocked_datetime = Test::MockModule->new('DateTime');
115 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
117 my $cache = Koha::Caches->get_instance();
118 $dbh->do(q|DELETE FROM special_holidays|);
119 $dbh->do(q|DELETE FROM repeatable_holidays|);
120 my $branches = Koha::Libraries->search();
121 for my $branch ( $branches->next ) {
122 my $key = $branch->branchcode . "_holidays";
123 $cache->clear_from_cache($key);
126 # Start with a clean slate
127 $dbh->do('DELETE FROM issues');
128 $dbh->do('DELETE FROM borrowers');
130 # Disable recording of the staff who checked out an item until we're ready for it
131 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 0);
133 my $module = Test::MockModule->new('C4::Context');
135 my $library = $builder->build({
138 my $library2 = $builder->build({
141 my $itemtype = $builder->build(
143 source => 'Itemtype',
147 rentalcharge_daily => 0,
148 defaultreplacecost => undef,
153 my $patron_category = $builder->build(
155 source => 'Category',
157 category_type => 'P',
159 BlockExpiredPatronOpacActions => -1, # Pick the pref value
164 my $CircControl = C4::Context->preference('CircControl');
165 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
167 my $item = $builder->build_object({
168 class => 'Koha::Items',
170 homebranch => $library2->{branchcode},
171 holdingbranch => $library2->{branchcode}
175 my $borrower = $builder->build_object({
176 class => 'Koha::Patrons',
177 value => { branchcode => $library2->{branchcode} }
180 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
182 # No userenv, PickupLibrary
183 t::lib::Mocks::mock_preference('IndependentBranches', '0');
184 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
186 C4::Context->preference('CircControl'),
188 'CircControl changed to PickupLibrary'
191 C4::Circulation::_GetCircControlBranch($item, $borrower),
192 $item->get_column($HomeOrHoldingBranch),
193 '_GetCircControlBranch returned item branch (no userenv defined)'
196 # No userenv, PatronLibrary
197 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
199 C4::Context->preference('CircControl'),
201 'CircControl changed to PatronLibrary'
204 C4::Circulation::_GetCircControlBranch($item, $borrower),
205 $borrower->branchcode,
206 '_GetCircControlBranch returned borrower branch'
209 # No userenv, ItemHomeLibrary
210 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
212 C4::Context->preference('CircControl'),
214 'CircControl changed to ItemHomeLibrary'
217 $item->get_column($HomeOrHoldingBranch),
218 C4::Circulation::_GetCircControlBranch($item, $borrower),
219 '_GetCircControlBranch returned item branch'
223 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
224 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
226 # Userenv set, PickupLibrary
227 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
229 C4::Context->preference('CircControl'),
231 'CircControl changed to PickupLibrary'
234 C4::Circulation::_GetCircControlBranch($item, $borrower),
235 $library2->{branchcode},
236 '_GetCircControlBranch returned current branch'
239 # Userenv set, PatronLibrary
240 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
242 C4::Context->preference('CircControl'),
244 'CircControl changed to PatronLibrary'
247 C4::Circulation::_GetCircControlBranch($item, $borrower),
248 $borrower->branchcode,
249 '_GetCircControlBranch returned borrower branch'
252 # Userenv set, ItemHomeLibrary
253 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
255 C4::Context->preference('CircControl'),
257 'CircControl changed to ItemHomeLibrary'
260 C4::Circulation::_GetCircControlBranch($item, $borrower),
261 $item->get_column($HomeOrHoldingBranch),
262 '_GetCircControlBranch returned item branch'
265 # Reset initial configuration
266 t::lib::Mocks::mock_preference('CircControl', $CircControl);
268 C4::Context->preference('CircControl'),
270 'CircControl reset to its initial value'
273 # Set a simple circ policy
274 $dbh->do('DELETE FROM circulation_rules');
275 Koha::CirculationRules->set_rules(
277 categorycode => undef,
281 reservesallowed => 25,
283 lengthunit => 'days',
284 renewalsallowed => 1,
286 norenewalbefore => undef,
287 noautorenewalbefore => undef,
295 subtest "CanBookBeRenewed AllowRenewalIfOtherItemsAvailable multiple borrowers and items tests" => sub {
298 #Can only reserve from home branch
299 Koha::CirculationRules->set_rule(
303 rule_name => 'holdallowed',
307 Koha::CirculationRules->set_rule(
310 categorycode => undef,
312 rule_name => 'onshelfholds',
317 # Patrons from three different branches
318 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
319 my $patron_hold_1 = $builder->build_object({ class => 'Koha::Patrons' });
320 my $patron_hold_2 = $builder->build_object({ class => 'Koha::Patrons' });
321 my $biblio = $builder->build_sample_biblio();
323 # Item at each patron branch
324 my $item_1 = $builder->build_sample_item({
325 biblionumber => $biblio->biblionumber,
326 homebranch => $patron->branchcode
328 my $item_2 = $builder->build_sample_item({
329 biblionumber => $biblio->biblionumber,
330 homebranch => $patron_hold_2->branchcode
332 my $item_3 = $builder->build_sample_item({
333 biblionumber => $biblio->biblionumber,
334 homebranch => $patron_hold_1->branchcode
337 my $issue = AddIssue( $patron, $item_1->barcode);
338 my $datedue = dt_from_string( $issue->date_due() );
339 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
342 my $reserve_1 = AddReserve(
344 branchcode => $patron_hold_1->branchcode,
345 borrowernumber => $patron_hold_1->borrowernumber,
346 biblionumber => $biblio->biblionumber,
348 reservation_date => dt_from_string(),
349 expiration_date => undef,
356 branchcode => $patron_hold_2->branchcode,
357 borrowernumber => $patron_hold_2->borrowernumber,
358 biblionumber => $biblio->biblionumber,
360 reservation_date => dt_from_string(),
361 expiration_date => undef,
366 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
368 my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue);
369 is( $renewokay, 0, 'Cannot renew, reserved');
370 is( $error, 'on_reserve', 'Cannot renew, reserved (returned error is on_reserve)');
372 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
374 ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue);
375 is( $renewokay, 1, 'Can renew, two items available for two holds');
376 is( $error, undef, 'Can renew, each reserve has an item');
379 my $hold = Koha::Holds->find( $reserve_1 );
380 $hold->itemnumber( $item_1->itemnumber )->store;
382 ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue);
383 is( $renewokay, 0, 'Cannot renew when there is an item specific hold');
384 is( $error, 'on_reserve', 'Cannot renew, only this item can fill the reserve');
387 subtest "GetIssuingCharges tests" => sub {
389 my $branch_discount = $builder->build_object({ class => 'Koha::Libraries' });
390 my $branch_no_discount = $builder->build_object({ class => 'Koha::Libraries' });
391 Koha::CirculationRules->set_rule(
393 categorycode => undef,
394 branchcode => $branch_discount->branchcode,
396 rule_name => 'rentaldiscount',
400 my $itype_charge = $builder->build_object({
401 class => 'Koha::ItemTypes',
406 my $itype_no_charge = $builder->build_object({
407 class => 'Koha::ItemTypes',
412 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
413 my $item_1 = $builder->build_sample_item({ itype => $itype_charge->itemtype });
414 my $item_2 = $builder->build_sample_item({ itype => $itype_no_charge->itemtype });
416 t::lib::Mocks::mock_userenv({ branchcode => $branch_no_discount->branchcode });
417 # For now the sub always uses the env branch, this should follow CircControl instead
418 my ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
419 is( $charge + 0, 10.00, "Charge fetched correctly when no discount exists");
420 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
421 is( $charge + 0, 0.00, "Charge fetched correctly when no discount exists and no charge");
423 t::lib::Mocks::mock_userenv({ branchcode => $branch_discount->branchcode });
424 # For now the sub always uses the env branch, this should follow CircControl instead
425 ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
426 is( $charge + 0, 8.50, "Charge fetched correctly when discount exists");
427 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
428 is( $charge + 0, 0.00, "Charge fetched correctly when discount exists and no charge");
432 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
433 subtest "CanBookBeRenewed tests" => sub {
436 C4::Context->set_preference('ItemsDeniedRenewal','');
437 # Generate test biblio
438 my $biblio = $builder->build_sample_biblio();
440 my $branch = $library2->{branchcode};
442 my $item_1 = $builder->build_sample_item(
444 biblionumber => $biblio->biblionumber,
446 replacementprice => 12.00,
450 $reused_itemnumber_1 = $item_1->itemnumber;
452 my $item_2 = $builder->build_sample_item(
454 biblionumber => $biblio->biblionumber,
456 replacementprice => 23.00,
460 $reused_itemnumber_2 = $item_2->itemnumber;
462 my $item_3 = $builder->build_sample_item(
464 biblionumber => $biblio->biblionumber,
466 replacementprice => 23.00,
472 my %renewing_borrower_data = (
474 surname => 'Renewal',
475 categorycode => $patron_category->{categorycode},
476 branchcode => $branch,
477 autorenew_checkouts => 1,
480 my %reserving_borrower_data = (
481 firstname => 'Katrin',
482 surname => 'Reservation',
483 categorycode => $patron_category->{categorycode},
484 branchcode => $branch,
487 my %hold_waiting_borrower_data = (
489 surname => 'Reservation',
490 categorycode => $patron_category->{categorycode},
491 branchcode => $branch,
494 my %restricted_borrower_data = (
495 firstname => 'Alice',
496 surname => 'Reservation',
497 categorycode => $patron_category->{categorycode},
498 debarred => '3228-01-01',
499 branchcode => $branch,
502 my %expired_borrower_data = (
505 categorycode => $patron_category->{categorycode},
506 branchcode => $branch,
507 dateexpiry => dt_from_string->subtract( months => 1 ),
508 autorenew_checkouts => 1,
511 my $renewing_borrower_obj = Koha::Patron->new(\%renewing_borrower_data)->store;
512 my $renewing_borrowernumber = $renewing_borrower_obj->borrowernumber;
513 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
514 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
515 my $restricted_borrower_obj = Koha::Patron->new(\%restricted_borrower_data)->store;
517 my $expired_borrower_obj = Koha::Patron->new(\%expired_borrower_data)->store;
524 my $checkitem = undef;
527 my $issue_1 = AddIssue( $renewing_borrower_obj, $item_1->barcode);
528 my $datedue = dt_from_string( $issue_1->date_due() );
529 is (defined $issue_1->date_due(), 1, "Item 1 checked out, due date: " . $issue_1->date_due() );
531 my $issue_2 = AddIssue( $renewing_borrower_obj, $item_2->barcode);
532 is (defined $issue_2, 1, "Item 2 checked out, due date: " . $issue_2->date_due());
534 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
535 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to ".$renewing_borrower_obj->firstname." ".$renewing_borrower_obj->surname);
537 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1, 1);
538 is( $renewokay, 1, 'Can renew, no holds for this title or item');
541 # Biblio-level hold, renewal test
544 branchcode => $branch,
545 borrowernumber => $reserving_borrowernumber,
546 biblionumber => $biblio->biblionumber,
547 priority => $priority,
548 reservation_date => $resdate,
549 expiration_date => $expdate,
551 itemnumber => $checkitem,
556 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
557 Koha::CirculationRules->set_rule(
559 categorycode => undef,
562 rule_name => 'onshelfholds',
566 Koha::CirculationRules->set_rule(
568 categorycode => undef,
571 rule_name => 'renewalsallowed',
575 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
576 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
577 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
578 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2);
579 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
582 # Second biblio-level hold
583 my $reserve_id = AddReserve(
585 branchcode => $branch,
586 borrowernumber => $reserving_borrowernumber,
587 biblionumber => $biblio->biblionumber,
588 priority => $priority,
589 reservation_date => $resdate,
590 expiration_date => $expdate,
592 itemnumber => $checkitem,
596 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
597 is( $renewokay, 0, 'Renewal not possible when single patron\'s holds exceed the number of available items');
598 Koha::Holds->find($reserve_id)->delete;
600 # Now let's add an item level hold, we should no longer be able to renew the item
601 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
603 borrowernumber => $hold_waiting_borrowernumber,
604 biblionumber => $biblio->biblionumber,
605 itemnumber => $item_1->itemnumber,
606 branchcode => $branch,
608 reservedate => '1999-01-01',
611 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
612 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
615 # 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
616 # be able to renew these items
617 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
619 borrowernumber => $hold_waiting_borrowernumber,
620 biblionumber => $biblio->biblionumber,
621 itemnumber => $item_3->itemnumber,
622 branchcode => $branch,
627 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
628 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
629 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2);
630 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
631 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
633 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
634 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
635 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
637 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2);
638 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
639 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
641 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
642 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber );
643 AddIssue($reserving_borrower, $item_3->barcode);
644 my $reserve = $dbh->selectrow_hashref(
645 'SELECT * FROM old_reserves WHERE reserve_id = ?',
649 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
651 # Item-level hold, renewal test
654 branchcode => $branch,
655 borrowernumber => $reserving_borrowernumber,
656 biblionumber => $biblio->biblionumber,
657 priority => $priority,
658 reservation_date => $resdate,
659 expiration_date => $expdate,
661 itemnumber => $item_1->itemnumber,
666 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1, 1);
667 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
668 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
670 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2, 1);
671 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
673 # Items can't fill hold for reasons
674 $issue_1->item->notforloan(1)->store;
675 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1, 1);
676 is( $renewokay, 0, 'Cannot renew, item is marked not for loan, but an item specific hold always blocks');
677 $item_1->set({notforloan => 0, itype => $itemtype })->store;
679 # FIXME: Add more for itemtype not for loan etc.
681 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
682 my $item_5 = $builder->build_sample_item(
684 biblionumber => $biblio->biblionumber,
686 replacementprice => 23.00,
690 my $issue_5 = AddIssue($restricted_borrower_obj, $item_5->barcode);
691 is (defined $issue_5, 1, "Item with date due checked out, due date: ". $issue_5->date_due);
693 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
694 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2);
695 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
696 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrower_obj, $issue_5);
697 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
698 is( $error, 'restriction', "Correct error returned");
700 # Users cannot renew an overdue item
701 my $item_6 = $builder->build_sample_item(
703 biblionumber => $biblio->biblionumber,
705 replacementprice => 23.00,
710 my $item_7 = $builder->build_sample_item(
712 biblionumber => $biblio->biblionumber,
714 replacementprice => 23.00,
719 my $issue_6 = AddIssue( $renewing_borrower_obj, $item_6->barcode);
720 is (defined $issue_6, 1, "Item 2 checked out, due date: ".$issue_6->date_due);
722 my $now = dt_from_string();
723 my $five_weeks = DateTime::Duration->new(weeks => 5);
724 my $five_weeks_ago = $now - $five_weeks;
725 t::lib::Mocks::mock_preference('finesMode', 'production');
727 my $issue_7 = AddIssue($renewing_borrower_obj, $item_7->barcode, $five_weeks_ago);
728 is (defined $issue_7, 1, "Item with passed date due checked out, due date: " . $issue_7->date_due);
730 t::lib::Mocks::mock_preference('OverduesBlockRenewing','allow');
731 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_6);
732 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
733 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_7);
734 is( $renewokay, 1, '(Bug 8236), Can renew, this item is overdue but not pref does not block');
736 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
737 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_6);
738 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is not overdue but patron has overdues');
739 is( $error, 'overdue', "Correct error returned");
740 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_7);
741 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue so patron has overdues');
742 is( $error, 'overdue', "Correct error returned");
744 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
745 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_6);
746 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
747 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_7);
748 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
749 is( $error, 'overdue', "Correct error returned");
751 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower_obj->categorycode, $branch, $five_weeks_ago, $now );
752 C4::Overdues::UpdateFine(
754 issue_id => $issue_7->id(),
755 itemnumber => $item_7->itemnumber,
756 borrowernumber => $renewing_borrower_obj->borrowernumber,
758 due => Koha::DateUtils::output_pref($five_weeks_ago)
762 # Make sure fine calculation isn't skipped when adding renewal
763 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
765 # Calculate new due-date based on the present date not to incur
767 t::lib::Mocks::mock_preference('RenewalPeriodBase', 'now');
769 my $staff = $builder->build_object({ class => "Koha::Patrons" });
770 t::lib::Mocks::mock_userenv({ patron => $staff });
772 t::lib::Mocks::mock_preference('RenewalLog', 0);
773 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
774 my %params_renewal = (
775 timestamp => { -like => $date . "%" },
776 module => "CIRCULATION",
780 timestamp => { -like => $date . "%" },
781 module => "CIRCULATION",
784 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
785 my $dt = dt_from_string();
786 Time::Fake->offset( $dt->epoch );
787 my $datedue1 = AddRenewal(
789 borrowernumber => $renewing_borrower_obj->borrowernumber,
790 itemnumber => $item_7->itemnumber,
794 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
795 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
796 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
799 t::lib::Mocks::mock_preference('RenewalLog', 1);
800 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
801 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
804 borrowernumber => $renewing_borrower_obj->borrowernumber,
805 itemnumber => $item_7->itemnumber,
809 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
810 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
812 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower_obj->borrowernumber, itemnumber => $item_7->itemnumber } );
813 is( $fines->count, 1, 'AddRenewal left fine' );
814 is( $fines->next->status, 'RENEWED', 'Fine on renewed item is closed out properly' );
817 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
818 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
820 $renewing_borrower_obj,
822 Koha::DateUtils::output_pref({str=>$issue_6->date_due, dateformat =>'iso'}),
827 ); # TODO: Already issued???
828 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
829 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
830 $new_log_size = Koha::ActionLogs->count( \%params_issue );
831 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
833 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
837 # Test automatic renewal before value for "norenewalbefore" in policy is set
838 # In this case automatic renewal should still be permitted
839 my $item_4 = $builder->build_sample_item(
841 biblionumber => $biblio->biblionumber,
843 replacementprice => 16.00,
848 my $auto_renew_issue = AddIssue( $renewing_borrower_obj, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
850 ( $renewokay, $error, $info ) =
851 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
852 is( $info->{soonest_renew_date}, undef, "soonest_renew_date is not returned because this issue can be renewed" );
853 is( $renewokay, 1, 'Bug 25393: Can do a manual renew, even if renewal is automatic and premature' );
855 $error, 'auto_renew',
856 'Bug 25393: Can do a manual renew, even if renewal is automatic and premature, norenewalbefore = undef -> manual renewals are allowed at any time'
859 my ( $renewokay_cron, $error_cron, $info_cron ) =
860 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 );
862 $info_cron->{soonest_renew_date}, dt_from_string( $auto_renew_issue->date_due ),
863 "Due date is returned as earliest renewal date when the CanBookBeRenewed check is done by cron and error is 'auto_too_soon'"
867 branchcode => $branch,
868 borrowernumber => $reserving_borrowernumber,
869 biblionumber => $biblio->biblionumber,
870 itemnumber => $bibitems,
871 priority => $priority,
872 reservation_date => $resdate,
873 expiration_date => $expdate,
876 itemnumber => $item_4->itemnumber,
880 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
881 is( $renewokay, 0, 'Still should not be able to renew' );
882 is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' );
883 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 );
884 is( $renewokay, 0, 'Still should not be able to renew' );
885 is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' );
886 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'" );
887 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, 1 );
888 is( $renewokay, 0, 'Still should not be able to renew' );
889 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
890 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, 1, 1 );
891 is( $renewokay, 0, 'Still should not be able to renew' );
892 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
893 $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
894 Koha::Cache::Memory::Lite->flush();
895 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, 1 );
896 is( $renewokay, 0, 'Still should not be able to renew' );
897 is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
898 ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
900 $renewing_borrower_obj = Koha::Patrons->find($renewing_borrower_obj->borrowernumber);
901 $renewing_borrower_obj->autorenew_checkouts(0)->store;
902 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
903 is( $renewokay, 1, 'No renewal before is undef, but patron opted out of auto_renewal' );
904 $renewing_borrower_obj->autorenew_checkouts(1)->store;
908 # Test premature manual renewal
909 Koha::CirculationRules->set_rule(
911 categorycode => undef,
914 rule_name => 'norenewalbefore',
919 ( $renewokay, $error, $info ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
920 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
921 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
922 is( $info->{soonest_renew_date}, dt_from_string($issue_1->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
925 # Test premature automatic renewal
926 Koha::CirculationRules->set_rule(
928 categorycode => undef,
931 rule_name => 'noautorenewalbefore',
936 ( $renewokay, $error, $info ) =
937 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
938 is( $renewokay, 0, 'Bug 25393: Cannot renew, renewal is premature' );
939 is( $error, 'too_soon',
940 'Bug 25393: Cannot renew, renewal is premature (returned code is too_soon)'
942 is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'auto_too_soon'");
944 ( $renewokay_cron, $error_cron, $info_cron ) =
945 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 );
947 $error_cron, 'auto_too_soon',
948 'Bug 25393: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
950 $renewing_borrower_obj->autorenew_checkouts(0)->store;
951 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
952 is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' );
953 is( $error, 'too_soon', 'Error is too_soon, no auto' );
954 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'");
955 $renewing_borrower_obj->autorenew_checkouts(1)->store;
957 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
958 # and test automatic renewal again
959 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
960 Koha::Cache::Memory::Lite->flush();
961 ( $renewokay, $error, $info ) =
962 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
963 is( $renewokay, 0, 'Bug 25393: Cannot manual renew, renewal is too soon' );
964 is( $error, 'too_soon',
965 'Bug 25393: Cannot manual renew, renewal is too soon, even though it\'s also scheduled for auto renewal'
967 is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
969 # Now we test for noautorenewalbefore if cron
970 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'noautorenewalbefore'});
971 Koha::Cache::Memory::Lite->flush();
972 ( $renewokay, $error, $info ) =
973 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 );
974 is( $renewokay, 0, 'Bug 25393: Cannot auto renew, renewal is too soon' );
975 is( $error, 'auto_too_soon',
976 'Bug 25393: Cannot auto renew, auto renewal is too soon'
978 is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
980 $renewing_borrower_obj->autorenew_checkouts(0)->store;
981 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
982 is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' );
983 is( $error, 'too_soon', 'Error is too_soon, no auto' );
984 is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
985 $renewing_borrower_obj->autorenew_checkouts(1)->store;
987 # Change policy so that loans can be renewed 99 days prior to the due date
988 # and test automatic renewal again
989 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
990 Koha::Cache::Memory::Lite->flush();
991 ( $renewokay, $error ) =
992 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
993 is( $renewokay, 1, 'Bug 25393: Can do a manual renew, even if renewal is automatic and premature' );
994 is( $error, 'auto_renew',
995 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
998 # Now we test for noautorenewalbefore if cron
999 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'noautorenewalbefore'});
1000 Koha::Cache::Memory::Lite->flush();
1001 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 );
1002 is( $renewokay, 1, 'Bug 25393: Can auto renew' );
1003 is( $error, 'auto_renew', 'Bug 25393: Can auto renew' );
1004 is( $info->{soonest_renew_date}, undef, "soonest_renew_date is not returned because this issue can be renewed" );
1006 $renewing_borrower_obj->autorenew_checkouts(0)->store;
1007 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
1008 is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' );
1009 $renewing_borrower_obj->autorenew_checkouts(1)->store;
1011 subtest "too_late_renewal / no_auto_renewal_after" => sub {
1013 my $item_to_auto_renew = $builder->build_sample_item(
1015 biblionumber => $biblio->biblionumber,
1020 my $ten_days_before = dt_from_string->add( days => -10 );
1021 my $ten_days_ahead = dt_from_string->add( days => 10 );
1022 my $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1024 Koha::CirculationRules->set_rules(
1026 categorycode => undef,
1027 branchcode => undef,
1030 norenewalbefore => '7',
1031 no_auto_renewal_after => '9',
1035 ( $renewokay, $error ) =
1036 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1037 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1038 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1040 Koha::CirculationRules->set_rules(
1042 categorycode => undef,
1043 branchcode => undef,
1046 norenewalbefore => '7',
1047 no_auto_renewal_after => '10',
1051 ( $renewokay, $error ) =
1052 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1053 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1054 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
1056 Koha::CirculationRules->set_rules(
1058 categorycode => undef,
1059 branchcode => undef,
1062 norenewalbefore => '7',
1063 no_auto_renewal_after => '11',
1067 ( $renewokay, $error ) =
1068 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1069 is( $renewokay, 0, 'Do not renew, too_soon' );
1070 is( $error, 'too_soon', 'Cannot renew, too_soon - no_auto_renewal_after is defined(returned code is too_soon)' );
1072 # Now check for cron
1073 Koha::CirculationRules->set_rules(
1075 categorycode => undef,
1076 branchcode => undef,
1079 noautorenewalbefore => '9',
1080 no_auto_renewal_after => '11',
1084 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue, undef, 1 );
1085 is( $renewokay, 0, 'Do not renew, too_soon' );
1087 $error, 'auto_too_soon',
1088 'Cannot renew, too_soon - no_auto_renewal_after is defined(returned code is too_soon)'
1091 Koha::CirculationRules->set_rules(
1093 categorycode => undef,
1094 branchcode => undef,
1097 norenewalbefore => '10',
1098 no_auto_renewal_after => '11',
1102 ( $renewokay, $error ) =
1103 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1104 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1105 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1107 Koha::CirculationRules->set_rules(
1109 categorycode => undef,
1110 branchcode => undef,
1113 norenewalbefore => '10',
1114 no_auto_renewal_after => undef,
1115 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1119 ( $renewokay, $error ) =
1120 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1121 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1122 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1124 Koha::CirculationRules->set_rules(
1126 categorycode => undef,
1127 branchcode => undef,
1130 norenewalbefore => '7',
1131 no_auto_renewal_after => '15',
1132 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1136 ( $renewokay, $error ) =
1137 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1138 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1139 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1141 Koha::CirculationRules->set_rules(
1143 categorycode => undef,
1144 branchcode => undef,
1147 norenewalbefore => '10',
1148 no_auto_renewal_after => undef,
1149 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
1153 ( $renewokay, $error ) =
1154 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1155 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1156 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1159 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
1161 my $item_to_auto_renew = $builder->build_sample_item(
1163 biblionumber => $biblio->biblionumber,
1168 my $ten_days_before = dt_from_string->add( days => -10 );
1169 my $ten_days_ahead = dt_from_string->add( days => 10 );
1170 my $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1172 Koha::CirculationRules->set_rules(
1174 categorycode => undef,
1175 branchcode => undef,
1178 norenewalbefore => '10',
1179 no_auto_renewal_after => '11',
1183 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
1184 C4::Context->set_preference('OPACFineNoRenewals','10');
1185 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1186 my $fines_amount = 5;
1187 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
1188 $account->add_debit(
1190 amount => $fines_amount,
1191 interface => 'test',
1193 item_id => $item_to_auto_renew->itemnumber,
1194 description => "Some fines"
1196 )->status('RETURNED')->store;
1197 ( $renewokay, $error ) =
1198 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1199 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1200 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
1202 $account->add_debit(
1204 amount => $fines_amount,
1205 interface => 'test',
1207 item_id => $item_to_auto_renew->itemnumber,
1208 description => "Some fines"
1210 )->status('RETURNED')->store;
1211 ( $renewokay, $error ) =
1212 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1213 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1214 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
1216 $account->add_debit(
1218 amount => $fines_amount,
1219 interface => 'test',
1221 item_id => $item_to_auto_renew->itemnumber,
1222 description => "Some fines"
1224 )->status('RETURNED')->store;
1225 ( $renewokay, $error ) =
1226 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1227 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1228 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
1230 $account->add_credit(
1232 amount => $fines_amount,
1233 interface => 'test',
1235 description => "Some payment"
1238 ( $renewokay, $error ) =
1239 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1240 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1241 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1243 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
1244 ( $renewokay, $error ) =
1245 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1246 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1247 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1249 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
1250 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1253 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
1255 my $item_to_auto_renew = $builder->build_sample_item(
1257 biblionumber => $biblio->biblionumber,
1262 Koha::CirculationRules->set_rules(
1264 categorycode => undef,
1265 branchcode => undef,
1268 norenewalbefore => 10,
1269 no_auto_renewal_after => 11,
1274 my $ten_days_before = dt_from_string->add( days => -10 );
1275 my $ten_days_ahead = dt_from_string->add( days => 10 );
1277 # Patron is expired and BlockExpiredPatronOpacActions=0
1278 # => auto renew is allowed
1279 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
1280 my $issue = AddIssue( $expired_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1281 ( $renewokay, $error ) =
1282 CanBookBeRenewed( $expired_borrower_obj, $issue );
1283 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1284 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
1285 Koha::Checkouts->find( $issue->issue_id )->delete;
1288 # Patron is expired and BlockExpiredPatronOpacActions=1
1289 # => auto renew is not allowed
1290 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1291 $issue = AddIssue( $expired_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1292 ( $renewokay, $error ) =
1293 CanBookBeRenewed( $expired_borrower_obj, $issue );
1294 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1295 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
1298 # Patron is not expired and BlockExpiredPatronOpacActions=1
1299 # => auto renew is allowed
1300 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1301 $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1302 ( $renewokay, $error ) =
1303 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1304 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1305 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1309 subtest "GetLatestAutoRenewDate" => sub {
1311 my $item_to_auto_renew = $builder->build_sample_item(
1313 biblionumber => $biblio->biblionumber,
1318 my $ten_days_before = dt_from_string->add( days => -10 );
1319 my $ten_days_ahead = dt_from_string->add( days => 10 );
1320 my $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1321 Koha::CirculationRules->set_rules(
1323 categorycode => undef,
1324 branchcode => undef,
1327 norenewalbefore => '7',
1328 no_auto_renewal_after => '',
1329 no_auto_renewal_after_hard_limit => undef,
1333 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1334 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' );
1335 my $five_days_before = dt_from_string->add( days => -5 );
1336 Koha::CirculationRules->set_rules(
1338 categorycode => undef,
1339 branchcode => undef,
1342 norenewalbefore => '10',
1343 no_auto_renewal_after => '5',
1344 no_auto_renewal_after_hard_limit => undef,
1348 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj,, $issue );
1349 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1350 $five_days_before->truncate( to => 'minute' ),
1351 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1353 my $five_days_ahead = dt_from_string->add( days => 5 );
1354 $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1355 $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1356 $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1357 Koha::Cache::Memory::Lite->flush();
1358 Koha::CirculationRules->set_rules(
1360 categorycode => undef,
1361 branchcode => undef,
1364 norenewalbefore => '10',
1365 no_auto_renewal_after => '15',
1366 no_auto_renewal_after_hard_limit => undef,
1370 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1371 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1372 $five_days_ahead->truncate( to => 'minute' ),
1373 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1375 my $two_days_ahead = dt_from_string->add( days => 2 );
1376 Koha::CirculationRules->set_rules(
1378 categorycode => undef,
1379 branchcode => undef,
1382 norenewalbefore => '10',
1383 no_auto_renewal_after => '',
1384 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1388 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1389 is( $latest_auto_renew_date->truncate( to => 'day' ),
1390 $two_days_ahead->truncate( to => 'day' ),
1391 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1393 Koha::CirculationRules->set_rules(
1395 categorycode => undef,
1396 branchcode => undef,
1399 norenewalbefore => '10',
1400 no_auto_renewal_after => '15',
1401 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1405 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1406 is( $latest_auto_renew_date->truncate( to => 'day' ),
1407 $two_days_ahead->truncate( to => 'day' ),
1408 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1414 # set policy to forbid renewals
1415 Koha::CirculationRules->set_rules(
1417 categorycode => undef,
1418 branchcode => undef,
1421 norenewalbefore => undef,
1422 renewalsallowed => 0,
1427 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
1428 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1429 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1431 # Too many unseen renewals
1432 Koha::CirculationRules->set_rules(
1434 categorycode => undef,
1435 branchcode => undef,
1438 unseen_renewals_allowed => 2,
1439 renewalsallowed => 10,
1443 t::lib::Mocks::mock_preference('UnseenRenewals', 1);
1444 $issue_1->unseen_renewals(2)->store;
1446 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
1447 is( $renewokay, 0, 'Cannot renew, 0 unseen renewals allowed');
1448 is( $error, 'too_unseen', 'Cannot renew, returned code is too_unseen');
1449 Koha::CirculationRules->set_rules(
1451 categorycode => undef,
1452 branchcode => undef,
1455 norenewalbefore => undef,
1456 renewalsallowed => 0,
1460 t::lib::Mocks::mock_preference('UnseenRenewals', 0);
1462 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1463 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1464 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1466 C4::Overdues::UpdateFine(
1468 issue_id => $issue_1->id(),
1469 itemnumber => $item_1->itemnumber,
1470 borrowernumber => $renewing_borrower_obj->borrowernumber,
1473 due => Koha::DateUtils::output_pref($datedue)
1477 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower_obj->borrowernumber })->next();
1478 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1479 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1480 is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1481 is( $line->amount+0, 15, 'Account line amount is 15.00' );
1482 is( $line->issue_id, $issue_1->id, 'Account line issue id matches' );
1484 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1485 is( $offset->type, 'CREATE', 'Account offset type is CREATE' );
1486 is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1488 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1489 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1491 LostItem( $item_1->itemnumber, 'test', 1 );
1493 $line = Koha::Account::Lines->find($line->id);
1494 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1495 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1497 my $item = Koha::Items->find($item_1->itemnumber);
1498 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1499 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1500 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1502 my $total_due = $dbh->selectrow_array(
1503 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1504 undef, $renewing_borrower_obj->borrowernumber
1507 is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1509 C4::Context->dbh->do("DELETE FROM accountlines");
1511 C4::Overdues::UpdateFine(
1513 issue_id => $issue_2->id(),
1514 itemnumber => $item_2->itemnumber,
1515 borrowernumber => $renewing_borrower_obj->borrowernumber,
1518 due => Koha::DateUtils::output_pref($datedue)
1522 LostItem( $item_2->itemnumber, 'test', 0 );
1524 my $item2 = Koha::Items->find($item_2->itemnumber);
1525 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1526 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1528 $total_due = $dbh->selectrow_array(
1529 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1530 undef, $renewing_borrower_obj->borrowernumber
1533 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1535 my $future = dt_from_string();
1536 $future->add( days => 7 );
1537 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1538 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1540 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1541 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1542 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1543 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1544 LostItem( $item_3->itemnumber, 'test', 0 );
1545 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1546 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1548 $accountline->description,
1549 sprintf( "%s %s %s",
1550 $item_3->biblio->title || '',
1551 $item_3->barcode || '',
1552 $item_3->itemcallnumber || '' ),
1553 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1557 t::lib::Mocks::mock_preference('UseRecalls', 1);
1558 Koha::CirculationRules->set_rules({
1559 categorycode => undef,
1560 branchcode => undef,
1563 recalls_allowed => 10,
1564 renewalsallowed => 5,
1567 my $recall_borrower = $builder->build_object({ class => 'Koha::Patrons' });
1568 my $recall_biblio = $builder->build_sample_biblio();
1569 my $recall_item1 = $builder->build_sample_item({ biblionumber => $recall_biblio->biblionumber });
1570 my $recall_item2 = $builder->build_sample_item({ biblionumber => $recall_biblio->biblionumber });
1572 my $recall_issue = AddIssue( $renewing_borrower_obj, $recall_item1->barcode );
1574 # item-level and this item: renewal not allowed
1575 my $recall = Koha::Recall->new({
1576 biblio_id => $recall_item1->biblionumber,
1577 item_id => $recall_item1->itemnumber,
1578 patron_id => $recall_borrower->borrowernumber,
1579 pickup_library_id => $recall_borrower->branchcode,
1582 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1583 is( $error, 'recalled', 'Cannot renew item that has been recalled' );
1584 $recall->set_cancelled;
1586 # biblio-level requested recall: renewal not allowed
1587 $recall = Koha::Recall->new({
1588 biblio_id => $recall_item1->biblionumber,
1590 patron_id => $recall_borrower->borrowernumber,
1591 pickup_library_id => $recall_borrower->branchcode,
1594 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1595 is( $error, 'recalled', 'Cannot renew item if biblio is recalled and has no item allocated' );
1596 $recall->set_cancelled;
1598 # item-level and not this item: renewal allowed
1599 $recall = Koha::Recall->new({
1600 biblio_id => $recall_item2->biblionumber,
1601 item_id => $recall_item2->itemnumber,
1602 patron_id => $recall_borrower->borrowernumber,
1603 pickup_library_id => $recall_borrower->branchcode,
1606 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1607 is( $renewokay, 1, 'Can renew item if item-level recall on biblio is not on this item' );
1608 $recall->set_cancelled;
1610 # biblio-level waiting recall: renewal allowed
1611 $recall = Koha::Recall->new({
1612 biblio_id => $recall_item1->biblionumber,
1614 patron_id => $recall_borrower->borrowernumber,
1615 pickup_library_id => $recall_borrower->branchcode,
1618 $recall->set_waiting({ item => $recall_item1 });
1619 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1620 is( $renewokay, 1, 'Can renew item if biblio-level recall has already been allocated an item' );
1621 $recall->set_cancelled;
1624 subtest "GetUpcomingDueIssues" => sub {
1627 my $branch = $library2->{branchcode};
1629 #Create another record
1630 my $biblio2 = $builder->build_sample_biblio();
1633 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1634 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1635 my $item_3 = $builder->build_sample_item(
1637 biblionumber => $biblio2->biblionumber,
1645 my %a_borrower_data = (
1646 firstname => 'Fridolyn',
1647 surname => 'SOMERS',
1648 categorycode => $patron_category->{categorycode},
1649 branchcode => $branch,
1652 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1653 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber );
1655 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1656 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1657 my $today = DateTime->today(time_zone => C4::Context->tz());
1659 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1660 my $datedue = dt_from_string( $issue->date_due() );
1661 my $issue_2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1662 my $datedue2 = dt_from_string( $issue->date_due() );
1666 # GetUpcomingDueIssues tests
1668 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1669 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1672 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1673 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1674 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1677 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1678 is ( scalar( @$upcoming_dues ), 1,
1679 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1682 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1684 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1686 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1687 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1689 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1690 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1692 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1693 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1695 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1696 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1698 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1699 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1701 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1702 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1706 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1707 my $branch = $library2->{branchcode};
1709 my $biblio = $builder->build_sample_biblio();
1712 my $item = $builder->build_sample_item(
1714 biblionumber => $biblio->biblionumber,
1721 my %a_borrower_data = (
1722 firstname => 'Kyle',
1724 categorycode => $patron_category->{categorycode},
1725 branchcode => $branch,
1728 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1730 my $borrower = Koha::Patrons->find( $borrowernumber );
1731 my $issue = AddIssue( $borrower, $item->barcode );
1734 issue_id => $issue->id(),
1735 itemnumber => $item->itemnumber,
1736 borrowernumber => $borrowernumber,
1742 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1743 my $count = $hr->{count};
1745 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1748 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1750 my $biblio = $builder->build_sample_biblio();
1751 my $item_1 = $builder->build_sample_item(
1753 biblionumber => $biblio->biblionumber,
1754 library => $library2->{branchcode},
1757 my $item_2= $builder->build_sample_item(
1759 biblionumber => $biblio->biblionumber,
1760 library => $library2->{branchcode},
1761 itype => $item_1->effective_itemtype,
1765 Koha::CirculationRules->set_rules(
1767 categorycode => undef,
1768 itemtype => $item_1->effective_itemtype,
1769 branchcode => undef,
1771 reservesallowed => 25,
1772 holds_per_record => 25,
1774 lengthunit => 'days',
1775 renewalsallowed => 1,
1777 norenewalbefore => undef,
1787 my $borrower1 = Koha::Patron->new({
1788 firstname => 'Kyle',
1790 categorycode => $patron_category->{categorycode},
1791 branchcode => $library2->{branchcode},
1793 my $borrowernumber2 = Koha::Patron->new({
1794 firstname => 'Chelsea',
1796 categorycode => $patron_category->{categorycode},
1797 branchcode => $library2->{branchcode},
1798 })->store->borrowernumber;
1799 my $patron_category_2 = $builder->build(
1801 source => 'Category',
1803 category_type => 'P',
1805 BlockExpiredPatronOpacActions => -1, # Pick the pref value
1809 my $borrowernumber3 = Koha::Patron->new({
1810 firstname => 'Carnegie',
1812 categorycode => $patron_category_2->{categorycode},
1813 branchcode => $library2->{branchcode},
1814 })->store->borrowernumber;
1816 my $issue = AddIssue( $borrower1, $item_1->barcode );
1818 my ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1819 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1823 branchcode => $library2->{branchcode},
1824 borrowernumber => $borrowernumber2,
1825 biblionumber => $biblio->biblionumber,
1830 Koha::CirculationRules->set_rules(
1832 categorycode => undef,
1833 itemtype => $item_1->effective_itemtype,
1834 branchcode => undef,
1840 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1841 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1842 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1844 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1845 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1846 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1848 Koha::CirculationRules->set_rules(
1850 categorycode => undef,
1851 itemtype => $item_1->effective_itemtype,
1852 branchcode => undef,
1858 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1859 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1860 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1862 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1863 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1864 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1868 branchcode => $library2->{branchcode},
1869 borrowernumber => $borrowernumber3,
1870 biblionumber => $biblio->biblionumber,
1875 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1876 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' );
1878 my $item_3= $builder->build_sample_item(
1880 biblionumber => $biblio->biblionumber,
1881 library => $library2->{branchcode},
1882 itype => $item_1->effective_itemtype,
1886 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1887 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' );
1889 Koha::CirculationRules->set_rules(
1891 categorycode => $patron_category_2->{categorycode},
1892 itemtype => $item_1->effective_itemtype,
1893 branchcode => undef,
1895 reservesallowed => 0,
1900 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1901 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' );
1903 Koha::CirculationRules->set_rules(
1905 categorycode => $patron_category_2->{categorycode},
1906 itemtype => $item_1->effective_itemtype,
1907 branchcode => undef,
1909 reservesallowed => 25,
1914 # Setting item not checked out to be not for loan but holdable
1915 $item_2->notforloan(-1)->store;
1917 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1918 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' );
1920 my $mock_circ = Test::MockModule->new("C4::Circulation");
1921 $mock_circ->mock( CanItemBeReserved => sub {
1923 return { status => 'no' }
1926 $item_2->notforloan(0)->store;
1928 # Two items total, one item available, one issued, two holds on record
1931 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1932 } [], "CanItemBeReserved not called when there are more possible holds than available items";
1933 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1935 $item_3 = $builder->build_sample_item(
1937 biblionumber => $biblio->biblionumber,
1938 library => $library2->{branchcode},
1939 itype => $item_1->effective_itemtype,
1943 Koha::CirculationRules->set_rules(
1945 categorycode => undef,
1946 itemtype => $item_1->effective_itemtype,
1947 branchcode => undef,
1949 reservesallowed => 0,
1955 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1956 } ["Checked","Checked"], "CanItemBeReserved only called once per available item if it returns a negative result for all items for a borrower";
1957 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1962 # Don't allow renewing onsite checkout
1963 my $branch = $library->{branchcode};
1965 #Create another record
1966 my $biblio = $builder->build_sample_biblio();
1968 my $item = $builder->build_sample_item(
1970 biblionumber => $biblio->biblionumber,
1976 my $borrower = Koha::Patron->new({
1979 categorycode => $patron_category->{categorycode},
1980 branchcode => $branch,
1983 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1984 my ( $renewed, $error ) = CanBookBeRenewed( $borrower, $issue );
1985 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1986 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1990 my $library = $builder->build({ source => 'Branch' });
1992 my $biblio = $builder->build_sample_biblio();
1994 my $item = $builder->build_sample_item(
1996 biblionumber => $biblio->biblionumber,
1997 library => $library->{branchcode},
2001 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2003 my $issue = AddIssue( $patron, $item->barcode );
2006 issue_id => $issue->id,
2007 itemnumber => $item->itemnumber,
2008 borrowernumber => $patron->borrowernumber,
2015 issue_id => $issue->id,
2016 itemnumber => $item->itemnumber,
2017 borrowernumber => $patron->borrowernumber,
2022 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
2025 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
2028 my $homebranch = $builder->build( { source => 'Branch' } );
2029 my $holdingbranch = $builder->build( { source => 'Branch' } );
2030 my $otherbranch = $builder->build( { source => 'Branch' } );
2031 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2032 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2034 my $item = $builder->build_sample_item(
2036 homebranch => $homebranch->{branchcode},
2037 holdingbranch => $holdingbranch->{branchcode},
2040 Koha::CirculationRules->set_rules(
2042 categorycode => undef,
2043 itemtype => $item->effective_itemtype,
2044 branchcode => undef,
2046 reservesallowed => 25,
2048 lengthunit => 'days',
2049 renewalsallowed => 1,
2051 norenewalbefore => undef,
2060 set_userenv($holdingbranch);
2062 my $issue = AddIssue( $patron_1, $item->barcode );
2063 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
2065 my ( $error, $question, $alerts );
2067 # AllowReturnToBranch == anywhere
2068 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2069 ## Test that unknown barcodes don't generate internal server errors
2070 set_userenv($homebranch);
2071 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
2072 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
2073 ## Can be issued from homebranch
2074 set_userenv($homebranch);
2075 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2076 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2077 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2078 ## Can be issued from holdingbranch
2079 set_userenv($holdingbranch);
2080 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2081 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2082 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2083 ## Can be issued from another branch
2084 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2085 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2086 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2088 # AllowReturnToBranch == holdingbranch
2089 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2090 ## Cannot be issued from homebranch
2091 set_userenv($homebranch);
2092 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2093 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2094 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2095 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
2096 ## Can be issued from holdinbranch
2097 set_userenv($holdingbranch);
2098 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2099 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2100 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2101 ## Cannot be issued from another branch
2102 set_userenv($otherbranch);
2103 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2104 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2105 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2106 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
2108 # AllowReturnToBranch == homebranch
2109 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2110 ## Can be issued from holdinbranch
2111 set_userenv($homebranch);
2112 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2113 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2114 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2115 ## Cannot be issued from holdinbranch
2116 set_userenv($holdingbranch);
2117 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2118 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2119 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2120 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2121 ## Cannot be issued from holdinbranch
2122 set_userenv($otherbranch);
2123 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2124 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2125 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2126 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2128 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2131 subtest 'AddIssue & AllowReturnToBranch' => sub {
2134 my $homebranch = $builder->build( { source => 'Branch' } );
2135 my $holdingbranch = $builder->build( { source => 'Branch' } );
2136 my $otherbranch = $builder->build( { source => 'Branch' } );
2138 my $patron_1 = $builder->build_object({
2139 class => 'Koha::Patrons',
2140 value => { categorycode => $patron_category->{categorycode} }
2143 my $patron_2 = $builder->build_object({
2144 class => 'Koha::Patrons',
2145 value => { categorycode => $patron_category->{categorycode} }
2149 my $item = $builder->build_sample_item(
2151 homebranch => $homebranch->{branchcode},
2152 holdingbranch => $holdingbranch->{branchcode},
2156 set_userenv($holdingbranch);
2158 my $ref_issue = 'Koha::Checkout';
2159 my $issue = AddIssue( $patron_1, $item->barcode );
2161 my ( $error, $question, $alerts );
2163 # AllowReturnToBranch == homebranch
2164 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2165 ## Can be issued from homebranch
2166 set_userenv($homebranch);
2167 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
2168 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2169 ## Can be issued from holdinbranch
2170 set_userenv($holdingbranch);
2171 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
2172 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2173 ## Can be issued from another branch
2174 set_userenv($otherbranch);
2175 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
2176 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2178 # AllowReturnToBranch == holdinbranch
2179 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2180 ## Cannot be issued from homebranch
2181 set_userenv($homebranch);
2182 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
2183 ## Can be issued from holdingbranch
2184 set_userenv($holdingbranch);
2185 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
2186 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2187 ## Cannot be issued from another branch
2188 set_userenv($otherbranch);
2189 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
2191 # AllowReturnToBranch == homebranch
2192 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2193 ## Can be issued from homebranch
2194 set_userenv($homebranch);
2195 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
2196 AddIssue( $patron_1, $item->barcode ); # Re-issue to patron 1
2197 ## Cannot be issued from holdinbranch
2198 set_userenv($holdingbranch);
2199 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
2200 ## Cannot be issued from another branch
2201 set_userenv($otherbranch);
2202 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
2203 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2206 subtest 'AddIssue | recalls' => sub {
2209 t::lib::Mocks::mock_preference("UseRecalls", 1);
2210 t::lib::Mocks::mock_preference("item-level_itypes", 1);
2211 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2212 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2213 my $item = $builder->build_sample_item;
2214 Koha::CirculationRules->set_rules({
2215 branchcode => undef,
2217 categorycode => undef,
2219 recalls_allowed => 10,
2223 # checking out item that they have recalled
2224 my $recall1 = Koha::Recall->new(
2225 { patron_id => $patron1->borrowernumber,
2226 biblio_id => $item->biblionumber,
2227 item_id => $item->itemnumber,
2229 pickup_library_id => $patron1->branchcode,
2232 AddIssue( $patron1, $item->barcode, undef, undef, undef, undef, { recall_id => $recall1->id } );
2233 $recall1 = Koha::Recalls->find( $recall1->id );
2234 is( $recall1->fulfilled, 1, 'Recall was fulfilled when patron checked out item' );
2235 AddReturn( $item->barcode, $item->homebranch );
2237 # this item is has a recall request. cancel recall
2238 my $recall2 = Koha::Recall->new(
2239 { patron_id => $patron2->borrowernumber,
2240 biblio_id => $item->biblionumber,
2241 item_id => $item->itemnumber,
2243 pickup_library_id => $patron2->branchcode,
2246 AddIssue( $patron1, $item->barcode, undef, undef, undef, undef, { recall_id => $recall2->id, cancel_recall => 'cancel' } );
2247 $recall2 = Koha::Recalls->find( $recall2->id );
2248 is( $recall2->cancelled, 1, 'Recall was cancelled when patron checked out item' );
2249 AddReturn( $item->barcode, $item->homebranch );
2251 # this item is waiting to fulfill a recall. revert recall
2252 my $recall3 = Koha::Recall->new(
2253 { patron_id => $patron2->borrowernumber,
2254 biblio_id => $item->biblionumber,
2255 item_id => $item->itemnumber,
2257 pickup_library_id => $patron2->branchcode,
2260 $recall3->set_waiting;
2261 AddIssue( $patron1, $item->barcode, undef, undef, undef, undef, { recall_id => $recall3->id, cancel_recall => 'revert' } );
2262 $recall3 = Koha::Recalls->find( $recall3->id );
2263 is( $recall3->requested, 1, 'Recall was reverted from waiting when patron checked out item' );
2264 AddReturn( $item->barcode, $item->homebranch );
2267 subtest 'AddIssue & illrequests.due_date' => sub {
2270 t::lib::Mocks::mock_preference( 'ILLModule', 1 );
2271 my $library = $builder->build( { source => 'Branch' } );
2272 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2273 my $item = $builder->build_sample_item();
2275 set_userenv($library);
2277 my $custom_date_due = '9999-12-18 12:34:56';
2278 my $expected_date_due = '9999-12-18 23:59:00';
2279 my $illrequest = Koha::Illrequest->new({
2280 borrowernumber => $patron->borrowernumber,
2281 biblio_id => $item->biblionumber,
2282 branchcode => $library->{'branchcode'},
2283 due_date => $custom_date_due,
2286 my $issue = AddIssue( $patron, $item->barcode );
2287 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2289 $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2290 $item = $builder->build_sample_item();
2291 $custom_date_due = '9999-12-19';
2292 $expected_date_due = '9999-12-19 23:59:00';
2293 $illrequest = Koha::Illrequest->new({
2294 borrowernumber => $patron->borrowernumber,
2295 biblio_id => $item->biblionumber,
2296 branchcode => $library->{'branchcode'},
2297 due_date => $custom_date_due,
2300 $issue = AddIssue( $patron, $item->barcode );
2301 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2304 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
2307 my $library = $builder->build( { source => 'Branch' } );
2308 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2309 my $item_1 = $builder->build_sample_item(
2311 library => $library->{branchcode},
2314 my $item_2 = $builder->build_sample_item(
2316 library => $library->{branchcode},
2319 Koha::CirculationRules->set_rules(
2321 categorycode => undef,
2323 branchcode => $library->{branchcode},
2325 reservesallowed => 25,
2327 lengthunit => 'days',
2328 renewalsallowed => 1,
2330 norenewalbefore => undef,
2339 my ( $error, $question, $alerts );
2341 # Patron cannot issue item_1, they have overdues
2342 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
2343 my $issue = AddIssue( $patron, $item_1->barcode, $yesterday ); # Add an overdue
2345 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
2346 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2347 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
2348 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
2350 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
2351 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2352 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2353 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
2355 # Patron cannot issue item_1, they are debarred
2356 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
2357 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
2358 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2359 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2360 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
2362 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
2363 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2364 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2365 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
2368 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
2371 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2372 my $patron_category_x = $builder->build_object(
2374 class => 'Koha::Patron::Categories',
2375 value => { category_type => 'X' }
2378 my $patron = $builder->build_object(
2380 class => 'Koha::Patrons',
2382 categorycode => $patron_category_x->categorycode,
2383 gonenoaddress => undef,
2390 my $item_1 = $builder->build_sample_item(
2392 library => $library->{branchcode},
2396 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
2397 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
2399 my $stat = Koha::Statistics->search( { itemnumber => $item_1->itemnumber } )->next;
2400 is( $stat->branch, C4::Context->userenv->{'branch'}, 'Recorded a branch' );
2401 is( $stat->type, 'localuse', 'Recorded type as localuse' );
2402 is( $stat->itemnumber, $item_1->itemnumber, 'Recorded an itemnumber' );
2403 is( $stat->itemtype, $item_1->effective_itemtype, 'Recorded an itemtype' );
2404 is( $stat->borrowernumber, $patron->borrowernumber, 'Recorded a borrower number' );
2405 is( $stat->ccode, $item_1->ccode, 'Recorded a collection code' );
2406 is( $stat->categorycode, $patron->categorycode, 'Recorded a categorycode' );
2407 is( $stat->location, $item_1->location, 'Recorded a location' );
2409 # TODO There are other tests to provide here
2412 subtest 'MultipleReserves' => sub {
2415 my $biblio = $builder->build_sample_biblio();
2417 my $branch = $library2->{branchcode};
2419 my $item_1 = $builder->build_sample_item(
2421 biblionumber => $biblio->biblionumber,
2423 replacementprice => 12.00,
2428 my $item_2 = $builder->build_sample_item(
2430 biblionumber => $biblio->biblionumber,
2432 replacementprice => 12.00,
2439 my $resdate = undef;
2440 my $expdate = undef;
2442 my $checkitem = undef;
2445 my %renewing_borrower_data = (
2446 firstname => 'John',
2447 surname => 'Renewal',
2448 categorycode => $patron_category->{categorycode},
2449 branchcode => $branch,
2451 my $patron = Koha::Patron->new(\%renewing_borrower_data)->store;
2452 my $issue = AddIssue( $patron, $item_1->barcode);
2453 my $datedue = dt_from_string( $issue->date_due() );
2454 is (defined $issue->date_due(), 1, "item 1 checked out");
2455 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
2457 my %reserving_borrower_data1 = (
2458 firstname => 'Katrin',
2459 surname => 'Reservation',
2460 categorycode => $patron_category->{categorycode},
2461 branchcode => $branch,
2463 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
2466 branchcode => $branch,
2467 borrowernumber => $reserving_borrowernumber1,
2468 biblionumber => $biblio->biblionumber,
2469 priority => $priority,
2470 reservation_date => $resdate,
2471 expiration_date => $expdate,
2473 itemnumber => $checkitem,
2478 my %reserving_borrower_data2 = (
2479 firstname => 'Kirk',
2480 surname => 'Reservation',
2481 categorycode => $patron_category->{categorycode},
2482 branchcode => $branch,
2484 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
2487 branchcode => $branch,
2488 borrowernumber => $reserving_borrowernumber2,
2489 biblionumber => $biblio->biblionumber,
2490 priority => $priority,
2491 reservation_date => $resdate,
2492 expiration_date => $expdate,
2494 itemnumber => $checkitem,
2500 my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue, 1);
2501 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2504 my $item_3 = $builder->build_sample_item(
2506 biblionumber => $biblio->biblionumber,
2508 replacementprice => 12.00,
2514 my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue, 1);
2515 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2519 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2522 my $library = $builder->build( { source => 'Branch' } );
2523 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2525 my $biblionumber = $builder->build_sample_biblio(
2527 branchcode => $library->{branchcode},
2530 my $item_1 = $builder->build_sample_item(
2532 biblionumber => $biblionumber,
2533 library => $library->{branchcode},
2537 my $item_2 = $builder->build_sample_item(
2539 biblionumber => $biblionumber,
2540 library => $library->{branchcode},
2544 Koha::CirculationRules->set_rules(
2546 categorycode => undef,
2548 branchcode => $library->{branchcode},
2550 reservesallowed => 25,
2552 lengthunit => 'days',
2553 renewalsallowed => 1,
2555 norenewalbefore => undef,
2564 my ( $error, $question, $alerts );
2565 my $issue = AddIssue( $patron, $item_1->barcode, dt_from_string->add( days => 1 ) );
2567 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2568 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2570 { error => $error, alerts => $alerts },
2571 { error => {}, alerts => {} },
2572 'No error or alert should be raised'
2574 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2576 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2577 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2579 { error => $error, question => $question, alerts => $alerts },
2580 { error => {}, question => {}, alerts => {} },
2581 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2584 # Add a subscription
2585 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2587 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2588 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2590 { error => $error, question => $question, alerts => $alerts },
2591 { error => {}, question => {}, alerts => {} },
2592 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2595 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2596 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2598 { error => $error, question => $question, alerts => $alerts },
2599 { error => {}, question => {}, alerts => {} },
2600 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2604 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2607 my $library = $builder->build( { source => 'Branch' } );
2608 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2611 my $biblionumber = $builder->build_sample_biblio(
2613 branchcode => $library->{branchcode},
2616 my $item_1 = $builder->build_sample_item(
2618 biblionumber => $biblionumber,
2619 library => $library->{branchcode},
2622 my $item_2 = $builder->build_sample_item(
2624 biblionumber => $biblionumber,
2625 library => $library->{branchcode},
2629 # And the circulation rule
2630 Koha::CirculationRules->search->delete;
2631 Koha::CirculationRules->set_rules(
2633 categorycode => undef,
2635 branchcode => undef,
2638 firstremind => 1, # 1 day of grace
2639 finedays => 2, # 2 days of fine per day of overdue
2640 lengthunit => 'days',
2645 # Patron cannot issue item_1, they have overdues
2646 my $now = dt_from_string;
2647 my $five_days_ago = $now->clone->subtract( days => 5 );
2648 my $ten_days_ago = $now->clone->subtract( days => 10 );
2649 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2650 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2651 ; # Add another overdue
2653 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2654 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2655 my $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2656 is( $suspensions->count, 1, "Suspension added" );
2657 my $THE_suspension = $suspensions->next;
2659 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2660 # Same for the others
2661 my $expected_expiration = output_pref(
2663 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2664 dateformat => 'sql',
2668 is( $THE_suspension->expiration, $expected_expiration, "Suspesion expiration set" );
2670 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2671 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2672 is( $suspensions->count, 1, "Only one suspension" );
2673 $THE_suspension = $suspensions->next;
2675 $expected_expiration = output_pref(
2677 dt => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2678 dateformat => 'sql',
2682 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2684 Koha::Patron::Debarments::DelUniqueDebarment(
2685 { borrowernumber => $patron->borrowernumber, type => 'SUSPENSION' } );
2687 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2688 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2689 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2690 ; # Add another overdue
2691 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2692 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2693 is( $suspensions->count, 1, "Only one suspension" );
2694 $THE_suspension = $suspensions->next;
2696 $expected_expiration = output_pref(
2698 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2699 dateformat => 'sql',
2703 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2705 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2706 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2707 is( $suspensions->count, 1, "Only one suspension" );
2708 $THE_suspension = $suspensions->next;
2710 $expected_expiration = output_pref(
2712 dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2713 dateformat => 'sql',
2717 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2720 subtest 'AddReturn + suspension_chargeperiod' => sub {
2723 my $library = $builder->build( { source => 'Branch' } );
2724 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2726 my $biblionumber = $builder->build_sample_biblio(
2728 branchcode => $library->{branchcode},
2731 my $item_1 = $builder->build_sample_item(
2733 biblionumber => $biblionumber,
2734 library => $library->{branchcode},
2738 # And the issuing rule
2739 Koha::CirculationRules->search->delete;
2740 Koha::CirculationRules->set_rules(
2742 categorycode => '*',
2747 firstremind => 0, # 0 day of grace
2748 finedays => 2, # 2 days of fine per day of overdue
2749 suspension_chargeperiod => 1,
2750 lengthunit => 'days',
2755 my $now = dt_from_string;
2756 my $five_days_ago = $now->clone->subtract( days => 5 );
2757 # We want to charge 2 days every day, without grace
2758 # With 5 days of overdue: 5 * Z
2759 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2760 test_debarment_on_checkout(
2763 library => $library,
2765 due_date => $five_days_ago,
2766 expiration_date => $expected_expiration,
2770 # Same with undef firstremind
2771 Koha::CirculationRules->search->delete;
2772 Koha::CirculationRules->set_rules(
2774 categorycode => '*',
2779 firstremind => undef, # 0 day of grace
2780 finedays => 2, # 2 days of fine per day of overdue
2781 suspension_chargeperiod => 1,
2782 lengthunit => 'days',
2787 my $now = dt_from_string;
2788 my $five_days_ago = $now->clone->subtract( days => 5 );
2789 # We want to charge 2 days every day, without grace
2790 # With 5 days of overdue: 5 * Z
2791 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2792 test_debarment_on_checkout(
2795 library => $library,
2797 due_date => $five_days_ago,
2798 expiration_date => $expected_expiration,
2802 # We want to charge 2 days every 2 days, without grace
2803 # With 5 days of overdue: (5 * 2) / 2
2804 Koha::CirculationRules->set_rule(
2806 categorycode => undef,
2807 branchcode => undef,
2809 rule_name => 'suspension_chargeperiod',
2814 $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2815 test_debarment_on_checkout(
2818 library => $library,
2820 due_date => $five_days_ago,
2821 expiration_date => $expected_expiration,
2825 # We want to charge 2 days every 3 days, with 1 day of grace
2826 # With 5 days of overdue: ((5-1) / 3 ) * 2
2827 Koha::CirculationRules->set_rules(
2829 categorycode => undef,
2830 branchcode => undef,
2833 suspension_chargeperiod => 3,
2838 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2839 test_debarment_on_checkout(
2842 library => $library,
2844 due_date => $five_days_ago,
2845 expiration_date => $expected_expiration,
2849 # Use finesCalendar to know if holiday must be skipped to calculate the due date
2850 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2851 Koha::CirculationRules->set_rules(
2853 categorycode => undef,
2854 branchcode => undef,
2858 suspension_chargeperiod => 1,
2863 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2864 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2866 # Adding a holiday 2 days ago
2867 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2868 my $two_days_ago = $now->clone->subtract( days => 2 );
2869 $calendar->insert_single_holiday(
2870 day => $two_days_ago->day,
2871 month => $two_days_ago->month,
2872 year => $two_days_ago->year,
2873 title => 'holidayTest-2d',
2874 description => 'holidayDesc 2 days ago'
2876 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2877 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2878 test_debarment_on_checkout(
2881 library => $library,
2883 due_date => $five_days_ago,
2884 expiration_date => $expected_expiration,
2888 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2889 my $two_days_ahead = $now->clone->add( days => 2 );
2890 $calendar->insert_single_holiday(
2891 day => $two_days_ahead->day,
2892 month => $two_days_ahead->month,
2893 year => $two_days_ahead->year,
2894 title => 'holidayTest+2d',
2895 description => 'holidayDesc 2 days ahead'
2898 # Same as above, but we should skip D+2
2899 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2900 test_debarment_on_checkout(
2903 library => $library,
2905 due_date => $five_days_ago,
2906 expiration_date => $expected_expiration,
2910 # Adding another holiday, day of expiration date
2911 my $expected_expiration_dt = dt_from_string($expected_expiration);
2912 $calendar->insert_single_holiday(
2913 day => $expected_expiration_dt->day,
2914 month => $expected_expiration_dt->month,
2915 year => $expected_expiration_dt->year,
2916 title => 'holidayTest_exp',
2917 description => 'holidayDesc on expiration date'
2919 # Expiration date will be the day after
2920 test_debarment_on_checkout(
2923 library => $library,
2925 due_date => $five_days_ago,
2926 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2930 test_debarment_on_checkout(
2933 library => $library,
2935 return_date => $now->clone->add(days => 5),
2936 expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2940 test_debarment_on_checkout(
2943 library => $library,
2945 due_date => $now->clone->add(days => 1),
2946 return_date => $now->clone->add(days => 5),
2947 expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2951 Koha::CirculationRules->search->delete;
2952 Koha::CirculationRules->set_rules(
2954 categorycode => undef,
2956 branchcode => undef,
2959 lengthunit => 'days',
2964 Koha::Patron::Debarments::AddDebarment(
2966 borrowernumber => $patron->borrowernumber,
2967 expiration => '9999-12-31',
2972 AddIssue( $patron, $item_1->barcode, $now->clone->subtract( days => 1 ) );
2973 my ( undef, $message ) = AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2974 is( $message->{WasReturned} && exists $message->{ForeverDebarred}, 1, 'Forever debarred message for Addreturn when overdue');
2976 Koha::Patron::Debarments::DelUniqueDebarment(
2978 borrowernumber => $patron->borrowernumber,
2982 Koha::Patron::Debarments::AddDebarment(
2984 borrowernumber => $patron->borrowernumber,
2985 expiration => $now->clone->add( days => 10 ),
2990 AddIssue( $patron, $item_1->barcode, $now->clone->subtract( days => 1 ) );
2991 (undef, $message) = AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2992 is( $message->{WasReturned} && exists $message->{PrevDebarred}, 1, 'Previously debarred message for Addreturn when overdue');
2995 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2998 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2999 my $patron1 = $builder->build_object(
3001 class => 'Koha::Patrons',
3003 branchcode => $library->branchcode,
3004 categorycode => $patron_category->{categorycode}
3008 my $patron2 = $builder->build_object(
3010 class => 'Koha::Patrons',
3012 branchcode => $library->branchcode,
3013 categorycode => $patron_category->{categorycode}
3018 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
3020 my $item = $builder->build_sample_item(
3022 library => $library->branchcode,
3026 my ( $error, $question, $alerts );
3027 my $issue = AddIssue( $patron1, $item->barcode );
3029 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
3030 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
3031 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' );
3033 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
3034 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
3035 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' );
3037 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
3041 subtest 'AddReturn | is_overdue' => sub {
3044 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
3045 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
3046 t::lib::Mocks::mock_preference('finesMode', 'production');
3047 t::lib::Mocks::mock_preference('MaxFine', '100');
3049 my $library = $builder->build( { source => 'Branch' } );
3050 my $patron = $builder->build_object(
3052 class => 'Koha::Patrons',
3053 value => { categorycode => $patron_category->{categorycode} }
3056 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
3057 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3059 my $item = $builder->build_sample_item(
3061 library => $library->{branchcode},
3062 replacementprice => 7
3066 Koha::CirculationRules->search->delete;
3067 Koha::CirculationRules->set_rules(
3069 categorycode => undef,
3071 branchcode => undef,
3074 lengthunit => 'days',
3075 fine => 1, # Charge 1 every day of overdue
3081 my $now = dt_from_string;
3082 my $one_day_ago = $now->clone->subtract( days => 1 );
3083 my $two_days_ago = $now->clone->subtract( days => 2 );
3084 my $five_days_ago = $now->clone->subtract( days => 5 );
3085 my $ten_days_ago = $now->clone->subtract( days => 10 );
3087 # No return date specified, today will be used => 10 days overdue charged
3088 AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago
3089 AddReturn( $item->barcode, $library->{branchcode} );
3090 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
3091 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3093 # specify return date 5 days before => no overdue charged
3094 AddIssue( $patron, $item->barcode, $five_days_ago ); # date due was 5d ago
3095 AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
3096 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
3097 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3099 # specify return date 5 days later => 5 days overdue charged
3100 AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago
3101 AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
3102 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
3103 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3105 # specify return date 5 days later, specify exemptfine => no overdue charge
3106 AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago
3107 AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago );
3108 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
3109 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3111 subtest 'bug 22877 | Lost item return' => sub {
3115 my $issue = AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago
3117 # Fake fines cronjob on this checkout
3119 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3120 $ten_days_ago, $now );
3123 issue_id => $issue->issue_id,
3124 itemnumber => $item->itemnumber,
3125 borrowernumber => $patron->borrowernumber,
3127 due => output_pref($ten_days_ago)
3130 is( int( $patron->account->balance() ),
3131 10, "Overdue fine of 10 days overdue" );
3133 # Fake longoverdue with charge and not marking returned
3134 LostItem( $item->itemnumber, 'cronjob', 0 );
3135 is( int( $patron->account->balance() ),
3136 17, "Lost fine of 7 plus 10 days overdue" );
3138 # Now we return it today
3139 AddReturn( $item->barcode, $library->{branchcode} );
3140 is( int( $patron->account->balance() ),
3141 17, "Should have a single 10 days overdue fine and lost charge" );
3144 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3147 subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
3151 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3153 my $issue = AddIssue( $patron, $item->barcode, $one_day_ago ); # date due was 1d ago
3155 # Fake fines cronjob on this checkout
3157 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3158 $one_day_ago, $now );
3161 issue_id => $issue->issue_id,
3162 itemnumber => $item->itemnumber,
3163 borrowernumber => $patron->borrowernumber,
3165 due => output_pref($one_day_ago)
3168 is( int( $patron->account->balance() ),
3169 1, "Overdue fine of 1 day overdue" );
3171 # Backdated return (dropbox mode example - charge should be removed)
3172 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3173 is( int( $patron->account->balance() ),
3174 0, "Overdue fine should be annulled" );
3175 my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3176 is( $lines->count, 0, "Overdue fine accountline has been removed");
3178 $issue = AddIssue( $patron, $item->barcode, $two_days_ago ); # date due was 2d ago
3180 # Fake fines cronjob on this checkout
3182 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3183 $two_days_ago, $now );
3186 issue_id => $issue->issue_id,
3187 itemnumber => $item->itemnumber,
3188 borrowernumber => $patron->borrowernumber,
3190 due => output_pref($one_day_ago)
3193 is( int( $patron->account->balance() ),
3194 2, "Overdue fine of 2 days overdue" );
3196 # Payment made against fine
3197 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3198 my $debit = $lines->next;
3199 my $credit = $patron->account->add_credit(
3203 interface => 'test',
3206 $credit->apply( { debits => [$debit] } );
3208 is( int( $patron->account->balance() ),
3209 0, "Overdue fine should be paid off" );
3210 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3211 is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
3212 my $line = $lines->next;
3213 is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
3214 is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
3216 # Backdated return (dropbox mode example - charge should be removed)
3217 AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
3218 is( int( $patron->account->balance() ),
3219 -1, "Refund credit has been applied" );
3220 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
3221 is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
3223 $line = $lines->next;
3224 is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
3225 is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
3226 is($line->status,'RETURNED', "Overdue fine is fixed");
3227 $line = $lines->next;
3228 is($line->amount+0,-2, "Original payment amount remains as 2");
3229 is($line->amountoutstanding+0,0, "Original payment remains applied");
3230 $line = $lines->next;
3231 is($line->amount+0,-1, "Refund amount correctly set to 1");
3232 is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
3235 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3238 subtest 'bug 25417 | backdated return + exemptfine' => sub {
3242 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3244 my $issue = AddIssue( $patron, $item->barcode, $one_day_ago ); # date due was 1d ago
3246 # Fake fines cronjob on this checkout
3248 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3249 $one_day_ago, $now );
3252 issue_id => $issue->issue_id,
3253 itemnumber => $item->itemnumber,
3254 borrowernumber => $patron->borrowernumber,
3256 due => output_pref($one_day_ago)
3259 is( int( $patron->account->balance() ),
3260 1, "Overdue fine of 1 day overdue" );
3262 # Backdated return (dropbox mode example - charge should no longer exist)
3263 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3264 is( int( $patron->account->balance() ),
3265 0, "Overdue fine should be annulled" );
3268 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3271 subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
3274 t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
3276 my $due_date = dt_from_string;
3277 my $issue = AddIssue( $patron, $item->barcode, $due_date );
3282 issue_id => $issue->issue_id,
3283 itemnumber => $item->itemnumber,
3284 borrowernumber => $patron->borrowernumber,
3286 due => output_pref($due_date)
3289 is( $patron->account->balance(),
3290 0.25, 'Overdue fine of $0.25 recorded' );
3292 # Backdate return to exact due date and time
3293 my ( undef, $message ) =
3294 AddReturn( $item->barcode, $library->{branchcode},
3298 Koha::Account::Lines->find( { issue_id => $issue->id } );
3299 ok( !$accountline, 'accountline removed as expected' );
3302 $issue = AddIssue( $patron, $item->barcode, $due_date );
3307 issue_id => $issue->issue_id,
3308 itemnumber => $item->itemnumber,
3309 borrowernumber => $patron->borrowernumber,
3311 due => output_pref($due_date)
3314 is( $patron->account->balance(),
3315 0.25, 'Overdue fine of $0.25 recorded' );
3317 # Partial pay accruing fine
3318 my $lines = Koha::Account::Lines->search(
3320 borrowernumber => $patron->borrowernumber,
3321 issue_id => $issue->id
3324 my $debit = $lines->next;
3325 my $credit = $patron->account->add_credit(
3329 interface => 'test',
3332 $credit->apply( { debits => [$debit] } );
3334 is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
3336 # Backdate return to exact due date and time
3337 ( undef, $message ) =
3338 AddReturn( $item->barcode, $library->{branchcode},
3341 $lines = Koha::Account::Lines->search(
3343 borrowernumber => $patron->borrowernumber,
3344 issue_id => $issue->id
3347 $accountline = $lines->next;
3348 is( $accountline->amountoutstanding + 0,
3349 0, 'Partially paid fee amount outstanding was reduced to 0' );
3350 is( $accountline->amount + 0,
3351 0, 'Partially paid fee amount was reduced to 0' );
3352 is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
3355 Koha::Account::Lines->search(
3356 { borrowernumber => $patron->borrowernumber } )->delete;
3359 subtest 'enh 23091 | Lost item return policies' => sub {
3362 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3364 my $branchcode_false =
3365 $builder->build( { source => 'Branch' } )->{branchcode};
3366 my $specific_rule_false = $builder->build(
3368 source => 'CirculationRule',
3370 branchcode => $branchcode_false,
3371 categorycode => undef,
3373 rule_name => 'lostreturn',
3378 my $branchcode_refund =
3379 $builder->build( { source => 'Branch' } )->{branchcode};
3380 my $specific_rule_refund = $builder->build(
3382 source => 'CirculationRule',
3384 branchcode => $branchcode_refund,
3385 categorycode => undef,
3387 rule_name => 'lostreturn',
3388 rule_value => 'refund'
3392 my $branchcode_restore =
3393 $builder->build( { source => 'Branch' } )->{branchcode};
3394 my $specific_rule_restore = $builder->build(
3396 source => 'CirculationRule',
3398 branchcode => $branchcode_restore,
3399 categorycode => undef,
3401 rule_name => 'lostreturn',
3402 rule_value => 'restore'
3406 my $branchcode_charge =
3407 $builder->build( { source => 'Branch' } )->{branchcode};
3408 my $specific_rule_charge = $builder->build(
3410 source => 'CirculationRule',
3412 branchcode => $branchcode_charge,
3413 categorycode => undef,
3415 rule_name => 'lostreturn',
3416 rule_value => 'charge'
3421 my $branchcode_refund_unpaid =
3422 $builder->build( { source => 'Branch' } )->{branchcode};
3423 my $specific_rule_refund_unpaid = $builder->build(
3425 source => 'CirculationRule',
3427 branchcode => $branchcode_refund_unpaid,
3428 categorycode => undef,
3430 rule_name => 'lostreturn',
3431 rule_value => 'refund_unpaid'
3436 my $replacement_amount = 99.00;
3437 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
3438 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
3439 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
3440 t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 );
3441 t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
3443 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
3446 subtest 'lostreturn | refund_unpaid' => sub {
3449 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund_unpaid });
3451 my $item = $builder->build_sample_item(
3453 replacementprice => $replacement_amount
3458 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode );
3461 $item->itemlost(3)->store;
3462 C4::Circulation::LostItem( $item->itemnumber, 1 );
3464 my $lost_fee_lines = Koha::Account::Lines->search(
3466 borrowernumber => $patron->id,
3467 itemnumber => $item->itemnumber,
3468 debit_type_code => 'LOST'
3471 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3472 my $lost_fee_line = $lost_fee_lines->next;
3473 is( int($lost_fee_line->amount),
3474 $replacement_amount, 'The right LOST amount is generated' );
3475 is( int($lost_fee_line->amountoutstanding),
3476 $replacement_amount,
3477 'The right LOST amountoutstanding is generated' );
3478 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3481 int($patron->account->balance),
3482 $replacement_amount ,
3483 "Account balance equals the replacement amount after being charged lost fee when no payments has been made"
3486 # Return lost item without any payments having been made
3487 my ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3489 $lost_fee_line->discard_changes;
3491 is( int($lost_fee_line->amount), $replacement_amount, 'The LOST amount is left intact' );
3492 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero' );
3493 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set' );
3495 int($patron->account->balance),
3497 'Account balance should be zero after returning item with lost fee when no payments has been made'
3500 # Create a second item
3501 $item = $builder->build_sample_item(
3503 replacementprice => $replacement_amount
3508 $issue = C4::Circulation::AddIssue( $patron, $item->barcode );
3511 $item->itemlost(3)->store;
3512 C4::Circulation::LostItem( $item->itemnumber, 1 );
3514 $lost_fee_lines = Koha::Account::Lines->search(
3516 borrowernumber => $patron->id,
3517 itemnumber => $item->itemnumber,
3518 debit_type_code => 'LOST'
3521 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3522 $lost_fee_line = $lost_fee_lines->next;
3524 # Make partial payment
3525 $patron->account->payin_amount({
3527 interface => 'intranet',
3528 payment_type => 'CASH',
3529 user_id => $patron->borrowernumber,
3531 debits => [$lost_fee_line]
3534 $lost_fee_line->discard_changes;
3536 is( int($lost_fee_line->amountoutstanding),
3538 'The LOST amountoutstanding is the expected amount after partial payment of lost fee'
3542 int($patron->account->balance),
3544 'Account balance is the expected amount after partial payment of lost fee'
3547 # Return lost item with partial payment having been made
3548 ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3550 $lost_fee_line->discard_changes;
3552 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero after returning lost item with partial payment' );
3553 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set for lost item with partial payment' );
3555 int($patron->account->balance),
3557 'Account balance should be zero after returning item with lost fee when partial payment has been made'
3560 # Create a third item
3561 $item = $builder->build_sample_item(
3563 replacementprice => $replacement_amount
3568 $issue = C4::Circulation::AddIssue( $patron, $item->barcode );
3571 $item->itemlost(3)->store;
3572 C4::Circulation::LostItem( $item->itemnumber, 1 );
3574 $lost_fee_lines = Koha::Account::Lines->search(
3576 borrowernumber => $patron->id,
3577 itemnumber => $item->itemnumber,
3578 debit_type_code => 'LOST'
3581 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3582 $lost_fee_line = $lost_fee_lines->next;
3585 $patron->account->payin_amount({
3587 interface => 'intranet',
3588 payment_type => 'CASH',
3589 user_id => $patron->borrowernumber,
3590 amount => $replacement_amount,
3591 debits => [$lost_fee_line]
3594 $lost_fee_line->discard_changes;
3596 is( int($lost_fee_line->amountoutstanding),
3598 'The LOST amountoutstanding is the expected amount after partial payment of lost fee'
3602 int($patron->account->balance),
3604 'Account balance is the expected amount after partial payment of lost fee'
3607 # Return lost item with partial payment having been made
3608 ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3610 $lost_fee_line->discard_changes;
3612 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero after returning lost item with full payment' );
3613 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set for lost item with partial payment' );
3615 int($patron->account->balance),
3617 'Account balance should be zero after returning item with lost fee when full payment has been made'
3621 subtest 'lostreturn | false' => sub {
3624 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
3626 my $item = $builder->build_sample_item(
3628 replacementprice => $replacement_amount
3633 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, $ten_days_ago );
3635 # Fake fines cronjob on this checkout
3637 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3638 $ten_days_ago, $now );
3641 issue_id => $issue->issue_id,
3642 itemnumber => $item->itemnumber,
3643 borrowernumber => $patron->borrowernumber,
3645 due => output_pref($ten_days_ago)
3648 my $overdue_fees = Koha::Account::Lines->search(
3650 borrowernumber => $patron->id,
3651 itemnumber => $item->itemnumber,
3652 debit_type_code => 'OVERDUE'
3655 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3656 my $overdue_fee = $overdue_fees->next;
3657 is( $overdue_fee->amount + 0,
3658 10, 'The right OVERDUE amount is generated' );
3659 is( $overdue_fee->amountoutstanding + 0,
3661 'The right OVERDUE amountoutstanding is generated' );
3663 # Simulate item marked as lost
3664 $item->itemlost(3)->store;
3665 C4::Circulation::LostItem( $item->itemnumber, 1 );
3667 my $lost_fee_lines = Koha::Account::Lines->search(
3669 borrowernumber => $patron->id,
3670 itemnumber => $item->itemnumber,
3671 debit_type_code => 'LOST'
3674 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3675 my $lost_fee_line = $lost_fee_lines->next;
3676 is( $lost_fee_line->amount + 0,
3677 $replacement_amount, 'The right LOST amount is generated' );
3678 is( $lost_fee_line->amountoutstanding + 0,
3679 $replacement_amount,
3680 'The right LOST amountoutstanding is generated' );
3681 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3684 my ( $returned, $message ) =
3685 AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
3687 $overdue_fee->discard_changes;
3688 is( $overdue_fee->amount + 0,
3689 10, 'The OVERDUE amount is left intact' );
3690 is( $overdue_fee->amountoutstanding + 0,
3692 'The OVERDUE amountoutstanding is left intact' );
3694 $lost_fee_line->discard_changes;
3695 is( $lost_fee_line->amount + 0,
3696 $replacement_amount, 'The LOST amount is left intact' );
3697 is( $lost_fee_line->amountoutstanding + 0,
3698 $replacement_amount,
3699 'The LOST amountoutstanding is left intact' );
3700 # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
3701 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3704 subtest 'lostreturn | refund' => sub {
3707 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
3709 my $item = $builder->build_sample_item(
3711 replacementprice => $replacement_amount
3716 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, $ten_days_ago );
3718 # Fake fines cronjob on this checkout
3720 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3721 $ten_days_ago, $now );
3724 issue_id => $issue->issue_id,
3725 itemnumber => $item->itemnumber,
3726 borrowernumber => $patron->borrowernumber,
3728 due => output_pref($ten_days_ago)
3731 my $overdue_fees = Koha::Account::Lines->search(
3733 borrowernumber => $patron->id,
3734 itemnumber => $item->itemnumber,
3735 debit_type_code => 'OVERDUE'
3738 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3739 my $overdue_fee = $overdue_fees->next;
3740 is( $overdue_fee->amount + 0,
3741 10, 'The right OVERDUE amount is generated' );
3742 is( $overdue_fee->amountoutstanding + 0,
3744 'The right OVERDUE amountoutstanding is generated' );
3746 # Simulate item marked as lost
3747 $item->itemlost(3)->store;
3748 C4::Circulation::LostItem( $item->itemnumber, 1 );
3750 my $lost_fee_lines = Koha::Account::Lines->search(
3752 borrowernumber => $patron->id,
3753 itemnumber => $item->itemnumber,
3754 debit_type_code => 'LOST'
3757 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3758 my $lost_fee_line = $lost_fee_lines->next;
3759 is( $lost_fee_line->amount + 0,
3760 $replacement_amount, 'The right LOST amount is generated' );
3761 is( $lost_fee_line->amountoutstanding + 0,
3762 $replacement_amount,
3763 'The right LOST amountoutstanding is generated' );
3764 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3766 # Return the lost item
3767 my ( undef, $message ) =
3768 AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
3770 $overdue_fee->discard_changes;
3771 is( $overdue_fee->amount + 0,
3772 10, 'The OVERDUE amount is left intact' );
3773 is( $overdue_fee->amountoutstanding + 0,
3775 'The OVERDUE amountoutstanding is left intact' );
3777 $lost_fee_line->discard_changes;
3778 is( $lost_fee_line->amount + 0,
3779 $replacement_amount, 'The LOST amount is left intact' );
3780 is( $lost_fee_line->amountoutstanding + 0,
3782 'The LOST amountoutstanding is refunded' );
3783 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3786 subtest 'lostreturn | restore' => sub {
3789 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
3791 my $item = $builder->build_sample_item(
3793 replacementprice => $replacement_amount
3798 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode , $ten_days_ago);
3800 # Fake fines cronjob on this checkout
3802 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3803 $ten_days_ago, $now );
3806 issue_id => $issue->issue_id,
3807 itemnumber => $item->itemnumber,
3808 borrowernumber => $patron->borrowernumber,
3810 due => output_pref($ten_days_ago)
3813 my $overdue_fees = Koha::Account::Lines->search(
3815 borrowernumber => $patron->id,
3816 itemnumber => $item->itemnumber,
3817 debit_type_code => 'OVERDUE'
3820 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3821 my $overdue_fee = $overdue_fees->next;
3822 is( $overdue_fee->amount + 0,
3823 10, 'The right OVERDUE amount is generated' );
3824 is( $overdue_fee->amountoutstanding + 0,
3826 'The right OVERDUE amountoutstanding is generated' );
3828 # Simulate item marked as lost
3829 $item->itemlost(3)->store;
3830 C4::Circulation::LostItem( $item->itemnumber, 1 );
3832 my $lost_fee_lines = Koha::Account::Lines->search(
3834 borrowernumber => $patron->id,
3835 itemnumber => $item->itemnumber,
3836 debit_type_code => 'LOST'
3839 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3840 my $lost_fee_line = $lost_fee_lines->next;
3841 is( $lost_fee_line->amount + 0,
3842 $replacement_amount, 'The right LOST amount is generated' );
3843 is( $lost_fee_line->amountoutstanding + 0,
3844 $replacement_amount,
3845 'The right LOST amountoutstanding is generated' );
3846 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3848 # Simulate refunding overdue fees upon marking item as lost
3849 my $overdue_forgive = $patron->account->add_credit(
3852 user_id => $manager->borrowernumber,
3853 library_id => $branchcode_restore,
3854 interface => 'test',
3856 item_id => $item->itemnumber
3859 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3860 $overdue_fee->discard_changes;
3861 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3864 my ( undef, $message ) =
3865 AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
3867 $overdue_fee->discard_changes;
3868 is( $overdue_fee->amount + 0,
3869 10, 'The OVERDUE amount is left intact' );
3870 is( $overdue_fee->amountoutstanding + 0,
3872 'The OVERDUE amountoutstanding is restored' );
3874 $lost_fee_line->discard_changes;
3875 is( $lost_fee_line->amount + 0,
3876 $replacement_amount, 'The LOST amount is left intact' );
3877 is( $lost_fee_line->amountoutstanding + 0,
3879 'The LOST amountoutstanding is refunded' );
3880 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3883 subtest 'lostreturn | charge' => sub {
3886 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
3888 my $item = $builder->build_sample_item(
3890 replacementprice => $replacement_amount
3895 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, $ten_days_ago );
3897 # Fake fines cronjob on this checkout
3899 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3900 $ten_days_ago, $now );
3903 issue_id => $issue->issue_id,
3904 itemnumber => $item->itemnumber,
3905 borrowernumber => $patron->borrowernumber,
3907 due => output_pref($ten_days_ago)
3910 my $overdue_fees = Koha::Account::Lines->search(
3912 borrowernumber => $patron->id,
3913 itemnumber => $item->itemnumber,
3914 debit_type_code => 'OVERDUE'
3917 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3918 my $overdue_fee = $overdue_fees->next;
3919 is( $overdue_fee->amount + 0,
3920 10, 'The right OVERDUE amount is generated' );
3921 is( $overdue_fee->amountoutstanding + 0,
3923 'The right OVERDUE amountoutstanding is generated' );
3925 # Simulate item marked as lost
3926 $item->itemlost(3)->store;
3927 C4::Circulation::LostItem( $item->itemnumber, 1 );
3929 my $lost_fee_lines = Koha::Account::Lines->search(
3931 borrowernumber => $patron->id,
3932 itemnumber => $item->itemnumber,
3933 debit_type_code => 'LOST'
3936 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3937 my $lost_fee_line = $lost_fee_lines->next;
3938 is( $lost_fee_line->amount + 0,
3939 $replacement_amount, 'The right LOST amount is generated' );
3940 is( $lost_fee_line->amountoutstanding + 0,
3941 $replacement_amount,
3942 'The right LOST amountoutstanding is generated' );
3943 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3945 # Simulate refunding overdue fees upon marking item as lost
3946 my $overdue_forgive = $patron->account->add_credit(
3949 user_id => $manager->borrowernumber,
3950 library_id => $branchcode_charge,
3951 interface => 'test',
3953 item_id => $item->itemnumber
3956 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3957 $overdue_fee->discard_changes;
3958 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3961 my ( undef, $message ) =
3962 AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
3964 $lost_fee_line->discard_changes;
3965 is( $lost_fee_line->amount + 0,
3966 $replacement_amount, 'The LOST amount is left intact' );
3967 is( $lost_fee_line->amountoutstanding + 0,
3969 'The LOST amountoutstanding is refunded' );
3970 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3972 $overdue_fees = Koha::Account::Lines->search(
3974 borrowernumber => $patron->id,
3975 itemnumber => $item->itemnumber,
3976 debit_type_code => 'OVERDUE'
3979 order_by => { '-asc' => 'accountlines_id'}
3982 is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
3983 $overdue_fee = $overdue_fees->next;
3984 is( $overdue_fee->amount + 0,
3985 10, 'The original OVERDUE amount is left intact' );
3986 is( $overdue_fee->amountoutstanding + 0,
3988 'The original OVERDUE amountoutstanding is left as forgiven' );
3989 $overdue_fee = $overdue_fees->next;
3990 is( $overdue_fee->amount + 0,
3991 5, 'The new OVERDUE amount is correct for the backdated return' );
3992 is( $overdue_fee->amountoutstanding + 0,
3994 'The new OVERDUE amountoutstanding is correct for the backdated return' );
3999 subtest '_FixOverduesOnReturn' => sub {
4002 my $manager = $builder->build_object({ class => "Koha::Patrons" });
4003 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
4005 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
4007 my $branchcode = $library2->{branchcode};
4009 my $item = $builder->build_sample_item(
4011 biblionumber => $biblio->biblionumber,
4012 library => $branchcode,
4013 replacementprice => 99.00,
4018 my $patron = $builder->build( { source => 'Borrower' } );
4020 ## Start with basic call, should just close out the open fine
4021 my $accountline = Koha::Account::Line->new(
4023 borrowernumber => $patron->{borrowernumber},
4024 debit_type_code => 'OVERDUE',
4025 status => 'UNRETURNED',
4026 itemnumber => $item->itemnumber,
4028 amountoutstanding => 99.00,
4029 interface => 'test',
4033 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
4035 $accountline->_result()->discard_changes();
4037 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
4038 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
4039 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
4041 ## Run again, with exemptfine enabled
4044 debit_type_code => 'OVERDUE',
4045 status => 'UNRETURNED',
4046 amountoutstanding => 99.00,
4050 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
4052 $accountline->_result()->discard_changes();
4053 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'APPLY' })->next();
4055 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
4056 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
4057 is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
4058 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
4059 is( $offset->amount + 0, -99, "Amount of offset is correct" );
4060 my $credit = $offset->credit;
4061 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
4062 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
4063 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
4065 # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
4068 debit_type_code => 'OVERDUE',
4069 status => 'UNRETURNED',
4070 amountoutstanding => 0.00,
4075 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
4077 $accountline->_result()->discard_changes();
4078 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'CREATE' })->next();
4079 is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
4080 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
4081 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
4084 subtest 'Set waiting flag' => sub {
4087 my $library_1 = $builder->build( { source => 'Branch' } );
4088 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
4089 my $library_2 = $builder->build( { source => 'Branch' } );
4090 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
4092 my $item = $builder->build_sample_item(
4094 library => $library_1->{branchcode},
4098 set_userenv( $library_2 );
4099 my $reserve_id = AddReserve(
4101 branchcode => $library_2->{branchcode},
4102 borrowernumber => $patron_2->{borrowernumber},
4103 biblionumber => $item->biblionumber,
4105 itemnumber => $item->itemnumber,
4109 set_userenv( $library_1 );
4110 my $do_transfer = 1;
4111 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
4112 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
4113 my $hold = Koha::Holds->find( $reserve_id );
4114 is( $hold->found, 'T', 'Hold is in transit' );
4116 my ( $status ) = CheckReserves($item);
4117 is( $status, 'Transferred', 'Hold is not waiting yet');
4119 set_userenv( $library_2 );
4121 AddReturn( $item->barcode, $library_2->{branchcode} );
4122 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
4123 $hold = Koha::Holds->find( $reserve_id );
4124 is( $hold->found, 'W', 'Hold is waiting' );
4125 ( $status ) = CheckReserves($item);
4126 is( $status, 'Waiting', 'Now the hold is waiting');
4128 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
4129 set_userenv( $library_1 );
4130 (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
4131 $hold = Koha::Holds->find( $reserve_id );
4132 is( $hold->found, undef, 'Hold is no longer marked waiting' );
4133 is( $hold->priority, 1, "Hold is now priority one again");
4134 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
4135 is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
4136 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
4137 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
4138 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
4141 subtest 'Cancel transfers on lost items' => sub {
4144 my $library_to = $builder->build_object( { class => 'Koha::Libraries' } );
4145 my $item = $builder->build_sample_item();
4146 my $holdingbranch = $item->holdingbranch;
4147 # Historic transfer (datearrived is defined)
4148 my $old_transfer = $builder->build_object(
4150 class => 'Koha::Item::Transfers',
4152 itemnumber => $item->itemnumber,
4153 frombranch => $holdingbranch,
4154 tobranch => $library_to->branchcode,
4156 datesent => \'NOW()',
4157 datearrived => \'NOW()',
4158 datecancelled => undef,
4159 daterequested => \'NOW()'
4163 # Queued transfer (datesent is undefined)
4164 my $transfer_1 = $builder->build_object(
4166 class => 'Koha::Item::Transfers',
4168 itemnumber => $item->itemnumber,
4169 frombranch => $holdingbranch,
4170 tobranch => $library_to->branchcode,
4173 datearrived => undef,
4174 datecancelled => undef,
4175 daterequested => \'NOW()'
4179 # In transit transfer (datesent is defined, datearrived and datecancelled are both undefined)
4180 my $transfer_2 = $builder->build_object(
4182 class => 'Koha::Item::Transfers',
4184 itemnumber => $item->itemnumber,
4185 frombranch => $holdingbranch,
4186 tobranch => $library_to->branchcode,
4188 datesent => \'NOW()',
4189 datearrived => undef,
4190 datecancelled => undef,
4191 daterequested => \'NOW()'
4196 # Simulate item being marked as lost
4197 $item->itemlost(1)->store;
4198 LostItem( $item->itemnumber, 'test', 1 );
4200 $transfer_1->discard_changes;
4201 isnt($transfer_1->datecancelled, undef, "Queud transfer was cancelled upon item lost");
4202 is($transfer_1->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
4203 $transfer_2->discard_changes;
4204 isnt($transfer_2->datecancelled, undef, "Active transfer was cancelled upon item lost");
4205 is($transfer_2->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
4206 $old_transfer->discard_changes;
4207 is($old_transfer->datecancelled, undef, "Old transfers are unaffected");
4208 $item->discard_changes;
4209 is($item->holdingbranch, $holdingbranch, "Items holding branch remains unchanged");
4212 subtest 'CanBookBeIssued | is_overdue' => sub {
4215 # Set a simple circ policy
4216 Koha::CirculationRules->set_rules(
4218 categorycode => undef,
4219 branchcode => undef,
4223 reservesallowed => 25,
4225 lengthunit => 'days',
4226 renewalsallowed => 1,
4228 norenewalbefore => undef,
4236 my $now = dt_from_string()->truncate( to => 'day' );
4237 my $five_days_go = $now->clone->add( days => 5 );
4238 my $ten_days_go = $now->clone->add( days => 10);
4239 my $library = $builder->build( { source => 'Branch' } );
4240 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
4242 my $item = $builder->build_sample_item(
4244 library => $library->{branchcode},
4248 my $issue = AddIssue( $patron, $item->barcode, $five_days_go ); # date due was 10d ago
4249 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
4250 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), output_pref({ str => $five_days_go, dateonly => 1}), "First issue works");
4251 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron, $item->barcode, $ten_days_go, undef, undef, undef);
4252 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
4253 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
4256 subtest 'ItemsDeniedRenewal rules are checked' => sub {
4259 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
4260 Koha::CirculationRules->set_rules(
4262 categorycode => '*',
4264 branchcode => $idr_lib->branchcode,
4266 reservesallowed => 25,
4268 lengthunit => 'days',
4269 renewalsallowed => 10,
4271 norenewalbefore => undef,
4279 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
4280 homebranch => $idr_lib->branchcode,
4283 location => 'NOPROC'
4287 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
4288 branchcode => $idr_lib->branchcode,
4291 my $future = dt_from_string->add( days => 1 );
4292 my $issue = $builder->build_object(
4294 class => 'Koha::Checkouts',
4296 returndate => undef,
4297 renewals_count => 0,
4299 borrowernumber => $idr_borrower->borrowernumber,
4300 itemnumber => $allow_book->itemnumber,
4301 onsite_checkout => 0,
4302 date_due => $future,
4307 my $mock_item_class = Test::MockModule->new("Koha::Item");
4308 $mock_item_class->mock( 'is_denied_renewal', sub { return 1; } );
4310 my ( $mayrenew, $error ) = CanBookBeRenewed( $idr_borrower, $issue );
4311 is( $mayrenew, 0, 'Renewal blocked when $item->is_denied_renewal returns true' );
4312 is( $error, 'item_denied_renewal', 'Renewal blocked when $item->is_denied_renewal returns true' );
4314 $mock_item_class->unmock( 'is_denied_renewal' );
4315 $mock_item_class->mock( 'is_denied_renewal', sub { return 0; } );
4317 ( $mayrenew, $error ) = CanBookBeRenewed( $idr_borrower, $issue );
4318 is( $mayrenew, 1, 'Renewal allowed when $item->is_denied_renewal returns false' );
4319 is( $error, undef, 'Renewal allowed when $item->is_denied_renewal returns false' );
4321 $mock_item_class->unmock( 'is_denied_renewal' );
4324 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
4327 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4328 my $library = $builder->build( { source => 'Branch' } );
4329 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4331 my $item = $builder->build_sample_item(
4333 library => $library->{branchcode},
4337 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4338 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4339 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4342 subtest 'CanBookBeIssued | notforloan' => sub {
4345 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
4347 my $library = $builder->build( { source => 'Branch' } );
4348 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4350 my $itemtype = $builder->build(
4352 source => 'Itemtype',
4353 value => { notforloan => undef, }
4356 my $item = $builder->build_sample_item(
4358 library => $library->{branchcode},
4359 itype => $itemtype->{itemtype},
4362 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4364 my ( $issuingimpossible, $needsconfirmation );
4367 subtest 'item-level_itypes = 1' => sub {
4370 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
4371 # Is for loan at item type and item level
4372 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4373 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4374 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4376 # not for loan at item type level
4377 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4378 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4379 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4382 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4383 'Item can not be issued, not for loan at item type level'
4386 # not for loan at item level
4387 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4388 $item->notforloan( 1 )->store;
4389 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4390 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4393 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4394 'Item can not be issued, not for loan at item type level'
4398 subtest 'item-level_itypes = 0' => sub {
4401 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4403 # We set another itemtype for biblioitem
4404 my $itemtype = $builder->build(
4406 source => 'Itemtype',
4407 value => { notforloan => undef, }
4411 # for loan at item type and item level
4412 $item->notforloan(0)->store;
4413 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4414 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4415 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4416 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4418 # not for loan at item type level
4419 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4420 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4421 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4424 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4425 'Item can not be issued, not for loan at item type level'
4428 # not for loan at item level
4429 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4430 $item->notforloan( 1 )->store;
4431 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4432 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4435 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4436 'Item can not be issued, not for loan at item type level'
4440 # TODO test with AllowNotForLoanOverride = 1
4443 subtest 'CanBookBeIssued | recalls' => sub {
4446 t::lib::Mocks::mock_preference("UseRecalls", 1);
4447 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4448 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4449 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4450 my $item = $builder->build_sample_item;
4451 Koha::CirculationRules->set_rules({
4452 branchcode => undef,
4454 categorycode => undef,
4456 recalls_allowed => 10,
4461 my $recall = Koha::Recall->new(
4462 { patron_id => $patron1->borrowernumber,
4463 biblio_id => $item->biblionumber,
4464 item_id => $item->itemnumber,
4466 pickup_library_id => $patron1->branchcode,
4470 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4471 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed an item-level recall on this item" );
4473 $recall->set_cancelled;
4475 # biblio-level recall
4476 $recall = Koha::Recall->new(
4477 { patron_id => $patron1->borrowernumber,
4478 biblio_id => $item->biblionumber,
4481 pickup_library_id => $patron1->branchcode,
4485 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4486 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed a biblio-level recall and this item is eligible to fill it" );
4488 $recall->set_cancelled;
4490 # biblio-level recall
4491 $recall = Koha::Recall->new(
4492 { patron_id => $patron1->borrowernumber,
4493 biblio_id => $item->biblionumber,
4496 pickup_library_id => $patron1->branchcode,
4499 $recall->set_waiting( { item => $item, expirationdate => dt_from_string() } );
4501 my ( undef, undef, undef, $messages ) = CanBookBeIssued( $patron1, $item->barcode, undef, undef, undef, undef );
4502 is( $messages->{RECALLED}, $recall->id, "This book can be issued by this patron and they have placed a recall" );
4504 $recall->set_cancelled;
4507 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
4510 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
4511 my $item = $builder->build_sample_item(
4513 onloan => '2018-01-01',
4517 AddReturn( $item->barcode, $item->homebranch );
4518 $item->discard_changes; # refresh
4519 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
4522 subtest 'AddReturn | recalls' => sub {
4525 t::lib::Mocks::mock_preference("UseRecalls", 1);
4526 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4527 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4528 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4529 my $item1 = $builder->build_sample_item;
4530 Koha::CirculationRules->set_rules({
4531 branchcode => undef,
4533 categorycode => undef,
4535 recalls_allowed => 10,
4539 # this item can fill a recall with pickup at this branch
4540 AddIssue( $patron1, $item1->barcode );
4541 my $recall1 = Koha::Recall->new(
4542 { patron_id => $patron2->borrowernumber,
4543 biblio_id => $item1->biblionumber,
4544 item_id => $item1->itemnumber,
4546 pickup_library_id => $item1->homebranch,
4549 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4550 is( $messages->{RecallFound}->id, $recall1->id, "Recall found" );
4551 $recall1->set_cancelled;
4553 # this item can fill a recall but needs transfer
4554 AddIssue( $patron1, $item1->barcode );
4555 $recall1 = Koha::Recall->new(
4556 { patron_id => $patron2->borrowernumber,
4557 biblio_id => $item1->biblionumber,
4558 item_id => $item1->itemnumber,
4560 pickup_library_id => $patron2->branchcode,
4563 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4564 is( $messages->{RecallNeedsTransfer}, $item1->homebranch, "Recall requiring transfer found" );
4565 $recall1->set_cancelled;
4567 # this item is already in transit, do not ask to transfer
4568 AddIssue( $patron1, $item1->barcode );
4569 $recall1 = Koha::Recall->new(
4570 { patron_id => $patron2->borrowernumber,
4571 biblio_id => $item1->biblionumber,
4572 item_id => $item1->itemnumber,
4574 pickup_library_id => $patron2->branchcode,
4577 $recall1->start_transfer;
4578 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $patron2->branchcode );
4579 is( $messages->{TransferredRecall}->id, $recall1->id, "In transit recall found" );
4580 $recall1->set_cancelled;
4583 subtest 'AddReturn | bundles' => sub {
4586 my $schema = Koha::Database->schema;
4587 $schema->storage->txn_begin;
4589 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4590 my $host_item1 = $builder->build_sample_item;
4591 my $bundle_item1 = $builder->build_sample_item;
4592 $schema->resultset('ItemBundle')
4594 { host => $host_item1->itemnumber, item => $bundle_item1->itemnumber } );
4596 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $bundle_item1->barcode, $bundle_item1->homebranch );
4597 is($messages->{InBundle}->id, $host_item1->id, 'AddReturn returns InBundle host item when item is part of a bundle');
4599 $schema->storage->txn_rollback;
4602 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
4607 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4609 my $issuing_charges = 15;
4610 my $title = 'A title';
4611 my $author = 'Author, An';
4612 my $barcode = 'WHATARETHEODDS';
4614 my $circ = Test::MockModule->new('C4::Circulation');
4616 'GetIssuingCharges',
4618 return $issuing_charges;
4622 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4623 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
4624 my $patron = $builder->build_object({
4625 class => 'Koha::Patrons',
4626 value => { branchcode => $library->id }
4629 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
4630 my $item_id = Koha::Item->new(
4632 biblionumber => $biblio->biblionumber,
4633 homebranch => $library->id,
4634 holdingbranch => $library->id,
4635 barcode => $barcode,
4636 replacementprice => 23.00,
4637 itype => $itemtype->id
4639 )->store->itemnumber;
4640 my $item = Koha::Items->find( $item_id );
4642 my $context = Test::MockModule->new('C4::Context');
4643 $context->mock( userenv => { branch => $library->id } );
4645 # Check the item out
4646 AddIssue( $patron, $item->barcode );
4651 borrowernumber => $patron->borrowernumber,
4652 itemnumber => $item->itemnumber,
4653 branch => $library->id,
4654 lastreneweddate => { break => "the_renewal" }
4657 } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
4659 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
4660 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
4661 my %params_renewal = (
4662 timestamp => { -like => $date . "%" },
4663 module => "CIRCULATION",
4664 action => "RENEWAL",
4666 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
4669 borrowernumber => $patron->id,
4670 itemnumber => $item->id,
4671 branch => $library->id
4674 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4675 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
4677 my $checkouts = $patron->checkouts;
4678 # The following will fail if run on 00:00:00
4679 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
4681 my $lines = Koha::Account::Lines->search({
4682 borrowernumber => $patron->id,
4683 itemnumber => $item->id
4686 is( $lines->count, 2 );
4688 my $line = $lines->next;
4689 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
4690 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
4691 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
4693 $line = $lines->next;
4694 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
4695 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
4696 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
4698 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
4700 $context = Test::MockModule->new('C4::Context');
4701 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
4703 my $now = dt_from_string;
4704 $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
4705 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
4706 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
4707 $sth->execute($item->id, $library->id);
4708 my ($old_stats_size) = $sth->fetchrow_array;
4711 borrowernumber => $patron->id,
4712 itemnumber => $item->id,
4713 branch => $library->id
4716 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4717 $sth->execute($item->id, $library->id);
4718 my ($new_stats_size) = $sth->fetchrow_array;
4719 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
4720 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
4722 AddReturn( $item->id, $library->id, undef, $date );
4723 AddIssue( $patron, $item->barcode, $now );
4726 borrowernumber => $patron->id,
4727 itemnumber => $item->id,
4728 branch => $library->id,
4732 my $lines_skipped = Koha::Account::Lines->search({
4733 borrowernumber => $patron->id,
4734 itemnumber => $item->id
4736 is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
4740 subtest 'AddRenewal() adds to renewals' => sub {
4743 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4744 my $patron = $builder->build_object({
4745 class => 'Koha::Patrons',
4746 value => { branchcode => $library->id }
4749 my $item = $builder->build_sample_item();
4751 set_userenv( $library->unblessed );
4753 # Check the item out
4754 my $issue = AddIssue( $patron, $item->barcode );
4755 is(ref($issue), 'Koha::Checkout', 'Issue added');
4758 my $duedate = AddRenewal(
4760 borrowernumber => $patron->id,
4761 itemnumber => $item->id,
4762 branch => $library->id,
4767 ok( $duedate, "Renewal added" );
4769 my $renewals = Koha::Checkouts::Renewals->search({ checkout_id => $issue->issue_id });
4770 is($renewals->count, 1, 'One renewal added');
4771 my $THE_renewal = $renewals->next;
4772 is( $THE_renewal->renewer_id, C4::Context->userenv->{'number'}, 'Renewer recorded from context' );
4773 is( $THE_renewal->renewal_type, 'Automatic', 'AddRenewal "automatic" parameter sets renewal type to "Automatic"');
4776 subtest 'ProcessOfflinePayment() tests' => sub {
4783 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
4784 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4785 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
4787 is( $result, 'Success.', 'The right string is returned' );
4789 my $lines = $patron->account->lines;
4790 is( $lines->count, 1, 'line created correctly');
4792 my $line = $lines->next;
4793 is( $line->amount+0, $amount * -1, 'amount picked from params' );
4794 is( $line->branchcode, $library->id, 'branchcode set correctly' );
4798 subtest 'Incremented fee tests' => sub {
4801 my $dt = dt_from_string();
4802 Time::Fake->offset( $dt->epoch );
4804 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
4806 my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store;
4808 $module->mock( 'userenv', sub { { branch => $library->id } } );
4810 my $patron = $builder->build_object(
4812 class => 'Koha::Patrons',
4813 value => { categorycode => $patron_category->{categorycode} }
4817 my $itemtype = $builder->build_object(
4819 class => 'Koha::ItemTypes',
4821 notforloan => undef,
4823 rentalcharge_daily => 1,
4824 rentalcharge_daily_calendar => 0
4829 my $item = $builder->build_sample_item(
4831 library => $library->id,
4832 itype => $itemtype->id,
4836 is( $itemtype->rentalcharge_daily + 0,1, 'Daily rental charge stored and retreived correctly' );
4837 is( $item->effective_itemtype, $itemtype->id, "Itemtype set correctly for item" );
4839 my $now = dt_from_string;
4840 my $dt_from = $now->clone;
4841 my $dt_to = $now->clone->add( days => 7 );
4842 my $dt_to_renew = $now->clone->add( days => 13 );
4846 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4847 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4849 $accountline->amount + 0,
4851 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
4853 $accountline->delete();
4856 borrowernumber => $patron->id,
4857 itemnumber => $item->id,
4858 branch => $library->id,
4859 datedue => $dt_to_renew,
4860 lastreneweddate => $dt_to
4863 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4865 $accountline->amount + 0,
4867 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
4869 $accountline->delete();
4872 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
4873 $itemtype->rentalcharge_daily_calendar(1)->store();
4875 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4876 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4878 $accountline->amount + 0,
4880 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
4882 $accountline->delete();
4885 borrowernumber => $patron->id,
4886 itemnumber => $item->id,
4887 branch => $library->id,
4888 datedue => $dt_to_renew,
4889 lastreneweddate => $dt_to
4892 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4894 $accountline->amount + 0,
4896 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
4898 $accountline->delete();
4901 my $calendar = C4::Calendar->new( branchcode => $library->id );
4902 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
4904 ( $dt_from->day_of_week == 6 ) ? 0
4905 : ( $dt_from->day_of_week == 7 ) ? 1
4906 : $dt_from->day_of_week + 1;
4907 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
4908 $calendar->insert_week_day_holiday(
4909 weekday => $closed_day,
4910 title => 'Test holiday',
4911 description => 'Test holiday'
4914 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4915 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4917 $accountline->amount + 0,
4919 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
4921 $accountline->delete();
4924 borrowernumber => $patron->id,
4925 itemnumber => $item->id,
4926 branch => $library->id,
4927 datedue => $dt_to_renew,
4928 lastreneweddate => $dt_to
4931 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4933 $accountline->amount + 0,
4935 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
4937 $accountline->delete();
4940 $itemtype->rentalcharge(2)->store;
4941 is( $itemtype->rentalcharge + 0, 2, 'Rental charge updated and retreived correctly' );
4943 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4945 Koha::Account::Lines->search( { itemnumber => $item->id } );
4946 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly" );
4947 $accountlines->delete();
4950 borrowernumber => $patron->id,
4951 itemnumber => $item->id,
4952 branch => $library->id,
4953 datedue => $dt_to_renew,
4954 lastreneweddate => $dt_to
4957 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
4958 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly, for renewal" );
4959 $accountlines->delete();
4961 $itemtype->rentalcharge(0)->store;
4962 is( $itemtype->rentalcharge + 0, 0, 'Rental charge reset and retreived correctly' );
4965 Koha::CirculationRules->set_rule(
4967 categorycode => $patron->categorycode,
4968 itemtype => $itemtype->id,
4969 branchcode => $library->id,
4970 rule_name => 'lengthunit',
4971 rule_value => 'hours',
4975 $itemtype->rentalcharge_hourly('0.25')->store();
4976 is( $itemtype->rentalcharge_hourly, '0.25', 'Hourly rental charge stored and retreived correctly' );
4978 $dt_to = $now->clone->add( hours => 168 );
4979 $dt_to_renew = $now->clone->add( hours => 312 );
4981 $itemtype->rentalcharge_hourly_calendar(0)->store();
4983 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4984 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4986 $accountline->amount + 0,
4988 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)"
4990 $accountline->delete();
4993 borrowernumber => $patron->id,
4994 itemnumber => $item->id,
4995 branch => $library->id,
4996 datedue => $dt_to_renew,
4997 lastreneweddate => $dt_to
5000 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5002 $accountline->amount + 0,
5004 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)"
5006 $accountline->delete();
5009 $itemtype->rentalcharge_hourly_calendar(1)->store();
5011 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
5012 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5014 $accountline->amount + 0,
5016 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)"
5018 $accountline->delete();
5021 borrowernumber => $patron->id,
5022 itemnumber => $item->id,
5023 branch => $library->id,
5024 datedue => $dt_to_renew,
5025 lastreneweddate => $dt_to
5028 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5030 $accountline->amount + 0,
5032 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u"
5034 $accountline->delete();
5037 $calendar->delete_holiday( weekday => $closed_day );
5039 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
5040 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5042 $accountline->amount + 0,
5044 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u"
5046 $accountline->delete();
5049 borrowernumber => $patron->id,
5050 itemnumber => $item->id,
5051 branch => $library->id,
5052 datedue => $dt_to_renew,
5053 lastreneweddate => $dt_to
5056 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5058 $accountline->amount + 0,
5060 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)"
5062 $accountline->delete();
5067 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
5070 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
5071 t::lib::Mocks::mock_preference('item-level_itypes', 1);
5074 $builder->build_object( { class => 'Koha::Libraries' } )->store;
5075 my $patron = $builder->build_object(
5077 class => 'Koha::Patrons',
5078 value => { categorycode => $patron_category->{categorycode} }
5082 my $itemtype = $builder->build_object(
5084 class => 'Koha::ItemTypes',
5088 rentalcharge_daily => 0
5093 my $item = $builder->build_sample_item(
5095 library => $library->id,
5099 itype => $itemtype->id,
5103 my ( $issuingimpossible, $needsconfirmation );
5104 my $dt_from = dt_from_string();
5105 my $dt_due = $dt_from->clone->add( days => 3 );
5107 $itemtype->rentalcharge(1)->store;
5108 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
5109 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
5110 $itemtype->rentalcharge('0')->store;
5111 $itemtype->rentalcharge_daily(1)->store;
5112 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
5113 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
5114 $itemtype->rentalcharge_daily('0')->store;
5117 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
5120 t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
5122 my $patron = $builder->build_object(
5124 class => 'Koha::Patrons',
5125 value => { categorycode => $patron_category->{categorycode} }
5129 my $item = $builder->build_sample_item(
5131 materials => 'includes DVD',
5135 my $dt_due = dt_from_string->add( days => 3 );
5137 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
5138 is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
5141 subtest 'Do not return on renewal (LOST charge)' => sub {
5144 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
5145 my $library = $builder->build_object( { class => "Koha::Libraries" } );
5146 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
5147 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
5149 my $biblio = $builder->build_sample_biblio;
5151 my $item = $builder->build_sample_item(
5153 biblionumber => $biblio->biblionumber,
5154 library => $library->branchcode,
5155 replacementprice => 99.00,
5160 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
5161 AddIssue( $patron, $item->barcode );
5163 my $accountline = Koha::Account::Line->new(
5165 borrowernumber => $patron->borrowernumber,
5166 debit_type_code => 'LOST',
5168 itemnumber => $item->itemnumber,
5170 amountoutstanding => 12,
5171 interface => 'something',
5175 # AddRenewal doesn't call _FixAccountForLostAndFound
5176 AddIssue( $patron, $item->barcode );
5178 is( $patron->checkouts->count, 1,
5179 'Renewal should not return the item even if a LOST payment has been made earlier'
5183 subtest 'Filling a hold should cancel existing transfer' => sub {
5186 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
5188 my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
5189 my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
5190 my $patron = $builder->build_object(
5192 class => 'Koha::Patrons',
5194 categorycode => $patron_category->{categorycode},
5195 branchcode => $libraryA->branchcode,
5200 my $item = $builder->build_sample_item({
5201 homebranch => $libraryB->branchcode,
5204 my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
5205 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
5207 branchcode => $libraryA->branchcode,
5208 borrowernumber => $patron->borrowernumber,
5209 biblionumber => $item->biblionumber,
5210 itemnumber => $item->itemnumber
5212 my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
5213 is( $reserves->count, 1, "Reserve is placed");
5214 ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
5215 my $reserve = $reserves->next;
5216 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
5217 $reserve->discard_changes;
5218 ok( $reserve->found eq 'W', "Reserve is marked waiting" );
5219 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
5222 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
5226 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
5227 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5228 my $patron = $builder->build_object(
5230 class => 'Koha::Patrons',
5231 value => { categorycode => $patron_category->{categorycode} }
5235 my $biblionumber = $builder->build_sample_biblio(
5237 branchcode => $library->branchcode,
5241 # And the circulation rule
5242 Koha::CirculationRules->search->delete;
5243 Koha::CirculationRules->set_rules(
5245 categorycode => undef,
5247 branchcode => undef,
5250 lengthunit => 'days',
5256 source => 'CirculationRule',
5258 branchcode => undef,
5259 categorycode => undef,
5261 rule_name => 'lostreturn',
5262 rule_value => 'refund'
5267 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5270 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5271 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5273 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5275 my $item = $builder->build_sample_item(
5277 biblionumber => $biblionumber,
5278 library => $library->branchcode,
5279 replacementprice => '42',
5282 my $issue = AddIssue( $patron, $item->barcode );
5283 LostItem( $item->itemnumber, 'cli', 0 );
5284 $item->_result->itemlost(1);
5285 $item->_result->itemlost_on( $lost_on );
5286 $item->_result->update();
5288 my $a = Koha::Account::Lines->search(
5290 itemnumber => $item->id,
5291 borrowernumber => $patron->borrowernumber
5294 ok( $a, "Found accountline for lost fee" );
5295 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5296 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5297 $a = $a->get_from_storage;
5298 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5302 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5305 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5306 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5308 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5310 my $item = $builder->build_sample_item(
5312 biblionumber => $biblionumber,
5313 library => $library->branchcode,
5314 replacementprice => '42',
5317 my $issue = AddIssue( $patron, $item->barcode );
5318 LostItem( $item->itemnumber, 'cli', 0 );
5319 $item->_result->itemlost(1);
5320 $item->_result->itemlost_on( $lost_on );
5321 $item->_result->update();
5323 my $a = Koha::Account::Lines->search(
5325 itemnumber => $item->id,
5326 borrowernumber => $patron->borrowernumber
5329 ok( $a, "Found accountline for lost fee" );
5330 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5331 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5332 $a = $a->get_from_storage;
5333 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5337 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5340 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5341 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5343 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5345 my $item = $builder->build_sample_item(
5347 biblionumber => $biblionumber,
5348 library => $library->branchcode,
5349 replacementprice => '42',
5352 my $issue = AddIssue( $patron, $item->barcode );
5353 LostItem( $item->itemnumber, 'cli', 0 );
5354 $item->_result->itemlost(1);
5355 $item->_result->itemlost_on( $lost_on );
5356 $item->_result->update();
5358 my $a = Koha::Account::Lines->search(
5360 itemnumber => $item->id,
5361 borrowernumber => $patron->borrowernumber
5364 ok( $a, "Found accountline for lost fee" );
5365 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5366 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5367 $a = $a->get_from_storage;
5368 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5372 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5375 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5376 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5378 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5380 my $item = $builder->build_sample_item(
5382 biblionumber => $biblionumber,
5383 library => $library->branchcode,
5384 replacementprice => '42',
5387 my $issue = AddIssue( $patron, $item->barcode );
5388 LostItem( $item->itemnumber, 'cli', 0 );
5389 $item->_result->itemlost(1);
5390 $item->_result->itemlost_on( $lost_on );
5391 $item->_result->update();
5393 my $a = Koha::Account::Lines->search(
5395 itemnumber => $item->id,
5396 borrowernumber => $patron->borrowernumber
5400 ok( $a, "Found accountline for lost fee" );
5401 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5402 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5403 $a = $a->get_from_storage;
5404 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5409 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
5413 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
5414 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5415 my $patron = $builder->build_object(
5417 class => 'Koha::Patrons',
5418 value => { categorycode => $patron_category->{categorycode} }
5421 my $patron2 = $builder->build_object(
5423 class => 'Koha::Patrons',
5424 value => { categorycode => $patron_category->{categorycode} }
5428 my $biblionumber = $builder->build_sample_biblio(
5430 branchcode => $library->branchcode,
5434 # And the circulation rule
5435 Koha::CirculationRules->search->delete;
5436 Koha::CirculationRules->set_rules(
5438 categorycode => undef,
5440 branchcode => undef,
5443 lengthunit => 'days',
5449 source => 'CirculationRule',
5451 branchcode => undef,
5452 categorycode => undef,
5454 rule_name => 'lostreturn',
5455 rule_value => 'refund'
5460 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5463 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5464 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5466 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5468 my $item = $builder->build_sample_item(
5470 biblionumber => $biblionumber,
5471 library => $library->branchcode,
5472 replacementprice => '42',
5475 my $issue = AddIssue( $patron, $item->barcode );
5476 LostItem( $item->itemnumber, 'cli', 0 );
5477 $item->_result->itemlost(1);
5478 $item->_result->itemlost_on( $lost_on );
5479 $item->_result->update();
5481 my $a = Koha::Account::Lines->search(
5483 itemnumber => $item->id,
5484 borrowernumber => $patron->borrowernumber
5487 ok( $a, "Found accountline for lost fee" );
5488 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5489 $issue = AddIssue( $patron2, $item->barcode );
5490 $a = $a->get_from_storage;
5491 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5496 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5499 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5500 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5502 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5504 my $item = $builder->build_sample_item(
5506 biblionumber => $biblionumber,
5507 library => $library->branchcode,
5508 replacementprice => '42',
5511 my $issue = AddIssue( $patron, $item->barcode );
5512 LostItem( $item->itemnumber, 'cli', 0 );
5513 $item->_result->itemlost(1);
5514 $item->_result->itemlost_on( $lost_on );
5515 $item->_result->update();
5517 my $a = Koha::Account::Lines->search(
5519 itemnumber => $item->id,
5520 borrowernumber => $patron->borrowernumber
5523 ok( $a, "Found accountline for lost fee" );
5524 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5525 $issue = AddIssue( $patron2, $item->barcode );
5526 $a = $a->get_from_storage;
5527 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5531 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5534 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5535 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5537 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5539 my $item = $builder->build_sample_item(
5541 biblionumber => $biblionumber,
5542 library => $library->branchcode,
5543 replacementprice => '42',
5546 my $issue = AddIssue( $patron, $item->barcode );
5547 LostItem( $item->itemnumber, 'cli', 0 );
5548 $item->_result->itemlost(1);
5549 $item->_result->itemlost_on( $lost_on );
5550 $item->_result->update();
5552 my $a = Koha::Account::Lines->search(
5554 itemnumber => $item->id,
5555 borrowernumber => $patron->borrowernumber
5558 ok( $a, "Found accountline for lost fee" );
5559 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5560 $issue = AddIssue( $patron2, $item->barcode );
5561 $a = $a->get_from_storage;
5562 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5566 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5569 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5570 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5572 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5574 my $item = $builder->build_sample_item(
5576 biblionumber => $biblionumber,
5577 library => $library->branchcode,
5578 replacementprice => '42',
5581 my $issue = AddIssue( $patron, $item->barcode );
5582 LostItem( $item->itemnumber, 'cli', 0 );
5583 $item->_result->itemlost(1);
5584 $item->_result->itemlost_on( $lost_on );
5585 $item->_result->update();
5587 my $a = Koha::Account::Lines->search(
5589 itemnumber => $item->id,
5590 borrowernumber => $patron->borrowernumber
5594 ok( $a, "Found accountline for lost fee" );
5595 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5596 $issue = AddIssue( $patron2, $item->barcode );
5597 $a = $a->get_from_storage;
5598 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5603 subtest 'transferbook tests' => sub {
5607 { C4::Circulation::transferbook({}); }
5608 'Koha::Exceptions::MissingParameter',
5609 'Koha::Patron->store raises an exception on missing params';
5612 { C4::Circulation::transferbook({to_branch=>'anything'}); }
5613 'Koha::Exceptions::MissingParameter',
5614 'Koha::Patron->store raises an exception on missing params';
5617 { C4::Circulation::transferbook({from_branch=>'anything'}); }
5618 'Koha::Exceptions::MissingParameter',
5619 'Koha::Patron->store raises an exception on missing params';
5621 my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
5622 is( $doreturn, 0, "No return without barcode");
5623 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5624 is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
5626 ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
5627 is( $doreturn, 0, "No return without barcode");
5628 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5629 is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
5633 subtest 'Checkout should correctly terminate a transfer' => sub {
5636 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5637 my $patron_1 = $builder->build_object(
5639 class => 'Koha::Patrons',
5640 value => { branchcode => $library_1->branchcode }
5643 my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
5644 my $patron_2 = $builder->build_object(
5646 class => 'Koha::Patrons',
5647 value => { branchcode => $library_2->branchcode }
5651 my $item = $builder->build_sample_item(
5653 library => $library_1->branchcode,
5657 t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
5658 my $reserve_id = AddReserve(
5660 branchcode => $library_2->branchcode,
5661 borrowernumber => $patron_2->borrowernumber,
5662 biblionumber => $item->biblionumber,
5663 itemnumber => $item->itemnumber,
5668 my $do_transfer = 1;
5669 ModItemTransfer( $item->itemnumber, $library_1->branchcode,
5670 $library_2->branchcode, 'Manual' );
5671 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
5672 GetOtherReserves( $item->itemnumber )
5673 ; # To put the Reason, it's what does returns.pl...
5674 my $hold = Koha::Holds->find($reserve_id);
5675 is( $hold->found, 'T', 'Hold is in transit' );
5676 my $transfer = $item->get_transfer;
5677 is( $transfer->frombranch, $library_1->branchcode );
5678 is( $transfer->tobranch, $library_2->branchcode );
5679 is( $transfer->reason, 'Reserve' );
5681 t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
5682 AddIssue( $patron_1, $item->barcode );
5683 $transfer = $transfer->get_from_storage;
5684 isnt( $transfer->datearrived, undef );
5685 $hold = $hold->get_from_storage;
5686 is( $hold->found, undef, 'Hold is waiting' );
5687 is( $hold->priority, 1, );
5690 subtest 'AddIssue records staff who checked out item if appropriate' => sub {
5693 $module->mock( 'userenv', sub { { branch => $library->{id} } } );
5695 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5696 my $patron = $builder->build_object(
5698 class => 'Koha::Patrons',
5699 value => { categorycode => $patron_category->{categorycode} }
5702 my $issuer = $builder->build_object(
5704 class => 'Koha::Patrons',
5705 value => { categorycode => $patron_category->{categorycode} }
5708 my $item_1 = $builder->build_sample_item(
5710 library => $library->{branchcode}
5714 my $item_2 = $builder->build_sample_item(
5716 library => $library->branchcode
5720 $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->borrowernumber } } );
5722 my $dt_from = dt_from_string();
5723 my $dt_to = dt_from_string()->add( days => 7 );
5725 my $issue_1 = AddIssue( $patron, $item_1->barcode, $dt_to, undef, $dt_from );
5727 is( $issue_1->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
5729 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
5732 AddIssue( $patron, $item_2->barcode, $dt_to, undef, $dt_from );
5734 is( $issue_2->issuer->borrowernumber, $issuer->borrowernumber, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
5737 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
5740 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5741 my $patron_1 = $builder->build_object(
5743 class => 'Koha::Patrons',
5744 value => { branchcode => $library_1->branchcode }
5747 my $patron_2 = $builder->build_object(
5749 class => 'Koha::Patrons',
5750 value => { branchcode => $library_1->branchcode }
5754 my $item = $builder->build_sample_item(
5756 library => $library_1->branchcode,
5760 AddIssue( $patron_1, $item->barcode );
5761 ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
5762 AddIssue( $patron_2, $item->barcode );
5763 ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
5766 subtest "updateWrongTransfer tests" => sub {
5769 my $library1 = $builder->build_object( { class => 'Koha::Libraries' } );
5770 my $library2 = $builder->build_object( { class => 'Koha::Libraries' } );
5771 my $library3 = $builder->build_object( { class => 'Koha::Libraries' } );
5772 my $item = $builder->build_sample_item(
5774 homebranch => $library1->branchcode,
5775 holdingbranch => $library2->branchcode,
5776 datelastseen => undef
5780 my $transfer = $builder->build_object(
5782 class => 'Koha::Item::Transfers',
5784 itemnumber => $item->itemnumber,
5785 frombranch => $library2->branchcode,
5786 tobranch => $library1->branchcode,
5787 daterequested => dt_from_string,
5788 datesent => dt_from_string,
5789 datecancelled => undef,
5790 datearrived => undef,
5795 is( ref($transfer), 'Koha::Item::Transfer', 'Mock transfer added' );
5797 my $new_transfer = C4::Circulation::updateWrongTransfer($item->itemnumber, $library1->branchcode);
5798 is(ref($new_transfer), 'Koha::Item::Transfer', "updateWrongTransfer returns a 'Koha::Item::Transfer' object");
5799 ok( !$new_transfer->in_transit, "New transfer is NOT created as in transit (or cancelled)");
5801 my $original_transfer = $transfer->get_from_storage;
5802 ok( defined($original_transfer->datecancelled), "Original transfer was cancelled");
5803 is( $original_transfer->cancellation_reason, 'WrongTransfer', "Original transfer cancellation reason is 'WrongTransfer'");
5806 subtest "SendCirculationAlert" => sub {
5809 # When you would unsuspectingly call this unit test (with perl, not prove), you will be bitten by LOCK.
5810 # LOCK will commit changes and ruin your data
5811 # In order to prevent that, we will add KOHA_TESTING to $ENV; see further Circulation.pm
5812 $ENV{KOHA_TESTING} = 1;
5814 # Setup branch, borrowr, and notice
5815 my $library = $builder->build_object({ class => 'Koha::Libraries' });
5816 set_userenv( $library->unblessed);
5817 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5818 C4::Members::Messaging::SetMessagingPreference({
5819 borrowernumber => $patron->id,
5820 message_transport_types => ['sms'],
5821 message_attribute_id => 5
5823 my $item = $builder->build_sample_item();
5824 my $checkin_notice = $builder->build_object({
5825 class => 'Koha::Notice::Templates',
5827 module => 'circulation',
5829 branchcode => $library->branchcode,
5830 name => 'Test Checkin',
5832 content => "Checkins:\n----\n[% biblio.title %]-[% old_checkout.issue_id %]\n----Thank you.",
5833 message_transport_type => 'sms',
5838 # Checkout an item, mark it returned, generate a notice
5839 my $issue_1 = AddIssue( $patron, $item->barcode);
5840 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5841 C4::Circulation::SendCirculationAlert({
5843 item => $item->unblessed,
5844 borrower => $patron->unblessed,
5845 branch => $library->branchcode,
5848 my $notice = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'CHECKIN' });
5849 is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\nThank you.", 'Letter generated with expected output on first checkin' );
5850 is($notice->to_address, $patron->smsalertnumber, "Letter has the correct to_address set to smsalertnumber for SMS type notices");
5852 # Checkout an item, mark it returned, generate a notice
5853 my $issue_2 = AddIssue( $patron, $item->barcode);
5854 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5855 C4::Circulation::SendCirculationAlert({
5857 item => $item->unblessed,
5858 borrower => $patron->unblessed,
5859 branch => $library->branchcode,
5862 $notice->discard_changes();
5863 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' );
5867 subtest "GetSoonestRenewDate tests" => sub {
5869 Koha::CirculationRules->set_rule(
5871 categorycode => undef,
5872 branchcode => undef,
5874 rule_name => 'norenewalbefore',
5878 my $patron = $builder->build_object(
5880 class => 'Koha::Patrons',
5882 autorenew_checkouts => 1,
5886 my $item = $builder->build_sample_item();
5887 my $issue = AddIssue( $patron, $item->barcode);
5888 my $datedue = dt_from_string( $issue->date_due() );
5891 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
5892 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
5894 GetSoonestRenewDate( $patron, $issue ),
5895 $datedue->clone->add( days => -7 ),
5896 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5900 # Test 'date' setting for syspref NoRenewalBeforePrecision
5901 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5903 GetSoonestRenewDate( $patron, $issue ),
5904 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
5905 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5909 Koha::CirculationRules->set_rule(
5911 categorycode => undef,
5912 branchcode => undef,
5914 rule_name => 'norenewalbefore',
5915 rule_value => undef,
5920 GetSoonestRenewDate( $patron, $issue ),
5922 'Checkouts without auto-renewal can be renewed immediately if no norenewalbefore'
5925 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5926 $issue->auto_renew(1)->store;
5928 GetSoonestRenewDate( $patron, $issue, 1 ),
5929 $datedue->clone->truncate( to => 'day' ),
5930 'Checkouts with auto-renewal can be renewed earliest on due date if noautorenewalbefore'
5932 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact' );
5934 GetSoonestRenewDate( $patron, $issue, 1 ),
5936 'Checkouts with auto-renewal can be renewed earliest on due date if noautorenewalbefore'
5939 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5940 Koha::CirculationRules->set_rule(
5942 categorycode => undef,
5943 branchcode => undef,
5945 rule_name => 'norenewalbefore',
5949 $issue->date_due(dt_from_string)->store;
5951 GetSoonestRenewDate( $patron, $issue ),
5952 dt_from_string->subtract( days => 1 )->truncate( to => 'day' ),
5953 'Checkouts with auto-renewal can be renewed 1 day before due date if no renewalbefore = 1 and precision = "date"'
5958 subtest "CanBookBeIssued + needsconfirmation message" => sub {
5961 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
5962 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5963 my $biblio = $builder->build_object({ class => 'Koha::Biblios' });
5964 my $biblioitem = $builder->build_object({ class => 'Koha::Biblioitems', value => { biblionumber => $biblio->biblionumber }});
5965 my $item = $builder->build_object({ class => 'Koha::Items' , value => { itype => $itemtype, biblionumber => $biblio->biblionumber }});
5967 my $hold = $builder->build_object({ class => 'Koha::Holds', value => {
5968 biblionumber => $item->biblionumber,
5969 branchcode => $library->branchcode,
5970 itemnumber => undef,
5975 item_group_id => undef
5978 my ( $error, $needsconfirmation, $alerts, $messages );
5980 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5981 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold exists.");
5983 $hold->priority(0)->store();
5985 $hold->found("W")->store();
5986 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5987 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is waiting.");
5989 $hold->found("T")->store();
5990 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5991 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is being transferred.");
5993 $hold->found("P")->store();
5994 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5995 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is being processed.");
5998 subtest 'Tests for BlockReturnOfWithdrawnItems' => sub {
6002 t::lib::Mocks::mock_preference('BlockReturnOfWithdrawnItems', 1);
6003 t::lib::Mocks::mock_preference('RecordLocalUseOnReturn', 0);
6004 my $item = $builder->build_sample_item();
6005 $item->withdrawn(1)->itemlost(1)->store;
6006 my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef );
6009 [ 0, { NotIssued => $item->barcode, withdrawn => 1 }, undef, {} ], "Item returned as withdrawn, no other messages");
6012 subtest 'Tests for transfer not in transit' => sub {
6017 # These tests are to ensure a 'pending' transfer, generated by
6018 # stock rotation, will be advanced when checked in
6020 my $item = $builder->build_sample_item();
6021 my $transfer = $builder->build_object({ class => 'Koha::Item::Transfers', value => {
6022 itemnumber => $item->id,
6023 reason => 'StockrotationRepatriation',
6025 frombranch => $item->homebranch,
6027 my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef );
6030 [ 0, { WasTransfered => $transfer->tobranch, TransferTrigger => 'StockrotationRepatriation', NotIssued => $item->barcode }, undef, {} ], "Item is reported to have been transferred");
6032 $transfer->discard_changes;
6033 ok( $transfer->datesent, 'The datesent field is populated, i.e. transfer is initiated');
6037 subtest 'Tests for RecordLocalUseOnReturn' => sub {
6041 t::lib::Mocks::mock_preference('RecordLocalUseOnReturn', 0);
6042 my $item = $builder->build_sample_item();
6043 $item->withdrawn(1)->itemlost(1)->store;
6044 my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef );
6047 [ 0, { NotIssued => $item->barcode, withdrawn => 1 }, undef, {} ], "RecordLocalUSeOnReturn is off, no local use recorded");
6049 t::lib::Mocks::mock_preference('RecordLocalUseOnReturn', 1);
6050 my @return2 = AddReturn( $item->barcode, $item->homebranch, 0, undef );
6053 [ 0, { NotIssued => $item->barcode, withdrawn => 1, LocalUse => 1 }, undef, {} ], "Local use is recorded");
6056 $schema->storage->txn_rollback;
6057 C4::Context->clear_syspref_cache();
6058 $branches = Koha::Libraries->search();
6059 for my $branch ( $branches->next ) {
6060 my $key = $branch->branchcode . "_holidays";
6061 $cache->clear_from_cache($key);