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 => 53;
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 "GetIssuingCharges tests" => sub {
287 my $branch_discount = $builder->build_object({ class => 'Koha::Libraries' });
288 my $branch_no_discount = $builder->build_object({ class => 'Koha::Libraries' });
289 Koha::CirculationRules->set_rule(
291 categorycode => undef,
292 branchcode => $branch_discount->branchcode,
294 rule_name => 'rentaldiscount',
298 my $itype_charge = $builder->build_object({
299 class => 'Koha::ItemTypes',
304 my $itype_no_charge = $builder->build_object({
305 class => 'Koha::ItemTypes',
310 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
311 my $item_1 = $builder->build_sample_item({ itype => $itype_charge->itemtype });
312 my $item_2 = $builder->build_sample_item({ itype => $itype_no_charge->itemtype });
314 t::lib::Mocks::mock_userenv({ branchcode => $branch_no_discount->branchcode });
315 # For now the sub always uses the env branch, this should follow CircControl instead
316 my ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
317 is( $charge + 0, 10.00, "Charge fetched correctly when no discount exists");
318 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
319 is( $charge + 0, 0.00, "Charge fetched correctly when no discount exists and no charge");
321 t::lib::Mocks::mock_userenv({ branchcode => $branch_discount->branchcode });
322 # For now the sub always uses the env branch, this should follow CircControl instead
323 ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
324 is( $charge + 0, 8.50, "Charge fetched correctly when discount exists");
325 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
326 is( $charge + 0, 0.00, "Charge fetched correctly when discount exists and no charge");
330 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
331 subtest "CanBookBeRenewed tests" => sub {
334 C4::Context->set_preference('ItemsDeniedRenewal','');
335 # Generate test biblio
336 my $biblio = $builder->build_sample_biblio();
338 my $branch = $library2->{branchcode};
340 my $item_1 = $builder->build_sample_item(
342 biblionumber => $biblio->biblionumber,
344 replacementprice => 12.00,
348 $reused_itemnumber_1 = $item_1->itemnumber;
350 my $item_2 = $builder->build_sample_item(
352 biblionumber => $biblio->biblionumber,
354 replacementprice => 23.00,
358 $reused_itemnumber_2 = $item_2->itemnumber;
360 my $item_3 = $builder->build_sample_item(
362 biblionumber => $biblio->biblionumber,
364 replacementprice => 23.00,
370 my %renewing_borrower_data = (
372 surname => 'Renewal',
373 categorycode => $patron_category->{categorycode},
374 branchcode => $branch,
377 my %reserving_borrower_data = (
378 firstname => 'Katrin',
379 surname => 'Reservation',
380 categorycode => $patron_category->{categorycode},
381 branchcode => $branch,
384 my %hold_waiting_borrower_data = (
386 surname => 'Reservation',
387 categorycode => $patron_category->{categorycode},
388 branchcode => $branch,
391 my %restricted_borrower_data = (
392 firstname => 'Alice',
393 surname => 'Reservation',
394 categorycode => $patron_category->{categorycode},
395 debarred => '3228-01-01',
396 branchcode => $branch,
399 my %expired_borrower_data = (
402 categorycode => $patron_category->{categorycode},
403 branchcode => $branch,
404 dateexpiry => dt_from_string->subtract( months => 1 ),
407 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
408 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
409 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
410 my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
411 my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
413 my $renewing_borrower_obj = Koha::Patrons->find( $renewing_borrowernumber );
414 my $renewing_borrower = $renewing_borrower_obj->unblessed;
415 my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
416 my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
423 my $checkitem = undef;
426 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
427 my $datedue = dt_from_string( $issue->date_due() );
428 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
430 my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
431 $datedue = dt_from_string( $issue->date_due() );
432 is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
435 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
436 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
438 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
439 is( $renewokay, 1, 'Can renew, no holds for this title or item');
442 # Biblio-level hold, renewal test
445 branchcode => $branch,
446 borrowernumber => $reserving_borrowernumber,
447 biblionumber => $biblio->biblionumber,
448 priority => $priority,
449 reservation_date => $resdate,
450 expiration_date => $expdate,
452 itemnumber => $checkitem,
457 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
458 Koha::CirculationRules->set_rule(
460 categorycode => undef,
463 rule_name => 'onshelfholds',
467 Koha::CirculationRules->set_rule(
469 categorycode => undef,
472 rule_name => 'renewalsallowed',
476 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
477 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
478 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
479 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
480 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
482 # Now let's add an item level hold, we should no longer be able to renew the item
483 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
485 borrowernumber => $hold_waiting_borrowernumber,
486 biblionumber => $biblio->biblionumber,
487 itemnumber => $item_1->itemnumber,
488 branchcode => $branch,
492 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
493 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
496 # 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
497 # be able to renew these items
498 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
500 borrowernumber => $hold_waiting_borrowernumber,
501 biblionumber => $biblio->biblionumber,
502 itemnumber => $item_3->itemnumber,
503 branchcode => $branch,
508 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
509 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
510 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
511 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
512 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
514 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
515 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
516 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
518 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
519 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
520 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
522 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
523 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
524 AddIssue($reserving_borrower, $item_3->barcode);
525 my $reserve = $dbh->selectrow_hashref(
526 'SELECT * FROM old_reserves WHERE reserve_id = ?',
530 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
532 # Item-level hold, renewal test
535 branchcode => $branch,
536 borrowernumber => $reserving_borrowernumber,
537 biblionumber => $biblio->biblionumber,
538 priority => $priority,
539 reservation_date => $resdate,
540 expiration_date => $expdate,
542 itemnumber => $item_1->itemnumber,
547 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
548 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
549 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
551 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
552 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
554 # Items can't fill hold for reasons
555 $item_1->notforloan(1)->store;
556 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
557 is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
558 $item_1->set({notforloan => 0, itype => $itemtype })->store;
560 # FIXME: Add more for itemtype not for loan etc.
562 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
563 my $item_5 = $builder->build_sample_item(
565 biblionumber => $biblio->biblionumber,
567 replacementprice => 23.00,
571 my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
572 is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
574 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
575 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
576 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
577 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
578 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
579 is( $error, 'restriction', "Correct error returned");
581 # Users cannot renew an overdue item
582 my $item_6 = $builder->build_sample_item(
584 biblionumber => $biblio->biblionumber,
586 replacementprice => 23.00,
591 my $item_7 = $builder->build_sample_item(
593 biblionumber => $biblio->biblionumber,
595 replacementprice => 23.00,
600 my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
601 is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
603 my $now = dt_from_string();
604 my $five_weeks = DateTime::Duration->new(weeks => 5);
605 my $five_weeks_ago = $now - $five_weeks;
606 t::lib::Mocks::mock_preference('finesMode', 'production');
608 my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
609 is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
611 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
612 C4::Overdues::UpdateFine(
614 issue_id => $passeddatedue1->id(),
615 itemnumber => $item_7->itemnumber,
616 borrowernumber => $renewing_borrower->{borrowernumber},
618 due => Koha::DateUtils::output_pref($five_weeks_ago)
622 t::lib::Mocks::mock_preference('RenewalLog', 0);
623 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
624 my %params_renewal = (
625 timestamp => { -like => $date . "%" },
626 module => "CIRCULATION",
630 timestamp => { -like => $date . "%" },
631 module => "CIRCULATION",
634 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
635 my $dt = dt_from_string();
636 Time::Fake->offset( $dt->epoch );
637 my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
638 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
639 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
640 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
643 t::lib::Mocks::mock_preference('RenewalLog', 1);
644 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
645 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
646 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
647 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
648 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
650 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
651 is( $fines->count, 2, 'AddRenewal left both fines' );
652 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
653 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
656 t::lib::Mocks::mock_preference('OverduesBlockRenewing','allow');
657 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
658 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
659 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
660 is( $renewokay, 1, '(Bug 8236), Can renew, this item is overdue but not pref does not block');
662 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
663 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
664 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is not overdue but patron has overdues');
665 is( $error, 'overdue', "Correct error returned");
666 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
667 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue so patron has overdues');
668 is( $error, 'overdue', "Correct error returned");
670 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
671 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
672 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
673 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
674 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
675 is( $error, 'overdue', "Correct error returned");
678 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
679 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
680 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
681 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
682 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
683 $new_log_size = Koha::ActionLogs->count( \%params_issue );
684 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
686 $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
689 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
693 # Test automatic renewal before value for "norenewalbefore" in policy is set
694 # In this case automatic renewal is not permitted prior to due date
695 my $item_4 = $builder->build_sample_item(
697 biblionumber => $biblio->biblionumber,
699 replacementprice => 16.00,
704 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
705 ( $renewokay, $error ) =
706 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
707 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
708 is( $error, 'auto_too_soon',
709 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
712 branchcode => $branch,
713 borrowernumber => $reserving_borrowernumber,
714 biblionumber => $biblio->biblionumber,
715 itemnumber => $bibitems,
716 priority => $priority,
717 reservation_date => $resdate,
718 expiration_date => $expdate,
721 itemnumber => $item_4->itemnumber,
725 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
726 is( $renewokay, 0, 'Still should not be able to renew' );
727 is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' );
728 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, undef, 1 );
729 is( $renewokay, 0, 'Still should not be able to renew' );
730 is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' );
731 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
732 is( $renewokay, 0, 'Still should not be able to renew' );
733 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
734 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1, 1 );
735 is( $renewokay, 0, 'Still should not be able to renew' );
736 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
737 $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
738 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
739 is( $renewokay, 0, 'Still should not be able to renew' );
740 is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
741 ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
745 $renewing_borrower_obj->autorenew_checkouts(0)->store;
746 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
747 is( $renewokay, 1, 'No renewal before is undef, but patron opted out of auto_renewal' );
748 $renewing_borrower_obj->autorenew_checkouts(1)->store;
752 # Test premature manual renewal
753 Koha::CirculationRules->set_rule(
755 categorycode => undef,
758 rule_name => 'norenewalbefore',
763 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
764 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
765 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
768 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
769 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
771 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
772 $datedue->clone->add( days => -7 ),
773 'Bug 14395: Renewals permitted 7 days before due date, as expected'
777 # Test 'date' setting for syspref NoRenewalBeforePrecision
778 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
780 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
781 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
782 'Bug 14395: Renewals permitted 7 days before due date, as expected'
786 # Test premature automatic renewal
787 ( $renewokay, $error ) =
788 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
789 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
790 is( $error, 'auto_too_soon',
791 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
794 $renewing_borrower_obj->autorenew_checkouts(0)->store;
795 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
796 is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' );
797 is( $error, 'too_soon', 'Error is too_soon, no auto' );
798 $renewing_borrower_obj->autorenew_checkouts(1)->store;
800 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
801 # and test automatic renewal again
802 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
803 ( $renewokay, $error ) =
804 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
805 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
806 is( $error, 'auto_too_soon',
807 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
810 $renewing_borrower_obj->autorenew_checkouts(0)->store;
811 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
812 is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' );
813 is( $error, 'too_soon', 'Error is too_soon, no auto' );
814 $renewing_borrower_obj->autorenew_checkouts(1)->store;
816 # Change policy so that loans can be renewed 99 days prior to the due date
817 # and test automatic renewal again
818 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
819 ( $renewokay, $error ) =
820 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
821 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
822 is( $error, 'auto_renew',
823 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
826 $renewing_borrower_obj->autorenew_checkouts(0)->store;
827 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
828 is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' );
829 $renewing_borrower_obj->autorenew_checkouts(1)->store;
831 subtest "too_late_renewal / no_auto_renewal_after" => sub {
833 my $item_to_auto_renew = $builder->build_sample_item(
835 biblionumber => $biblio->biblionumber,
840 my $ten_days_before = dt_from_string->add( days => -10 );
841 my $ten_days_ahead = dt_from_string->add( days => 10 );
842 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
844 Koha::CirculationRules->set_rules(
846 categorycode => undef,
850 norenewalbefore => '7',
851 no_auto_renewal_after => '9',
855 ( $renewokay, $error ) =
856 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
857 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
858 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
860 Koha::CirculationRules->set_rules(
862 categorycode => undef,
866 norenewalbefore => '7',
867 no_auto_renewal_after => '10',
871 ( $renewokay, $error ) =
872 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
873 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
874 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
876 Koha::CirculationRules->set_rules(
878 categorycode => undef,
882 norenewalbefore => '7',
883 no_auto_renewal_after => '11',
887 ( $renewokay, $error ) =
888 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
889 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
890 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
892 Koha::CirculationRules->set_rules(
894 categorycode => undef,
898 norenewalbefore => '10',
899 no_auto_renewal_after => '11',
903 ( $renewokay, $error ) =
904 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
905 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
906 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
908 Koha::CirculationRules->set_rules(
910 categorycode => undef,
914 norenewalbefore => '10',
915 no_auto_renewal_after => undef,
916 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
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 => '15',
933 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
937 ( $renewokay, $error ) =
938 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
939 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
940 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
942 Koha::CirculationRules->set_rules(
944 categorycode => undef,
948 norenewalbefore => '10',
949 no_auto_renewal_after => undef,
950 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
954 ( $renewokay, $error ) =
955 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
956 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
957 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
960 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
962 my $item_to_auto_renew = $builder->build_sample_item(
964 biblionumber => $biblio->biblionumber,
969 my $ten_days_before = dt_from_string->add( days => -10 );
970 my $ten_days_ahead = dt_from_string->add( days => 10 );
971 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
973 Koha::CirculationRules->set_rules(
975 categorycode => undef,
979 norenewalbefore => '10',
980 no_auto_renewal_after => '11',
984 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
985 C4::Context->set_preference('OPACFineNoRenewals','10');
986 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
987 my $fines_amount = 5;
988 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
991 amount => $fines_amount,
994 item_id => $item_to_auto_renew->itemnumber,
995 description => "Some fines"
997 )->status('RETURNED')->store;
998 ( $renewokay, $error ) =
999 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1000 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1001 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
1003 $account->add_debit(
1005 amount => $fines_amount,
1006 interface => 'test',
1008 item_id => $item_to_auto_renew->itemnumber,
1009 description => "Some fines"
1011 )->status('RETURNED')->store;
1012 ( $renewokay, $error ) =
1013 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1014 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1015 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
1017 $account->add_debit(
1019 amount => $fines_amount,
1020 interface => 'test',
1022 item_id => $item_to_auto_renew->itemnumber,
1023 description => "Some fines"
1025 )->status('RETURNED')->store;
1026 ( $renewokay, $error ) =
1027 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1028 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1029 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
1031 $account->add_credit(
1033 amount => $fines_amount,
1034 interface => 'test',
1036 description => "Some payment"
1039 ( $renewokay, $error ) =
1040 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1041 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1042 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1044 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
1045 ( $renewokay, $error ) =
1046 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1047 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1048 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1050 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
1051 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1054 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
1056 my $item_to_auto_renew = $builder->build_sample_item(
1058 biblionumber => $biblio->biblionumber,
1063 Koha::CirculationRules->set_rules(
1065 categorycode => undef,
1066 branchcode => undef,
1069 norenewalbefore => 10,
1070 no_auto_renewal_after => 11,
1075 my $ten_days_before = dt_from_string->add( days => -10 );
1076 my $ten_days_ahead = dt_from_string->add( days => 10 );
1078 # Patron is expired and BlockExpiredPatronOpacActions=0
1079 # => auto renew is allowed
1080 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
1081 my $patron = $expired_borrower;
1082 my $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1083 ( $renewokay, $error ) =
1084 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1085 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1086 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
1087 Koha::Checkouts->find( $checkout->issue_id )->delete;
1090 # Patron is expired and BlockExpiredPatronOpacActions=1
1091 # => auto renew is not allowed
1092 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1093 $patron = $expired_borrower;
1094 $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1095 ( $renewokay, $error ) =
1096 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1097 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1098 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
1099 Koha::Checkouts->find( $checkout->issue_id )->delete;
1102 # Patron is not expired and BlockExpiredPatronOpacActions=1
1103 # => auto renew is allowed
1104 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1105 $patron = $renewing_borrower;
1106 $checkout = AddIssue( $patron, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1107 ( $renewokay, $error ) =
1108 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->itemnumber );
1109 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1110 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1111 Koha::Checkouts->find( $checkout->issue_id )->delete;
1114 subtest "GetLatestAutoRenewDate" => sub {
1116 my $item_to_auto_renew = $builder->build_sample_item(
1118 biblionumber => $biblio->biblionumber,
1123 my $ten_days_before = dt_from_string->add( days => -10 );
1124 my $ten_days_ahead = dt_from_string->add( days => 10 );
1125 AddIssue( $renewing_borrower, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1126 Koha::CirculationRules->set_rules(
1128 categorycode => undef,
1129 branchcode => undef,
1132 norenewalbefore => '7',
1133 no_auto_renewal_after => '',
1134 no_auto_renewal_after_hard_limit => undef,
1138 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1139 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' );
1140 my $five_days_before = dt_from_string->add( days => -5 );
1141 Koha::CirculationRules->set_rules(
1143 categorycode => undef,
1144 branchcode => undef,
1147 norenewalbefore => '10',
1148 no_auto_renewal_after => '5',
1149 no_auto_renewal_after_hard_limit => undef,
1153 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1154 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1155 $five_days_before->truncate( to => 'minute' ),
1156 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1158 my $five_days_ahead = dt_from_string->add( days => 5 );
1159 $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1160 $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1161 $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1162 Koha::CirculationRules->set_rules(
1164 categorycode => undef,
1165 branchcode => undef,
1168 norenewalbefore => '10',
1169 no_auto_renewal_after => '15',
1170 no_auto_renewal_after_hard_limit => undef,
1174 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1175 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1176 $five_days_ahead->truncate( to => 'minute' ),
1177 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1179 my $two_days_ahead = dt_from_string->add( days => 2 );
1180 Koha::CirculationRules->set_rules(
1182 categorycode => undef,
1183 branchcode => undef,
1186 norenewalbefore => '10',
1187 no_auto_renewal_after => '',
1188 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1192 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1193 is( $latest_auto_renew_date->truncate( to => 'day' ),
1194 $two_days_ahead->truncate( to => 'day' ),
1195 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1197 Koha::CirculationRules->set_rules(
1199 categorycode => undef,
1200 branchcode => undef,
1203 norenewalbefore => '10',
1204 no_auto_renewal_after => '15',
1205 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1209 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->itemnumber );
1210 is( $latest_auto_renew_date->truncate( to => 'day' ),
1211 $two_days_ahead->truncate( to => 'day' ),
1212 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1218 # set policy to forbid renewals
1219 Koha::CirculationRules->set_rules(
1221 categorycode => undef,
1222 branchcode => undef,
1225 norenewalbefore => undef,
1226 renewalsallowed => 0,
1231 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1232 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1233 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1235 # Too many unseen renewals
1236 Koha::CirculationRules->set_rules(
1238 categorycode => undef,
1239 branchcode => undef,
1242 unseen_renewals_allowed => 2,
1243 renewalsallowed => 10,
1247 t::lib::Mocks::mock_preference('UnseenRenewals', 1);
1248 $dbh->do('UPDATE issues SET unseen_renewals = 2 where borrowernumber = ? AND itemnumber = ?', undef, ($renewing_borrowernumber, $item_1->itemnumber));
1249 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1250 is( $renewokay, 0, 'Cannot renew, 0 unseen renewals allowed');
1251 is( $error, 'too_unseen', 'Cannot renew, returned code is too_unseen');
1252 Koha::CirculationRules->set_rules(
1254 categorycode => undef,
1255 branchcode => undef,
1258 norenewalbefore => undef,
1259 renewalsallowed => 0,
1263 t::lib::Mocks::mock_preference('UnseenRenewals', 0);
1265 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1266 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1267 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1269 C4::Overdues::UpdateFine(
1271 issue_id => $issue->id(),
1272 itemnumber => $item_1->itemnumber,
1273 borrowernumber => $renewing_borrower->{borrowernumber},
1276 due => Koha::DateUtils::output_pref($datedue)
1280 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
1281 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1282 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1283 is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1284 is( $line->amount+0, 15, 'Account line amount is 15.00' );
1285 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
1287 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1288 is( $offset->type, 'OVERDUE', 'Account offset type is Fine' );
1289 is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1291 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1292 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1294 LostItem( $item_1->itemnumber, 'test', 1 );
1296 $line = Koha::Account::Lines->find($line->id);
1297 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1298 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1300 my $item = Koha::Items->find($item_1->itemnumber);
1301 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1302 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1303 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1305 my $total_due = $dbh->selectrow_array(
1306 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1307 undef, $renewing_borrower->{borrowernumber}
1310 is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1312 C4::Context->dbh->do("DELETE FROM accountlines");
1314 C4::Overdues::UpdateFine(
1316 issue_id => $issue2->id(),
1317 itemnumber => $item_2->itemnumber,
1318 borrowernumber => $renewing_borrower->{borrowernumber},
1321 due => Koha::DateUtils::output_pref($datedue)
1325 LostItem( $item_2->itemnumber, 'test', 0 );
1327 my $item2 = Koha::Items->find($item_2->itemnumber);
1328 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1329 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1331 $total_due = $dbh->selectrow_array(
1332 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1333 undef, $renewing_borrower->{borrowernumber}
1336 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1338 my $future = dt_from_string();
1339 $future->add( days => 7 );
1340 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1341 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1343 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1344 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1345 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1346 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1347 LostItem( $item_3->itemnumber, 'test', 0 );
1348 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1349 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1351 $accountline->description,
1352 sprintf( "%s %s %s",
1353 $item_3->biblio->title || '',
1354 $item_3->barcode || '',
1355 $item_3->itemcallnumber || '' ),
1356 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1360 subtest "GetUpcomingDueIssues" => sub {
1363 my $branch = $library2->{branchcode};
1365 #Create another record
1366 my $biblio2 = $builder->build_sample_biblio();
1369 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1370 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1371 my $item_3 = $builder->build_sample_item(
1373 biblionumber => $biblio2->biblionumber,
1381 my %a_borrower_data = (
1382 firstname => 'Fridolyn',
1383 surname => 'SOMERS',
1384 categorycode => $patron_category->{categorycode},
1385 branchcode => $branch,
1388 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1389 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1391 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1392 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1393 my $today = DateTime->today(time_zone => C4::Context->tz());
1395 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1396 my $datedue = dt_from_string( $issue->date_due() );
1397 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1398 my $datedue2 = dt_from_string( $issue->date_due() );
1402 # GetUpcomingDueIssues tests
1404 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1405 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1408 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1409 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1410 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1413 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1414 is ( scalar( @$upcoming_dues ), 1,
1415 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1418 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1420 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1422 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1423 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1425 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1426 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1428 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1429 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1431 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1432 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1434 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1435 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1437 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1438 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1442 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1443 my $branch = $library2->{branchcode};
1445 my $biblio = $builder->build_sample_biblio();
1448 my $item = $builder->build_sample_item(
1450 biblionumber => $biblio->biblionumber,
1457 my %a_borrower_data = (
1458 firstname => 'Kyle',
1460 categorycode => $patron_category->{categorycode},
1461 branchcode => $branch,
1464 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1466 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1467 my $issue = AddIssue( $borrower, $item->barcode );
1470 issue_id => $issue->id(),
1471 itemnumber => $item->itemnumber,
1472 borrowernumber => $borrowernumber,
1478 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1479 my $count = $hr->{count};
1481 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1484 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1485 $dbh->do('DELETE FROM issues');
1486 $dbh->do('DELETE FROM items');
1487 $dbh->do('DELETE FROM circulation_rules');
1488 Koha::CirculationRules->set_rules(
1490 categorycode => undef,
1492 branchcode => undef,
1494 reservesallowed => 25,
1496 lengthunit => 'days',
1497 renewalsallowed => 1,
1499 norenewalbefore => undef,
1507 my $biblio = $builder->build_sample_biblio();
1509 my $item_1 = $builder->build_sample_item(
1511 biblionumber => $biblio->biblionumber,
1512 library => $library2->{branchcode},
1517 my $item_2= $builder->build_sample_item(
1519 biblionumber => $biblio->biblionumber,
1520 library => $library2->{branchcode},
1525 my $borrowernumber1 = Koha::Patron->new({
1526 firstname => 'Kyle',
1528 categorycode => $patron_category->{categorycode},
1529 branchcode => $library2->{branchcode},
1530 })->store->borrowernumber;
1531 my $borrowernumber2 = Koha::Patron->new({
1532 firstname => 'Chelsea',
1534 categorycode => $patron_category->{categorycode},
1535 branchcode => $library2->{branchcode},
1536 })->store->borrowernumber;
1538 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1539 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1541 my $issue = AddIssue( $borrower1, $item_1->barcode );
1543 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1544 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1548 branchcode => $library2->{branchcode},
1549 borrowernumber => $borrowernumber2,
1550 biblionumber => $biblio->biblionumber,
1555 Koha::CirculationRules->set_rules(
1557 categorycode => undef,
1559 branchcode => undef,
1565 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1566 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1567 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1569 Koha::CirculationRules->set_rules(
1571 categorycode => undef,
1573 branchcode => undef,
1579 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1580 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1581 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1583 Koha::CirculationRules->set_rules(
1585 categorycode => undef,
1587 branchcode => undef,
1593 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1594 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1595 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1597 Koha::CirculationRules->set_rules(
1599 categorycode => undef,
1601 branchcode => undef,
1607 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1608 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1609 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1611 # Setting item not checked out to be not for loan but holdable
1612 $item_2->notforloan(-1)->store;
1614 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1615 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' );
1619 # Don't allow renewing onsite checkout
1620 my $branch = $library->{branchcode};
1622 #Create another record
1623 my $biblio = $builder->build_sample_biblio();
1625 my $item = $builder->build_sample_item(
1627 biblionumber => $biblio->biblionumber,
1633 my $borrowernumber = Koha::Patron->new({
1636 categorycode => $patron_category->{categorycode},
1637 branchcode => $branch,
1638 })->store->borrowernumber;
1640 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1642 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1643 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1644 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1645 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1649 my $library = $builder->build({ source => 'Branch' });
1651 my $biblio = $builder->build_sample_biblio();
1653 my $item = $builder->build_sample_item(
1655 biblionumber => $biblio->biblionumber,
1656 library => $library->{branchcode},
1661 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1663 my $issue = AddIssue( $patron, $item->barcode );
1666 issue_id => $issue->id(),
1667 itemnumber => $item->itemnumber,
1668 borrowernumber => $patron->{borrowernumber},
1675 issue_id => $issue->id(),
1676 itemnumber => $item->itemnumber,
1677 borrowernumber => $patron->{borrowernumber},
1682 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1685 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1688 my $homebranch = $builder->build( { source => 'Branch' } );
1689 my $holdingbranch = $builder->build( { source => 'Branch' } );
1690 my $otherbranch = $builder->build( { source => 'Branch' } );
1691 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1692 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1694 my $item = $builder->build_sample_item(
1696 homebranch => $homebranch->{branchcode},
1697 holdingbranch => $holdingbranch->{branchcode},
1701 set_userenv($holdingbranch);
1703 my $issue = AddIssue( $patron_1->unblessed, $item->barcode );
1704 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1706 my ( $error, $question, $alerts );
1708 # AllowReturnToBranch == anywhere
1709 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1710 ## Test that unknown barcodes don't generate internal server errors
1711 set_userenv($homebranch);
1712 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1713 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1714 ## Can be issued from homebranch
1715 set_userenv($homebranch);
1716 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1717 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1718 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1719 ## Can be issued from holdingbranch
1720 set_userenv($holdingbranch);
1721 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1722 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1723 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1724 ## Can be issued from another branch
1725 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1726 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1727 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1729 # AllowReturnToBranch == holdingbranch
1730 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1731 ## Cannot be issued from homebranch
1732 set_userenv($homebranch);
1733 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1734 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1735 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1736 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1737 ## Can be issued from holdinbranch
1738 set_userenv($holdingbranch);
1739 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1740 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1741 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1742 ## Cannot be issued from another branch
1743 set_userenv($otherbranch);
1744 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1745 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1746 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1747 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
1749 # AllowReturnToBranch == homebranch
1750 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1751 ## Can be issued from holdinbranch
1752 set_userenv($homebranch);
1753 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1754 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1755 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1756 ## Cannot be issued from holdinbranch
1757 set_userenv($holdingbranch);
1758 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1759 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1760 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1761 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1762 ## Cannot be issued from holdinbranch
1763 set_userenv($otherbranch);
1764 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
1765 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1766 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1767 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1769 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1772 subtest 'AddIssue & AllowReturnToBranch' => sub {
1775 my $homebranch = $builder->build( { source => 'Branch' } );
1776 my $holdingbranch = $builder->build( { source => 'Branch' } );
1777 my $otherbranch = $builder->build( { source => 'Branch' } );
1778 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1779 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1781 my $item = $builder->build_sample_item(
1783 homebranch => $homebranch->{branchcode},
1784 holdingbranch => $holdingbranch->{branchcode},
1788 set_userenv($holdingbranch);
1790 my $ref_issue = 'Koha::Checkout';
1791 my $issue = AddIssue( $patron_1, $item->barcode );
1793 my ( $error, $question, $alerts );
1795 # AllowReturnToBranch == homebranch
1796 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1797 ## Can be issued from homebranch
1798 set_userenv($homebranch);
1799 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
1800 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1801 ## Can be issued from holdinbranch
1802 set_userenv($holdingbranch);
1803 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
1804 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1805 ## Can be issued from another branch
1806 set_userenv($otherbranch);
1807 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
1808 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1810 # AllowReturnToBranch == holdinbranch
1811 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1812 ## Cannot be issued from homebranch
1813 set_userenv($homebranch);
1814 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
1815 ## Can be issued from holdingbranch
1816 set_userenv($holdingbranch);
1817 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
1818 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1819 ## Cannot be issued from another branch
1820 set_userenv($otherbranch);
1821 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
1823 # AllowReturnToBranch == homebranch
1824 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1825 ## Can be issued from homebranch
1826 set_userenv($homebranch);
1827 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
1828 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
1829 ## Cannot be issued from holdinbranch
1830 set_userenv($holdingbranch);
1831 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
1832 ## Cannot be issued from another branch
1833 set_userenv($otherbranch);
1834 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
1835 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1838 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1841 my $library = $builder->build( { source => 'Branch' } );
1842 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1843 my $item_1 = $builder->build_sample_item(
1845 library => $library->{branchcode},
1848 my $item_2 = $builder->build_sample_item(
1850 library => $library->{branchcode},
1854 my ( $error, $question, $alerts );
1856 # Patron cannot issue item_1, they have overdues
1857 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1858 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, $yesterday ); # Add an overdue
1860 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1861 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
1862 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
1863 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1865 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1866 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
1867 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1868 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1870 # Patron cannot issue item_1, they are debarred
1871 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1872 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1873 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
1874 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1875 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1877 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1878 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
1879 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1880 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1883 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1886 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1887 my $patron_category_x = $builder->build_object(
1889 class => 'Koha::Patron::Categories',
1890 value => { category_type => 'X' }
1893 my $patron = $builder->build_object(
1895 class => 'Koha::Patrons',
1897 categorycode => $patron_category_x->categorycode,
1898 gonenoaddress => undef,
1905 my $item_1 = $builder->build_sample_item(
1907 library => $library->{branchcode},
1911 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
1912 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1914 # TODO There are other tests to provide here
1917 subtest 'MultipleReserves' => sub {
1920 my $biblio = $builder->build_sample_biblio();
1922 my $branch = $library2->{branchcode};
1924 my $item_1 = $builder->build_sample_item(
1926 biblionumber => $biblio->biblionumber,
1928 replacementprice => 12.00,
1933 my $item_2 = $builder->build_sample_item(
1935 biblionumber => $biblio->biblionumber,
1937 replacementprice => 12.00,
1944 my $resdate = undef;
1945 my $expdate = undef;
1947 my $checkitem = undef;
1950 my %renewing_borrower_data = (
1951 firstname => 'John',
1952 surname => 'Renewal',
1953 categorycode => $patron_category->{categorycode},
1954 branchcode => $branch,
1956 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1957 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1958 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1959 my $datedue = dt_from_string( $issue->date_due() );
1960 is (defined $issue->date_due(), 1, "item 1 checked out");
1961 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1963 my %reserving_borrower_data1 = (
1964 firstname => 'Katrin',
1965 surname => 'Reservation',
1966 categorycode => $patron_category->{categorycode},
1967 branchcode => $branch,
1969 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1972 branchcode => $branch,
1973 borrowernumber => $reserving_borrowernumber1,
1974 biblionumber => $biblio->biblionumber,
1975 priority => $priority,
1976 reservation_date => $resdate,
1977 expiration_date => $expdate,
1979 itemnumber => $checkitem,
1984 my %reserving_borrower_data2 = (
1985 firstname => 'Kirk',
1986 surname => 'Reservation',
1987 categorycode => $patron_category->{categorycode},
1988 branchcode => $branch,
1990 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1993 branchcode => $branch,
1994 borrowernumber => $reserving_borrowernumber2,
1995 biblionumber => $biblio->biblionumber,
1996 priority => $priority,
1997 reservation_date => $resdate,
1998 expiration_date => $expdate,
2000 itemnumber => $checkitem,
2006 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2007 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2010 my $item_3 = $builder->build_sample_item(
2012 biblionumber => $biblio->biblionumber,
2014 replacementprice => 12.00,
2020 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
2021 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2025 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2028 my $library = $builder->build( { source => 'Branch' } );
2029 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2031 my $biblionumber = $builder->build_sample_biblio(
2033 branchcode => $library->{branchcode},
2036 my $item_1 = $builder->build_sample_item(
2038 biblionumber => $biblionumber,
2039 library => $library->{branchcode},
2043 my $item_2 = $builder->build_sample_item(
2045 biblionumber => $biblionumber,
2046 library => $library->{branchcode},
2050 my ( $error, $question, $alerts );
2051 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, dt_from_string->add( days => 1 ) );
2053 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2054 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2056 { error => $error, alerts => $alerts },
2057 { error => {}, alerts => {} },
2058 'No error or alert should be raised'
2060 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2062 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2063 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2065 { error => $error, question => $question, alerts => $alerts },
2066 { error => {}, question => {}, alerts => {} },
2067 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2070 # Add a subscription
2071 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2073 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2074 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2076 { error => $error, question => $question, alerts => $alerts },
2077 { error => {}, question => {}, alerts => {} },
2078 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2081 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2082 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2084 { error => $error, question => $question, alerts => $alerts },
2085 { error => {}, question => {}, alerts => {} },
2086 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2090 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2093 my $library = $builder->build( { source => 'Branch' } );
2094 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2097 my $biblionumber = $builder->build_sample_biblio(
2099 branchcode => $library->{branchcode},
2102 my $item_1 = $builder->build_sample_item(
2104 biblionumber => $biblionumber,
2105 library => $library->{branchcode},
2108 my $item_2 = $builder->build_sample_item(
2110 biblionumber => $biblionumber,
2111 library => $library->{branchcode},
2115 # And the circulation rule
2116 Koha::CirculationRules->search->delete;
2117 Koha::CirculationRules->set_rules(
2119 categorycode => undef,
2121 branchcode => undef,
2124 firstremind => 1, # 1 day of grace
2125 finedays => 2, # 2 days of fine per day of overdue
2126 lengthunit => 'days',
2131 # Patron cannot issue item_1, they have overdues
2132 my $now = dt_from_string;
2133 my $five_days_ago = $now->clone->subtract( days => 5 );
2134 my $ten_days_ago = $now->clone->subtract( days => 10 );
2135 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2136 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2137 ; # Add another overdue
2139 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2140 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2141 my $debarments = Koha::Patron::Debarments::GetDebarments(
2142 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2143 is( scalar(@$debarments), 1 );
2145 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2146 # Same for the others
2147 my $expected_expiration = output_pref(
2149 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2150 dateformat => 'sql',
2154 is( $debarments->[0]->{expiration}, $expected_expiration );
2156 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2157 $debarments = Koha::Patron::Debarments::GetDebarments(
2158 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2159 is( scalar(@$debarments), 1 );
2160 $expected_expiration = output_pref(
2162 dt => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2163 dateformat => 'sql',
2167 is( $debarments->[0]->{expiration}, $expected_expiration );
2169 Koha::Patron::Debarments::DelUniqueDebarment(
2170 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2172 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2173 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2174 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2175 ; # Add another overdue
2176 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2177 $debarments = Koha::Patron::Debarments::GetDebarments(
2178 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2179 is( scalar(@$debarments), 1 );
2180 $expected_expiration = output_pref(
2182 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2183 dateformat => 'sql',
2187 is( $debarments->[0]->{expiration}, $expected_expiration );
2189 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2190 $debarments = Koha::Patron::Debarments::GetDebarments(
2191 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2192 is( scalar(@$debarments), 1 );
2193 $expected_expiration = output_pref(
2195 dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2196 dateformat => 'sql',
2200 is( $debarments->[0]->{expiration}, $expected_expiration );
2203 subtest 'AddReturn + suspension_chargeperiod' => sub {
2206 my $library = $builder->build( { source => 'Branch' } );
2207 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2209 my $biblionumber = $builder->build_sample_biblio(
2211 branchcode => $library->{branchcode},
2214 my $item_1 = $builder->build_sample_item(
2216 biblionumber => $biblionumber,
2217 library => $library->{branchcode},
2221 # And the issuing rule
2222 Koha::CirculationRules->search->delete;
2223 Koha::CirculationRules->set_rules(
2225 categorycode => '*',
2230 firstremind => 0, # 0 day of grace
2231 finedays => 2, # 2 days of fine per day of overdue
2232 suspension_chargeperiod => 1,
2233 lengthunit => 'days',
2238 my $now = dt_from_string;
2239 my $five_days_ago = $now->clone->subtract( days => 5 );
2240 # We want to charge 2 days every day, without grace
2241 # With 5 days of overdue: 5 * Z
2242 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2243 test_debarment_on_checkout(
2246 library => $library,
2248 due_date => $five_days_ago,
2249 expiration_date => $expected_expiration,
2253 # Same with undef firstremind
2254 Koha::CirculationRules->search->delete;
2255 Koha::CirculationRules->set_rules(
2257 categorycode => '*',
2262 firstremind => undef, # 0 day of grace
2263 finedays => 2, # 2 days of fine per day of overdue
2264 suspension_chargeperiod => 1,
2265 lengthunit => 'days',
2270 my $now = dt_from_string;
2271 my $five_days_ago = $now->clone->subtract( days => 5 );
2272 # We want to charge 2 days every day, without grace
2273 # With 5 days of overdue: 5 * Z
2274 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2275 test_debarment_on_checkout(
2278 library => $library,
2280 due_date => $five_days_ago,
2281 expiration_date => $expected_expiration,
2285 # We want to charge 2 days every 2 days, without grace
2286 # With 5 days of overdue: (5 * 2) / 2
2287 Koha::CirculationRules->set_rule(
2289 categorycode => undef,
2290 branchcode => undef,
2292 rule_name => 'suspension_chargeperiod',
2297 $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2298 test_debarment_on_checkout(
2301 library => $library,
2303 due_date => $five_days_ago,
2304 expiration_date => $expected_expiration,
2308 # We want to charge 2 days every 3 days, with 1 day of grace
2309 # With 5 days of overdue: ((5-1) / 3 ) * 2
2310 Koha::CirculationRules->set_rules(
2312 categorycode => undef,
2313 branchcode => undef,
2316 suspension_chargeperiod => 3,
2321 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2322 test_debarment_on_checkout(
2325 library => $library,
2327 due_date => $five_days_ago,
2328 expiration_date => $expected_expiration,
2332 # Use finesCalendar to know if holiday must be skipped to calculate the due date
2333 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2334 Koha::CirculationRules->set_rules(
2336 categorycode => undef,
2337 branchcode => undef,
2341 suspension_chargeperiod => 1,
2346 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2347 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2349 # Adding a holiday 2 days ago
2350 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2351 my $two_days_ago = $now->clone->subtract( days => 2 );
2352 $calendar->insert_single_holiday(
2353 day => $two_days_ago->day,
2354 month => $two_days_ago->month,
2355 year => $two_days_ago->year,
2356 title => 'holidayTest-2d',
2357 description => 'holidayDesc 2 days ago'
2359 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2360 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2361 test_debarment_on_checkout(
2364 library => $library,
2366 due_date => $five_days_ago,
2367 expiration_date => $expected_expiration,
2371 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2372 my $two_days_ahead = $now->clone->add( days => 2 );
2373 $calendar->insert_single_holiday(
2374 day => $two_days_ahead->day,
2375 month => $two_days_ahead->month,
2376 year => $two_days_ahead->year,
2377 title => 'holidayTest+2d',
2378 description => 'holidayDesc 2 days ahead'
2381 # Same as above, but we should skip D+2
2382 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2383 test_debarment_on_checkout(
2386 library => $library,
2388 due_date => $five_days_ago,
2389 expiration_date => $expected_expiration,
2393 # Adding another holiday, day of expiration date
2394 my $expected_expiration_dt = dt_from_string($expected_expiration);
2395 $calendar->insert_single_holiday(
2396 day => $expected_expiration_dt->day,
2397 month => $expected_expiration_dt->month,
2398 year => $expected_expiration_dt->year,
2399 title => 'holidayTest_exp',
2400 description => 'holidayDesc on expiration date'
2402 # Expiration date will be the day after
2403 test_debarment_on_checkout(
2406 library => $library,
2408 due_date => $five_days_ago,
2409 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2413 test_debarment_on_checkout(
2416 library => $library,
2418 return_date => $now->clone->add(days => 5),
2419 expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2423 test_debarment_on_checkout(
2426 library => $library,
2428 due_date => $now->clone->add(days => 1),
2429 return_date => $now->clone->add(days => 5),
2430 expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2436 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2439 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2440 my $patron1 = $builder->build_object(
2442 class => 'Koha::Patrons',
2444 library => $library->branchcode,
2445 categorycode => $patron_category->{categorycode}
2449 my $patron2 = $builder->build_object(
2451 class => 'Koha::Patrons',
2453 library => $library->branchcode,
2454 categorycode => $patron_category->{categorycode}
2459 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2461 my $item = $builder->build_sample_item(
2463 library => $library->branchcode,
2467 my ( $error, $question, $alerts );
2468 my $issue = AddIssue( $patron1->unblessed, $item->barcode );
2470 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2471 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2472 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' );
2474 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2475 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2476 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' );
2478 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2482 subtest 'AddReturn | is_overdue' => sub {
2485 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2486 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2487 t::lib::Mocks::mock_preference('finesMode', 'production');
2488 t::lib::Mocks::mock_preference('MaxFine', '100');
2490 my $library = $builder->build( { source => 'Branch' } );
2491 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2492 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2493 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2495 my $item = $builder->build_sample_item(
2497 library => $library->{branchcode},
2498 replacementprice => 7
2502 Koha::CirculationRules->search->delete;
2503 Koha::CirculationRules->set_rules(
2505 categorycode => undef,
2507 branchcode => undef,
2510 lengthunit => 'days',
2511 fine => 1, # Charge 1 every day of overdue
2517 my $now = dt_from_string;
2518 my $one_day_ago = $now->clone->subtract( days => 1 );
2519 my $two_days_ago = $now->clone->subtract( days => 2 );
2520 my $five_days_ago = $now->clone->subtract( days => 5 );
2521 my $ten_days_ago = $now->clone->subtract( days => 10 );
2522 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2524 # No return date specified, today will be used => 10 days overdue charged
2525 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2526 AddReturn( $item->barcode, $library->{branchcode} );
2527 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2528 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2530 # specify return date 5 days before => no overdue charged
2531 AddIssue( $patron->unblessed, $item->barcode, $five_days_ago ); # date due was 5d ago
2532 AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
2533 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2534 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2536 # specify return date 5 days later => 5 days overdue charged
2537 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2538 AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
2539 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2540 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2542 # specify return date 5 days later, specify exemptfine => no overdue charge
2543 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2544 AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago );
2545 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2546 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2548 subtest 'bug 22877 | Lost item return' => sub {
2552 my $issue = AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
2554 # Fake fines cronjob on this checkout
2556 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2557 $ten_days_ago, $now );
2560 issue_id => $issue->issue_id,
2561 itemnumber => $item->itemnumber,
2562 borrowernumber => $patron->borrowernumber,
2564 due => output_pref($ten_days_ago)
2567 is( int( $patron->account->balance() ),
2568 10, "Overdue fine of 10 days overdue" );
2570 # Fake longoverdue with charge and not marking returned
2571 LostItem( $item->itemnumber, 'cronjob', 0 );
2572 is( int( $patron->account->balance() ),
2573 17, "Lost fine of 7 plus 10 days overdue" );
2575 # Now we return it today
2576 AddReturn( $item->barcode, $library->{branchcode} );
2577 is( int( $patron->account->balance() ),
2578 17, "Should have a single 10 days overdue fine and lost charge" );
2581 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2584 subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
2588 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2590 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
2592 # Fake fines cronjob on this checkout
2594 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2595 $one_day_ago, $now );
2598 issue_id => $issue->issue_id,
2599 itemnumber => $item->itemnumber,
2600 borrowernumber => $patron->borrowernumber,
2602 due => output_pref($one_day_ago)
2605 is( int( $patron->account->balance() ),
2606 1, "Overdue fine of 1 day overdue" );
2608 # Backdated return (dropbox mode example - charge should be removed)
2609 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
2610 is( int( $patron->account->balance() ),
2611 0, "Overdue fine should be annulled" );
2612 my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2613 is( $lines->count, 0, "Overdue fine accountline has been removed");
2615 $issue = AddIssue( $patron->unblessed, $item->barcode, $two_days_ago ); # date due was 2d ago
2617 # Fake fines cronjob on this checkout
2619 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2620 $two_days_ago, $now );
2623 issue_id => $issue->issue_id,
2624 itemnumber => $item->itemnumber,
2625 borrowernumber => $patron->borrowernumber,
2627 due => output_pref($one_day_ago)
2630 is( int( $patron->account->balance() ),
2631 2, "Overdue fine of 2 days overdue" );
2633 # Payment made against fine
2634 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2635 my $debit = $lines->next;
2636 my $credit = $patron->account->add_credit(
2640 interface => 'test',
2644 { debits => [ $debit ], offset_type => 'Payment' } );
2646 is( int( $patron->account->balance() ),
2647 0, "Overdue fine should be paid off" );
2648 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2649 is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
2650 my $line = $lines->next;
2651 is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
2652 is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
2654 # Backdated return (dropbox mode example - charge should be removed)
2655 AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
2656 is( int( $patron->account->balance() ),
2657 -1, "Refund credit has been applied" );
2658 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
2659 is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
2661 $line = $lines->next;
2662 is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
2663 is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
2664 is($line->status,'RETURNED', "Overdue fine is fixed");
2665 $line = $lines->next;
2666 is($line->amount+0,-2, "Original payment amount remains as 2");
2667 is($line->amountoutstanding+0,0, "Original payment remains applied");
2668 $line = $lines->next;
2669 is($line->amount+0,-1, "Refund amount correctly set to 1");
2670 is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
2673 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2676 subtest 'bug 25417 | backdated return + exemptfine' => sub {
2680 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2682 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
2684 # Fake fines cronjob on this checkout
2686 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2687 $one_day_ago, $now );
2690 issue_id => $issue->issue_id,
2691 itemnumber => $item->itemnumber,
2692 borrowernumber => $patron->borrowernumber,
2694 due => output_pref($one_day_ago)
2697 is( int( $patron->account->balance() ),
2698 1, "Overdue fine of 1 day overdue" );
2700 # Backdated return (dropbox mode example - charge should no longer exist)
2701 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
2702 is( int( $patron->account->balance() ),
2703 0, "Overdue fine should be annulled" );
2706 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2709 subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
2712 t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
2714 my $due_date = dt_from_string;
2715 my $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
2720 issue_id => $issue->issue_id,
2721 itemnumber => $item->itemnumber,
2722 borrowernumber => $patron->borrowernumber,
2724 due => output_pref($due_date)
2727 is( $patron->account->balance(),
2728 0.25, 'Overdue fine of $0.25 recorded' );
2730 # Backdate return to exact due date and time
2731 my ( undef, $message ) =
2732 AddReturn( $item->barcode, $library->{branchcode},
2736 Koha::Account::Lines->find( { issue_id => $issue->id } );
2737 ok( !$accountline, 'accountline removed as expected' );
2740 $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
2745 issue_id => $issue->issue_id,
2746 itemnumber => $item->itemnumber,
2747 borrowernumber => $patron->borrowernumber,
2749 due => output_pref($due_date)
2752 is( $patron->account->balance(),
2753 0.25, 'Overdue fine of $0.25 recorded' );
2755 # Partial pay accruing fine
2756 my $lines = Koha::Account::Lines->search(
2758 borrowernumber => $patron->borrowernumber,
2759 issue_id => $issue->id
2762 my $debit = $lines->next;
2763 my $credit = $patron->account->add_credit(
2767 interface => 'test',
2770 $credit->apply( { debits => [$debit], offset_type => 'Payment' } );
2772 is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
2774 # Backdate return to exact due date and time
2775 ( undef, $message ) =
2776 AddReturn( $item->barcode, $library->{branchcode},
2779 $lines = Koha::Account::Lines->search(
2781 borrowernumber => $patron->borrowernumber,
2782 issue_id => $issue->id
2785 $accountline = $lines->next;
2786 is( $accountline->amountoutstanding + 0,
2787 0, 'Partially paid fee amount outstanding was reduced to 0' );
2788 is( $accountline->amount + 0,
2789 0, 'Partially paid fee amount was reduced to 0' );
2790 is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
2793 Koha::Account::Lines->search(
2794 { borrowernumber => $patron->borrowernumber } )->delete;
2797 subtest 'enh 23091 | Lost item return policies' => sub {
2800 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2802 my $branchcode_false =
2803 $builder->build( { source => 'Branch' } )->{branchcode};
2804 my $specific_rule_false = $builder->build(
2806 source => 'CirculationRule',
2808 branchcode => $branchcode_false,
2809 categorycode => undef,
2811 rule_name => 'lostreturn',
2816 my $branchcode_refund =
2817 $builder->build( { source => 'Branch' } )->{branchcode};
2818 my $specific_rule_refund = $builder->build(
2820 source => 'CirculationRule',
2822 branchcode => $branchcode_refund,
2823 categorycode => undef,
2825 rule_name => 'lostreturn',
2826 rule_value => 'refund'
2830 my $branchcode_restore =
2831 $builder->build( { source => 'Branch' } )->{branchcode};
2832 my $specific_rule_restore = $builder->build(
2834 source => 'CirculationRule',
2836 branchcode => $branchcode_restore,
2837 categorycode => undef,
2839 rule_name => 'lostreturn',
2840 rule_value => 'restore'
2844 my $branchcode_charge =
2845 $builder->build( { source => 'Branch' } )->{branchcode};
2846 my $specific_rule_charge = $builder->build(
2848 source => 'CirculationRule',
2850 branchcode => $branchcode_charge,
2851 categorycode => undef,
2853 rule_name => 'lostreturn',
2854 rule_value => 'charge'
2859 my $replacement_amount = 99.00;
2860 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2861 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
2862 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
2863 t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 );
2864 t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
2866 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
2869 subtest 'lostreturn | false' => sub {
2872 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
2874 my $item = $builder->build_sample_item(
2876 replacementprice => $replacement_amount
2881 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
2883 # Fake fines cronjob on this checkout
2885 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2886 $ten_days_ago, $now );
2889 issue_id => $issue->issue_id,
2890 itemnumber => $item->itemnumber,
2891 borrowernumber => $patron->borrowernumber,
2893 due => output_pref($ten_days_ago)
2896 my $overdue_fees = Koha::Account::Lines->search(
2898 borrowernumber => $patron->id,
2899 itemnumber => $item->itemnumber,
2900 debit_type_code => 'OVERDUE'
2903 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
2904 my $overdue_fee = $overdue_fees->next;
2905 is( $overdue_fee->amount + 0,
2906 10, 'The right OVERDUE amount is generated' );
2907 is( $overdue_fee->amountoutstanding + 0,
2909 'The right OVERDUE amountoutstanding is generated' );
2911 # Simulate item marked as lost
2912 $item->itemlost(3)->store;
2913 C4::Circulation::LostItem( $item->itemnumber, 1 );
2915 my $lost_fee_lines = Koha::Account::Lines->search(
2917 borrowernumber => $patron->id,
2918 itemnumber => $item->itemnumber,
2919 debit_type_code => 'LOST'
2922 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
2923 my $lost_fee_line = $lost_fee_lines->next;
2924 is( $lost_fee_line->amount + 0,
2925 $replacement_amount, 'The right LOST amount is generated' );
2926 is( $lost_fee_line->amountoutstanding + 0,
2927 $replacement_amount,
2928 'The right LOST amountoutstanding is generated' );
2929 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
2932 my ( $returned, $message ) =
2933 AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
2935 $overdue_fee->discard_changes;
2936 is( $overdue_fee->amount + 0,
2937 10, 'The OVERDUE amount is left intact' );
2938 is( $overdue_fee->amountoutstanding + 0,
2940 'The OVERDUE amountoutstanding is left intact' );
2942 $lost_fee_line->discard_changes;
2943 is( $lost_fee_line->amount + 0,
2944 $replacement_amount, 'The LOST amount is left intact' );
2945 is( $lost_fee_line->amountoutstanding + 0,
2946 $replacement_amount,
2947 'The LOST amountoutstanding is left intact' );
2948 # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
2949 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
2952 subtest 'lostreturn | refund' => sub {
2955 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
2957 my $item = $builder->build_sample_item(
2959 replacementprice => $replacement_amount
2964 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
2966 # Fake fines cronjob on this checkout
2968 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2969 $ten_days_ago, $now );
2972 issue_id => $issue->issue_id,
2973 itemnumber => $item->itemnumber,
2974 borrowernumber => $patron->borrowernumber,
2976 due => output_pref($ten_days_ago)
2979 my $overdue_fees = Koha::Account::Lines->search(
2981 borrowernumber => $patron->id,
2982 itemnumber => $item->itemnumber,
2983 debit_type_code => 'OVERDUE'
2986 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
2987 my $overdue_fee = $overdue_fees->next;
2988 is( $overdue_fee->amount + 0,
2989 10, 'The right OVERDUE amount is generated' );
2990 is( $overdue_fee->amountoutstanding + 0,
2992 'The right OVERDUE amountoutstanding is generated' );
2994 # Simulate item marked as lost
2995 $item->itemlost(3)->store;
2996 C4::Circulation::LostItem( $item->itemnumber, 1 );
2998 my $lost_fee_lines = Koha::Account::Lines->search(
3000 borrowernumber => $patron->id,
3001 itemnumber => $item->itemnumber,
3002 debit_type_code => 'LOST'
3005 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3006 my $lost_fee_line = $lost_fee_lines->next;
3007 is( $lost_fee_line->amount + 0,
3008 $replacement_amount, 'The right LOST amount is generated' );
3009 is( $lost_fee_line->amountoutstanding + 0,
3010 $replacement_amount,
3011 'The right LOST amountoutstanding is generated' );
3012 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3014 # Return the lost item
3015 my ( undef, $message ) =
3016 AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
3018 $overdue_fee->discard_changes;
3019 is( $overdue_fee->amount + 0,
3020 10, 'The OVERDUE amount is left intact' );
3021 is( $overdue_fee->amountoutstanding + 0,
3023 'The OVERDUE amountoutstanding is left intact' );
3025 $lost_fee_line->discard_changes;
3026 is( $lost_fee_line->amount + 0,
3027 $replacement_amount, 'The LOST amount is left intact' );
3028 is( $lost_fee_line->amountoutstanding + 0,
3030 'The LOST amountoutstanding is refunded' );
3031 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3034 subtest 'lostreturn | restore' => sub {
3037 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
3039 my $item = $builder->build_sample_item(
3041 replacementprice => $replacement_amount
3046 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode , $ten_days_ago);
3048 # Fake fines cronjob on this checkout
3050 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3051 $ten_days_ago, $now );
3054 issue_id => $issue->issue_id,
3055 itemnumber => $item->itemnumber,
3056 borrowernumber => $patron->borrowernumber,
3058 due => output_pref($ten_days_ago)
3061 my $overdue_fees = Koha::Account::Lines->search(
3063 borrowernumber => $patron->id,
3064 itemnumber => $item->itemnumber,
3065 debit_type_code => 'OVERDUE'
3068 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3069 my $overdue_fee = $overdue_fees->next;
3070 is( $overdue_fee->amount + 0,
3071 10, 'The right OVERDUE amount is generated' );
3072 is( $overdue_fee->amountoutstanding + 0,
3074 'The right OVERDUE amountoutstanding is generated' );
3076 # Simulate item marked as lost
3077 $item->itemlost(3)->store;
3078 C4::Circulation::LostItem( $item->itemnumber, 1 );
3080 my $lost_fee_lines = Koha::Account::Lines->search(
3082 borrowernumber => $patron->id,
3083 itemnumber => $item->itemnumber,
3084 debit_type_code => 'LOST'
3087 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3088 my $lost_fee_line = $lost_fee_lines->next;
3089 is( $lost_fee_line->amount + 0,
3090 $replacement_amount, 'The right LOST amount is generated' );
3091 is( $lost_fee_line->amountoutstanding + 0,
3092 $replacement_amount,
3093 'The right LOST amountoutstanding is generated' );
3094 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3096 # Simulate refunding overdue fees upon marking item as lost
3097 my $overdue_forgive = $patron->account->add_credit(
3100 user_id => $manager->borrowernumber,
3101 library_id => $branchcode_restore,
3102 interface => 'test',
3104 item_id => $item->itemnumber
3107 $overdue_forgive->apply(
3108 { debits => [$overdue_fee], offset_type => 'Forgiven' } );
3109 $overdue_fee->discard_changes;
3110 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3113 my ( undef, $message ) =
3114 AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
3116 $overdue_fee->discard_changes;
3117 is( $overdue_fee->amount + 0,
3118 10, 'The OVERDUE amount is left intact' );
3119 is( $overdue_fee->amountoutstanding + 0,
3121 'The OVERDUE amountoutstanding is restored' );
3123 $lost_fee_line->discard_changes;
3124 is( $lost_fee_line->amount + 0,
3125 $replacement_amount, 'The LOST amount is left intact' );
3126 is( $lost_fee_line->amountoutstanding + 0,
3128 'The LOST amountoutstanding is refunded' );
3129 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3132 subtest 'lostreturn | charge' => sub {
3135 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
3137 my $item = $builder->build_sample_item(
3139 replacementprice => $replacement_amount
3144 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3146 # Fake fines cronjob on this checkout
3148 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3149 $ten_days_ago, $now );
3152 issue_id => $issue->issue_id,
3153 itemnumber => $item->itemnumber,
3154 borrowernumber => $patron->borrowernumber,
3156 due => output_pref($ten_days_ago)
3159 my $overdue_fees = Koha::Account::Lines->search(
3161 borrowernumber => $patron->id,
3162 itemnumber => $item->itemnumber,
3163 debit_type_code => 'OVERDUE'
3166 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3167 my $overdue_fee = $overdue_fees->next;
3168 is( $overdue_fee->amount + 0,
3169 10, 'The right OVERDUE amount is generated' );
3170 is( $overdue_fee->amountoutstanding + 0,
3172 'The right OVERDUE amountoutstanding is generated' );
3174 # Simulate item marked as lost
3175 $item->itemlost(3)->store;
3176 C4::Circulation::LostItem( $item->itemnumber, 1 );
3178 my $lost_fee_lines = Koha::Account::Lines->search(
3180 borrowernumber => $patron->id,
3181 itemnumber => $item->itemnumber,
3182 debit_type_code => 'LOST'
3185 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3186 my $lost_fee_line = $lost_fee_lines->next;
3187 is( $lost_fee_line->amount + 0,
3188 $replacement_amount, 'The right LOST amount is generated' );
3189 is( $lost_fee_line->amountoutstanding + 0,
3190 $replacement_amount,
3191 'The right LOST amountoutstanding is generated' );
3192 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3194 # Simulate refunding overdue fees upon marking item as lost
3195 my $overdue_forgive = $patron->account->add_credit(
3198 user_id => $manager->borrowernumber,
3199 library_id => $branchcode_charge,
3200 interface => 'test',
3202 item_id => $item->itemnumber
3205 $overdue_forgive->apply(
3206 { debits => [$overdue_fee], offset_type => 'Forgiven' } );
3207 $overdue_fee->discard_changes;
3208 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3211 my ( undef, $message ) =
3212 AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
3214 $lost_fee_line->discard_changes;
3215 is( $lost_fee_line->amount + 0,
3216 $replacement_amount, 'The LOST amount is left intact' );
3217 is( $lost_fee_line->amountoutstanding + 0,
3219 'The LOST amountoutstanding is refunded' );
3220 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3222 $overdue_fees = Koha::Account::Lines->search(
3224 borrowernumber => $patron->id,
3225 itemnumber => $item->itemnumber,
3226 debit_type_code => 'OVERDUE'
3229 order_by => { '-asc' => 'accountlines_id'}
3232 is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
3233 $overdue_fee = $overdue_fees->next;
3234 is( $overdue_fee->amount + 0,
3235 10, 'The original OVERDUE amount is left intact' );
3236 is( $overdue_fee->amountoutstanding + 0,
3238 'The original OVERDUE amountoutstanding is left as forgiven' );
3239 $overdue_fee = $overdue_fees->next;
3240 is( $overdue_fee->amount + 0,
3241 5, 'The new OVERDUE amount is correct for the backdated return' );
3242 is( $overdue_fee->amountoutstanding + 0,
3244 'The new OVERDUE amountoutstanding is correct for the backdated return' );
3249 subtest '_FixOverduesOnReturn' => sub {
3252 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3253 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3255 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3257 my $branchcode = $library2->{branchcode};
3259 my $item = $builder->build_sample_item(
3261 biblionumber => $biblio->biblionumber,
3262 library => $branchcode,
3263 replacementprice => 99.00,
3268 my $patron = $builder->build( { source => 'Borrower' } );
3270 ## Start with basic call, should just close out the open fine
3271 my $accountline = Koha::Account::Line->new(
3273 borrowernumber => $patron->{borrowernumber},
3274 debit_type_code => 'OVERDUE',
3275 status => 'UNRETURNED',
3276 itemnumber => $item->itemnumber,
3278 amountoutstanding => 99.00,
3279 interface => 'test',
3283 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
3285 $accountline->_result()->discard_changes();
3287 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
3288 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3289 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3291 ## Run again, with exemptfine enabled
3294 debit_type_code => 'OVERDUE',
3295 status => 'UNRETURNED',
3296 amountoutstanding => 99.00,
3300 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3302 $accountline->_result()->discard_changes();
3303 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
3305 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
3306 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3307 is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
3308 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
3309 is( $offset->amount + 0, -99, "Amount of offset is correct" );
3310 my $credit = $offset->credit;
3311 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
3312 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
3313 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
3315 # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
3318 debit_type_code => 'OVERDUE',
3319 status => 'UNRETURNED',
3320 amountoutstanding => 0.00,
3325 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3327 $accountline->_result()->discard_changes();
3328 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
3329 is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
3330 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3331 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3334 subtest 'Set waiting flag' => sub {
3337 my $library_1 = $builder->build( { source => 'Branch' } );
3338 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3339 my $library_2 = $builder->build( { source => 'Branch' } );
3340 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3342 my $item = $builder->build_sample_item(
3344 library => $library_1->{branchcode},
3348 set_userenv( $library_2 );
3349 my $reserve_id = AddReserve(
3351 branchcode => $library_2->{branchcode},
3352 borrowernumber => $patron_2->{borrowernumber},
3353 biblionumber => $item->biblionumber,
3355 itemnumber => $item->itemnumber,
3359 set_userenv( $library_1 );
3360 my $do_transfer = 1;
3361 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3362 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3363 my $hold = Koha::Holds->find( $reserve_id );
3364 is( $hold->found, 'T', 'Hold is in transit' );
3366 my ( $status ) = CheckReserves($item->itemnumber);
3367 is( $status, 'Reserved', 'Hold is not waiting yet');
3369 set_userenv( $library_2 );
3371 AddReturn( $item->barcode, $library_2->{branchcode} );
3372 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3373 $hold = Koha::Holds->find( $reserve_id );
3374 is( $hold->found, 'W', 'Hold is waiting' );
3375 ( $status ) = CheckReserves($item->itemnumber);
3376 is( $status, 'Waiting', 'Now the hold is waiting');
3378 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
3379 set_userenv( $library_1 );
3380 (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
3381 $hold = Koha::Holds->find( $reserve_id );
3382 is( $hold->found, undef, 'Hold is no longer marked waiting' );
3383 is( $hold->priority, 1, "Hold is now priority one again");
3384 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
3385 is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
3386 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
3387 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
3388 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
3391 subtest 'Cancel transfers on lost items' => sub {
3393 my $library_1 = $builder->build( { source => 'Branch' } );
3394 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3395 my $library_2 = $builder->build( { source => 'Branch' } );
3396 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3397 my $biblio = $builder->build_sample_biblio({branchcode => $library->{branchcode}});
3398 my $item = $builder->build_sample_item({
3399 biblionumber => $biblio->biblionumber,
3400 library => $library_1->{branchcode},
3403 set_userenv( $library_2 );
3404 my $reserve_id = AddReserve(
3406 branchcode => $library_2->{branchcode},
3407 borrowernumber => $patron_2->{borrowernumber},
3408 biblionumber => $item->biblionumber,
3410 itemnumber => $item->itemnumber,
3414 #Return book and add transfer
3415 set_userenv( $library_1 );
3416 my $do_transfer = 1;
3417 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3418 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3419 C4::Circulation::transferbook({
3420 from_branch => $library_1->{branchcode},
3421 to_branch => $library_2->{branchcode},
3422 barcode => $item->barcode,
3423 trigger => 'Reserve',
3425 my $hold = Koha::Holds->find( $reserve_id );
3426 is( $hold->found, 'T', 'Hold is in transit' );
3428 #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
3429 my ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
3430 is( $frombranch, $library_1->{branchcode}, 'The transfer is generated from the correct library');
3431 is( $tobranch, $library_2->{branchcode}, 'The transfer is generated to the correct library');
3432 my $itemcheck = Koha::Items->find($item->itemnumber);
3433 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Items holding branch is the transfers origination branch before it is marked as lost' );
3435 #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
3436 $item->itemlost(1)->store;
3437 LostItem( $item->itemnumber, 'test', 1 );
3438 ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
3439 is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
3440 $itemcheck = Koha::Items->find($item->itemnumber);
3441 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
3445 subtest 'CanBookBeIssued | is_overdue' => sub {
3448 # Set a simple circ policy
3449 Koha::CirculationRules->set_rules(
3451 categorycode => undef,
3452 branchcode => undef,
3456 reservesallowed => 25,
3458 lengthunit => 'days',
3459 renewalsallowed => 1,
3461 norenewalbefore => undef,
3469 my $now = dt_from_string;
3470 my $five_days_go = output_pref({ dt => $now->clone->add( days => 5 ), dateonly => 1});
3471 my $ten_days_go = output_pref({ dt => $now->clone->add( days => 10), dateonly => 1 });
3472 my $library = $builder->build( { source => 'Branch' } );
3473 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
3475 my $item = $builder->build_sample_item(
3477 library => $library->{branchcode},
3481 my $issue = AddIssue( $patron->unblessed, $item->barcode, $five_days_go ); # date due was 10d ago
3482 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
3483 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
3484 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->barcode,$ten_days_go, undef, undef, undef);
3485 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
3486 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
3489 subtest 'ItemsDeniedRenewal preference' => sub {
3492 C4::Context->set_preference('ItemsDeniedRenewal','');
3494 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
3495 Koha::CirculationRules->set_rules(
3497 categorycode => '*',
3499 branchcode => $idr_lib->branchcode,
3501 reservesallowed => 25,
3503 lengthunit => 'days',
3504 renewalsallowed => 10,
3506 norenewalbefore => undef,
3514 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
3515 homebranch => $idr_lib->branchcode,
3519 itemcallnumber => undef,
3523 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
3524 homebranch => $idr_lib->branchcode,
3527 location => 'NOPROC'
3531 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
3532 branchcode => $idr_lib->branchcode,
3535 my $future = dt_from_string->add( days => 1 );
3536 my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3537 returndate => undef,
3540 borrowernumber => $idr_borrower->borrowernumber,
3541 itemnumber => $deny_book->itemnumber,
3542 onsite_checkout => 0,
3543 date_due => $future,
3546 my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3547 returndate => undef,
3550 borrowernumber => $idr_borrower->borrowernumber,
3551 itemnumber => $allow_book->itemnumber,
3552 onsite_checkout => 0,
3553 date_due => $future,
3559 my ( $idr_mayrenew, $idr_error ) =
3560 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3561 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3562 is( $idr_error, undef, 'Renewal allowed when no rules' );
3564 $idr_rules="withdrawn: [1]";
3566 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3567 ( $idr_mayrenew, $idr_error ) =
3568 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3569 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3570 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3571 ( $idr_mayrenew, $idr_error ) =
3572 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3573 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3574 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3576 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
3578 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3579 ( $idr_mayrenew, $idr_error ) =
3580 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3581 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
3582 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
3583 ( $idr_mayrenew, $idr_error ) =
3584 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3585 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3586 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3588 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
3590 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3591 ( $idr_mayrenew, $idr_error ) =
3592 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3593 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
3594 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
3595 ( $idr_mayrenew, $idr_error ) =
3596 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3597 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3598 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3600 $idr_rules="itemcallnumber: [NULL]";
3601 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3602 ( $idr_mayrenew, $idr_error ) =
3603 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3604 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
3605 $idr_rules="itemcallnumber: ['']";
3606 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3607 ( $idr_mayrenew, $idr_error ) =
3608 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3609 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
3611 $idr_rules="itemnotes: [NULL]";
3612 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3613 ( $idr_mayrenew, $idr_error ) =
3614 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3615 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
3616 $idr_rules="itemnotes: ['']";
3617 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3618 ( $idr_mayrenew, $idr_error ) =
3619 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3620 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
3623 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
3626 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3627 my $library = $builder->build( { source => 'Branch' } );
3628 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3630 my $item = $builder->build_sample_item(
3632 library => $library->{branchcode},
3636 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3637 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3638 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3641 subtest 'CanBookBeIssued | notforloan' => sub {
3644 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
3646 my $library = $builder->build( { source => 'Branch' } );
3647 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3649 my $itemtype = $builder->build(
3651 source => 'Itemtype',
3652 value => { notforloan => undef, }
3655 my $item = $builder->build_sample_item(
3657 library => $library->{branchcode},
3658 itype => $itemtype->{itemtype},
3661 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3663 my ( $issuingimpossible, $needsconfirmation );
3666 subtest 'item-level_itypes = 1' => sub {
3669 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
3670 # Is for loan at item type and item level
3671 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3672 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3673 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3675 # not for loan at item type level
3676 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3677 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3678 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3681 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3682 'Item can not be issued, not for loan at item type level'
3685 # not for loan at item level
3686 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3687 $item->notforloan( 1 )->store;
3688 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3689 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3692 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3693 'Item can not be issued, not for loan at item type level'
3697 subtest 'item-level_itypes = 0' => sub {
3700 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3702 # We set another itemtype for biblioitem
3703 my $itemtype = $builder->build(
3705 source => 'Itemtype',
3706 value => { notforloan => undef, }
3710 # for loan at item type and item level
3711 $item->notforloan(0)->store;
3712 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3713 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3714 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3715 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3717 # not for loan at item type level
3718 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3719 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3720 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3723 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3724 'Item can not be issued, not for loan at item type level'
3727 # not for loan at item level
3728 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3729 $item->notforloan( 1 )->store;
3730 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3731 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3734 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3735 'Item can not be issued, not for loan at item type level'
3739 # TODO test with AllowNotForLoanOverride = 1
3742 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
3745 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
3746 my $item = $builder->build_sample_item(
3748 onloan => '2018-01-01',
3752 AddReturn( $item->barcode, $item->homebranch );
3753 $item->discard_changes; # refresh
3754 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
3758 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
3763 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3765 my $issuing_charges = 15;
3766 my $title = 'A title';
3767 my $author = 'Author, An';
3768 my $barcode = 'WHATARETHEODDS';
3770 my $circ = Test::MockModule->new('C4::Circulation');
3772 'GetIssuingCharges',
3774 return $issuing_charges;
3778 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3779 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
3780 my $patron = $builder->build_object({
3781 class => 'Koha::Patrons',
3782 value => { branchcode => $library->id }
3785 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
3786 my $item_id = Koha::Item->new(
3788 biblionumber => $biblio->biblionumber,
3789 homebranch => $library->id,
3790 holdingbranch => $library->id,
3791 barcode => $barcode,
3792 replacementprice => 23.00,
3793 itype => $itemtype->id
3795 )->store->itemnumber;
3796 my $item = Koha::Items->find( $item_id );
3798 my $context = Test::MockModule->new('C4::Context');
3799 $context->mock( userenv => { branch => $library->id } );
3801 # Check the item out
3802 AddIssue( $patron->unblessed, $item->barcode );
3805 AddRenewal( $patron->borrowernumber, $item->itemnumber, $library->id, undef, {break=>"the_renewal"} );
3806 } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
3808 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
3809 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3810 my %params_renewal = (
3811 timestamp => { -like => $date . "%" },
3812 module => "CIRCULATION",
3813 action => "RENEWAL",
3815 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
3816 AddRenewal( $patron->id, $item->id, $library->id );
3817 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3818 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
3820 my $checkouts = $patron->checkouts;
3821 # The following will fail if run on 00:00:00
3822 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
3824 my $lines = Koha::Account::Lines->search({
3825 borrowernumber => $patron->id,
3826 itemnumber => $item->id
3829 is( $lines->count, 2 );
3831 my $line = $lines->next;
3832 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
3833 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
3834 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
3836 $line = $lines->next;
3837 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
3838 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
3839 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
3841 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
3843 $context = Test::MockModule->new('C4::Context');
3844 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
3846 my $now = dt_from_string;
3847 $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
3848 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
3849 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
3850 $sth->execute($item->id, $library->id);
3851 my ($old_stats_size) = $sth->fetchrow_array;
3852 AddRenewal( $patron->id, $item->id, $library->id );
3853 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3854 $sth->execute($item->id, $library->id);
3855 my ($new_stats_size) = $sth->fetchrow_array;
3856 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
3857 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
3859 AddReturn( $item->id, $library->id, undef, $date );
3860 AddIssue( $patron->unblessed, $item->barcode, $now );
3861 AddRenewal( $patron->id, $item->id, $library->id, undef, undef, 1 );
3862 my $lines_skipped = Koha::Account::Lines->search({
3863 borrowernumber => $patron->id,
3864 itemnumber => $item->id
3866 is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
3870 subtest 'ProcessOfflinePayment() tests' => sub {
3877 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
3878 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3879 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
3881 is( $result, 'Success.', 'The right string is returned' );
3883 my $lines = $patron->account->lines;
3884 is( $lines->count, 1, 'line created correctly');
3886 my $line = $lines->next;
3887 is( $line->amount+0, $amount * -1, 'amount picked from params' );
3888 is( $line->branchcode, $library->id, 'branchcode set correctly' );
3892 subtest 'Incremented fee tests' => sub {
3895 my $dt = dt_from_string();
3896 Time::Fake->offset( $dt->epoch );
3898 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
3901 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3903 $module->mock( 'userenv', sub { { branch => $library->id } } );
3905 my $patron = $builder->build_object(
3907 class => 'Koha::Patrons',
3908 value => { categorycode => $patron_category->{categorycode} }
3912 my $itemtype = $builder->build_object(
3914 class => 'Koha::ItemTypes',
3916 notforloan => undef,
3918 rentalcharge_daily => 1,
3919 rentalcharge_daily_calendar => 0
3924 my $item = $builder->build_sample_item(
3926 library => $library->{branchcode},
3927 itype => $itemtype->id,
3931 is( $itemtype->rentalcharge_daily+0,
3932 1, 'Daily rental charge stored and retreived correctly' );
3933 is( $item->effective_itemtype, $itemtype->id,
3934 "Itemtype set correctly for item" );
3936 my $now = dt_from_string;
3937 my $dt_from = $now->clone;
3938 my $dt_to = $now->clone->add( days => 7 );
3939 my $dt_to_renew = $now->clone->add( days => 13 );
3943 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3944 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3945 is( $accountline->amount+0, 7,
3946 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
3948 $accountline->delete();
3949 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3950 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3951 is( $accountline->amount+0, 6,
3952 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
3954 $accountline->delete();
3957 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3958 $itemtype->rentalcharge_daily_calendar(1)->store();
3960 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3961 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3962 is( $accountline->amount+0, 7,
3963 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
3965 $accountline->delete();
3966 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3967 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3968 is( $accountline->amount+0, 6,
3969 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
3971 $accountline->delete();
3974 my $calendar = C4::Calendar->new( branchcode => $library->id );
3975 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
3977 ( $dt_from->day_of_week == 6 ) ? 0
3978 : ( $dt_from->day_of_week == 7 ) ? 1
3979 : $dt_from->day_of_week + 1;
3980 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
3981 $calendar->insert_week_day_holiday(
3982 weekday => $closed_day,
3983 title => 'Test holiday',
3984 description => 'Test holiday'
3987 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3988 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3989 is( $accountline->amount+0, 6,
3990 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
3992 $accountline->delete();
3993 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3994 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3995 is( $accountline->amount+0, 5,
3996 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
3998 $accountline->delete();
4001 $itemtype->rentalcharge(2)->store;
4002 is( $itemtype->rentalcharge+0, 2,
4003 'Rental charge updated and retreived correctly' );
4005 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4007 Koha::Account::Lines->search( { itemnumber => $item->id } );
4008 is( $accountlines->count, '2',
4009 "Fixed charge and accrued charge recorded distinctly" );
4010 $accountlines->delete();
4011 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4012 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
4013 is( $accountlines->count, '2',
4014 "Fixed charge and accrued charge recorded distinctly, for renewal" );
4015 $accountlines->delete();
4017 $itemtype->rentalcharge(0)->store;
4018 is( $itemtype->rentalcharge+0, 0,
4019 'Rental charge reset and retreived correctly' );
4022 Koha::CirculationRules->set_rule(
4024 categorycode => $patron->categorycode,
4025 itemtype => $itemtype->id,
4026 branchcode => $library->id,
4027 rule_name => 'lengthunit',
4028 rule_value => 'hours',
4032 $itemtype->rentalcharge_hourly('0.25')->store();
4033 is( $itemtype->rentalcharge_hourly,
4034 '0.25', 'Hourly rental charge stored and retreived correctly' );
4036 $dt_to = $now->clone->add( hours => 168 );
4037 $dt_to_renew = $now->clone->add( hours => 312 );
4039 $itemtype->rentalcharge_hourly_calendar(0)->store();
4041 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4042 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4043 is( $accountline->amount + 0, 42,
4044 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)" );
4045 $accountline->delete();
4046 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4047 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4048 is( $accountline->amount + 0, 36,
4049 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)" );
4050 $accountline->delete();
4053 $itemtype->rentalcharge_hourly_calendar(1)->store();
4055 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4056 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4057 is( $accountline->amount + 0, 36,
4058 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)" );
4059 $accountline->delete();
4060 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4061 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4062 is( $accountline->amount + 0, 30,
4063 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
4064 $accountline->delete();
4067 $calendar->delete_holiday( weekday => $closed_day );
4069 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4070 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4071 is( $accountline->amount + 0, 42,
4072 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u" );
4073 $accountline->delete();
4074 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4075 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4076 is( $accountline->amount + 0, 36,
4077 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)" );
4078 $accountline->delete();
4083 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
4086 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
4087 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4090 $builder->build_object( { class => 'Koha::Libraries' } )->store;
4091 my $patron = $builder->build_object(
4093 class => 'Koha::Patrons',
4094 value => { categorycode => $patron_category->{categorycode} }
4098 my $itemtype = $builder->build_object(
4100 class => 'Koha::ItemTypes',
4104 rentalcharge_daily => 0
4109 my $item = $builder->build_sample_item(
4111 library => $library->id,
4115 itype => $itemtype->id,
4119 my ( $issuingimpossible, $needsconfirmation );
4120 my $dt_from = dt_from_string();
4121 my $dt_due = $dt_from->clone->add( days => 3 );
4123 $itemtype->rentalcharge(1)->store;
4124 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4125 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
4126 $itemtype->rentalcharge('0')->store;
4127 $itemtype->rentalcharge_daily(1)->store;
4128 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4129 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
4130 $itemtype->rentalcharge_daily('0')->store;
4133 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
4136 t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
4138 my $patron = $builder->build_object(
4140 class => 'Koha::Patrons',
4141 value => { categorycode => $patron_category->{categorycode} }
4145 my $item = $builder->build_sample_item(
4147 materials => 'includes DVD',
4151 my $dt_due = dt_from_string->add( days => 3 );
4153 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4154 is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
4157 subtest 'Do not return on renewal (LOST charge)' => sub {
4160 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
4161 my $library = $builder->build_object( { class => "Koha::Libraries" } );
4162 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
4163 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
4165 my $biblio = $builder->build_sample_biblio;
4167 my $item = $builder->build_sample_item(
4169 biblionumber => $biblio->biblionumber,
4170 library => $library->branchcode,
4171 replacementprice => 99.00,
4176 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
4177 AddIssue( $patron->unblessed, $item->barcode );
4179 my $accountline = Koha::Account::Line->new(
4181 borrowernumber => $patron->borrowernumber,
4182 debit_type_code => 'LOST',
4184 itemnumber => $item->itemnumber,
4186 amountoutstanding => 12,
4187 interface => 'something',
4191 # AddRenewal doesn't call _FixAccountForLostAndFound
4192 AddIssue( $patron->unblessed, $item->barcode );
4194 is( $patron->checkouts->count, 1,
4195 'Renewal should not return the item even if a LOST payment has been made earlier'
4199 subtest 'Filling a hold should cancel existing transfer' => sub {
4202 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
4204 my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
4205 my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
4206 my $patron = $builder->build_object(
4208 class => 'Koha::Patrons',
4210 categorycode => $patron_category->{categorycode},
4211 branchcode => $libraryA->branchcode,
4216 my $item = $builder->build_sample_item({
4217 homebranch => $libraryB->branchcode,
4220 my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4221 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
4223 branchcode => $libraryA->branchcode,
4224 borrowernumber => $patron->borrowernumber,
4225 biblionumber => $item->biblionumber,
4226 itemnumber => $item->itemnumber
4228 my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
4229 is( $reserves->count, 1, "Reserve is placed");
4230 ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4231 my $reserve = $reserves->next;
4232 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
4233 $reserve->discard_changes;
4234 ok( $reserve->found eq 'W', "Reserve is marked waiting" );
4235 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
4238 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
4242 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4243 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4244 my $patron = $builder->build_object(
4246 class => 'Koha::Patrons',
4247 value => { categorycode => $patron_category->{categorycode} }
4251 my $biblionumber = $builder->build_sample_biblio(
4253 branchcode => $library->branchcode,
4257 # And the circulation rule
4258 Koha::CirculationRules->search->delete;
4259 Koha::CirculationRules->set_rules(
4261 categorycode => undef,
4263 branchcode => undef,
4266 lengthunit => 'days',
4272 source => 'CirculationRule',
4274 branchcode => undef,
4275 categorycode => undef,
4277 rule_name => 'lostreturn',
4278 rule_value => 'refund'
4283 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4286 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4287 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4289 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4291 my $item = $builder->build_sample_item(
4293 biblionumber => $biblionumber,
4294 library => $library->branchcode,
4295 replacementprice => '42',
4298 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4299 LostItem( $item->itemnumber, 'cli', 0 );
4300 $item->_result->itemlost(1);
4301 $item->_result->itemlost_on( $lost_on );
4302 $item->_result->update();
4304 my $a = Koha::Account::Lines->search(
4306 itemnumber => $item->id,
4307 borrowernumber => $patron->borrowernumber
4310 ok( $a, "Found accountline for lost fee" );
4311 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4312 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4313 $a = $a->get_from_storage;
4314 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4318 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4321 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4322 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4324 my $lost_on = dt_from_string->subtract( days => 6 )->date;
4326 my $item = $builder->build_sample_item(
4328 biblionumber => $biblionumber,
4329 library => $library->branchcode,
4330 replacementprice => '42',
4333 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4334 LostItem( $item->itemnumber, 'cli', 0 );
4335 $item->_result->itemlost(1);
4336 $item->_result->itemlost_on( $lost_on );
4337 $item->_result->update();
4339 my $a = Koha::Account::Lines->search(
4341 itemnumber => $item->id,
4342 borrowernumber => $patron->borrowernumber
4345 ok( $a, "Found accountline for lost fee" );
4346 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4347 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4348 $a = $a->get_from_storage;
4349 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4353 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4356 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4357 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4359 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4361 my $item = $builder->build_sample_item(
4363 biblionumber => $biblionumber,
4364 library => $library->branchcode,
4365 replacementprice => '42',
4368 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4369 LostItem( $item->itemnumber, 'cli', 0 );
4370 $item->_result->itemlost(1);
4371 $item->_result->itemlost_on( $lost_on );
4372 $item->_result->update();
4374 my $a = Koha::Account::Lines->search(
4376 itemnumber => $item->id,
4377 borrowernumber => $patron->borrowernumber
4380 ok( $a, "Found accountline for lost fee" );
4381 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4382 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
4383 $a = $a->get_from_storage;
4384 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
4388 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4391 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4392 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4394 my $lost_on = dt_from_string->subtract( days => 8 )->date;
4396 my $item = $builder->build_sample_item(
4398 biblionumber => $biblionumber,
4399 library => $library->branchcode,
4400 replacementprice => '42',
4403 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4404 LostItem( $item->itemnumber, 'cli', 0 );
4405 $item->_result->itemlost(1);
4406 $item->_result->itemlost_on( $lost_on );
4407 $item->_result->update();
4409 my $a = Koha::Account::Lines->search(
4411 itemnumber => $item->id,
4412 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, 42, "Lost fee was not refunded" );
4425 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
4429 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
4430 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4431 my $patron = $builder->build_object(
4433 class => 'Koha::Patrons',
4434 value => { categorycode => $patron_category->{categorycode} }
4437 my $patron2 = $builder->build_object(
4439 class => 'Koha::Patrons',
4440 value => { categorycode => $patron_category->{categorycode} }
4444 my $biblionumber = $builder->build_sample_biblio(
4446 branchcode => $library->branchcode,
4450 # And the circulation rule
4451 Koha::CirculationRules->search->delete;
4452 Koha::CirculationRules->set_rules(
4454 categorycode => undef,
4456 branchcode => undef,
4459 lengthunit => 'days',
4465 source => 'CirculationRule',
4467 branchcode => undef,
4468 categorycode => undef,
4470 rule_name => 'lostreturn',
4471 rule_value => 'refund'
4476 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
4479 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4480 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
4482 my $lost_on = dt_from_string->subtract( days => 7 )->date;
4484 my $item = $builder->build_sample_item(
4486 biblionumber => $biblionumber,
4487 library => $library->branchcode,
4488 replacementprice => '42',
4491 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4492 LostItem( $item->itemnumber, 'cli', 0 );
4493 $item->_result->itemlost(1);
4494 $item->_result->itemlost_on( $lost_on );
4495 $item->_result->update();
4497 my $a = Koha::Account::Lines->search(
4499 itemnumber => $item->id,
4500 borrowernumber => $patron->borrowernumber
4503 ok( $a, "Found accountline for lost fee" );
4504 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4505 $issue = AddIssue( $patron2->unblessed, $item->barcode );
4506 $a = $a->get_from_storage;
4507 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4512 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
4515 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4516 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4518 my $lost_on = dt_from_string->subtract( days => 6 )->date;
4520 my $item = $builder->build_sample_item(
4522 biblionumber => $biblionumber,
4523 library => $library->branchcode,
4524 replacementprice => '42',
4527 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4528 LostItem( $item->itemnumber, 'cli', 0 );
4529 $item->_result->itemlost(1);
4530 $item->_result->itemlost_on( $lost_on );
4531 $item->_result->update();
4533 my $a = Koha::Account::Lines->search(
4535 itemnumber => $item->id,
4536 borrowernumber => $patron->borrowernumber
4539 ok( $a, "Found accountline for lost fee" );
4540 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
4541 $issue = AddIssue( $patron2->unblessed, $item->barcode );
4542 $a = $a->get_from_storage;
4543 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
4547 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
4550 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4551 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
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, 42, "Lost fee was not refunded" );
4582 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
4585 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
4586 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
4588 my $lost_on = dt_from_string->subtract( days => 8 )->date;
4590 my $item = $builder->build_sample_item(
4592 biblionumber => $biblionumber,
4593 library => $library->branchcode,
4594 replacementprice => '42',
4597 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4598 LostItem( $item->itemnumber, 'cli', 0 );
4599 $item->_result->itemlost(1);
4600 $item->_result->itemlost_on( $lost_on );
4601 $item->_result->update();
4603 my $a = Koha::Account::Lines->search(
4605 itemnumber => $item->id,
4606 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, 42, "Lost fee was not refunded" );
4619 subtest 'transferbook tests' => sub {
4623 { C4::Circulation::transferbook({}); }
4624 'Koha::Exceptions::MissingParameter',
4625 'Koha::Patron->store raises an exception on missing params';
4628 { C4::Circulation::transferbook({to_branch=>'anything'}); }
4629 'Koha::Exceptions::MissingParameter',
4630 'Koha::Patron->store raises an exception on missing params';
4633 { C4::Circulation::transferbook({from_branch=>'anything'}); }
4634 'Koha::Exceptions::MissingParameter',
4635 'Koha::Patron->store raises an exception on missing params';
4637 my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
4638 is( $doreturn, 0, "No return without barcode");
4639 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
4640 is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
4642 ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
4643 is( $doreturn, 0, "No return without barcode");
4644 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
4645 is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
4649 subtest 'Checkout should correctly terminate a transfer' => sub {
4652 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
4653 my $patron_1 = $builder->build_object(
4655 class => 'Koha::Patrons',
4656 value => { branchcode => $library_1->branchcode }
4659 my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
4660 my $patron_2 = $builder->build_object(
4662 class => 'Koha::Patrons',
4663 value => { branchcode => $library_2->branchcode }
4667 my $item = $builder->build_sample_item(
4669 library => $library_1->branchcode,
4673 t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
4674 my $reserve_id = AddReserve(
4676 branchcode => $library_2->branchcode,
4677 borrowernumber => $patron_2->borrowernumber,
4678 biblionumber => $item->biblionumber,
4679 itemnumber => $item->itemnumber,
4684 my $do_transfer = 1;
4685 ModItemTransfer( $item->itemnumber, $library_1->branchcode,
4686 $library_2->branchcode, 'Manual' );
4687 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
4688 GetOtherReserves( $item->itemnumber )
4689 ; # To put the Reason, it's what does returns.pl...
4690 my $hold = Koha::Holds->find($reserve_id);
4691 is( $hold->found, 'T', 'Hold is in transit' );
4692 my $transfer = $item->get_transfer;
4693 is( $transfer->frombranch, $library_1->branchcode );
4694 is( $transfer->tobranch, $library_2->branchcode );
4695 is( $transfer->reason, 'Reserve' );
4697 t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
4698 AddIssue( $patron_1->unblessed, $item->barcode );
4699 $transfer = $transfer->get_from_storage;
4700 isnt( $transfer->datearrived, undef );
4701 $hold = $hold->get_from_storage;
4702 is( $hold->found, undef, 'Hold is waiting' );
4703 is( $hold->priority, 1, );
4706 subtest 'AddIssue records staff who checked out item if appropriate' => sub {
4709 $module->mock( 'userenv', sub { { branch => $library->{id} } } );
4711 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
4712 my $patron = $builder->build_object(
4714 class => 'Koha::Patrons',
4715 value => { categorycode => $patron_category->{categorycode} }
4718 my $issuer = $builder->build_object(
4720 class => 'Koha::Patrons',
4721 value => { categorycode => $patron_category->{categorycode} }
4724 my $item = $builder->build_sample_item(
4726 library => $library->{branchcode}
4730 $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->{borrowernumber} } } );
4732 my $dt_from = dt_from_string();
4733 my $dt_to = dt_from_string()->add( days => 7 );
4735 my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4737 is( $issue->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
4739 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
4742 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4744 is( $issue->issuer, $issuer->{borrowernumber}, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
4747 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
4750 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
4751 my $patron_1 = $builder->build_object(
4753 class => 'Koha::Patrons',
4754 value => { branchcode => $library_1->branchcode }
4757 my $patron_2 = $builder->build_object(
4759 class => 'Koha::Patrons',
4760 value => { branchcode => $library_1->branchcode }
4764 my $item = $builder->build_sample_item(
4766 library => $library_1->branchcode,
4770 AddIssue( $patron_1->unblessed, $item->barcode );
4771 ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
4772 AddIssue( $patron_2->unblessed, $item->barcode );
4773 ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
4776 $schema->storage->txn_rollback;
4777 C4::Context->clear_syspref_cache();
4778 $branches = Koha::Libraries->search();
4779 for my $branch ( $branches->next ) {
4780 my $key = $branch->branchcode . "_holidays";
4781 $cache->clear_from_cache($key);