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 => 54;
24 use Test::Deep qw( cmp_deeply );
30 use POSIX qw( floor );
32 use t::lib::TestBuilder;
41 use C4::Overdues qw(UpdateFine CalcFine);
45 use Koha::Item::Transfers;
49 use Koha::CirculationRules;
50 use Koha::Subscriptions;
51 use Koha::Account::Lines;
52 use Koha::Account::Offsets;
57 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
61 my ( $error, $question, $alert ) = @_;
63 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
64 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
65 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
69 sub test_debarment_on_checkout {
71 my $item = $params->{item};
72 my $library = $params->{library};
73 my $patron = $params->{patron};
74 my $due_date = $params->{due_date} || dt_from_string;
75 my $return_date = $params->{return_date} || dt_from_string;
76 my $expected_expiration_date = $params->{expiration_date};
78 $expected_expiration_date = output_pref(
80 dt => $expected_expiration_date,
86 my $line_number = $caller[2];
87 AddIssue( $patron, $item->barcode, $due_date );
89 my ( undef, $message ) = AddReturn( $item->barcode, $library->{branchcode}, undef, $return_date );
90 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
91 or diag('AddReturn returned message ' . Dumper $message );
92 my $debarments = Koha::Patron::Debarments::GetDebarments(
93 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
94 is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
96 is( $debarments->[0]->{expiration},
97 $expected_expiration_date, 'Test at line ' . $line_number );
98 Koha::Patron::Debarments::DelUniqueDebarment(
99 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
102 my $schema = Koha::Database->schema;
103 $schema->storage->txn_begin;
104 my $builder = t::lib::TestBuilder->new;
105 my $dbh = C4::Context->dbh;
107 # Prevent random failures by mocking ->now
108 my $now_value = dt_from_string;
109 my $mocked_datetime = Test::MockModule->new('DateTime');
110 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
112 my $cache = Koha::Caches->get_instance();
113 $dbh->do(q|DELETE FROM special_holidays|);
114 $dbh->do(q|DELETE FROM repeatable_holidays|);
115 my $branches = Koha::Libraries->search();
116 for my $branch ( $branches->next ) {
117 my $key = $branch->branchcode . "_holidays";
118 $cache->clear_from_cache($key);
121 # Start with a clean slate
122 $dbh->do('DELETE FROM issues');
123 $dbh->do('DELETE FROM borrowers');
125 # Disable recording of the staff who checked out an item until we're ready for it
126 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 0);
128 my $module = Test::MockModule->new('C4::Context');
130 my $library = $builder->build({
133 my $library2 = $builder->build({
136 my $itemtype = $builder->build(
138 source => 'Itemtype',
142 rentalcharge_daily => 0,
143 defaultreplacecost => undef,
148 my $patron_category = $builder->build(
150 source => 'Category',
152 category_type => 'P',
154 BlockExpiredPatronOpacActions => -1, # Pick the pref value
159 my $CircControl = C4::Context->preference('CircControl');
160 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
163 homebranch => $library2->{branchcode},
164 holdingbranch => $library2->{branchcode}
168 branchcode => $library2->{branchcode}
171 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
173 # No userenv, PickupLibrary
174 t::lib::Mocks::mock_preference('IndependentBranches', '0');
175 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
177 C4::Context->preference('CircControl'),
179 'CircControl changed to PickupLibrary'
182 C4::Circulation::_GetCircControlBranch($item, $borrower),
183 $item->{$HomeOrHoldingBranch},
184 '_GetCircControlBranch returned item branch (no userenv defined)'
187 # No userenv, PatronLibrary
188 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
190 C4::Context->preference('CircControl'),
192 'CircControl changed to PatronLibrary'
195 C4::Circulation::_GetCircControlBranch($item, $borrower),
196 $borrower->{branchcode},
197 '_GetCircControlBranch returned borrower branch'
200 # No userenv, ItemHomeLibrary
201 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
203 C4::Context->preference('CircControl'),
205 'CircControl changed to ItemHomeLibrary'
208 $item->{$HomeOrHoldingBranch},
209 C4::Circulation::_GetCircControlBranch($item, $borrower),
210 '_GetCircControlBranch returned item branch'
214 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
215 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
217 # Userenv set, PickupLibrary
218 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
220 C4::Context->preference('CircControl'),
222 'CircControl changed to PickupLibrary'
225 C4::Circulation::_GetCircControlBranch($item, $borrower),
226 $library2->{branchcode},
227 '_GetCircControlBranch returned current branch'
230 # Userenv set, PatronLibrary
231 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
233 C4::Context->preference('CircControl'),
235 'CircControl changed to PatronLibrary'
238 C4::Circulation::_GetCircControlBranch($item, $borrower),
239 $borrower->{branchcode},
240 '_GetCircControlBranch returned borrower branch'
243 # Userenv set, ItemHomeLibrary
244 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
246 C4::Context->preference('CircControl'),
248 'CircControl changed to ItemHomeLibrary'
251 C4::Circulation::_GetCircControlBranch($item, $borrower),
252 $item->{$HomeOrHoldingBranch},
253 '_GetCircControlBranch returned item branch'
256 # Reset initial configuration
257 t::lib::Mocks::mock_preference('CircControl', $CircControl);
259 C4::Context->preference('CircControl'),
261 'CircControl reset to its initial value'
264 # Set a simple circ policy
265 $dbh->do('DELETE FROM circulation_rules');
266 Koha::CirculationRules->set_rules(
268 categorycode => undef,
272 reservesallowed => 25,
274 lengthunit => 'days',
275 renewalsallowed => 1,
277 norenewalbefore => undef,
285 subtest "CanBookBeRenewed AllowRenewalIfOtherItemsAvailable multiple borrowers and items tests" => sub {
288 #Can only reserve from home branch
289 Koha::CirculationRules->set_rule(
293 rule_name => 'holdallowed',
297 Koha::CirculationRules->set_rule(
300 categorycode => undef,
302 rule_name => 'onshelfholds',
307 # Patrons from three different branches
308 my $patron_borrower = $builder->build_object({ class => 'Koha::Patrons' });
309 my $patron_hold_1 = $builder->build_object({ class => 'Koha::Patrons' });
310 my $patron_hold_2 = $builder->build_object({ class => 'Koha::Patrons' });
311 my $biblio = $builder->build_sample_biblio();
313 # Item at each patron branch
314 my $item_1 = $builder->build_sample_item({
315 biblionumber => $biblio->biblionumber,
316 homebranch => $patron_borrower->branchcode
318 my $item_2 = $builder->build_sample_item({
319 biblionumber => $biblio->biblionumber,
320 homebranch => $patron_hold_2->branchcode
322 my $item_3 = $builder->build_sample_item({
323 biblionumber => $biblio->biblionumber,
324 homebranch => $patron_hold_1->branchcode
327 my $issue = AddIssue( $patron_borrower->unblessed, $item_1->barcode);
328 my $datedue = dt_from_string( $issue->date_due() );
329 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
334 branchcode => $patron_hold_1->branchcode,
335 borrowernumber => $patron_hold_1->borrowernumber,
336 biblionumber => $biblio->biblionumber,
338 reservation_date => dt_from_string(),
339 expiration_date => undef,
346 branchcode => $patron_hold_2->branchcode,
347 borrowernumber => $patron_hold_2->borrowernumber,
348 biblionumber => $biblio->biblionumber,
350 reservation_date => dt_from_string(),
351 expiration_date => undef,
356 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
358 my ( $renewokay, $error ) = CanBookBeRenewed($patron_borrower->borrowernumber, $item_1->itemnumber);
359 is( $renewokay, 0, 'Cannot renew, reserved');
360 is( $error, 'on_reserve', 'Cannot renew, reserved (returned error is on_reserve)');
362 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
364 ( $renewokay, $error ) = CanBookBeRenewed($patron_borrower->borrowernumber, $item_1->itemnumber);
365 is( $renewokay, 1, 'Can renew, two items available for two holds');
366 is( $error, undef, 'Can renew, each reserve has an item');
371 subtest "GetIssuingCharges tests" => sub {
373 my $branch_discount = $builder->build_object({ class => 'Koha::Libraries' });
374 my $branch_no_discount = $builder->build_object({ class => 'Koha::Libraries' });
375 Koha::CirculationRules->set_rule(
377 categorycode => undef,
378 branchcode => $branch_discount->branchcode,
380 rule_name => 'rentaldiscount',
384 my $itype_charge = $builder->build_object({
385 class => 'Koha::ItemTypes',
390 my $itype_no_charge = $builder->build_object({
391 class => 'Koha::ItemTypes',
396 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
397 my $item_1 = $builder->build_sample_item({ itype => $itype_charge->itemtype });
398 my $item_2 = $builder->build_sample_item({ itype => $itype_no_charge->itemtype });
400 t::lib::Mocks::mock_userenv({ branchcode => $branch_no_discount->branchcode });
401 # For now the sub always uses the env branch, this should follow CircControl instead
402 my ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
403 is( $charge + 0, 10.00, "Charge fetched correctly when no discount exists");
404 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
405 is( $charge + 0, 0.00, "Charge fetched correctly when no discount exists and no charge");
407 t::lib::Mocks::mock_userenv({ branchcode => $branch_discount->branchcode });
408 # For now the sub always uses the env branch, this should follow CircControl instead
409 ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
410 is( $charge + 0, 8.50, "Charge fetched correctly when discount exists");
411 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
412 is( $charge + 0, 0.00, "Charge fetched correctly when discount exists and no charge");
416 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
417 subtest "CanBookBeRenewed tests" => sub {
420 C4::Context->set_preference('ItemsDeniedRenewal','');
421 # Generate test biblio
422 my $biblio = $builder->build_sample_biblio();
424 my $branch = $library2->{branchcode};
426 my $item_1 = $builder->build_sample_item(
428 biblionumber => $biblio->biblionumber,
430 replacementprice => 12.00,
434 $reused_itemnumber_1 = $item_1->itemnumber;
436 my $item_2 = $builder->build_sample_item(
438 biblionumber => $biblio->biblionumber,
440 replacementprice => 23.00,
444 $reused_itemnumber_2 = $item_2->itemnumber;
446 my $item_3 = $builder->build_sample_item(
448 biblionumber => $biblio->biblionumber,
450 replacementprice => 23.00,
456 my %renewing_borrower_data = (
458 surname => 'Renewal',
459 categorycode => $patron_category->{categorycode},
460 branchcode => $branch,
463 my %reserving_borrower_data = (
464 firstname => 'Katrin',
465 surname => 'Reservation',
466 categorycode => $patron_category->{categorycode},
467 branchcode => $branch,
470 my %hold_waiting_borrower_data = (
472 surname => 'Reservation',
473 categorycode => $patron_category->{categorycode},
474 branchcode => $branch,
477 my %restricted_borrower_data = (
478 firstname => 'Alice',
479 surname => 'Reservation',
480 categorycode => $patron_category->{categorycode},
481 debarred => '3228-01-01',
482 branchcode => $branch,
485 my %expired_borrower_data = (
488 categorycode => $patron_category->{categorycode},
489 branchcode => $branch,
490 dateexpiry => dt_from_string->subtract( months => 1 ),
493 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
494 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
495 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
496 my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
497 my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
499 my $renewing_borrower_obj = Koha::Patrons->find( $renewing_borrowernumber );
500 my $renewing_borrower = $renewing_borrower_obj->unblessed;
501 my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
502 my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
509 my $checkitem = undef;
512 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
513 my $datedue = dt_from_string( $issue->date_due() );
514 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
516 my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
517 $datedue = dt_from_string( $issue->date_due() );
518 is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
521 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
522 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
524 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
525 is( $renewokay, 1, 'Can renew, no holds for this title or item');
528 # Biblio-level hold, renewal test
531 branchcode => $branch,
532 borrowernumber => $reserving_borrowernumber,
533 biblionumber => $biblio->biblionumber,
534 priority => $priority,
535 reservation_date => $resdate,
536 expiration_date => $expdate,
538 itemnumber => $checkitem,
543 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
544 Koha::CirculationRules->set_rule(
546 categorycode => undef,
549 rule_name => 'onshelfholds',
553 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
554 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
555 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
556 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
557 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
559 # Now let's add an item level hold, we should no longer be able to renew the item
560 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
562 borrowernumber => $hold_waiting_borrowernumber,
563 biblionumber => $biblio->biblionumber,
564 itemnumber => $item_1->itemnumber,
565 branchcode => $branch,
569 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
570 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
573 # 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
574 # be able to renew these items
575 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
577 borrowernumber => $hold_waiting_borrowernumber,
578 biblionumber => $biblio->biblionumber,
579 itemnumber => $item_3->itemnumber,
580 branchcode => $branch,
585 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
586 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
587 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
588 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
589 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
591 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
592 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
593 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
595 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
596 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
597 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
599 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
600 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
601 AddIssue($reserving_borrower, $item_3->barcode);
602 my $reserve = $dbh->selectrow_hashref(
603 'SELECT * FROM old_reserves WHERE reserve_id = ?',
607 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
609 # Item-level hold, renewal test
612 branchcode => $branch,
613 borrowernumber => $reserving_borrowernumber,
614 biblionumber => $biblio->biblionumber,
615 priority => $priority,
616 reservation_date => $resdate,
617 expiration_date => $expdate,
619 itemnumber => $item_1->itemnumber,
624 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
625 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
626 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
628 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
629 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
631 # Items can't fill hold for reasons
632 $item_1->notforloan(1)->store;
633 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
634 is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
635 $item_1->set({notforloan => 0, itype => $itemtype })->store;
637 # FIXME: Add more for itemtype not for loan etc.
639 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
640 my $item_5 = $builder->build_sample_item(
642 biblionumber => $biblio->biblionumber,
644 replacementprice => 23.00,
648 my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
649 is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
651 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
652 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
653 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
654 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
655 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
657 # Users cannot renew an overdue item
658 my $item_6 = $builder->build_sample_item(
660 biblionumber => $biblio->biblionumber,
662 replacementprice => 23.00,
667 my $item_7 = $builder->build_sample_item(
669 biblionumber => $biblio->biblionumber,
671 replacementprice => 23.00,
676 my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
677 is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
679 my $now = dt_from_string();
680 my $five_weeks = DateTime::Duration->new(weeks => 5);
681 my $five_weeks_ago = $now - $five_weeks;
682 t::lib::Mocks::mock_preference('finesMode', 'production');
684 my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
685 is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
687 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
688 C4::Overdues::UpdateFine(
690 issue_id => $passeddatedue1->id(),
691 itemnumber => $item_7->itemnumber,
692 borrowernumber => $renewing_borrower->{borrowernumber},
694 due => Koha::DateUtils::output_pref($five_weeks_ago)
698 # Make sure fine calculation isn't skipped when adding renewal
699 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
701 t::lib::Mocks::mock_preference('RenewalLog', 0);
702 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
703 my %params_renewal = (
704 timestamp => { -like => $date . "%" },
705 module => "CIRCULATION",
709 timestamp => { -like => $date . "%" },
710 module => "CIRCULATION",
713 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
714 my $dt = dt_from_string();
715 Time::Fake->offset( $dt->epoch );
716 my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
717 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
718 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
719 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
722 t::lib::Mocks::mock_preference('RenewalLog', 1);
723 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
724 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
725 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
726 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
727 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
729 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
730 is( $fines->count, 2, 'AddRenewal left both fines' );
731 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
732 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
736 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
737 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
738 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
739 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
740 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
741 $new_log_size = Koha::ActionLogs->count( \%params_issue );
742 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
744 $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
747 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
748 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
749 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
750 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
751 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
754 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
758 # Test automatic renewal before value for "norenewalbefore" in policy is set
759 # In this case automatic renewal is not permitted prior to due date
760 my $item_4 = $builder->build_sample_item(
762 biblionumber => $biblio->biblionumber,
764 replacementprice => 16.00,
769 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
770 ( $renewokay, $error ) =
771 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
772 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
773 is( $error, 'auto_too_soon',
774 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
777 branchcode => $branch,
778 borrowernumber => $reserving_borrowernumber,
779 biblionumber => $biblio->biblionumber,
780 itemnumber => $bibitems,
781 priority => $priority,
782 reservation_date => $resdate,
783 expiration_date => $expdate,
786 itemnumber => $item_4->itemnumber,
790 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
791 is( $renewokay, 0, 'Still should not be able to renew' );
792 is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' );
793 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, undef, 1 );
794 is( $renewokay, 0, 'Still should not be able to renew' );
795 is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' );
796 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
797 is( $renewokay, 0, 'Still should not be able to renew' );
798 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
799 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1, 1 );
800 is( $renewokay, 0, 'Still should not be able to renew' );
801 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
802 $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
803 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
804 is( $renewokay, 0, 'Still should not be able to renew' );
805 is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
806 ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
810 $renewing_borrower_obj->autorenew_checkouts(0)->store;
811 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
812 is( $renewokay, 1, 'No renewal before is undef, but patron opted out of auto_renewal' );
813 $renewing_borrower_obj->autorenew_checkouts(1)->store;
817 # Test premature manual renewal
818 Koha::CirculationRules->set_rule(
820 categorycode => undef,
823 rule_name => 'norenewalbefore',
828 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
829 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
830 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
833 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
834 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
836 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
837 $datedue->clone->add( days => -7 ),
838 'Bug 14395: Renewals permitted 7 days before due date, as expected'
842 # Test 'date' setting for syspref NoRenewalBeforePrecision
843 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
845 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
846 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
847 'Bug 14395: Renewals permitted 7 days before due date, as expected'
851 # Test premature automatic renewal
852 ( $renewokay, $error ) =
853 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
854 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
855 is( $error, 'auto_too_soon',
856 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
859 $renewing_borrower_obj->autorenew_checkouts(0)->store;
860 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
861 is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' );
862 is( $error, 'too_soon', 'Error is too_soon, no auto' );
863 $renewing_borrower_obj->autorenew_checkouts(1)->store;
865 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
866 # and test automatic renewal again
867 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
868 ( $renewokay, $error ) =
869 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
870 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
871 is( $error, 'auto_too_soon',
872 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
875 $renewing_borrower_obj->autorenew_checkouts(0)->store;
876 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
877 is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' );
878 is( $error, 'too_soon', 'Error is too_soon, no auto' );
879 $renewing_borrower_obj->autorenew_checkouts(1)->store;
881 # Change policy so that loans can be renewed 99 days prior to the due date
882 # and test automatic renewal again
883 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
884 ( $renewokay, $error ) =
885 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
886 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
887 is( $error, 'auto_renew',
888 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
891 $renewing_borrower_obj->autorenew_checkouts(0)->store;
892 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
893 is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' );
894 $renewing_borrower_obj->autorenew_checkouts(1)->store;
896 subtest "too_late_renewal / no_auto_renewal_after" => sub {
898 my $item_to_auto_renew = $builder->build_sample_item(
900 biblionumber => $biblio->biblionumber,
905 my $ten_days_before = dt_from_string->add( days => -10 );
906 my $ten_days_ahead = dt_from_string->add( days => 10 );
907 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
909 Koha::CirculationRules->set_rules(
911 categorycode => undef,
915 norenewalbefore => '7',
916 no_auto_renewal_after => '9',
920 ( $renewokay, $error ) =
921 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
922 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
923 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
925 Koha::CirculationRules->set_rules(
927 categorycode => undef,
931 norenewalbefore => '7',
932 no_auto_renewal_after => '10',
936 ( $renewokay, $error ) =
937 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
938 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
939 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
941 Koha::CirculationRules->set_rules(
943 categorycode => undef,
947 norenewalbefore => '7',
948 no_auto_renewal_after => '11',
952 ( $renewokay, $error ) =
953 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
954 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
955 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
957 Koha::CirculationRules->set_rules(
959 categorycode => undef,
963 norenewalbefore => '10',
964 no_auto_renewal_after => '11',
968 ( $renewokay, $error ) =
969 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
970 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
971 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
973 Koha::CirculationRules->set_rules(
975 categorycode => undef,
979 norenewalbefore => '10',
980 no_auto_renewal_after => undef,
981 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
985 ( $renewokay, $error ) =
986 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
987 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
988 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
990 Koha::CirculationRules->set_rules(
992 categorycode => undef,
996 norenewalbefore => '7',
997 no_auto_renewal_after => '15',
998 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1002 ( $renewokay, $error ) =
1003 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1004 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1005 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1007 Koha::CirculationRules->set_rules(
1009 categorycode => undef,
1010 branchcode => undef,
1013 norenewalbefore => '10',
1014 no_auto_renewal_after => undef,
1015 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
1019 ( $renewokay, $error ) =
1020 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1021 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1022 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1025 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
1027 my $item_to_auto_renew = $builder->build_sample_item(
1029 biblionumber => $biblio->biblionumber,
1034 my $ten_days_before = dt_from_string->add( days => -10 );
1035 my $ten_days_ahead = dt_from_string->add( days => 10 );
1036 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1038 Koha::CirculationRules->set_rules(
1040 categorycode => undef,
1041 branchcode => undef,
1044 norenewalbefore => '10',
1045 no_auto_renewal_after => '11',
1049 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
1050 C4::Context->set_preference('OPACFineNoRenewals','10');
1051 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1052 my $fines_amount = 5;
1053 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
1054 $account->add_debit(
1056 amount => $fines_amount,
1057 interface => 'test',
1059 item_id => $item_to_auto_renew->itemnumber,
1060 description => "Some fines"
1062 )->status('RETURNED')->store;
1063 ( $renewokay, $error ) =
1064 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1065 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1066 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
1068 $account->add_debit(
1070 amount => $fines_amount,
1071 interface => 'test',
1073 item_id => $item_to_auto_renew->itemnumber,
1074 description => "Some fines"
1076 )->status('RETURNED')->store;
1077 ( $renewokay, $error ) =
1078 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1079 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1080 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
1082 $account->add_debit(
1084 amount => $fines_amount,
1085 interface => 'test',
1087 item_id => $item_to_auto_renew->itemnumber,
1088 description => "Some fines"
1090 )->status('RETURNED')->store;
1091 ( $renewokay, $error ) =
1092 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1093 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1094 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
1096 $account->add_credit(
1098 amount => $fines_amount,
1099 interface => 'test',
1101 description => "Some payment"
1104 ( $renewokay, $error ) =
1105 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1106 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1107 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1109 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
1110 ( $renewokay, $error ) =
1111 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1112 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1113 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1115 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
1116 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1119 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
1121 my $item_to_auto_renew = $builder->build_sample_item(
1123 biblionumber => $biblio->biblionumber,
1128 Koha::CirculationRules->set_rules(
1130 categorycode => undef,
1131 branchcode => undef,
1134 norenewalbefore => 10,
1135 no_auto_renewal_after => 11,
1140 my $ten_days_before = dt_from_string->add( days => -10 );
1141 my $ten_days_ahead = dt_from_string->add( days => 10 );
1143 # Patron is expired and BlockExpiredPatronOpacActions=0
1144 # => auto renew is allowed
1145 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
1146 my $patron = $expired_borrower;
1147 my $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1148 ( $renewokay, $error ) =
1149 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1150 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1151 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
1152 Koha::Checkouts->find( $checkout->issue_id )->delete;
1155 # Patron is expired and BlockExpiredPatronOpacActions=1
1156 # => auto renew is not allowed
1157 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1158 $patron = $expired_borrower;
1159 $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1160 ( $renewokay, $error ) =
1161 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1162 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1163 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
1164 Koha::Checkouts->find( $checkout->issue_id )->delete;
1167 # Patron is not expired and BlockExpiredPatronOpacActions=1
1168 # => auto renew is allowed
1169 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1170 $patron = $renewing_borrower;
1171 $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1172 ( $renewokay, $error ) =
1173 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1174 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1175 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1176 Koha::Checkouts->find( $checkout->issue_id )->delete;
1179 subtest "GetLatestAutoRenewDate" => sub {
1181 my $item_to_auto_renew = $builder->build_sample_item(
1183 biblionumber => $biblio->biblionumber,
1188 my $ten_days_before = dt_from_string->add( days => -10 );
1189 my $ten_days_ahead = dt_from_string->add( days => 10 );
1190 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1191 Koha::CirculationRules->set_rules(
1193 categorycode => undef,
1194 branchcode => undef,
1197 norenewalbefore => '7',
1198 no_auto_renewal_after => '',
1199 no_auto_renewal_after_hard_limit => undef,
1203 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1204 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' );
1205 my $five_days_before = dt_from_string->add( days => -5 );
1206 Koha::CirculationRules->set_rules(
1208 categorycode => undef,
1209 branchcode => undef,
1212 norenewalbefore => '10',
1213 no_auto_renewal_after => '5',
1214 no_auto_renewal_after_hard_limit => undef,
1218 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1219 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1220 $five_days_before->truncate( to => 'minute' ),
1221 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1223 my $five_days_ahead = dt_from_string->add( days => 5 );
1224 $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1225 $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1226 $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1227 Koha::CirculationRules->set_rules(
1229 categorycode => undef,
1230 branchcode => undef,
1233 norenewalbefore => '10',
1234 no_auto_renewal_after => '15',
1235 no_auto_renewal_after_hard_limit => undef,
1239 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1240 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1241 $five_days_ahead->truncate( to => 'minute' ),
1242 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1244 my $two_days_ahead = dt_from_string->add( days => 2 );
1245 Koha::CirculationRules->set_rules(
1247 categorycode => undef,
1248 branchcode => undef,
1251 norenewalbefore => '10',
1252 no_auto_renewal_after => '',
1253 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1257 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1258 is( $latest_auto_renew_date->truncate( to => 'day' ),
1259 $two_days_ahead->truncate( to => 'day' ),
1260 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1262 Koha::CirculationRules->set_rules(
1264 categorycode => undef,
1265 branchcode => undef,
1268 norenewalbefore => '10',
1269 no_auto_renewal_after => '15',
1270 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1274 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1275 is( $latest_auto_renew_date->truncate( to => 'day' ),
1276 $two_days_ahead->truncate( to => 'day' ),
1277 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1283 # set policy to forbid renewals
1284 Koha::CirculationRules->set_rules(
1286 categorycode => undef,
1287 branchcode => undef,
1290 norenewalbefore => undef,
1291 renewalsallowed => 0,
1296 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1297 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1298 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1300 # Too many unseen renewals
1301 Koha::CirculationRules->set_rules(
1303 categorycode => undef,
1304 branchcode => undef,
1307 unseen_renewals_allowed => 2,
1308 renewalsallowed => 10,
1312 t::lib::Mocks::mock_preference('UnseenRenewals', 1);
1313 $dbh->do('UPDATE issues SET unseen_renewals = 2 where borrowernumber = ? AND itemnumber = ?', undef, ($renewing_borrowernumber, $item_1->itemnumber));
1314 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1315 is( $renewokay, 0, 'Cannot renew, 0 unseen renewals allowed');
1316 is( $error, 'too_unseen', 'Cannot renew, returned code is too_unseen');
1317 Koha::CirculationRules->set_rules(
1319 categorycode => undef,
1320 branchcode => undef,
1323 norenewalbefore => undef,
1324 renewalsallowed => 0,
1328 t::lib::Mocks::mock_preference('UnseenRenewals', 0);
1330 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1331 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1332 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1334 C4::Overdues::UpdateFine(
1336 issue_id => $issue->id(),
1337 itemnumber => $item_1->itemnumber,
1338 borrowernumber => $renewing_borrower->{borrowernumber},
1341 due => Koha::DateUtils::output_pref($datedue)
1345 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
1346 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1347 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1348 is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1349 is( $line->amount+0, 15, 'Account line amount is 15.00' );
1350 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
1352 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1353 is( $offset->type, 'OVERDUE', 'Account offset type is Fine' );
1354 is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1356 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1357 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1359 LostItem( $item_1->itemnumber, 'test', 1 );
1361 $line = Koha::Account::Lines->find($line->id);
1362 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1363 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1365 my $item = Koha::Items->find($item_1->itemnumber);
1366 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1367 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1368 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1370 my $total_due = $dbh->selectrow_array(
1371 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1372 undef, $renewing_borrower->{borrowernumber}
1375 is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1377 C4::Context->dbh->do("DELETE FROM accountlines");
1379 C4::Overdues::UpdateFine(
1381 issue_id => $issue2->id(),
1382 itemnumber => $item_2->itemnumber,
1383 borrowernumber => $renewing_borrower->{borrowernumber},
1386 due => Koha::DateUtils::output_pref($datedue)
1390 LostItem( $item_2->itemnumber, 'test', 0 );
1392 my $item2 = Koha::Items->find($item_2->itemnumber);
1393 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1394 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1396 $total_due = $dbh->selectrow_array(
1397 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1398 undef, $renewing_borrower->{borrowernumber}
1401 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1403 my $future = dt_from_string();
1404 $future->add( days => 7 );
1405 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1406 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1408 # Users cannot renew any item if there is an overdue item
1409 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
1410 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
1411 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1412 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
1413 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1415 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1416 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1417 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1418 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1419 LostItem( $item_3->itemnumber, 'test', 0 );
1420 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1421 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1423 $accountline->description,
1424 sprintf( "%s %s %s",
1425 $item_3->biblio->title || '',
1426 $item_3->barcode || '',
1427 $item_3->itemcallnumber || '' ),
1428 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1432 subtest "GetUpcomingDueIssues" => sub {
1435 my $branch = $library2->{branchcode};
1437 #Create another record
1438 my $biblio2 = $builder->build_sample_biblio();
1441 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1442 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1443 my $item_3 = $builder->build_sample_item(
1445 biblionumber => $biblio2->biblionumber,
1453 my %a_borrower_data = (
1454 firstname => 'Fridolyn',
1455 surname => 'SOMERS',
1456 categorycode => $patron_category->{categorycode},
1457 branchcode => $branch,
1460 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1461 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1463 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1464 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1465 my $today = DateTime->today(time_zone => C4::Context->tz());
1467 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1468 my $datedue = dt_from_string( $issue->date_due() );
1469 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1470 my $datedue2 = dt_from_string( $issue->date_due() );
1474 # GetUpcomingDueIssues tests
1476 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1477 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1480 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1481 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1482 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1485 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1486 is ( scalar( @$upcoming_dues ), 1,
1487 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1490 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1492 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1494 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1495 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1497 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1498 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1500 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1501 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1503 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1504 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1506 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1507 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1509 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1510 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1514 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1515 my $branch = $library2->{branchcode};
1517 my $biblio = $builder->build_sample_biblio();
1520 my $item = $builder->build_sample_item(
1522 biblionumber => $biblio->biblionumber,
1529 my %a_borrower_data = (
1530 firstname => 'Kyle',
1532 categorycode => $patron_category->{categorycode},
1533 branchcode => $branch,
1536 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1538 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1539 my $issue = AddIssue( $borrower, $item->barcode );
1542 issue_id => $issue->id(),
1543 itemnumber => $item->itemnumber,
1544 borrowernumber => $borrowernumber,
1550 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1551 my $count = $hr->{count};
1553 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1556 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1557 $dbh->do('DELETE FROM issues');
1558 $dbh->do('DELETE FROM items');
1559 $dbh->do('DELETE FROM circulation_rules');
1560 Koha::CirculationRules->set_rules(
1562 categorycode => undef,
1564 branchcode => undef,
1566 reservesallowed => 25,
1568 lengthunit => 'days',
1569 renewalsallowed => 1,
1571 norenewalbefore => undef,
1579 my $biblio = $builder->build_sample_biblio();
1581 my $item_1 = $builder->build_sample_item(
1583 biblionumber => $biblio->biblionumber,
1584 library => $library2->{branchcode},
1589 my $item_2= $builder->build_sample_item(
1591 biblionumber => $biblio->biblionumber,
1592 library => $library2->{branchcode},
1597 my $borrowernumber1 = Koha::Patron->new({
1598 firstname => 'Kyle',
1600 categorycode => $patron_category->{categorycode},
1601 branchcode => $library2->{branchcode},
1602 })->store->borrowernumber;
1603 my $borrowernumber2 = Koha::Patron->new({
1604 firstname => 'Chelsea',
1606 categorycode => $patron_category->{categorycode},
1607 branchcode => $library2->{branchcode},
1608 })->store->borrowernumber;
1610 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1611 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1613 my $issue = AddIssue( $borrower1, $item_1->barcode );
1615 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1616 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1620 branchcode => $library2->{branchcode},
1621 borrowernumber => $borrowernumber2,
1622 biblionumber => $biblio->biblionumber,
1627 Koha::CirculationRules->set_rules(
1629 categorycode => undef,
1631 branchcode => undef,
1637 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1638 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1639 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1641 Koha::CirculationRules->set_rules(
1643 categorycode => undef,
1645 branchcode => undef,
1651 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1652 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1653 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1655 Koha::CirculationRules->set_rules(
1657 categorycode => undef,
1659 branchcode => undef,
1665 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1666 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1667 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1669 Koha::CirculationRules->set_rules(
1671 categorycode => undef,
1673 branchcode => undef,
1679 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1680 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1681 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1683 # Setting item not checked out to be not for loan but holdable
1684 $item_2->notforloan(-1)->store;
1686 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1687 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' );
1691 # Don't allow renewing onsite checkout
1692 my $branch = $library->{branchcode};
1694 #Create another record
1695 my $biblio = $builder->build_sample_biblio();
1697 my $item = $builder->build_sample_item(
1699 biblionumber => $biblio->biblionumber,
1705 my $borrowernumber = Koha::Patron->new({
1708 categorycode => $patron_category->{categorycode},
1709 branchcode => $branch,
1710 })->store->borrowernumber;
1712 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1714 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1715 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1716 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1717 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1721 my $library = $builder->build({ source => 'Branch' });
1723 my $biblio = $builder->build_sample_biblio();
1725 my $item = $builder->build_sample_item(
1727 biblionumber => $biblio->biblionumber,
1728 library => $library->{branchcode},
1733 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1735 my $issue = AddIssue( $patron, $item->barcode );
1738 issue_id => $issue->id(),
1739 itemnumber => $item->itemnumber,
1740 borrowernumber => $patron->{borrowernumber},
1747 issue_id => $issue->id(),
1748 itemnumber => $item->itemnumber,
1749 borrowernumber => $patron->{borrowernumber},
1754 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1757 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1760 my $homebranch = $builder->build( { source => 'Branch' } );
1761 my $holdingbranch = $builder->build( { source => 'Branch' } );
1762 my $otherbranch = $builder->build( { source => 'Branch' } );
1763 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1764 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1766 my $item = $builder->build_sample_item(
1768 homebranch => $homebranch->{branchcode},
1769 holdingbranch => $holdingbranch->{branchcode},
1773 set_userenv($holdingbranch);
1775 my $issue = AddIssue( $patron_1->unblessed, $item->barcode );
1776 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1778 my ( $error, $question, $alerts );
1780 # AllowReturnToBranch == anywhere
1781 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1782 ## Test that unknown barcodes don't generate internal server errors
1783 set_userenv($homebranch);
1784 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1785 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1786 ## Can be issued from homebranch
1787 set_userenv($homebranch);
1788 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1789 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1790 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1791 ## Can be issued from holdingbranch
1792 set_userenv($holdingbranch);
1793 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1794 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1795 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1796 ## Can be issued from another branch
1797 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1798 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1799 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1801 # AllowReturnToBranch == holdingbranch
1802 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1803 ## Cannot be issued from homebranch
1804 set_userenv($homebranch);
1805 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1806 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1807 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1808 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1809 ## Can be issued from holdinbranch
1810 set_userenv($holdingbranch);
1811 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1812 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1813 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1814 ## Cannot be issued from another branch
1815 set_userenv($otherbranch);
1816 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1817 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1818 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1819 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
1821 # AllowReturnToBranch == homebranch
1822 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1823 ## Can be issued from holdinbranch
1824 set_userenv($homebranch);
1825 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1826 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1827 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1828 ## Cannot be issued from holdinbranch
1829 set_userenv($holdingbranch);
1830 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1831 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1832 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1833 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1834 ## Cannot be issued from holdinbranch
1835 set_userenv($otherbranch);
1836 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1837 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1838 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1839 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1841 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1844 subtest 'AddIssue & AllowReturnToBranch' => sub {
1847 my $homebranch = $builder->build( { source => 'Branch' } );
1848 my $holdingbranch = $builder->build( { source => 'Branch' } );
1849 my $otherbranch = $builder->build( { source => 'Branch' } );
1850 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1851 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1853 my $item = $builder->build_sample_item(
1855 homebranch => $homebranch->{branchcode},
1856 holdingbranch => $holdingbranch->{branchcode},
1860 set_userenv($holdingbranch);
1862 my $ref_issue = 'Koha::Checkout';
1863 my $issue = AddIssue( $patron_1, $item->barcode );
1865 my ( $error, $question, $alerts );
1867 # AllowReturnToBranch == homebranch
1868 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1869 ## Can be issued from homebranch
1870 set_userenv($homebranch);
1871 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
1872 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1873 ## Can be issued from holdinbranch
1874 set_userenv($holdingbranch);
1875 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
1876 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1877 ## Can be issued from another branch
1878 set_userenv($otherbranch);
1879 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
1880 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1882 # AllowReturnToBranch == holdinbranch
1883 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1884 ## Cannot be issued from homebranch
1885 set_userenv($homebranch);
1886 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
1887 ## Can be issued from holdingbranch
1888 set_userenv($holdingbranch);
1889 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
1890 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1891 ## Cannot be issued from another branch
1892 set_userenv($otherbranch);
1893 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
1895 # AllowReturnToBranch == homebranch
1896 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1897 ## Can be issued from homebranch
1898 set_userenv($homebranch);
1899 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
1900 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1901 ## Cannot be issued from holdinbranch
1902 set_userenv($holdingbranch);
1903 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
1904 ## Cannot be issued from another branch
1905 set_userenv($otherbranch);
1906 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
1907 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1910 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1913 my $library = $builder->build( { source => 'Branch' } );
1914 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1915 my $item_1 = $builder->build_sample_item(
1917 library => $library->{branchcode},
1920 my $item_2 = $builder->build_sample_item(
1922 library => $library->{branchcode},
1926 my ( $error, $question, $alerts );
1928 # Patron cannot issue item_1, they have overdues
1929 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1930 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, $yesterday ); # Add an overdue
1932 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1933 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
1934 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
1935 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1937 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1938 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
1939 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1940 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1942 # Patron cannot issue item_1, they are debarred
1943 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1944 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1945 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
1946 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1947 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1949 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1950 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
1951 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1952 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1955 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1958 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1959 my $patron_category_x = $builder->build_object(
1961 class => 'Koha::Patron::Categories',
1962 value => { category_type => 'X' }
1965 my $patron = $builder->build_object(
1967 class => 'Koha::Patrons',
1969 categorycode => $patron_category_x->categorycode,
1970 gonenoaddress => undef,
1977 my $item_1 = $builder->build_sample_item(
1979 library => $library->{branchcode},
1983 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
1984 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1986 # TODO There are other tests to provide here
1989 subtest 'MultipleReserves' => sub {
1992 my $biblio = $builder->build_sample_biblio();
1994 my $branch = $library2->{branchcode};
1996 my $item_1 = $builder->build_sample_item(
1998 biblionumber => $biblio->biblionumber,
2000 replacementprice => 12.00,
2005 my $item_2 = $builder->build_sample_item(
2007 biblionumber => $biblio->biblionumber,
2009 replacementprice => 12.00,
2016 my $resdate = undef;
2017 my $expdate = undef;
2019 my $checkitem = undef;
2022 my %renewing_borrower_data = (
2023 firstname => 'John',
2024 surname => 'Renewal',
2025 categorycode => $patron_category->{categorycode},
2026 branchcode => $branch,
2028 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
2029 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
2030 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
2031 my $datedue = dt_from_string( $issue->date_due() );
2032 is (defined $issue->date_due(), 1, "item 1 checked out");
2033 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
2035 my %reserving_borrower_data1 = (
2036 firstname => 'Katrin',
2037 surname => 'Reservation',
2038 categorycode => $patron_category->{categorycode},
2039 branchcode => $branch,
2041 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
2044 branchcode => $branch,
2045 borrowernumber => $reserving_borrowernumber1,
2046 biblionumber => $biblio->biblionumber,
2047 priority => $priority,
2048 reservation_date => $resdate,
2049 expiration_date => $expdate,
2051 itemnumber => $checkitem,
2056 my %reserving_borrower_data2 = (
2057 firstname => 'Kirk',
2058 surname => 'Reservation',
2059 categorycode => $patron_category->{categorycode},
2060 branchcode => $branch,
2062 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
2065 branchcode => $branch,
2066 borrowernumber => $reserving_borrowernumber2,
2067 biblionumber => $biblio->biblionumber,
2068 priority => $priority,
2069 reservation_date => $resdate,
2070 expiration_date => $expdate,
2072 itemnumber => $checkitem,
2078 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2079 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2082 my $item_3 = $builder->build_sample_item(
2084 biblionumber => $biblio->biblionumber,
2086 replacementprice => 12.00,
2092 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2093 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2097 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2100 my $library = $builder->build( { source => 'Branch' } );
2101 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2103 my $biblionumber = $builder->build_sample_biblio(
2105 branchcode => $library->{branchcode},
2108 my $item_1 = $builder->build_sample_item(
2110 biblionumber => $biblionumber,
2111 library => $library->{branchcode},
2115 my $item_2 = $builder->build_sample_item(
2117 biblionumber => $biblionumber,
2118 library => $library->{branchcode},
2122 my ( $error, $question, $alerts );
2123 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, dt_from_string->add( days => 1 ) );
2125 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2126 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2128 { error => $error, alerts => $alerts },
2129 { error => {}, alerts => {} },
2130 'No error or alert should be raised'
2132 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2134 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2135 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2137 { error => $error, question => $question, alerts => $alerts },
2138 { error => {}, question => {}, alerts => {} },
2139 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2142 # Add a subscription
2143 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2145 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2146 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2148 { error => $error, question => $question, alerts => $alerts },
2149 { error => {}, question => {}, alerts => {} },
2150 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2153 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2154 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2156 { error => $error, question => $question, alerts => $alerts },
2157 { error => {}, question => {}, alerts => {} },
2158 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2162 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2165 my $library = $builder->build( { source => 'Branch' } );
2166 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2169 my $biblionumber = $builder->build_sample_biblio(
2171 branchcode => $library->{branchcode},
2174 my $item_1 = $builder->build_sample_item(
2176 biblionumber => $biblionumber,
2177 library => $library->{branchcode},
2180 my $item_2 = $builder->build_sample_item(
2182 biblionumber => $biblionumber,
2183 library => $library->{branchcode},
2187 # And the circulation rule
2188 Koha::CirculationRules->search->delete;
2189 Koha::CirculationRules->set_rules(
2191 categorycode => undef,
2193 branchcode => undef,
2196 firstremind => 1, # 1 day of grace
2197 finedays => 2, # 2 days of fine per day of overdue
2198 lengthunit => 'days',
2203 # Patron cannot issue item_1, they have overdues
2204 my $now = dt_from_string;
2205 my $five_days_ago = $now->clone->subtract( days => 5 );
2206 my $ten_days_ago = $now->clone->subtract( days => 10 );
2207 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2208 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2209 ; # Add another overdue
2211 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2212 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2213 my $debarments = Koha::Patron::Debarments::GetDebarments(
2214 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2215 is( scalar(@$debarments), 1 );
2217 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2218 # Same for the others
2219 my $expected_expiration = output_pref(
2221 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2222 dateformat => 'sql',
2226 is( $debarments->[0]->{expiration}, $expected_expiration );
2228 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2229 $debarments = Koha::Patron::Debarments::GetDebarments(
2230 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2231 is( scalar(@$debarments), 1 );
2232 $expected_expiration = output_pref(
2234 dt => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2235 dateformat => 'sql',
2239 is( $debarments->[0]->{expiration}, $expected_expiration );
2241 Koha::Patron::Debarments::DelUniqueDebarment(
2242 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2244 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2245 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2246 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2247 ; # Add another overdue
2248 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2249 $debarments = Koha::Patron::Debarments::GetDebarments(
2250 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2251 is( scalar(@$debarments), 1 );
2252 $expected_expiration = output_pref(
2254 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2255 dateformat => 'sql',
2259 is( $debarments->[0]->{expiration}, $expected_expiration );
2261 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2262 $debarments = Koha::Patron::Debarments::GetDebarments(
2263 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2264 is( scalar(@$debarments), 1 );
2265 $expected_expiration = output_pref(
2267 dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2268 dateformat => 'sql',
2272 is( $debarments->[0]->{expiration}, $expected_expiration );
2275 subtest 'AddReturn + suspension_chargeperiod' => sub {
2278 my $library = $builder->build( { source => 'Branch' } );
2279 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2281 my $biblionumber = $builder->build_sample_biblio(
2283 branchcode => $library->{branchcode},
2286 my $item_1 = $builder->build_sample_item(
2288 biblionumber => $biblionumber,
2289 library => $library->{branchcode},
2293 # And the issuing rule
2294 Koha::CirculationRules->search->delete;
2295 Koha::CirculationRules->set_rules(
2297 categorycode => '*',
2302 firstremind => 0, # 0 day of grace
2303 finedays => 2, # 2 days of fine per day of overdue
2304 suspension_chargeperiod => 1,
2305 lengthunit => 'days',
2310 my $now = dt_from_string;
2311 my $five_days_ago = $now->clone->subtract( days => 5 );
2312 # We want to charge 2 days every day, without grace
2313 # With 5 days of overdue: 5 * Z
2314 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2315 test_debarment_on_checkout(
2318 library => $library,
2320 due_date => $five_days_ago,
2321 expiration_date => $expected_expiration,
2325 # Same with undef firstremind
2326 Koha::CirculationRules->search->delete;
2327 Koha::CirculationRules->set_rules(
2329 categorycode => '*',
2334 firstremind => undef, # 0 day of grace
2335 finedays => 2, # 2 days of fine per day of overdue
2336 suspension_chargeperiod => 1,
2337 lengthunit => 'days',
2342 my $now = dt_from_string;
2343 my $five_days_ago = $now->clone->subtract( days => 5 );
2344 # We want to charge 2 days every day, without grace
2345 # With 5 days of overdue: 5 * Z
2346 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2347 test_debarment_on_checkout(
2350 library => $library,
2352 due_date => $five_days_ago,
2353 expiration_date => $expected_expiration,
2357 # We want to charge 2 days every 2 days, without grace
2358 # With 5 days of overdue: (5 * 2) / 2
2359 Koha::CirculationRules->set_rule(
2361 categorycode => undef,
2362 branchcode => undef,
2364 rule_name => 'suspension_chargeperiod',
2369 $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2370 test_debarment_on_checkout(
2373 library => $library,
2375 due_date => $five_days_ago,
2376 expiration_date => $expected_expiration,
2380 # We want to charge 2 days every 3 days, with 1 day of grace
2381 # With 5 days of overdue: ((5-1) / 3 ) * 2
2382 Koha::CirculationRules->set_rules(
2384 categorycode => undef,
2385 branchcode => undef,
2388 suspension_chargeperiod => 3,
2393 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2394 test_debarment_on_checkout(
2397 library => $library,
2399 due_date => $five_days_ago,
2400 expiration_date => $expected_expiration,
2404 # Use finesCalendar to know if holiday must be skipped to calculate the due date
2405 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2406 Koha::CirculationRules->set_rules(
2408 categorycode => undef,
2409 branchcode => undef,
2413 suspension_chargeperiod => 1,
2418 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2419 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2421 # Adding a holiday 2 days ago
2422 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2423 my $two_days_ago = $now->clone->subtract( days => 2 );
2424 $calendar->insert_single_holiday(
2425 day => $two_days_ago->day,
2426 month => $two_days_ago->month,
2427 year => $two_days_ago->year,
2428 title => 'holidayTest-2d',
2429 description => 'holidayDesc 2 days ago'
2431 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2432 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2433 test_debarment_on_checkout(
2436 library => $library,
2438 due_date => $five_days_ago,
2439 expiration_date => $expected_expiration,
2443 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2444 my $two_days_ahead = $now->clone->add( days => 2 );
2445 $calendar->insert_single_holiday(
2446 day => $two_days_ahead->day,
2447 month => $two_days_ahead->month,
2448 year => $two_days_ahead->year,
2449 title => 'holidayTest+2d',
2450 description => 'holidayDesc 2 days ahead'
2453 # Same as above, but we should skip D+2
2454 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2455 test_debarment_on_checkout(
2458 library => $library,
2460 due_date => $five_days_ago,
2461 expiration_date => $expected_expiration,
2465 # Adding another holiday, day of expiration date
2466 my $expected_expiration_dt = dt_from_string($expected_expiration);
2467 $calendar->insert_single_holiday(
2468 day => $expected_expiration_dt->day,
2469 month => $expected_expiration_dt->month,
2470 year => $expected_expiration_dt->year,
2471 title => 'holidayTest_exp',
2472 description => 'holidayDesc on expiration date'
2474 # Expiration date will be the day after
2475 test_debarment_on_checkout(
2478 library => $library,
2480 due_date => $five_days_ago,
2481 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2485 test_debarment_on_checkout(
2488 library => $library,
2490 return_date => $now->clone->add(days => 5),
2491 expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2495 test_debarment_on_checkout(
2498 library => $library,
2500 due_date => $now->clone->add(days => 1),
2501 return_date => $now->clone->add(days => 5),
2502 expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2508 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2511 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2512 my $patron1 = $builder->build_object(
2514 class => 'Koha::Patrons',
2516 library => $library->branchcode,
2517 categorycode => $patron_category->{categorycode}
2521 my $patron2 = $builder->build_object(
2523 class => 'Koha::Patrons',
2525 library => $library->branchcode,
2526 categorycode => $patron_category->{categorycode}
2531 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2533 my $item = $builder->build_sample_item(
2535 library => $library->branchcode,
2539 my ( $error, $question, $alerts );
2540 my $issue = AddIssue( $patron1->unblessed, $item->barcode );
2542 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2543 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2544 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' );
2546 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2547 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2548 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' );
2550 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2554 subtest 'AddReturn | is_overdue' => sub {
2557 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2558 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2559 t::lib::Mocks::mock_preference('finesMode', 'production');
2560 t::lib::Mocks::mock_preference('MaxFine', '100');
2562 my $library = $builder->build( { source => 'Branch' } );
2563 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2564 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2565 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2567 my $item = $builder->build_sample_item(
2569 library => $library->{branchcode},
2570 replacementprice => 7
2574 Koha::CirculationRules->search->delete;
2575 Koha::CirculationRules->set_rules(
2577 categorycode => undef,
2579 branchcode => undef,
2582 lengthunit => 'days',
2583 fine => 1, # Charge 1 every day of overdue
2589 my $now = dt_from_string;
2590 my $one_day_ago = $now->clone->subtract( days => 1 );
2591 my $two_days_ago = $now->clone->subtract( days => 2 );
2592 my $five_days_ago = $now->clone->subtract( days => 5 );
2593 my $ten_days_ago = $now->clone->subtract( days => 10 );
2594 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2596 # No return date specified, today will be used => 10 days overdue charged
2597 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2598 AddReturn( $item->barcode, $library->{branchcode} );
2599 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2600 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2602 # specify return date 5 days before => no overdue charged
2603 AddIssue( $patron->unblessed, $item->barcode, $five_days_ago ); # date due was 5d ago
2604 AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
2605 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2606 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2608 # specify return date 5 days later => 5 days overdue charged
2609 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2610 AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
2611 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2612 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2614 # specify return date 5 days later, specify exemptfine => no overdue charge
2615 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2616 AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago );
2617 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2618 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2620 subtest 'bug 22877 | Lost item return' => sub {
2624 my $issue = AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2626 # Fake fines cronjob on this checkout
2628 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2629 $ten_days_ago, $now );
2632 issue_id => $issue->issue_id,
2633 itemnumber => $item->itemnumber,
2634 borrowernumber => $patron->borrowernumber,
2636 due => output_pref($ten_days_ago)
2639 is( int( $patron->account->balance() ),
2640 10, "Overdue fine of 10 days overdue" );
2642 # Fake longoverdue with charge and not marking returned
2643 LostItem( $item->itemnumber, 'cronjob', 0 );
2644 is( int( $patron->account->balance() ),
2645 17, "Lost fine of 7 plus 10 days overdue" );
2647 # Now we return it today
2648 AddReturn( $item->barcode, $library->{branchcode} );
2649 is( int( $patron->account->balance() ),
2650 17, "Should have a single 10 days overdue fine and lost charge" );
2653 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2656 subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
2660 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2662 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
2664 # Fake fines cronjob on this checkout
2666 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2667 $one_day_ago, $now );
2670 issue_id => $issue->issue_id,
2671 itemnumber => $item->itemnumber,
2672 borrowernumber => $patron->borrowernumber,
2674 due => output_pref($one_day_ago)
2677 is( int( $patron->account->balance() ),
2678 1, "Overdue fine of 1 day overdue" );
2680 # Backdated return (dropbox mode example - charge should be removed)
2681 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
2682 is( int( $patron->account->balance() ),
2683 0, "Overdue fine should be annulled" );
2684 my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2685 is( $lines->count, 0, "Overdue fine accountline has been removed");
2687 $issue = AddIssue( $patron->unblessed, $item->barcode, $two_days_ago ); # date due was 2d ago
2689 # Fake fines cronjob on this checkout
2691 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2692 $two_days_ago, $now );
2695 issue_id => $issue->issue_id,
2696 itemnumber => $item->itemnumber,
2697 borrowernumber => $patron->borrowernumber,
2699 due => output_pref($one_day_ago)
2702 is( int( $patron->account->balance() ),
2703 2, "Overdue fine of 2 days overdue" );
2705 # Payment made against fine
2706 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2707 my $debit = $lines->next;
2708 my $credit = $patron->account->add_credit(
2712 interface => 'test',
2716 { debits => [ $debit ], offset_type => 'Payment' } );
2718 is( int( $patron->account->balance() ),
2719 0, "Overdue fine should be paid off" );
2720 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2721 is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
2722 my $line = $lines->next;
2723 is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
2724 is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
2726 # Backdated return (dropbox mode example - charge should be removed)
2727 AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
2728 is( int( $patron->account->balance() ),
2729 -1, "Refund credit has been applied" );
2730 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
2731 is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
2733 $line = $lines->next;
2734 is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
2735 is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
2736 is($line->status,'RETURNED', "Overdue fine is fixed");
2737 $line = $lines->next;
2738 is($line->amount+0,-2, "Original payment amount remains as 2");
2739 is($line->amountoutstanding+0,0, "Original payment remains applied");
2740 $line = $lines->next;
2741 is($line->amount+0,-1, "Refund amount correctly set to 1");
2742 is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
2745 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2748 subtest 'bug 25417 | backdated return + exemptfine' => sub {
2752 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2754 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
2756 # Fake fines cronjob on this checkout
2758 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2759 $one_day_ago, $now );
2762 issue_id => $issue->issue_id,
2763 itemnumber => $item->itemnumber,
2764 borrowernumber => $patron->borrowernumber,
2766 due => output_pref($one_day_ago)
2769 is( int( $patron->account->balance() ),
2770 1, "Overdue fine of 1 day overdue" );
2772 # Backdated return (dropbox mode example - charge should no longer exist)
2773 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
2774 is( int( $patron->account->balance() ),
2775 0, "Overdue fine should be annulled" );
2778 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2781 subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
2784 t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
2786 my $due_date = dt_from_string;
2787 my $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
2792 issue_id => $issue->issue_id,
2793 itemnumber => $item->itemnumber,
2794 borrowernumber => $patron->borrowernumber,
2796 due => output_pref($due_date)
2799 is( $patron->account->balance(),
2800 0.25, 'Overdue fine of $0.25 recorded' );
2802 # Backdate return to exact due date and time
2803 my ( undef, $message ) =
2804 AddReturn( $item->barcode, $library->{branchcode},
2808 Koha::Account::Lines->find( { issue_id => $issue->id } );
2809 ok( !$accountline, 'accountline removed as expected' );
2812 $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
2817 issue_id => $issue->issue_id,
2818 itemnumber => $item->itemnumber,
2819 borrowernumber => $patron->borrowernumber,
2821 due => output_pref($due_date)
2824 is( $patron->account->balance(),
2825 0.25, 'Overdue fine of $0.25 recorded' );
2827 # Partial pay accruing fine
2828 my $lines = Koha::Account::Lines->search(
2830 borrowernumber => $patron->borrowernumber,
2831 issue_id => $issue->id
2834 my $debit = $lines->next;
2835 my $credit = $patron->account->add_credit(
2839 interface => 'test',
2842 $credit->apply( { debits => [$debit], offset_type => 'Payment' } );
2844 is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
2846 # Backdate return to exact due date and time
2847 ( undef, $message ) =
2848 AddReturn( $item->barcode, $library->{branchcode},
2851 $lines = Koha::Account::Lines->search(
2853 borrowernumber => $patron->borrowernumber,
2854 issue_id => $issue->id
2857 $accountline = $lines->next;
2858 is( $accountline->amountoutstanding + 0,
2859 0, 'Partially paid fee amount outstanding was reduced to 0' );
2860 is( $accountline->amount + 0,
2861 0, 'Partially paid fee amount was reduced to 0' );
2862 is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
2865 Koha::Account::Lines->search(
2866 { borrowernumber => $patron->borrowernumber } )->delete;
2869 subtest 'enh 23091 | Lost item return policies' => sub {
2872 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2874 my $branchcode_false =
2875 $builder->build( { source => 'Branch' } )->{branchcode};
2876 my $specific_rule_false = $builder->build(
2878 source => 'CirculationRule',
2880 branchcode => $branchcode_false,
2881 categorycode => undef,
2883 rule_name => 'lostreturn',
2888 my $branchcode_refund =
2889 $builder->build( { source => 'Branch' } )->{branchcode};
2890 my $specific_rule_refund = $builder->build(
2892 source => 'CirculationRule',
2894 branchcode => $branchcode_refund,
2895 categorycode => undef,
2897 rule_name => 'lostreturn',
2898 rule_value => 'refund'
2902 my $branchcode_restore =
2903 $builder->build( { source => 'Branch' } )->{branchcode};
2904 my $specific_rule_restore = $builder->build(
2906 source => 'CirculationRule',
2908 branchcode => $branchcode_restore,
2909 categorycode => undef,
2911 rule_name => 'lostreturn',
2912 rule_value => 'restore'
2916 my $branchcode_charge =
2917 $builder->build( { source => 'Branch' } )->{branchcode};
2918 my $specific_rule_charge = $builder->build(
2920 source => 'CirculationRule',
2922 branchcode => $branchcode_charge,
2923 categorycode => undef,
2925 rule_name => 'lostreturn',
2926 rule_value => 'charge'
2931 my $replacement_amount = 99.00;
2932 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2933 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
2934 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
2935 t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 );
2936 t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
2938 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
2941 subtest 'lostreturn | false' => sub {
2944 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
2946 my $item = $builder->build_sample_item(
2948 replacementprice => $replacement_amount
2953 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
2955 # Fake fines cronjob on this checkout
2957 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2958 $ten_days_ago, $now );
2961 issue_id => $issue->issue_id,
2962 itemnumber => $item->itemnumber,
2963 borrowernumber => $patron->borrowernumber,
2965 due => output_pref($ten_days_ago)
2968 my $overdue_fees = Koha::Account::Lines->search(
2970 borrowernumber => $patron->id,
2971 itemnumber => $item->itemnumber,
2972 debit_type_code => 'OVERDUE'
2975 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
2976 my $overdue_fee = $overdue_fees->next;
2977 is( $overdue_fee->amount + 0,
2978 10, 'The right OVERDUE amount is generated' );
2979 is( $overdue_fee->amountoutstanding + 0,
2981 'The right OVERDUE amountoutstanding is generated' );
2983 # Simulate item marked as lost
2984 $item->itemlost(3)->store;
2985 C4::Circulation::LostItem( $item->itemnumber, 1 );
2987 my $lost_fee_lines = Koha::Account::Lines->search(
2989 borrowernumber => $patron->id,
2990 itemnumber => $item->itemnumber,
2991 debit_type_code => 'LOST'
2994 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
2995 my $lost_fee_line = $lost_fee_lines->next;
2996 is( $lost_fee_line->amount + 0,
2997 $replacement_amount, 'The right LOST amount is generated' );
2998 is( $lost_fee_line->amountoutstanding + 0,
2999 $replacement_amount,
3000 'The right LOST amountoutstanding is generated' );
3001 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3004 my ( $returned, $message ) =
3005 AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
3007 $overdue_fee->discard_changes;
3008 is( $overdue_fee->amount + 0,
3009 10, 'The OVERDUE amount is left intact' );
3010 is( $overdue_fee->amountoutstanding + 0,
3012 'The OVERDUE amountoutstanding is left intact' );
3014 $lost_fee_line->discard_changes;
3015 is( $lost_fee_line->amount + 0,
3016 $replacement_amount, 'The LOST amount is left intact' );
3017 is( $lost_fee_line->amountoutstanding + 0,
3018 $replacement_amount,
3019 'The LOST amountoutstanding is left intact' );
3020 # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
3021 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3024 subtest 'lostreturn | refund' => sub {
3027 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
3029 my $item = $builder->build_sample_item(
3031 replacementprice => $replacement_amount
3036 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3038 # Fake fines cronjob on this checkout
3040 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3041 $ten_days_ago, $now );
3044 issue_id => $issue->issue_id,
3045 itemnumber => $item->itemnumber,
3046 borrowernumber => $patron->borrowernumber,
3048 due => output_pref($ten_days_ago)
3051 my $overdue_fees = Koha::Account::Lines->search(
3053 borrowernumber => $patron->id,
3054 itemnumber => $item->itemnumber,
3055 debit_type_code => 'OVERDUE'
3058 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3059 my $overdue_fee = $overdue_fees->next;
3060 is( $overdue_fee->amount + 0,
3061 10, 'The right OVERDUE amount is generated' );
3062 is( $overdue_fee->amountoutstanding + 0,
3064 'The right OVERDUE amountoutstanding is generated' );
3066 # Simulate item marked as lost
3067 $item->itemlost(3)->store;
3068 C4::Circulation::LostItem( $item->itemnumber, 1 );
3070 my $lost_fee_lines = Koha::Account::Lines->search(
3072 borrowernumber => $patron->id,
3073 itemnumber => $item->itemnumber,
3074 debit_type_code => 'LOST'
3077 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3078 my $lost_fee_line = $lost_fee_lines->next;
3079 is( $lost_fee_line->amount + 0,
3080 $replacement_amount, 'The right LOST amount is generated' );
3081 is( $lost_fee_line->amountoutstanding + 0,
3082 $replacement_amount,
3083 'The right LOST amountoutstanding is generated' );
3084 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3086 # Return the lost item
3087 my ( undef, $message ) =
3088 AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
3090 $overdue_fee->discard_changes;
3091 is( $overdue_fee->amount + 0,
3092 10, 'The OVERDUE amount is left intact' );
3093 is( $overdue_fee->amountoutstanding + 0,
3095 'The OVERDUE amountoutstanding is left intact' );
3097 $lost_fee_line->discard_changes;
3098 is( $lost_fee_line->amount + 0,
3099 $replacement_amount, 'The LOST amount is left intact' );
3100 is( $lost_fee_line->amountoutstanding + 0,
3102 'The LOST amountoutstanding is refunded' );
3103 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3106 subtest 'lostreturn | restore' => sub {
3109 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
3111 my $item = $builder->build_sample_item(
3113 replacementprice => $replacement_amount
3118 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode , $ten_days_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 my $overdue_fees = Koha::Account::Lines->search(
3135 borrowernumber => $patron->id,
3136 itemnumber => $item->itemnumber,
3137 debit_type_code => 'OVERDUE'
3140 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3141 my $overdue_fee = $overdue_fees->next;
3142 is( $overdue_fee->amount + 0,
3143 10, 'The right OVERDUE amount is generated' );
3144 is( $overdue_fee->amountoutstanding + 0,
3146 'The right OVERDUE amountoutstanding is generated' );
3148 # Simulate item marked as lost
3149 $item->itemlost(3)->store;
3150 C4::Circulation::LostItem( $item->itemnumber, 1 );
3152 my $lost_fee_lines = Koha::Account::Lines->search(
3154 borrowernumber => $patron->id,
3155 itemnumber => $item->itemnumber,
3156 debit_type_code => 'LOST'
3159 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3160 my $lost_fee_line = $lost_fee_lines->next;
3161 is( $lost_fee_line->amount + 0,
3162 $replacement_amount, 'The right LOST amount is generated' );
3163 is( $lost_fee_line->amountoutstanding + 0,
3164 $replacement_amount,
3165 'The right LOST amountoutstanding is generated' );
3166 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3168 # Simulate refunding overdue fees upon marking item as lost
3169 my $overdue_forgive = $patron->account->add_credit(
3172 user_id => $manager->borrowernumber,
3173 library_id => $branchcode_restore,
3174 interface => 'test',
3176 item_id => $item->itemnumber
3179 $overdue_forgive->apply(
3180 { debits => [$overdue_fee], offset_type => 'Forgiven' } );
3181 $overdue_fee->discard_changes;
3182 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3185 my ( undef, $message ) =
3186 AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
3188 $overdue_fee->discard_changes;
3189 is( $overdue_fee->amount + 0,
3190 10, 'The OVERDUE amount is left intact' );
3191 is( $overdue_fee->amountoutstanding + 0,
3193 'The OVERDUE amountoutstanding is restored' );
3195 $lost_fee_line->discard_changes;
3196 is( $lost_fee_line->amount + 0,
3197 $replacement_amount, 'The LOST amount is left intact' );
3198 is( $lost_fee_line->amountoutstanding + 0,
3200 'The LOST amountoutstanding is refunded' );
3201 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3204 subtest 'lostreturn | charge' => sub {
3207 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
3209 my $item = $builder->build_sample_item(
3211 replacementprice => $replacement_amount
3216 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3218 # Fake fines cronjob on this checkout
3220 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3221 $ten_days_ago, $now );
3224 issue_id => $issue->issue_id,
3225 itemnumber => $item->itemnumber,
3226 borrowernumber => $patron->borrowernumber,
3228 due => output_pref($ten_days_ago)
3231 my $overdue_fees = Koha::Account::Lines->search(
3233 borrowernumber => $patron->id,
3234 itemnumber => $item->itemnumber,
3235 debit_type_code => 'OVERDUE'
3238 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3239 my $overdue_fee = $overdue_fees->next;
3240 is( $overdue_fee->amount + 0,
3241 10, 'The right OVERDUE amount is generated' );
3242 is( $overdue_fee->amountoutstanding + 0,
3244 'The right OVERDUE amountoutstanding is generated' );
3246 # Simulate item marked as lost
3247 $item->itemlost(3)->store;
3248 C4::Circulation::LostItem( $item->itemnumber, 1 );
3250 my $lost_fee_lines = Koha::Account::Lines->search(
3252 borrowernumber => $patron->id,
3253 itemnumber => $item->itemnumber,
3254 debit_type_code => 'LOST'
3257 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3258 my $lost_fee_line = $lost_fee_lines->next;
3259 is( $lost_fee_line->amount + 0,
3260 $replacement_amount, 'The right LOST amount is generated' );
3261 is( $lost_fee_line->amountoutstanding + 0,
3262 $replacement_amount,
3263 'The right LOST amountoutstanding is generated' );
3264 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3266 # Simulate refunding overdue fees upon marking item as lost
3267 my $overdue_forgive = $patron->account->add_credit(
3270 user_id => $manager->borrowernumber,
3271 library_id => $branchcode_charge,
3272 interface => 'test',
3274 item_id => $item->itemnumber
3277 $overdue_forgive->apply(
3278 { debits => [$overdue_fee], offset_type => 'Forgiven' } );
3279 $overdue_fee->discard_changes;
3280 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3283 my ( undef, $message ) =
3284 AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
3286 $lost_fee_line->discard_changes;
3287 is( $lost_fee_line->amount + 0,
3288 $replacement_amount, 'The LOST amount is left intact' );
3289 is( $lost_fee_line->amountoutstanding + 0,
3291 'The LOST amountoutstanding is refunded' );
3292 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3294 $overdue_fees = Koha::Account::Lines->search(
3296 borrowernumber => $patron->id,
3297 itemnumber => $item->itemnumber,
3298 debit_type_code => 'OVERDUE'
3301 order_by => { '-asc' => 'accountlines_id'}
3304 is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
3305 $overdue_fee = $overdue_fees->next;
3306 is( $overdue_fee->amount + 0,
3307 10, 'The original OVERDUE amount is left intact' );
3308 is( $overdue_fee->amountoutstanding + 0,
3310 'The original OVERDUE amountoutstanding is left as forgiven' );
3311 $overdue_fee = $overdue_fees->next;
3312 is( $overdue_fee->amount + 0,
3313 5, 'The new OVERDUE amount is correct for the backdated return' );
3314 is( $overdue_fee->amountoutstanding + 0,
3316 'The new OVERDUE amountoutstanding is correct for the backdated return' );
3321 subtest '_FixOverduesOnReturn' => sub {
3324 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3325 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3327 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3329 my $branchcode = $library2->{branchcode};
3331 my $item = $builder->build_sample_item(
3333 biblionumber => $biblio->biblionumber,
3334 library => $branchcode,
3335 replacementprice => 99.00,
3340 my $patron = $builder->build( { source => 'Borrower' } );
3342 ## Start with basic call, should just close out the open fine
3343 my $accountline = Koha::Account::Line->new(
3345 borrowernumber => $patron->{borrowernumber},
3346 debit_type_code => 'OVERDUE',
3347 status => 'UNRETURNED',
3348 itemnumber => $item->itemnumber,
3350 amountoutstanding => 99.00,
3351 interface => 'test',
3355 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
3357 $accountline->_result()->discard_changes();
3359 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
3360 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3361 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3363 ## Run again, with exemptfine enabled
3366 debit_type_code => 'OVERDUE',
3367 status => 'UNRETURNED',
3368 amountoutstanding => 99.00,
3372 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3374 $accountline->_result()->discard_changes();
3375 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
3377 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
3378 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3379 is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
3380 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
3381 is( $offset->amount + 0, -99, "Amount of offset is correct" );
3382 my $credit = $offset->credit;
3383 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
3384 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
3385 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
3387 # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
3390 debit_type_code => 'OVERDUE',
3391 status => 'UNRETURNED',
3392 amountoutstanding => 0.00,
3397 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3399 $accountline->_result()->discard_changes();
3400 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
3401 is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
3402 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3403 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3406 subtest 'Set waiting flag' => sub {
3409 my $library_1 = $builder->build( { source => 'Branch' } );
3410 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3411 my $library_2 = $builder->build( { source => 'Branch' } );
3412 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3414 my $item = $builder->build_sample_item(
3416 library => $library_1->{branchcode},
3420 set_userenv( $library_2 );
3421 my $reserve_id = AddReserve(
3423 branchcode => $library_2->{branchcode},
3424 borrowernumber => $patron_2->{borrowernumber},
3425 biblionumber => $item->biblionumber,
3427 itemnumber => $item->itemnumber,
3431 set_userenv( $library_1 );
3432 my $do_transfer = 1;
3433 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3434 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3435 my $hold = Koha::Holds->find( $reserve_id );
3436 is( $hold->found, 'T', 'Hold is in transit' );
3438 my ( $status ) = CheckReserves($item->itemnumber);
3439 is( $status, 'Transferred', 'Hold is not waiting yet');
3441 set_userenv( $library_2 );
3443 AddReturn( $item->barcode, $library_2->{branchcode} );
3444 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3445 $hold = Koha::Holds->find( $reserve_id );
3446 is( $hold->found, 'W', 'Hold is waiting' );
3447 ( $status ) = CheckReserves($item->itemnumber);
3448 is( $status, 'Waiting', 'Now the hold is waiting');
3450 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
3451 set_userenv( $library_1 );
3452 (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
3453 $hold = Koha::Holds->find( $reserve_id );
3454 is( $hold->found, undef, 'Hold is no longer marked waiting' );
3455 is( $hold->priority, 1, "Hold is now priority one again");
3456 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
3457 is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
3458 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
3459 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
3460 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
3463 subtest 'Cancel transfers on lost items' => sub {
3465 my $library_1 = $builder->build( { source => 'Branch' } );
3466 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3467 my $library_2 = $builder->build( { source => 'Branch' } );
3468 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3469 my $biblio = $builder->build_sample_biblio({branchcode => $library->{branchcode}});
3470 my $item = $builder->build_sample_item({
3471 biblionumber => $biblio->biblionumber,
3472 library => $library_1->{branchcode},
3475 set_userenv( $library_2 );
3476 my $reserve_id = AddReserve(
3478 branchcode => $library_2->{branchcode},
3479 borrowernumber => $patron_2->{borrowernumber},
3480 biblionumber => $item->biblionumber,
3482 itemnumber => $item->itemnumber,
3486 #Return book and add transfer
3487 set_userenv( $library_1 );
3488 my $do_transfer = 1;
3489 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3490 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3491 C4::Circulation::transferbook({
3492 from_branch => $library_1->{branchcode},
3493 to_branch => $library_2->{branchcode},
3494 barcode => $item->barcode,
3496 my $hold = Koha::Holds->find( $reserve_id );
3497 is( $hold->found, 'T', 'Hold is in transit' );
3499 #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
3500 my ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
3501 is( $frombranch, $library_1->{branchcode}, 'The transfer is generated from the correct library');
3502 is( $tobranch, $library_2->{branchcode}, 'The transfer is generated to the correct library');
3503 my $itemcheck = Koha::Items->find($item->itemnumber);
3504 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Items holding branch is the transfers origination branch before it is marked as lost' );
3506 #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
3507 $item->itemlost(1)->store;
3508 LostItem( $item->itemnumber, 'test', 1 );
3509 ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
3510 is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
3511 $itemcheck = Koha::Items->find($item->itemnumber);
3512 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
3516 subtest 'CanBookBeIssued | is_overdue' => sub {
3519 # Set a simple circ policy
3520 Koha::CirculationRules->set_rules(
3522 categorycode => undef,
3523 branchcode => undef,
3527 reservesallowed => 25,
3529 lengthunit => 'days',
3530 renewalsallowed => 1,
3532 norenewalbefore => undef,
3540 my $now = dt_from_string;
3541 my $five_days_go = output_pref({ dt => $now->clone->add( days => 5 ), dateonly => 1});
3542 my $ten_days_go = output_pref({ dt => $now->clone->add( days => 10), dateonly => 1 });
3543 my $library = $builder->build( { source => 'Branch' } );
3544 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
3546 my $item = $builder->build_sample_item(
3548 library => $library->{branchcode},
3552 my $issue = AddIssue( $patron->unblessed, $item->barcode, $five_days_go ); # date due was 10d ago
3553 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
3554 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
3555 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->barcode,$ten_days_go, undef, undef, undef);
3556 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
3557 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
3560 subtest 'ItemsDeniedRenewal preference' => sub {
3563 C4::Context->set_preference('ItemsDeniedRenewal','');
3565 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
3566 Koha::CirculationRules->set_rules(
3568 categorycode => '*',
3570 branchcode => $idr_lib->branchcode,
3572 reservesallowed => 25,
3574 lengthunit => 'days',
3575 renewalsallowed => 10,
3577 norenewalbefore => undef,
3585 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
3586 homebranch => $idr_lib->branchcode,
3590 itemcallnumber => undef,
3594 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
3595 homebranch => $idr_lib->branchcode,
3598 location => 'NOPROC'
3602 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
3603 branchcode => $idr_lib->branchcode,
3606 my $future = dt_from_string->add( days => 1 );
3607 my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3608 returndate => undef,
3611 borrowernumber => $idr_borrower->borrowernumber,
3612 itemnumber => $deny_book->itemnumber,
3613 onsite_checkout => 0,
3614 date_due => $future,
3617 my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3618 returndate => undef,
3621 borrowernumber => $idr_borrower->borrowernumber,
3622 itemnumber => $allow_book->itemnumber,
3623 onsite_checkout => 0,
3624 date_due => $future,
3630 my ( $idr_mayrenew, $idr_error ) =
3631 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3632 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3633 is( $idr_error, undef, 'Renewal allowed when no rules' );
3635 $idr_rules="withdrawn: [1]";
3637 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3638 ( $idr_mayrenew, $idr_error ) =
3639 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3640 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3641 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3642 ( $idr_mayrenew, $idr_error ) =
3643 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3644 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3645 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3647 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
3649 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3650 ( $idr_mayrenew, $idr_error ) =
3651 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3652 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
3653 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
3654 ( $idr_mayrenew, $idr_error ) =
3655 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3656 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3657 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3659 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
3661 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3662 ( $idr_mayrenew, $idr_error ) =
3663 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3664 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
3665 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
3666 ( $idr_mayrenew, $idr_error ) =
3667 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3668 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3669 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3671 $idr_rules="itemcallnumber: [NULL]";
3672 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3673 ( $idr_mayrenew, $idr_error ) =
3674 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3675 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
3676 $idr_rules="itemcallnumber: ['']";
3677 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3678 ( $idr_mayrenew, $idr_error ) =
3679 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3680 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
3682 $idr_rules="itemnotes: [NULL]";
3683 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3684 ( $idr_mayrenew, $idr_error ) =
3685 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3686 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
3687 $idr_rules="itemnotes: ['']";
3688 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3689 ( $idr_mayrenew, $idr_error ) =
3690 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3691 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
3694 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
3697 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3698 my $library = $builder->build( { source => 'Branch' } );
3699 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3701 my $item = $builder->build_sample_item(
3703 library => $library->{branchcode},
3707 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3708 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3709 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3712 subtest 'CanBookBeIssued | notforloan' => sub {
3715 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
3717 my $library = $builder->build( { source => 'Branch' } );
3718 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3720 my $itemtype = $builder->build(
3722 source => 'Itemtype',
3723 value => { notforloan => undef, }
3726 my $item = $builder->build_sample_item(
3728 library => $library->{branchcode},
3729 itype => $itemtype->{itemtype},
3732 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3734 my ( $issuingimpossible, $needsconfirmation );
3737 subtest 'item-level_itypes = 1' => sub {
3740 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
3741 # Is for loan at item type and item level
3742 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3743 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3744 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3746 # not for loan at item type level
3747 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3748 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3749 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3752 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3753 'Item can not be issued, not for loan at item type level'
3756 # not for loan at item level
3757 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3758 $item->notforloan( 1 )->store;
3759 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3760 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3763 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3764 'Item can not be issued, not for loan at item type level'
3768 subtest 'item-level_itypes = 0' => sub {
3771 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3773 # We set another itemtype for biblioitem
3774 my $itemtype = $builder->build(
3776 source => 'Itemtype',
3777 value => { notforloan => undef, }
3781 # for loan at item type and item level
3782 $item->notforloan(0)->store;
3783 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3784 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3785 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3786 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3788 # not for loan at item type level
3789 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3790 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3791 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3794 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3795 'Item can not be issued, not for loan at item type level'
3798 # not for loan at item level
3799 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3800 $item->notforloan( 1 )->store;
3801 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3802 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3805 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3806 'Item can not be issued, not for loan at item type level'
3810 # TODO test with AllowNotForLoanOverride = 1
3813 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
3816 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
3817 my $item = $builder->build_sample_item(
3819 onloan => '2018-01-01',
3823 AddReturn( $item->barcode, $item->homebranch );
3824 $item->discard_changes; # refresh
3825 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
3829 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
3834 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3836 my $issuing_charges = 15;
3837 my $title = 'A title';
3838 my $author = 'Author, An';
3839 my $barcode = 'WHATARETHEODDS';
3841 my $circ = Test::MockModule->new('C4::Circulation');
3843 'GetIssuingCharges',
3845 return $issuing_charges;
3849 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3850 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
3851 my $patron = $builder->build_object({
3852 class => 'Koha::Patrons',
3853 value => { branchcode => $library->id }
3856 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
3857 my $item_id = Koha::Item->new(
3859 biblionumber => $biblio->biblionumber,
3860 homebranch => $library->id,
3861 holdingbranch => $library->id,
3862 barcode => $barcode,
3863 replacementprice => 23.00,
3864 itype => $itemtype->id
3866 )->store->itemnumber;
3867 my $item = Koha::Items->find( $item_id );
3869 my $context = Test::MockModule->new('C4::Context');
3870 $context->mock( userenv => { branch => $library->id } );
3872 # Check the item out
3873 AddIssue( $patron->unblessed, $item->barcode );
3876 AddRenewal( $patron->borrowernumber, $item->itemnumber, $library->id, undef, {break=>"the_renewal"} );
3877 } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
3879 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
3880 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3881 my %params_renewal = (
3882 timestamp => { -like => $date . "%" },
3883 module => "CIRCULATION",
3884 action => "RENEWAL",
3886 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
3887 AddRenewal( $patron->id, $item->id, $library->id );
3888 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3889 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
3891 my $checkouts = $patron->checkouts;
3892 # The following will fail if run on 00:00:00
3893 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
3895 my $lines = Koha::Account::Lines->search({
3896 borrowernumber => $patron->id,
3897 itemnumber => $item->id
3900 is( $lines->count, 2 );
3902 my $line = $lines->next;
3903 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
3904 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
3905 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
3907 $line = $lines->next;
3908 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
3909 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
3910 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
3912 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
3914 $context = Test::MockModule->new('C4::Context');
3915 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
3917 my $now = dt_from_string;
3918 $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
3919 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
3920 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
3921 $sth->execute($item->id, $library->id);
3922 my ($old_stats_size) = $sth->fetchrow_array;
3923 AddRenewal( $patron->id, $item->id, $library->id );
3924 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3925 $sth->execute($item->id, $library->id);
3926 my ($new_stats_size) = $sth->fetchrow_array;
3927 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
3928 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
3930 AddReturn( $item->id, $library->id, undef, $date );
3931 AddIssue( $patron->unblessed, $item->barcode, $now );
3932 AddRenewal( $patron->id, $item->id, $library->id, undef, undef, 1 );
3933 my $lines_skipped = Koha::Account::Lines->search({
3934 borrowernumber => $patron->id,
3935 itemnumber => $item->id
3937 is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
3941 subtest 'ProcessOfflinePayment() tests' => sub {
3948 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
3949 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3950 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
3952 is( $result, 'Success.', 'The right string is returned' );
3954 my $lines = $patron->account->lines;
3955 is( $lines->count, 1, 'line created correctly');
3957 my $line = $lines->next;
3958 is( $line->amount+0, $amount * -1, 'amount picked from params' );
3959 is( $line->branchcode, $library->id, 'branchcode set correctly' );
3963 subtest 'Incremented fee tests' => sub {
3966 my $dt = dt_from_string();
3967 Time::Fake->offset( $dt->epoch );
3969 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
3972 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3974 $module->mock( 'userenv', sub { { branch => $library->id } } );
3976 my $patron = $builder->build_object(
3978 class => 'Koha::Patrons',
3979 value => { categorycode => $patron_category->{categorycode} }
3983 my $itemtype = $builder->build_object(
3985 class => 'Koha::ItemTypes',
3987 notforloan => undef,
3989 rentalcharge_daily => 1,
3990 rentalcharge_daily_calendar => 0
3995 my $item = $builder->build_sample_item(
3997 library => $library->{branchcode},
3998 itype => $itemtype->id,
4002 is( $itemtype->rentalcharge_daily+0,
4003 1, 'Daily rental charge stored and retreived correctly' );
4004 is( $item->effective_itemtype, $itemtype->id,
4005 "Itemtype set correctly for item" );
4007 my $now = dt_from_string;
4008 my $dt_from = $now->clone;
4009 my $dt_to = $now->clone->add( days => 7 );
4010 my $dt_to_renew = $now->clone->add( days => 13 );
4014 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4015 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4016 is( $accountline->amount+0, 7,
4017 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
4019 $accountline->delete();
4020 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4021 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4022 is( $accountline->amount+0, 6,
4023 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
4025 $accountline->delete();
4028 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
4029 $itemtype->rentalcharge_daily_calendar(1)->store();
4031 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4032 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4033 is( $accountline->amount+0, 7,
4034 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
4036 $accountline->delete();
4037 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4038 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4039 is( $accountline->amount+0, 6,
4040 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
4042 $accountline->delete();
4045 my $calendar = C4::Calendar->new( branchcode => $library->id );
4046 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
4048 ( $dt_from->day_of_week == 6 ) ? 0
4049 : ( $dt_from->day_of_week == 7 ) ? 1
4050 : $dt_from->day_of_week + 1;
4051 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
4052 $calendar->insert_week_day_holiday(
4053 weekday => $closed_day,
4054 title => 'Test holiday',
4055 description => 'Test holiday'
4058 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4059 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4060 is( $accountline->amount+0, 6,
4061 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
4063 $accountline->delete();
4064 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4065 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4066 is( $accountline->amount+0, 5,
4067 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
4069 $accountline->delete();
4072 $itemtype->rentalcharge(2)->store;
4073 is( $itemtype->rentalcharge+0, 2,
4074 'Rental charge updated and retreived correctly' );
4076 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4078 Koha::Account::Lines->search( { itemnumber => $item->id } );
4079 is( $accountlines->count, '2',
4080 "Fixed charge and accrued charge recorded distinctly" );
4081 $accountlines->delete();
4082 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4083 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
4084 is( $accountlines->count, '2',
4085 "Fixed charge and accrued charge recorded distinctly, for renewal" );
4086 $accountlines->delete();
4088 $itemtype->rentalcharge(0)->store;
4089 is( $itemtype->rentalcharge+0, 0,
4090 'Rental charge reset and retreived correctly' );
4093 Koha::CirculationRules->set_rule(
4095 categorycode => $patron->categorycode,
4096 itemtype => $itemtype->id,
4097 branchcode => $library->id,
4098 rule_name => 'lengthunit',
4099 rule_value => 'hours',
4103 $itemtype->rentalcharge_hourly('0.25')->store();
4104 is( $itemtype->rentalcharge_hourly,
4105 '0.25', 'Hourly rental charge stored and retreived correctly' );
4107 $dt_to = $now->clone->add( hours => 168 );
4108 $dt_to_renew = $now->clone->add( hours => 312 );
4110 $itemtype->rentalcharge_hourly_calendar(0)->store();
4112 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4113 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4114 is( $accountline->amount + 0, 42,
4115 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)" );
4116 $accountline->delete();
4117 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4118 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4119 is( $accountline->amount + 0, 36,
4120 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)" );
4121 $accountline->delete();
4124 $itemtype->rentalcharge_hourly_calendar(1)->store();
4126 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4127 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4128 is( $accountline->amount + 0, 36,
4129 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)" );
4130 $accountline->delete();
4131 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4132 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4133 is( $accountline->amount + 0, 30,
4134 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
4135 $accountline->delete();
4138 $calendar->delete_holiday( weekday => $closed_day );
4140 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4141 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4142 is( $accountline->amount + 0, 42,
4143 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u" );
4144 $accountline->delete();
4145 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4146 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4147 is( $accountline->amount + 0, 36,
4148 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)" );
4149 $accountline->delete();
4154 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
4157 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
4158 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4161 $builder->build_object( { class => 'Koha::Libraries' } )->store;
4162 my $patron = $builder->build_object(
4164 class => 'Koha::Patrons',
4165 value => { categorycode => $patron_category->{categorycode} }
4169 my $itemtype = $builder->build_object(
4171 class => 'Koha::ItemTypes',
4175 rentalcharge_daily => 0
4180 my $item = $builder->build_sample_item(
4182 library => $library->id,
4186 itype => $itemtype->id,
4190 my ( $issuingimpossible, $needsconfirmation );
4191 my $dt_from = dt_from_string();
4192 my $dt_due = $dt_from->clone->add( days => 3 );
4194 $itemtype->rentalcharge(1)->store;
4195 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4196 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
4197 $itemtype->rentalcharge('0')->store;
4198 $itemtype->rentalcharge_daily(1)->store;
4199 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4200 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
4201 $itemtype->rentalcharge_daily('0')->store;
4204 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
4207 t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
4209 my $patron = $builder->build_object(
4211 class => 'Koha::Patrons',
4212 value => { categorycode => $patron_category->{categorycode} }
4216 my $item = $builder->build_sample_item(
4218 materials => 'includes DVD',
4222 my $dt_due = dt_from_string->add( days => 3 );
4224 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4225 is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
4228 subtest 'Do not return on renewal (LOST charge)' => sub {
4231 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
4232 my $library = $builder->build_object( { class => "Koha::Libraries" } );
4233 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
4234 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
4236 my $biblio = $builder->build_sample_biblio;
4238 my $item = $builder->build_sample_item(
4240 biblionumber => $biblio->biblionumber,
4241 library => $library->branchcode,
4242 replacementprice => 99.00,
4247 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
4248 AddIssue( $patron->unblessed, $item->barcode );
4250 my $accountline = Koha::Account::Line->new(
4252 borrowernumber => $patron->borrowernumber,
4253 debit_type_code => 'LOST',
4255 itemnumber => $item->itemnumber,
4257 amountoutstanding => 12,
4258 interface => 'something',
4262 # AddRenewal doesn't call _FixAccountForLostAndFound
4263 AddIssue( $patron->unblessed, $item->barcode );
4265 is( $patron->checkouts->count, 1,
4266 'Renewal should not return the item even if a LOST payment has been made earlier'
4270 subtest 'Filling a hold should cancel existing transfer' => sub {
4273 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
4275 my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
4276 my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
4277 my $patron = $builder->build_object(
4279 class => 'Koha::Patrons',
4281 categorycode => $patron_category->{categorycode},
4282 branchcode => $libraryA->branchcode,
4287 my $item = $builder->build_sample_item({
4288 homebranch => $libraryB->branchcode,
4291 my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4292 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
4294 branchcode => $libraryA->branchcode,
4295 borrowernumber => $patron->borrowernumber,
4296 biblionumber => $item->biblionumber,
4297 itemnumber => $item->itemnumber
4299 my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
4300 is( $reserves->count, 1, "Reserve is placed");
4301 ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4302 my $reserve = $reserves->next;
4303 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
4304 $reserve->discard_changes;
4305 ok( $reserve->found eq 'W', "Reserve is marked waiting" );
4306 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
4309 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
4313 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4314 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4315 my $patron = $builder->build_object(
4317 class => 'Koha::Patrons',
4318 value => { categorycode => $patron_category->{categorycode} }
4322 my $biblionumber = $builder->build_sample_biblio(
4324 branchcode => $library->branchcode,
4328 # And the circulation rule
4329 Koha::CirculationRules->search->delete;
4330 Koha::CirculationRules->set_rules(
4332 categorycode => undef,
4334 branchcode => undef,
4337 lengthunit => 'days',
4343 source => 'CirculationRule',
4345 branchcode => undef,
4346 categorycode => undef,
4348 rule_name => 'lostreturn',
4349 rule_value => 'refund'
4354 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4357 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4358 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4360 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4362 my $item = $builder->build_sample_item(
4364 biblionumber => $biblionumber,
4365 library => $library->branchcode,
4366 replacementprice => '42',
4369 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4370 LostItem( $item->itemnumber, 'cli', 0 );
4371 $item->_result->itemlost(1);
4372 $item->_result->itemlost_on( $lost_on );
4373 $item->_result->update();
4375 my $a = Koha::Account::Lines->search(
4377 itemnumber => $item->id,
4378 borrowernumber => $patron->borrowernumber
4381 ok( $a, "Found accountline for lost fee" );
4382 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4383 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4384 $a = $a->get_from_storage;
4385 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4389 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4392 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4393 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4395 my $lost_on = dt_from_string->subtract( days => 6 )->date;
4397 my $item = $builder->build_sample_item(
4399 biblionumber => $biblionumber,
4400 library => $library->branchcode,
4401 replacementprice => '42',
4404 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4405 LostItem( $item->itemnumber, 'cli', 0 );
4406 $item->_result->itemlost(1);
4407 $item->_result->itemlost_on( $lost_on );
4408 $item->_result->update();
4410 my $a = Koha::Account::Lines->search(
4412 itemnumber => $item->id,
4413 borrowernumber => $patron->borrowernumber
4416 ok( $a, "Found accountline for lost fee" );
4417 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4418 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4419 $a = $a->get_from_storage;
4420 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4424 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4427 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4428 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4430 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4432 my $item = $builder->build_sample_item(
4434 biblionumber => $biblionumber,
4435 library => $library->branchcode,
4436 replacementprice => '42',
4439 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4440 LostItem( $item->itemnumber, 'cli', 0 );
4441 $item->_result->itemlost(1);
4442 $item->_result->itemlost_on( $lost_on );
4443 $item->_result->update();
4445 my $a = Koha::Account::Lines->search(
4447 itemnumber => $item->id,
4448 borrowernumber => $patron->borrowernumber
4451 ok( $a, "Found accountline for lost fee" );
4452 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4453 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4454 $a = $a->get_from_storage;
4455 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4459 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4462 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4463 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4465 my $lost_on = dt_from_string->subtract( days => 8 )->date;
4467 my $item = $builder->build_sample_item(
4469 biblionumber => $biblionumber,
4470 library => $library->branchcode,
4471 replacementprice => '42',
4474 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4475 LostItem( $item->itemnumber, 'cli', 0 );
4476 $item->_result->itemlost(1);
4477 $item->_result->itemlost_on( $lost_on );
4478 $item->_result->update();
4480 my $a = Koha::Account::Lines->search(
4482 itemnumber => $item->id,
4483 borrowernumber => $patron->borrowernumber
4487 ok( $a, "Found accountline for lost fee" );
4488 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4489 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4490 $a = $a->get_from_storage;
4491 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4496 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
4500 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4501 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4502 my $patron = $builder->build_object(
4504 class => 'Koha::Patrons',
4505 value => { categorycode => $patron_category->{categorycode} }
4508 my $patron2 = $builder->build_object(
4510 class => 'Koha::Patrons',
4511 value => { categorycode => $patron_category->{categorycode} }
4515 my $biblionumber = $builder->build_sample_biblio(
4517 branchcode => $library->branchcode,
4521 # And the circulation rule
4522 Koha::CirculationRules->search->delete;
4523 Koha::CirculationRules->set_rules(
4525 categorycode => undef,
4527 branchcode => undef,
4530 lengthunit => 'days',
4536 source => 'CirculationRule',
4538 branchcode => undef,
4539 categorycode => undef,
4541 rule_name => 'lostreturn',
4542 rule_value => 'refund'
4547 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4550 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4551 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4553 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4555 my $item = $builder->build_sample_item(
4557 biblionumber => $biblionumber,
4558 library => $library->branchcode,
4559 replacementprice => '42',
4562 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4563 LostItem( $item->itemnumber, 'cli', 0 );
4564 $item->_result->itemlost(1);
4565 $item->_result->itemlost_on( $lost_on );
4566 $item->_result->update();
4568 my $a = Koha::Account::Lines->search(
4570 itemnumber => $item->id,
4571 borrowernumber => $patron->borrowernumber
4574 ok( $a, "Found accountline for lost fee" );
4575 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4576 $issue = AddIssue( $patron2->unblessed, $item->barcode );
4577 $a = $a->get_from_storage;
4578 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4583 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4586 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4587 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4589 my $lost_on = dt_from_string->subtract( days => 6 )->date;
4591 my $item = $builder->build_sample_item(
4593 biblionumber => $biblionumber,
4594 library => $library->branchcode,
4595 replacementprice => '42',
4598 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4599 LostItem( $item->itemnumber, 'cli', 0 );
4600 $item->_result->itemlost(1);
4601 $item->_result->itemlost_on( $lost_on );
4602 $item->_result->update();
4604 my $a = Koha::Account::Lines->search(
4606 itemnumber => $item->id,
4607 borrowernumber => $patron->borrowernumber
4610 ok( $a, "Found accountline for lost fee" );
4611 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4612 $issue = AddIssue( $patron2->unblessed, $item->barcode );
4613 $a = $a->get_from_storage;
4614 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4618 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4621 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4622 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4624 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4626 my $item = $builder->build_sample_item(
4628 biblionumber => $biblionumber,
4629 library => $library->branchcode,
4630 replacementprice => '42',
4633 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4634 LostItem( $item->itemnumber, 'cli', 0 );
4635 $item->_result->itemlost(1);
4636 $item->_result->itemlost_on( $lost_on );
4637 $item->_result->update();
4639 my $a = Koha::Account::Lines->search(
4641 itemnumber => $item->id,
4642 borrowernumber => $patron->borrowernumber
4645 ok( $a, "Found accountline for lost fee" );
4646 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4647 $issue = AddIssue( $patron2->unblessed, $item->barcode );
4648 $a = $a->get_from_storage;
4649 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4653 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4656 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4657 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4659 my $lost_on = dt_from_string->subtract( days => 8 )->date;
4661 my $item = $builder->build_sample_item(
4663 biblionumber => $biblionumber,
4664 library => $library->branchcode,
4665 replacementprice => '42',
4668 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4669 LostItem( $item->itemnumber, 'cli', 0 );
4670 $item->_result->itemlost(1);
4671 $item->_result->itemlost_on( $lost_on );
4672 $item->_result->update();
4674 my $a = Koha::Account::Lines->search(
4676 itemnumber => $item->id,
4677 borrowernumber => $patron->borrowernumber
4681 ok( $a, "Found accountline for lost fee" );
4682 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4683 $issue = AddIssue( $patron2->unblessed, $item->barcode );
4684 $a = $a->get_from_storage;
4685 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4690 subtest 'transferbook tests' => sub {
4694 { C4::Circulation::transferbook({}); }
4695 'Koha::Exceptions::MissingParameter',
4696 'Koha::Patron->store raises an exception on missing params';
4699 { C4::Circulation::transferbook({to_branch=>'anything'}); }
4700 'Koha::Exceptions::MissingParameter',
4701 'Koha::Patron->store raises an exception on missing params';
4704 { C4::Circulation::transferbook({from_branch=>'anything'}); }
4705 'Koha::Exceptions::MissingParameter',
4706 'Koha::Patron->store raises an exception on missing params';
4708 my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
4709 is( $doreturn, 0, "No return without barcode");
4710 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
4711 is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
4713 ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
4714 is( $doreturn, 0, "No return without barcode");
4715 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
4716 is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
4720 subtest 'Checkout should correctly terminate a transfer' => sub {
4723 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
4724 my $patron_1 = $builder->build_object(
4726 class => 'Koha::Patrons',
4727 value => { branchcode => $library_1->branchcode }
4730 my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
4731 my $patron_2 = $builder->build_object(
4733 class => 'Koha::Patrons',
4734 value => { branchcode => $library_2->branchcode }
4738 my $item = $builder->build_sample_item(
4740 library => $library_1->branchcode,
4744 t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
4745 my $reserve_id = AddReserve(
4747 branchcode => $library_2->branchcode,
4748 borrowernumber => $patron_2->borrowernumber,
4749 biblionumber => $item->biblionumber,
4750 itemnumber => $item->itemnumber,
4755 my $do_transfer = 1;
4756 ModItemTransfer( $item->itemnumber, $library_1->branchcode,
4757 $library_2->branchcode );
4758 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
4759 GetOtherReserves( $item->itemnumber )
4760 ; # To put the Reason, it's what does returns.pl...
4761 my $hold = Koha::Holds->find($reserve_id);
4762 is( $hold->found, 'T', 'Hold is in transit' );
4763 my $transfer = $item->get_transfer;
4764 is( $transfer->frombranch, $library_1->branchcode );
4765 is( $transfer->tobranch, $library_2->branchcode );
4766 is( $transfer->reason, 'Reserve' );
4768 t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
4769 AddIssue( $patron_1->unblessed, $item->barcode );
4770 $transfer = $transfer->get_from_storage;
4771 isnt( $transfer->datearrived, undef );
4772 $hold = $hold->get_from_storage;
4773 is( $hold->found, undef, 'Hold is waiting' );
4774 is( $hold->priority, 1, );
4777 subtest 'AddIssue records staff who checked out item if appropriate' => sub {
4780 $module->mock( 'userenv', sub { { branch => $library->{id} } } );
4782 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4783 my $patron = $builder->build_object(
4785 class => 'Koha::Patrons',
4786 value => { categorycode => $patron_category->{categorycode} }
4789 my $issuer = $builder->build_object(
4791 class => 'Koha::Patrons',
4792 value => { categorycode => $patron_category->{categorycode} }
4795 my $item = $builder->build_sample_item(
4797 library => $library->{branchcode}
4801 $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->{borrowernumber} } } );
4803 my $dt_from = dt_from_string();
4804 my $dt_to = dt_from_string()->add( days => 7 );
4806 my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4808 is( $issue->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
4810 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
4813 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4815 is( $issue->issuer, $issuer->{borrowernumber}, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
4818 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
4821 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
4822 my $patron_1 = $builder->build_object(
4824 class => 'Koha::Patrons',
4825 value => { branchcode => $library_1->branchcode }
4828 my $patron_2 = $builder->build_object(
4830 class => 'Koha::Patrons',
4831 value => { branchcode => $library_1->branchcode }
4835 my $item = $builder->build_sample_item(
4837 library => $library_1->branchcode,
4841 AddIssue( $patron_1->unblessed, $item->barcode );
4842 ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
4843 AddIssue( $patron_2->unblessed, $item->barcode );
4844 ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
4847 $schema->storage->txn_rollback;
4848 C4::Context->clear_syspref_cache();
4849 $branches = Koha::Libraries->search();
4850 for my $branch ( $branches->next ) {
4851 my $key = $branch->branchcode . "_holidays";
4852 $cache->clear_from_cache($key);