3 # This file is part of Koha.
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21 use Test::More tests => 67;
24 use Test::Deep qw( cmp_deeply );
30 use POSIX qw( floor );
32 use t::lib::TestBuilder;
35 use C4::Calendar qw( new insert_single_holiday insert_week_day_holiday delete_holiday );
36 use C4::Circulation qw( AddIssue AddReturn CanBookBeRenewed GetIssuingCharges AddRenewal GetSoonestRenewDate GetLatestAutoRenewDate LostItem GetUpcomingDueIssues CanBookBeIssued AddIssuingCharge MarkIssueReturned ProcessOfflinePayment transferbook updateWrongTransfer );
38 use C4::Items qw( ModItemTransfer );
40 use C4::Reserves qw( AddReserve ModReserve ModReserveCancelAll ModReserveAffect CheckReserves GetOtherReserves );
41 use C4::Overdues qw( CalcFine UpdateFine get_chargeable_units );
42 use C4::Members::Messaging qw( SetMessagingPreference );
43 use Koha::DateUtils qw( dt_from_string output_pref );
46 use Koha::Item::Transfers;
49 use Koha::Patron::Debarments qw( AddDebarment DelUniqueDebarment );
51 use Koha::CirculationRules;
52 use Koha::Subscriptions;
53 use Koha::Account::Lines;
54 use Koha::Account::Offsets;
56 use Koha::Notice::Messages;
57 use Koha::Cache::Memory::Lite;
59 my $builder = t::lib::TestBuilder->new;
62 my $staff = $builder->build_object({ class => "Koha::Patrons" });
63 t::lib::Mocks::mock_userenv({ patron => $staff, branchcode => $library->{branchcode} });
67 my ( $error, $question, $alert ) = @_;
69 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
70 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
71 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
75 sub test_debarment_on_checkout {
77 my $item = $params->{item};
78 my $library = $params->{library};
79 my $patron = $params->{patron};
80 my $due_date = $params->{due_date} || dt_from_string;
81 my $return_date = $params->{return_date} || dt_from_string;
82 my $expected_expiration_date = $params->{expiration_date};
84 $expected_expiration_date = output_pref(
86 dt => $expected_expiration_date,
92 my $line_number = $caller[2];
93 AddIssue( $patron->unblessed, $item->barcode, $due_date );
95 my ( undef, $message ) = AddReturn( $item->barcode, $library->{branchcode}, undef, $return_date );
96 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
97 or diag('AddReturn returned message ' . Dumper $message );
98 my $suspensions = $patron->restrictions->search({ type => 'SUSPENSION' } );
99 is( $suspensions->count, 1, 'Test at line ' . $line_number );
101 my $THE_suspension = $suspensions->next;
102 is( $THE_suspension->expiration,
103 $expected_expiration_date, 'Test at line ' . $line_number );
104 Koha::Patron::Debarments::DelUniqueDebarment(
105 { borrowernumber => $patron->borrowernumber, type => 'SUSPENSION' } );
108 my $schema = Koha::Database->schema;
109 $schema->storage->txn_begin;
110 my $dbh = C4::Context->dbh;
112 # Prevent random failures by mocking ->now
113 my $now_value = dt_from_string;
114 my $mocked_datetime = Test::MockModule->new('DateTime');
115 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
117 my $cache = Koha::Caches->get_instance();
118 $dbh->do(q|DELETE FROM special_holidays|);
119 $dbh->do(q|DELETE FROM repeatable_holidays|);
120 my $branches = Koha::Libraries->search();
121 for my $branch ( $branches->next ) {
122 my $key = $branch->branchcode . "_holidays";
123 $cache->clear_from_cache($key);
126 # Start with a clean slate
127 $dbh->do('DELETE FROM issues');
128 $dbh->do('DELETE FROM borrowers');
130 # Disable recording of the staff who checked out an item until we're ready for it
131 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 0);
133 my $module = Test::MockModule->new('C4::Context');
135 my $library = $builder->build({
138 my $library2 = $builder->build({
141 my $itemtype = $builder->build(
143 source => 'Itemtype',
147 rentalcharge_daily => 0,
148 defaultreplacecost => undef,
153 my $patron_category = $builder->build(
155 source => 'Category',
157 category_type => 'P',
159 BlockExpiredPatronOpacActions => -1, # Pick the pref value
164 my $CircControl = C4::Context->preference('CircControl');
165 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
168 homebranch => $library2->{branchcode},
169 holdingbranch => $library2->{branchcode}
173 branchcode => $library2->{branchcode}
176 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
178 # No userenv, PickupLibrary
179 t::lib::Mocks::mock_preference('IndependentBranches', '0');
180 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
182 C4::Context->preference('CircControl'),
184 'CircControl changed to PickupLibrary'
187 C4::Circulation::_GetCircControlBranch($item, $borrower),
188 $item->{$HomeOrHoldingBranch},
189 '_GetCircControlBranch returned item branch (no userenv defined)'
192 # No userenv, PatronLibrary
193 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
195 C4::Context->preference('CircControl'),
197 'CircControl changed to PatronLibrary'
200 C4::Circulation::_GetCircControlBranch($item, $borrower),
201 $borrower->{branchcode},
202 '_GetCircControlBranch returned borrower branch'
205 # No userenv, ItemHomeLibrary
206 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
208 C4::Context->preference('CircControl'),
210 'CircControl changed to ItemHomeLibrary'
213 $item->{$HomeOrHoldingBranch},
214 C4::Circulation::_GetCircControlBranch($item, $borrower),
215 '_GetCircControlBranch returned item branch'
219 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
220 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
222 # Userenv set, PickupLibrary
223 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
225 C4::Context->preference('CircControl'),
227 'CircControl changed to PickupLibrary'
230 C4::Circulation::_GetCircControlBranch($item, $borrower),
231 $library2->{branchcode},
232 '_GetCircControlBranch returned current branch'
235 # Userenv set, PatronLibrary
236 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
238 C4::Context->preference('CircControl'),
240 'CircControl changed to PatronLibrary'
243 C4::Circulation::_GetCircControlBranch($item, $borrower),
244 $borrower->{branchcode},
245 '_GetCircControlBranch returned borrower branch'
248 # Userenv set, ItemHomeLibrary
249 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
251 C4::Context->preference('CircControl'),
253 'CircControl changed to ItemHomeLibrary'
256 C4::Circulation::_GetCircControlBranch($item, $borrower),
257 $item->{$HomeOrHoldingBranch},
258 '_GetCircControlBranch returned item branch'
261 # Reset initial configuration
262 t::lib::Mocks::mock_preference('CircControl', $CircControl);
264 C4::Context->preference('CircControl'),
266 'CircControl reset to its initial value'
269 # Set a simple circ policy
270 $dbh->do('DELETE FROM circulation_rules');
271 Koha::CirculationRules->set_rules(
273 categorycode => undef,
277 reservesallowed => 25,
279 lengthunit => 'days',
280 renewalsallowed => 1,
282 norenewalbefore => undef,
290 subtest "CanBookBeRenewed AllowRenewalIfOtherItemsAvailable multiple borrowers and items tests" => sub {
293 #Can only reserve from home branch
294 Koha::CirculationRules->set_rule(
298 rule_name => 'holdallowed',
302 Koha::CirculationRules->set_rule(
305 categorycode => undef,
307 rule_name => 'onshelfholds',
312 # Patrons from three different branches
313 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
314 my $patron_hold_1 = $builder->build_object({ class => 'Koha::Patrons' });
315 my $patron_hold_2 = $builder->build_object({ class => 'Koha::Patrons' });
316 my $biblio = $builder->build_sample_biblio();
318 # Item at each patron branch
319 my $item_1 = $builder->build_sample_item({
320 biblionumber => $biblio->biblionumber,
321 homebranch => $patron->branchcode
323 my $item_2 = $builder->build_sample_item({
324 biblionumber => $biblio->biblionumber,
325 homebranch => $patron_hold_2->branchcode
327 my $item_3 = $builder->build_sample_item({
328 biblionumber => $biblio->biblionumber,
329 homebranch => $patron_hold_1->branchcode
332 my $issue = AddIssue( $patron->unblessed, $item_1->barcode);
333 my $datedue = dt_from_string( $issue->date_due() );
334 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
337 my $reserve_1 = AddReserve(
339 branchcode => $patron_hold_1->branchcode,
340 borrowernumber => $patron_hold_1->borrowernumber,
341 biblionumber => $biblio->biblionumber,
343 reservation_date => dt_from_string(),
344 expiration_date => undef,
351 branchcode => $patron_hold_2->branchcode,
352 borrowernumber => $patron_hold_2->borrowernumber,
353 biblionumber => $biblio->biblionumber,
355 reservation_date => dt_from_string(),
356 expiration_date => undef,
361 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
363 my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue);
364 is( $renewokay, 0, 'Cannot renew, reserved');
365 is( $error, 'on_reserve', 'Cannot renew, reserved (returned error is on_reserve)');
367 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
369 ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue);
370 is( $renewokay, 1, 'Can renew, two items available for two holds');
371 is( $error, undef, 'Can renew, each reserve has an item');
374 my $hold = Koha::Holds->find( $reserve_1 );
375 $hold->itemnumber( $item_1->itemnumber )->store;
377 ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue);
378 is( $renewokay, 0, 'Cannot renew when there is an item specific hold');
379 is( $error, 'on_reserve', 'Cannot renew, only this item can fill the reserve');
382 subtest "GetIssuingCharges tests" => sub {
384 my $branch_discount = $builder->build_object({ class => 'Koha::Libraries' });
385 my $branch_no_discount = $builder->build_object({ class => 'Koha::Libraries' });
386 Koha::CirculationRules->set_rule(
388 categorycode => undef,
389 branchcode => $branch_discount->branchcode,
391 rule_name => 'rentaldiscount',
395 my $itype_charge = $builder->build_object({
396 class => 'Koha::ItemTypes',
401 my $itype_no_charge = $builder->build_object({
402 class => 'Koha::ItemTypes',
407 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
408 my $item_1 = $builder->build_sample_item({ itype => $itype_charge->itemtype });
409 my $item_2 = $builder->build_sample_item({ itype => $itype_no_charge->itemtype });
411 t::lib::Mocks::mock_userenv({ branchcode => $branch_no_discount->branchcode });
412 # For now the sub always uses the env branch, this should follow CircControl instead
413 my ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
414 is( $charge + 0, 10.00, "Charge fetched correctly when no discount exists");
415 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
416 is( $charge + 0, 0.00, "Charge fetched correctly when no discount exists and no charge");
418 t::lib::Mocks::mock_userenv({ branchcode => $branch_discount->branchcode });
419 # For now the sub always uses the env branch, this should follow CircControl instead
420 ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
421 is( $charge + 0, 8.50, "Charge fetched correctly when discount exists");
422 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
423 is( $charge + 0, 0.00, "Charge fetched correctly when discount exists and no charge");
427 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
428 subtest "CanBookBeRenewed tests" => sub {
431 C4::Context->set_preference('ItemsDeniedRenewal','');
432 # Generate test biblio
433 my $biblio = $builder->build_sample_biblio();
435 my $branch = $library2->{branchcode};
437 my $item_1 = $builder->build_sample_item(
439 biblionumber => $biblio->biblionumber,
441 replacementprice => 12.00,
445 $reused_itemnumber_1 = $item_1->itemnumber;
447 my $item_2 = $builder->build_sample_item(
449 biblionumber => $biblio->biblionumber,
451 replacementprice => 23.00,
455 $reused_itemnumber_2 = $item_2->itemnumber;
457 my $item_3 = $builder->build_sample_item(
459 biblionumber => $biblio->biblionumber,
461 replacementprice => 23.00,
467 my %renewing_borrower_data = (
469 surname => 'Renewal',
470 categorycode => $patron_category->{categorycode},
471 branchcode => $branch,
472 autorenew_checkouts => 1,
475 my %reserving_borrower_data = (
476 firstname => 'Katrin',
477 surname => 'Reservation',
478 categorycode => $patron_category->{categorycode},
479 branchcode => $branch,
482 my %hold_waiting_borrower_data = (
484 surname => 'Reservation',
485 categorycode => $patron_category->{categorycode},
486 branchcode => $branch,
489 my %restricted_borrower_data = (
490 firstname => 'Alice',
491 surname => 'Reservation',
492 categorycode => $patron_category->{categorycode},
493 debarred => '3228-01-01',
494 branchcode => $branch,
497 my %expired_borrower_data = (
500 categorycode => $patron_category->{categorycode},
501 branchcode => $branch,
502 dateexpiry => dt_from_string->subtract( months => 1 ),
503 autorenew_checkouts => 1,
506 my $renewing_borrower_obj = Koha::Patron->new(\%renewing_borrower_data)->store;
507 my $renewing_borrowernumber = $renewing_borrower_obj->borrowernumber;
508 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
509 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
510 my $restricted_borrower_obj = Koha::Patron->new(\%restricted_borrower_data)->store;
512 my $expired_borrower_obj = Koha::Patron->new(\%expired_borrower_data)->store;
519 my $checkitem = undef;
522 my $issue_1 = AddIssue( $renewing_borrower_obj->unblessed, $item_1->barcode);
523 my $datedue = dt_from_string( $issue_1->date_due() );
524 is (defined $issue_1->date_due(), 1, "Item 1 checked out, due date: " . $issue_1->date_due() );
526 my $issue_2 = AddIssue( $renewing_borrower_obj->unblessed, $item_2->barcode);
527 is (defined $issue_2, 1, "Item 2 checked out, due date: " . $issue_2->date_due());
529 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
530 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to ".$renewing_borrower_obj->firstname." ".$renewing_borrower_obj->surname);
532 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1, 1);
533 is( $renewokay, 1, 'Can renew, no holds for this title or item');
536 # Biblio-level hold, renewal test
539 branchcode => $branch,
540 borrowernumber => $reserving_borrowernumber,
541 biblionumber => $biblio->biblionumber,
542 priority => $priority,
543 reservation_date => $resdate,
544 expiration_date => $expdate,
546 itemnumber => $checkitem,
551 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
552 Koha::CirculationRules->set_rule(
554 categorycode => undef,
557 rule_name => 'onshelfholds',
561 Koha::CirculationRules->set_rule(
563 categorycode => undef,
566 rule_name => 'renewalsallowed',
570 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
571 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
572 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
573 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2);
574 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
577 # Second biblio-level hold
578 my $reserve_id = AddReserve(
580 branchcode => $branch,
581 borrowernumber => $reserving_borrowernumber,
582 biblionumber => $biblio->biblionumber,
583 priority => $priority,
584 reservation_date => $resdate,
585 expiration_date => $expdate,
587 itemnumber => $checkitem,
591 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
592 is( $renewokay, 0, 'Renewal not possible when single patron\'s holds exceed the number of available items');
593 Koha::Holds->find($reserve_id)->delete;
595 # Now let's add an item level hold, we should no longer be able to renew the item
596 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
598 borrowernumber => $hold_waiting_borrowernumber,
599 biblionumber => $biblio->biblionumber,
600 itemnumber => $item_1->itemnumber,
601 branchcode => $branch,
603 reservedate => '1999-01-01',
606 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
607 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
610 # 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
611 # be able to renew these items
612 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
614 borrowernumber => $hold_waiting_borrowernumber,
615 biblionumber => $biblio->biblionumber,
616 itemnumber => $item_3->itemnumber,
617 branchcode => $branch,
622 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
623 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
624 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2);
625 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
626 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
628 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
629 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
630 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
632 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2);
633 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
634 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
636 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
637 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
638 AddIssue($reserving_borrower, $item_3->barcode);
639 my $reserve = $dbh->selectrow_hashref(
640 'SELECT * FROM old_reserves WHERE reserve_id = ?',
644 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
646 # Item-level hold, renewal test
649 branchcode => $branch,
650 borrowernumber => $reserving_borrowernumber,
651 biblionumber => $biblio->biblionumber,
652 priority => $priority,
653 reservation_date => $resdate,
654 expiration_date => $expdate,
656 itemnumber => $item_1->itemnumber,
661 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1, 1);
662 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
663 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
665 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2, 1);
666 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
668 # Items can't fill hold for reasons
669 $issue_1->item->notforloan(1)->store;
670 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1, 1);
671 is( $renewokay, 0, 'Cannot renew, item is marked not for loan, but an item specific hold always blocks');
672 $item_1->set({notforloan => 0, itype => $itemtype })->store;
674 # FIXME: Add more for itemtype not for loan etc.
676 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
677 my $item_5 = $builder->build_sample_item(
679 biblionumber => $biblio->biblionumber,
681 replacementprice => 23.00,
685 my $issue_5 = AddIssue($restricted_borrower_obj->unblessed, $item_5->barcode);
686 is (defined $issue_5, 1, "Item with date due checked out, due date: ". $issue_5->date_due);
688 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
689 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2);
690 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
691 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrower_obj, $issue_5);
692 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
693 is( $error, 'restriction', "Correct error returned");
695 # Users cannot renew an overdue item
696 my $item_6 = $builder->build_sample_item(
698 biblionumber => $biblio->biblionumber,
700 replacementprice => 23.00,
705 my $item_7 = $builder->build_sample_item(
707 biblionumber => $biblio->biblionumber,
709 replacementprice => 23.00,
714 my $issue_6 = AddIssue( $renewing_borrower_obj->unblessed, $item_6->barcode);
715 is (defined $issue_6, 1, "Item 2 checked out, due date: ".$issue_6->date_due);
717 my $now = dt_from_string();
718 my $five_weeks = DateTime::Duration->new(weeks => 5);
719 my $five_weeks_ago = $now - $five_weeks;
720 t::lib::Mocks::mock_preference('finesMode', 'production');
722 my $issue_7 = AddIssue($renewing_borrower_obj->unblessed, $item_7->barcode, $five_weeks_ago);
723 is (defined $issue_7, 1, "Item with passed date due checked out, due date: " . $issue_7->date_due);
725 t::lib::Mocks::mock_preference('OverduesBlockRenewing','allow');
726 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_6);
727 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
728 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_7);
729 is( $renewokay, 1, '(Bug 8236), Can renew, this item is overdue but not pref does not block');
731 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
732 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_6);
733 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is not overdue but patron has overdues');
734 is( $error, 'overdue', "Correct error returned");
735 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_7);
736 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue so patron has overdues');
737 is( $error, 'overdue', "Correct error returned");
739 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
740 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_6);
741 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
742 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_7);
743 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
744 is( $error, 'overdue', "Correct error returned");
746 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower_obj->categorycode, $branch, $five_weeks_ago, $now );
747 C4::Overdues::UpdateFine(
749 issue_id => $issue_7->id(),
750 itemnumber => $item_7->itemnumber,
751 borrowernumber => $renewing_borrower_obj->borrowernumber,
753 due => Koha::DateUtils::output_pref($five_weeks_ago)
757 # Make sure fine calculation isn't skipped when adding renewal
758 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
760 # Calculate new due-date based on the present date not to incur
762 t::lib::Mocks::mock_preference('RenewalPeriodBase', 'now');
764 my $staff = $builder->build_object({ class => "Koha::Patrons" });
765 t::lib::Mocks::mock_userenv({ patron => $staff });
767 t::lib::Mocks::mock_preference('RenewalLog', 0);
768 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
769 my %params_renewal = (
770 timestamp => { -like => $date . "%" },
771 module => "CIRCULATION",
775 timestamp => { -like => $date . "%" },
776 module => "CIRCULATION",
779 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
780 my $dt = dt_from_string();
781 Time::Fake->offset( $dt->epoch );
782 my $datedue1 = AddRenewal(
784 borrowernumber => $renewing_borrower_obj->borrowernumber,
785 itemnumber => $item_7->itemnumber,
789 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
790 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
791 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
794 t::lib::Mocks::mock_preference('RenewalLog', 1);
795 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
796 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
799 borrowernumber => $renewing_borrower_obj->borrowernumber,
800 itemnumber => $item_7->itemnumber,
804 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
805 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
807 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower_obj->borrowernumber, itemnumber => $item_7->itemnumber } );
808 is( $fines->count, 1, 'AddRenewal left fine' );
809 is( $fines->next->status, 'RENEWED', 'Fine on renewed item is closed out properly' );
812 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
813 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
815 $renewing_borrower_obj->unblessed,
817 Koha::DateUtils::output_pref({str=>$issue_6->date_due, dateformat =>'iso'}),
822 ); # TODO: Already issued???
823 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
824 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
825 $new_log_size = Koha::ActionLogs->count( \%params_issue );
826 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
828 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
832 # Test automatic renewal before value for "norenewalbefore" in policy is set
833 # In this case automatic renewal is not permitted prior to due date
834 my $item_4 = $builder->build_sample_item(
836 biblionumber => $biblio->biblionumber,
838 replacementprice => 16.00,
843 my $issue_4 = AddIssue( $renewing_borrower_obj->unblessed, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
845 ( $renewokay, $error, $info ) =
846 CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
847 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
848 is( $error, 'auto_too_soon',
849 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
850 is( $info->{soonest_renew_date} , dt_from_string($issue_4->date_due), "Due date is returned as earliest renewal date when error is 'auto_too_soon'" );
853 branchcode => $branch,
854 borrowernumber => $reserving_borrowernumber,
855 biblionumber => $biblio->biblionumber,
856 itemnumber => $bibitems,
857 priority => $priority,
858 reservation_date => $resdate,
859 expiration_date => $expdate,
862 itemnumber => $item_4->itemnumber,
866 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
867 is( $renewokay, 0, 'Still should not be able to renew' );
868 is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' );
869 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4, undef, 1 );
870 is( $renewokay, 0, 'Still should not be able to renew' );
871 is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' );
872 is( $info->{soonest_renew_date}, dt_from_string($issue_4->date_due), "Due date is returned as earliest renewal date when error is 'auto_too_soon'" );
873 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4, 1 );
874 is( $renewokay, 0, 'Still should not be able to renew' );
875 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
876 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4, 1, 1 );
877 is( $renewokay, 0, 'Still should not be able to renew' );
878 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
879 $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
880 Koha::Cache::Memory::Lite->flush();
881 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4, 1 );
882 is( $renewokay, 0, 'Still should not be able to renew' );
883 is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
884 ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
886 $renewing_borrower_obj = Koha::Patrons->find($renewing_borrower_obj->borrowernumber);
887 $renewing_borrower_obj->autorenew_checkouts(0)->store;
888 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
889 is( $renewokay, 1, 'No renewal before is undef, but patron opted out of auto_renewal' );
890 $renewing_borrower_obj->autorenew_checkouts(1)->store;
894 # Test premature manual renewal
895 Koha::CirculationRules->set_rule(
897 categorycode => undef,
900 rule_name => 'norenewalbefore',
905 ( $renewokay, $error, $info ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
906 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
907 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
908 is( $info->{soonest_renew_date}, dt_from_string($issue_1->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
911 # Test premature automatic renewal
912 ( $renewokay, $error, $info ) =
913 CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
914 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
915 is( $error, 'auto_too_soon',
916 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
918 is( $info->{soonest_renew_date}, dt_from_string($issue_4->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'auto_too_soon'");
920 $renewing_borrower_obj->autorenew_checkouts(0)->store;
921 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
922 is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' );
923 is( $error, 'too_soon', 'Error is too_soon, no auto' );
924 is( $info->{soonest_renew_date}, dt_from_string($issue_4->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
925 $renewing_borrower_obj->autorenew_checkouts(1)->store;
927 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
928 # and test automatic renewal again
929 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
930 Koha::Cache::Memory::Lite->flush();
931 ( $renewokay, $error, $info ) =
932 CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
933 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
934 is( $error, 'auto_too_soon',
935 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
937 is( $info->{soonest_renew_date}, dt_from_string($issue_4->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
939 $renewing_borrower_obj->autorenew_checkouts(0)->store;
940 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
941 is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' );
942 is( $error, 'too_soon', 'Error is too_soon, no auto' );
943 is( $info->{soonest_renew_date}, dt_from_string($issue_4->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
944 $renewing_borrower_obj->autorenew_checkouts(1)->store;
946 # Change policy so that loans can be renewed 99 days prior to the due date
947 # and test automatic renewal again
948 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
949 Koha::Cache::Memory::Lite->flush();
950 ( $renewokay, $error ) =
951 CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
952 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
953 is( $error, 'auto_renew',
954 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
957 $renewing_borrower_obj->autorenew_checkouts(0)->store;
958 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
959 is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' );
960 $renewing_borrower_obj->autorenew_checkouts(1)->store;
962 subtest "too_late_renewal / no_auto_renewal_after" => sub {
964 my $item_to_auto_renew = $builder->build_sample_item(
966 biblionumber => $biblio->biblionumber,
971 my $ten_days_before = dt_from_string->add( days => -10 );
972 my $ten_days_ahead = dt_from_string->add( days => 10 );
973 my $issue = AddIssue( $renewing_borrower_obj->unblessed, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
975 Koha::CirculationRules->set_rules(
977 categorycode => undef,
981 norenewalbefore => '7',
982 no_auto_renewal_after => '9',
986 ( $renewokay, $error ) =
987 CanBookBeRenewed( $renewing_borrower_obj, $issue );
988 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
989 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
991 Koha::CirculationRules->set_rules(
993 categorycode => undef,
997 norenewalbefore => '7',
998 no_auto_renewal_after => '10',
1002 ( $renewokay, $error ) =
1003 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1004 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1005 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
1007 Koha::CirculationRules->set_rules(
1009 categorycode => undef,
1010 branchcode => undef,
1013 norenewalbefore => '7',
1014 no_auto_renewal_after => '11',
1018 ( $renewokay, $error ) =
1019 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1020 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1021 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
1023 Koha::CirculationRules->set_rules(
1025 categorycode => undef,
1026 branchcode => undef,
1029 norenewalbefore => '10',
1030 no_auto_renewal_after => '11',
1034 ( $renewokay, $error ) =
1035 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1036 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1037 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1039 Koha::CirculationRules->set_rules(
1041 categorycode => undef,
1042 branchcode => undef,
1045 norenewalbefore => '10',
1046 no_auto_renewal_after => undef,
1047 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1051 ( $renewokay, $error ) =
1052 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1053 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1054 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1056 Koha::CirculationRules->set_rules(
1058 categorycode => undef,
1059 branchcode => undef,
1062 norenewalbefore => '7',
1063 no_auto_renewal_after => '15',
1064 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1068 ( $renewokay, $error ) =
1069 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1070 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1071 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1073 Koha::CirculationRules->set_rules(
1075 categorycode => undef,
1076 branchcode => undef,
1079 norenewalbefore => '10',
1080 no_auto_renewal_after => undef,
1081 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
1085 ( $renewokay, $error ) =
1086 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1087 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1088 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1091 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
1093 my $item_to_auto_renew = $builder->build_sample_item(
1095 biblionumber => $biblio->biblionumber,
1100 my $ten_days_before = dt_from_string->add( days => -10 );
1101 my $ten_days_ahead = dt_from_string->add( days => 10 );
1102 my $issue = AddIssue( $renewing_borrower_obj->unblessed, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1104 Koha::CirculationRules->set_rules(
1106 categorycode => undef,
1107 branchcode => undef,
1110 norenewalbefore => '10',
1111 no_auto_renewal_after => '11',
1115 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
1116 C4::Context->set_preference('OPACFineNoRenewals','10');
1117 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1118 my $fines_amount = 5;
1119 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
1120 $account->add_debit(
1122 amount => $fines_amount,
1123 interface => 'test',
1125 item_id => $item_to_auto_renew->itemnumber,
1126 description => "Some fines"
1128 )->status('RETURNED')->store;
1129 ( $renewokay, $error ) =
1130 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1131 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1132 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
1134 $account->add_debit(
1136 amount => $fines_amount,
1137 interface => 'test',
1139 item_id => $item_to_auto_renew->itemnumber,
1140 description => "Some fines"
1142 )->status('RETURNED')->store;
1143 ( $renewokay, $error ) =
1144 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1145 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1146 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
1148 $account->add_debit(
1150 amount => $fines_amount,
1151 interface => 'test',
1153 item_id => $item_to_auto_renew->itemnumber,
1154 description => "Some fines"
1156 )->status('RETURNED')->store;
1157 ( $renewokay, $error ) =
1158 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1159 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1160 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
1162 $account->add_credit(
1164 amount => $fines_amount,
1165 interface => 'test',
1167 description => "Some payment"
1170 ( $renewokay, $error ) =
1171 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1172 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1173 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1175 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
1176 ( $renewokay, $error ) =
1177 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1178 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1179 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1181 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
1182 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1185 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
1187 my $item_to_auto_renew = $builder->build_sample_item(
1189 biblionumber => $biblio->biblionumber,
1194 Koha::CirculationRules->set_rules(
1196 categorycode => undef,
1197 branchcode => undef,
1200 norenewalbefore => 10,
1201 no_auto_renewal_after => 11,
1206 my $ten_days_before = dt_from_string->add( days => -10 );
1207 my $ten_days_ahead = dt_from_string->add( days => 10 );
1209 # Patron is expired and BlockExpiredPatronOpacActions=0
1210 # => auto renew is allowed
1211 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
1212 my $issue = AddIssue( $expired_borrower_obj->unblessed, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1213 ( $renewokay, $error ) =
1214 CanBookBeRenewed( $expired_borrower_obj, $issue );
1215 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1216 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
1217 Koha::Checkouts->find( $issue->issue_id )->delete;
1220 # Patron is expired and BlockExpiredPatronOpacActions=1
1221 # => auto renew is not allowed
1222 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1223 $issue = AddIssue( $expired_borrower_obj->unblessed, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1224 ( $renewokay, $error ) =
1225 CanBookBeRenewed( $expired_borrower_obj, $issue );
1226 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1227 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
1230 # Patron is not expired and BlockExpiredPatronOpacActions=1
1231 # => auto renew is allowed
1232 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1233 $issue = AddIssue( $renewing_borrower_obj->unblessed, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1234 ( $renewokay, $error ) =
1235 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1236 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1237 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1241 subtest "GetLatestAutoRenewDate" => sub {
1243 my $item_to_auto_renew = $builder->build_sample_item(
1245 biblionumber => $biblio->biblionumber,
1250 my $ten_days_before = dt_from_string->add( days => -10 );
1251 my $ten_days_ahead = dt_from_string->add( days => 10 );
1252 my $issue = AddIssue( $renewing_borrower_obj->unblessed, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1253 Koha::CirculationRules->set_rules(
1255 categorycode => undef,
1256 branchcode => undef,
1259 norenewalbefore => '7',
1260 no_auto_renewal_after => '',
1261 no_auto_renewal_after_hard_limit => undef,
1265 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1266 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' );
1267 my $five_days_before = dt_from_string->add( days => -5 );
1268 Koha::CirculationRules->set_rules(
1270 categorycode => undef,
1271 branchcode => undef,
1274 norenewalbefore => '10',
1275 no_auto_renewal_after => '5',
1276 no_auto_renewal_after_hard_limit => undef,
1280 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj,, $issue );
1281 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1282 $five_days_before->truncate( to => 'minute' ),
1283 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1285 my $five_days_ahead = dt_from_string->add( days => 5 );
1286 $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1287 $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1288 $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1289 Koha::Cache::Memory::Lite->flush();
1290 Koha::CirculationRules->set_rules(
1292 categorycode => undef,
1293 branchcode => undef,
1296 norenewalbefore => '10',
1297 no_auto_renewal_after => '15',
1298 no_auto_renewal_after_hard_limit => undef,
1302 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1303 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1304 $five_days_ahead->truncate( to => 'minute' ),
1305 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1307 my $two_days_ahead = dt_from_string->add( days => 2 );
1308 Koha::CirculationRules->set_rules(
1310 categorycode => undef,
1311 branchcode => undef,
1314 norenewalbefore => '10',
1315 no_auto_renewal_after => '',
1316 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1320 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1321 is( $latest_auto_renew_date->truncate( to => 'day' ),
1322 $two_days_ahead->truncate( to => 'day' ),
1323 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1325 Koha::CirculationRules->set_rules(
1327 categorycode => undef,
1328 branchcode => undef,
1331 norenewalbefore => '10',
1332 no_auto_renewal_after => '15',
1333 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1337 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1338 is( $latest_auto_renew_date->truncate( to => 'day' ),
1339 $two_days_ahead->truncate( to => 'day' ),
1340 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1346 # set policy to forbid renewals
1347 Koha::CirculationRules->set_rules(
1349 categorycode => undef,
1350 branchcode => undef,
1353 norenewalbefore => undef,
1354 renewalsallowed => 0,
1359 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
1360 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1361 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1363 # Too many unseen renewals
1364 Koha::CirculationRules->set_rules(
1366 categorycode => undef,
1367 branchcode => undef,
1370 unseen_renewals_allowed => 2,
1371 renewalsallowed => 10,
1375 t::lib::Mocks::mock_preference('UnseenRenewals', 1);
1376 $issue_1->unseen_renewals(2)->store;
1378 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
1379 is( $renewokay, 0, 'Cannot renew, 0 unseen renewals allowed');
1380 is( $error, 'too_unseen', 'Cannot renew, returned code is too_unseen');
1381 Koha::CirculationRules->set_rules(
1383 categorycode => undef,
1384 branchcode => undef,
1387 norenewalbefore => undef,
1388 renewalsallowed => 0,
1392 t::lib::Mocks::mock_preference('UnseenRenewals', 0);
1394 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1395 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1396 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1398 C4::Overdues::UpdateFine(
1400 issue_id => $issue_1->id(),
1401 itemnumber => $item_1->itemnumber,
1402 borrowernumber => $renewing_borrower_obj->borrowernumber,
1405 due => Koha::DateUtils::output_pref($datedue)
1409 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower_obj->borrowernumber })->next();
1410 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1411 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1412 is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1413 is( $line->amount+0, 15, 'Account line amount is 15.00' );
1414 is( $line->issue_id, $issue_1->id, 'Account line issue id matches' );
1416 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1417 is( $offset->type, 'CREATE', 'Account offset type is CREATE' );
1418 is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1420 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1421 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1423 LostItem( $item_1->itemnumber, 'test', 1 );
1425 $line = Koha::Account::Lines->find($line->id);
1426 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1427 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1429 my $item = Koha::Items->find($item_1->itemnumber);
1430 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1431 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1432 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1434 my $total_due = $dbh->selectrow_array(
1435 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1436 undef, $renewing_borrower_obj->borrowernumber
1439 is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1441 C4::Context->dbh->do("DELETE FROM accountlines");
1443 C4::Overdues::UpdateFine(
1445 issue_id => $issue_2->id(),
1446 itemnumber => $item_2->itemnumber,
1447 borrowernumber => $renewing_borrower_obj->borrowernumber,
1450 due => Koha::DateUtils::output_pref($datedue)
1454 LostItem( $item_2->itemnumber, 'test', 0 );
1456 my $item2 = Koha::Items->find($item_2->itemnumber);
1457 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1458 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1460 $total_due = $dbh->selectrow_array(
1461 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1462 undef, $renewing_borrower_obj->borrowernumber
1465 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1467 my $future = dt_from_string();
1468 $future->add( days => 7 );
1469 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1470 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1472 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1473 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1474 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1475 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1476 LostItem( $item_3->itemnumber, 'test', 0 );
1477 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1478 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1480 $accountline->description,
1481 sprintf( "%s %s %s",
1482 $item_3->biblio->title || '',
1483 $item_3->barcode || '',
1484 $item_3->itemcallnumber || '' ),
1485 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1489 t::lib::Mocks::mock_preference('UseRecalls', 1);
1490 Koha::CirculationRules->set_rules({
1491 categorycode => undef,
1492 branchcode => undef,
1495 recalls_allowed => 10,
1496 renewalsallowed => 5,
1499 my $recall_borrower = $builder->build_object({ class => 'Koha::Patrons' });
1500 my $recall_biblio = $builder->build_sample_biblio();
1501 my $recall_item1 = $builder->build_sample_item({ biblionumber => $recall_biblio->biblionumber });
1502 my $recall_item2 = $builder->build_sample_item({ biblionumber => $recall_biblio->biblionumber });
1504 my $recall_issue = AddIssue( $renewing_borrower_obj->unblessed, $recall_item1->barcode );
1506 # item-level and this item: renewal not allowed
1507 my $recall = Koha::Recall->new({
1508 biblio_id => $recall_item1->biblionumber,
1509 item_id => $recall_item1->itemnumber,
1510 patron_id => $recall_borrower->borrowernumber,
1511 pickup_library_id => $recall_borrower->branchcode,
1514 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1515 is( $error, 'recalled', 'Cannot renew item that has been recalled' );
1516 $recall->set_cancelled;
1518 # biblio-level requested recall: renewal not allowed
1519 $recall = Koha::Recall->new({
1520 biblio_id => $recall_item1->biblionumber,
1522 patron_id => $recall_borrower->borrowernumber,
1523 pickup_library_id => $recall_borrower->branchcode,
1526 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1527 is( $error, 'recalled', 'Cannot renew item if biblio is recalled and has no item allocated' );
1528 $recall->set_cancelled;
1530 # item-level and not this item: renewal allowed
1531 $recall = Koha::Recall->new({
1532 biblio_id => $recall_item2->biblionumber,
1533 item_id => $recall_item2->itemnumber,
1534 patron_id => $recall_borrower->borrowernumber,
1535 pickup_library_id => $recall_borrower->branchcode,
1538 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1539 is( $renewokay, 1, 'Can renew item if item-level recall on biblio is not on this item' );
1540 $recall->set_cancelled;
1542 # biblio-level waiting recall: renewal allowed
1543 $recall = Koha::Recall->new({
1544 biblio_id => $recall_item1->biblionumber,
1546 patron_id => $recall_borrower->borrowernumber,
1547 pickup_library_id => $recall_borrower->branchcode,
1550 $recall->set_waiting({ item => $recall_item1 });
1551 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1552 is( $renewokay, 1, 'Can renew item if biblio-level recall has already been allocated an item' );
1553 $recall->set_cancelled;
1556 subtest "GetUpcomingDueIssues" => sub {
1559 my $branch = $library2->{branchcode};
1561 #Create another record
1562 my $biblio2 = $builder->build_sample_biblio();
1565 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1566 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1567 my $item_3 = $builder->build_sample_item(
1569 biblionumber => $biblio2->biblionumber,
1577 my %a_borrower_data = (
1578 firstname => 'Fridolyn',
1579 surname => 'SOMERS',
1580 categorycode => $patron_category->{categorycode},
1581 branchcode => $branch,
1584 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1585 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1587 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1588 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1589 my $today = DateTime->today(time_zone => C4::Context->tz());
1591 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1592 my $datedue = dt_from_string( $issue->date_due() );
1593 my $issue_2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1594 my $datedue2 = dt_from_string( $issue->date_due() );
1598 # GetUpcomingDueIssues tests
1600 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1601 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1604 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1605 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1606 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1609 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1610 is ( scalar( @$upcoming_dues ), 1,
1611 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1614 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1616 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1618 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1619 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1621 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1622 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1624 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1625 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1627 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1628 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1630 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1631 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1633 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1634 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1638 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1639 my $branch = $library2->{branchcode};
1641 my $biblio = $builder->build_sample_biblio();
1644 my $item = $builder->build_sample_item(
1646 biblionumber => $biblio->biblionumber,
1653 my %a_borrower_data = (
1654 firstname => 'Kyle',
1656 categorycode => $patron_category->{categorycode},
1657 branchcode => $branch,
1660 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1662 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1663 my $issue = AddIssue( $borrower, $item->barcode );
1666 issue_id => $issue->id(),
1667 itemnumber => $item->itemnumber,
1668 borrowernumber => $borrowernumber,
1674 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1675 my $count = $hr->{count};
1677 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1680 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1682 my $biblio = $builder->build_sample_biblio();
1683 my $item_1 = $builder->build_sample_item(
1685 biblionumber => $biblio->biblionumber,
1686 library => $library2->{branchcode},
1689 my $item_2= $builder->build_sample_item(
1691 biblionumber => $biblio->biblionumber,
1692 library => $library2->{branchcode},
1693 itype => $item_1->effective_itemtype,
1697 Koha::CirculationRules->set_rules(
1699 categorycode => undef,
1700 itemtype => $item_1->effective_itemtype,
1701 branchcode => undef,
1703 reservesallowed => 25,
1704 holds_per_record => 25,
1706 lengthunit => 'days',
1707 renewalsallowed => 1,
1709 norenewalbefore => undef,
1719 my $borrower1 = Koha::Patron->new({
1720 firstname => 'Kyle',
1722 categorycode => $patron_category->{categorycode},
1723 branchcode => $library2->{branchcode},
1725 my $borrowernumber2 = Koha::Patron->new({
1726 firstname => 'Chelsea',
1728 categorycode => $patron_category->{categorycode},
1729 branchcode => $library2->{branchcode},
1730 })->store->borrowernumber;
1731 my $patron_category_2 = $builder->build(
1733 source => 'Category',
1735 category_type => 'P',
1737 BlockExpiredPatronOpacActions => -1, # Pick the pref value
1741 my $borrowernumber3 = Koha::Patron->new({
1742 firstname => 'Carnegie',
1744 categorycode => $patron_category_2->{categorycode},
1745 branchcode => $library2->{branchcode},
1746 })->store->borrowernumber;
1748 my $issue = AddIssue( $borrower1->unblessed, $item_1->barcode );
1750 my ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1751 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1755 branchcode => $library2->{branchcode},
1756 borrowernumber => $borrowernumber2,
1757 biblionumber => $biblio->biblionumber,
1762 Koha::CirculationRules->set_rules(
1764 categorycode => undef,
1765 itemtype => $item_1->effective_itemtype,
1766 branchcode => undef,
1772 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1773 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1774 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1776 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1777 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1778 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1780 Koha::CirculationRules->set_rules(
1782 categorycode => undef,
1783 itemtype => $item_1->effective_itemtype,
1784 branchcode => undef,
1790 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1791 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1792 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1794 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1795 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1796 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1800 branchcode => $library2->{branchcode},
1801 borrowernumber => $borrowernumber3,
1802 biblionumber => $biblio->biblionumber,
1807 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1808 is( $renewokay, 0, 'Verify the borrower cannot renew with 2 holds on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled and one other item on record' );
1810 my $item_3= $builder->build_sample_item(
1812 biblionumber => $biblio->biblionumber,
1813 library => $library2->{branchcode},
1814 itype => $item_1->effective_itemtype,
1818 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1819 is( $renewokay, 1, 'Verify the borrower cannot renew with 2 holds on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled and two other items on record' );
1821 Koha::CirculationRules->set_rules(
1823 categorycode => $patron_category_2->{categorycode},
1824 itemtype => $item_1->effective_itemtype,
1825 branchcode => undef,
1827 reservesallowed => 0,
1832 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1833 is( $renewokay, 0, 'Verify the borrower cannot renew with 2 holds on the record, but only one of those holds can be filled when AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled and two other items on record' );
1835 Koha::CirculationRules->set_rules(
1837 categorycode => $patron_category_2->{categorycode},
1838 itemtype => $item_1->effective_itemtype,
1839 branchcode => undef,
1841 reservesallowed => 25,
1846 # Setting item not checked out to be not for loan but holdable
1847 $item_2->notforloan(-1)->store;
1849 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1850 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' );
1852 my $mock_circ = Test::MockModule->new("C4::Circulation");
1853 $mock_circ->mock( CanItemBeReserved => sub {
1855 return { status => 'no' }
1858 $item_2->notforloan(0)->store;
1860 # Two items total, one item available, one issued, two holds on record
1863 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1864 } [], "CanItemBeReserved not called when there are more possible holds than available items";
1865 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1867 $item_3 = $builder->build_sample_item(
1869 biblionumber => $biblio->biblionumber,
1870 library => $library2->{branchcode},
1871 itype => $item_1->effective_itemtype,
1875 Koha::CirculationRules->set_rules(
1877 categorycode => undef,
1878 itemtype => $item_1->effective_itemtype,
1879 branchcode => undef,
1881 reservesallowed => 0,
1887 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1888 } ["Checked","Checked"], "CanItemBeReserved only called once per available item if it returns a negative result for all items for a borrower";
1889 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1894 # Don't allow renewing onsite checkout
1895 my $branch = $library->{branchcode};
1897 #Create another record
1898 my $biblio = $builder->build_sample_biblio();
1900 my $item = $builder->build_sample_item(
1902 biblionumber => $biblio->biblionumber,
1908 my $borrower = Koha::Patron->new({
1911 categorycode => $patron_category->{categorycode},
1912 branchcode => $branch,
1915 my $issue = AddIssue( $borrower->unblessed, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1916 my ( $renewed, $error ) = CanBookBeRenewed( $borrower, $issue );
1917 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1918 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1922 my $library = $builder->build({ source => 'Branch' });
1924 my $biblio = $builder->build_sample_biblio();
1926 my $item = $builder->build_sample_item(
1928 biblionumber => $biblio->biblionumber,
1929 library => $library->{branchcode},
1933 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1935 my $issue = AddIssue( $patron->unblessed, $item->barcode );
1938 issue_id => $issue->id,
1939 itemnumber => $item->itemnumber,
1940 borrowernumber => $patron->borrowernumber,
1947 issue_id => $issue->id,
1948 itemnumber => $item->itemnumber,
1949 borrowernumber => $patron->borrowernumber,
1954 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1957 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1960 my $homebranch = $builder->build( { source => 'Branch' } );
1961 my $holdingbranch = $builder->build( { source => 'Branch' } );
1962 my $otherbranch = $builder->build( { source => 'Branch' } );
1963 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1964 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1966 my $item = $builder->build_sample_item(
1968 homebranch => $homebranch->{branchcode},
1969 holdingbranch => $holdingbranch->{branchcode},
1972 Koha::CirculationRules->set_rules(
1974 categorycode => undef,
1975 itemtype => $item->effective_itemtype,
1976 branchcode => undef,
1978 reservesallowed => 25,
1980 lengthunit => 'days',
1981 renewalsallowed => 1,
1983 norenewalbefore => undef,
1992 set_userenv($holdingbranch);
1994 my $issue = AddIssue( $patron_1->unblessed, $item->barcode );
1995 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1997 my ( $error, $question, $alerts );
1999 # AllowReturnToBranch == anywhere
2000 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2001 ## Test that unknown barcodes don't generate internal server errors
2002 set_userenv($homebranch);
2003 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
2004 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
2005 ## Can be issued from homebranch
2006 set_userenv($homebranch);
2007 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2008 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2009 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2010 ## Can be issued from holdingbranch
2011 set_userenv($holdingbranch);
2012 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2013 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2014 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2015 ## Can be issued from another branch
2016 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2017 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2018 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2020 # AllowReturnToBranch == holdingbranch
2021 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2022 ## Cannot be issued from homebranch
2023 set_userenv($homebranch);
2024 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2025 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2026 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2027 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
2028 ## Can be issued from holdinbranch
2029 set_userenv($holdingbranch);
2030 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2031 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2032 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2033 ## Cannot be issued from another branch
2034 set_userenv($otherbranch);
2035 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2036 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2037 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2038 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
2040 # AllowReturnToBranch == homebranch
2041 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2042 ## Can be issued from holdinbranch
2043 set_userenv($homebranch);
2044 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2045 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2046 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2047 ## Cannot be issued from holdinbranch
2048 set_userenv($holdingbranch);
2049 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2050 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2051 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2052 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2053 ## Cannot be issued from holdinbranch
2054 set_userenv($otherbranch);
2055 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2056 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2057 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2058 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2060 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2063 subtest 'AddIssue & AllowReturnToBranch' => sub {
2066 my $homebranch = $builder->build( { source => 'Branch' } );
2067 my $holdingbranch = $builder->build( { source => 'Branch' } );
2068 my $otherbranch = $builder->build( { source => 'Branch' } );
2069 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2070 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2072 my $item = $builder->build_sample_item(
2074 homebranch => $homebranch->{branchcode},
2075 holdingbranch => $holdingbranch->{branchcode},
2079 set_userenv($holdingbranch);
2081 my $ref_issue = 'Koha::Checkout';
2082 my $issue = AddIssue( $patron_1, $item->barcode );
2084 my ( $error, $question, $alerts );
2086 # AllowReturnToBranch == homebranch
2087 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2088 ## Can be issued from homebranch
2089 set_userenv($homebranch);
2090 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
2091 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2092 ## Can be issued from holdinbranch
2093 set_userenv($holdingbranch);
2094 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
2095 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2096 ## Can be issued from another branch
2097 set_userenv($otherbranch);
2098 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
2099 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2101 # AllowReturnToBranch == holdinbranch
2102 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2103 ## Cannot be issued from homebranch
2104 set_userenv($homebranch);
2105 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
2106 ## Can be issued from holdingbranch
2107 set_userenv($holdingbranch);
2108 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
2109 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2110 ## Cannot be issued from another branch
2111 set_userenv($otherbranch);
2112 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
2114 # AllowReturnToBranch == homebranch
2115 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2116 ## Can be issued from homebranch
2117 set_userenv($homebranch);
2118 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
2119 AddIssue( $patron_1, $item->barcode ); # Re-issue to patron 1
2120 ## Cannot be issued from holdinbranch
2121 set_userenv($holdingbranch);
2122 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
2123 ## Cannot be issued from another branch
2124 set_userenv($otherbranch);
2125 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
2126 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2129 subtest 'AddIssue | recalls' => sub {
2132 t::lib::Mocks::mock_preference("UseRecalls", 1);
2133 t::lib::Mocks::mock_preference("item-level_itypes", 1);
2134 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2135 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2136 my $item = $builder->build_sample_item;
2137 Koha::CirculationRules->set_rules({
2138 branchcode => undef,
2140 categorycode => undef,
2142 recalls_allowed => 10,
2146 # checking out item that they have recalled
2147 my $recall1 = Koha::Recall->new(
2148 { patron_id => $patron1->borrowernumber,
2149 biblio_id => $item->biblionumber,
2150 item_id => $item->itemnumber,
2152 pickup_library_id => $patron1->branchcode,
2155 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall1->id } );
2156 $recall1 = Koha::Recalls->find( $recall1->id );
2157 is( $recall1->fulfilled, 1, 'Recall was fulfilled when patron checked out item' );
2158 AddReturn( $item->barcode, $item->homebranch );
2160 # this item is has a recall request. cancel recall
2161 my $recall2 = Koha::Recall->new(
2162 { patron_id => $patron2->borrowernumber,
2163 biblio_id => $item->biblionumber,
2164 item_id => $item->itemnumber,
2166 pickup_library_id => $patron2->branchcode,
2169 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall2->id, cancel_recall => 'cancel' } );
2170 $recall2 = Koha::Recalls->find( $recall2->id );
2171 is( $recall2->cancelled, 1, 'Recall was cancelled when patron checked out item' );
2172 AddReturn( $item->barcode, $item->homebranch );
2174 # this item is waiting to fulfill a recall. revert recall
2175 my $recall3 = Koha::Recall->new(
2176 { patron_id => $patron2->borrowernumber,
2177 biblio_id => $item->biblionumber,
2178 item_id => $item->itemnumber,
2180 pickup_library_id => $patron2->branchcode,
2183 $recall3->set_waiting;
2184 AddIssue( $patron1->unblessed, $item->barcode, undef, undef, undef, undef, { recall_id => $recall3->id, cancel_recall => 'revert' } );
2185 $recall3 = Koha::Recalls->find( $recall3->id );
2186 is( $recall3->requested, 1, 'Recall was reverted from waiting when patron checked out item' );
2187 AddReturn( $item->barcode, $item->homebranch );
2190 subtest 'AddIssue & illrequests.due_date' => sub {
2193 t::lib::Mocks::mock_preference( 'ILLModule', 1 );
2194 my $library = $builder->build( { source => 'Branch' } );
2195 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2196 my $item = $builder->build_sample_item();
2198 set_userenv($library);
2200 my $custom_date_due = '9999-12-18 12:34:56';
2201 my $expected_date_due = '9999-12-18 23:59:00';
2202 my $illrequest = Koha::Illrequest->new({
2203 borrowernumber => $patron->borrowernumber,
2204 biblio_id => $item->biblionumber,
2205 branchcode => $library->{'branchcode'},
2206 due_date => $custom_date_due,
2209 my $issue = AddIssue( $patron->unblessed, $item->barcode );
2210 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2212 $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2213 $item = $builder->build_sample_item();
2214 $custom_date_due = '9999-12-19';
2215 $expected_date_due = '9999-12-19 23:59:00';
2216 $illrequest = Koha::Illrequest->new({
2217 borrowernumber => $patron->borrowernumber,
2218 biblio_id => $item->biblionumber,
2219 branchcode => $library->{'branchcode'},
2220 due_date => $custom_date_due,
2223 $issue = AddIssue( $patron->unblessed, $item->barcode );
2224 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2227 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
2230 my $library = $builder->build( { source => 'Branch' } );
2231 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2232 my $item_1 = $builder->build_sample_item(
2234 library => $library->{branchcode},
2237 my $item_2 = $builder->build_sample_item(
2239 library => $library->{branchcode},
2242 Koha::CirculationRules->set_rules(
2244 categorycode => undef,
2246 branchcode => $library->{branchcode},
2248 reservesallowed => 25,
2250 lengthunit => 'days',
2251 renewalsallowed => 1,
2253 norenewalbefore => undef,
2262 my ( $error, $question, $alerts );
2264 # Patron cannot issue item_1, they have overdues
2265 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
2266 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, $yesterday ); # Add an overdue
2268 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
2269 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2270 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
2271 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
2273 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
2274 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2275 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2276 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
2278 # Patron cannot issue item_1, they are debarred
2279 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
2280 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
2281 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2282 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2283 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
2285 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
2286 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2287 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2288 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
2291 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
2294 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2295 my $patron_category_x = $builder->build_object(
2297 class => 'Koha::Patron::Categories',
2298 value => { category_type => 'X' }
2301 my $patron = $builder->build_object(
2303 class => 'Koha::Patrons',
2305 categorycode => $patron_category_x->categorycode,
2306 gonenoaddress => undef,
2313 my $item_1 = $builder->build_sample_item(
2315 library => $library->{branchcode},
2319 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
2320 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
2322 my $stat = Koha::Statistics->search( { itemnumber => $item_1->itemnumber } )->next;
2323 is( $stat->branch, C4::Context->userenv->{'branch'}, 'Recorded a branch' );
2324 is( $stat->type, 'localuse', 'Recorded type as localuse' );
2325 is( $stat->itemnumber, $item_1->itemnumber, 'Recorded an itemnumber' );
2326 is( $stat->itemtype, $item_1->effective_itemtype, 'Recorded an itemtype' );
2327 is( $stat->borrowernumber, $patron->borrowernumber, 'Recorded a borrower number' );
2328 is( $stat->ccode, $item_1->ccode, 'Recorded a collection code' );
2329 is( $stat->categorycode, $patron->categorycode, 'Recorded a categorycode' );
2330 is( $stat->location, $item_1->location, 'Recorded a location' );
2332 # TODO There are other tests to provide here
2335 subtest 'MultipleReserves' => sub {
2338 my $biblio = $builder->build_sample_biblio();
2340 my $branch = $library2->{branchcode};
2342 my $item_1 = $builder->build_sample_item(
2344 biblionumber => $biblio->biblionumber,
2346 replacementprice => 12.00,
2351 my $item_2 = $builder->build_sample_item(
2353 biblionumber => $biblio->biblionumber,
2355 replacementprice => 12.00,
2362 my $resdate = undef;
2363 my $expdate = undef;
2365 my $checkitem = undef;
2368 my %renewing_borrower_data = (
2369 firstname => 'John',
2370 surname => 'Renewal',
2371 categorycode => $patron_category->{categorycode},
2372 branchcode => $branch,
2374 my $patron = Koha::Patron->new(\%renewing_borrower_data)->store;
2375 my $issue = AddIssue( $patron->unblessed, $item_1->barcode);
2376 my $datedue = dt_from_string( $issue->date_due() );
2377 is (defined $issue->date_due(), 1, "item 1 checked out");
2378 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
2380 my %reserving_borrower_data1 = (
2381 firstname => 'Katrin',
2382 surname => 'Reservation',
2383 categorycode => $patron_category->{categorycode},
2384 branchcode => $branch,
2386 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
2389 branchcode => $branch,
2390 borrowernumber => $reserving_borrowernumber1,
2391 biblionumber => $biblio->biblionumber,
2392 priority => $priority,
2393 reservation_date => $resdate,
2394 expiration_date => $expdate,
2396 itemnumber => $checkitem,
2401 my %reserving_borrower_data2 = (
2402 firstname => 'Kirk',
2403 surname => 'Reservation',
2404 categorycode => $patron_category->{categorycode},
2405 branchcode => $branch,
2407 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
2410 branchcode => $branch,
2411 borrowernumber => $reserving_borrowernumber2,
2412 biblionumber => $biblio->biblionumber,
2413 priority => $priority,
2414 reservation_date => $resdate,
2415 expiration_date => $expdate,
2417 itemnumber => $checkitem,
2423 my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue, 1);
2424 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2427 my $item_3 = $builder->build_sample_item(
2429 biblionumber => $biblio->biblionumber,
2431 replacementprice => 12.00,
2437 my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue, 1);
2438 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2442 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2445 my $library = $builder->build( { source => 'Branch' } );
2446 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2448 my $biblionumber = $builder->build_sample_biblio(
2450 branchcode => $library->{branchcode},
2453 my $item_1 = $builder->build_sample_item(
2455 biblionumber => $biblionumber,
2456 library => $library->{branchcode},
2460 my $item_2 = $builder->build_sample_item(
2462 biblionumber => $biblionumber,
2463 library => $library->{branchcode},
2467 Koha::CirculationRules->set_rules(
2469 categorycode => undef,
2471 branchcode => $library->{branchcode},
2473 reservesallowed => 25,
2475 lengthunit => 'days',
2476 renewalsallowed => 1,
2478 norenewalbefore => undef,
2487 my ( $error, $question, $alerts );
2488 my $issue = AddIssue( $patron->unblessed, $item_1->barcode, dt_from_string->add( days => 1 ) );
2490 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2491 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2493 { error => $error, alerts => $alerts },
2494 { error => {}, alerts => {} },
2495 'No error or alert should be raised'
2497 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2499 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2500 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2502 { error => $error, question => $question, alerts => $alerts },
2503 { error => {}, question => {}, alerts => {} },
2504 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2507 # Add a subscription
2508 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2510 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2511 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2513 { error => $error, question => $question, alerts => $alerts },
2514 { error => {}, question => {}, alerts => {} },
2515 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2518 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2519 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2521 { error => $error, question => $question, alerts => $alerts },
2522 { error => {}, question => {}, alerts => {} },
2523 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2527 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2530 my $library = $builder->build( { source => 'Branch' } );
2531 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2534 my $biblionumber = $builder->build_sample_biblio(
2536 branchcode => $library->{branchcode},
2539 my $item_1 = $builder->build_sample_item(
2541 biblionumber => $biblionumber,
2542 library => $library->{branchcode},
2545 my $item_2 = $builder->build_sample_item(
2547 biblionumber => $biblionumber,
2548 library => $library->{branchcode},
2552 # And the circulation rule
2553 Koha::CirculationRules->search->delete;
2554 Koha::CirculationRules->set_rules(
2556 categorycode => undef,
2558 branchcode => undef,
2561 firstremind => 1, # 1 day of grace
2562 finedays => 2, # 2 days of fine per day of overdue
2563 lengthunit => 'days',
2568 # Patron cannot issue item_1, they have overdues
2569 my $now = dt_from_string;
2570 my $five_days_ago = $now->clone->subtract( days => 5 );
2571 my $ten_days_ago = $now->clone->subtract( days => 10 );
2572 AddIssue( $patron->unblessed, $item_1->barcode, $five_days_ago ); # Add an overdue
2573 AddIssue( $patron->unblessed, $item_2->barcode, $ten_days_ago )
2574 ; # Add another overdue
2576 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2577 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2578 my $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2579 is( $suspensions->count, 1, "Suspension added" );
2580 my $THE_suspension = $suspensions->next;
2582 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2583 # Same for the others
2584 my $expected_expiration = output_pref(
2586 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2587 dateformat => 'sql',
2591 is( $THE_suspension->expiration, $expected_expiration, "Suspesion expiration set" );
2593 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2594 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2595 is( $suspensions->count, 1, "Only one suspension" );
2596 $THE_suspension = $suspensions->next;
2598 $expected_expiration = output_pref(
2600 dt => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2601 dateformat => 'sql',
2605 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2607 Koha::Patron::Debarments::DelUniqueDebarment(
2608 { borrowernumber => $patron->borrowernumber, type => 'SUSPENSION' } );
2610 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2611 AddIssue( $patron->unblessed, $item_1->barcode, $five_days_ago ); # Add an overdue
2612 AddIssue( $patron->unblessed, $item_2->barcode, $ten_days_ago )
2613 ; # Add another overdue
2614 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2615 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2616 is( $suspensions->count, 1, "Only one suspension" );
2617 $THE_suspension = $suspensions->next;
2619 $expected_expiration = output_pref(
2621 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2622 dateformat => 'sql',
2626 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2628 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2629 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2630 is( $suspensions->count, 1, "Only one suspension" );
2631 $THE_suspension = $suspensions->next;
2633 $expected_expiration = output_pref(
2635 dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2636 dateformat => 'sql',
2640 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2643 subtest 'AddReturn + suspension_chargeperiod' => sub {
2646 my $library = $builder->build( { source => 'Branch' } );
2647 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2649 my $biblionumber = $builder->build_sample_biblio(
2651 branchcode => $library->{branchcode},
2654 my $item_1 = $builder->build_sample_item(
2656 biblionumber => $biblionumber,
2657 library => $library->{branchcode},
2661 # And the issuing rule
2662 Koha::CirculationRules->search->delete;
2663 Koha::CirculationRules->set_rules(
2665 categorycode => '*',
2670 firstremind => 0, # 0 day of grace
2671 finedays => 2, # 2 days of fine per day of overdue
2672 suspension_chargeperiod => 1,
2673 lengthunit => 'days',
2678 my $now = dt_from_string;
2679 my $five_days_ago = $now->clone->subtract( days => 5 );
2680 # We want to charge 2 days every day, without grace
2681 # With 5 days of overdue: 5 * Z
2682 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2683 test_debarment_on_checkout(
2686 library => $library,
2688 due_date => $five_days_ago,
2689 expiration_date => $expected_expiration,
2693 # Same with undef firstremind
2694 Koha::CirculationRules->search->delete;
2695 Koha::CirculationRules->set_rules(
2697 categorycode => '*',
2702 firstremind => undef, # 0 day of grace
2703 finedays => 2, # 2 days of fine per day of overdue
2704 suspension_chargeperiod => 1,
2705 lengthunit => 'days',
2710 my $now = dt_from_string;
2711 my $five_days_ago = $now->clone->subtract( days => 5 );
2712 # We want to charge 2 days every day, without grace
2713 # With 5 days of overdue: 5 * Z
2714 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2715 test_debarment_on_checkout(
2718 library => $library,
2720 due_date => $five_days_ago,
2721 expiration_date => $expected_expiration,
2725 # We want to charge 2 days every 2 days, without grace
2726 # With 5 days of overdue: (5 * 2) / 2
2727 Koha::CirculationRules->set_rule(
2729 categorycode => undef,
2730 branchcode => undef,
2732 rule_name => 'suspension_chargeperiod',
2737 $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2738 test_debarment_on_checkout(
2741 library => $library,
2743 due_date => $five_days_ago,
2744 expiration_date => $expected_expiration,
2748 # We want to charge 2 days every 3 days, with 1 day of grace
2749 # With 5 days of overdue: ((5-1) / 3 ) * 2
2750 Koha::CirculationRules->set_rules(
2752 categorycode => undef,
2753 branchcode => undef,
2756 suspension_chargeperiod => 3,
2761 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2762 test_debarment_on_checkout(
2765 library => $library,
2767 due_date => $five_days_ago,
2768 expiration_date => $expected_expiration,
2772 # Use finesCalendar to know if holiday must be skipped to calculate the due date
2773 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2774 Koha::CirculationRules->set_rules(
2776 categorycode => undef,
2777 branchcode => undef,
2781 suspension_chargeperiod => 1,
2786 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2787 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2789 # Adding a holiday 2 days ago
2790 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2791 my $two_days_ago = $now->clone->subtract( days => 2 );
2792 $calendar->insert_single_holiday(
2793 day => $two_days_ago->day,
2794 month => $two_days_ago->month,
2795 year => $two_days_ago->year,
2796 title => 'holidayTest-2d',
2797 description => 'holidayDesc 2 days ago'
2799 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2800 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2801 test_debarment_on_checkout(
2804 library => $library,
2806 due_date => $five_days_ago,
2807 expiration_date => $expected_expiration,
2811 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2812 my $two_days_ahead = $now->clone->add( days => 2 );
2813 $calendar->insert_single_holiday(
2814 day => $two_days_ahead->day,
2815 month => $two_days_ahead->month,
2816 year => $two_days_ahead->year,
2817 title => 'holidayTest+2d',
2818 description => 'holidayDesc 2 days ahead'
2821 # Same as above, but we should skip D+2
2822 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2823 test_debarment_on_checkout(
2826 library => $library,
2828 due_date => $five_days_ago,
2829 expiration_date => $expected_expiration,
2833 # Adding another holiday, day of expiration date
2834 my $expected_expiration_dt = dt_from_string($expected_expiration);
2835 $calendar->insert_single_holiday(
2836 day => $expected_expiration_dt->day,
2837 month => $expected_expiration_dt->month,
2838 year => $expected_expiration_dt->year,
2839 title => 'holidayTest_exp',
2840 description => 'holidayDesc on expiration date'
2842 # Expiration date will be the day after
2843 test_debarment_on_checkout(
2846 library => $library,
2848 due_date => $five_days_ago,
2849 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2853 test_debarment_on_checkout(
2856 library => $library,
2858 return_date => $now->clone->add(days => 5),
2859 expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2863 test_debarment_on_checkout(
2866 library => $library,
2868 due_date => $now->clone->add(days => 1),
2869 return_date => $now->clone->add(days => 5),
2870 expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2874 Koha::CirculationRules->search->delete;
2875 Koha::CirculationRules->set_rules(
2877 categorycode => undef,
2879 branchcode => undef,
2882 lengthunit => 'days',
2887 Koha::Patron::Debarments::AddDebarment(
2889 borrowernumber => $patron->borrowernumber,
2890 expiration => '9999-12-31',
2895 AddIssue( $patron->unblessed, $item_1->barcode, $now->clone->subtract( days => 1 ) );
2896 my ( undef, $message ) = AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2897 is( $message->{WasReturned} && exists $message->{ForeverDebarred}, 1, 'Forever debarred message for Addreturn when overdue');
2899 Koha::Patron::Debarments::DelUniqueDebarment(
2901 borrowernumber => $patron->borrowernumber,
2905 Koha::Patron::Debarments::AddDebarment(
2907 borrowernumber => $patron->borrowernumber,
2908 expiration => $now->clone->add( days => 10 ),
2913 AddIssue( $patron->unblessed, $item_1->barcode, $now->clone->subtract( days => 1 ) );
2914 (undef, $message) = AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2915 is( $message->{WasReturned} && exists $message->{PrevDebarred}, 1, 'Previously debarred message for Addreturn when overdue');
2918 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2921 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2922 my $patron1 = $builder->build_object(
2924 class => 'Koha::Patrons',
2926 branchcode => $library->branchcode,
2927 categorycode => $patron_category->{categorycode}
2931 my $patron2 = $builder->build_object(
2933 class => 'Koha::Patrons',
2935 branchcode => $library->branchcode,
2936 categorycode => $patron_category->{categorycode}
2941 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2943 my $item = $builder->build_sample_item(
2945 library => $library->branchcode,
2949 my ( $error, $question, $alerts );
2950 my $issue = AddIssue( $patron1->unblessed, $item->barcode );
2952 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2953 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2954 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' );
2956 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2957 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2958 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' );
2960 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2964 subtest 'AddReturn | is_overdue' => sub {
2967 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2968 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2969 t::lib::Mocks::mock_preference('finesMode', 'production');
2970 t::lib::Mocks::mock_preference('MaxFine', '100');
2972 my $library = $builder->build( { source => 'Branch' } );
2973 my $patron = $builder->build_object(
2975 class => 'Koha::Patrons',
2976 value => { categorycode => $patron_category->{categorycode} }
2979 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
2980 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2982 my $item = $builder->build_sample_item(
2984 library => $library->{branchcode},
2985 replacementprice => 7
2989 Koha::CirculationRules->search->delete;
2990 Koha::CirculationRules->set_rules(
2992 categorycode => undef,
2994 branchcode => undef,
2997 lengthunit => 'days',
2998 fine => 1, # Charge 1 every day of overdue
3004 my $now = dt_from_string;
3005 my $one_day_ago = $now->clone->subtract( days => 1 );
3006 my $two_days_ago = $now->clone->subtract( days => 2 );
3007 my $five_days_ago = $now->clone->subtract( days => 5 );
3008 my $ten_days_ago = $now->clone->subtract( days => 10 );
3010 # No return date specified, today will be used => 10 days overdue charged
3011 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
3012 AddReturn( $item->barcode, $library->{branchcode} );
3013 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
3014 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3016 # specify return date 5 days before => no overdue charged
3017 AddIssue( $patron->unblessed, $item->barcode, $five_days_ago ); # date due was 5d ago
3018 AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
3019 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
3020 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3022 # specify return date 5 days later => 5 days overdue charged
3023 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
3024 AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
3025 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
3026 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3028 # specify return date 5 days later, specify exemptfine => no overdue charge
3029 AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
3030 AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago );
3031 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
3032 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3034 subtest 'bug 22877 | Lost item return' => sub {
3038 my $issue = AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago ); # date due was 10d ago
3040 # Fake fines cronjob on this checkout
3042 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3043 $ten_days_ago, $now );
3046 issue_id => $issue->issue_id,
3047 itemnumber => $item->itemnumber,
3048 borrowernumber => $patron->borrowernumber,
3050 due => output_pref($ten_days_ago)
3053 is( int( $patron->account->balance() ),
3054 10, "Overdue fine of 10 days overdue" );
3056 # Fake longoverdue with charge and not marking returned
3057 LostItem( $item->itemnumber, 'cronjob', 0 );
3058 is( int( $patron->account->balance() ),
3059 17, "Lost fine of 7 plus 10 days overdue" );
3061 # Now we return it today
3062 AddReturn( $item->barcode, $library->{branchcode} );
3063 is( int( $patron->account->balance() ),
3064 17, "Should have a single 10 days overdue fine and lost charge" );
3067 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3070 subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
3074 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3076 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
3078 # Fake fines cronjob on this checkout
3080 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3081 $one_day_ago, $now );
3084 issue_id => $issue->issue_id,
3085 itemnumber => $item->itemnumber,
3086 borrowernumber => $patron->borrowernumber,
3088 due => output_pref($one_day_ago)
3091 is( int( $patron->account->balance() ),
3092 1, "Overdue fine of 1 day overdue" );
3094 # Backdated return (dropbox mode example - charge should be removed)
3095 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3096 is( int( $patron->account->balance() ),
3097 0, "Overdue fine should be annulled" );
3098 my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3099 is( $lines->count, 0, "Overdue fine accountline has been removed");
3101 $issue = AddIssue( $patron->unblessed, $item->barcode, $two_days_ago ); # date due was 2d ago
3103 # Fake fines cronjob on this checkout
3105 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3106 $two_days_ago, $now );
3109 issue_id => $issue->issue_id,
3110 itemnumber => $item->itemnumber,
3111 borrowernumber => $patron->borrowernumber,
3113 due => output_pref($one_day_ago)
3116 is( int( $patron->account->balance() ),
3117 2, "Overdue fine of 2 days overdue" );
3119 # Payment made against fine
3120 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3121 my $debit = $lines->next;
3122 my $credit = $patron->account->add_credit(
3126 interface => 'test',
3129 $credit->apply( { debits => [$debit] } );
3131 is( int( $patron->account->balance() ),
3132 0, "Overdue fine should be paid off" );
3133 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3134 is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
3135 my $line = $lines->next;
3136 is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
3137 is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
3139 # Backdated return (dropbox mode example - charge should be removed)
3140 AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
3141 is( int( $patron->account->balance() ),
3142 -1, "Refund credit has been applied" );
3143 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
3144 is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
3146 $line = $lines->next;
3147 is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
3148 is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
3149 is($line->status,'RETURNED', "Overdue fine is fixed");
3150 $line = $lines->next;
3151 is($line->amount+0,-2, "Original payment amount remains as 2");
3152 is($line->amountoutstanding+0,0, "Original payment remains applied");
3153 $line = $lines->next;
3154 is($line->amount+0,-1, "Refund amount correctly set to 1");
3155 is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
3158 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3161 subtest 'bug 25417 | backdated return + exemptfine' => sub {
3165 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3167 my $issue = AddIssue( $patron->unblessed, $item->barcode, $one_day_ago ); # date due was 1d ago
3169 # Fake fines cronjob on this checkout
3171 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3172 $one_day_ago, $now );
3175 issue_id => $issue->issue_id,
3176 itemnumber => $item->itemnumber,
3177 borrowernumber => $patron->borrowernumber,
3179 due => output_pref($one_day_ago)
3182 is( int( $patron->account->balance() ),
3183 1, "Overdue fine of 1 day overdue" );
3185 # Backdated return (dropbox mode example - charge should no longer exist)
3186 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3187 is( int( $patron->account->balance() ),
3188 0, "Overdue fine should be annulled" );
3191 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3194 subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
3197 t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
3199 my $due_date = dt_from_string;
3200 my $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
3205 issue_id => $issue->issue_id,
3206 itemnumber => $item->itemnumber,
3207 borrowernumber => $patron->borrowernumber,
3209 due => output_pref($due_date)
3212 is( $patron->account->balance(),
3213 0.25, 'Overdue fine of $0.25 recorded' );
3215 # Backdate return to exact due date and time
3216 my ( undef, $message ) =
3217 AddReturn( $item->barcode, $library->{branchcode},
3221 Koha::Account::Lines->find( { issue_id => $issue->id } );
3222 ok( !$accountline, 'accountline removed as expected' );
3225 $issue = AddIssue( $patron->unblessed, $item->barcode, $due_date );
3230 issue_id => $issue->issue_id,
3231 itemnumber => $item->itemnumber,
3232 borrowernumber => $patron->borrowernumber,
3234 due => output_pref($due_date)
3237 is( $patron->account->balance(),
3238 0.25, 'Overdue fine of $0.25 recorded' );
3240 # Partial pay accruing fine
3241 my $lines = Koha::Account::Lines->search(
3243 borrowernumber => $patron->borrowernumber,
3244 issue_id => $issue->id
3247 my $debit = $lines->next;
3248 my $credit = $patron->account->add_credit(
3252 interface => 'test',
3255 $credit->apply( { debits => [$debit] } );
3257 is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
3259 # Backdate return to exact due date and time
3260 ( undef, $message ) =
3261 AddReturn( $item->barcode, $library->{branchcode},
3264 $lines = Koha::Account::Lines->search(
3266 borrowernumber => $patron->borrowernumber,
3267 issue_id => $issue->id
3270 $accountline = $lines->next;
3271 is( $accountline->amountoutstanding + 0,
3272 0, 'Partially paid fee amount outstanding was reduced to 0' );
3273 is( $accountline->amount + 0,
3274 0, 'Partially paid fee amount was reduced to 0' );
3275 is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
3278 Koha::Account::Lines->search(
3279 { borrowernumber => $patron->borrowernumber } )->delete;
3282 subtest 'enh 23091 | Lost item return policies' => sub {
3285 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3287 my $branchcode_false =
3288 $builder->build( { source => 'Branch' } )->{branchcode};
3289 my $specific_rule_false = $builder->build(
3291 source => 'CirculationRule',
3293 branchcode => $branchcode_false,
3294 categorycode => undef,
3296 rule_name => 'lostreturn',
3301 my $branchcode_refund =
3302 $builder->build( { source => 'Branch' } )->{branchcode};
3303 my $specific_rule_refund = $builder->build(
3305 source => 'CirculationRule',
3307 branchcode => $branchcode_refund,
3308 categorycode => undef,
3310 rule_name => 'lostreturn',
3311 rule_value => 'refund'
3315 my $branchcode_restore =
3316 $builder->build( { source => 'Branch' } )->{branchcode};
3317 my $specific_rule_restore = $builder->build(
3319 source => 'CirculationRule',
3321 branchcode => $branchcode_restore,
3322 categorycode => undef,
3324 rule_name => 'lostreturn',
3325 rule_value => 'restore'
3329 my $branchcode_charge =
3330 $builder->build( { source => 'Branch' } )->{branchcode};
3331 my $specific_rule_charge = $builder->build(
3333 source => 'CirculationRule',
3335 branchcode => $branchcode_charge,
3336 categorycode => undef,
3338 rule_name => 'lostreturn',
3339 rule_value => 'charge'
3344 my $branchcode_refund_unpaid =
3345 $builder->build( { source => 'Branch' } )->{branchcode};
3346 my $specific_rule_refund_unpaid = $builder->build(
3348 source => 'CirculationRule',
3350 branchcode => $branchcode_refund_unpaid,
3351 categorycode => undef,
3353 rule_name => 'lostreturn',
3354 rule_value => 'refund_unpaid'
3359 my $replacement_amount = 99.00;
3360 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
3361 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
3362 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
3363 t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 );
3364 t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
3366 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
3369 subtest 'lostreturn | refund_unpaid' => sub {
3372 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund_unpaid });
3374 my $item = $builder->build_sample_item(
3376 replacementprice => $replacement_amount
3381 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode );
3384 $item->itemlost(3)->store;
3385 C4::Circulation::LostItem( $item->itemnumber, 1 );
3387 my $lost_fee_lines = Koha::Account::Lines->search(
3389 borrowernumber => $patron->id,
3390 itemnumber => $item->itemnumber,
3391 debit_type_code => 'LOST'
3394 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3395 my $lost_fee_line = $lost_fee_lines->next;
3396 is( int($lost_fee_line->amount),
3397 $replacement_amount, 'The right LOST amount is generated' );
3398 is( int($lost_fee_line->amountoutstanding),
3399 $replacement_amount,
3400 'The right LOST amountoutstanding is generated' );
3401 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3404 int($patron->account->balance),
3405 $replacement_amount ,
3406 "Account balance equals the replacement amount after being charged lost fee when no payments has been made"
3409 # Return lost item without any payments having been made
3410 my ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3412 $lost_fee_line->discard_changes;
3414 is( int($lost_fee_line->amount), $replacement_amount, 'The LOST amount is left intact' );
3415 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero' );
3416 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set' );
3418 int($patron->account->balance),
3420 'Account balance should be zero after returning item with lost fee when no payments has been made'
3423 # Create a second item
3424 $item = $builder->build_sample_item(
3426 replacementprice => $replacement_amount
3431 $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode );
3434 $item->itemlost(3)->store;
3435 C4::Circulation::LostItem( $item->itemnumber, 1 );
3437 $lost_fee_lines = Koha::Account::Lines->search(
3439 borrowernumber => $patron->id,
3440 itemnumber => $item->itemnumber,
3441 debit_type_code => 'LOST'
3444 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3445 $lost_fee_line = $lost_fee_lines->next;
3447 # Make partial payment
3448 $patron->account->payin_amount({
3450 interface => 'intranet',
3451 payment_type => 'CASH',
3452 user_id => $patron->borrowernumber,
3454 debits => [$lost_fee_line]
3457 $lost_fee_line->discard_changes;
3459 is( int($lost_fee_line->amountoutstanding),
3461 'The LOST amountoutstanding is the expected amount after partial payment of lost fee'
3465 int($patron->account->balance),
3467 'Account balance is the expected amount after partial payment of lost fee'
3470 # Return lost item with partial payment having been made
3471 ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3473 $lost_fee_line->discard_changes;
3475 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero after returning lost item with partial payment' );
3476 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set for lost item with partial payment' );
3478 int($patron->account->balance),
3480 'Account balance should be zero after returning item with lost fee when partial payment has been made'
3483 # Create a third item
3484 $item = $builder->build_sample_item(
3486 replacementprice => $replacement_amount
3491 $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode );
3494 $item->itemlost(3)->store;
3495 C4::Circulation::LostItem( $item->itemnumber, 1 );
3497 $lost_fee_lines = Koha::Account::Lines->search(
3499 borrowernumber => $patron->id,
3500 itemnumber => $item->itemnumber,
3501 debit_type_code => 'LOST'
3504 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3505 $lost_fee_line = $lost_fee_lines->next;
3508 $patron->account->payin_amount({
3510 interface => 'intranet',
3511 payment_type => 'CASH',
3512 user_id => $patron->borrowernumber,
3513 amount => $replacement_amount,
3514 debits => [$lost_fee_line]
3517 $lost_fee_line->discard_changes;
3519 is( int($lost_fee_line->amountoutstanding),
3521 'The LOST amountoutstanding is the expected amount after partial payment of lost fee'
3525 int($patron->account->balance),
3527 'Account balance is the expected amount after partial payment of lost fee'
3530 # Return lost item with partial payment having been made
3531 ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3533 $lost_fee_line->discard_changes;
3535 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero after returning lost item with full payment' );
3536 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set for lost item with partial payment' );
3538 int($patron->account->balance),
3540 'Account balance should be zero after returning item with lost fee when full payment has been made'
3544 subtest 'lostreturn | false' => sub {
3547 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
3549 my $item = $builder->build_sample_item(
3551 replacementprice => $replacement_amount
3556 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3558 # Fake fines cronjob on this checkout
3560 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3561 $ten_days_ago, $now );
3564 issue_id => $issue->issue_id,
3565 itemnumber => $item->itemnumber,
3566 borrowernumber => $patron->borrowernumber,
3568 due => output_pref($ten_days_ago)
3571 my $overdue_fees = Koha::Account::Lines->search(
3573 borrowernumber => $patron->id,
3574 itemnumber => $item->itemnumber,
3575 debit_type_code => 'OVERDUE'
3578 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3579 my $overdue_fee = $overdue_fees->next;
3580 is( $overdue_fee->amount + 0,
3581 10, 'The right OVERDUE amount is generated' );
3582 is( $overdue_fee->amountoutstanding + 0,
3584 'The right OVERDUE amountoutstanding is generated' );
3586 # Simulate item marked as lost
3587 $item->itemlost(3)->store;
3588 C4::Circulation::LostItem( $item->itemnumber, 1 );
3590 my $lost_fee_lines = Koha::Account::Lines->search(
3592 borrowernumber => $patron->id,
3593 itemnumber => $item->itemnumber,
3594 debit_type_code => 'LOST'
3597 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3598 my $lost_fee_line = $lost_fee_lines->next;
3599 is( $lost_fee_line->amount + 0,
3600 $replacement_amount, 'The right LOST amount is generated' );
3601 is( $lost_fee_line->amountoutstanding + 0,
3602 $replacement_amount,
3603 'The right LOST amountoutstanding is generated' );
3604 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3607 my ( $returned, $message ) =
3608 AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
3610 $overdue_fee->discard_changes;
3611 is( $overdue_fee->amount + 0,
3612 10, 'The OVERDUE amount is left intact' );
3613 is( $overdue_fee->amountoutstanding + 0,
3615 'The OVERDUE amountoutstanding is left intact' );
3617 $lost_fee_line->discard_changes;
3618 is( $lost_fee_line->amount + 0,
3619 $replacement_amount, 'The LOST amount is left intact' );
3620 is( $lost_fee_line->amountoutstanding + 0,
3621 $replacement_amount,
3622 'The LOST amountoutstanding is left intact' );
3623 # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
3624 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3627 subtest 'lostreturn | refund' => sub {
3630 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
3632 my $item = $builder->build_sample_item(
3634 replacementprice => $replacement_amount
3639 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3641 # Fake fines cronjob on this checkout
3643 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3644 $ten_days_ago, $now );
3647 issue_id => $issue->issue_id,
3648 itemnumber => $item->itemnumber,
3649 borrowernumber => $patron->borrowernumber,
3651 due => output_pref($ten_days_ago)
3654 my $overdue_fees = Koha::Account::Lines->search(
3656 borrowernumber => $patron->id,
3657 itemnumber => $item->itemnumber,
3658 debit_type_code => 'OVERDUE'
3661 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3662 my $overdue_fee = $overdue_fees->next;
3663 is( $overdue_fee->amount + 0,
3664 10, 'The right OVERDUE amount is generated' );
3665 is( $overdue_fee->amountoutstanding + 0,
3667 'The right OVERDUE amountoutstanding is generated' );
3669 # Simulate item marked as lost
3670 $item->itemlost(3)->store;
3671 C4::Circulation::LostItem( $item->itemnumber, 1 );
3673 my $lost_fee_lines = Koha::Account::Lines->search(
3675 borrowernumber => $patron->id,
3676 itemnumber => $item->itemnumber,
3677 debit_type_code => 'LOST'
3680 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3681 my $lost_fee_line = $lost_fee_lines->next;
3682 is( $lost_fee_line->amount + 0,
3683 $replacement_amount, 'The right LOST amount is generated' );
3684 is( $lost_fee_line->amountoutstanding + 0,
3685 $replacement_amount,
3686 'The right LOST amountoutstanding is generated' );
3687 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3689 # Return the lost item
3690 my ( undef, $message ) =
3691 AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
3693 $overdue_fee->discard_changes;
3694 is( $overdue_fee->amount + 0,
3695 10, 'The OVERDUE amount is left intact' );
3696 is( $overdue_fee->amountoutstanding + 0,
3698 'The OVERDUE amountoutstanding is left intact' );
3700 $lost_fee_line->discard_changes;
3701 is( $lost_fee_line->amount + 0,
3702 $replacement_amount, 'The LOST amount is left intact' );
3703 is( $lost_fee_line->amountoutstanding + 0,
3705 'The LOST amountoutstanding is refunded' );
3706 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3709 subtest 'lostreturn | restore' => sub {
3712 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
3714 my $item = $builder->build_sample_item(
3716 replacementprice => $replacement_amount
3721 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode , $ten_days_ago);
3723 # Fake fines cronjob on this checkout
3725 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3726 $ten_days_ago, $now );
3729 issue_id => $issue->issue_id,
3730 itemnumber => $item->itemnumber,
3731 borrowernumber => $patron->borrowernumber,
3733 due => output_pref($ten_days_ago)
3736 my $overdue_fees = Koha::Account::Lines->search(
3738 borrowernumber => $patron->id,
3739 itemnumber => $item->itemnumber,
3740 debit_type_code => 'OVERDUE'
3743 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3744 my $overdue_fee = $overdue_fees->next;
3745 is( $overdue_fee->amount + 0,
3746 10, 'The right OVERDUE amount is generated' );
3747 is( $overdue_fee->amountoutstanding + 0,
3749 'The right OVERDUE amountoutstanding is generated' );
3751 # Simulate item marked as lost
3752 $item->itemlost(3)->store;
3753 C4::Circulation::LostItem( $item->itemnumber, 1 );
3755 my $lost_fee_lines = Koha::Account::Lines->search(
3757 borrowernumber => $patron->id,
3758 itemnumber => $item->itemnumber,
3759 debit_type_code => 'LOST'
3762 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3763 my $lost_fee_line = $lost_fee_lines->next;
3764 is( $lost_fee_line->amount + 0,
3765 $replacement_amount, 'The right LOST amount is generated' );
3766 is( $lost_fee_line->amountoutstanding + 0,
3767 $replacement_amount,
3768 'The right LOST amountoutstanding is generated' );
3769 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3771 # Simulate refunding overdue fees upon marking item as lost
3772 my $overdue_forgive = $patron->account->add_credit(
3775 user_id => $manager->borrowernumber,
3776 library_id => $branchcode_restore,
3777 interface => 'test',
3779 item_id => $item->itemnumber
3782 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3783 $overdue_fee->discard_changes;
3784 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3787 my ( undef, $message ) =
3788 AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
3790 $overdue_fee->discard_changes;
3791 is( $overdue_fee->amount + 0,
3792 10, 'The OVERDUE amount is left intact' );
3793 is( $overdue_fee->amountoutstanding + 0,
3795 'The OVERDUE amountoutstanding is restored' );
3797 $lost_fee_line->discard_changes;
3798 is( $lost_fee_line->amount + 0,
3799 $replacement_amount, 'The LOST amount is left intact' );
3800 is( $lost_fee_line->amountoutstanding + 0,
3802 'The LOST amountoutstanding is refunded' );
3803 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3806 subtest 'lostreturn | charge' => sub {
3809 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
3811 my $item = $builder->build_sample_item(
3813 replacementprice => $replacement_amount
3818 my $issue = C4::Circulation::AddIssue( $patron->unblessed, $item->barcode, $ten_days_ago );
3820 # Fake fines cronjob on this checkout
3822 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3823 $ten_days_ago, $now );
3826 issue_id => $issue->issue_id,
3827 itemnumber => $item->itemnumber,
3828 borrowernumber => $patron->borrowernumber,
3830 due => output_pref($ten_days_ago)
3833 my $overdue_fees = Koha::Account::Lines->search(
3835 borrowernumber => $patron->id,
3836 itemnumber => $item->itemnumber,
3837 debit_type_code => 'OVERDUE'
3840 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3841 my $overdue_fee = $overdue_fees->next;
3842 is( $overdue_fee->amount + 0,
3843 10, 'The right OVERDUE amount is generated' );
3844 is( $overdue_fee->amountoutstanding + 0,
3846 'The right OVERDUE amountoutstanding is generated' );
3848 # Simulate item marked as lost
3849 $item->itemlost(3)->store;
3850 C4::Circulation::LostItem( $item->itemnumber, 1 );
3852 my $lost_fee_lines = Koha::Account::Lines->search(
3854 borrowernumber => $patron->id,
3855 itemnumber => $item->itemnumber,
3856 debit_type_code => 'LOST'
3859 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3860 my $lost_fee_line = $lost_fee_lines->next;
3861 is( $lost_fee_line->amount + 0,
3862 $replacement_amount, 'The right LOST amount is generated' );
3863 is( $lost_fee_line->amountoutstanding + 0,
3864 $replacement_amount,
3865 'The right LOST amountoutstanding is generated' );
3866 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3868 # Simulate refunding overdue fees upon marking item as lost
3869 my $overdue_forgive = $patron->account->add_credit(
3872 user_id => $manager->borrowernumber,
3873 library_id => $branchcode_charge,
3874 interface => 'test',
3876 item_id => $item->itemnumber
3879 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3880 $overdue_fee->discard_changes;
3881 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3884 my ( undef, $message ) =
3885 AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
3887 $lost_fee_line->discard_changes;
3888 is( $lost_fee_line->amount + 0,
3889 $replacement_amount, 'The LOST amount is left intact' );
3890 is( $lost_fee_line->amountoutstanding + 0,
3892 'The LOST amountoutstanding is refunded' );
3893 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3895 $overdue_fees = Koha::Account::Lines->search(
3897 borrowernumber => $patron->id,
3898 itemnumber => $item->itemnumber,
3899 debit_type_code => 'OVERDUE'
3902 order_by => { '-asc' => 'accountlines_id'}
3905 is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
3906 $overdue_fee = $overdue_fees->next;
3907 is( $overdue_fee->amount + 0,
3908 10, 'The original OVERDUE amount is left intact' );
3909 is( $overdue_fee->amountoutstanding + 0,
3911 'The original OVERDUE amountoutstanding is left as forgiven' );
3912 $overdue_fee = $overdue_fees->next;
3913 is( $overdue_fee->amount + 0,
3914 5, 'The new OVERDUE amount is correct for the backdated return' );
3915 is( $overdue_fee->amountoutstanding + 0,
3917 'The new OVERDUE amountoutstanding is correct for the backdated return' );
3922 subtest '_FixOverduesOnReturn' => sub {
3925 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3926 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3928 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3930 my $branchcode = $library2->{branchcode};
3932 my $item = $builder->build_sample_item(
3934 biblionumber => $biblio->biblionumber,
3935 library => $branchcode,
3936 replacementprice => 99.00,
3941 my $patron = $builder->build( { source => 'Borrower' } );
3943 ## Start with basic call, should just close out the open fine
3944 my $accountline = Koha::Account::Line->new(
3946 borrowernumber => $patron->{borrowernumber},
3947 debit_type_code => 'OVERDUE',
3948 status => 'UNRETURNED',
3949 itemnumber => $item->itemnumber,
3951 amountoutstanding => 99.00,
3952 interface => 'test',
3956 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
3958 $accountline->_result()->discard_changes();
3960 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
3961 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3962 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3964 ## Run again, with exemptfine enabled
3967 debit_type_code => 'OVERDUE',
3968 status => 'UNRETURNED',
3969 amountoutstanding => 99.00,
3973 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3975 $accountline->_result()->discard_changes();
3976 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'APPLY' })->next();
3978 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
3979 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3980 is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
3981 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
3982 is( $offset->amount + 0, -99, "Amount of offset is correct" );
3983 my $credit = $offset->credit;
3984 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
3985 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
3986 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
3988 # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
3991 debit_type_code => 'OVERDUE',
3992 status => 'UNRETURNED',
3993 amountoutstanding => 0.00,
3998 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
4000 $accountline->_result()->discard_changes();
4001 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'CREATE' })->next();
4002 is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
4003 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
4004 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
4007 subtest 'Set waiting flag' => sub {
4010 my $library_1 = $builder->build( { source => 'Branch' } );
4011 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
4012 my $library_2 = $builder->build( { source => 'Branch' } );
4013 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
4015 my $item = $builder->build_sample_item(
4017 library => $library_1->{branchcode},
4021 set_userenv( $library_2 );
4022 my $reserve_id = AddReserve(
4024 branchcode => $library_2->{branchcode},
4025 borrowernumber => $patron_2->{borrowernumber},
4026 biblionumber => $item->biblionumber,
4028 itemnumber => $item->itemnumber,
4032 set_userenv( $library_1 );
4033 my $do_transfer = 1;
4034 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
4035 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
4036 my $hold = Koha::Holds->find( $reserve_id );
4037 is( $hold->found, 'T', 'Hold is in transit' );
4039 my ( $status ) = CheckReserves($item);
4040 is( $status, 'Transferred', 'Hold is not waiting yet');
4042 set_userenv( $library_2 );
4044 AddReturn( $item->barcode, $library_2->{branchcode} );
4045 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
4046 $hold = Koha::Holds->find( $reserve_id );
4047 is( $hold->found, 'W', 'Hold is waiting' );
4048 ( $status ) = CheckReserves($item);
4049 is( $status, 'Waiting', 'Now the hold is waiting');
4051 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
4052 set_userenv( $library_1 );
4053 (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
4054 $hold = Koha::Holds->find( $reserve_id );
4055 is( $hold->found, undef, 'Hold is no longer marked waiting' );
4056 is( $hold->priority, 1, "Hold is now priority one again");
4057 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
4058 is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
4059 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
4060 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
4061 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
4064 subtest 'Cancel transfers on lost items' => sub {
4067 my $library_to = $builder->build_object( { class => 'Koha::Libraries' } );
4068 my $item = $builder->build_sample_item();
4069 my $holdingbranch = $item->holdingbranch;
4070 # Historic transfer (datearrived is defined)
4071 my $old_transfer = $builder->build_object(
4073 class => 'Koha::Item::Transfers',
4075 itemnumber => $item->itemnumber,
4076 frombranch => $holdingbranch,
4077 tobranch => $library_to->branchcode,
4079 datesent => \'NOW()',
4080 datearrived => \'NOW()',
4081 datecancelled => undef,
4082 daterequested => \'NOW()'
4086 # Queued transfer (datesent is undefined)
4087 my $transfer_1 = $builder->build_object(
4089 class => 'Koha::Item::Transfers',
4091 itemnumber => $item->itemnumber,
4092 frombranch => $holdingbranch,
4093 tobranch => $library_to->branchcode,
4096 datearrived => undef,
4097 datecancelled => undef,
4098 daterequested => \'NOW()'
4102 # In transit transfer (datesent is defined, datearrived and datecancelled are both undefined)
4103 my $transfer_2 = $builder->build_object(
4105 class => 'Koha::Item::Transfers',
4107 itemnumber => $item->itemnumber,
4108 frombranch => $holdingbranch,
4109 tobranch => $library_to->branchcode,
4111 datesent => \'NOW()',
4112 datearrived => undef,
4113 datecancelled => undef,
4114 daterequested => \'NOW()'
4119 # Simulate item being marked as lost
4120 $item->itemlost(1)->store;
4121 LostItem( $item->itemnumber, 'test', 1 );
4123 $transfer_1->discard_changes;
4124 isnt($transfer_1->datecancelled, undef, "Queud transfer was cancelled upon item lost");
4125 is($transfer_1->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
4126 $transfer_2->discard_changes;
4127 isnt($transfer_2->datecancelled, undef, "Active transfer was cancelled upon item lost");
4128 is($transfer_2->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
4129 $old_transfer->discard_changes;
4130 is($old_transfer->datecancelled, undef, "Old transfers are unaffected");
4131 $item->discard_changes;
4132 is($item->holdingbranch, $holdingbranch, "Items holding branch remains unchanged");
4135 subtest 'CanBookBeIssued | is_overdue' => sub {
4138 # Set a simple circ policy
4139 Koha::CirculationRules->set_rules(
4141 categorycode => undef,
4142 branchcode => undef,
4146 reservesallowed => 25,
4148 lengthunit => 'days',
4149 renewalsallowed => 1,
4151 norenewalbefore => undef,
4159 my $now = dt_from_string()->truncate( to => 'day' );
4160 my $five_days_go = $now->clone->add( days => 5 );
4161 my $ten_days_go = $now->clone->add( days => 10);
4162 my $library = $builder->build( { source => 'Branch' } );
4163 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
4165 my $item = $builder->build_sample_item(
4167 library => $library->{branchcode},
4171 my $issue = AddIssue( $patron->unblessed, $item->barcode, $five_days_go ); # date due was 10d ago
4172 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
4173 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), output_pref({ str => $five_days_go, dateonly => 1}), "First issue works");
4174 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron, $item->barcode, $ten_days_go, undef, undef, undef);
4175 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
4176 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
4179 subtest 'ItemsDeniedRenewal rules are checked' => sub {
4182 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
4183 Koha::CirculationRules->set_rules(
4185 categorycode => '*',
4187 branchcode => $idr_lib->branchcode,
4189 reservesallowed => 25,
4191 lengthunit => 'days',
4192 renewalsallowed => 10,
4194 norenewalbefore => undef,
4202 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
4203 homebranch => $idr_lib->branchcode,
4206 location => 'NOPROC'
4210 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
4211 branchcode => $idr_lib->branchcode,
4214 my $future = dt_from_string->add( days => 1 );
4215 my $issue = $builder->build_object(
4217 class => 'Koha::Checkouts',
4219 returndate => undef,
4220 renewals_count => 0,
4222 borrowernumber => $idr_borrower->borrowernumber,
4223 itemnumber => $allow_book->itemnumber,
4224 onsite_checkout => 0,
4225 date_due => $future,
4230 my $mock_item_class = Test::MockModule->new("Koha::Item");
4231 $mock_item_class->mock( 'is_denied_renewal', sub { return 1; } );
4233 my ( $mayrenew, $error ) = CanBookBeRenewed( $idr_borrower, $issue );
4234 is( $mayrenew, 0, 'Renewal blocked when $item->is_denied_renewal returns true' );
4235 is( $error, 'item_denied_renewal', 'Renewal blocked when $item->is_denied_renewal returns true' );
4237 $mock_item_class->unmock( 'is_denied_renewal' );
4238 $mock_item_class->mock( 'is_denied_renewal', sub { return 0; } );
4240 ( $mayrenew, $error ) = CanBookBeRenewed( $idr_borrower, $issue );
4241 is( $mayrenew, 1, 'Renewal allowed when $item->is_denied_renewal returns false' );
4242 is( $error, undef, 'Renewal allowed when $item->is_denied_renewal returns false' );
4244 $mock_item_class->unmock( 'is_denied_renewal' );
4247 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
4250 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4251 my $library = $builder->build( { source => 'Branch' } );
4252 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4254 my $item = $builder->build_sample_item(
4256 library => $library->{branchcode},
4260 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4261 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4262 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4265 subtest 'CanBookBeIssued | notforloan' => sub {
4268 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
4270 my $library = $builder->build( { source => 'Branch' } );
4271 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4273 my $itemtype = $builder->build(
4275 source => 'Itemtype',
4276 value => { notforloan => undef, }
4279 my $item = $builder->build_sample_item(
4281 library => $library->{branchcode},
4282 itype => $itemtype->{itemtype},
4285 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4287 my ( $issuingimpossible, $needsconfirmation );
4290 subtest 'item-level_itypes = 1' => sub {
4293 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
4294 # Is for loan at item type and item level
4295 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4296 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4297 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4299 # not for loan at item type level
4300 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4301 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4302 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4305 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4306 'Item can not be issued, not for loan at item type level'
4309 # not for loan at item level
4310 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4311 $item->notforloan( 1 )->store;
4312 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4313 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4316 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4317 'Item can not be issued, not for loan at item type level'
4321 subtest 'item-level_itypes = 0' => sub {
4324 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4326 # We set another itemtype for biblioitem
4327 my $itemtype = $builder->build(
4329 source => 'Itemtype',
4330 value => { notforloan => undef, }
4334 # for loan at item type and item level
4335 $item->notforloan(0)->store;
4336 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4337 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4338 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4339 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4341 # not for loan at item type level
4342 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4343 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4344 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4347 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4348 'Item can not be issued, not for loan at item type level'
4351 # not for loan at item level
4352 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4353 $item->notforloan( 1 )->store;
4354 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4355 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4358 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4359 'Item can not be issued, not for loan at item type level'
4363 # TODO test with AllowNotForLoanOverride = 1
4366 subtest 'CanBookBeIssued | recalls' => sub {
4369 t::lib::Mocks::mock_preference("UseRecalls", 1);
4370 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4371 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4372 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4373 my $item = $builder->build_sample_item;
4374 Koha::CirculationRules->set_rules({
4375 branchcode => undef,
4377 categorycode => undef,
4379 recalls_allowed => 10,
4384 my $recall = Koha::Recall->new(
4385 { patron_id => $patron1->borrowernumber,
4386 biblio_id => $item->biblionumber,
4387 item_id => $item->itemnumber,
4389 pickup_library_id => $patron1->branchcode,
4393 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4394 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed an item-level recall on this item" );
4396 $recall->set_cancelled;
4398 # biblio-level recall
4399 $recall = Koha::Recall->new(
4400 { patron_id => $patron1->borrowernumber,
4401 biblio_id => $item->biblionumber,
4404 pickup_library_id => $patron1->branchcode,
4408 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4409 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed a biblio-level recall and this item is eligible to fill it" );
4411 $recall->set_cancelled;
4413 # biblio-level recall
4414 $recall = Koha::Recall->new(
4415 { patron_id => $patron1->borrowernumber,
4416 biblio_id => $item->biblionumber,
4419 pickup_library_id => $patron1->branchcode,
4422 $recall->set_waiting( { item => $item, expirationdate => dt_from_string() } );
4424 my ( undef, undef, undef, $messages ) = CanBookBeIssued( $patron1, $item->barcode, undef, undef, undef, undef );
4425 is( $messages->{RECALLED}, $recall->id, "This book can be issued by this patron and they have placed a recall" );
4427 $recall->set_cancelled;
4430 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
4433 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
4434 my $item = $builder->build_sample_item(
4436 onloan => '2018-01-01',
4440 AddReturn( $item->barcode, $item->homebranch );
4441 $item->discard_changes; # refresh
4442 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
4445 subtest 'AddReturn | recalls' => sub {
4448 t::lib::Mocks::mock_preference("UseRecalls", 1);
4449 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4450 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4451 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4452 my $item1 = $builder->build_sample_item;
4453 Koha::CirculationRules->set_rules({
4454 branchcode => undef,
4456 categorycode => undef,
4458 recalls_allowed => 10,
4462 # this item can fill a recall with pickup at this branch
4463 AddIssue( $patron1->unblessed, $item1->barcode );
4464 my $recall1 = Koha::Recall->new(
4465 { patron_id => $patron2->borrowernumber,
4466 biblio_id => $item1->biblionumber,
4467 item_id => $item1->itemnumber,
4469 pickup_library_id => $item1->homebranch,
4472 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4473 is( $messages->{RecallFound}->id, $recall1->id, "Recall found" );
4474 $recall1->set_cancelled;
4476 # this item can fill a recall but needs transfer
4477 AddIssue( $patron1->unblessed, $item1->barcode );
4478 $recall1 = Koha::Recall->new(
4479 { patron_id => $patron2->borrowernumber,
4480 biblio_id => $item1->biblionumber,
4481 item_id => $item1->itemnumber,
4483 pickup_library_id => $patron2->branchcode,
4486 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4487 is( $messages->{RecallNeedsTransfer}, $item1->homebranch, "Recall requiring transfer found" );
4488 $recall1->set_cancelled;
4490 # this item is already in transit, do not ask to transfer
4491 AddIssue( $patron1->unblessed, $item1->barcode );
4492 $recall1 = Koha::Recall->new(
4493 { patron_id => $patron2->borrowernumber,
4494 biblio_id => $item1->biblionumber,
4495 item_id => $item1->itemnumber,
4497 pickup_library_id => $patron2->branchcode,
4500 $recall1->start_transfer;
4501 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $patron2->branchcode );
4502 is( $messages->{TransferredRecall}->id, $recall1->id, "In transit recall found" );
4503 $recall1->set_cancelled;
4506 subtest 'AddReturn | bundles' => sub {
4509 my $schema = Koha::Database->schema;
4510 $schema->storage->txn_begin;
4512 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4513 my $host_item1 = $builder->build_sample_item;
4514 my $bundle_item1 = $builder->build_sample_item;
4515 $schema->resultset('ItemBundle')
4517 { host => $host_item1->itemnumber, item => $bundle_item1->itemnumber } );
4519 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $bundle_item1->barcode, $bundle_item1->homebranch );
4520 is($messages->{InBundle}->id, $host_item1->id, 'AddReturn returns InBundle host item when item is part of a bundle');
4522 $schema->storage->txn_rollback;
4525 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
4530 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4532 my $issuing_charges = 15;
4533 my $title = 'A title';
4534 my $author = 'Author, An';
4535 my $barcode = 'WHATARETHEODDS';
4537 my $circ = Test::MockModule->new('C4::Circulation');
4539 'GetIssuingCharges',
4541 return $issuing_charges;
4545 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4546 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
4547 my $patron = $builder->build_object({
4548 class => 'Koha::Patrons',
4549 value => { branchcode => $library->id }
4552 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
4553 my $item_id = Koha::Item->new(
4555 biblionumber => $biblio->biblionumber,
4556 homebranch => $library->id,
4557 holdingbranch => $library->id,
4558 barcode => $barcode,
4559 replacementprice => 23.00,
4560 itype => $itemtype->id
4562 )->store->itemnumber;
4563 my $item = Koha::Items->find( $item_id );
4565 my $context = Test::MockModule->new('C4::Context');
4566 $context->mock( userenv => { branch => $library->id } );
4568 # Check the item out
4569 AddIssue( $patron->unblessed, $item->barcode );
4574 borrowernumber => $patron->borrowernumber,
4575 itemnumber => $item->itemnumber,
4576 branch => $library->id,
4577 lastreneweddate => { break => "the_renewal" }
4580 } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
4582 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
4583 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
4584 my %params_renewal = (
4585 timestamp => { -like => $date . "%" },
4586 module => "CIRCULATION",
4587 action => "RENEWAL",
4589 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
4592 borrowernumber => $patron->id,
4593 itemnumber => $item->id,
4594 branch => $library->id
4597 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4598 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
4600 my $checkouts = $patron->checkouts;
4601 # The following will fail if run on 00:00:00
4602 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
4604 my $lines = Koha::Account::Lines->search({
4605 borrowernumber => $patron->id,
4606 itemnumber => $item->id
4609 is( $lines->count, 2 );
4611 my $line = $lines->next;
4612 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
4613 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
4614 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
4616 $line = $lines->next;
4617 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
4618 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
4619 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
4621 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
4623 $context = Test::MockModule->new('C4::Context');
4624 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
4626 my $now = dt_from_string;
4627 $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
4628 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
4629 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
4630 $sth->execute($item->id, $library->id);
4631 my ($old_stats_size) = $sth->fetchrow_array;
4634 borrowernumber => $patron->id,
4635 itemnumber => $item->id,
4636 branch => $library->id
4639 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4640 $sth->execute($item->id, $library->id);
4641 my ($new_stats_size) = $sth->fetchrow_array;
4642 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
4643 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
4645 AddReturn( $item->id, $library->id, undef, $date );
4646 AddIssue( $patron->unblessed, $item->barcode, $now );
4649 borrowernumber => $patron->id,
4650 itemnumber => $item->id,
4651 branch => $library->id,
4655 my $lines_skipped = Koha::Account::Lines->search({
4656 borrowernumber => $patron->id,
4657 itemnumber => $item->id
4659 is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
4663 subtest 'AddRenewal() adds to renewals' => sub {
4666 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4667 my $patron = $builder->build_object({
4668 class => 'Koha::Patrons',
4669 value => { branchcode => $library->id }
4672 my $item = $builder->build_sample_item();
4674 set_userenv( $library->unblessed );
4676 # Check the item out
4677 my $issue = AddIssue( $patron->unblessed, $item->barcode );
4678 is(ref($issue), 'Koha::Checkout', 'Issue added');
4681 my $duedate = AddRenewal(
4683 borrowernumber => $patron->id,
4684 itemnumber => $item->id,
4685 branch => $library->id,
4690 ok( $duedate, "Renewal added" );
4692 my $renewals = Koha::Checkouts::Renewals->search({ checkout_id => $issue->issue_id });
4693 is($renewals->count, 1, 'One renewal added');
4694 my $THE_renewal = $renewals->next;
4695 is( $THE_renewal->renewer_id, C4::Context->userenv->{'number'}, 'Renewer recorded from context' );
4696 is( $THE_renewal->renewal_type, 'Automatic', 'AddRenewal "automatic" parameter sets renewal type to "Automatic"');
4699 subtest 'ProcessOfflinePayment() tests' => sub {
4706 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
4707 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4708 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
4710 is( $result, 'Success.', 'The right string is returned' );
4712 my $lines = $patron->account->lines;
4713 is( $lines->count, 1, 'line created correctly');
4715 my $line = $lines->next;
4716 is( $line->amount+0, $amount * -1, 'amount picked from params' );
4717 is( $line->branchcode, $library->id, 'branchcode set correctly' );
4721 subtest 'Incremented fee tests' => sub {
4724 my $dt = dt_from_string();
4725 Time::Fake->offset( $dt->epoch );
4727 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
4729 my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store;
4731 $module->mock( 'userenv', sub { { branch => $library->id } } );
4733 my $patron = $builder->build_object(
4735 class => 'Koha::Patrons',
4736 value => { categorycode => $patron_category->{categorycode} }
4740 my $itemtype = $builder->build_object(
4742 class => 'Koha::ItemTypes',
4744 notforloan => undef,
4746 rentalcharge_daily => 1,
4747 rentalcharge_daily_calendar => 0
4752 my $item = $builder->build_sample_item(
4754 library => $library->id,
4755 itype => $itemtype->id,
4759 is( $itemtype->rentalcharge_daily + 0,1, 'Daily rental charge stored and retreived correctly' );
4760 is( $item->effective_itemtype, $itemtype->id, "Itemtype set correctly for item" );
4762 my $now = dt_from_string;
4763 my $dt_from = $now->clone;
4764 my $dt_to = $now->clone->add( days => 7 );
4765 my $dt_to_renew = $now->clone->add( days => 13 );
4769 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4770 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4772 $accountline->amount + 0,
4774 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
4776 $accountline->delete();
4779 borrowernumber => $patron->id,
4780 itemnumber => $item->id,
4781 branch => $library->id,
4782 datedue => $dt_to_renew,
4783 lastreneweddate => $dt_to
4786 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4788 $accountline->amount + 0,
4790 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
4792 $accountline->delete();
4795 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
4796 $itemtype->rentalcharge_daily_calendar(1)->store();
4798 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4799 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4801 $accountline->amount + 0,
4803 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
4805 $accountline->delete();
4808 borrowernumber => $patron->id,
4809 itemnumber => $item->id,
4810 branch => $library->id,
4811 datedue => $dt_to_renew,
4812 lastreneweddate => $dt_to
4815 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4817 $accountline->amount + 0,
4819 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
4821 $accountline->delete();
4824 my $calendar = C4::Calendar->new( branchcode => $library->id );
4825 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
4827 ( $dt_from->day_of_week == 6 ) ? 0
4828 : ( $dt_from->day_of_week == 7 ) ? 1
4829 : $dt_from->day_of_week + 1;
4830 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
4831 $calendar->insert_week_day_holiday(
4832 weekday => $closed_day,
4833 title => 'Test holiday',
4834 description => 'Test holiday'
4837 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4838 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4840 $accountline->amount + 0,
4842 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
4844 $accountline->delete();
4847 borrowernumber => $patron->id,
4848 itemnumber => $item->id,
4849 branch => $library->id,
4850 datedue => $dt_to_renew,
4851 lastreneweddate => $dt_to
4854 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4856 $accountline->amount + 0,
4858 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
4860 $accountline->delete();
4863 $itemtype->rentalcharge(2)->store;
4864 is( $itemtype->rentalcharge + 0, 2, 'Rental charge updated and retreived correctly' );
4866 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4868 Koha::Account::Lines->search( { itemnumber => $item->id } );
4869 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly" );
4870 $accountlines->delete();
4873 borrowernumber => $patron->id,
4874 itemnumber => $item->id,
4875 branch => $library->id,
4876 datedue => $dt_to_renew,
4877 lastreneweddate => $dt_to
4880 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
4881 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly, for renewal" );
4882 $accountlines->delete();
4884 $itemtype->rentalcharge(0)->store;
4885 is( $itemtype->rentalcharge + 0, 0, 'Rental charge reset and retreived correctly' );
4888 Koha::CirculationRules->set_rule(
4890 categorycode => $patron->categorycode,
4891 itemtype => $itemtype->id,
4892 branchcode => $library->id,
4893 rule_name => 'lengthunit',
4894 rule_value => 'hours',
4898 $itemtype->rentalcharge_hourly('0.25')->store();
4899 is( $itemtype->rentalcharge_hourly, '0.25', 'Hourly rental charge stored and retreived correctly' );
4901 $dt_to = $now->clone->add( hours => 168 );
4902 $dt_to_renew = $now->clone->add( hours => 312 );
4904 $itemtype->rentalcharge_hourly_calendar(0)->store();
4906 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4907 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4909 $accountline->amount + 0,
4911 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)"
4913 $accountline->delete();
4916 borrowernumber => $patron->id,
4917 itemnumber => $item->id,
4918 branch => $library->id,
4919 datedue => $dt_to_renew,
4920 lastreneweddate => $dt_to
4923 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4925 $accountline->amount + 0,
4927 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)"
4929 $accountline->delete();
4932 $itemtype->rentalcharge_hourly_calendar(1)->store();
4934 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4935 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4937 $accountline->amount + 0,
4939 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)"
4941 $accountline->delete();
4944 borrowernumber => $patron->id,
4945 itemnumber => $item->id,
4946 branch => $library->id,
4947 datedue => $dt_to_renew,
4948 lastreneweddate => $dt_to
4951 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4953 $accountline->amount + 0,
4955 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u"
4957 $accountline->delete();
4960 $calendar->delete_holiday( weekday => $closed_day );
4962 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4963 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4965 $accountline->amount + 0,
4967 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u"
4969 $accountline->delete();
4972 borrowernumber => $patron->id,
4973 itemnumber => $item->id,
4974 branch => $library->id,
4975 datedue => $dt_to_renew,
4976 lastreneweddate => $dt_to
4979 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4981 $accountline->amount + 0,
4983 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)"
4985 $accountline->delete();
4990 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
4993 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
4994 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4997 $builder->build_object( { class => 'Koha::Libraries' } )->store;
4998 my $patron = $builder->build_object(
5000 class => 'Koha::Patrons',
5001 value => { categorycode => $patron_category->{categorycode} }
5005 my $itemtype = $builder->build_object(
5007 class => 'Koha::ItemTypes',
5011 rentalcharge_daily => 0
5016 my $item = $builder->build_sample_item(
5018 library => $library->id,
5022 itype => $itemtype->id,
5026 my ( $issuingimpossible, $needsconfirmation );
5027 my $dt_from = dt_from_string();
5028 my $dt_due = $dt_from->clone->add( days => 3 );
5030 $itemtype->rentalcharge(1)->store;
5031 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
5032 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
5033 $itemtype->rentalcharge('0')->store;
5034 $itemtype->rentalcharge_daily(1)->store;
5035 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
5036 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
5037 $itemtype->rentalcharge_daily('0')->store;
5040 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
5043 t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
5045 my $patron = $builder->build_object(
5047 class => 'Koha::Patrons',
5048 value => { categorycode => $patron_category->{categorycode} }
5052 my $item = $builder->build_sample_item(
5054 materials => 'includes DVD',
5058 my $dt_due = dt_from_string->add( days => 3 );
5060 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
5061 is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
5064 subtest 'Do not return on renewal (LOST charge)' => sub {
5067 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
5068 my $library = $builder->build_object( { class => "Koha::Libraries" } );
5069 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
5070 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
5072 my $biblio = $builder->build_sample_biblio;
5074 my $item = $builder->build_sample_item(
5076 biblionumber => $biblio->biblionumber,
5077 library => $library->branchcode,
5078 replacementprice => 99.00,
5083 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
5084 AddIssue( $patron->unblessed, $item->barcode );
5086 my $accountline = Koha::Account::Line->new(
5088 borrowernumber => $patron->borrowernumber,
5089 debit_type_code => 'LOST',
5091 itemnumber => $item->itemnumber,
5093 amountoutstanding => 12,
5094 interface => 'something',
5098 # AddRenewal doesn't call _FixAccountForLostAndFound
5099 AddIssue( $patron->unblessed, $item->barcode );
5101 is( $patron->checkouts->count, 1,
5102 'Renewal should not return the item even if a LOST payment has been made earlier'
5106 subtest 'Filling a hold should cancel existing transfer' => sub {
5109 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
5111 my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
5112 my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
5113 my $patron = $builder->build_object(
5115 class => 'Koha::Patrons',
5117 categorycode => $patron_category->{categorycode},
5118 branchcode => $libraryA->branchcode,
5123 my $item = $builder->build_sample_item({
5124 homebranch => $libraryB->branchcode,
5127 my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
5128 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
5130 branchcode => $libraryA->branchcode,
5131 borrowernumber => $patron->borrowernumber,
5132 biblionumber => $item->biblionumber,
5133 itemnumber => $item->itemnumber
5135 my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
5136 is( $reserves->count, 1, "Reserve is placed");
5137 ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
5138 my $reserve = $reserves->next;
5139 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
5140 $reserve->discard_changes;
5141 ok( $reserve->found eq 'W', "Reserve is marked waiting" );
5142 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
5145 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
5149 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
5150 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5151 my $patron = $builder->build_object(
5153 class => 'Koha::Patrons',
5154 value => { categorycode => $patron_category->{categorycode} }
5158 my $biblionumber = $builder->build_sample_biblio(
5160 branchcode => $library->branchcode,
5164 # And the circulation rule
5165 Koha::CirculationRules->search->delete;
5166 Koha::CirculationRules->set_rules(
5168 categorycode => undef,
5170 branchcode => undef,
5173 lengthunit => 'days',
5179 source => 'CirculationRule',
5181 branchcode => undef,
5182 categorycode => undef,
5184 rule_name => 'lostreturn',
5185 rule_value => 'refund'
5190 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5193 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5194 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5196 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5198 my $item = $builder->build_sample_item(
5200 biblionumber => $biblionumber,
5201 library => $library->branchcode,
5202 replacementprice => '42',
5205 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5206 LostItem( $item->itemnumber, 'cli', 0 );
5207 $item->_result->itemlost(1);
5208 $item->_result->itemlost_on( $lost_on );
5209 $item->_result->update();
5211 my $a = Koha::Account::Lines->search(
5213 itemnumber => $item->id,
5214 borrowernumber => $patron->borrowernumber
5217 ok( $a, "Found accountline for lost fee" );
5218 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5219 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5220 $a = $a->get_from_storage;
5221 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5225 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5228 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5229 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5231 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5233 my $item = $builder->build_sample_item(
5235 biblionumber => $biblionumber,
5236 library => $library->branchcode,
5237 replacementprice => '42',
5240 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5241 LostItem( $item->itemnumber, 'cli', 0 );
5242 $item->_result->itemlost(1);
5243 $item->_result->itemlost_on( $lost_on );
5244 $item->_result->update();
5246 my $a = Koha::Account::Lines->search(
5248 itemnumber => $item->id,
5249 borrowernumber => $patron->borrowernumber
5252 ok( $a, "Found accountline for lost fee" );
5253 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5254 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5255 $a = $a->get_from_storage;
5256 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5260 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5263 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5264 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5266 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5268 my $item = $builder->build_sample_item(
5270 biblionumber => $biblionumber,
5271 library => $library->branchcode,
5272 replacementprice => '42',
5275 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5276 LostItem( $item->itemnumber, 'cli', 0 );
5277 $item->_result->itemlost(1);
5278 $item->_result->itemlost_on( $lost_on );
5279 $item->_result->update();
5281 my $a = Koha::Account::Lines->search(
5283 itemnumber => $item->id,
5284 borrowernumber => $patron->borrowernumber
5287 ok( $a, "Found accountline for lost fee" );
5288 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5289 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5290 $a = $a->get_from_storage;
5291 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5295 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5298 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5299 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5301 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5303 my $item = $builder->build_sample_item(
5305 biblionumber => $biblionumber,
5306 library => $library->branchcode,
5307 replacementprice => '42',
5310 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5311 LostItem( $item->itemnumber, 'cli', 0 );
5312 $item->_result->itemlost(1);
5313 $item->_result->itemlost_on( $lost_on );
5314 $item->_result->update();
5316 my $a = Koha::Account::Lines->search(
5318 itemnumber => $item->id,
5319 borrowernumber => $patron->borrowernumber
5323 ok( $a, "Found accountline for lost fee" );
5324 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5325 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5326 $a = $a->get_from_storage;
5327 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5332 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
5336 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
5337 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5338 my $patron = $builder->build_object(
5340 class => 'Koha::Patrons',
5341 value => { categorycode => $patron_category->{categorycode} }
5344 my $patron2 = $builder->build_object(
5346 class => 'Koha::Patrons',
5347 value => { categorycode => $patron_category->{categorycode} }
5351 my $biblionumber = $builder->build_sample_biblio(
5353 branchcode => $library->branchcode,
5357 # And the circulation rule
5358 Koha::CirculationRules->search->delete;
5359 Koha::CirculationRules->set_rules(
5361 categorycode => undef,
5363 branchcode => undef,
5366 lengthunit => 'days',
5372 source => 'CirculationRule',
5374 branchcode => undef,
5375 categorycode => undef,
5377 rule_name => 'lostreturn',
5378 rule_value => 'refund'
5383 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5386 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5387 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5389 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5391 my $item = $builder->build_sample_item(
5393 biblionumber => $biblionumber,
5394 library => $library->branchcode,
5395 replacementprice => '42',
5398 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5399 LostItem( $item->itemnumber, 'cli', 0 );
5400 $item->_result->itemlost(1);
5401 $item->_result->itemlost_on( $lost_on );
5402 $item->_result->update();
5404 my $a = Koha::Account::Lines->search(
5406 itemnumber => $item->id,
5407 borrowernumber => $patron->borrowernumber
5410 ok( $a, "Found accountline for lost fee" );
5411 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5412 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5413 $a = $a->get_from_storage;
5414 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5419 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5422 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5423 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5425 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5427 my $item = $builder->build_sample_item(
5429 biblionumber => $biblionumber,
5430 library => $library->branchcode,
5431 replacementprice => '42',
5434 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5435 LostItem( $item->itemnumber, 'cli', 0 );
5436 $item->_result->itemlost(1);
5437 $item->_result->itemlost_on( $lost_on );
5438 $item->_result->update();
5440 my $a = Koha::Account::Lines->search(
5442 itemnumber => $item->id,
5443 borrowernumber => $patron->borrowernumber
5446 ok( $a, "Found accountline for lost fee" );
5447 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5448 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5449 $a = $a->get_from_storage;
5450 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5454 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5457 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5458 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5460 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5462 my $item = $builder->build_sample_item(
5464 biblionumber => $biblionumber,
5465 library => $library->branchcode,
5466 replacementprice => '42',
5469 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5470 LostItem( $item->itemnumber, 'cli', 0 );
5471 $item->_result->itemlost(1);
5472 $item->_result->itemlost_on( $lost_on );
5473 $item->_result->update();
5475 my $a = Koha::Account::Lines->search(
5477 itemnumber => $item->id,
5478 borrowernumber => $patron->borrowernumber
5481 ok( $a, "Found accountline for lost fee" );
5482 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5483 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5484 $a = $a->get_from_storage;
5485 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5489 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5492 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5493 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5495 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5497 my $item = $builder->build_sample_item(
5499 biblionumber => $biblionumber,
5500 library => $library->branchcode,
5501 replacementprice => '42',
5504 my $issue = AddIssue( $patron->unblessed, $item->barcode );
5505 LostItem( $item->itemnumber, 'cli', 0 );
5506 $item->_result->itemlost(1);
5507 $item->_result->itemlost_on( $lost_on );
5508 $item->_result->update();
5510 my $a = Koha::Account::Lines->search(
5512 itemnumber => $item->id,
5513 borrowernumber => $patron->borrowernumber
5517 ok( $a, "Found accountline for lost fee" );
5518 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5519 $issue = AddIssue( $patron2->unblessed, $item->barcode );
5520 $a = $a->get_from_storage;
5521 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5526 subtest 'transferbook tests' => sub {
5530 { C4::Circulation::transferbook({}); }
5531 'Koha::Exceptions::MissingParameter',
5532 'Koha::Patron->store raises an exception on missing params';
5535 { C4::Circulation::transferbook({to_branch=>'anything'}); }
5536 'Koha::Exceptions::MissingParameter',
5537 'Koha::Patron->store raises an exception on missing params';
5540 { C4::Circulation::transferbook({from_branch=>'anything'}); }
5541 'Koha::Exceptions::MissingParameter',
5542 'Koha::Patron->store raises an exception on missing params';
5544 my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
5545 is( $doreturn, 0, "No return without barcode");
5546 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5547 is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
5549 ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
5550 is( $doreturn, 0, "No return without barcode");
5551 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5552 is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
5556 subtest 'Checkout should correctly terminate a transfer' => sub {
5559 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5560 my $patron_1 = $builder->build_object(
5562 class => 'Koha::Patrons',
5563 value => { branchcode => $library_1->branchcode }
5566 my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
5567 my $patron_2 = $builder->build_object(
5569 class => 'Koha::Patrons',
5570 value => { branchcode => $library_2->branchcode }
5574 my $item = $builder->build_sample_item(
5576 library => $library_1->branchcode,
5580 t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
5581 my $reserve_id = AddReserve(
5583 branchcode => $library_2->branchcode,
5584 borrowernumber => $patron_2->borrowernumber,
5585 biblionumber => $item->biblionumber,
5586 itemnumber => $item->itemnumber,
5591 my $do_transfer = 1;
5592 ModItemTransfer( $item->itemnumber, $library_1->branchcode,
5593 $library_2->branchcode, 'Manual' );
5594 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
5595 GetOtherReserves( $item->itemnumber )
5596 ; # To put the Reason, it's what does returns.pl...
5597 my $hold = Koha::Holds->find($reserve_id);
5598 is( $hold->found, 'T', 'Hold is in transit' );
5599 my $transfer = $item->get_transfer;
5600 is( $transfer->frombranch, $library_1->branchcode );
5601 is( $transfer->tobranch, $library_2->branchcode );
5602 is( $transfer->reason, 'Reserve' );
5604 t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
5605 AddIssue( $patron_1->unblessed, $item->barcode );
5606 $transfer = $transfer->get_from_storage;
5607 isnt( $transfer->datearrived, undef );
5608 $hold = $hold->get_from_storage;
5609 is( $hold->found, undef, 'Hold is waiting' );
5610 is( $hold->priority, 1, );
5613 subtest 'AddIssue records staff who checked out item if appropriate' => sub {
5616 $module->mock( 'userenv', sub { { branch => $library->{id} } } );
5618 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5619 my $patron = $builder->build_object(
5621 class => 'Koha::Patrons',
5622 value => { categorycode => $patron_category->{categorycode} }
5625 my $issuer = $builder->build_object(
5627 class => 'Koha::Patrons',
5628 value => { categorycode => $patron_category->{categorycode} }
5631 my $item_1 = $builder->build_sample_item(
5633 library => $library->{branchcode}
5637 my $item_2 = $builder->build_sample_item(
5639 library => $library->branchcode
5643 $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->borrowernumber } } );
5645 my $dt_from = dt_from_string();
5646 my $dt_to = dt_from_string()->add( days => 7 );
5648 my $issue_1 = AddIssue( $patron->unblessed, $item_1->barcode, $dt_to, undef, $dt_from );
5650 is( $issue_1->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
5652 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
5655 AddIssue( $patron->unblessed, $item_2->barcode, $dt_to, undef, $dt_from );
5657 is( $issue_2->issuer->borrowernumber, $issuer->borrowernumber, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
5660 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
5663 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5664 my $patron_1 = $builder->build_object(
5666 class => 'Koha::Patrons',
5667 value => { branchcode => $library_1->branchcode }
5670 my $patron_2 = $builder->build_object(
5672 class => 'Koha::Patrons',
5673 value => { branchcode => $library_1->branchcode }
5677 my $item = $builder->build_sample_item(
5679 library => $library_1->branchcode,
5683 AddIssue( $patron_1->unblessed, $item->barcode );
5684 ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
5685 AddIssue( $patron_2->unblessed, $item->barcode );
5686 ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
5689 subtest "updateWrongTransfer tests" => sub {
5692 my $library1 = $builder->build_object( { class => 'Koha::Libraries' } );
5693 my $library2 = $builder->build_object( { class => 'Koha::Libraries' } );
5694 my $library3 = $builder->build_object( { class => 'Koha::Libraries' } );
5695 my $item = $builder->build_sample_item(
5697 homebranch => $library1->branchcode,
5698 holdingbranch => $library2->branchcode,
5699 datelastseen => undef
5703 my $transfer = $builder->build_object(
5705 class => 'Koha::Item::Transfers',
5707 itemnumber => $item->itemnumber,
5708 frombranch => $library2->branchcode,
5709 tobranch => $library1->branchcode,
5710 daterequested => dt_from_string,
5711 datesent => dt_from_string,
5712 datecancelled => undef,
5713 datearrived => undef,
5718 is( ref($transfer), 'Koha::Item::Transfer', 'Mock transfer added' );
5720 my $new_transfer = C4::Circulation::updateWrongTransfer($item->itemnumber, $library1->branchcode);
5721 is(ref($new_transfer), 'Koha::Item::Transfer', "updateWrongTransfer returns a 'Koha::Item::Transfer' object");
5722 ok( !$new_transfer->in_transit, "New transfer is NOT created as in transit (or cancelled)");
5724 my $original_transfer = $transfer->get_from_storage;
5725 ok( defined($original_transfer->datecancelled), "Original transfer was cancelled");
5726 is( $original_transfer->cancellation_reason, 'WrongTransfer', "Original transfer cancellation reason is 'WrongTransfer'");
5729 subtest "SendCirculationAlert" => sub {
5732 # When you would unsuspectingly call this unit test (with perl, not prove), you will be bitten by LOCK.
5733 # LOCK will commit changes and ruin your data
5734 # In order to prevent that, we will add KOHA_TESTING to $ENV; see further Circulation.pm
5735 $ENV{KOHA_TESTING} = 1;
5737 # Setup branch, borrowr, and notice
5738 my $library = $builder->build_object({ class => 'Koha::Libraries' });
5739 set_userenv( $library->unblessed);
5740 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5741 C4::Members::Messaging::SetMessagingPreference({
5742 borrowernumber => $patron->id,
5743 message_transport_types => ['sms'],
5744 message_attribute_id => 5
5746 my $item = $builder->build_sample_item();
5747 my $checkin_notice = $builder->build_object({
5748 class => 'Koha::Notice::Templates',
5750 module => 'circulation',
5752 branchcode => $library->branchcode,
5753 name => 'Test Checkin',
5755 content => "Checkins:\n----\n[% biblio.title %]-[% old_checkout.issue_id %]\n----Thank you.",
5756 message_transport_type => 'sms',
5761 # Checkout an item, mark it returned, generate a notice
5762 my $issue_1 = AddIssue( $patron->unblessed, $item->barcode);
5763 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5764 C4::Circulation::SendCirculationAlert({
5766 item => $item->unblessed,
5767 borrower => $patron->unblessed,
5768 branch => $library->branchcode,
5771 my $notice = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'CHECKIN' });
5772 is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\nThank you.", 'Letter generated with expected output on first checkin' );
5773 is($notice->to_address, $patron->smsalertnumber, "Letter has the correct to_address set to smsalertnumber for SMS type notices");
5775 # Checkout an item, mark it returned, generate a notice
5776 my $issue_2 = AddIssue( $patron->unblessed, $item->barcode);
5777 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5778 C4::Circulation::SendCirculationAlert({
5780 item => $item->unblessed,
5781 borrower => $patron->unblessed,
5782 branch => $library->branchcode,
5785 $notice->discard_changes();
5786 is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\n".$item->biblio->title."-".$issue_2->id."\nThank you.", 'Letter appended with expected output on second checkin' );
5790 subtest "GetSoonestRenewDate tests" => sub {
5792 Koha::CirculationRules->set_rule(
5794 categorycode => undef,
5795 branchcode => undef,
5797 rule_name => 'norenewalbefore',
5801 my $patron = $builder->build_object(
5803 class => 'Koha::Patrons',
5805 autorenew_checkouts => 1,
5809 my $item = $builder->build_sample_item();
5810 my $issue = AddIssue( $patron->unblessed, $item->barcode);
5811 my $datedue = dt_from_string( $issue->date_due() );
5814 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
5815 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
5817 GetSoonestRenewDate( $patron, $issue ),
5818 $datedue->clone->add( days => -7 ),
5819 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5823 # Test 'date' setting for syspref NoRenewalBeforePrecision
5824 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5826 GetSoonestRenewDate( $patron, $issue ),
5827 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
5828 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5832 Koha::CirculationRules->set_rule(
5834 categorycode => undef,
5835 branchcode => undef,
5837 rule_name => 'norenewalbefore',
5838 rule_value => undef,
5843 GetSoonestRenewDate( $patron, $issue ),
5845 'Checkouts without auto-renewal can be renewed immediately if no norenewalbefore'
5848 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5849 $issue->auto_renew(1)->store;
5851 GetSoonestRenewDate( $patron, $issue ),
5852 $datedue->clone->truncate( to => 'day' ),
5853 'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5855 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact' );
5857 GetSoonestRenewDate( $patron, $issue ),
5859 'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5862 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5863 Koha::CirculationRules->set_rule(
5865 categorycode => undef,
5866 branchcode => undef,
5868 rule_name => 'norenewalbefore',
5872 $issue->date_due(dt_from_string)->store;
5874 GetSoonestRenewDate( $patron, $issue ),
5875 dt_from_string->subtract( days => 1 )->truncate( to => 'day' ),
5876 'Checkouts with auto-renewal can be renewed 1 day before due date if no renewalbefore = 1 and precision = "date"'
5881 subtest "CanBookBeIssued + needsconfirmation message" => sub {
5884 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
5885 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5886 my $biblio = $builder->build_object({ class => 'Koha::Biblios' });
5887 my $biblioitem = $builder->build_object({ class => 'Koha::Biblioitems', value => { biblionumber => $biblio->biblionumber }});
5888 my $item = $builder->build_object({ class => 'Koha::Items' , value => { itype => $itemtype, biblionumber => $biblio->biblionumber }});
5890 my $hold = $builder->build_object({ class => 'Koha::Holds', value => {
5891 biblionumber => $item->biblionumber,
5892 branchcode => $library->branchcode,
5893 itemnumber => undef,
5900 my ( $error, $needsconfirmation, $alerts, $messages );
5902 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5903 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold exists.");
5905 $hold->priority(0)->store();
5907 $hold->found("W")->store();
5908 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5909 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is waiting.");
5911 $hold->found("T")->store();
5912 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5913 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is being transferred.");
5915 $hold->found("P")->store();
5916 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5917 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is being processed.");
5920 subtest 'Tests for BlockReturnOfWithdrawnItems' => sub {
5924 t::lib::Mocks::mock_preference('BlockReturnOfWithdrawnItems', 1);
5925 t::lib::Mocks::mock_preference('RecordLocalUseOnReturn', 0);
5926 my $item = $builder->build_sample_item();
5927 $item->withdrawn(1)->itemlost(1)->store;
5928 my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef );
5931 [ 0, { NotIssued => $item->barcode, withdrawn => 1 }, undef, {} ], "Item returned as withdrawn, no other messages");
5934 subtest 'Tests for transfer not in transit' => sub {
5939 # These tests are to ensure a 'pending' transfer, generated by
5940 # stock rotation, will be advanced when checked in
5942 my $item = $builder->build_sample_item();
5943 my $transfer = $builder->build_object({ class => 'Koha::Item::Transfers', value => {
5944 itemnumber => $item->id,
5945 reason => 'StockrotationRepatriation',
5947 frombranch => $item->homebranch,
5949 my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef );
5952 [ 0, { WasTransfered => $transfer->tobranch, TransferTrigger => 'StockrotationRepatriation', NotIssued => $item->barcode }, undef, {} ], "Item is reported to have been transferred");
5954 $transfer->discard_changes;
5955 ok( $transfer->datesent, 'The datesent field is populated, i.e. transfer is initiated');
5959 subtest 'Tests for RecordLocalUseOnReturn' => sub {
5963 t::lib::Mocks::mock_preference('RecordLocalUseOnReturn', 0);
5964 my $item = $builder->build_sample_item();
5965 $item->withdrawn(1)->itemlost(1)->store;
5966 my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef );
5969 [ 0, { NotIssued => $item->barcode, withdrawn => 1 }, undef, {} ], "RecordLocalUSeOnReturn is off, no local use recorded");
5971 t::lib::Mocks::mock_preference('RecordLocalUseOnReturn', 1);
5972 my @return2 = AddReturn( $item->barcode, $item->homebranch, 0, undef );
5975 [ 0, { NotIssued => $item->barcode, withdrawn => 1, LocalUse => 1 }, undef, {} ], "Local use is recorded");
5978 $schema->storage->txn_rollback;
5979 C4::Context->clear_syspref_cache();
5980 $branches = Koha::Libraries->search();
5981 for my $branch ( $branches->next ) {
5982 my $key = $branch->branchcode . "_holidays";
5983 $cache->clear_from_cache($key);