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 =
849 AddIssue( $renewing_borrower_obj, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
851 ( $renewokay, $error, $info ) = 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)'
943 $info->{soonest_renew_date}, dt_from_string( $auto_renew_issue->date_due )->subtract( days => 7 ),
944 "Soonest renew date returned when error is 'auto_too_soon'"
947 ( $renewokay_cron, $error_cron, $info_cron ) =
948 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 );
950 $error_cron, 'auto_too_soon',
951 'Bug 25393: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
953 $renewing_borrower_obj->autorenew_checkouts(0)->store;
954 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
955 is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' );
956 is( $error, 'too_soon', 'Error is too_soon, no auto' );
957 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'");
958 $renewing_borrower_obj->autorenew_checkouts(1)->store;
960 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
961 # and test automatic renewal again
962 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
963 Koha::Cache::Memory::Lite->flush();
964 ( $renewokay, $error, $info ) =
965 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
966 is( $renewokay, 0, 'Bug 25393: Cannot manual renew, renewal is too soon' );
967 is( $error, 'too_soon',
968 'Bug 25393: Cannot manual renew, renewal is too soon, even though it\'s also scheduled for auto renewal'
970 is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
972 # Now we test for noautorenewalbefore if cron
973 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'noautorenewalbefore'});
974 Koha::Cache::Memory::Lite->flush();
975 ( $renewokay, $error, $info ) =
976 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 );
977 is( $renewokay, 0, 'Bug 25393: Cannot auto renew, renewal is too soon' );
978 is( $error, 'auto_too_soon',
979 'Bug 25393: Cannot auto renew, auto renewal is too soon'
981 is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
983 $renewing_borrower_obj->autorenew_checkouts(0)->store;
984 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
985 is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' );
986 is( $error, 'too_soon', 'Error is too_soon, no auto' );
987 is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
988 $renewing_borrower_obj->autorenew_checkouts(1)->store;
990 # Change policy so that loans can be renewed 99 days prior to the due date
991 # and test automatic renewal again
992 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
993 Koha::Cache::Memory::Lite->flush();
994 ( $renewokay, $error ) =
995 CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
996 is( $renewokay, 1, 'Bug 25393: Can do a manual renew, even if renewal is automatic and premature' );
997 is( $error, 'auto_renew',
998 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
1001 # Now we test for noautorenewalbefore if cron
1002 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'noautorenewalbefore'});
1003 Koha::Cache::Memory::Lite->flush();
1004 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 );
1005 is( $renewokay, 1, 'Bug 25393: Can auto renew' );
1006 is( $error, 'auto_renew', 'Bug 25393: Can auto renew' );
1007 is( $info->{soonest_renew_date}, undef, "soonest_renew_date is not returned because this issue can be renewed" );
1009 $renewing_borrower_obj->autorenew_checkouts(0)->store;
1010 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue );
1011 is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' );
1012 $renewing_borrower_obj->autorenew_checkouts(1)->store;
1014 subtest "too_late_renewal / no_auto_renewal_after" => sub {
1016 my $item_to_auto_renew = $builder->build_sample_item(
1018 biblionumber => $biblio->biblionumber,
1023 my $ten_days_before = dt_from_string->add( days => -10 );
1024 my $ten_days_ahead = dt_from_string->add( days => 10 );
1025 my $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1027 Koha::CirculationRules->set_rules(
1029 categorycode => undef,
1030 branchcode => undef,
1033 norenewalbefore => '7',
1034 no_auto_renewal_after => '9',
1038 ( $renewokay, $error ) =
1039 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1040 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1041 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1043 Koha::CirculationRules->set_rules(
1045 categorycode => undef,
1046 branchcode => undef,
1049 norenewalbefore => '7',
1050 no_auto_renewal_after => '10',
1054 ( $renewokay, $error ) =
1055 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1056 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1057 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
1059 Koha::CirculationRules->set_rules(
1061 categorycode => undef,
1062 branchcode => undef,
1065 norenewalbefore => '7',
1066 no_auto_renewal_after => '11',
1070 ( $renewokay, $error ) =
1071 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1072 is( $renewokay, 0, 'Do not renew, too_soon' );
1073 is( $error, 'too_soon', 'Cannot renew, too_soon - no_auto_renewal_after is defined(returned code is too_soon)' );
1075 # Now check for cron
1076 Koha::CirculationRules->set_rules(
1078 categorycode => undef,
1079 branchcode => undef,
1082 noautorenewalbefore => '9',
1083 no_auto_renewal_after => '11',
1087 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue, undef, 1 );
1088 is( $renewokay, 0, 'Do not renew, too_soon' );
1090 $error, 'auto_too_soon',
1091 'Cannot renew, too_soon - no_auto_renewal_after is defined(returned code is too_soon)'
1094 Koha::CirculationRules->set_rules(
1096 categorycode => undef,
1097 branchcode => undef,
1100 norenewalbefore => '10',
1101 no_auto_renewal_after => '11',
1105 ( $renewokay, $error ) =
1106 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1107 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1108 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1110 Koha::CirculationRules->set_rules(
1112 categorycode => undef,
1113 branchcode => undef,
1116 norenewalbefore => '10',
1117 no_auto_renewal_after => undef,
1118 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1122 ( $renewokay, $error ) =
1123 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1124 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1125 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1127 Koha::CirculationRules->set_rules(
1129 categorycode => undef,
1130 branchcode => undef,
1133 norenewalbefore => '7',
1134 no_auto_renewal_after => '15',
1135 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1139 ( $renewokay, $error ) =
1140 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1141 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1142 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1144 Koha::CirculationRules->set_rules(
1146 categorycode => undef,
1147 branchcode => undef,
1150 norenewalbefore => '10',
1151 no_auto_renewal_after => undef,
1152 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
1156 ( $renewokay, $error ) =
1157 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1158 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1159 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1162 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
1164 my $item_to_auto_renew = $builder->build_sample_item(
1166 biblionumber => $biblio->biblionumber,
1171 my $ten_days_before = dt_from_string->add( days => -10 );
1172 my $ten_days_ahead = dt_from_string->add( days => 10 );
1173 my $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1175 Koha::CirculationRules->set_rules(
1177 categorycode => undef,
1178 branchcode => undef,
1181 norenewalbefore => '10',
1182 no_auto_renewal_after => '11',
1186 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
1187 C4::Context->set_preference('OPACFineNoRenewals','10');
1188 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1189 my $fines_amount = 5;
1190 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
1191 $account->add_debit(
1193 amount => $fines_amount,
1194 interface => 'test',
1196 item_id => $item_to_auto_renew->itemnumber,
1197 description => "Some fines"
1199 )->status('RETURNED')->store;
1200 ( $renewokay, $error ) =
1201 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1202 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1203 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
1205 $account->add_debit(
1207 amount => $fines_amount,
1208 interface => 'test',
1210 item_id => $item_to_auto_renew->itemnumber,
1211 description => "Some fines"
1213 )->status('RETURNED')->store;
1214 ( $renewokay, $error ) =
1215 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1216 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1217 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
1219 $account->add_debit(
1221 amount => $fines_amount,
1222 interface => 'test',
1224 item_id => $item_to_auto_renew->itemnumber,
1225 description => "Some fines"
1227 )->status('RETURNED')->store;
1228 ( $renewokay, $error ) =
1229 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1230 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1231 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
1233 $account->add_credit(
1235 amount => $fines_amount,
1236 interface => 'test',
1238 description => "Some payment"
1241 ( $renewokay, $error ) =
1242 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1243 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1244 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1246 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
1247 ( $renewokay, $error ) =
1248 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1249 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1250 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1252 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
1253 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1256 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
1258 my $item_to_auto_renew = $builder->build_sample_item(
1260 biblionumber => $biblio->biblionumber,
1265 Koha::CirculationRules->set_rules(
1267 categorycode => undef,
1268 branchcode => undef,
1271 norenewalbefore => 10,
1272 no_auto_renewal_after => 11,
1277 my $ten_days_before = dt_from_string->add( days => -10 );
1278 my $ten_days_ahead = dt_from_string->add( days => 10 );
1280 # Patron is expired and BlockExpiredPatronOpacActions=0
1281 # => auto renew is allowed
1282 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
1283 my $issue = AddIssue( $expired_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1284 ( $renewokay, $error ) =
1285 CanBookBeRenewed( $expired_borrower_obj, $issue );
1286 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1287 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
1288 Koha::Checkouts->find( $issue->issue_id )->delete;
1291 # Patron is expired and BlockExpiredPatronOpacActions=1
1292 # => auto renew is not allowed
1293 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1294 $issue = AddIssue( $expired_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1295 ( $renewokay, $error ) =
1296 CanBookBeRenewed( $expired_borrower_obj, $issue );
1297 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1298 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
1301 # Patron is not expired and BlockExpiredPatronOpacActions=1
1302 # => auto renew is allowed
1303 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1304 $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1305 ( $renewokay, $error ) =
1306 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1307 is( $renewokay, 1, 'Renew, even if renewal is automatic' );
1308 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1312 subtest "GetLatestAutoRenewDate" => sub {
1314 my $item_to_auto_renew = $builder->build_sample_item(
1316 biblionumber => $biblio->biblionumber,
1321 my $ten_days_before = dt_from_string->add( days => -10 );
1322 my $ten_days_ahead = dt_from_string->add( days => 10 );
1323 my $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1324 Koha::CirculationRules->set_rules(
1326 categorycode => undef,
1327 branchcode => undef,
1330 norenewalbefore => '7',
1331 no_auto_renewal_after => '',
1332 no_auto_renewal_after_hard_limit => undef,
1336 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1337 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' );
1338 my $five_days_before = dt_from_string->add( days => -5 );
1339 Koha::CirculationRules->set_rules(
1341 categorycode => undef,
1342 branchcode => undef,
1345 norenewalbefore => '10',
1346 no_auto_renewal_after => '5',
1347 no_auto_renewal_after_hard_limit => undef,
1351 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj,, $issue );
1352 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1353 $five_days_before->truncate( to => 'minute' ),
1354 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1356 my $five_days_ahead = dt_from_string->add( days => 5 );
1357 $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1358 $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1359 $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1360 Koha::Cache::Memory::Lite->flush();
1361 Koha::CirculationRules->set_rules(
1363 categorycode => undef,
1364 branchcode => undef,
1367 norenewalbefore => '10',
1368 no_auto_renewal_after => '15',
1369 no_auto_renewal_after_hard_limit => undef,
1373 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1374 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1375 $five_days_ahead->truncate( to => 'minute' ),
1376 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1378 my $two_days_ahead = dt_from_string->add( days => 2 );
1379 Koha::CirculationRules->set_rules(
1381 categorycode => undef,
1382 branchcode => undef,
1385 norenewalbefore => '10',
1386 no_auto_renewal_after => '',
1387 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1391 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1392 is( $latest_auto_renew_date->truncate( to => 'day' ),
1393 $two_days_ahead->truncate( to => 'day' ),
1394 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1396 Koha::CirculationRules->set_rules(
1398 categorycode => undef,
1399 branchcode => undef,
1402 norenewalbefore => '10',
1403 no_auto_renewal_after => '15',
1404 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1408 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1409 is( $latest_auto_renew_date->truncate( to => 'day' ),
1410 $two_days_ahead->truncate( to => 'day' ),
1411 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1417 # set policy to forbid renewals
1418 Koha::CirculationRules->set_rules(
1420 categorycode => undef,
1421 branchcode => undef,
1424 norenewalbefore => undef,
1425 renewalsallowed => 0,
1430 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
1431 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1432 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1434 # Too many unseen renewals
1435 Koha::CirculationRules->set_rules(
1437 categorycode => undef,
1438 branchcode => undef,
1441 unseen_renewals_allowed => 2,
1442 renewalsallowed => 10,
1446 t::lib::Mocks::mock_preference('UnseenRenewals', 1);
1447 $issue_1->unseen_renewals(2)->store;
1449 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
1450 is( $renewokay, 0, 'Cannot renew, 0 unseen renewals allowed');
1451 is( $error, 'too_unseen', 'Cannot renew, returned code is too_unseen');
1452 Koha::CirculationRules->set_rules(
1454 categorycode => undef,
1455 branchcode => undef,
1458 norenewalbefore => undef,
1459 renewalsallowed => 0,
1463 t::lib::Mocks::mock_preference('UnseenRenewals', 0);
1465 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1466 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1467 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1469 C4::Overdues::UpdateFine(
1471 issue_id => $issue_1->id(),
1472 itemnumber => $item_1->itemnumber,
1473 borrowernumber => $renewing_borrower_obj->borrowernumber,
1476 due => Koha::DateUtils::output_pref($datedue)
1480 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower_obj->borrowernumber })->next();
1481 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1482 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1483 is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1484 is( $line->amount+0, 15, 'Account line amount is 15.00' );
1485 is( $line->issue_id, $issue_1->id, 'Account line issue id matches' );
1487 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1488 is( $offset->type, 'CREATE', 'Account offset type is CREATE' );
1489 is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1491 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1492 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1494 LostItem( $item_1->itemnumber, 'test', 1 );
1496 $line = Koha::Account::Lines->find($line->id);
1497 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1498 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1500 my $item = Koha::Items->find($item_1->itemnumber);
1501 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1502 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1503 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1505 my $total_due = $dbh->selectrow_array(
1506 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1507 undef, $renewing_borrower_obj->borrowernumber
1510 is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1512 C4::Context->dbh->do("DELETE FROM accountlines");
1514 C4::Overdues::UpdateFine(
1516 issue_id => $issue_2->id(),
1517 itemnumber => $item_2->itemnumber,
1518 borrowernumber => $renewing_borrower_obj->borrowernumber,
1521 due => Koha::DateUtils::output_pref($datedue)
1525 LostItem( $item_2->itemnumber, 'test', 0 );
1527 my $item2 = Koha::Items->find($item_2->itemnumber);
1528 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1529 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1531 $total_due = $dbh->selectrow_array(
1532 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1533 undef, $renewing_borrower_obj->borrowernumber
1536 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1538 my $future = dt_from_string();
1539 $future->add( days => 7 );
1540 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1541 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1543 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1544 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1545 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1546 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1547 LostItem( $item_3->itemnumber, 'test', 0 );
1548 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1549 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1551 $accountline->description,
1552 sprintf( "%s %s %s",
1553 $item_3->biblio->title || '',
1554 $item_3->barcode || '',
1555 $item_3->itemcallnumber || '' ),
1556 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1560 t::lib::Mocks::mock_preference('UseRecalls', 1);
1561 Koha::CirculationRules->set_rules({
1562 categorycode => undef,
1563 branchcode => undef,
1566 recalls_allowed => 10,
1567 renewalsallowed => 5,
1570 my $recall_borrower = $builder->build_object({ class => 'Koha::Patrons' });
1571 my $recall_biblio = $builder->build_sample_biblio();
1572 my $recall_item1 = $builder->build_sample_item({ biblionumber => $recall_biblio->biblionumber });
1573 my $recall_item2 = $builder->build_sample_item({ biblionumber => $recall_biblio->biblionumber });
1575 my $recall_issue = AddIssue( $renewing_borrower_obj, $recall_item1->barcode );
1577 # item-level and this item: renewal not allowed
1578 my $recall = Koha::Recall->new({
1579 biblio_id => $recall_item1->biblionumber,
1580 item_id => $recall_item1->itemnumber,
1581 patron_id => $recall_borrower->borrowernumber,
1582 pickup_library_id => $recall_borrower->branchcode,
1585 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1586 is( $error, 'recalled', 'Cannot renew item that has been recalled' );
1587 $recall->set_cancelled;
1589 # biblio-level requested recall: renewal not allowed
1590 $recall = Koha::Recall->new({
1591 biblio_id => $recall_item1->biblionumber,
1593 patron_id => $recall_borrower->borrowernumber,
1594 pickup_library_id => $recall_borrower->branchcode,
1597 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1598 is( $error, 'recalled', 'Cannot renew item if biblio is recalled and has no item allocated' );
1599 $recall->set_cancelled;
1601 # item-level and not this item: renewal allowed
1602 $recall = Koha::Recall->new({
1603 biblio_id => $recall_item2->biblionumber,
1604 item_id => $recall_item2->itemnumber,
1605 patron_id => $recall_borrower->borrowernumber,
1606 pickup_library_id => $recall_borrower->branchcode,
1609 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1610 is( $renewokay, 1, 'Can renew item if item-level recall on biblio is not on this item' );
1611 $recall->set_cancelled;
1613 # biblio-level waiting recall: renewal allowed
1614 $recall = Koha::Recall->new({
1615 biblio_id => $recall_item1->biblionumber,
1617 patron_id => $recall_borrower->borrowernumber,
1618 pickup_library_id => $recall_borrower->branchcode,
1621 $recall->set_waiting({ item => $recall_item1 });
1622 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1623 is( $renewokay, 1, 'Can renew item if biblio-level recall has already been allocated an item' );
1624 $recall->set_cancelled;
1627 subtest "GetUpcomingDueIssues" => sub {
1630 my $branch = $library2->{branchcode};
1632 #Create another record
1633 my $biblio2 = $builder->build_sample_biblio();
1636 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1637 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1638 my $item_3 = $builder->build_sample_item(
1640 biblionumber => $biblio2->biblionumber,
1648 my %a_borrower_data = (
1649 firstname => 'Fridolyn',
1650 surname => 'SOMERS',
1651 categorycode => $patron_category->{categorycode},
1652 branchcode => $branch,
1655 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1656 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber );
1658 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1659 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1660 my $today = DateTime->today(time_zone => C4::Context->tz());
1662 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1663 my $datedue = dt_from_string( $issue->date_due() );
1664 my $issue_2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1665 my $datedue2 = dt_from_string( $issue->date_due() );
1669 # GetUpcomingDueIssues tests
1671 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1672 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1675 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1676 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1677 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1680 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1681 is ( scalar( @$upcoming_dues ), 1,
1682 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1685 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1687 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1689 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1690 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1692 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1693 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1695 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1696 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1698 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1699 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1701 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1702 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1704 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1705 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1709 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1710 my $branch = $library2->{branchcode};
1712 my $biblio = $builder->build_sample_biblio();
1715 my $item = $builder->build_sample_item(
1717 biblionumber => $biblio->biblionumber,
1724 my %a_borrower_data = (
1725 firstname => 'Kyle',
1727 categorycode => $patron_category->{categorycode},
1728 branchcode => $branch,
1731 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1733 my $borrower = Koha::Patrons->find( $borrowernumber );
1734 my $issue = AddIssue( $borrower, $item->barcode );
1737 issue_id => $issue->id(),
1738 itemnumber => $item->itemnumber,
1739 borrowernumber => $borrowernumber,
1745 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1746 my $count = $hr->{count};
1748 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1751 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1753 my $biblio = $builder->build_sample_biblio();
1754 my $item_1 = $builder->build_sample_item(
1756 biblionumber => $biblio->biblionumber,
1757 library => $library2->{branchcode},
1760 my $item_2= $builder->build_sample_item(
1762 biblionumber => $biblio->biblionumber,
1763 library => $library2->{branchcode},
1764 itype => $item_1->effective_itemtype,
1768 Koha::CirculationRules->set_rules(
1770 categorycode => undef,
1771 itemtype => $item_1->effective_itemtype,
1772 branchcode => undef,
1774 reservesallowed => 25,
1775 holds_per_record => 25,
1777 lengthunit => 'days',
1778 renewalsallowed => 1,
1780 norenewalbefore => undef,
1790 my $borrower1 = Koha::Patron->new({
1791 firstname => 'Kyle',
1793 categorycode => $patron_category->{categorycode},
1794 branchcode => $library2->{branchcode},
1796 my $borrowernumber2 = Koha::Patron->new({
1797 firstname => 'Chelsea',
1799 categorycode => $patron_category->{categorycode},
1800 branchcode => $library2->{branchcode},
1801 })->store->borrowernumber;
1802 my $patron_category_2 = $builder->build(
1804 source => 'Category',
1806 category_type => 'P',
1808 BlockExpiredPatronOpacActions => -1, # Pick the pref value
1812 my $borrowernumber3 = Koha::Patron->new({
1813 firstname => 'Carnegie',
1815 categorycode => $patron_category_2->{categorycode},
1816 branchcode => $library2->{branchcode},
1817 })->store->borrowernumber;
1819 my $issue = AddIssue( $borrower1, $item_1->barcode );
1821 my ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1822 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1826 branchcode => $library2->{branchcode},
1827 borrowernumber => $borrowernumber2,
1828 biblionumber => $biblio->biblionumber,
1833 Koha::CirculationRules->set_rules(
1835 categorycode => undef,
1836 itemtype => $item_1->effective_itemtype,
1837 branchcode => undef,
1843 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1844 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1845 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1847 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1848 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1849 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1851 Koha::CirculationRules->set_rules(
1853 categorycode => undef,
1854 itemtype => $item_1->effective_itemtype,
1855 branchcode => undef,
1861 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1862 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1863 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1865 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1866 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1867 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1871 branchcode => $library2->{branchcode},
1872 borrowernumber => $borrowernumber3,
1873 biblionumber => $biblio->biblionumber,
1878 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1879 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' );
1881 my $item_3= $builder->build_sample_item(
1883 biblionumber => $biblio->biblionumber,
1884 library => $library2->{branchcode},
1885 itype => $item_1->effective_itemtype,
1889 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1890 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' );
1892 Koha::CirculationRules->set_rules(
1894 categorycode => $patron_category_2->{categorycode},
1895 itemtype => $item_1->effective_itemtype,
1896 branchcode => undef,
1898 reservesallowed => 0,
1903 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1904 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' );
1906 Koha::CirculationRules->set_rules(
1908 categorycode => $patron_category_2->{categorycode},
1909 itemtype => $item_1->effective_itemtype,
1910 branchcode => undef,
1912 reservesallowed => 25,
1917 # Setting item not checked out to be not for loan but holdable
1918 $item_2->notforloan(-1)->store;
1920 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1921 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' );
1923 my $mock_circ = Test::MockModule->new("C4::Circulation");
1924 $mock_circ->mock( CanItemBeReserved => sub {
1926 return { status => 'no' }
1929 $item_2->notforloan(0)->store;
1931 # Two items total, one item available, one issued, two holds on record
1934 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1935 } [], "CanItemBeReserved not called when there are more possible holds than available items";
1936 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1938 $item_3 = $builder->build_sample_item(
1940 biblionumber => $biblio->biblionumber,
1941 library => $library2->{branchcode},
1942 itype => $item_1->effective_itemtype,
1946 Koha::CirculationRules->set_rules(
1948 categorycode => undef,
1949 itemtype => $item_1->effective_itemtype,
1950 branchcode => undef,
1952 reservesallowed => 0,
1958 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1959 } ["Checked","Checked"], "CanItemBeReserved only called once per available item if it returns a negative result for all items for a borrower";
1960 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1965 # Don't allow renewing onsite checkout
1966 my $branch = $library->{branchcode};
1968 #Create another record
1969 my $biblio = $builder->build_sample_biblio();
1971 my $item = $builder->build_sample_item(
1973 biblionumber => $biblio->biblionumber,
1979 my $borrower = Koha::Patron->new({
1982 categorycode => $patron_category->{categorycode},
1983 branchcode => $branch,
1986 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1987 my ( $renewed, $error ) = CanBookBeRenewed( $borrower, $issue );
1988 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1989 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1993 my $library = $builder->build({ source => 'Branch' });
1995 my $biblio = $builder->build_sample_biblio();
1997 my $item = $builder->build_sample_item(
1999 biblionumber => $biblio->biblionumber,
2000 library => $library->{branchcode},
2004 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2006 my $issue = AddIssue( $patron, $item->barcode );
2009 issue_id => $issue->id,
2010 itemnumber => $item->itemnumber,
2011 borrowernumber => $patron->borrowernumber,
2018 issue_id => $issue->id,
2019 itemnumber => $item->itemnumber,
2020 borrowernumber => $patron->borrowernumber,
2025 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
2028 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
2031 my $homebranch = $builder->build( { source => 'Branch' } );
2032 my $holdingbranch = $builder->build( { source => 'Branch' } );
2033 my $otherbranch = $builder->build( { source => 'Branch' } );
2034 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2035 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2037 my $item = $builder->build_sample_item(
2039 homebranch => $homebranch->{branchcode},
2040 holdingbranch => $holdingbranch->{branchcode},
2043 Koha::CirculationRules->set_rules(
2045 categorycode => undef,
2046 itemtype => $item->effective_itemtype,
2047 branchcode => undef,
2049 reservesallowed => 25,
2051 lengthunit => 'days',
2052 renewalsallowed => 1,
2054 norenewalbefore => undef,
2063 set_userenv($holdingbranch);
2065 my $issue = AddIssue( $patron_1, $item->barcode );
2066 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
2068 my ( $error, $question, $alerts );
2070 # AllowReturnToBranch == anywhere
2071 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2072 ## Test that unknown barcodes don't generate internal server errors
2073 set_userenv($homebranch);
2074 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
2075 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
2076 ## Can be issued from homebranch
2077 set_userenv($homebranch);
2078 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2079 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2080 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2081 ## Can be issued from holdingbranch
2082 set_userenv($holdingbranch);
2083 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2084 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2085 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2086 ## Can be issued from another branch
2087 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2088 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2089 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2091 # AllowReturnToBranch == holdingbranch
2092 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2093 ## Cannot be issued from homebranch
2094 set_userenv($homebranch);
2095 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2096 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2097 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2098 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
2099 ## Can be issued from holdinbranch
2100 set_userenv($holdingbranch);
2101 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2102 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2103 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2104 ## Cannot be issued from another branch
2105 set_userenv($otherbranch);
2106 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2107 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2108 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2109 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
2111 # AllowReturnToBranch == homebranch
2112 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2113 ## Can be issued from holdinbranch
2114 set_userenv($homebranch);
2115 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2116 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2117 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2118 ## Cannot be issued from holdinbranch
2119 set_userenv($holdingbranch);
2120 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2121 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2122 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2123 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2124 ## Cannot be issued from holdinbranch
2125 set_userenv($otherbranch);
2126 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2127 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2128 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2129 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2131 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2134 subtest 'AddIssue & AllowReturnToBranch' => sub {
2137 my $homebranch = $builder->build( { source => 'Branch' } );
2138 my $holdingbranch = $builder->build( { source => 'Branch' } );
2139 my $otherbranch = $builder->build( { source => 'Branch' } );
2141 my $patron_1 = $builder->build_object({
2142 class => 'Koha::Patrons',
2143 value => { categorycode => $patron_category->{categorycode} }
2146 my $patron_2 = $builder->build_object({
2147 class => 'Koha::Patrons',
2148 value => { categorycode => $patron_category->{categorycode} }
2152 my $item = $builder->build_sample_item(
2154 homebranch => $homebranch->{branchcode},
2155 holdingbranch => $holdingbranch->{branchcode},
2159 set_userenv($holdingbranch);
2161 my $ref_issue = 'Koha::Checkout';
2162 my $issue = AddIssue( $patron_1, $item->barcode );
2164 my ( $error, $question, $alerts );
2166 # AllowReturnToBranch == homebranch
2167 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2168 ## Can be issued from homebranch
2169 set_userenv($homebranch);
2170 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
2171 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2172 ## Can be issued from holdinbranch
2173 set_userenv($holdingbranch);
2174 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
2175 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2176 ## Can be issued from another branch
2177 set_userenv($otherbranch);
2178 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
2179 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2181 # AllowReturnToBranch == holdinbranch
2182 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2183 ## Cannot be issued from homebranch
2184 set_userenv($homebranch);
2185 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
2186 ## Can be issued from holdingbranch
2187 set_userenv($holdingbranch);
2188 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
2189 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2190 ## Cannot be issued from another branch
2191 set_userenv($otherbranch);
2192 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
2194 # AllowReturnToBranch == homebranch
2195 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2196 ## Can be issued from homebranch
2197 set_userenv($homebranch);
2198 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
2199 AddIssue( $patron_1, $item->barcode ); # Re-issue to patron 1
2200 ## Cannot be issued from holdinbranch
2201 set_userenv($holdingbranch);
2202 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
2203 ## Cannot be issued from another branch
2204 set_userenv($otherbranch);
2205 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
2206 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2209 subtest 'AddIssue | recalls' => sub {
2212 t::lib::Mocks::mock_preference("UseRecalls", 1);
2213 t::lib::Mocks::mock_preference("item-level_itypes", 1);
2214 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2215 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2216 my $item = $builder->build_sample_item;
2217 Koha::CirculationRules->set_rules({
2218 branchcode => undef,
2220 categorycode => undef,
2222 recalls_allowed => 10,
2226 # checking out item that they have recalled
2227 my $recall1 = Koha::Recall->new(
2228 { patron_id => $patron1->borrowernumber,
2229 biblio_id => $item->biblionumber,
2230 item_id => $item->itemnumber,
2232 pickup_library_id => $patron1->branchcode,
2235 AddIssue( $patron1, $item->barcode, undef, undef, undef, undef, { recall_id => $recall1->id } );
2236 $recall1 = Koha::Recalls->find( $recall1->id );
2237 is( $recall1->fulfilled, 1, 'Recall was fulfilled when patron checked out item' );
2238 AddReturn( $item->barcode, $item->homebranch );
2240 # this item is has a recall request. cancel recall
2241 my $recall2 = Koha::Recall->new(
2242 { patron_id => $patron2->borrowernumber,
2243 biblio_id => $item->biblionumber,
2244 item_id => $item->itemnumber,
2246 pickup_library_id => $patron2->branchcode,
2249 AddIssue( $patron1, $item->barcode, undef, undef, undef, undef, { recall_id => $recall2->id, cancel_recall => 'cancel' } );
2250 $recall2 = Koha::Recalls->find( $recall2->id );
2251 is( $recall2->cancelled, 1, 'Recall was cancelled when patron checked out item' );
2252 AddReturn( $item->barcode, $item->homebranch );
2254 # this item is waiting to fulfill a recall. revert recall
2255 my $recall3 = Koha::Recall->new(
2256 { patron_id => $patron2->borrowernumber,
2257 biblio_id => $item->biblionumber,
2258 item_id => $item->itemnumber,
2260 pickup_library_id => $patron2->branchcode,
2263 $recall3->set_waiting;
2264 AddIssue( $patron1, $item->barcode, undef, undef, undef, undef, { recall_id => $recall3->id, cancel_recall => 'revert' } );
2265 $recall3 = Koha::Recalls->find( $recall3->id );
2266 is( $recall3->requested, 1, 'Recall was reverted from waiting when patron checked out item' );
2267 AddReturn( $item->barcode, $item->homebranch );
2270 subtest 'AddIssue & illrequests.due_date' => sub {
2273 t::lib::Mocks::mock_preference( 'ILLModule', 1 );
2274 my $library = $builder->build( { source => 'Branch' } );
2275 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2276 my $item = $builder->build_sample_item();
2278 set_userenv($library);
2280 my $custom_date_due = '9999-12-18 12:34:56';
2281 my $expected_date_due = '9999-12-18 23:59:00';
2282 my $illrequest = Koha::Illrequest->new({
2283 borrowernumber => $patron->borrowernumber,
2284 biblio_id => $item->biblionumber,
2285 branchcode => $library->{'branchcode'},
2286 due_date => $custom_date_due,
2289 my $issue = AddIssue( $patron, $item->barcode );
2290 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2292 $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2293 $item = $builder->build_sample_item();
2294 $custom_date_due = '9999-12-19';
2295 $expected_date_due = '9999-12-19 23:59:00';
2296 $illrequest = Koha::Illrequest->new({
2297 borrowernumber => $patron->borrowernumber,
2298 biblio_id => $item->biblionumber,
2299 branchcode => $library->{'branchcode'},
2300 due_date => $custom_date_due,
2303 $issue = AddIssue( $patron, $item->barcode );
2304 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2307 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
2310 my $library = $builder->build( { source => 'Branch' } );
2311 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2312 my $item_1 = $builder->build_sample_item(
2314 library => $library->{branchcode},
2317 my $item_2 = $builder->build_sample_item(
2319 library => $library->{branchcode},
2322 Koha::CirculationRules->set_rules(
2324 categorycode => undef,
2326 branchcode => $library->{branchcode},
2328 reservesallowed => 25,
2330 lengthunit => 'days',
2331 renewalsallowed => 1,
2333 norenewalbefore => undef,
2342 my ( $error, $question, $alerts );
2344 # Patron cannot issue item_1, they have overdues
2345 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
2346 my $issue = AddIssue( $patron, $item_1->barcode, $yesterday ); # Add an overdue
2348 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
2349 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2350 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
2351 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
2353 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
2354 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2355 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2356 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
2358 # Patron cannot issue item_1, they are debarred
2359 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
2360 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
2361 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2362 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2363 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
2365 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
2366 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2367 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2368 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
2371 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
2374 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2375 my $patron_category_x = $builder->build_object(
2377 class => 'Koha::Patron::Categories',
2378 value => { category_type => 'X' }
2381 my $patron = $builder->build_object(
2383 class => 'Koha::Patrons',
2385 categorycode => $patron_category_x->categorycode,
2386 gonenoaddress => undef,
2393 my $item_1 = $builder->build_sample_item(
2395 library => $library->{branchcode},
2399 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
2400 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
2402 my $stat = Koha::Statistics->search( { itemnumber => $item_1->itemnumber } )->next;
2403 is( $stat->branch, C4::Context->userenv->{'branch'}, 'Recorded a branch' );
2404 is( $stat->type, 'localuse', 'Recorded type as localuse' );
2405 is( $stat->itemnumber, $item_1->itemnumber, 'Recorded an itemnumber' );
2406 is( $stat->itemtype, $item_1->effective_itemtype, 'Recorded an itemtype' );
2407 is( $stat->borrowernumber, $patron->borrowernumber, 'Recorded a borrower number' );
2408 is( $stat->ccode, $item_1->ccode, 'Recorded a collection code' );
2409 is( $stat->categorycode, $patron->categorycode, 'Recorded a categorycode' );
2410 is( $stat->location, $item_1->location, 'Recorded a location' );
2412 # TODO There are other tests to provide here
2415 subtest 'MultipleReserves' => sub {
2418 my $biblio = $builder->build_sample_biblio();
2420 my $branch = $library2->{branchcode};
2422 my $item_1 = $builder->build_sample_item(
2424 biblionumber => $biblio->biblionumber,
2426 replacementprice => 12.00,
2431 my $item_2 = $builder->build_sample_item(
2433 biblionumber => $biblio->biblionumber,
2435 replacementprice => 12.00,
2442 my $resdate = undef;
2443 my $expdate = undef;
2445 my $checkitem = undef;
2448 my %renewing_borrower_data = (
2449 firstname => 'John',
2450 surname => 'Renewal',
2451 categorycode => $patron_category->{categorycode},
2452 branchcode => $branch,
2454 my $patron = Koha::Patron->new(\%renewing_borrower_data)->store;
2455 my $issue = AddIssue( $patron, $item_1->barcode);
2456 my $datedue = dt_from_string( $issue->date_due() );
2457 is (defined $issue->date_due(), 1, "item 1 checked out");
2458 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
2460 my %reserving_borrower_data1 = (
2461 firstname => 'Katrin',
2462 surname => 'Reservation',
2463 categorycode => $patron_category->{categorycode},
2464 branchcode => $branch,
2466 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
2469 branchcode => $branch,
2470 borrowernumber => $reserving_borrowernumber1,
2471 biblionumber => $biblio->biblionumber,
2472 priority => $priority,
2473 reservation_date => $resdate,
2474 expiration_date => $expdate,
2476 itemnumber => $checkitem,
2481 my %reserving_borrower_data2 = (
2482 firstname => 'Kirk',
2483 surname => 'Reservation',
2484 categorycode => $patron_category->{categorycode},
2485 branchcode => $branch,
2487 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
2490 branchcode => $branch,
2491 borrowernumber => $reserving_borrowernumber2,
2492 biblionumber => $biblio->biblionumber,
2493 priority => $priority,
2494 reservation_date => $resdate,
2495 expiration_date => $expdate,
2497 itemnumber => $checkitem,
2503 my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue, 1);
2504 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2507 my $item_3 = $builder->build_sample_item(
2509 biblionumber => $biblio->biblionumber,
2511 replacementprice => 12.00,
2517 my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue, 1);
2518 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2522 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2525 my $library = $builder->build( { source => 'Branch' } );
2526 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2528 my $biblionumber = $builder->build_sample_biblio(
2530 branchcode => $library->{branchcode},
2533 my $item_1 = $builder->build_sample_item(
2535 biblionumber => $biblionumber,
2536 library => $library->{branchcode},
2540 my $item_2 = $builder->build_sample_item(
2542 biblionumber => $biblionumber,
2543 library => $library->{branchcode},
2547 Koha::CirculationRules->set_rules(
2549 categorycode => undef,
2551 branchcode => $library->{branchcode},
2553 reservesallowed => 25,
2555 lengthunit => 'days',
2556 renewalsallowed => 1,
2558 norenewalbefore => undef,
2567 my ( $error, $question, $alerts );
2568 my $issue = AddIssue( $patron, $item_1->barcode, dt_from_string->add( days => 1 ) );
2570 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2571 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2573 { error => $error, alerts => $alerts },
2574 { error => {}, alerts => {} },
2575 'No error or alert should be raised'
2577 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2579 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2580 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2582 { error => $error, question => $question, alerts => $alerts },
2583 { error => {}, question => {}, alerts => {} },
2584 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2587 # Add a subscription
2588 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2590 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2591 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2593 { error => $error, question => $question, alerts => $alerts },
2594 { error => {}, question => {}, alerts => {} },
2595 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2598 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2599 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2601 { error => $error, question => $question, alerts => $alerts },
2602 { error => {}, question => {}, alerts => {} },
2603 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2607 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2610 my $library = $builder->build( { source => 'Branch' } );
2611 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2614 my $biblionumber = $builder->build_sample_biblio(
2616 branchcode => $library->{branchcode},
2619 my $item_1 = $builder->build_sample_item(
2621 biblionumber => $biblionumber,
2622 library => $library->{branchcode},
2625 my $item_2 = $builder->build_sample_item(
2627 biblionumber => $biblionumber,
2628 library => $library->{branchcode},
2632 # And the circulation rule
2633 Koha::CirculationRules->search->delete;
2634 Koha::CirculationRules->set_rules(
2636 categorycode => undef,
2638 branchcode => undef,
2641 firstremind => 1, # 1 day of grace
2642 finedays => 2, # 2 days of fine per day of overdue
2643 lengthunit => 'days',
2648 # Patron cannot issue item_1, they have overdues
2649 my $now = dt_from_string;
2650 my $five_days_ago = $now->clone->subtract( days => 5 );
2651 my $ten_days_ago = $now->clone->subtract( days => 10 );
2652 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2653 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2654 ; # Add another overdue
2656 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2657 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2658 my $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2659 is( $suspensions->count, 1, "Suspension added" );
2660 my $THE_suspension = $suspensions->next;
2662 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2663 # Same for the others
2664 my $expected_expiration = output_pref(
2666 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2667 dateformat => 'sql',
2671 is( $THE_suspension->expiration, $expected_expiration, "Suspesion expiration set" );
2673 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2674 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2675 is( $suspensions->count, 1, "Only one suspension" );
2676 $THE_suspension = $suspensions->next;
2678 $expected_expiration = output_pref(
2680 dt => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2681 dateformat => 'sql',
2685 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2687 Koha::Patron::Debarments::DelUniqueDebarment(
2688 { borrowernumber => $patron->borrowernumber, type => 'SUSPENSION' } );
2690 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2691 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2692 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2693 ; # Add another overdue
2694 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2695 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2696 is( $suspensions->count, 1, "Only one suspension" );
2697 $THE_suspension = $suspensions->next;
2699 $expected_expiration = output_pref(
2701 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2702 dateformat => 'sql',
2706 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2708 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2709 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2710 is( $suspensions->count, 1, "Only one suspension" );
2711 $THE_suspension = $suspensions->next;
2713 $expected_expiration = output_pref(
2715 dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2716 dateformat => 'sql',
2720 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2723 subtest 'AddReturn + suspension_chargeperiod' => sub {
2726 my $library = $builder->build( { source => 'Branch' } );
2727 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2729 my $biblionumber = $builder->build_sample_biblio(
2731 branchcode => $library->{branchcode},
2734 my $item_1 = $builder->build_sample_item(
2736 biblionumber => $biblionumber,
2737 library => $library->{branchcode},
2741 # And the issuing rule
2742 Koha::CirculationRules->search->delete;
2743 Koha::CirculationRules->set_rules(
2745 categorycode => '*',
2750 firstremind => 0, # 0 day of grace
2751 finedays => 2, # 2 days of fine per day of overdue
2752 suspension_chargeperiod => 1,
2753 lengthunit => 'days',
2758 my $now = dt_from_string;
2759 my $five_days_ago = $now->clone->subtract( days => 5 );
2760 # We want to charge 2 days every day, without grace
2761 # With 5 days of overdue: 5 * Z
2762 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2763 test_debarment_on_checkout(
2766 library => $library,
2768 due_date => $five_days_ago,
2769 expiration_date => $expected_expiration,
2773 # Same with undef firstremind
2774 Koha::CirculationRules->search->delete;
2775 Koha::CirculationRules->set_rules(
2777 categorycode => '*',
2782 firstremind => undef, # 0 day of grace
2783 finedays => 2, # 2 days of fine per day of overdue
2784 suspension_chargeperiod => 1,
2785 lengthunit => 'days',
2790 my $now = dt_from_string;
2791 my $five_days_ago = $now->clone->subtract( days => 5 );
2792 # We want to charge 2 days every day, without grace
2793 # With 5 days of overdue: 5 * Z
2794 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2795 test_debarment_on_checkout(
2798 library => $library,
2800 due_date => $five_days_ago,
2801 expiration_date => $expected_expiration,
2805 # We want to charge 2 days every 2 days, without grace
2806 # With 5 days of overdue: (5 * 2) / 2
2807 Koha::CirculationRules->set_rule(
2809 categorycode => undef,
2810 branchcode => undef,
2812 rule_name => 'suspension_chargeperiod',
2817 $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2818 test_debarment_on_checkout(
2821 library => $library,
2823 due_date => $five_days_ago,
2824 expiration_date => $expected_expiration,
2828 # We want to charge 2 days every 3 days, with 1 day of grace
2829 # With 5 days of overdue: ((5-1) / 3 ) * 2
2830 Koha::CirculationRules->set_rules(
2832 categorycode => undef,
2833 branchcode => undef,
2836 suspension_chargeperiod => 3,
2841 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2842 test_debarment_on_checkout(
2845 library => $library,
2847 due_date => $five_days_ago,
2848 expiration_date => $expected_expiration,
2852 # Use finesCalendar to know if holiday must be skipped to calculate the due date
2853 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2854 Koha::CirculationRules->set_rules(
2856 categorycode => undef,
2857 branchcode => undef,
2861 suspension_chargeperiod => 1,
2866 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2867 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2869 # Adding a holiday 2 days ago
2870 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2871 my $two_days_ago = $now->clone->subtract( days => 2 );
2872 $calendar->insert_single_holiday(
2873 day => $two_days_ago->day,
2874 month => $two_days_ago->month,
2875 year => $two_days_ago->year,
2876 title => 'holidayTest-2d',
2877 description => 'holidayDesc 2 days ago'
2879 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2880 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2881 test_debarment_on_checkout(
2884 library => $library,
2886 due_date => $five_days_ago,
2887 expiration_date => $expected_expiration,
2891 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2892 my $two_days_ahead = $now->clone->add( days => 2 );
2893 $calendar->insert_single_holiday(
2894 day => $two_days_ahead->day,
2895 month => $two_days_ahead->month,
2896 year => $two_days_ahead->year,
2897 title => 'holidayTest+2d',
2898 description => 'holidayDesc 2 days ahead'
2901 # Same as above, but we should skip D+2
2902 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2903 test_debarment_on_checkout(
2906 library => $library,
2908 due_date => $five_days_ago,
2909 expiration_date => $expected_expiration,
2913 # Adding another holiday, day of expiration date
2914 my $expected_expiration_dt = dt_from_string($expected_expiration);
2915 $calendar->insert_single_holiday(
2916 day => $expected_expiration_dt->day,
2917 month => $expected_expiration_dt->month,
2918 year => $expected_expiration_dt->year,
2919 title => 'holidayTest_exp',
2920 description => 'holidayDesc on expiration date'
2922 # Expiration date will be the day after
2923 test_debarment_on_checkout(
2926 library => $library,
2928 due_date => $five_days_ago,
2929 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2933 test_debarment_on_checkout(
2936 library => $library,
2938 return_date => $now->clone->add(days => 5),
2939 expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2943 test_debarment_on_checkout(
2946 library => $library,
2948 due_date => $now->clone->add(days => 1),
2949 return_date => $now->clone->add(days => 5),
2950 expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2954 Koha::CirculationRules->search->delete;
2955 Koha::CirculationRules->set_rules(
2957 categorycode => undef,
2959 branchcode => undef,
2962 lengthunit => 'days',
2967 Koha::Patron::Debarments::AddDebarment(
2969 borrowernumber => $patron->borrowernumber,
2970 expiration => '9999-12-31',
2975 AddIssue( $patron, $item_1->barcode, $now->clone->subtract( days => 1 ) );
2976 my ( undef, $message ) = AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2977 is( $message->{WasReturned} && exists $message->{ForeverDebarred}, 1, 'Forever debarred message for Addreturn when overdue');
2979 Koha::Patron::Debarments::DelUniqueDebarment(
2981 borrowernumber => $patron->borrowernumber,
2985 Koha::Patron::Debarments::AddDebarment(
2987 borrowernumber => $patron->borrowernumber,
2988 expiration => $now->clone->add( days => 10 ),
2993 AddIssue( $patron, $item_1->barcode, $now->clone->subtract( days => 1 ) );
2994 (undef, $message) = AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2995 is( $message->{WasReturned} && exists $message->{PrevDebarred}, 1, 'Previously debarred message for Addreturn when overdue');
2998 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
3001 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
3002 my $patron1 = $builder->build_object(
3004 class => 'Koha::Patrons',
3006 branchcode => $library->branchcode,
3007 categorycode => $patron_category->{categorycode}
3011 my $patron2 = $builder->build_object(
3013 class => 'Koha::Patrons',
3015 branchcode => $library->branchcode,
3016 categorycode => $patron_category->{categorycode}
3021 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
3023 my $item = $builder->build_sample_item(
3025 library => $library->branchcode,
3029 my ( $error, $question, $alerts );
3030 my $issue = AddIssue( $patron1, $item->barcode );
3032 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
3033 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
3034 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' );
3036 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
3037 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
3038 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' );
3040 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
3044 subtest 'AddReturn | is_overdue' => sub {
3047 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
3048 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
3049 t::lib::Mocks::mock_preference('finesMode', 'production');
3050 t::lib::Mocks::mock_preference('MaxFine', '100');
3052 my $library = $builder->build( { source => 'Branch' } );
3053 my $patron = $builder->build_object(
3055 class => 'Koha::Patrons',
3056 value => { categorycode => $patron_category->{categorycode} }
3059 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
3060 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3062 my $item = $builder->build_sample_item(
3064 library => $library->{branchcode},
3065 replacementprice => 7
3069 Koha::CirculationRules->search->delete;
3070 Koha::CirculationRules->set_rules(
3072 categorycode => undef,
3074 branchcode => undef,
3077 lengthunit => 'days',
3078 fine => 1, # Charge 1 every day of overdue
3084 my $now = dt_from_string;
3085 my $one_day_ago = $now->clone->subtract( days => 1 );
3086 my $two_days_ago = $now->clone->subtract( days => 2 );
3087 my $five_days_ago = $now->clone->subtract( days => 5 );
3088 my $ten_days_ago = $now->clone->subtract( days => 10 );
3090 # No return date specified, today will be used => 10 days overdue charged
3091 AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago
3092 AddReturn( $item->barcode, $library->{branchcode} );
3093 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
3094 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3096 # specify return date 5 days before => no overdue charged
3097 AddIssue( $patron, $item->barcode, $five_days_ago ); # date due was 5d ago
3098 AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
3099 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
3100 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3102 # specify return date 5 days later => 5 days overdue charged
3103 AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago
3104 AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
3105 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
3106 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3108 # specify return date 5 days later, specify exemptfine => no overdue charge
3109 AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago
3110 AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago );
3111 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
3112 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3114 subtest 'bug 22877 | Lost item return' => sub {
3118 my $issue = AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago
3120 # Fake fines cronjob on this checkout
3122 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3123 $ten_days_ago, $now );
3126 issue_id => $issue->issue_id,
3127 itemnumber => $item->itemnumber,
3128 borrowernumber => $patron->borrowernumber,
3130 due => output_pref($ten_days_ago)
3133 is( int( $patron->account->balance() ),
3134 10, "Overdue fine of 10 days overdue" );
3136 # Fake longoverdue with charge and not marking returned
3137 LostItem( $item->itemnumber, 'cronjob', 0 );
3138 is( int( $patron->account->balance() ),
3139 17, "Lost fine of 7 plus 10 days overdue" );
3141 # Now we return it today
3142 AddReturn( $item->barcode, $library->{branchcode} );
3143 is( int( $patron->account->balance() ),
3144 17, "Should have a single 10 days overdue fine and lost charge" );
3147 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3150 subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
3154 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3156 my $issue = AddIssue( $patron, $item->barcode, $one_day_ago ); # date due was 1d ago
3158 # Fake fines cronjob on this checkout
3160 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3161 $one_day_ago, $now );
3164 issue_id => $issue->issue_id,
3165 itemnumber => $item->itemnumber,
3166 borrowernumber => $patron->borrowernumber,
3168 due => output_pref($one_day_ago)
3171 is( int( $patron->account->balance() ),
3172 1, "Overdue fine of 1 day overdue" );
3174 # Backdated return (dropbox mode example - charge should be removed)
3175 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3176 is( int( $patron->account->balance() ),
3177 0, "Overdue fine should be annulled" );
3178 my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3179 is( $lines->count, 0, "Overdue fine accountline has been removed");
3181 $issue = AddIssue( $patron, $item->barcode, $two_days_ago ); # date due was 2d ago
3183 # Fake fines cronjob on this checkout
3185 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3186 $two_days_ago, $now );
3189 issue_id => $issue->issue_id,
3190 itemnumber => $item->itemnumber,
3191 borrowernumber => $patron->borrowernumber,
3193 due => output_pref($one_day_ago)
3196 is( int( $patron->account->balance() ),
3197 2, "Overdue fine of 2 days overdue" );
3199 # Payment made against fine
3200 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3201 my $debit = $lines->next;
3202 my $credit = $patron->account->add_credit(
3206 interface => 'test',
3209 $credit->apply( { debits => [$debit] } );
3211 is( int( $patron->account->balance() ),
3212 0, "Overdue fine should be paid off" );
3213 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3214 is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
3215 my $line = $lines->next;
3216 is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
3217 is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
3219 # Backdated return (dropbox mode example - charge should be removed)
3220 AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
3221 is( int( $patron->account->balance() ),
3222 -1, "Refund credit has been applied" );
3223 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
3224 is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
3226 $line = $lines->next;
3227 is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
3228 is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
3229 is($line->status,'RETURNED', "Overdue fine is fixed");
3230 $line = $lines->next;
3231 is($line->amount+0,-2, "Original payment amount remains as 2");
3232 is($line->amountoutstanding+0,0, "Original payment remains applied");
3233 $line = $lines->next;
3234 is($line->amount+0,-1, "Refund amount correctly set to 1");
3235 is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
3238 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3241 subtest 'bug 25417 | backdated return + exemptfine' => sub {
3245 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3247 my $issue = AddIssue( $patron, $item->barcode, $one_day_ago ); # date due was 1d ago
3249 # Fake fines cronjob on this checkout
3251 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3252 $one_day_ago, $now );
3255 issue_id => $issue->issue_id,
3256 itemnumber => $item->itemnumber,
3257 borrowernumber => $patron->borrowernumber,
3259 due => output_pref($one_day_ago)
3262 is( int( $patron->account->balance() ),
3263 1, "Overdue fine of 1 day overdue" );
3265 # Backdated return (dropbox mode example - charge should no longer exist)
3266 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3267 is( int( $patron->account->balance() ),
3268 0, "Overdue fine should be annulled" );
3271 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3274 subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
3277 t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
3279 my $due_date = dt_from_string;
3280 my $issue = AddIssue( $patron, $item->barcode, $due_date );
3285 issue_id => $issue->issue_id,
3286 itemnumber => $item->itemnumber,
3287 borrowernumber => $patron->borrowernumber,
3289 due => output_pref($due_date)
3292 is( $patron->account->balance(),
3293 0.25, 'Overdue fine of $0.25 recorded' );
3295 # Backdate return to exact due date and time
3296 my ( undef, $message ) =
3297 AddReturn( $item->barcode, $library->{branchcode},
3301 Koha::Account::Lines->find( { issue_id => $issue->id } );
3302 ok( !$accountline, 'accountline removed as expected' );
3305 $issue = AddIssue( $patron, $item->barcode, $due_date );
3310 issue_id => $issue->issue_id,
3311 itemnumber => $item->itemnumber,
3312 borrowernumber => $patron->borrowernumber,
3314 due => output_pref($due_date)
3317 is( $patron->account->balance(),
3318 0.25, 'Overdue fine of $0.25 recorded' );
3320 # Partial pay accruing fine
3321 my $lines = Koha::Account::Lines->search(
3323 borrowernumber => $patron->borrowernumber,
3324 issue_id => $issue->id
3327 my $debit = $lines->next;
3328 my $credit = $patron->account->add_credit(
3332 interface => 'test',
3335 $credit->apply( { debits => [$debit] } );
3337 is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
3339 # Backdate return to exact due date and time
3340 ( undef, $message ) =
3341 AddReturn( $item->barcode, $library->{branchcode},
3344 $lines = Koha::Account::Lines->search(
3346 borrowernumber => $patron->borrowernumber,
3347 issue_id => $issue->id
3350 $accountline = $lines->next;
3351 is( $accountline->amountoutstanding + 0,
3352 0, 'Partially paid fee amount outstanding was reduced to 0' );
3353 is( $accountline->amount + 0,
3354 0, 'Partially paid fee amount was reduced to 0' );
3355 is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
3358 Koha::Account::Lines->search(
3359 { borrowernumber => $patron->borrowernumber } )->delete;
3362 subtest 'enh 23091 | Lost item return policies' => sub {
3365 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3367 my $branchcode_false =
3368 $builder->build( { source => 'Branch' } )->{branchcode};
3369 my $specific_rule_false = $builder->build(
3371 source => 'CirculationRule',
3373 branchcode => $branchcode_false,
3374 categorycode => undef,
3376 rule_name => 'lostreturn',
3381 my $branchcode_refund =
3382 $builder->build( { source => 'Branch' } )->{branchcode};
3383 my $specific_rule_refund = $builder->build(
3385 source => 'CirculationRule',
3387 branchcode => $branchcode_refund,
3388 categorycode => undef,
3390 rule_name => 'lostreturn',
3391 rule_value => 'refund'
3395 my $branchcode_restore =
3396 $builder->build( { source => 'Branch' } )->{branchcode};
3397 my $specific_rule_restore = $builder->build(
3399 source => 'CirculationRule',
3401 branchcode => $branchcode_restore,
3402 categorycode => undef,
3404 rule_name => 'lostreturn',
3405 rule_value => 'restore'
3409 my $branchcode_charge =
3410 $builder->build( { source => 'Branch' } )->{branchcode};
3411 my $specific_rule_charge = $builder->build(
3413 source => 'CirculationRule',
3415 branchcode => $branchcode_charge,
3416 categorycode => undef,
3418 rule_name => 'lostreturn',
3419 rule_value => 'charge'
3424 my $branchcode_refund_unpaid =
3425 $builder->build( { source => 'Branch' } )->{branchcode};
3426 my $specific_rule_refund_unpaid = $builder->build(
3428 source => 'CirculationRule',
3430 branchcode => $branchcode_refund_unpaid,
3431 categorycode => undef,
3433 rule_name => 'lostreturn',
3434 rule_value => 'refund_unpaid'
3439 my $replacement_amount = 99.00;
3440 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
3441 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
3442 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
3443 t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 );
3444 t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
3446 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
3449 subtest 'lostreturn | refund_unpaid' => sub {
3452 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund_unpaid });
3454 my $item = $builder->build_sample_item(
3456 replacementprice => $replacement_amount
3461 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode );
3464 $item->itemlost(3)->store;
3465 C4::Circulation::LostItem( $item->itemnumber, 1 );
3467 my $lost_fee_lines = Koha::Account::Lines->search(
3469 borrowernumber => $patron->id,
3470 itemnumber => $item->itemnumber,
3471 debit_type_code => 'LOST'
3474 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3475 my $lost_fee_line = $lost_fee_lines->next;
3476 is( int($lost_fee_line->amount),
3477 $replacement_amount, 'The right LOST amount is generated' );
3478 is( int($lost_fee_line->amountoutstanding),
3479 $replacement_amount,
3480 'The right LOST amountoutstanding is generated' );
3481 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3484 int($patron->account->balance),
3485 $replacement_amount ,
3486 "Account balance equals the replacement amount after being charged lost fee when no payments has been made"
3489 # Return lost item without any payments having been made
3490 my ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3492 $lost_fee_line->discard_changes;
3494 is( int($lost_fee_line->amount), $replacement_amount, 'The LOST amount is left intact' );
3495 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero' );
3496 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set' );
3498 int($patron->account->balance),
3500 'Account balance should be zero after returning item with lost fee when no payments has been made'
3503 # Create a second item
3504 $item = $builder->build_sample_item(
3506 replacementprice => $replacement_amount
3511 $issue = C4::Circulation::AddIssue( $patron, $item->barcode );
3514 $item->itemlost(3)->store;
3515 C4::Circulation::LostItem( $item->itemnumber, 1 );
3517 $lost_fee_lines = Koha::Account::Lines->search(
3519 borrowernumber => $patron->id,
3520 itemnumber => $item->itemnumber,
3521 debit_type_code => 'LOST'
3524 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3525 $lost_fee_line = $lost_fee_lines->next;
3527 # Make partial payment
3528 $patron->account->payin_amount({
3530 interface => 'intranet',
3531 payment_type => 'CASH',
3532 user_id => $patron->borrowernumber,
3534 debits => [$lost_fee_line]
3537 $lost_fee_line->discard_changes;
3539 is( int($lost_fee_line->amountoutstanding),
3541 'The LOST amountoutstanding is the expected amount after partial payment of lost fee'
3545 int($patron->account->balance),
3547 'Account balance is the expected amount after partial payment of lost fee'
3550 # Return lost item with partial payment having been made
3551 ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3553 $lost_fee_line->discard_changes;
3555 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero after returning lost item with partial payment' );
3556 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set for lost item with partial payment' );
3558 int($patron->account->balance),
3560 'Account balance should be zero after returning item with lost fee when partial payment has been made'
3563 # Create a third item
3564 $item = $builder->build_sample_item(
3566 replacementprice => $replacement_amount
3571 $issue = C4::Circulation::AddIssue( $patron, $item->barcode );
3574 $item->itemlost(3)->store;
3575 C4::Circulation::LostItem( $item->itemnumber, 1 );
3577 $lost_fee_lines = Koha::Account::Lines->search(
3579 borrowernumber => $patron->id,
3580 itemnumber => $item->itemnumber,
3581 debit_type_code => 'LOST'
3584 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3585 $lost_fee_line = $lost_fee_lines->next;
3588 $patron->account->payin_amount({
3590 interface => 'intranet',
3591 payment_type => 'CASH',
3592 user_id => $patron->borrowernumber,
3593 amount => $replacement_amount,
3594 debits => [$lost_fee_line]
3597 $lost_fee_line->discard_changes;
3599 is( int($lost_fee_line->amountoutstanding),
3601 'The LOST amountoutstanding is the expected amount after partial payment of lost fee'
3605 int($patron->account->balance),
3607 'Account balance is the expected amount after partial payment of lost fee'
3610 # Return lost item with partial payment having been made
3611 ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3613 $lost_fee_line->discard_changes;
3615 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero after returning lost item with full payment' );
3616 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set for lost item with partial payment' );
3618 int($patron->account->balance),
3620 'Account balance should be zero after returning item with lost fee when full payment has been made'
3624 subtest 'lostreturn | false' => sub {
3627 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
3629 my $item = $builder->build_sample_item(
3631 replacementprice => $replacement_amount
3636 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, $ten_days_ago );
3638 # Fake fines cronjob on this checkout
3640 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3641 $ten_days_ago, $now );
3644 issue_id => $issue->issue_id,
3645 itemnumber => $item->itemnumber,
3646 borrowernumber => $patron->borrowernumber,
3648 due => output_pref($ten_days_ago)
3651 my $overdue_fees = Koha::Account::Lines->search(
3653 borrowernumber => $patron->id,
3654 itemnumber => $item->itemnumber,
3655 debit_type_code => 'OVERDUE'
3658 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3659 my $overdue_fee = $overdue_fees->next;
3660 is( $overdue_fee->amount + 0,
3661 10, 'The right OVERDUE amount is generated' );
3662 is( $overdue_fee->amountoutstanding + 0,
3664 'The right OVERDUE amountoutstanding is generated' );
3666 # Simulate item marked as lost
3667 $item->itemlost(3)->store;
3668 C4::Circulation::LostItem( $item->itemnumber, 1 );
3670 my $lost_fee_lines = Koha::Account::Lines->search(
3672 borrowernumber => $patron->id,
3673 itemnumber => $item->itemnumber,
3674 debit_type_code => 'LOST'
3677 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3678 my $lost_fee_line = $lost_fee_lines->next;
3679 is( $lost_fee_line->amount + 0,
3680 $replacement_amount, 'The right LOST amount is generated' );
3681 is( $lost_fee_line->amountoutstanding + 0,
3682 $replacement_amount,
3683 'The right LOST amountoutstanding is generated' );
3684 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3687 my ( $returned, $message ) =
3688 AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
3690 $overdue_fee->discard_changes;
3691 is( $overdue_fee->amount + 0,
3692 10, 'The OVERDUE amount is left intact' );
3693 is( $overdue_fee->amountoutstanding + 0,
3695 'The OVERDUE amountoutstanding is left intact' );
3697 $lost_fee_line->discard_changes;
3698 is( $lost_fee_line->amount + 0,
3699 $replacement_amount, 'The LOST amount is left intact' );
3700 is( $lost_fee_line->amountoutstanding + 0,
3701 $replacement_amount,
3702 'The LOST amountoutstanding is left intact' );
3703 # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
3704 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3707 subtest 'lostreturn | refund' => sub {
3710 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
3712 my $item = $builder->build_sample_item(
3714 replacementprice => $replacement_amount
3719 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, $ten_days_ago );
3721 # Fake fines cronjob on this checkout
3723 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3724 $ten_days_ago, $now );
3727 issue_id => $issue->issue_id,
3728 itemnumber => $item->itemnumber,
3729 borrowernumber => $patron->borrowernumber,
3731 due => output_pref($ten_days_ago)
3734 my $overdue_fees = Koha::Account::Lines->search(
3736 borrowernumber => $patron->id,
3737 itemnumber => $item->itemnumber,
3738 debit_type_code => 'OVERDUE'
3741 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3742 my $overdue_fee = $overdue_fees->next;
3743 is( $overdue_fee->amount + 0,
3744 10, 'The right OVERDUE amount is generated' );
3745 is( $overdue_fee->amountoutstanding + 0,
3747 'The right OVERDUE amountoutstanding is generated' );
3749 # Simulate item marked as lost
3750 $item->itemlost(3)->store;
3751 C4::Circulation::LostItem( $item->itemnumber, 1 );
3753 my $lost_fee_lines = Koha::Account::Lines->search(
3755 borrowernumber => $patron->id,
3756 itemnumber => $item->itemnumber,
3757 debit_type_code => 'LOST'
3760 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3761 my $lost_fee_line = $lost_fee_lines->next;
3762 is( $lost_fee_line->amount + 0,
3763 $replacement_amount, 'The right LOST amount is generated' );
3764 is( $lost_fee_line->amountoutstanding + 0,
3765 $replacement_amount,
3766 'The right LOST amountoutstanding is generated' );
3767 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3769 # Return the lost item
3770 my ( undef, $message ) =
3771 AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
3773 $overdue_fee->discard_changes;
3774 is( $overdue_fee->amount + 0,
3775 10, 'The OVERDUE amount is left intact' );
3776 is( $overdue_fee->amountoutstanding + 0,
3778 'The OVERDUE amountoutstanding is left intact' );
3780 $lost_fee_line->discard_changes;
3781 is( $lost_fee_line->amount + 0,
3782 $replacement_amount, 'The LOST amount is left intact' );
3783 is( $lost_fee_line->amountoutstanding + 0,
3785 'The LOST amountoutstanding is refunded' );
3786 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3789 subtest 'lostreturn | restore' => sub {
3792 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
3794 my $item = $builder->build_sample_item(
3796 replacementprice => $replacement_amount
3801 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode , $ten_days_ago);
3803 # Fake fines cronjob on this checkout
3805 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3806 $ten_days_ago, $now );
3809 issue_id => $issue->issue_id,
3810 itemnumber => $item->itemnumber,
3811 borrowernumber => $patron->borrowernumber,
3813 due => output_pref($ten_days_ago)
3816 my $overdue_fees = Koha::Account::Lines->search(
3818 borrowernumber => $patron->id,
3819 itemnumber => $item->itemnumber,
3820 debit_type_code => 'OVERDUE'
3823 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3824 my $overdue_fee = $overdue_fees->next;
3825 is( $overdue_fee->amount + 0,
3826 10, 'The right OVERDUE amount is generated' );
3827 is( $overdue_fee->amountoutstanding + 0,
3829 'The right OVERDUE amountoutstanding is generated' );
3831 # Simulate item marked as lost
3832 $item->itemlost(3)->store;
3833 C4::Circulation::LostItem( $item->itemnumber, 1 );
3835 my $lost_fee_lines = Koha::Account::Lines->search(
3837 borrowernumber => $patron->id,
3838 itemnumber => $item->itemnumber,
3839 debit_type_code => 'LOST'
3842 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3843 my $lost_fee_line = $lost_fee_lines->next;
3844 is( $lost_fee_line->amount + 0,
3845 $replacement_amount, 'The right LOST amount is generated' );
3846 is( $lost_fee_line->amountoutstanding + 0,
3847 $replacement_amount,
3848 'The right LOST amountoutstanding is generated' );
3849 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3851 # Simulate refunding overdue fees upon marking item as lost
3852 my $overdue_forgive = $patron->account->add_credit(
3855 user_id => $manager->borrowernumber,
3856 library_id => $branchcode_restore,
3857 interface => 'test',
3859 item_id => $item->itemnumber
3862 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3863 $overdue_fee->discard_changes;
3864 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3867 my ( undef, $message ) =
3868 AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
3870 $overdue_fee->discard_changes;
3871 is( $overdue_fee->amount + 0,
3872 10, 'The OVERDUE amount is left intact' );
3873 is( $overdue_fee->amountoutstanding + 0,
3875 'The OVERDUE amountoutstanding is restored' );
3877 $lost_fee_line->discard_changes;
3878 is( $lost_fee_line->amount + 0,
3879 $replacement_amount, 'The LOST amount is left intact' );
3880 is( $lost_fee_line->amountoutstanding + 0,
3882 'The LOST amountoutstanding is refunded' );
3883 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3886 subtest 'lostreturn | charge' => sub {
3889 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
3891 my $item = $builder->build_sample_item(
3893 replacementprice => $replacement_amount
3898 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, $ten_days_ago );
3900 # Fake fines cronjob on this checkout
3902 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3903 $ten_days_ago, $now );
3906 issue_id => $issue->issue_id,
3907 itemnumber => $item->itemnumber,
3908 borrowernumber => $patron->borrowernumber,
3910 due => output_pref($ten_days_ago)
3913 my $overdue_fees = Koha::Account::Lines->search(
3915 borrowernumber => $patron->id,
3916 itemnumber => $item->itemnumber,
3917 debit_type_code => 'OVERDUE'
3920 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3921 my $overdue_fee = $overdue_fees->next;
3922 is( $overdue_fee->amount + 0,
3923 10, 'The right OVERDUE amount is generated' );
3924 is( $overdue_fee->amountoutstanding + 0,
3926 'The right OVERDUE amountoutstanding is generated' );
3928 # Simulate item marked as lost
3929 $item->itemlost(3)->store;
3930 C4::Circulation::LostItem( $item->itemnumber, 1 );
3932 my $lost_fee_lines = Koha::Account::Lines->search(
3934 borrowernumber => $patron->id,
3935 itemnumber => $item->itemnumber,
3936 debit_type_code => 'LOST'
3939 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3940 my $lost_fee_line = $lost_fee_lines->next;
3941 is( $lost_fee_line->amount + 0,
3942 $replacement_amount, 'The right LOST amount is generated' );
3943 is( $lost_fee_line->amountoutstanding + 0,
3944 $replacement_amount,
3945 'The right LOST amountoutstanding is generated' );
3946 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3948 # Simulate refunding overdue fees upon marking item as lost
3949 my $overdue_forgive = $patron->account->add_credit(
3952 user_id => $manager->borrowernumber,
3953 library_id => $branchcode_charge,
3954 interface => 'test',
3956 item_id => $item->itemnumber
3959 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3960 $overdue_fee->discard_changes;
3961 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3964 my ( undef, $message ) =
3965 AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
3967 $lost_fee_line->discard_changes;
3968 is( $lost_fee_line->amount + 0,
3969 $replacement_amount, 'The LOST amount is left intact' );
3970 is( $lost_fee_line->amountoutstanding + 0,
3972 'The LOST amountoutstanding is refunded' );
3973 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3975 $overdue_fees = Koha::Account::Lines->search(
3977 borrowernumber => $patron->id,
3978 itemnumber => $item->itemnumber,
3979 debit_type_code => 'OVERDUE'
3982 order_by => { '-asc' => 'accountlines_id'}
3985 is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
3986 $overdue_fee = $overdue_fees->next;
3987 is( $overdue_fee->amount + 0,
3988 10, 'The original OVERDUE amount is left intact' );
3989 is( $overdue_fee->amountoutstanding + 0,
3991 'The original OVERDUE amountoutstanding is left as forgiven' );
3992 $overdue_fee = $overdue_fees->next;
3993 is( $overdue_fee->amount + 0,
3994 5, 'The new OVERDUE amount is correct for the backdated return' );
3995 is( $overdue_fee->amountoutstanding + 0,
3997 'The new OVERDUE amountoutstanding is correct for the backdated return' );
4002 subtest '_FixOverduesOnReturn' => sub {
4005 my $manager = $builder->build_object({ class => "Koha::Patrons" });
4006 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
4008 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
4010 my $branchcode = $library2->{branchcode};
4012 my $item = $builder->build_sample_item(
4014 biblionumber => $biblio->biblionumber,
4015 library => $branchcode,
4016 replacementprice => 99.00,
4021 my $patron = $builder->build( { source => 'Borrower' } );
4023 ## Start with basic call, should just close out the open fine
4024 my $accountline = Koha::Account::Line->new(
4026 borrowernumber => $patron->{borrowernumber},
4027 debit_type_code => 'OVERDUE',
4028 status => 'UNRETURNED',
4029 itemnumber => $item->itemnumber,
4031 amountoutstanding => 99.00,
4032 interface => 'test',
4036 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
4038 $accountline->_result()->discard_changes();
4040 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
4041 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
4042 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
4044 ## Run again, with exemptfine enabled
4047 debit_type_code => 'OVERDUE',
4048 status => 'UNRETURNED',
4049 amountoutstanding => 99.00,
4053 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
4055 $accountline->_result()->discard_changes();
4056 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'APPLY' })->next();
4058 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
4059 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
4060 is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
4061 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
4062 is( $offset->amount + 0, -99, "Amount of offset is correct" );
4063 my $credit = $offset->credit;
4064 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
4065 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
4066 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
4068 # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
4071 debit_type_code => 'OVERDUE',
4072 status => 'UNRETURNED',
4073 amountoutstanding => 0.00,
4078 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
4080 $accountline->_result()->discard_changes();
4081 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'CREATE' })->next();
4082 is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
4083 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
4084 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
4087 subtest 'Set waiting flag' => sub {
4090 my $library_1 = $builder->build( { source => 'Branch' } );
4091 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
4092 my $library_2 = $builder->build( { source => 'Branch' } );
4093 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
4095 my $item = $builder->build_sample_item(
4097 library => $library_1->{branchcode},
4101 set_userenv( $library_2 );
4102 my $reserve_id = AddReserve(
4104 branchcode => $library_2->{branchcode},
4105 borrowernumber => $patron_2->{borrowernumber},
4106 biblionumber => $item->biblionumber,
4108 itemnumber => $item->itemnumber,
4112 set_userenv( $library_1 );
4113 my $do_transfer = 1;
4114 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
4115 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
4116 my $hold = Koha::Holds->find( $reserve_id );
4117 is( $hold->found, 'T', 'Hold is in transit' );
4119 my ( $status ) = CheckReserves($item);
4120 is( $status, 'Transferred', 'Hold is not waiting yet');
4122 set_userenv( $library_2 );
4124 AddReturn( $item->barcode, $library_2->{branchcode} );
4125 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
4126 $hold = Koha::Holds->find( $reserve_id );
4127 is( $hold->found, 'W', 'Hold is waiting' );
4128 ( $status ) = CheckReserves($item);
4129 is( $status, 'Waiting', 'Now the hold is waiting');
4131 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
4132 set_userenv( $library_1 );
4133 (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
4134 $hold = Koha::Holds->find( $reserve_id );
4135 is( $hold->found, undef, 'Hold is no longer marked waiting' );
4136 is( $hold->priority, 1, "Hold is now priority one again");
4137 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
4138 is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
4139 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
4140 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
4141 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
4144 subtest 'Cancel transfers on lost items' => sub {
4147 my $library_to = $builder->build_object( { class => 'Koha::Libraries' } );
4148 my $item = $builder->build_sample_item();
4149 my $holdingbranch = $item->holdingbranch;
4150 # Historic transfer (datearrived is defined)
4151 my $old_transfer = $builder->build_object(
4153 class => 'Koha::Item::Transfers',
4155 itemnumber => $item->itemnumber,
4156 frombranch => $holdingbranch,
4157 tobranch => $library_to->branchcode,
4159 datesent => \'NOW()',
4160 datearrived => \'NOW()',
4161 datecancelled => undef,
4162 daterequested => \'NOW()'
4166 # Queued transfer (datesent is undefined)
4167 my $transfer_1 = $builder->build_object(
4169 class => 'Koha::Item::Transfers',
4171 itemnumber => $item->itemnumber,
4172 frombranch => $holdingbranch,
4173 tobranch => $library_to->branchcode,
4176 datearrived => undef,
4177 datecancelled => undef,
4178 daterequested => \'NOW()'
4182 # In transit transfer (datesent is defined, datearrived and datecancelled are both undefined)
4183 my $transfer_2 = $builder->build_object(
4185 class => 'Koha::Item::Transfers',
4187 itemnumber => $item->itemnumber,
4188 frombranch => $holdingbranch,
4189 tobranch => $library_to->branchcode,
4191 datesent => \'NOW()',
4192 datearrived => undef,
4193 datecancelled => undef,
4194 daterequested => \'NOW()'
4199 # Simulate item being marked as lost
4200 $item->itemlost(1)->store;
4201 LostItem( $item->itemnumber, 'test', 1 );
4203 $transfer_1->discard_changes;
4204 isnt($transfer_1->datecancelled, undef, "Queud transfer was cancelled upon item lost");
4205 is($transfer_1->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
4206 $transfer_2->discard_changes;
4207 isnt($transfer_2->datecancelled, undef, "Active transfer was cancelled upon item lost");
4208 is($transfer_2->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
4209 $old_transfer->discard_changes;
4210 is($old_transfer->datecancelled, undef, "Old transfers are unaffected");
4211 $item->discard_changes;
4212 is($item->holdingbranch, $holdingbranch, "Items holding branch remains unchanged");
4215 subtest 'CanBookBeIssued | is_overdue' => sub {
4218 # Set a simple circ policy
4219 Koha::CirculationRules->set_rules(
4221 categorycode => undef,
4222 branchcode => undef,
4226 reservesallowed => 25,
4228 lengthunit => 'days',
4229 renewalsallowed => 1,
4231 norenewalbefore => undef,
4239 my $now = dt_from_string()->truncate( to => 'day' );
4240 my $five_days_go = $now->clone->add( days => 5 );
4241 my $ten_days_go = $now->clone->add( days => 10);
4242 my $library = $builder->build( { source => 'Branch' } );
4243 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
4245 my $item = $builder->build_sample_item(
4247 library => $library->{branchcode},
4251 my $issue = AddIssue( $patron, $item->barcode, $five_days_go ); # date due was 10d ago
4252 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
4253 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), output_pref({ str => $five_days_go, dateonly => 1}), "First issue works");
4254 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron, $item->barcode, $ten_days_go, undef, undef, undef);
4255 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
4256 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
4259 subtest 'ItemsDeniedRenewal rules are checked' => sub {
4262 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
4263 Koha::CirculationRules->set_rules(
4265 categorycode => '*',
4267 branchcode => $idr_lib->branchcode,
4269 reservesallowed => 25,
4271 lengthunit => 'days',
4272 renewalsallowed => 10,
4274 norenewalbefore => undef,
4282 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
4283 homebranch => $idr_lib->branchcode,
4286 location => 'NOPROC'
4290 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
4291 branchcode => $idr_lib->branchcode,
4294 my $future = dt_from_string->add( days => 1 );
4295 my $issue = $builder->build_object(
4297 class => 'Koha::Checkouts',
4299 returndate => undef,
4300 renewals_count => 0,
4302 borrowernumber => $idr_borrower->borrowernumber,
4303 itemnumber => $allow_book->itemnumber,
4304 onsite_checkout => 0,
4305 date_due => $future,
4310 my $mock_item_class = Test::MockModule->new("Koha::Item");
4311 $mock_item_class->mock( 'is_denied_renewal', sub { return 1; } );
4313 my ( $mayrenew, $error ) = CanBookBeRenewed( $idr_borrower, $issue );
4314 is( $mayrenew, 0, 'Renewal blocked when $item->is_denied_renewal returns true' );
4315 is( $error, 'item_denied_renewal', 'Renewal blocked when $item->is_denied_renewal returns true' );
4317 $mock_item_class->unmock( 'is_denied_renewal' );
4318 $mock_item_class->mock( 'is_denied_renewal', sub { return 0; } );
4320 ( $mayrenew, $error ) = CanBookBeRenewed( $idr_borrower, $issue );
4321 is( $mayrenew, 1, 'Renewal allowed when $item->is_denied_renewal returns false' );
4322 is( $error, undef, 'Renewal allowed when $item->is_denied_renewal returns false' );
4324 $mock_item_class->unmock( 'is_denied_renewal' );
4327 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
4330 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4331 my $library = $builder->build( { source => 'Branch' } );
4332 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4334 my $item = $builder->build_sample_item(
4336 library => $library->{branchcode},
4340 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4341 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4342 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4345 subtest 'CanBookBeIssued | notforloan' => sub {
4348 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
4350 my $library = $builder->build( { source => 'Branch' } );
4351 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4353 my $itemtype = $builder->build(
4355 source => 'Itemtype',
4356 value => { notforloan => undef, }
4359 my $item = $builder->build_sample_item(
4361 library => $library->{branchcode},
4362 itype => $itemtype->{itemtype},
4365 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4367 my ( $issuingimpossible, $needsconfirmation );
4370 subtest 'item-level_itypes = 1' => sub {
4373 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
4374 # Is for loan at item type and item level
4375 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4376 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4377 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4379 # not for loan at item type level
4380 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4381 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4382 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4385 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4386 'Item can not be issued, not for loan at item type level'
4389 # not for loan at item level
4390 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4391 $item->notforloan( 1 )->store;
4392 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4393 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4396 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4397 'Item can not be issued, not for loan at item type level'
4401 subtest 'item-level_itypes = 0' => sub {
4404 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4406 # We set another itemtype for biblioitem
4407 my $itemtype = $builder->build(
4409 source => 'Itemtype',
4410 value => { notforloan => undef, }
4414 # for loan at item type and item level
4415 $item->notforloan(0)->store;
4416 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4417 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4418 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4419 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4421 # not for loan at item type level
4422 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4423 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4424 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4427 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4428 'Item can not be issued, not for loan at item type level'
4431 # not for loan at item level
4432 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4433 $item->notforloan( 1 )->store;
4434 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4435 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4438 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4439 'Item can not be issued, not for loan at item type level'
4443 # TODO test with AllowNotForLoanOverride = 1
4446 subtest 'CanBookBeIssued | recalls' => sub {
4449 t::lib::Mocks::mock_preference("UseRecalls", 1);
4450 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4451 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4452 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4453 my $item = $builder->build_sample_item;
4454 Koha::CirculationRules->set_rules({
4455 branchcode => undef,
4457 categorycode => undef,
4459 recalls_allowed => 10,
4464 my $recall = Koha::Recall->new(
4465 { patron_id => $patron1->borrowernumber,
4466 biblio_id => $item->biblionumber,
4467 item_id => $item->itemnumber,
4469 pickup_library_id => $patron1->branchcode,
4473 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4474 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed an item-level recall on this item" );
4476 $recall->set_cancelled;
4478 # biblio-level recall
4479 $recall = Koha::Recall->new(
4480 { patron_id => $patron1->borrowernumber,
4481 biblio_id => $item->biblionumber,
4484 pickup_library_id => $patron1->branchcode,
4488 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4489 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed a biblio-level recall and this item is eligible to fill it" );
4491 $recall->set_cancelled;
4493 # biblio-level recall
4494 $recall = Koha::Recall->new(
4495 { patron_id => $patron1->borrowernumber,
4496 biblio_id => $item->biblionumber,
4499 pickup_library_id => $patron1->branchcode,
4502 $recall->set_waiting( { item => $item, expirationdate => dt_from_string() } );
4504 my ( undef, undef, undef, $messages ) = CanBookBeIssued( $patron1, $item->barcode, undef, undef, undef, undef );
4505 is( $messages->{RECALLED}, $recall->id, "This book can be issued by this patron and they have placed a recall" );
4507 $recall->set_cancelled;
4510 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
4513 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
4514 my $item = $builder->build_sample_item(
4516 onloan => '2018-01-01',
4520 AddReturn( $item->barcode, $item->homebranch );
4521 $item->discard_changes; # refresh
4522 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
4525 subtest 'AddReturn | recalls' => sub {
4528 t::lib::Mocks::mock_preference("UseRecalls", 1);
4529 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4530 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4531 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4532 my $item1 = $builder->build_sample_item;
4533 Koha::CirculationRules->set_rules({
4534 branchcode => undef,
4536 categorycode => undef,
4538 recalls_allowed => 10,
4542 # this item can fill a recall with pickup at this branch
4543 AddIssue( $patron1, $item1->barcode );
4544 my $recall1 = Koha::Recall->new(
4545 { patron_id => $patron2->borrowernumber,
4546 biblio_id => $item1->biblionumber,
4547 item_id => $item1->itemnumber,
4549 pickup_library_id => $item1->homebranch,
4552 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4553 is( $messages->{RecallFound}->id, $recall1->id, "Recall found" );
4554 $recall1->set_cancelled;
4556 # this item can fill a recall but needs transfer
4557 AddIssue( $patron1, $item1->barcode );
4558 $recall1 = Koha::Recall->new(
4559 { patron_id => $patron2->borrowernumber,
4560 biblio_id => $item1->biblionumber,
4561 item_id => $item1->itemnumber,
4563 pickup_library_id => $patron2->branchcode,
4566 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4567 is( $messages->{RecallNeedsTransfer}, $item1->homebranch, "Recall requiring transfer found" );
4568 $recall1->set_cancelled;
4570 # this item is already in transit, do not ask to transfer
4571 AddIssue( $patron1, $item1->barcode );
4572 $recall1 = Koha::Recall->new(
4573 { patron_id => $patron2->borrowernumber,
4574 biblio_id => $item1->biblionumber,
4575 item_id => $item1->itemnumber,
4577 pickup_library_id => $patron2->branchcode,
4580 $recall1->start_transfer;
4581 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $patron2->branchcode );
4582 is( $messages->{TransferredRecall}->id, $recall1->id, "In transit recall found" );
4583 $recall1->set_cancelled;
4586 subtest 'AddReturn | bundles' => sub {
4589 my $schema = Koha::Database->schema;
4590 $schema->storage->txn_begin;
4592 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4593 my $host_item1 = $builder->build_sample_item;
4594 my $bundle_item1 = $builder->build_sample_item;
4595 $schema->resultset('ItemBundle')
4597 { host => $host_item1->itemnumber, item => $bundle_item1->itemnumber } );
4599 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $bundle_item1->barcode, $bundle_item1->homebranch );
4600 is($messages->{InBundle}->id, $host_item1->id, 'AddReturn returns InBundle host item when item is part of a bundle');
4602 $schema->storage->txn_rollback;
4605 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
4610 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4612 my $issuing_charges = 15;
4613 my $title = 'A title';
4614 my $author = 'Author, An';
4615 my $barcode = 'WHATARETHEODDS';
4617 my $circ = Test::MockModule->new('C4::Circulation');
4619 'GetIssuingCharges',
4621 return $issuing_charges;
4625 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4626 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
4627 my $patron = $builder->build_object({
4628 class => 'Koha::Patrons',
4629 value => { branchcode => $library->id }
4632 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
4633 my $item_id = Koha::Item->new(
4635 biblionumber => $biblio->biblionumber,
4636 homebranch => $library->id,
4637 holdingbranch => $library->id,
4638 barcode => $barcode,
4639 replacementprice => 23.00,
4640 itype => $itemtype->id
4642 )->store->itemnumber;
4643 my $item = Koha::Items->find( $item_id );
4645 my $context = Test::MockModule->new('C4::Context');
4646 $context->mock( userenv => { branch => $library->id } );
4648 # Check the item out
4649 AddIssue( $patron, $item->barcode );
4654 borrowernumber => $patron->borrowernumber,
4655 itemnumber => $item->itemnumber,
4656 branch => $library->id,
4657 lastreneweddate => { break => "the_renewal" }
4660 } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
4662 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
4663 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
4664 my %params_renewal = (
4665 timestamp => { -like => $date . "%" },
4666 module => "CIRCULATION",
4667 action => "RENEWAL",
4669 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
4672 borrowernumber => $patron->id,
4673 itemnumber => $item->id,
4674 branch => $library->id
4677 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4678 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
4680 my $checkouts = $patron->checkouts;
4681 # The following will fail if run on 00:00:00
4682 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
4684 my $lines = Koha::Account::Lines->search({
4685 borrowernumber => $patron->id,
4686 itemnumber => $item->id
4689 is( $lines->count, 2 );
4691 my $line = $lines->next;
4692 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
4693 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
4694 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
4696 $line = $lines->next;
4697 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
4698 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
4699 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
4701 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
4703 $context = Test::MockModule->new('C4::Context');
4704 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
4706 my $now = dt_from_string;
4707 $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
4708 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
4709 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
4710 $sth->execute($item->id, $library->id);
4711 my ($old_stats_size) = $sth->fetchrow_array;
4714 borrowernumber => $patron->id,
4715 itemnumber => $item->id,
4716 branch => $library->id
4719 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4720 $sth->execute($item->id, $library->id);
4721 my ($new_stats_size) = $sth->fetchrow_array;
4722 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
4723 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
4725 AddReturn( $item->id, $library->id, undef, $date );
4726 AddIssue( $patron, $item->barcode, $now );
4729 borrowernumber => $patron->id,
4730 itemnumber => $item->id,
4731 branch => $library->id,
4735 my $lines_skipped = Koha::Account::Lines->search({
4736 borrowernumber => $patron->id,
4737 itemnumber => $item->id
4739 is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
4743 subtest 'AddRenewal() adds to renewals' => sub {
4746 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4747 my $patron = $builder->build_object({
4748 class => 'Koha::Patrons',
4749 value => { branchcode => $library->id }
4752 my $item = $builder->build_sample_item();
4754 set_userenv( $library->unblessed );
4756 # Check the item out
4757 my $issue = AddIssue( $patron, $item->barcode );
4758 is(ref($issue), 'Koha::Checkout', 'Issue added');
4761 my $duedate = AddRenewal(
4763 borrowernumber => $patron->id,
4764 itemnumber => $item->id,
4765 branch => $library->id,
4770 ok( $duedate, "Renewal added" );
4772 my $renewals = Koha::Checkouts::Renewals->search({ checkout_id => $issue->issue_id });
4773 is($renewals->count, 1, 'One renewal added');
4774 my $THE_renewal = $renewals->next;
4775 is( $THE_renewal->renewer_id, C4::Context->userenv->{'number'}, 'Renewer recorded from context' );
4776 is( $THE_renewal->renewal_type, 'Automatic', 'AddRenewal "automatic" parameter sets renewal type to "Automatic"');
4779 subtest 'ProcessOfflinePayment() tests' => sub {
4786 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
4787 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4788 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
4790 is( $result, 'Success.', 'The right string is returned' );
4792 my $lines = $patron->account->lines;
4793 is( $lines->count, 1, 'line created correctly');
4795 my $line = $lines->next;
4796 is( $line->amount+0, $amount * -1, 'amount picked from params' );
4797 is( $line->branchcode, $library->id, 'branchcode set correctly' );
4801 subtest 'Incremented fee tests' => sub {
4804 my $dt = dt_from_string();
4805 Time::Fake->offset( $dt->epoch );
4807 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
4809 my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store;
4811 $module->mock( 'userenv', sub { { branch => $library->id } } );
4813 my $patron = $builder->build_object(
4815 class => 'Koha::Patrons',
4816 value => { categorycode => $patron_category->{categorycode} }
4820 my $itemtype = $builder->build_object(
4822 class => 'Koha::ItemTypes',
4824 notforloan => undef,
4826 rentalcharge_daily => 1,
4827 rentalcharge_daily_calendar => 0
4832 my $item = $builder->build_sample_item(
4834 library => $library->id,
4835 itype => $itemtype->id,
4839 is( $itemtype->rentalcharge_daily + 0,1, 'Daily rental charge stored and retreived correctly' );
4840 is( $item->effective_itemtype, $itemtype->id, "Itemtype set correctly for item" );
4842 my $now = dt_from_string;
4843 my $dt_from = $now->clone;
4844 my $dt_to = $now->clone->add( days => 7 );
4845 my $dt_to_renew = $now->clone->add( days => 13 );
4849 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4850 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4852 $accountline->amount + 0,
4854 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
4856 $accountline->delete();
4859 borrowernumber => $patron->id,
4860 itemnumber => $item->id,
4861 branch => $library->id,
4862 datedue => $dt_to_renew,
4863 lastreneweddate => $dt_to
4866 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4868 $accountline->amount + 0,
4870 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
4872 $accountline->delete();
4875 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
4876 $itemtype->rentalcharge_daily_calendar(1)->store();
4878 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4879 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4881 $accountline->amount + 0,
4883 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
4885 $accountline->delete();
4888 borrowernumber => $patron->id,
4889 itemnumber => $item->id,
4890 branch => $library->id,
4891 datedue => $dt_to_renew,
4892 lastreneweddate => $dt_to
4895 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4897 $accountline->amount + 0,
4899 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
4901 $accountline->delete();
4904 my $calendar = C4::Calendar->new( branchcode => $library->id );
4905 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
4907 ( $dt_from->day_of_week == 6 ) ? 0
4908 : ( $dt_from->day_of_week == 7 ) ? 1
4909 : $dt_from->day_of_week + 1;
4910 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
4911 $calendar->insert_week_day_holiday(
4912 weekday => $closed_day,
4913 title => 'Test holiday',
4914 description => 'Test holiday'
4917 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4918 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4920 $accountline->amount + 0,
4922 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
4924 $accountline->delete();
4927 borrowernumber => $patron->id,
4928 itemnumber => $item->id,
4929 branch => $library->id,
4930 datedue => $dt_to_renew,
4931 lastreneweddate => $dt_to
4934 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4936 $accountline->amount + 0,
4938 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
4940 $accountline->delete();
4943 $itemtype->rentalcharge(2)->store;
4944 is( $itemtype->rentalcharge + 0, 2, 'Rental charge updated and retreived correctly' );
4946 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4948 Koha::Account::Lines->search( { itemnumber => $item->id } );
4949 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly" );
4950 $accountlines->delete();
4953 borrowernumber => $patron->id,
4954 itemnumber => $item->id,
4955 branch => $library->id,
4956 datedue => $dt_to_renew,
4957 lastreneweddate => $dt_to
4960 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
4961 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly, for renewal" );
4962 $accountlines->delete();
4964 $itemtype->rentalcharge(0)->store;
4965 is( $itemtype->rentalcharge + 0, 0, 'Rental charge reset and retreived correctly' );
4968 Koha::CirculationRules->set_rule(
4970 categorycode => $patron->categorycode,
4971 itemtype => $itemtype->id,
4972 branchcode => $library->id,
4973 rule_name => 'lengthunit',
4974 rule_value => 'hours',
4978 $itemtype->rentalcharge_hourly('0.25')->store();
4979 is( $itemtype->rentalcharge_hourly, '0.25', 'Hourly rental charge stored and retreived correctly' );
4981 $dt_to = $now->clone->add( hours => 168 );
4982 $dt_to_renew = $now->clone->add( hours => 312 );
4984 $itemtype->rentalcharge_hourly_calendar(0)->store();
4986 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4987 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4989 $accountline->amount + 0,
4991 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)"
4993 $accountline->delete();
4996 borrowernumber => $patron->id,
4997 itemnumber => $item->id,
4998 branch => $library->id,
4999 datedue => $dt_to_renew,
5000 lastreneweddate => $dt_to
5003 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5005 $accountline->amount + 0,
5007 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)"
5009 $accountline->delete();
5012 $itemtype->rentalcharge_hourly_calendar(1)->store();
5014 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
5015 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5017 $accountline->amount + 0,
5019 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)"
5021 $accountline->delete();
5024 borrowernumber => $patron->id,
5025 itemnumber => $item->id,
5026 branch => $library->id,
5027 datedue => $dt_to_renew,
5028 lastreneweddate => $dt_to
5031 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5033 $accountline->amount + 0,
5035 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u"
5037 $accountline->delete();
5040 $calendar->delete_holiday( weekday => $closed_day );
5042 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
5043 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5045 $accountline->amount + 0,
5047 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u"
5049 $accountline->delete();
5052 borrowernumber => $patron->id,
5053 itemnumber => $item->id,
5054 branch => $library->id,
5055 datedue => $dt_to_renew,
5056 lastreneweddate => $dt_to
5059 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
5061 $accountline->amount + 0,
5063 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)"
5065 $accountline->delete();
5070 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
5073 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
5074 t::lib::Mocks::mock_preference('item-level_itypes', 1);
5077 $builder->build_object( { class => 'Koha::Libraries' } )->store;
5078 my $patron = $builder->build_object(
5080 class => 'Koha::Patrons',
5081 value => { categorycode => $patron_category->{categorycode} }
5085 my $itemtype = $builder->build_object(
5087 class => 'Koha::ItemTypes',
5091 rentalcharge_daily => 0
5096 my $item = $builder->build_sample_item(
5098 library => $library->id,
5102 itype => $itemtype->id,
5106 my ( $issuingimpossible, $needsconfirmation );
5107 my $dt_from = dt_from_string();
5108 my $dt_due = $dt_from->clone->add( days => 3 );
5110 $itemtype->rentalcharge(1)->store;
5111 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
5112 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
5113 $itemtype->rentalcharge('0')->store;
5114 $itemtype->rentalcharge_daily(1)->store;
5115 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
5116 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
5117 $itemtype->rentalcharge_daily('0')->store;
5120 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
5123 t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
5125 my $patron = $builder->build_object(
5127 class => 'Koha::Patrons',
5128 value => { categorycode => $patron_category->{categorycode} }
5132 my $item = $builder->build_sample_item(
5134 materials => 'includes DVD',
5138 my $dt_due = dt_from_string->add( days => 3 );
5140 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
5141 is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
5144 subtest 'Do not return on renewal (LOST charge)' => sub {
5147 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
5148 my $library = $builder->build_object( { class => "Koha::Libraries" } );
5149 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
5150 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
5152 my $biblio = $builder->build_sample_biblio;
5154 my $item = $builder->build_sample_item(
5156 biblionumber => $biblio->biblionumber,
5157 library => $library->branchcode,
5158 replacementprice => 99.00,
5163 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
5164 AddIssue( $patron, $item->barcode );
5166 my $accountline = Koha::Account::Line->new(
5168 borrowernumber => $patron->borrowernumber,
5169 debit_type_code => 'LOST',
5171 itemnumber => $item->itemnumber,
5173 amountoutstanding => 12,
5174 interface => 'something',
5178 # AddRenewal doesn't call _FixAccountForLostAndFound
5179 AddIssue( $patron, $item->barcode );
5181 is( $patron->checkouts->count, 1,
5182 'Renewal should not return the item even if a LOST payment has been made earlier'
5186 subtest 'Filling a hold should cancel existing transfer' => sub {
5189 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
5191 my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
5192 my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
5193 my $patron = $builder->build_object(
5195 class => 'Koha::Patrons',
5197 categorycode => $patron_category->{categorycode},
5198 branchcode => $libraryA->branchcode,
5203 my $item = $builder->build_sample_item({
5204 homebranch => $libraryB->branchcode,
5207 my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
5208 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
5210 branchcode => $libraryA->branchcode,
5211 borrowernumber => $patron->borrowernumber,
5212 biblionumber => $item->biblionumber,
5213 itemnumber => $item->itemnumber
5215 my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
5216 is( $reserves->count, 1, "Reserve is placed");
5217 ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
5218 my $reserve = $reserves->next;
5219 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
5220 $reserve->discard_changes;
5221 ok( $reserve->found eq 'W', "Reserve is marked waiting" );
5222 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
5225 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
5229 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
5230 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5231 my $patron = $builder->build_object(
5233 class => 'Koha::Patrons',
5234 value => { categorycode => $patron_category->{categorycode} }
5238 my $biblionumber = $builder->build_sample_biblio(
5240 branchcode => $library->branchcode,
5244 # And the circulation rule
5245 Koha::CirculationRules->search->delete;
5246 Koha::CirculationRules->set_rules(
5248 categorycode => undef,
5250 branchcode => undef,
5253 lengthunit => 'days',
5259 source => 'CirculationRule',
5261 branchcode => undef,
5262 categorycode => undef,
5264 rule_name => 'lostreturn',
5265 rule_value => 'refund'
5270 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5273 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5274 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5276 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5278 my $item = $builder->build_sample_item(
5280 biblionumber => $biblionumber,
5281 library => $library->branchcode,
5282 replacementprice => '42',
5285 my $issue = AddIssue( $patron, $item->barcode );
5286 LostItem( $item->itemnumber, 'cli', 0 );
5287 $item->_result->itemlost(1);
5288 $item->_result->itemlost_on( $lost_on );
5289 $item->_result->update();
5291 my $a = Koha::Account::Lines->search(
5293 itemnumber => $item->id,
5294 borrowernumber => $patron->borrowernumber
5297 ok( $a, "Found accountline for lost fee" );
5298 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5299 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5300 $a = $a->get_from_storage;
5301 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5305 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5308 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5309 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5311 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5313 my $item = $builder->build_sample_item(
5315 biblionumber => $biblionumber,
5316 library => $library->branchcode,
5317 replacementprice => '42',
5320 my $issue = AddIssue( $patron, $item->barcode );
5321 LostItem( $item->itemnumber, 'cli', 0 );
5322 $item->_result->itemlost(1);
5323 $item->_result->itemlost_on( $lost_on );
5324 $item->_result->update();
5326 my $a = Koha::Account::Lines->search(
5328 itemnumber => $item->id,
5329 borrowernumber => $patron->borrowernumber
5332 ok( $a, "Found accountline for lost fee" );
5333 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5334 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5335 $a = $a->get_from_storage;
5336 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5340 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5343 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5344 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5346 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5348 my $item = $builder->build_sample_item(
5350 biblionumber => $biblionumber,
5351 library => $library->branchcode,
5352 replacementprice => '42',
5355 my $issue = AddIssue( $patron, $item->barcode );
5356 LostItem( $item->itemnumber, 'cli', 0 );
5357 $item->_result->itemlost(1);
5358 $item->_result->itemlost_on( $lost_on );
5359 $item->_result->update();
5361 my $a = Koha::Account::Lines->search(
5363 itemnumber => $item->id,
5364 borrowernumber => $patron->borrowernumber
5367 ok( $a, "Found accountline for lost fee" );
5368 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5369 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5370 $a = $a->get_from_storage;
5371 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5375 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5378 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5379 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5381 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5383 my $item = $builder->build_sample_item(
5385 biblionumber => $biblionumber,
5386 library => $library->branchcode,
5387 replacementprice => '42',
5390 my $issue = AddIssue( $patron, $item->barcode );
5391 LostItem( $item->itemnumber, 'cli', 0 );
5392 $item->_result->itemlost(1);
5393 $item->_result->itemlost_on( $lost_on );
5394 $item->_result->update();
5396 my $a = Koha::Account::Lines->search(
5398 itemnumber => $item->id,
5399 borrowernumber => $patron->borrowernumber
5403 ok( $a, "Found accountline for lost fee" );
5404 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5405 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5406 $a = $a->get_from_storage;
5407 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5412 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
5416 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
5417 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5418 my $patron = $builder->build_object(
5420 class => 'Koha::Patrons',
5421 value => { categorycode => $patron_category->{categorycode} }
5424 my $patron2 = $builder->build_object(
5426 class => 'Koha::Patrons',
5427 value => { categorycode => $patron_category->{categorycode} }
5431 my $biblionumber = $builder->build_sample_biblio(
5433 branchcode => $library->branchcode,
5437 # And the circulation rule
5438 Koha::CirculationRules->search->delete;
5439 Koha::CirculationRules->set_rules(
5441 categorycode => undef,
5443 branchcode => undef,
5446 lengthunit => 'days',
5452 source => 'CirculationRule',
5454 branchcode => undef,
5455 categorycode => undef,
5457 rule_name => 'lostreturn',
5458 rule_value => 'refund'
5463 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5466 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5467 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5469 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5471 my $item = $builder->build_sample_item(
5473 biblionumber => $biblionumber,
5474 library => $library->branchcode,
5475 replacementprice => '42',
5478 my $issue = AddIssue( $patron, $item->barcode );
5479 LostItem( $item->itemnumber, 'cli', 0 );
5480 $item->_result->itemlost(1);
5481 $item->_result->itemlost_on( $lost_on );
5482 $item->_result->update();
5484 my $a = Koha::Account::Lines->search(
5486 itemnumber => $item->id,
5487 borrowernumber => $patron->borrowernumber
5490 ok( $a, "Found accountline for lost fee" );
5491 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5492 $issue = AddIssue( $patron2, $item->barcode );
5493 $a = $a->get_from_storage;
5494 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5499 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5502 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5503 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5505 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5507 my $item = $builder->build_sample_item(
5509 biblionumber => $biblionumber,
5510 library => $library->branchcode,
5511 replacementprice => '42',
5514 my $issue = AddIssue( $patron, $item->barcode );
5515 LostItem( $item->itemnumber, 'cli', 0 );
5516 $item->_result->itemlost(1);
5517 $item->_result->itemlost_on( $lost_on );
5518 $item->_result->update();
5520 my $a = Koha::Account::Lines->search(
5522 itemnumber => $item->id,
5523 borrowernumber => $patron->borrowernumber
5526 ok( $a, "Found accountline for lost fee" );
5527 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5528 $issue = AddIssue( $patron2, $item->barcode );
5529 $a = $a->get_from_storage;
5530 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5534 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5537 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5538 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5540 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5542 my $item = $builder->build_sample_item(
5544 biblionumber => $biblionumber,
5545 library => $library->branchcode,
5546 replacementprice => '42',
5549 my $issue = AddIssue( $patron, $item->barcode );
5550 LostItem( $item->itemnumber, 'cli', 0 );
5551 $item->_result->itemlost(1);
5552 $item->_result->itemlost_on( $lost_on );
5553 $item->_result->update();
5555 my $a = Koha::Account::Lines->search(
5557 itemnumber => $item->id,
5558 borrowernumber => $patron->borrowernumber
5561 ok( $a, "Found accountline for lost fee" );
5562 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5563 $issue = AddIssue( $patron2, $item->barcode );
5564 $a = $a->get_from_storage;
5565 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5569 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5572 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5573 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5575 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5577 my $item = $builder->build_sample_item(
5579 biblionumber => $biblionumber,
5580 library => $library->branchcode,
5581 replacementprice => '42',
5584 my $issue = AddIssue( $patron, $item->barcode );
5585 LostItem( $item->itemnumber, 'cli', 0 );
5586 $item->_result->itemlost(1);
5587 $item->_result->itemlost_on( $lost_on );
5588 $item->_result->update();
5590 my $a = Koha::Account::Lines->search(
5592 itemnumber => $item->id,
5593 borrowernumber => $patron->borrowernumber
5597 ok( $a, "Found accountline for lost fee" );
5598 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5599 $issue = AddIssue( $patron2, $item->barcode );
5600 $a = $a->get_from_storage;
5601 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5606 subtest 'transferbook tests' => sub {
5610 { C4::Circulation::transferbook({}); }
5611 'Koha::Exceptions::MissingParameter',
5612 'Koha::Patron->store raises an exception on missing params';
5615 { C4::Circulation::transferbook({to_branch=>'anything'}); }
5616 'Koha::Exceptions::MissingParameter',
5617 'Koha::Patron->store raises an exception on missing params';
5620 { C4::Circulation::transferbook({from_branch=>'anything'}); }
5621 'Koha::Exceptions::MissingParameter',
5622 'Koha::Patron->store raises an exception on missing params';
5624 my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
5625 is( $doreturn, 0, "No return without barcode");
5626 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5627 is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
5629 ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
5630 is( $doreturn, 0, "No return without barcode");
5631 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5632 is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
5636 subtest 'Checkout should correctly terminate a transfer' => sub {
5639 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5640 my $patron_1 = $builder->build_object(
5642 class => 'Koha::Patrons',
5643 value => { branchcode => $library_1->branchcode }
5646 my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
5647 my $patron_2 = $builder->build_object(
5649 class => 'Koha::Patrons',
5650 value => { branchcode => $library_2->branchcode }
5654 my $item = $builder->build_sample_item(
5656 library => $library_1->branchcode,
5660 t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
5661 my $reserve_id = AddReserve(
5663 branchcode => $library_2->branchcode,
5664 borrowernumber => $patron_2->borrowernumber,
5665 biblionumber => $item->biblionumber,
5666 itemnumber => $item->itemnumber,
5671 my $do_transfer = 1;
5672 ModItemTransfer( $item->itemnumber, $library_1->branchcode,
5673 $library_2->branchcode, 'Manual' );
5674 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
5675 GetOtherReserves( $item->itemnumber )
5676 ; # To put the Reason, it's what does returns.pl...
5677 my $hold = Koha::Holds->find($reserve_id);
5678 is( $hold->found, 'T', 'Hold is in transit' );
5679 my $transfer = $item->get_transfer;
5680 is( $transfer->frombranch, $library_1->branchcode );
5681 is( $transfer->tobranch, $library_2->branchcode );
5682 is( $transfer->reason, 'Reserve' );
5684 t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
5685 AddIssue( $patron_1, $item->barcode );
5686 $transfer = $transfer->get_from_storage;
5687 isnt( $transfer->datearrived, undef );
5688 $hold = $hold->get_from_storage;
5689 is( $hold->found, undef, 'Hold is waiting' );
5690 is( $hold->priority, 1, );
5693 subtest 'AddIssue records staff who checked out item if appropriate' => sub {
5696 $module->mock( 'userenv', sub { { branch => $library->{id} } } );
5698 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5699 my $patron = $builder->build_object(
5701 class => 'Koha::Patrons',
5702 value => { categorycode => $patron_category->{categorycode} }
5705 my $issuer = $builder->build_object(
5707 class => 'Koha::Patrons',
5708 value => { categorycode => $patron_category->{categorycode} }
5711 my $item_1 = $builder->build_sample_item(
5713 library => $library->{branchcode}
5717 my $item_2 = $builder->build_sample_item(
5719 library => $library->branchcode
5723 $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->borrowernumber } } );
5725 my $dt_from = dt_from_string();
5726 my $dt_to = dt_from_string()->add( days => 7 );
5728 my $issue_1 = AddIssue( $patron, $item_1->barcode, $dt_to, undef, $dt_from );
5730 is( $issue_1->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
5732 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
5735 AddIssue( $patron, $item_2->barcode, $dt_to, undef, $dt_from );
5737 is( $issue_2->issuer->borrowernumber, $issuer->borrowernumber, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
5740 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
5743 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5744 my $patron_1 = $builder->build_object(
5746 class => 'Koha::Patrons',
5747 value => { branchcode => $library_1->branchcode }
5750 my $patron_2 = $builder->build_object(
5752 class => 'Koha::Patrons',
5753 value => { branchcode => $library_1->branchcode }
5757 my $item = $builder->build_sample_item(
5759 library => $library_1->branchcode,
5763 AddIssue( $patron_1, $item->barcode );
5764 ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
5765 AddIssue( $patron_2, $item->barcode );
5766 ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
5769 subtest "updateWrongTransfer tests" => sub {
5772 my $library1 = $builder->build_object( { class => 'Koha::Libraries' } );
5773 my $library2 = $builder->build_object( { class => 'Koha::Libraries' } );
5774 my $library3 = $builder->build_object( { class => 'Koha::Libraries' } );
5775 my $item = $builder->build_sample_item(
5777 homebranch => $library1->branchcode,
5778 holdingbranch => $library2->branchcode,
5779 datelastseen => undef
5783 my $transfer = $builder->build_object(
5785 class => 'Koha::Item::Transfers',
5787 itemnumber => $item->itemnumber,
5788 frombranch => $library2->branchcode,
5789 tobranch => $library1->branchcode,
5790 daterequested => dt_from_string,
5791 datesent => dt_from_string,
5792 datecancelled => undef,
5793 datearrived => undef,
5798 is( ref($transfer), 'Koha::Item::Transfer', 'Mock transfer added' );
5800 my $new_transfer = C4::Circulation::updateWrongTransfer($item->itemnumber, $library1->branchcode);
5801 is(ref($new_transfer), 'Koha::Item::Transfer', "updateWrongTransfer returns a 'Koha::Item::Transfer' object");
5802 ok( !$new_transfer->in_transit, "New transfer is NOT created as in transit (or cancelled)");
5804 my $original_transfer = $transfer->get_from_storage;
5805 ok( defined($original_transfer->datecancelled), "Original transfer was cancelled");
5806 is( $original_transfer->cancellation_reason, 'WrongTransfer', "Original transfer cancellation reason is 'WrongTransfer'");
5809 subtest "SendCirculationAlert" => sub {
5812 # When you would unsuspectingly call this unit test (with perl, not prove), you will be bitten by LOCK.
5813 # LOCK will commit changes and ruin your data
5814 # In order to prevent that, we will add KOHA_TESTING to $ENV; see further Circulation.pm
5815 $ENV{KOHA_TESTING} = 1;
5817 # Setup branch, borrowr, and notice
5818 my $library = $builder->build_object({ class => 'Koha::Libraries' });
5819 set_userenv( $library->unblessed);
5820 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5821 C4::Members::Messaging::SetMessagingPreference({
5822 borrowernumber => $patron->id,
5823 message_transport_types => ['sms'],
5824 message_attribute_id => 5
5826 my $item = $builder->build_sample_item();
5827 my $checkin_notice = $builder->build_object({
5828 class => 'Koha::Notice::Templates',
5830 module => 'circulation',
5832 branchcode => $library->branchcode,
5833 name => 'Test Checkin',
5835 content => "Checkins:\n----\n[% biblio.title %]-[% old_checkout.issue_id %]\n----Thank you.",
5836 message_transport_type => 'sms',
5841 # Checkout an item, mark it returned, generate a notice
5842 my $issue_1 = AddIssue( $patron, $item->barcode);
5843 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5844 C4::Circulation::SendCirculationAlert({
5846 item => $item->unblessed,
5847 borrower => $patron->unblessed,
5848 branch => $library->branchcode,
5851 my $notice = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'CHECKIN' });
5852 is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\nThank you.", 'Letter generated with expected output on first checkin' );
5853 is($notice->to_address, $patron->smsalertnumber, "Letter has the correct to_address set to smsalertnumber for SMS type notices");
5855 # Checkout an item, mark it returned, generate a notice
5856 my $issue_2 = AddIssue( $patron, $item->barcode);
5857 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5858 C4::Circulation::SendCirculationAlert({
5860 item => $item->unblessed,
5861 borrower => $patron->unblessed,
5862 branch => $library->branchcode,
5865 $notice->discard_changes();
5866 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' );
5870 subtest "GetSoonestRenewDate tests" => sub {
5872 Koha::CirculationRules->set_rule(
5874 categorycode => undef,
5875 branchcode => undef,
5877 rule_name => 'norenewalbefore',
5881 my $patron = $builder->build_object(
5883 class => 'Koha::Patrons',
5885 autorenew_checkouts => 1,
5889 my $item = $builder->build_sample_item();
5890 my $issue = AddIssue( $patron, $item->barcode);
5891 my $datedue = dt_from_string( $issue->date_due() );
5894 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
5895 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
5897 GetSoonestRenewDate( $patron, $issue ),
5898 $datedue->clone->add( days => -7 ),
5899 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5903 # Test 'date' setting for syspref NoRenewalBeforePrecision
5904 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5906 GetSoonestRenewDate( $patron, $issue ),
5907 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
5908 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5912 Koha::CirculationRules->set_rule(
5914 categorycode => undef,
5915 branchcode => undef,
5917 rule_name => 'norenewalbefore',
5918 rule_value => undef,
5923 GetSoonestRenewDate( $patron, $issue ),
5925 'Checkouts without auto-renewal can be renewed immediately if no norenewalbefore'
5928 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5929 $issue->auto_renew(1)->store;
5931 GetSoonestRenewDate( $patron, $issue, 1 ),
5932 $datedue->clone->truncate( to => 'day' ),
5933 'Checkouts with auto-renewal can be renewed earliest on due date if noautorenewalbefore'
5935 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact' );
5937 GetSoonestRenewDate( $patron, $issue, 1 ),
5939 'Checkouts with auto-renewal can be renewed earliest on due date if noautorenewalbefore'
5942 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5943 Koha::CirculationRules->set_rule(
5945 categorycode => undef,
5946 branchcode => undef,
5948 rule_name => 'norenewalbefore',
5952 $issue->date_due(dt_from_string)->store;
5954 GetSoonestRenewDate( $patron, $issue ),
5955 dt_from_string->subtract( days => 1 )->truncate( to => 'day' ),
5956 'Checkouts with auto-renewal can be renewed 1 day before due date if no renewalbefore = 1 and precision = "date"'
5961 subtest "CanBookBeIssued + needsconfirmation message" => sub {
5964 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
5965 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5966 my $biblio = $builder->build_object({ class => 'Koha::Biblios' });
5967 my $biblioitem = $builder->build_object({ class => 'Koha::Biblioitems', value => { biblionumber => $biblio->biblionumber }});
5968 my $item = $builder->build_object({ class => 'Koha::Items' , value => { itype => $itemtype, biblionumber => $biblio->biblionumber }});
5970 my $hold = $builder->build_object({ class => 'Koha::Holds', value => {
5971 biblionumber => $item->biblionumber,
5972 branchcode => $library->branchcode,
5973 itemnumber => undef,
5978 item_group_id => undef
5981 my ( $error, $needsconfirmation, $alerts, $messages );
5983 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5984 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold exists.");
5986 $hold->priority(0)->store();
5988 $hold->found("W")->store();
5989 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5990 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is waiting.");
5992 $hold->found("T")->store();
5993 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5994 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is being transferred.");
5996 $hold->found("P")->store();
5997 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5998 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is being processed.");
6001 subtest 'Tests for BlockReturnOfWithdrawnItems' => sub {
6005 t::lib::Mocks::mock_preference('BlockReturnOfWithdrawnItems', 1);
6006 t::lib::Mocks::mock_preference('RecordLocalUseOnReturn', 0);
6007 my $item = $builder->build_sample_item();
6008 $item->withdrawn(1)->itemlost(1)->store;
6009 my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef );
6012 [ 0, { NotIssued => $item->barcode, withdrawn => 1 }, undef, {} ], "Item returned as withdrawn, no other messages");
6015 subtest 'Tests for transfer not in transit' => sub {
6020 # These tests are to ensure a 'pending' transfer, generated by
6021 # stock rotation, will be advanced when checked in
6023 my $item = $builder->build_sample_item();
6024 my $transfer = $builder->build_object({ class => 'Koha::Item::Transfers', value => {
6025 itemnumber => $item->id,
6026 reason => 'StockrotationRepatriation',
6028 frombranch => $item->homebranch,
6030 my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef );
6033 [ 0, { WasTransfered => $transfer->tobranch, TransferTrigger => 'StockrotationRepatriation', NotIssued => $item->barcode }, undef, {} ], "Item is reported to have been transferred");
6035 $transfer->discard_changes;
6036 ok( $transfer->datesent, 'The datesent field is populated, i.e. transfer is initiated');
6040 subtest 'Tests for RecordLocalUseOnReturn' => sub {
6044 t::lib::Mocks::mock_preference('RecordLocalUseOnReturn', 0);
6045 my $item = $builder->build_sample_item();
6046 $item->withdrawn(1)->itemlost(1)->store;
6047 my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef );
6050 [ 0, { NotIssued => $item->barcode, withdrawn => 1 }, undef, {} ], "RecordLocalUSeOnReturn is off, no local use recorded");
6052 t::lib::Mocks::mock_preference('RecordLocalUseOnReturn', 1);
6053 my @return2 = AddReturn( $item->barcode, $item->homebranch, 0, undef );
6056 [ 0, { NotIssued => $item->barcode, withdrawn => 1, LocalUse => 1 }, undef, {} ], "Local use is recorded");
6059 $schema->storage->txn_rollback;
6060 C4::Context->clear_syspref_cache();
6061 $branches = Koha::Libraries->search();
6062 for my $branch ( $branches->next ) {
6063 my $key = $branch->branchcode . "_holidays";
6064 $cache->clear_from_cache($key);