3 # This file is part of Koha.
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21 use Test::More tests => 67;
24 use Test::Deep qw( cmp_deeply );
30 use POSIX qw( floor );
32 use t::lib::TestBuilder;
35 use C4::Calendar qw( new insert_single_holiday insert_week_day_holiday delete_holiday );
36 use C4::Circulation qw( AddIssue AddReturn CanBookBeRenewed GetIssuingCharges AddRenewal GetSoonestRenewDate GetLatestAutoRenewDate LostItem GetUpcomingDueIssues CanBookBeIssued AddIssuingCharge MarkIssueReturned ProcessOfflinePayment transferbook updateWrongTransfer );
38 use C4::Items qw( ModItemTransfer );
40 use C4::Reserves qw( AddReserve ModReserve ModReserveCancelAll ModReserveAffect CheckReserves GetOtherReserves );
41 use C4::Overdues qw( CalcFine UpdateFine get_chargeable_units );
42 use C4::Members::Messaging qw( SetMessagingPreference );
43 use Koha::DateUtils qw( dt_from_string output_pref );
46 use Koha::Item::Transfers;
49 use Koha::Patron::Debarments qw( AddDebarment DelUniqueDebarment );
51 use Koha::CirculationRules;
52 use Koha::Subscriptions;
53 use Koha::Account::Lines;
54 use Koha::Account::Offsets;
56 use Koha::Notice::Messages;
57 use Koha::Cache::Memory::Lite;
59 my $builder = t::lib::TestBuilder->new;
62 my $staff = $builder->build_object({ class => "Koha::Patrons" });
63 t::lib::Mocks::mock_userenv({ patron => $staff, branchcode => $library->{branchcode} });
67 my ( $error, $question, $alert ) = @_;
69 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
70 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
71 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
75 sub test_debarment_on_checkout {
77 my $item = $params->{item};
78 my $library = $params->{library};
79 my $patron = $params->{patron};
80 my $due_date = $params->{due_date} || dt_from_string;
81 my $return_date = $params->{return_date} || dt_from_string;
82 my $expected_expiration_date = $params->{expiration_date};
84 $expected_expiration_date = output_pref(
86 dt => $expected_expiration_date,
92 my $line_number = $caller[2];
93 AddIssue( $patron, $item->barcode, $due_date );
95 my ( undef, $message ) = AddReturn( $item->barcode, $library->{branchcode}, undef, $return_date );
96 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
97 or diag('AddReturn returned message ' . Dumper $message );
98 my $suspensions = $patron->restrictions->search({ type => 'SUSPENSION' } );
99 is( $suspensions->count, 1, 'Test at line ' . $line_number );
101 my $THE_suspension = $suspensions->next;
102 is( $THE_suspension->expiration,
103 $expected_expiration_date, 'Test at line ' . $line_number );
104 Koha::Patron::Debarments::DelUniqueDebarment(
105 { borrowernumber => $patron->borrowernumber, type => 'SUSPENSION' } );
108 my $schema = Koha::Database->schema;
109 $schema->storage->txn_begin;
110 my $dbh = C4::Context->dbh;
112 # Prevent random failures by mocking ->now
113 my $now_value = dt_from_string;
114 my $mocked_datetime = Test::MockModule->new('DateTime');
115 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
117 my $cache = Koha::Caches->get_instance();
118 $dbh->do(q|DELETE FROM special_holidays|);
119 $dbh->do(q|DELETE FROM repeatable_holidays|);
120 my $branches = Koha::Libraries->search();
121 for my $branch ( $branches->next ) {
122 my $key = $branch->branchcode . "_holidays";
123 $cache->clear_from_cache($key);
126 # Start with a clean slate
127 $dbh->do('DELETE FROM issues');
128 $dbh->do('DELETE FROM borrowers');
130 # Disable recording of the staff who checked out an item until we're ready for it
131 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 0);
133 my $module = Test::MockModule->new('C4::Context');
135 my $library = $builder->build({
138 my $library2 = $builder->build({
141 my $itemtype = $builder->build(
143 source => 'Itemtype',
147 rentalcharge_daily => 0,
148 defaultreplacecost => undef,
153 my $patron_category = $builder->build(
155 source => 'Category',
157 category_type => 'P',
159 BlockExpiredPatronOpacActions => -1, # Pick the pref value
164 my $CircControl = C4::Context->preference('CircControl');
165 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
167 my $item = $builder->build_object({
168 class => 'Koha::Items',
170 homebranch => $library2->{branchcode},
171 holdingbranch => $library2->{branchcode}
175 my $borrower = $builder->build_object({
176 class => 'Koha::Patrons',
177 value => { branchcode => $library2->{branchcode} }
180 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
182 # No userenv, PickupLibrary
183 t::lib::Mocks::mock_preference('IndependentBranches', '0');
184 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
186 C4::Context->preference('CircControl'),
188 'CircControl changed to PickupLibrary'
191 C4::Circulation::_GetCircControlBranch($item, $borrower),
192 $item->get_column($HomeOrHoldingBranch),
193 '_GetCircControlBranch returned item branch (no userenv defined)'
196 # No userenv, PatronLibrary
197 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
199 C4::Context->preference('CircControl'),
201 'CircControl changed to PatronLibrary'
204 C4::Circulation::_GetCircControlBranch($item, $borrower),
205 $borrower->branchcode,
206 '_GetCircControlBranch returned borrower branch'
209 # No userenv, ItemHomeLibrary
210 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
212 C4::Context->preference('CircControl'),
214 'CircControl changed to ItemHomeLibrary'
217 $item->get_column($HomeOrHoldingBranch),
218 C4::Circulation::_GetCircControlBranch($item, $borrower),
219 '_GetCircControlBranch returned item branch'
223 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
224 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
226 # Userenv set, PickupLibrary
227 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
229 C4::Context->preference('CircControl'),
231 'CircControl changed to PickupLibrary'
234 C4::Circulation::_GetCircControlBranch($item, $borrower),
235 $library2->{branchcode},
236 '_GetCircControlBranch returned current branch'
239 # Userenv set, PatronLibrary
240 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
242 C4::Context->preference('CircControl'),
244 'CircControl changed to PatronLibrary'
247 C4::Circulation::_GetCircControlBranch($item, $borrower),
248 $borrower->branchcode,
249 '_GetCircControlBranch returned borrower branch'
252 # Userenv set, ItemHomeLibrary
253 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
255 C4::Context->preference('CircControl'),
257 'CircControl changed to ItemHomeLibrary'
260 C4::Circulation::_GetCircControlBranch($item, $borrower),
261 $item->get_column($HomeOrHoldingBranch),
262 '_GetCircControlBranch returned item branch'
265 # Reset initial configuration
266 t::lib::Mocks::mock_preference('CircControl', $CircControl);
268 C4::Context->preference('CircControl'),
270 'CircControl reset to its initial value'
273 # Set a simple circ policy
274 $dbh->do('DELETE FROM circulation_rules');
275 Koha::CirculationRules->set_rules(
277 categorycode => undef,
281 reservesallowed => 25,
283 lengthunit => 'days',
284 renewalsallowed => 1,
286 norenewalbefore => undef,
294 subtest "CanBookBeRenewed AllowRenewalIfOtherItemsAvailable multiple borrowers and items tests" => sub {
297 #Can only reserve from home branch
298 Koha::CirculationRules->set_rule(
302 rule_name => 'holdallowed',
306 Koha::CirculationRules->set_rule(
309 categorycode => undef,
311 rule_name => 'onshelfholds',
316 # Patrons from three different branches
317 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
318 my $patron_hold_1 = $builder->build_object({ class => 'Koha::Patrons' });
319 my $patron_hold_2 = $builder->build_object({ class => 'Koha::Patrons' });
320 my $biblio = $builder->build_sample_biblio();
322 # Item at each patron branch
323 my $item_1 = $builder->build_sample_item({
324 biblionumber => $biblio->biblionumber,
325 homebranch => $patron->branchcode
327 my $item_2 = $builder->build_sample_item({
328 biblionumber => $biblio->biblionumber,
329 homebranch => $patron_hold_2->branchcode
331 my $item_3 = $builder->build_sample_item({
332 biblionumber => $biblio->biblionumber,
333 homebranch => $patron_hold_1->branchcode
336 my $issue = AddIssue( $patron, $item_1->barcode);
337 my $datedue = dt_from_string( $issue->date_due() );
338 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
341 my $reserve_1 = AddReserve(
343 branchcode => $patron_hold_1->branchcode,
344 borrowernumber => $patron_hold_1->borrowernumber,
345 biblionumber => $biblio->biblionumber,
347 reservation_date => dt_from_string(),
348 expiration_date => undef,
355 branchcode => $patron_hold_2->branchcode,
356 borrowernumber => $patron_hold_2->borrowernumber,
357 biblionumber => $biblio->biblionumber,
359 reservation_date => dt_from_string(),
360 expiration_date => undef,
365 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
367 my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue);
368 is( $renewokay, 0, 'Cannot renew, reserved');
369 is( $error, 'on_reserve', 'Cannot renew, reserved (returned error is on_reserve)');
371 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
373 ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue);
374 is( $renewokay, 1, 'Can renew, two items available for two holds');
375 is( $error, undef, 'Can renew, each reserve has an item');
378 my $hold = Koha::Holds->find( $reserve_1 );
379 $hold->itemnumber( $item_1->itemnumber )->store;
381 ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue);
382 is( $renewokay, 0, 'Cannot renew when there is an item specific hold');
383 is( $error, 'on_reserve', 'Cannot renew, only this item can fill the reserve');
386 subtest "GetIssuingCharges tests" => sub {
388 my $branch_discount = $builder->build_object({ class => 'Koha::Libraries' });
389 my $branch_no_discount = $builder->build_object({ class => 'Koha::Libraries' });
390 Koha::CirculationRules->set_rule(
392 categorycode => undef,
393 branchcode => $branch_discount->branchcode,
395 rule_name => 'rentaldiscount',
399 my $itype_charge = $builder->build_object({
400 class => 'Koha::ItemTypes',
405 my $itype_no_charge = $builder->build_object({
406 class => 'Koha::ItemTypes',
411 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
412 my $item_1 = $builder->build_sample_item({ itype => $itype_charge->itemtype });
413 my $item_2 = $builder->build_sample_item({ itype => $itype_no_charge->itemtype });
415 t::lib::Mocks::mock_userenv({ branchcode => $branch_no_discount->branchcode });
416 # For now the sub always uses the env branch, this should follow CircControl instead
417 my ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
418 is( $charge + 0, 10.00, "Charge fetched correctly when no discount exists");
419 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
420 is( $charge + 0, 0.00, "Charge fetched correctly when no discount exists and no charge");
422 t::lib::Mocks::mock_userenv({ branchcode => $branch_discount->branchcode });
423 # For now the sub always uses the env branch, this should follow CircControl instead
424 ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
425 is( $charge + 0, 8.50, "Charge fetched correctly when discount exists");
426 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
427 is( $charge + 0, 0.00, "Charge fetched correctly when discount exists and no charge");
431 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
432 subtest "CanBookBeRenewed tests" => sub {
435 C4::Context->set_preference('ItemsDeniedRenewal','');
436 # Generate test biblio
437 my $biblio = $builder->build_sample_biblio();
439 my $branch = $library2->{branchcode};
441 my $item_1 = $builder->build_sample_item(
443 biblionumber => $biblio->biblionumber,
445 replacementprice => 12.00,
449 $reused_itemnumber_1 = $item_1->itemnumber;
451 my $item_2 = $builder->build_sample_item(
453 biblionumber => $biblio->biblionumber,
455 replacementprice => 23.00,
459 $reused_itemnumber_2 = $item_2->itemnumber;
461 my $item_3 = $builder->build_sample_item(
463 biblionumber => $biblio->biblionumber,
465 replacementprice => 23.00,
471 my %renewing_borrower_data = (
473 surname => 'Renewal',
474 categorycode => $patron_category->{categorycode},
475 branchcode => $branch,
476 autorenew_checkouts => 1,
479 my %reserving_borrower_data = (
480 firstname => 'Katrin',
481 surname => 'Reservation',
482 categorycode => $patron_category->{categorycode},
483 branchcode => $branch,
486 my %hold_waiting_borrower_data = (
488 surname => 'Reservation',
489 categorycode => $patron_category->{categorycode},
490 branchcode => $branch,
493 my %restricted_borrower_data = (
494 firstname => 'Alice',
495 surname => 'Reservation',
496 categorycode => $patron_category->{categorycode},
497 debarred => '3228-01-01',
498 branchcode => $branch,
501 my %expired_borrower_data = (
504 categorycode => $patron_category->{categorycode},
505 branchcode => $branch,
506 dateexpiry => dt_from_string->subtract( months => 1 ),
507 autorenew_checkouts => 1,
510 my $renewing_borrower_obj = Koha::Patron->new(\%renewing_borrower_data)->store;
511 my $renewing_borrowernumber = $renewing_borrower_obj->borrowernumber;
512 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
513 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
514 my $restricted_borrower_obj = Koha::Patron->new(\%restricted_borrower_data)->store;
516 my $expired_borrower_obj = Koha::Patron->new(\%expired_borrower_data)->store;
523 my $checkitem = undef;
526 my $issue_1 = AddIssue( $renewing_borrower_obj, $item_1->barcode);
527 my $datedue = dt_from_string( $issue_1->date_due() );
528 is (defined $issue_1->date_due(), 1, "Item 1 checked out, due date: " . $issue_1->date_due() );
530 my $issue_2 = AddIssue( $renewing_borrower_obj, $item_2->barcode);
531 is (defined $issue_2, 1, "Item 2 checked out, due date: " . $issue_2->date_due());
533 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
534 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to ".$renewing_borrower_obj->firstname." ".$renewing_borrower_obj->surname);
536 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1, 1);
537 is( $renewokay, 1, 'Can renew, no holds for this title or item');
540 # Biblio-level hold, renewal test
543 branchcode => $branch,
544 borrowernumber => $reserving_borrowernumber,
545 biblionumber => $biblio->biblionumber,
546 priority => $priority,
547 reservation_date => $resdate,
548 expiration_date => $expdate,
550 itemnumber => $checkitem,
555 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
556 Koha::CirculationRules->set_rule(
558 categorycode => undef,
561 rule_name => 'onshelfholds',
565 Koha::CirculationRules->set_rule(
567 categorycode => undef,
570 rule_name => 'renewalsallowed',
574 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
575 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
576 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
577 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2);
578 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
581 # Second biblio-level hold
582 my $reserve_id = AddReserve(
584 branchcode => $branch,
585 borrowernumber => $reserving_borrowernumber,
586 biblionumber => $biblio->biblionumber,
587 priority => $priority,
588 reservation_date => $resdate,
589 expiration_date => $expdate,
591 itemnumber => $checkitem,
595 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
596 is( $renewokay, 0, 'Renewal not possible when single patron\'s holds exceed the number of available items');
597 Koha::Holds->find($reserve_id)->delete;
599 # Now let's add an item level hold, we should no longer be able to renew the item
600 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
602 borrowernumber => $hold_waiting_borrowernumber,
603 biblionumber => $biblio->biblionumber,
604 itemnumber => $item_1->itemnumber,
605 branchcode => $branch,
607 reservedate => '1999-01-01',
610 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
611 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
614 # 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
615 # be able to renew these items
616 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
618 borrowernumber => $hold_waiting_borrowernumber,
619 biblionumber => $biblio->biblionumber,
620 itemnumber => $item_3->itemnumber,
621 branchcode => $branch,
626 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
627 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
628 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2);
629 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
630 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
632 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
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 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2);
637 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
638 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
640 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
641 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber );
642 AddIssue($reserving_borrower, $item_3->barcode);
643 my $reserve = $dbh->selectrow_hashref(
644 'SELECT * FROM old_reserves WHERE reserve_id = ?',
648 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
650 # Item-level hold, renewal test
653 branchcode => $branch,
654 borrowernumber => $reserving_borrowernumber,
655 biblionumber => $biblio->biblionumber,
656 priority => $priority,
657 reservation_date => $resdate,
658 expiration_date => $expdate,
660 itemnumber => $item_1->itemnumber,
665 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1, 1);
666 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
667 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
669 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2, 1);
670 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
672 # Items can't fill hold for reasons
673 $issue_1->item->notforloan(1)->store;
674 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1, 1);
675 is( $renewokay, 0, 'Cannot renew, item is marked not for loan, but an item specific hold always blocks');
676 $item_1->set({notforloan => 0, itype => $itemtype })->store;
678 # FIXME: Add more for itemtype not for loan etc.
680 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
681 my $item_5 = $builder->build_sample_item(
683 biblionumber => $biblio->biblionumber,
685 replacementprice => 23.00,
689 my $issue_5 = AddIssue($restricted_borrower_obj, $item_5->barcode);
690 is (defined $issue_5, 1, "Item with date due checked out, due date: ". $issue_5->date_due);
692 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
693 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2);
694 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
695 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrower_obj, $issue_5);
696 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
697 is( $error, 'restriction', "Correct error returned");
699 # Users cannot renew an overdue item
700 my $item_6 = $builder->build_sample_item(
702 biblionumber => $biblio->biblionumber,
704 replacementprice => 23.00,
709 my $item_7 = $builder->build_sample_item(
711 biblionumber => $biblio->biblionumber,
713 replacementprice => 23.00,
718 my $issue_6 = AddIssue( $renewing_borrower_obj, $item_6->barcode);
719 is (defined $issue_6, 1, "Item 2 checked out, due date: ".$issue_6->date_due);
721 my $now = dt_from_string();
722 my $five_weeks = DateTime::Duration->new(weeks => 5);
723 my $five_weeks_ago = $now - $five_weeks;
724 t::lib::Mocks::mock_preference('finesMode', 'production');
726 my $issue_7 = AddIssue($renewing_borrower_obj, $item_7->barcode, $five_weeks_ago);
727 is (defined $issue_7, 1, "Item with passed date due checked out, due date: " . $issue_7->date_due);
729 t::lib::Mocks::mock_preference('OverduesBlockRenewing','allow');
730 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_6);
731 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
732 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_7);
733 is( $renewokay, 1, '(Bug 8236), Can renew, this item is overdue but not pref does not block');
735 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
736 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_6);
737 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is not overdue but patron has overdues');
738 is( $error, 'overdue', "Correct error returned");
739 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_7);
740 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue so patron has overdues');
741 is( $error, 'overdue', "Correct error returned");
743 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
744 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_6);
745 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
746 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_7);
747 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
748 is( $error, 'overdue', "Correct error returned");
750 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower_obj->categorycode, $branch, $five_weeks_ago, $now );
751 C4::Overdues::UpdateFine(
753 issue_id => $issue_7->id(),
754 itemnumber => $item_7->itemnumber,
755 borrowernumber => $renewing_borrower_obj->borrowernumber,
757 due => Koha::DateUtils::output_pref($five_weeks_ago)
761 # Make sure fine calculation isn't skipped when adding renewal
762 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
764 # Calculate new due-date based on the present date not to incur
766 t::lib::Mocks::mock_preference('RenewalPeriodBase', 'now');
768 my $staff = $builder->build_object({ class => "Koha::Patrons" });
769 t::lib::Mocks::mock_userenv({ patron => $staff });
771 t::lib::Mocks::mock_preference('RenewalLog', 0);
772 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
773 my %params_renewal = (
774 timestamp => { -like => $date . "%" },
775 module => "CIRCULATION",
779 timestamp => { -like => $date . "%" },
780 module => "CIRCULATION",
783 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
784 my $dt = dt_from_string();
785 Time::Fake->offset( $dt->epoch );
786 my $datedue1 = AddRenewal(
788 borrowernumber => $renewing_borrower_obj->borrowernumber,
789 itemnumber => $item_7->itemnumber,
793 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
794 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
795 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
798 t::lib::Mocks::mock_preference('RenewalLog', 1);
799 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
800 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
803 borrowernumber => $renewing_borrower_obj->borrowernumber,
804 itemnumber => $item_7->itemnumber,
808 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
809 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
811 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower_obj->borrowernumber, itemnumber => $item_7->itemnumber } );
812 is( $fines->count, 1, 'AddRenewal left fine' );
813 is( $fines->next->status, 'RENEWED', 'Fine on renewed item is closed out properly' );
816 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
817 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
819 $renewing_borrower_obj,
821 Koha::DateUtils::output_pref({str=>$issue_6->date_due, dateformat =>'iso'}),
826 ); # TODO: Already issued???
827 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
828 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
829 $new_log_size = Koha::ActionLogs->count( \%params_issue );
830 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
832 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
836 # Test automatic renewal before value for "norenewalbefore" in policy is set
837 # In this case automatic renewal is not permitted prior to due date
838 my $item_4 = $builder->build_sample_item(
840 biblionumber => $biblio->biblionumber,
842 replacementprice => 16.00,
847 my $issue_4 = AddIssue( $renewing_borrower_obj, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
849 ( $renewokay, $error, $info ) =
850 CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
851 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
852 is( $error, 'auto_too_soon',
853 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
854 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'" );
857 branchcode => $branch,
858 borrowernumber => $reserving_borrowernumber,
859 biblionumber => $biblio->biblionumber,
860 itemnumber => $bibitems,
861 priority => $priority,
862 reservation_date => $resdate,
863 expiration_date => $expdate,
866 itemnumber => $item_4->itemnumber,
870 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
871 is( $renewokay, 0, 'Still should not be able to renew' );
872 is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' );
873 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4, undef, 1 );
874 is( $renewokay, 0, 'Still should not be able to renew' );
875 is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' );
876 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'" );
877 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4, 1 );
878 is( $renewokay, 0, 'Still should not be able to renew' );
879 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
880 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4, 1, 1 );
881 is( $renewokay, 0, 'Still should not be able to renew' );
882 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
883 $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
884 Koha::Cache::Memory::Lite->flush();
885 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4, 1 );
886 is( $renewokay, 0, 'Still should not be able to renew' );
887 is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
888 ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
890 $renewing_borrower_obj = Koha::Patrons->find($renewing_borrower_obj->borrowernumber);
891 $renewing_borrower_obj->autorenew_checkouts(0)->store;
892 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
893 is( $renewokay, 1, 'No renewal before is undef, but patron opted out of auto_renewal' );
894 $renewing_borrower_obj->autorenew_checkouts(1)->store;
898 # Test premature manual renewal
899 Koha::CirculationRules->set_rule(
901 categorycode => undef,
904 rule_name => 'norenewalbefore',
909 ( $renewokay, $error, $info ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
910 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
911 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
912 is( $info->{soonest_renew_date}, dt_from_string($issue_1->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
915 # Test premature automatic renewal
916 ( $renewokay, $error, $info ) =
917 CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
918 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
919 is( $error, 'auto_too_soon',
920 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
922 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'");
924 $renewing_borrower_obj->autorenew_checkouts(0)->store;
925 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
926 is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' );
927 is( $error, 'too_soon', 'Error is too_soon, no auto' );
928 is( $info->{soonest_renew_date}, dt_from_string($issue_4->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'");
929 $renewing_borrower_obj->autorenew_checkouts(1)->store;
931 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
932 # and test automatic renewal again
933 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
934 Koha::Cache::Memory::Lite->flush();
935 ( $renewokay, $error, $info ) =
936 CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
937 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
938 is( $error, 'auto_too_soon',
939 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
941 is( $info->{soonest_renew_date}, dt_from_string($issue_4->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
943 $renewing_borrower_obj->autorenew_checkouts(0)->store;
944 ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
945 is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' );
946 is( $error, 'too_soon', 'Error is too_soon, no auto' );
947 is( $info->{soonest_renew_date}, dt_from_string($issue_4->date_due), "Soonest renew date returned when error is 'auto_too_soon'");
948 $renewing_borrower_obj->autorenew_checkouts(1)->store;
950 # Change policy so that loans can be renewed 99 days prior to the due date
951 # and test automatic renewal again
952 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
953 Koha::Cache::Memory::Lite->flush();
954 ( $renewokay, $error ) =
955 CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
956 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
957 is( $error, 'auto_renew',
958 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
961 $renewing_borrower_obj->autorenew_checkouts(0)->store;
962 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_4 );
963 is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' );
964 $renewing_borrower_obj->autorenew_checkouts(1)->store;
966 subtest "too_late_renewal / no_auto_renewal_after" => sub {
968 my $item_to_auto_renew = $builder->build_sample_item(
970 biblionumber => $biblio->biblionumber,
975 my $ten_days_before = dt_from_string->add( days => -10 );
976 my $ten_days_ahead = dt_from_string->add( days => 10 );
977 my $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
979 Koha::CirculationRules->set_rules(
981 categorycode => undef,
985 norenewalbefore => '7',
986 no_auto_renewal_after => '9',
990 ( $renewokay, $error ) =
991 CanBookBeRenewed( $renewing_borrower_obj, $issue );
992 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
993 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
995 Koha::CirculationRules->set_rules(
997 categorycode => undef,
1001 norenewalbefore => '7',
1002 no_auto_renewal_after => '10',
1006 ( $renewokay, $error ) =
1007 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1008 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1009 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
1011 Koha::CirculationRules->set_rules(
1013 categorycode => undef,
1014 branchcode => undef,
1017 norenewalbefore => '7',
1018 no_auto_renewal_after => '11',
1022 ( $renewokay, $error ) =
1023 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1024 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1025 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
1027 Koha::CirculationRules->set_rules(
1029 categorycode => undef,
1030 branchcode => undef,
1033 norenewalbefore => '10',
1034 no_auto_renewal_after => '11',
1038 ( $renewokay, $error ) =
1039 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1040 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1041 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1043 Koha::CirculationRules->set_rules(
1045 categorycode => undef,
1046 branchcode => undef,
1049 norenewalbefore => '10',
1050 no_auto_renewal_after => undef,
1051 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1055 ( $renewokay, $error ) =
1056 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1057 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1058 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1060 Koha::CirculationRules->set_rules(
1062 categorycode => undef,
1063 branchcode => undef,
1066 norenewalbefore => '7',
1067 no_auto_renewal_after => '15',
1068 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
1072 ( $renewokay, $error ) =
1073 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1074 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1075 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
1077 Koha::CirculationRules->set_rules(
1079 categorycode => undef,
1080 branchcode => undef,
1083 norenewalbefore => '10',
1084 no_auto_renewal_after => undef,
1085 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
1089 ( $renewokay, $error ) =
1090 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1091 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1092 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
1095 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
1097 my $item_to_auto_renew = $builder->build_sample_item(
1099 biblionumber => $biblio->biblionumber,
1104 my $ten_days_before = dt_from_string->add( days => -10 );
1105 my $ten_days_ahead = dt_from_string->add( days => 10 );
1106 my $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1108 Koha::CirculationRules->set_rules(
1110 categorycode => undef,
1111 branchcode => undef,
1114 norenewalbefore => '10',
1115 no_auto_renewal_after => '11',
1119 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
1120 C4::Context->set_preference('OPACFineNoRenewals','10');
1121 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1122 my $fines_amount = 5;
1123 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
1124 $account->add_debit(
1126 amount => $fines_amount,
1127 interface => 'test',
1129 item_id => $item_to_auto_renew->itemnumber,
1130 description => "Some fines"
1132 )->status('RETURNED')->store;
1133 ( $renewokay, $error ) =
1134 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1135 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1136 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
1138 $account->add_debit(
1140 amount => $fines_amount,
1141 interface => 'test',
1143 item_id => $item_to_auto_renew->itemnumber,
1144 description => "Some fines"
1146 )->status('RETURNED')->store;
1147 ( $renewokay, $error ) =
1148 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1149 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1150 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
1152 $account->add_debit(
1154 amount => $fines_amount,
1155 interface => 'test',
1157 item_id => $item_to_auto_renew->itemnumber,
1158 description => "Some fines"
1160 )->status('RETURNED')->store;
1161 ( $renewokay, $error ) =
1162 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1163 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1164 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
1166 $account->add_credit(
1168 amount => $fines_amount,
1169 interface => 'test',
1171 description => "Some payment"
1174 ( $renewokay, $error ) =
1175 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1176 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1177 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1179 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
1180 ( $renewokay, $error ) =
1181 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1182 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1183 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1185 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
1186 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1189 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
1191 my $item_to_auto_renew = $builder->build_sample_item(
1193 biblionumber => $biblio->biblionumber,
1198 Koha::CirculationRules->set_rules(
1200 categorycode => undef,
1201 branchcode => undef,
1204 norenewalbefore => 10,
1205 no_auto_renewal_after => 11,
1210 my $ten_days_before = dt_from_string->add( days => -10 );
1211 my $ten_days_ahead = dt_from_string->add( days => 10 );
1213 # Patron is expired and BlockExpiredPatronOpacActions=0
1214 # => auto renew is allowed
1215 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
1216 my $issue = AddIssue( $expired_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1217 ( $renewokay, $error ) =
1218 CanBookBeRenewed( $expired_borrower_obj, $issue );
1219 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1220 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
1221 Koha::Checkouts->find( $issue->issue_id )->delete;
1224 # Patron is expired and BlockExpiredPatronOpacActions=1
1225 # => auto renew is not allowed
1226 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1227 $issue = AddIssue( $expired_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1228 ( $renewokay, $error ) =
1229 CanBookBeRenewed( $expired_borrower_obj, $issue );
1230 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1231 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
1234 # Patron is not expired and BlockExpiredPatronOpacActions=1
1235 # => auto renew is allowed
1236 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1237 $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1238 ( $renewokay, $error ) =
1239 CanBookBeRenewed( $renewing_borrower_obj, $issue );
1240 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1241 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1245 subtest "GetLatestAutoRenewDate" => sub {
1247 my $item_to_auto_renew = $builder->build_sample_item(
1249 biblionumber => $biblio->biblionumber,
1254 my $ten_days_before = dt_from_string->add( days => -10 );
1255 my $ten_days_ahead = dt_from_string->add( days => 10 );
1256 my $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1257 Koha::CirculationRules->set_rules(
1259 categorycode => undef,
1260 branchcode => undef,
1263 norenewalbefore => '7',
1264 no_auto_renewal_after => '',
1265 no_auto_renewal_after_hard_limit => undef,
1269 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1270 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' );
1271 my $five_days_before = dt_from_string->add( days => -5 );
1272 Koha::CirculationRules->set_rules(
1274 categorycode => undef,
1275 branchcode => undef,
1278 norenewalbefore => '10',
1279 no_auto_renewal_after => '5',
1280 no_auto_renewal_after_hard_limit => undef,
1284 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj,, $issue );
1285 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1286 $five_days_before->truncate( to => 'minute' ),
1287 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1289 my $five_days_ahead = dt_from_string->add( days => 5 );
1290 $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1291 $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1292 $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1293 Koha::Cache::Memory::Lite->flush();
1294 Koha::CirculationRules->set_rules(
1296 categorycode => undef,
1297 branchcode => undef,
1300 norenewalbefore => '10',
1301 no_auto_renewal_after => '15',
1302 no_auto_renewal_after_hard_limit => undef,
1306 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1307 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1308 $five_days_ahead->truncate( to => 'minute' ),
1309 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1311 my $two_days_ahead = dt_from_string->add( days => 2 );
1312 Koha::CirculationRules->set_rules(
1314 categorycode => undef,
1315 branchcode => undef,
1318 norenewalbefore => '10',
1319 no_auto_renewal_after => '',
1320 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1324 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1325 is( $latest_auto_renew_date->truncate( to => 'day' ),
1326 $two_days_ahead->truncate( to => 'day' ),
1327 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1329 Koha::CirculationRules->set_rules(
1331 categorycode => undef,
1332 branchcode => undef,
1335 norenewalbefore => '10',
1336 no_auto_renewal_after => '15',
1337 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1341 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue );
1342 is( $latest_auto_renew_date->truncate( to => 'day' ),
1343 $two_days_ahead->truncate( to => 'day' ),
1344 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1350 # set policy to forbid renewals
1351 Koha::CirculationRules->set_rules(
1353 categorycode => undef,
1354 branchcode => undef,
1357 norenewalbefore => undef,
1358 renewalsallowed => 0,
1363 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
1364 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1365 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1367 # Too many unseen renewals
1368 Koha::CirculationRules->set_rules(
1370 categorycode => undef,
1371 branchcode => undef,
1374 unseen_renewals_allowed => 2,
1375 renewalsallowed => 10,
1379 t::lib::Mocks::mock_preference('UnseenRenewals', 1);
1380 $issue_1->unseen_renewals(2)->store;
1382 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1);
1383 is( $renewokay, 0, 'Cannot renew, 0 unseen renewals allowed');
1384 is( $error, 'too_unseen', 'Cannot renew, returned code is too_unseen');
1385 Koha::CirculationRules->set_rules(
1387 categorycode => undef,
1388 branchcode => undef,
1391 norenewalbefore => undef,
1392 renewalsallowed => 0,
1396 t::lib::Mocks::mock_preference('UnseenRenewals', 0);
1398 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1399 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1400 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1402 C4::Overdues::UpdateFine(
1404 issue_id => $issue_1->id(),
1405 itemnumber => $item_1->itemnumber,
1406 borrowernumber => $renewing_borrower_obj->borrowernumber,
1409 due => Koha::DateUtils::output_pref($datedue)
1413 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower_obj->borrowernumber })->next();
1414 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1415 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1416 is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1417 is( $line->amount+0, 15, 'Account line amount is 15.00' );
1418 is( $line->issue_id, $issue_1->id, 'Account line issue id matches' );
1420 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1421 is( $offset->type, 'CREATE', 'Account offset type is CREATE' );
1422 is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1424 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1425 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1427 LostItem( $item_1->itemnumber, 'test', 1 );
1429 $line = Koha::Account::Lines->find($line->id);
1430 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1431 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1433 my $item = Koha::Items->find($item_1->itemnumber);
1434 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1435 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1436 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1438 my $total_due = $dbh->selectrow_array(
1439 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1440 undef, $renewing_borrower_obj->borrowernumber
1443 is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1445 C4::Context->dbh->do("DELETE FROM accountlines");
1447 C4::Overdues::UpdateFine(
1449 issue_id => $issue_2->id(),
1450 itemnumber => $item_2->itemnumber,
1451 borrowernumber => $renewing_borrower_obj->borrowernumber,
1454 due => Koha::DateUtils::output_pref($datedue)
1458 LostItem( $item_2->itemnumber, 'test', 0 );
1460 my $item2 = Koha::Items->find($item_2->itemnumber);
1461 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1462 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1464 $total_due = $dbh->selectrow_array(
1465 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1466 undef, $renewing_borrower_obj->borrowernumber
1469 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1471 my $future = dt_from_string();
1472 $future->add( days => 7 );
1473 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1474 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1476 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1477 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1478 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1479 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1480 LostItem( $item_3->itemnumber, 'test', 0 );
1481 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1482 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1484 $accountline->description,
1485 sprintf( "%s %s %s",
1486 $item_3->biblio->title || '',
1487 $item_3->barcode || '',
1488 $item_3->itemcallnumber || '' ),
1489 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1493 t::lib::Mocks::mock_preference('UseRecalls', 1);
1494 Koha::CirculationRules->set_rules({
1495 categorycode => undef,
1496 branchcode => undef,
1499 recalls_allowed => 10,
1500 renewalsallowed => 5,
1503 my $recall_borrower = $builder->build_object({ class => 'Koha::Patrons' });
1504 my $recall_biblio = $builder->build_sample_biblio();
1505 my $recall_item1 = $builder->build_sample_item({ biblionumber => $recall_biblio->biblionumber });
1506 my $recall_item2 = $builder->build_sample_item({ biblionumber => $recall_biblio->biblionumber });
1508 my $recall_issue = AddIssue( $renewing_borrower_obj, $recall_item1->barcode );
1510 # item-level and this item: renewal not allowed
1511 my $recall = Koha::Recall->new({
1512 biblio_id => $recall_item1->biblionumber,
1513 item_id => $recall_item1->itemnumber,
1514 patron_id => $recall_borrower->borrowernumber,
1515 pickup_library_id => $recall_borrower->branchcode,
1518 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1519 is( $error, 'recalled', 'Cannot renew item that has been recalled' );
1520 $recall->set_cancelled;
1522 # biblio-level requested recall: renewal not allowed
1523 $recall = Koha::Recall->new({
1524 biblio_id => $recall_item1->biblionumber,
1526 patron_id => $recall_borrower->borrowernumber,
1527 pickup_library_id => $recall_borrower->branchcode,
1530 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1531 is( $error, 'recalled', 'Cannot renew item if biblio is recalled and has no item allocated' );
1532 $recall->set_cancelled;
1534 # item-level and not this item: renewal allowed
1535 $recall = Koha::Recall->new({
1536 biblio_id => $recall_item2->biblionumber,
1537 item_id => $recall_item2->itemnumber,
1538 patron_id => $recall_borrower->borrowernumber,
1539 pickup_library_id => $recall_borrower->branchcode,
1542 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1543 is( $renewokay, 1, 'Can renew item if item-level recall on biblio is not on this item' );
1544 $recall->set_cancelled;
1546 # biblio-level waiting recall: renewal allowed
1547 $recall = Koha::Recall->new({
1548 biblio_id => $recall_item1->biblionumber,
1550 patron_id => $recall_borrower->borrowernumber,
1551 pickup_library_id => $recall_borrower->branchcode,
1554 $recall->set_waiting({ item => $recall_item1 });
1555 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue );
1556 is( $renewokay, 1, 'Can renew item if biblio-level recall has already been allocated an item' );
1557 $recall->set_cancelled;
1560 subtest "GetUpcomingDueIssues" => sub {
1563 my $branch = $library2->{branchcode};
1565 #Create another record
1566 my $biblio2 = $builder->build_sample_biblio();
1569 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1570 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1571 my $item_3 = $builder->build_sample_item(
1573 biblionumber => $biblio2->biblionumber,
1581 my %a_borrower_data = (
1582 firstname => 'Fridolyn',
1583 surname => 'SOMERS',
1584 categorycode => $patron_category->{categorycode},
1585 branchcode => $branch,
1588 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1589 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber );
1591 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1592 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1593 my $today = DateTime->today(time_zone => C4::Context->tz());
1595 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1596 my $datedue = dt_from_string( $issue->date_due() );
1597 my $issue_2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1598 my $datedue2 = dt_from_string( $issue->date_due() );
1602 # GetUpcomingDueIssues tests
1604 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1605 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1608 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1609 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1610 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1613 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1614 is ( scalar( @$upcoming_dues ), 1,
1615 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1618 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1620 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1622 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1623 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1625 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1626 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1628 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1629 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1631 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1632 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1634 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1635 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1637 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1638 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1642 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1643 my $branch = $library2->{branchcode};
1645 my $biblio = $builder->build_sample_biblio();
1648 my $item = $builder->build_sample_item(
1650 biblionumber => $biblio->biblionumber,
1657 my %a_borrower_data = (
1658 firstname => 'Kyle',
1660 categorycode => $patron_category->{categorycode},
1661 branchcode => $branch,
1664 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1666 my $borrower = Koha::Patrons->find( $borrowernumber );
1667 my $issue = AddIssue( $borrower, $item->barcode );
1670 issue_id => $issue->id(),
1671 itemnumber => $item->itemnumber,
1672 borrowernumber => $borrowernumber,
1678 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1679 my $count = $hr->{count};
1681 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1684 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1686 my $biblio = $builder->build_sample_biblio();
1687 my $item_1 = $builder->build_sample_item(
1689 biblionumber => $biblio->biblionumber,
1690 library => $library2->{branchcode},
1693 my $item_2= $builder->build_sample_item(
1695 biblionumber => $biblio->biblionumber,
1696 library => $library2->{branchcode},
1697 itype => $item_1->effective_itemtype,
1701 Koha::CirculationRules->set_rules(
1703 categorycode => undef,
1704 itemtype => $item_1->effective_itemtype,
1705 branchcode => undef,
1707 reservesallowed => 25,
1708 holds_per_record => 25,
1710 lengthunit => 'days',
1711 renewalsallowed => 1,
1713 norenewalbefore => undef,
1723 my $borrower1 = Koha::Patron->new({
1724 firstname => 'Kyle',
1726 categorycode => $patron_category->{categorycode},
1727 branchcode => $library2->{branchcode},
1729 my $borrowernumber2 = Koha::Patron->new({
1730 firstname => 'Chelsea',
1732 categorycode => $patron_category->{categorycode},
1733 branchcode => $library2->{branchcode},
1734 })->store->borrowernumber;
1735 my $patron_category_2 = $builder->build(
1737 source => 'Category',
1739 category_type => 'P',
1741 BlockExpiredPatronOpacActions => -1, # Pick the pref value
1745 my $borrowernumber3 = Koha::Patron->new({
1746 firstname => 'Carnegie',
1748 categorycode => $patron_category_2->{categorycode},
1749 branchcode => $library2->{branchcode},
1750 })->store->borrowernumber;
1752 my $issue = AddIssue( $borrower1, $item_1->barcode );
1754 my ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1755 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1759 branchcode => $library2->{branchcode},
1760 borrowernumber => $borrowernumber2,
1761 biblionumber => $biblio->biblionumber,
1766 Koha::CirculationRules->set_rules(
1768 categorycode => undef,
1769 itemtype => $item_1->effective_itemtype,
1770 branchcode => undef,
1776 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
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 and onshelfholds are disabled' );
1780 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1781 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1782 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1784 Koha::CirculationRules->set_rules(
1786 categorycode => undef,
1787 itemtype => $item_1->effective_itemtype,
1788 branchcode => undef,
1794 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1795 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1796 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1798 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1799 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1800 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1804 branchcode => $library2->{branchcode},
1805 borrowernumber => $borrowernumber3,
1806 biblionumber => $biblio->biblionumber,
1811 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1812 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' );
1814 my $item_3= $builder->build_sample_item(
1816 biblionumber => $biblio->biblionumber,
1817 library => $library2->{branchcode},
1818 itype => $item_1->effective_itemtype,
1822 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1823 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' );
1825 Koha::CirculationRules->set_rules(
1827 categorycode => $patron_category_2->{categorycode},
1828 itemtype => $item_1->effective_itemtype,
1829 branchcode => undef,
1831 reservesallowed => 0,
1836 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1837 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' );
1839 Koha::CirculationRules->set_rules(
1841 categorycode => $patron_category_2->{categorycode},
1842 itemtype => $item_1->effective_itemtype,
1843 branchcode => undef,
1845 reservesallowed => 25,
1850 # Setting item not checked out to be not for loan but holdable
1851 $item_2->notforloan(-1)->store;
1853 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1854 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' );
1856 my $mock_circ = Test::MockModule->new("C4::Circulation");
1857 $mock_circ->mock( CanItemBeReserved => sub {
1859 return { status => 'no' }
1862 $item_2->notforloan(0)->store;
1864 # Two items total, one item available, one issued, two holds on record
1867 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1868 } [], "CanItemBeReserved not called when there are more possible holds than available items";
1869 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1871 $item_3 = $builder->build_sample_item(
1873 biblionumber => $biblio->biblionumber,
1874 library => $library2->{branchcode},
1875 itype => $item_1->effective_itemtype,
1879 Koha::CirculationRules->set_rules(
1881 categorycode => undef,
1882 itemtype => $item_1->effective_itemtype,
1883 branchcode => undef,
1885 reservesallowed => 0,
1891 ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue );
1892 } ["Checked","Checked"], "CanItemBeReserved only called once per available item if it returns a negative result for all items for a borrower";
1893 is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' );
1898 # Don't allow renewing onsite checkout
1899 my $branch = $library->{branchcode};
1901 #Create another record
1902 my $biblio = $builder->build_sample_biblio();
1904 my $item = $builder->build_sample_item(
1906 biblionumber => $biblio->biblionumber,
1912 my $borrower = Koha::Patron->new({
1915 categorycode => $patron_category->{categorycode},
1916 branchcode => $branch,
1919 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1920 my ( $renewed, $error ) = CanBookBeRenewed( $borrower, $issue );
1921 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1922 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1926 my $library = $builder->build({ source => 'Branch' });
1928 my $biblio = $builder->build_sample_biblio();
1930 my $item = $builder->build_sample_item(
1932 biblionumber => $biblio->biblionumber,
1933 library => $library->{branchcode},
1937 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1939 my $issue = AddIssue( $patron, $item->barcode );
1942 issue_id => $issue->id,
1943 itemnumber => $item->itemnumber,
1944 borrowernumber => $patron->borrowernumber,
1951 issue_id => $issue->id,
1952 itemnumber => $item->itemnumber,
1953 borrowernumber => $patron->borrowernumber,
1958 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1961 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1964 my $homebranch = $builder->build( { source => 'Branch' } );
1965 my $holdingbranch = $builder->build( { source => 'Branch' } );
1966 my $otherbranch = $builder->build( { source => 'Branch' } );
1967 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1968 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1970 my $item = $builder->build_sample_item(
1972 homebranch => $homebranch->{branchcode},
1973 holdingbranch => $holdingbranch->{branchcode},
1976 Koha::CirculationRules->set_rules(
1978 categorycode => undef,
1979 itemtype => $item->effective_itemtype,
1980 branchcode => undef,
1982 reservesallowed => 25,
1984 lengthunit => 'days',
1985 renewalsallowed => 1,
1987 norenewalbefore => undef,
1996 set_userenv($holdingbranch);
1998 my $issue = AddIssue( $patron_1, $item->barcode );
1999 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
2001 my ( $error, $question, $alerts );
2003 # AllowReturnToBranch == anywhere
2004 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2005 ## Test that unknown barcodes don't generate internal server errors
2006 set_userenv($homebranch);
2007 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
2008 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
2009 ## Can be issued from homebranch
2010 set_userenv($homebranch);
2011 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2012 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2013 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2014 ## Can be issued from holdingbranch
2015 set_userenv($holdingbranch);
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' );
2019 ## Can be issued from another branch
2020 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2021 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2022 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2024 # AllowReturnToBranch == holdingbranch
2025 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2026 ## Cannot be issued from homebranch
2027 set_userenv($homebranch);
2028 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2029 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2030 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2031 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
2032 ## Can be issued from holdinbranch
2033 set_userenv($holdingbranch);
2034 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2035 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2036 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2037 ## Cannot be issued from another branch
2038 set_userenv($otherbranch);
2039 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2040 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2041 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2042 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
2044 # AllowReturnToBranch == homebranch
2045 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2046 ## Can be issued from holdinbranch
2047 set_userenv($homebranch);
2048 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2049 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2050 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
2051 ## Cannot be issued from holdinbranch
2052 set_userenv($holdingbranch);
2053 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2054 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2055 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2056 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2057 ## Cannot be issued from holdinbranch
2058 set_userenv($otherbranch);
2059 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode );
2060 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
2061 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
2062 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
2064 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2067 subtest 'AddIssue & AllowReturnToBranch' => sub {
2070 my $homebranch = $builder->build( { source => 'Branch' } );
2071 my $holdingbranch = $builder->build( { source => 'Branch' } );
2072 my $otherbranch = $builder->build( { source => 'Branch' } );
2074 my $patron_1 = $builder->build_object({
2075 class => 'Koha::Patrons',
2076 value => { categorycode => $patron_category->{categorycode} }
2079 my $patron_2 = $builder->build_object({
2080 class => 'Koha::Patrons',
2081 value => { categorycode => $patron_category->{categorycode} }
2085 my $item = $builder->build_sample_item(
2087 homebranch => $homebranch->{branchcode},
2088 holdingbranch => $holdingbranch->{branchcode},
2092 set_userenv($holdingbranch);
2094 my $ref_issue = 'Koha::Checkout';
2095 my $issue = AddIssue( $patron_1, $item->barcode );
2097 my ( $error, $question, $alerts );
2099 # AllowReturnToBranch == homebranch
2100 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
2101 ## Can be issued from homebranch
2102 set_userenv($homebranch);
2103 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
2104 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2105 ## Can be issued from holdinbranch
2106 set_userenv($holdingbranch);
2107 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
2108 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2109 ## Can be issued from another branch
2110 set_userenv($otherbranch);
2111 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
2112 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2114 # AllowReturnToBranch == holdinbranch
2115 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
2116 ## Cannot be issued from homebranch
2117 set_userenv($homebranch);
2118 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
2119 ## Can be issued from holdingbranch
2120 set_userenv($holdingbranch);
2121 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
2122 set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue
2123 ## Cannot be issued from another branch
2124 set_userenv($otherbranch);
2125 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
2127 # AllowReturnToBranch == homebranch
2128 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
2129 ## Can be issued from homebranch
2130 set_userenv($homebranch);
2131 is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
2132 AddIssue( $patron_1, $item->barcode ); # Re-issue to patron 1
2133 ## Cannot be issued from holdinbranch
2134 set_userenv($holdingbranch);
2135 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
2136 ## Cannot be issued from another branch
2137 set_userenv($otherbranch);
2138 is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
2139 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
2142 subtest 'AddIssue | recalls' => sub {
2145 t::lib::Mocks::mock_preference("UseRecalls", 1);
2146 t::lib::Mocks::mock_preference("item-level_itypes", 1);
2147 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2148 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2149 my $item = $builder->build_sample_item;
2150 Koha::CirculationRules->set_rules({
2151 branchcode => undef,
2153 categorycode => undef,
2155 recalls_allowed => 10,
2159 # checking out item that they have recalled
2160 my $recall1 = Koha::Recall->new(
2161 { patron_id => $patron1->borrowernumber,
2162 biblio_id => $item->biblionumber,
2163 item_id => $item->itemnumber,
2165 pickup_library_id => $patron1->branchcode,
2168 AddIssue( $patron1, $item->barcode, undef, undef, undef, undef, { recall_id => $recall1->id } );
2169 $recall1 = Koha::Recalls->find( $recall1->id );
2170 is( $recall1->fulfilled, 1, 'Recall was fulfilled when patron checked out item' );
2171 AddReturn( $item->barcode, $item->homebranch );
2173 # this item is has a recall request. cancel recall
2174 my $recall2 = Koha::Recall->new(
2175 { patron_id => $patron2->borrowernumber,
2176 biblio_id => $item->biblionumber,
2177 item_id => $item->itemnumber,
2179 pickup_library_id => $patron2->branchcode,
2182 AddIssue( $patron1, $item->barcode, undef, undef, undef, undef, { recall_id => $recall2->id, cancel_recall => 'cancel' } );
2183 $recall2 = Koha::Recalls->find( $recall2->id );
2184 is( $recall2->cancelled, 1, 'Recall was cancelled when patron checked out item' );
2185 AddReturn( $item->barcode, $item->homebranch );
2187 # this item is waiting to fulfill a recall. revert recall
2188 my $recall3 = Koha::Recall->new(
2189 { patron_id => $patron2->borrowernumber,
2190 biblio_id => $item->biblionumber,
2191 item_id => $item->itemnumber,
2193 pickup_library_id => $patron2->branchcode,
2196 $recall3->set_waiting;
2197 AddIssue( $patron1, $item->barcode, undef, undef, undef, undef, { recall_id => $recall3->id, cancel_recall => 'revert' } );
2198 $recall3 = Koha::Recalls->find( $recall3->id );
2199 is( $recall3->requested, 1, 'Recall was reverted from waiting when patron checked out item' );
2200 AddReturn( $item->barcode, $item->homebranch );
2203 subtest 'AddIssue & illrequests.due_date' => sub {
2206 t::lib::Mocks::mock_preference( 'ILLModule', 1 );
2207 my $library = $builder->build( { source => 'Branch' } );
2208 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2209 my $item = $builder->build_sample_item();
2211 set_userenv($library);
2213 my $custom_date_due = '9999-12-18 12:34:56';
2214 my $expected_date_due = '9999-12-18 23:59:00';
2215 my $illrequest = Koha::Illrequest->new({
2216 borrowernumber => $patron->borrowernumber,
2217 biblio_id => $item->biblionumber,
2218 branchcode => $library->{'branchcode'},
2219 due_date => $custom_date_due,
2222 my $issue = AddIssue( $patron, $item->barcode );
2223 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2225 $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2226 $item = $builder->build_sample_item();
2227 $custom_date_due = '9999-12-19';
2228 $expected_date_due = '9999-12-19 23:59:00';
2229 $illrequest = Koha::Illrequest->new({
2230 borrowernumber => $patron->borrowernumber,
2231 biblio_id => $item->biblionumber,
2232 branchcode => $library->{'branchcode'},
2233 due_date => $custom_date_due,
2236 $issue = AddIssue( $patron, $item->barcode );
2237 is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue');
2240 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
2243 my $library = $builder->build( { source => 'Branch' } );
2244 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2245 my $item_1 = $builder->build_sample_item(
2247 library => $library->{branchcode},
2250 my $item_2 = $builder->build_sample_item(
2252 library => $library->{branchcode},
2255 Koha::CirculationRules->set_rules(
2257 categorycode => undef,
2259 branchcode => $library->{branchcode},
2261 reservesallowed => 25,
2263 lengthunit => 'days',
2264 renewalsallowed => 1,
2266 norenewalbefore => undef,
2275 my ( $error, $question, $alerts );
2277 # Patron cannot issue item_1, they have overdues
2278 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
2279 my $issue = AddIssue( $patron, $item_1->barcode, $yesterday ); # Add an overdue
2281 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
2282 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2283 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
2284 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
2286 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
2287 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2288 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2289 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
2291 # Patron cannot issue item_1, they are debarred
2292 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
2293 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
2294 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2295 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2296 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
2298 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
2299 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2300 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
2301 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
2304 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
2307 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2308 my $patron_category_x = $builder->build_object(
2310 class => 'Koha::Patron::Categories',
2311 value => { category_type => 'X' }
2314 my $patron = $builder->build_object(
2316 class => 'Koha::Patrons',
2318 categorycode => $patron_category_x->categorycode,
2319 gonenoaddress => undef,
2326 my $item_1 = $builder->build_sample_item(
2328 library => $library->{branchcode},
2332 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->barcode );
2333 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
2335 my $stat = Koha::Statistics->search( { itemnumber => $item_1->itemnumber } )->next;
2336 is( $stat->branch, C4::Context->userenv->{'branch'}, 'Recorded a branch' );
2337 is( $stat->type, 'localuse', 'Recorded type as localuse' );
2338 is( $stat->itemnumber, $item_1->itemnumber, 'Recorded an itemnumber' );
2339 is( $stat->itemtype, $item_1->effective_itemtype, 'Recorded an itemtype' );
2340 is( $stat->borrowernumber, $patron->borrowernumber, 'Recorded a borrower number' );
2341 is( $stat->ccode, $item_1->ccode, 'Recorded a collection code' );
2342 is( $stat->categorycode, $patron->categorycode, 'Recorded a categorycode' );
2343 is( $stat->location, $item_1->location, 'Recorded a location' );
2345 # TODO There are other tests to provide here
2348 subtest 'MultipleReserves' => sub {
2351 my $biblio = $builder->build_sample_biblio();
2353 my $branch = $library2->{branchcode};
2355 my $item_1 = $builder->build_sample_item(
2357 biblionumber => $biblio->biblionumber,
2359 replacementprice => 12.00,
2364 my $item_2 = $builder->build_sample_item(
2366 biblionumber => $biblio->biblionumber,
2368 replacementprice => 12.00,
2375 my $resdate = undef;
2376 my $expdate = undef;
2378 my $checkitem = undef;
2381 my %renewing_borrower_data = (
2382 firstname => 'John',
2383 surname => 'Renewal',
2384 categorycode => $patron_category->{categorycode},
2385 branchcode => $branch,
2387 my $patron = Koha::Patron->new(\%renewing_borrower_data)->store;
2388 my $issue = AddIssue( $patron, $item_1->barcode);
2389 my $datedue = dt_from_string( $issue->date_due() );
2390 is (defined $issue->date_due(), 1, "item 1 checked out");
2391 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
2393 my %reserving_borrower_data1 = (
2394 firstname => 'Katrin',
2395 surname => 'Reservation',
2396 categorycode => $patron_category->{categorycode},
2397 branchcode => $branch,
2399 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
2402 branchcode => $branch,
2403 borrowernumber => $reserving_borrowernumber1,
2404 biblionumber => $biblio->biblionumber,
2405 priority => $priority,
2406 reservation_date => $resdate,
2407 expiration_date => $expdate,
2409 itemnumber => $checkitem,
2414 my %reserving_borrower_data2 = (
2415 firstname => 'Kirk',
2416 surname => 'Reservation',
2417 categorycode => $patron_category->{categorycode},
2418 branchcode => $branch,
2420 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
2423 branchcode => $branch,
2424 borrowernumber => $reserving_borrowernumber2,
2425 biblionumber => $biblio->biblionumber,
2426 priority => $priority,
2427 reservation_date => $resdate,
2428 expiration_date => $expdate,
2430 itemnumber => $checkitem,
2436 my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue, 1);
2437 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
2440 my $item_3 = $builder->build_sample_item(
2442 biblionumber => $biblio->biblionumber,
2444 replacementprice => 12.00,
2450 my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue, 1);
2451 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
2455 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
2458 my $library = $builder->build( { source => 'Branch' } );
2459 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2461 my $biblionumber = $builder->build_sample_biblio(
2463 branchcode => $library->{branchcode},
2466 my $item_1 = $builder->build_sample_item(
2468 biblionumber => $biblionumber,
2469 library => $library->{branchcode},
2473 my $item_2 = $builder->build_sample_item(
2475 biblionumber => $biblionumber,
2476 library => $library->{branchcode},
2480 Koha::CirculationRules->set_rules(
2482 categorycode => undef,
2484 branchcode => $library->{branchcode},
2486 reservesallowed => 25,
2488 lengthunit => 'days',
2489 renewalsallowed => 1,
2491 norenewalbefore => undef,
2500 my ( $error, $question, $alerts );
2501 my $issue = AddIssue( $patron, $item_1->barcode, dt_from_string->add( days => 1 ) );
2503 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2504 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2506 { error => $error, alerts => $alerts },
2507 { error => {}, alerts => {} },
2508 'No error or alert should be raised'
2510 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2512 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2513 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2515 { error => $error, question => $question, alerts => $alerts },
2516 { error => {}, question => {}, alerts => {} },
2517 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2520 # Add a subscription
2521 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2523 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2524 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2526 { error => $error, question => $question, alerts => $alerts },
2527 { error => {}, question => {}, alerts => {} },
2528 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2531 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2532 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode );
2534 { error => $error, question => $question, alerts => $alerts },
2535 { error => {}, question => {}, alerts => {} },
2536 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2540 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2543 my $library = $builder->build( { source => 'Branch' } );
2544 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2547 my $biblionumber = $builder->build_sample_biblio(
2549 branchcode => $library->{branchcode},
2552 my $item_1 = $builder->build_sample_item(
2554 biblionumber => $biblionumber,
2555 library => $library->{branchcode},
2558 my $item_2 = $builder->build_sample_item(
2560 biblionumber => $biblionumber,
2561 library => $library->{branchcode},
2565 # And the circulation rule
2566 Koha::CirculationRules->search->delete;
2567 Koha::CirculationRules->set_rules(
2569 categorycode => undef,
2571 branchcode => undef,
2574 firstremind => 1, # 1 day of grace
2575 finedays => 2, # 2 days of fine per day of overdue
2576 lengthunit => 'days',
2581 # Patron cannot issue item_1, they have overdues
2582 my $now = dt_from_string;
2583 my $five_days_ago = $now->clone->subtract( days => 5 );
2584 my $ten_days_ago = $now->clone->subtract( days => 10 );
2585 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2586 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2587 ; # Add another overdue
2589 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2590 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2591 my $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2592 is( $suspensions->count, 1, "Suspension added" );
2593 my $THE_suspension = $suspensions->next;
2595 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2596 # Same for the others
2597 my $expected_expiration = output_pref(
2599 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2600 dateformat => 'sql',
2604 is( $THE_suspension->expiration, $expected_expiration, "Suspesion expiration set" );
2606 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2607 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2608 is( $suspensions->count, 1, "Only one suspension" );
2609 $THE_suspension = $suspensions->next;
2611 $expected_expiration = output_pref(
2613 dt => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2614 dateformat => 'sql',
2618 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2620 Koha::Patron::Debarments::DelUniqueDebarment(
2621 { borrowernumber => $patron->borrowernumber, type => 'SUSPENSION' } );
2623 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2624 AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue
2625 AddIssue( $patron, $item_2->barcode, $ten_days_ago )
2626 ; # Add another overdue
2627 AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2628 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2629 is( $suspensions->count, 1, "Only one suspension" );
2630 $THE_suspension = $suspensions->next;
2632 $expected_expiration = output_pref(
2634 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2635 dateformat => 'sql',
2639 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2641 AddReturn( $item_2->barcode, $library->{branchcode}, undef, $now );
2642 $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } );
2643 is( $suspensions->count, 1, "Only one suspension" );
2644 $THE_suspension = $suspensions->next;
2646 $expected_expiration = output_pref(
2648 dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2649 dateformat => 'sql',
2653 is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" );
2656 subtest 'AddReturn + suspension_chargeperiod' => sub {
2659 my $library = $builder->build( { source => 'Branch' } );
2660 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2662 my $biblionumber = $builder->build_sample_biblio(
2664 branchcode => $library->{branchcode},
2667 my $item_1 = $builder->build_sample_item(
2669 biblionumber => $biblionumber,
2670 library => $library->{branchcode},
2674 # And the issuing rule
2675 Koha::CirculationRules->search->delete;
2676 Koha::CirculationRules->set_rules(
2678 categorycode => '*',
2683 firstremind => 0, # 0 day of grace
2684 finedays => 2, # 2 days of fine per day of overdue
2685 suspension_chargeperiod => 1,
2686 lengthunit => 'days',
2691 my $now = dt_from_string;
2692 my $five_days_ago = $now->clone->subtract( days => 5 );
2693 # We want to charge 2 days every day, without grace
2694 # With 5 days of overdue: 5 * Z
2695 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2696 test_debarment_on_checkout(
2699 library => $library,
2701 due_date => $five_days_ago,
2702 expiration_date => $expected_expiration,
2706 # Same with undef firstremind
2707 Koha::CirculationRules->search->delete;
2708 Koha::CirculationRules->set_rules(
2710 categorycode => '*',
2715 firstremind => undef, # 0 day of grace
2716 finedays => 2, # 2 days of fine per day of overdue
2717 suspension_chargeperiod => 1,
2718 lengthunit => 'days',
2723 my $now = dt_from_string;
2724 my $five_days_ago = $now->clone->subtract( days => 5 );
2725 # We want to charge 2 days every day, without grace
2726 # With 5 days of overdue: 5 * Z
2727 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2728 test_debarment_on_checkout(
2731 library => $library,
2733 due_date => $five_days_ago,
2734 expiration_date => $expected_expiration,
2738 # We want to charge 2 days every 2 days, without grace
2739 # With 5 days of overdue: (5 * 2) / 2
2740 Koha::CirculationRules->set_rule(
2742 categorycode => undef,
2743 branchcode => undef,
2745 rule_name => 'suspension_chargeperiod',
2750 $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2751 test_debarment_on_checkout(
2754 library => $library,
2756 due_date => $five_days_ago,
2757 expiration_date => $expected_expiration,
2761 # We want to charge 2 days every 3 days, with 1 day of grace
2762 # With 5 days of overdue: ((5-1) / 3 ) * 2
2763 Koha::CirculationRules->set_rules(
2765 categorycode => undef,
2766 branchcode => undef,
2769 suspension_chargeperiod => 3,
2774 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2775 test_debarment_on_checkout(
2778 library => $library,
2780 due_date => $five_days_ago,
2781 expiration_date => $expected_expiration,
2785 # Use finesCalendar to know if holiday must be skipped to calculate the due date
2786 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2787 Koha::CirculationRules->set_rules(
2789 categorycode => undef,
2790 branchcode => undef,
2794 suspension_chargeperiod => 1,
2799 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2800 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2802 # Adding a holiday 2 days ago
2803 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2804 my $two_days_ago = $now->clone->subtract( days => 2 );
2805 $calendar->insert_single_holiday(
2806 day => $two_days_ago->day,
2807 month => $two_days_ago->month,
2808 year => $two_days_ago->year,
2809 title => 'holidayTest-2d',
2810 description => 'holidayDesc 2 days ago'
2812 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2813 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2814 test_debarment_on_checkout(
2817 library => $library,
2819 due_date => $five_days_ago,
2820 expiration_date => $expected_expiration,
2824 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2825 my $two_days_ahead = $now->clone->add( days => 2 );
2826 $calendar->insert_single_holiday(
2827 day => $two_days_ahead->day,
2828 month => $two_days_ahead->month,
2829 year => $two_days_ahead->year,
2830 title => 'holidayTest+2d',
2831 description => 'holidayDesc 2 days ahead'
2834 # Same as above, but we should skip D+2
2835 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2836 test_debarment_on_checkout(
2839 library => $library,
2841 due_date => $five_days_ago,
2842 expiration_date => $expected_expiration,
2846 # Adding another holiday, day of expiration date
2847 my $expected_expiration_dt = dt_from_string($expected_expiration);
2848 $calendar->insert_single_holiday(
2849 day => $expected_expiration_dt->day,
2850 month => $expected_expiration_dt->month,
2851 year => $expected_expiration_dt->year,
2852 title => 'holidayTest_exp',
2853 description => 'holidayDesc on expiration date'
2855 # Expiration date will be the day after
2856 test_debarment_on_checkout(
2859 library => $library,
2861 due_date => $five_days_ago,
2862 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2866 test_debarment_on_checkout(
2869 library => $library,
2871 return_date => $now->clone->add(days => 5),
2872 expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2876 test_debarment_on_checkout(
2879 library => $library,
2881 due_date => $now->clone->add(days => 1),
2882 return_date => $now->clone->add(days => 5),
2883 expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2887 Koha::CirculationRules->search->delete;
2888 Koha::CirculationRules->set_rules(
2890 categorycode => undef,
2892 branchcode => undef,
2895 lengthunit => 'days',
2900 Koha::Patron::Debarments::AddDebarment(
2902 borrowernumber => $patron->borrowernumber,
2903 expiration => '9999-12-31',
2908 AddIssue( $patron, $item_1->barcode, $now->clone->subtract( days => 1 ) );
2909 my ( undef, $message ) = AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2910 is( $message->{WasReturned} && exists $message->{ForeverDebarred}, 1, 'Forever debarred message for Addreturn when overdue');
2912 Koha::Patron::Debarments::DelUniqueDebarment(
2914 borrowernumber => $patron->borrowernumber,
2918 Koha::Patron::Debarments::AddDebarment(
2920 borrowernumber => $patron->borrowernumber,
2921 expiration => $now->clone->add( days => 10 ),
2926 AddIssue( $patron, $item_1->barcode, $now->clone->subtract( days => 1 ) );
2927 (undef, $message) = AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now );
2928 is( $message->{WasReturned} && exists $message->{PrevDebarred}, 1, 'Previously debarred message for Addreturn when overdue');
2931 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2934 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2935 my $patron1 = $builder->build_object(
2937 class => 'Koha::Patrons',
2939 branchcode => $library->branchcode,
2940 categorycode => $patron_category->{categorycode}
2944 my $patron2 = $builder->build_object(
2946 class => 'Koha::Patrons',
2948 branchcode => $library->branchcode,
2949 categorycode => $patron_category->{categorycode}
2954 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2956 my $item = $builder->build_sample_item(
2958 library => $library->branchcode,
2962 my ( $error, $question, $alerts );
2963 my $issue = AddIssue( $patron1, $item->barcode );
2965 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2966 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2967 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' );
2969 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2970 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode );
2971 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' );
2973 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2977 subtest 'AddReturn | is_overdue' => sub {
2980 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2981 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2982 t::lib::Mocks::mock_preference('finesMode', 'production');
2983 t::lib::Mocks::mock_preference('MaxFine', '100');
2985 my $library = $builder->build( { source => 'Branch' } );
2986 my $patron = $builder->build_object(
2988 class => 'Koha::Patrons',
2989 value => { categorycode => $patron_category->{categorycode} }
2992 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
2993 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2995 my $item = $builder->build_sample_item(
2997 library => $library->{branchcode},
2998 replacementprice => 7
3002 Koha::CirculationRules->search->delete;
3003 Koha::CirculationRules->set_rules(
3005 categorycode => undef,
3007 branchcode => undef,
3010 lengthunit => 'days',
3011 fine => 1, # Charge 1 every day of overdue
3017 my $now = dt_from_string;
3018 my $one_day_ago = $now->clone->subtract( days => 1 );
3019 my $two_days_ago = $now->clone->subtract( days => 2 );
3020 my $five_days_ago = $now->clone->subtract( days => 5 );
3021 my $ten_days_ago = $now->clone->subtract( days => 10 );
3023 # No return date specified, today will be used => 10 days overdue charged
3024 AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago
3025 AddReturn( $item->barcode, $library->{branchcode} );
3026 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
3027 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3029 # specify return date 5 days before => no overdue charged
3030 AddIssue( $patron, $item->barcode, $five_days_ago ); # date due was 5d ago
3031 AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago );
3032 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
3033 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3035 # specify return date 5 days later => 5 days overdue charged
3036 AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago
3037 AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago );
3038 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
3039 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3041 # specify return date 5 days later, specify exemptfine => no overdue charge
3042 AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago
3043 AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago );
3044 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
3045 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3047 subtest 'bug 22877 | Lost item return' => sub {
3051 my $issue = AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago
3053 # Fake fines cronjob on this checkout
3055 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3056 $ten_days_ago, $now );
3059 issue_id => $issue->issue_id,
3060 itemnumber => $item->itemnumber,
3061 borrowernumber => $patron->borrowernumber,
3063 due => output_pref($ten_days_ago)
3066 is( int( $patron->account->balance() ),
3067 10, "Overdue fine of 10 days overdue" );
3069 # Fake longoverdue with charge and not marking returned
3070 LostItem( $item->itemnumber, 'cronjob', 0 );
3071 is( int( $patron->account->balance() ),
3072 17, "Lost fine of 7 plus 10 days overdue" );
3074 # Now we return it today
3075 AddReturn( $item->barcode, $library->{branchcode} );
3076 is( int( $patron->account->balance() ),
3077 17, "Should have a single 10 days overdue fine and lost charge" );
3080 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3083 subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
3087 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3089 my $issue = AddIssue( $patron, $item->barcode, $one_day_ago ); # date due was 1d ago
3091 # Fake fines cronjob on this checkout
3093 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3094 $one_day_ago, $now );
3097 issue_id => $issue->issue_id,
3098 itemnumber => $item->itemnumber,
3099 borrowernumber => $patron->borrowernumber,
3101 due => output_pref($one_day_ago)
3104 is( int( $patron->account->balance() ),
3105 1, "Overdue fine of 1 day overdue" );
3107 # Backdated return (dropbox mode example - charge should be removed)
3108 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3109 is( int( $patron->account->balance() ),
3110 0, "Overdue fine should be annulled" );
3111 my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3112 is( $lines->count, 0, "Overdue fine accountline has been removed");
3114 $issue = AddIssue( $patron, $item->barcode, $two_days_ago ); # date due was 2d ago
3116 # Fake fines cronjob on this checkout
3118 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3119 $two_days_ago, $now );
3122 issue_id => $issue->issue_id,
3123 itemnumber => $item->itemnumber,
3124 borrowernumber => $patron->borrowernumber,
3126 due => output_pref($one_day_ago)
3129 is( int( $patron->account->balance() ),
3130 2, "Overdue fine of 2 days overdue" );
3132 # Payment made against fine
3133 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3134 my $debit = $lines->next;
3135 my $credit = $patron->account->add_credit(
3139 interface => 'test',
3142 $credit->apply( { debits => [$debit] } );
3144 is( int( $patron->account->balance() ),
3145 0, "Overdue fine should be paid off" );
3146 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
3147 is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
3148 my $line = $lines->next;
3149 is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
3150 is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
3152 # Backdated return (dropbox mode example - charge should be removed)
3153 AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago );
3154 is( int( $patron->account->balance() ),
3155 -1, "Refund credit has been applied" );
3156 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
3157 is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
3159 $line = $lines->next;
3160 is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
3161 is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
3162 is($line->status,'RETURNED', "Overdue fine is fixed");
3163 $line = $lines->next;
3164 is($line->amount+0,-2, "Original payment amount remains as 2");
3165 is($line->amountoutstanding+0,0, "Original payment remains applied");
3166 $line = $lines->next;
3167 is($line->amount+0,-1, "Refund amount correctly set to 1");
3168 is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
3171 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3174 subtest 'bug 25417 | backdated return + exemptfine' => sub {
3178 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
3180 my $issue = AddIssue( $patron, $item->barcode, $one_day_ago ); # date due was 1d ago
3182 # Fake fines cronjob on this checkout
3184 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3185 $one_day_ago, $now );
3188 issue_id => $issue->issue_id,
3189 itemnumber => $item->itemnumber,
3190 borrowernumber => $patron->borrowernumber,
3192 due => output_pref($one_day_ago)
3195 is( int( $patron->account->balance() ),
3196 1, "Overdue fine of 1 day overdue" );
3198 # Backdated return (dropbox mode example - charge should no longer exist)
3199 AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago );
3200 is( int( $patron->account->balance() ),
3201 0, "Overdue fine should be annulled" );
3204 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
3207 subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
3210 t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
3212 my $due_date = dt_from_string;
3213 my $issue = AddIssue( $patron, $item->barcode, $due_date );
3218 issue_id => $issue->issue_id,
3219 itemnumber => $item->itemnumber,
3220 borrowernumber => $patron->borrowernumber,
3222 due => output_pref($due_date)
3225 is( $patron->account->balance(),
3226 0.25, 'Overdue fine of $0.25 recorded' );
3228 # Backdate return to exact due date and time
3229 my ( undef, $message ) =
3230 AddReturn( $item->barcode, $library->{branchcode},
3234 Koha::Account::Lines->find( { issue_id => $issue->id } );
3235 ok( !$accountline, 'accountline removed as expected' );
3238 $issue = AddIssue( $patron, $item->barcode, $due_date );
3243 issue_id => $issue->issue_id,
3244 itemnumber => $item->itemnumber,
3245 borrowernumber => $patron->borrowernumber,
3247 due => output_pref($due_date)
3250 is( $patron->account->balance(),
3251 0.25, 'Overdue fine of $0.25 recorded' );
3253 # Partial pay accruing fine
3254 my $lines = Koha::Account::Lines->search(
3256 borrowernumber => $patron->borrowernumber,
3257 issue_id => $issue->id
3260 my $debit = $lines->next;
3261 my $credit = $patron->account->add_credit(
3265 interface => 'test',
3268 $credit->apply( { debits => [$debit] } );
3270 is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
3272 # Backdate return to exact due date and time
3273 ( undef, $message ) =
3274 AddReturn( $item->barcode, $library->{branchcode},
3277 $lines = Koha::Account::Lines->search(
3279 borrowernumber => $patron->borrowernumber,
3280 issue_id => $issue->id
3283 $accountline = $lines->next;
3284 is( $accountline->amountoutstanding + 0,
3285 0, 'Partially paid fee amount outstanding was reduced to 0' );
3286 is( $accountline->amount + 0,
3287 0, 'Partially paid fee amount was reduced to 0' );
3288 is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
3291 Koha::Account::Lines->search(
3292 { borrowernumber => $patron->borrowernumber } )->delete;
3295 subtest 'enh 23091 | Lost item return policies' => sub {
3298 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3300 my $branchcode_false =
3301 $builder->build( { source => 'Branch' } )->{branchcode};
3302 my $specific_rule_false = $builder->build(
3304 source => 'CirculationRule',
3306 branchcode => $branchcode_false,
3307 categorycode => undef,
3309 rule_name => 'lostreturn',
3314 my $branchcode_refund =
3315 $builder->build( { source => 'Branch' } )->{branchcode};
3316 my $specific_rule_refund = $builder->build(
3318 source => 'CirculationRule',
3320 branchcode => $branchcode_refund,
3321 categorycode => undef,
3323 rule_name => 'lostreturn',
3324 rule_value => 'refund'
3328 my $branchcode_restore =
3329 $builder->build( { source => 'Branch' } )->{branchcode};
3330 my $specific_rule_restore = $builder->build(
3332 source => 'CirculationRule',
3334 branchcode => $branchcode_restore,
3335 categorycode => undef,
3337 rule_name => 'lostreturn',
3338 rule_value => 'restore'
3342 my $branchcode_charge =
3343 $builder->build( { source => 'Branch' } )->{branchcode};
3344 my $specific_rule_charge = $builder->build(
3346 source => 'CirculationRule',
3348 branchcode => $branchcode_charge,
3349 categorycode => undef,
3351 rule_name => 'lostreturn',
3352 rule_value => 'charge'
3357 my $branchcode_refund_unpaid =
3358 $builder->build( { source => 'Branch' } )->{branchcode};
3359 my $specific_rule_refund_unpaid = $builder->build(
3361 source => 'CirculationRule',
3363 branchcode => $branchcode_refund_unpaid,
3364 categorycode => undef,
3366 rule_name => 'lostreturn',
3367 rule_value => 'refund_unpaid'
3372 my $replacement_amount = 99.00;
3373 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
3374 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
3375 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
3376 t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 );
3377 t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl',
3379 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge',
3382 subtest 'lostreturn | refund_unpaid' => sub {
3385 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund_unpaid });
3387 my $item = $builder->build_sample_item(
3389 replacementprice => $replacement_amount
3394 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode );
3397 $item->itemlost(3)->store;
3398 C4::Circulation::LostItem( $item->itemnumber, 1 );
3400 my $lost_fee_lines = Koha::Account::Lines->search(
3402 borrowernumber => $patron->id,
3403 itemnumber => $item->itemnumber,
3404 debit_type_code => 'LOST'
3407 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3408 my $lost_fee_line = $lost_fee_lines->next;
3409 is( int($lost_fee_line->amount),
3410 $replacement_amount, 'The right LOST amount is generated' );
3411 is( int($lost_fee_line->amountoutstanding),
3412 $replacement_amount,
3413 'The right LOST amountoutstanding is generated' );
3414 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3417 int($patron->account->balance),
3418 $replacement_amount ,
3419 "Account balance equals the replacement amount after being charged lost fee when no payments has been made"
3422 # Return lost item without any payments having been made
3423 my ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3425 $lost_fee_line->discard_changes;
3427 is( int($lost_fee_line->amount), $replacement_amount, 'The LOST amount is left intact' );
3428 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero' );
3429 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set' );
3431 int($patron->account->balance),
3433 'Account balance should be zero after returning item with lost fee when no payments has been made'
3436 # Create a second item
3437 $item = $builder->build_sample_item(
3439 replacementprice => $replacement_amount
3444 $issue = C4::Circulation::AddIssue( $patron, $item->barcode );
3447 $item->itemlost(3)->store;
3448 C4::Circulation::LostItem( $item->itemnumber, 1 );
3450 $lost_fee_lines = Koha::Account::Lines->search(
3452 borrowernumber => $patron->id,
3453 itemnumber => $item->itemnumber,
3454 debit_type_code => 'LOST'
3457 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3458 $lost_fee_line = $lost_fee_lines->next;
3460 # Make partial payment
3461 $patron->account->payin_amount({
3463 interface => 'intranet',
3464 payment_type => 'CASH',
3465 user_id => $patron->borrowernumber,
3467 debits => [$lost_fee_line]
3470 $lost_fee_line->discard_changes;
3472 is( int($lost_fee_line->amountoutstanding),
3474 'The LOST amountoutstanding is the expected amount after partial payment of lost fee'
3478 int($patron->account->balance),
3480 'Account balance is the expected amount after partial payment of lost fee'
3483 # Return lost item with partial payment having been made
3484 ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3486 $lost_fee_line->discard_changes;
3488 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero after returning lost item with partial payment' );
3489 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set for lost item with partial payment' );
3491 int($patron->account->balance),
3493 'Account balance should be zero after returning item with lost fee when partial payment has been made'
3496 # Create a third item
3497 $item = $builder->build_sample_item(
3499 replacementprice => $replacement_amount
3504 $issue = C4::Circulation::AddIssue( $patron, $item->barcode );
3507 $item->itemlost(3)->store;
3508 C4::Circulation::LostItem( $item->itemnumber, 1 );
3510 $lost_fee_lines = Koha::Account::Lines->search(
3512 borrowernumber => $patron->id,
3513 itemnumber => $item->itemnumber,
3514 debit_type_code => 'LOST'
3517 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3518 $lost_fee_line = $lost_fee_lines->next;
3521 $patron->account->payin_amount({
3523 interface => 'intranet',
3524 payment_type => 'CASH',
3525 user_id => $patron->borrowernumber,
3526 amount => $replacement_amount,
3527 debits => [$lost_fee_line]
3530 $lost_fee_line->discard_changes;
3532 is( int($lost_fee_line->amountoutstanding),
3534 'The LOST amountoutstanding is the expected amount after partial payment of lost fee'
3538 int($patron->account->balance),
3540 'Account balance is the expected amount after partial payment of lost fee'
3543 # Return lost item with partial payment having been made
3544 ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid );
3546 $lost_fee_line->discard_changes;
3548 is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero after returning lost item with full payment' );
3549 is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set for lost item with partial payment' );
3551 int($patron->account->balance),
3553 'Account balance should be zero after returning item with lost fee when full payment has been made'
3557 subtest 'lostreturn | false' => sub {
3560 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false });
3562 my $item = $builder->build_sample_item(
3564 replacementprice => $replacement_amount
3569 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, $ten_days_ago );
3571 # Fake fines cronjob on this checkout
3573 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3574 $ten_days_ago, $now );
3577 issue_id => $issue->issue_id,
3578 itemnumber => $item->itemnumber,
3579 borrowernumber => $patron->borrowernumber,
3581 due => output_pref($ten_days_ago)
3584 my $overdue_fees = Koha::Account::Lines->search(
3586 borrowernumber => $patron->id,
3587 itemnumber => $item->itemnumber,
3588 debit_type_code => 'OVERDUE'
3591 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3592 my $overdue_fee = $overdue_fees->next;
3593 is( $overdue_fee->amount + 0,
3594 10, 'The right OVERDUE amount is generated' );
3595 is( $overdue_fee->amountoutstanding + 0,
3597 'The right OVERDUE amountoutstanding is generated' );
3599 # Simulate item marked as lost
3600 $item->itemlost(3)->store;
3601 C4::Circulation::LostItem( $item->itemnumber, 1 );
3603 my $lost_fee_lines = Koha::Account::Lines->search(
3605 borrowernumber => $patron->id,
3606 itemnumber => $item->itemnumber,
3607 debit_type_code => 'LOST'
3610 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3611 my $lost_fee_line = $lost_fee_lines->next;
3612 is( $lost_fee_line->amount + 0,
3613 $replacement_amount, 'The right LOST amount is generated' );
3614 is( $lost_fee_line->amountoutstanding + 0,
3615 $replacement_amount,
3616 'The right LOST amountoutstanding is generated' );
3617 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3620 my ( $returned, $message ) =
3621 AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago );
3623 $overdue_fee->discard_changes;
3624 is( $overdue_fee->amount + 0,
3625 10, 'The OVERDUE amount is left intact' );
3626 is( $overdue_fee->amountoutstanding + 0,
3628 'The OVERDUE amountoutstanding is left intact' );
3630 $lost_fee_line->discard_changes;
3631 is( $lost_fee_line->amount + 0,
3632 $replacement_amount, 'The LOST amount is left intact' );
3633 is( $lost_fee_line->amountoutstanding + 0,
3634 $replacement_amount,
3635 'The LOST amountoutstanding is left intact' );
3636 # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not?
3637 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3640 subtest 'lostreturn | refund' => sub {
3643 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund });
3645 my $item = $builder->build_sample_item(
3647 replacementprice => $replacement_amount
3652 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, $ten_days_ago );
3654 # Fake fines cronjob on this checkout
3656 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3657 $ten_days_ago, $now );
3660 issue_id => $issue->issue_id,
3661 itemnumber => $item->itemnumber,
3662 borrowernumber => $patron->borrowernumber,
3664 due => output_pref($ten_days_ago)
3667 my $overdue_fees = Koha::Account::Lines->search(
3669 borrowernumber => $patron->id,
3670 itemnumber => $item->itemnumber,
3671 debit_type_code => 'OVERDUE'
3674 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3675 my $overdue_fee = $overdue_fees->next;
3676 is( $overdue_fee->amount + 0,
3677 10, 'The right OVERDUE amount is generated' );
3678 is( $overdue_fee->amountoutstanding + 0,
3680 'The right OVERDUE amountoutstanding is generated' );
3682 # Simulate item marked as lost
3683 $item->itemlost(3)->store;
3684 C4::Circulation::LostItem( $item->itemnumber, 1 );
3686 my $lost_fee_lines = Koha::Account::Lines->search(
3688 borrowernumber => $patron->id,
3689 itemnumber => $item->itemnumber,
3690 debit_type_code => 'LOST'
3693 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3694 my $lost_fee_line = $lost_fee_lines->next;
3695 is( $lost_fee_line->amount + 0,
3696 $replacement_amount, 'The right LOST amount is generated' );
3697 is( $lost_fee_line->amountoutstanding + 0,
3698 $replacement_amount,
3699 'The right LOST amountoutstanding is generated' );
3700 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3702 # Return the lost item
3703 my ( undef, $message ) =
3704 AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago );
3706 $overdue_fee->discard_changes;
3707 is( $overdue_fee->amount + 0,
3708 10, 'The OVERDUE amount is left intact' );
3709 is( $overdue_fee->amountoutstanding + 0,
3711 'The OVERDUE amountoutstanding is left intact' );
3713 $lost_fee_line->discard_changes;
3714 is( $lost_fee_line->amount + 0,
3715 $replacement_amount, 'The LOST amount is left intact' );
3716 is( $lost_fee_line->amountoutstanding + 0,
3718 'The LOST amountoutstanding is refunded' );
3719 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3722 subtest 'lostreturn | restore' => sub {
3725 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore });
3727 my $item = $builder->build_sample_item(
3729 replacementprice => $replacement_amount
3734 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode , $ten_days_ago);
3736 # Fake fines cronjob on this checkout
3738 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3739 $ten_days_ago, $now );
3742 issue_id => $issue->issue_id,
3743 itemnumber => $item->itemnumber,
3744 borrowernumber => $patron->borrowernumber,
3746 due => output_pref($ten_days_ago)
3749 my $overdue_fees = Koha::Account::Lines->search(
3751 borrowernumber => $patron->id,
3752 itemnumber => $item->itemnumber,
3753 debit_type_code => 'OVERDUE'
3756 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3757 my $overdue_fee = $overdue_fees->next;
3758 is( $overdue_fee->amount + 0,
3759 10, 'The right OVERDUE amount is generated' );
3760 is( $overdue_fee->amountoutstanding + 0,
3762 'The right OVERDUE amountoutstanding is generated' );
3764 # Simulate item marked as lost
3765 $item->itemlost(3)->store;
3766 C4::Circulation::LostItem( $item->itemnumber, 1 );
3768 my $lost_fee_lines = Koha::Account::Lines->search(
3770 borrowernumber => $patron->id,
3771 itemnumber => $item->itemnumber,
3772 debit_type_code => 'LOST'
3775 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3776 my $lost_fee_line = $lost_fee_lines->next;
3777 is( $lost_fee_line->amount + 0,
3778 $replacement_amount, 'The right LOST amount is generated' );
3779 is( $lost_fee_line->amountoutstanding + 0,
3780 $replacement_amount,
3781 'The right LOST amountoutstanding is generated' );
3782 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3784 # Simulate refunding overdue fees upon marking item as lost
3785 my $overdue_forgive = $patron->account->add_credit(
3788 user_id => $manager->borrowernumber,
3789 library_id => $branchcode_restore,
3790 interface => 'test',
3792 item_id => $item->itemnumber
3795 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3796 $overdue_fee->discard_changes;
3797 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3800 my ( undef, $message ) =
3801 AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago );
3803 $overdue_fee->discard_changes;
3804 is( $overdue_fee->amount + 0,
3805 10, 'The OVERDUE amount is left intact' );
3806 is( $overdue_fee->amountoutstanding + 0,
3808 'The OVERDUE amountoutstanding is restored' );
3810 $lost_fee_line->discard_changes;
3811 is( $lost_fee_line->amount + 0,
3812 $replacement_amount, 'The LOST amount is left intact' );
3813 is( $lost_fee_line->amountoutstanding + 0,
3815 'The LOST amountoutstanding is refunded' );
3816 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3819 subtest 'lostreturn | charge' => sub {
3822 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge });
3824 my $item = $builder->build_sample_item(
3826 replacementprice => $replacement_amount
3831 my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, $ten_days_ago );
3833 # Fake fines cronjob on this checkout
3835 CalcFine( $item, $patron->categorycode, $library->{branchcode},
3836 $ten_days_ago, $now );
3839 issue_id => $issue->issue_id,
3840 itemnumber => $item->itemnumber,
3841 borrowernumber => $patron->borrowernumber,
3843 due => output_pref($ten_days_ago)
3846 my $overdue_fees = Koha::Account::Lines->search(
3848 borrowernumber => $patron->id,
3849 itemnumber => $item->itemnumber,
3850 debit_type_code => 'OVERDUE'
3853 is( $overdue_fees->count, 1, 'Overdue item fee produced' );
3854 my $overdue_fee = $overdue_fees->next;
3855 is( $overdue_fee->amount + 0,
3856 10, 'The right OVERDUE amount is generated' );
3857 is( $overdue_fee->amountoutstanding + 0,
3859 'The right OVERDUE amountoutstanding is generated' );
3861 # Simulate item marked as lost
3862 $item->itemlost(3)->store;
3863 C4::Circulation::LostItem( $item->itemnumber, 1 );
3865 my $lost_fee_lines = Koha::Account::Lines->search(
3867 borrowernumber => $patron->id,
3868 itemnumber => $item->itemnumber,
3869 debit_type_code => 'LOST'
3872 is( $lost_fee_lines->count, 1, 'Lost item fee produced' );
3873 my $lost_fee_line = $lost_fee_lines->next;
3874 is( $lost_fee_line->amount + 0,
3875 $replacement_amount, 'The right LOST amount is generated' );
3876 is( $lost_fee_line->amountoutstanding + 0,
3877 $replacement_amount,
3878 'The right LOST amountoutstanding is generated' );
3879 is( $lost_fee_line->status, undef, 'The LOST status was not set' );
3881 # Simulate refunding overdue fees upon marking item as lost
3882 my $overdue_forgive = $patron->account->add_credit(
3885 user_id => $manager->borrowernumber,
3886 library_id => $branchcode_charge,
3887 interface => 'test',
3889 item_id => $item->itemnumber
3892 $overdue_forgive->apply( { debits => [$overdue_fee] } );
3893 $overdue_fee->discard_changes;
3894 is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven');
3897 my ( undef, $message ) =
3898 AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago );
3900 $lost_fee_line->discard_changes;
3901 is( $lost_fee_line->amount + 0,
3902 $replacement_amount, 'The LOST amount is left intact' );
3903 is( $lost_fee_line->amountoutstanding + 0,
3905 'The LOST amountoutstanding is refunded' );
3906 is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' );
3908 $overdue_fees = Koha::Account::Lines->search(
3910 borrowernumber => $patron->id,
3911 itemnumber => $item->itemnumber,
3912 debit_type_code => 'OVERDUE'
3915 order_by => { '-asc' => 'accountlines_id'}
3918 is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' );
3919 $overdue_fee = $overdue_fees->next;
3920 is( $overdue_fee->amount + 0,
3921 10, 'The original OVERDUE amount is left intact' );
3922 is( $overdue_fee->amountoutstanding + 0,
3924 'The original OVERDUE amountoutstanding is left as forgiven' );
3925 $overdue_fee = $overdue_fees->next;
3926 is( $overdue_fee->amount + 0,
3927 5, 'The new OVERDUE amount is correct for the backdated return' );
3928 is( $overdue_fee->amountoutstanding + 0,
3930 'The new OVERDUE amountoutstanding is correct for the backdated return' );
3935 subtest '_FixOverduesOnReturn' => sub {
3938 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3939 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3941 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3943 my $branchcode = $library2->{branchcode};
3945 my $item = $builder->build_sample_item(
3947 biblionumber => $biblio->biblionumber,
3948 library => $branchcode,
3949 replacementprice => 99.00,
3954 my $patron = $builder->build( { source => 'Borrower' } );
3956 ## Start with basic call, should just close out the open fine
3957 my $accountline = Koha::Account::Line->new(
3959 borrowernumber => $patron->{borrowernumber},
3960 debit_type_code => 'OVERDUE',
3961 status => 'UNRETURNED',
3962 itemnumber => $item->itemnumber,
3964 amountoutstanding => 99.00,
3965 interface => 'test',
3969 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
3971 $accountline->_result()->discard_changes();
3973 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
3974 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3975 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3977 ## Run again, with exemptfine enabled
3980 debit_type_code => 'OVERDUE',
3981 status => 'UNRETURNED',
3982 amountoutstanding => 99.00,
3986 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3988 $accountline->_result()->discard_changes();
3989 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'APPLY' })->next();
3991 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
3992 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3993 is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )');
3994 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
3995 is( $offset->amount + 0, -99, "Amount of offset is correct" );
3996 my $credit = $offset->credit;
3997 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
3998 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
3999 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
4001 # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
4004 debit_type_code => 'OVERDUE',
4005 status => 'UNRETURNED',
4006 amountoutstanding => 0.00,
4011 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
4013 $accountline->_result()->discard_changes();
4014 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'CREATE' })->next();
4015 is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
4016 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
4017 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
4020 subtest 'Set waiting flag' => sub {
4023 my $library_1 = $builder->build( { source => 'Branch' } );
4024 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
4025 my $library_2 = $builder->build( { source => 'Branch' } );
4026 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
4028 my $item = $builder->build_sample_item(
4030 library => $library_1->{branchcode},
4034 set_userenv( $library_2 );
4035 my $reserve_id = AddReserve(
4037 branchcode => $library_2->{branchcode},
4038 borrowernumber => $patron_2->{borrowernumber},
4039 biblionumber => $item->biblionumber,
4041 itemnumber => $item->itemnumber,
4045 set_userenv( $library_1 );
4046 my $do_transfer = 1;
4047 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
4048 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
4049 my $hold = Koha::Holds->find( $reserve_id );
4050 is( $hold->found, 'T', 'Hold is in transit' );
4052 my ( $status ) = CheckReserves($item);
4053 is( $status, 'Transferred', 'Hold is not waiting yet');
4055 set_userenv( $library_2 );
4057 AddReturn( $item->barcode, $library_2->{branchcode} );
4058 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
4059 $hold = Koha::Holds->find( $reserve_id );
4060 is( $hold->found, 'W', 'Hold is waiting' );
4061 ( $status ) = CheckReserves($item);
4062 is( $status, 'Waiting', 'Now the hold is waiting');
4064 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
4065 set_userenv( $library_1 );
4066 (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} );
4067 $hold = Koha::Holds->find( $reserve_id );
4068 is( $hold->found, undef, 'Hold is no longer marked waiting' );
4069 is( $hold->priority, 1, "Hold is now priority one again");
4070 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
4071 is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber");
4072 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
4073 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
4074 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
4077 subtest 'Cancel transfers on lost items' => sub {
4080 my $library_to = $builder->build_object( { class => 'Koha::Libraries' } );
4081 my $item = $builder->build_sample_item();
4082 my $holdingbranch = $item->holdingbranch;
4083 # Historic transfer (datearrived is defined)
4084 my $old_transfer = $builder->build_object(
4086 class => 'Koha::Item::Transfers',
4088 itemnumber => $item->itemnumber,
4089 frombranch => $holdingbranch,
4090 tobranch => $library_to->branchcode,
4092 datesent => \'NOW()',
4093 datearrived => \'NOW()',
4094 datecancelled => undef,
4095 daterequested => \'NOW()'
4099 # Queued transfer (datesent is undefined)
4100 my $transfer_1 = $builder->build_object(
4102 class => 'Koha::Item::Transfers',
4104 itemnumber => $item->itemnumber,
4105 frombranch => $holdingbranch,
4106 tobranch => $library_to->branchcode,
4109 datearrived => undef,
4110 datecancelled => undef,
4111 daterequested => \'NOW()'
4115 # In transit transfer (datesent is defined, datearrived and datecancelled are both undefined)
4116 my $transfer_2 = $builder->build_object(
4118 class => 'Koha::Item::Transfers',
4120 itemnumber => $item->itemnumber,
4121 frombranch => $holdingbranch,
4122 tobranch => $library_to->branchcode,
4124 datesent => \'NOW()',
4125 datearrived => undef,
4126 datecancelled => undef,
4127 daterequested => \'NOW()'
4132 # Simulate item being marked as lost
4133 $item->itemlost(1)->store;
4134 LostItem( $item->itemnumber, 'test', 1 );
4136 $transfer_1->discard_changes;
4137 isnt($transfer_1->datecancelled, undef, "Queud transfer was cancelled upon item lost");
4138 is($transfer_1->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
4139 $transfer_2->discard_changes;
4140 isnt($transfer_2->datecancelled, undef, "Active transfer was cancelled upon item lost");
4141 is($transfer_2->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'");
4142 $old_transfer->discard_changes;
4143 is($old_transfer->datecancelled, undef, "Old transfers are unaffected");
4144 $item->discard_changes;
4145 is($item->holdingbranch, $holdingbranch, "Items holding branch remains unchanged");
4148 subtest 'CanBookBeIssued | is_overdue' => sub {
4151 # Set a simple circ policy
4152 Koha::CirculationRules->set_rules(
4154 categorycode => undef,
4155 branchcode => undef,
4159 reservesallowed => 25,
4161 lengthunit => 'days',
4162 renewalsallowed => 1,
4164 norenewalbefore => undef,
4172 my $now = dt_from_string()->truncate( to => 'day' );
4173 my $five_days_go = $now->clone->add( days => 5 );
4174 my $ten_days_go = $now->clone->add( days => 10);
4175 my $library = $builder->build( { source => 'Branch' } );
4176 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
4178 my $item = $builder->build_sample_item(
4180 library => $library->{branchcode},
4184 my $issue = AddIssue( $patron, $item->barcode, $five_days_go ); # date due was 10d ago
4185 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
4186 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), output_pref({ str => $five_days_go, dateonly => 1}), "First issue works");
4187 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron, $item->barcode, $ten_days_go, undef, undef, undef);
4188 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
4189 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
4192 subtest 'ItemsDeniedRenewal rules are checked' => sub {
4195 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
4196 Koha::CirculationRules->set_rules(
4198 categorycode => '*',
4200 branchcode => $idr_lib->branchcode,
4202 reservesallowed => 25,
4204 lengthunit => 'days',
4205 renewalsallowed => 10,
4207 norenewalbefore => undef,
4215 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
4216 homebranch => $idr_lib->branchcode,
4219 location => 'NOPROC'
4223 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
4224 branchcode => $idr_lib->branchcode,
4227 my $future = dt_from_string->add( days => 1 );
4228 my $issue = $builder->build_object(
4230 class => 'Koha::Checkouts',
4232 returndate => undef,
4233 renewals_count => 0,
4235 borrowernumber => $idr_borrower->borrowernumber,
4236 itemnumber => $allow_book->itemnumber,
4237 onsite_checkout => 0,
4238 date_due => $future,
4243 my $mock_item_class = Test::MockModule->new("Koha::Item");
4244 $mock_item_class->mock( 'is_denied_renewal', sub { return 1; } );
4246 my ( $mayrenew, $error ) = CanBookBeRenewed( $idr_borrower, $issue );
4247 is( $mayrenew, 0, 'Renewal blocked when $item->is_denied_renewal returns true' );
4248 is( $error, 'item_denied_renewal', 'Renewal blocked when $item->is_denied_renewal returns true' );
4250 $mock_item_class->unmock( 'is_denied_renewal' );
4251 $mock_item_class->mock( 'is_denied_renewal', sub { return 0; } );
4253 ( $mayrenew, $error ) = CanBookBeRenewed( $idr_borrower, $issue );
4254 is( $mayrenew, 1, 'Renewal allowed when $item->is_denied_renewal returns false' );
4255 is( $error, undef, 'Renewal allowed when $item->is_denied_renewal returns false' );
4257 $mock_item_class->unmock( 'is_denied_renewal' );
4260 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
4263 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4264 my $library = $builder->build( { source => 'Branch' } );
4265 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4267 my $item = $builder->build_sample_item(
4269 library => $library->{branchcode},
4273 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4274 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4275 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4278 subtest 'CanBookBeIssued | notforloan' => sub {
4281 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
4283 my $library = $builder->build( { source => 'Branch' } );
4284 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
4286 my $itemtype = $builder->build(
4288 source => 'Itemtype',
4289 value => { notforloan => undef, }
4292 my $item = $builder->build_sample_item(
4294 library => $library->{branchcode},
4295 itype => $itemtype->{itemtype},
4298 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4300 my ( $issuingimpossible, $needsconfirmation );
4303 subtest 'item-level_itypes = 1' => sub {
4306 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
4307 # Is for loan at item type and item level
4308 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4309 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4310 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4312 # not for loan at item type level
4313 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4314 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4315 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4318 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4319 'Item can not be issued, not for loan at item type level'
4322 # not for loan at item level
4323 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4324 $item->notforloan( 1 )->store;
4325 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4326 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4329 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4330 'Item can not be issued, not for loan at item type level'
4334 subtest 'item-level_itypes = 0' => sub {
4337 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
4339 # We set another itemtype for biblioitem
4340 my $itemtype = $builder->build(
4342 source => 'Itemtype',
4343 value => { notforloan => undef, }
4347 # for loan at item type and item level
4348 $item->notforloan(0)->store;
4349 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
4350 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4351 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
4352 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
4354 # not for loan at item type level
4355 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
4356 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4357 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4360 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
4361 'Item can not be issued, not for loan at item type level'
4364 # not for loan at item level
4365 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
4366 $item->notforloan( 1 )->store;
4367 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
4368 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
4371 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
4372 'Item can not be issued, not for loan at item type level'
4376 # TODO test with AllowNotForLoanOverride = 1
4379 subtest 'CanBookBeIssued | recalls' => sub {
4382 t::lib::Mocks::mock_preference("UseRecalls", 1);
4383 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4384 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4385 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4386 my $item = $builder->build_sample_item;
4387 Koha::CirculationRules->set_rules({
4388 branchcode => undef,
4390 categorycode => undef,
4392 recalls_allowed => 10,
4397 my $recall = Koha::Recall->new(
4398 { patron_id => $patron1->borrowernumber,
4399 biblio_id => $item->biblionumber,
4400 item_id => $item->itemnumber,
4402 pickup_library_id => $patron1->branchcode,
4406 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4407 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed an item-level recall on this item" );
4409 $recall->set_cancelled;
4411 # biblio-level recall
4412 $recall = Koha::Recall->new(
4413 { patron_id => $patron1->borrowernumber,
4414 biblio_id => $item->biblionumber,
4417 pickup_library_id => $patron1->branchcode,
4421 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef );
4422 is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed a biblio-level recall and this item is eligible to fill it" );
4424 $recall->set_cancelled;
4426 # biblio-level recall
4427 $recall = Koha::Recall->new(
4428 { patron_id => $patron1->borrowernumber,
4429 biblio_id => $item->biblionumber,
4432 pickup_library_id => $patron1->branchcode,
4435 $recall->set_waiting( { item => $item, expirationdate => dt_from_string() } );
4437 my ( undef, undef, undef, $messages ) = CanBookBeIssued( $patron1, $item->barcode, undef, undef, undef, undef );
4438 is( $messages->{RECALLED}, $recall->id, "This book can be issued by this patron and they have placed a recall" );
4440 $recall->set_cancelled;
4443 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
4446 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
4447 my $item = $builder->build_sample_item(
4449 onloan => '2018-01-01',
4453 AddReturn( $item->barcode, $item->homebranch );
4454 $item->discard_changes; # refresh
4455 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
4458 subtest 'AddReturn | recalls' => sub {
4461 t::lib::Mocks::mock_preference("UseRecalls", 1);
4462 t::lib::Mocks::mock_preference("item-level_itypes", 1);
4463 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4464 my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
4465 my $item1 = $builder->build_sample_item;
4466 Koha::CirculationRules->set_rules({
4467 branchcode => undef,
4469 categorycode => undef,
4471 recalls_allowed => 10,
4475 # this item can fill a recall with pickup at this branch
4476 AddIssue( $patron1, $item1->barcode );
4477 my $recall1 = Koha::Recall->new(
4478 { patron_id => $patron2->borrowernumber,
4479 biblio_id => $item1->biblionumber,
4480 item_id => $item1->itemnumber,
4482 pickup_library_id => $item1->homebranch,
4485 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4486 is( $messages->{RecallFound}->id, $recall1->id, "Recall found" );
4487 $recall1->set_cancelled;
4489 # this item can fill a recall but needs transfer
4490 AddIssue( $patron1, $item1->barcode );
4491 $recall1 = Koha::Recall->new(
4492 { patron_id => $patron2->borrowernumber,
4493 biblio_id => $item1->biblionumber,
4494 item_id => $item1->itemnumber,
4496 pickup_library_id => $patron2->branchcode,
4499 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $item1->homebranch );
4500 is( $messages->{RecallNeedsTransfer}, $item1->homebranch, "Recall requiring transfer found" );
4501 $recall1->set_cancelled;
4503 # this item is already in transit, do not ask to transfer
4504 AddIssue( $patron1, $item1->barcode );
4505 $recall1 = Koha::Recall->new(
4506 { patron_id => $patron2->borrowernumber,
4507 biblio_id => $item1->biblionumber,
4508 item_id => $item1->itemnumber,
4510 pickup_library_id => $patron2->branchcode,
4513 $recall1->start_transfer;
4514 ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $item1->barcode, $patron2->branchcode );
4515 is( $messages->{TransferredRecall}->id, $recall1->id, "In transit recall found" );
4516 $recall1->set_cancelled;
4519 subtest 'AddReturn | bundles' => sub {
4522 my $schema = Koha::Database->schema;
4523 $schema->storage->txn_begin;
4525 my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
4526 my $host_item1 = $builder->build_sample_item;
4527 my $bundle_item1 = $builder->build_sample_item;
4528 $schema->resultset('ItemBundle')
4530 { host => $host_item1->itemnumber, item => $bundle_item1->itemnumber } );
4532 my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $bundle_item1->barcode, $bundle_item1->homebranch );
4533 is($messages->{InBundle}->id, $host_item1->id, 'AddReturn returns InBundle host item when item is part of a bundle');
4535 $schema->storage->txn_rollback;
4538 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
4543 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4545 my $issuing_charges = 15;
4546 my $title = 'A title';
4547 my $author = 'Author, An';
4548 my $barcode = 'WHATARETHEODDS';
4550 my $circ = Test::MockModule->new('C4::Circulation');
4552 'GetIssuingCharges',
4554 return $issuing_charges;
4558 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4559 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
4560 my $patron = $builder->build_object({
4561 class => 'Koha::Patrons',
4562 value => { branchcode => $library->id }
4565 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
4566 my $item_id = Koha::Item->new(
4568 biblionumber => $biblio->biblionumber,
4569 homebranch => $library->id,
4570 holdingbranch => $library->id,
4571 barcode => $barcode,
4572 replacementprice => 23.00,
4573 itype => $itemtype->id
4575 )->store->itemnumber;
4576 my $item = Koha::Items->find( $item_id );
4578 my $context = Test::MockModule->new('C4::Context');
4579 $context->mock( userenv => { branch => $library->id } );
4581 # Check the item out
4582 AddIssue( $patron, $item->barcode );
4587 borrowernumber => $patron->borrowernumber,
4588 itemnumber => $item->itemnumber,
4589 branch => $library->id,
4590 lastreneweddate => { break => "the_renewal" }
4593 } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
4595 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
4596 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
4597 my %params_renewal = (
4598 timestamp => { -like => $date . "%" },
4599 module => "CIRCULATION",
4600 action => "RENEWAL",
4602 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
4605 borrowernumber => $patron->id,
4606 itemnumber => $item->id,
4607 branch => $library->id
4610 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4611 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
4613 my $checkouts = $patron->checkouts;
4614 # The following will fail if run on 00:00:00
4615 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
4617 my $lines = Koha::Account::Lines->search({
4618 borrowernumber => $patron->id,
4619 itemnumber => $item->id
4622 is( $lines->count, 2 );
4624 my $line = $lines->next;
4625 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
4626 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
4627 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
4629 $line = $lines->next;
4630 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
4631 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
4632 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
4634 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
4636 $context = Test::MockModule->new('C4::Context');
4637 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
4639 my $now = dt_from_string;
4640 $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
4641 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
4642 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
4643 $sth->execute($item->id, $library->id);
4644 my ($old_stats_size) = $sth->fetchrow_array;
4647 borrowernumber => $patron->id,
4648 itemnumber => $item->id,
4649 branch => $library->id
4652 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
4653 $sth->execute($item->id, $library->id);
4654 my ($new_stats_size) = $sth->fetchrow_array;
4655 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
4656 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
4658 AddReturn( $item->id, $library->id, undef, $date );
4659 AddIssue( $patron, $item->barcode, $now );
4662 borrowernumber => $patron->id,
4663 itemnumber => $item->id,
4664 branch => $library->id,
4668 my $lines_skipped = Koha::Account::Lines->search({
4669 borrowernumber => $patron->id,
4670 itemnumber => $item->id
4672 is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
4676 subtest 'AddRenewal() adds to renewals' => sub {
4679 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4680 my $patron = $builder->build_object({
4681 class => 'Koha::Patrons',
4682 value => { branchcode => $library->id }
4685 my $item = $builder->build_sample_item();
4687 set_userenv( $library->unblessed );
4689 # Check the item out
4690 my $issue = AddIssue( $patron, $item->barcode );
4691 is(ref($issue), 'Koha::Checkout', 'Issue added');
4694 my $duedate = AddRenewal(
4696 borrowernumber => $patron->id,
4697 itemnumber => $item->id,
4698 branch => $library->id,
4703 ok( $duedate, "Renewal added" );
4705 my $renewals = Koha::Checkouts::Renewals->search({ checkout_id => $issue->issue_id });
4706 is($renewals->count, 1, 'One renewal added');
4707 my $THE_renewal = $renewals->next;
4708 is( $THE_renewal->renewer_id, C4::Context->userenv->{'number'}, 'Renewer recorded from context' );
4709 is( $THE_renewal->renewal_type, 'Automatic', 'AddRenewal "automatic" parameter sets renewal type to "Automatic"');
4712 subtest 'ProcessOfflinePayment() tests' => sub {
4719 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
4720 my $library = $builder->build_object({ class => 'Koha::Libraries' });
4721 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
4723 is( $result, 'Success.', 'The right string is returned' );
4725 my $lines = $patron->account->lines;
4726 is( $lines->count, 1, 'line created correctly');
4728 my $line = $lines->next;
4729 is( $line->amount+0, $amount * -1, 'amount picked from params' );
4730 is( $line->branchcode, $library->id, 'branchcode set correctly' );
4734 subtest 'Incremented fee tests' => sub {
4737 my $dt = dt_from_string();
4738 Time::Fake->offset( $dt->epoch );
4740 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
4742 my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store;
4744 $module->mock( 'userenv', sub { { branch => $library->id } } );
4746 my $patron = $builder->build_object(
4748 class => 'Koha::Patrons',
4749 value => { categorycode => $patron_category->{categorycode} }
4753 my $itemtype = $builder->build_object(
4755 class => 'Koha::ItemTypes',
4757 notforloan => undef,
4759 rentalcharge_daily => 1,
4760 rentalcharge_daily_calendar => 0
4765 my $item = $builder->build_sample_item(
4767 library => $library->id,
4768 itype => $itemtype->id,
4772 is( $itemtype->rentalcharge_daily + 0,1, 'Daily rental charge stored and retreived correctly' );
4773 is( $item->effective_itemtype, $itemtype->id, "Itemtype set correctly for item" );
4775 my $now = dt_from_string;
4776 my $dt_from = $now->clone;
4777 my $dt_to = $now->clone->add( days => 7 );
4778 my $dt_to_renew = $now->clone->add( days => 13 );
4782 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4783 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4785 $accountline->amount + 0,
4787 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
4789 $accountline->delete();
4792 borrowernumber => $patron->id,
4793 itemnumber => $item->id,
4794 branch => $library->id,
4795 datedue => $dt_to_renew,
4796 lastreneweddate => $dt_to
4799 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4801 $accountline->amount + 0,
4803 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
4805 $accountline->delete();
4808 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
4809 $itemtype->rentalcharge_daily_calendar(1)->store();
4811 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4812 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4814 $accountline->amount + 0,
4816 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
4818 $accountline->delete();
4821 borrowernumber => $patron->id,
4822 itemnumber => $item->id,
4823 branch => $library->id,
4824 datedue => $dt_to_renew,
4825 lastreneweddate => $dt_to
4828 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4830 $accountline->amount + 0,
4832 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
4834 $accountline->delete();
4837 my $calendar = C4::Calendar->new( branchcode => $library->id );
4838 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
4840 ( $dt_from->day_of_week == 6 ) ? 0
4841 : ( $dt_from->day_of_week == 7 ) ? 1
4842 : $dt_from->day_of_week + 1;
4843 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
4844 $calendar->insert_week_day_holiday(
4845 weekday => $closed_day,
4846 title => 'Test holiday',
4847 description => 'Test holiday'
4850 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4851 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4853 $accountline->amount + 0,
4855 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
4857 $accountline->delete();
4860 borrowernumber => $patron->id,
4861 itemnumber => $item->id,
4862 branch => $library->id,
4863 datedue => $dt_to_renew,
4864 lastreneweddate => $dt_to
4867 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4869 $accountline->amount + 0,
4871 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
4873 $accountline->delete();
4876 $itemtype->rentalcharge(2)->store;
4877 is( $itemtype->rentalcharge + 0, 2, 'Rental charge updated and retreived correctly' );
4879 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4881 Koha::Account::Lines->search( { itemnumber => $item->id } );
4882 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly" );
4883 $accountlines->delete();
4886 borrowernumber => $patron->id,
4887 itemnumber => $item->id,
4888 branch => $library->id,
4889 datedue => $dt_to_renew,
4890 lastreneweddate => $dt_to
4893 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
4894 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly, for renewal" );
4895 $accountlines->delete();
4897 $itemtype->rentalcharge(0)->store;
4898 is( $itemtype->rentalcharge + 0, 0, 'Rental charge reset and retreived correctly' );
4901 Koha::CirculationRules->set_rule(
4903 categorycode => $patron->categorycode,
4904 itemtype => $itemtype->id,
4905 branchcode => $library->id,
4906 rule_name => 'lengthunit',
4907 rule_value => 'hours',
4911 $itemtype->rentalcharge_hourly('0.25')->store();
4912 is( $itemtype->rentalcharge_hourly, '0.25', 'Hourly rental charge stored and retreived correctly' );
4914 $dt_to = $now->clone->add( hours => 168 );
4915 $dt_to_renew = $now->clone->add( hours => 312 );
4917 $itemtype->rentalcharge_hourly_calendar(0)->store();
4919 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4920 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4922 $accountline->amount + 0,
4924 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)"
4926 $accountline->delete();
4929 borrowernumber => $patron->id,
4930 itemnumber => $item->id,
4931 branch => $library->id,
4932 datedue => $dt_to_renew,
4933 lastreneweddate => $dt_to
4936 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4938 $accountline->amount + 0,
4940 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)"
4942 $accountline->delete();
4945 $itemtype->rentalcharge_hourly_calendar(1)->store();
4947 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4948 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4950 $accountline->amount + 0,
4952 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)"
4954 $accountline->delete();
4957 borrowernumber => $patron->id,
4958 itemnumber => $item->id,
4959 branch => $library->id,
4960 datedue => $dt_to_renew,
4961 lastreneweddate => $dt_to
4964 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4966 $accountline->amount + 0,
4968 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u"
4970 $accountline->delete();
4973 $calendar->delete_holiday( weekday => $closed_day );
4975 AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from );
4976 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4978 $accountline->amount + 0,
4980 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u"
4982 $accountline->delete();
4985 borrowernumber => $patron->id,
4986 itemnumber => $item->id,
4987 branch => $library->id,
4988 datedue => $dt_to_renew,
4989 lastreneweddate => $dt_to
4992 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4994 $accountline->amount + 0,
4996 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)"
4998 $accountline->delete();
5003 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
5006 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
5007 t::lib::Mocks::mock_preference('item-level_itypes', 1);
5010 $builder->build_object( { class => 'Koha::Libraries' } )->store;
5011 my $patron = $builder->build_object(
5013 class => 'Koha::Patrons',
5014 value => { categorycode => $patron_category->{categorycode} }
5018 my $itemtype = $builder->build_object(
5020 class => 'Koha::ItemTypes',
5024 rentalcharge_daily => 0
5029 my $item = $builder->build_sample_item(
5031 library => $library->id,
5035 itype => $itemtype->id,
5039 my ( $issuingimpossible, $needsconfirmation );
5040 my $dt_from = dt_from_string();
5041 my $dt_due = $dt_from->clone->add( days => 3 );
5043 $itemtype->rentalcharge(1)->store;
5044 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
5045 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
5046 $itemtype->rentalcharge('0')->store;
5047 $itemtype->rentalcharge_daily(1)->store;
5048 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
5049 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
5050 $itemtype->rentalcharge_daily('0')->store;
5053 subtest 'CanBookBeIssued & CircConfirmItemParts' => sub {
5056 t::lib::Mocks::mock_preference('CircConfirmItemParts', 1);
5058 my $patron = $builder->build_object(
5060 class => 'Koha::Patrons',
5061 value => { categorycode => $patron_category->{categorycode} }
5065 my $item = $builder->build_sample_item(
5067 materials => 'includes DVD',
5071 my $dt_due = dt_from_string->add( days => 3 );
5073 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
5074 is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' );
5077 subtest 'Do not return on renewal (LOST charge)' => sub {
5080 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
5081 my $library = $builder->build_object( { class => "Koha::Libraries" } );
5082 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
5083 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
5085 my $biblio = $builder->build_sample_biblio;
5087 my $item = $builder->build_sample_item(
5089 biblionumber => $biblio->biblionumber,
5090 library => $library->branchcode,
5091 replacementprice => 99.00,
5096 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
5097 AddIssue( $patron, $item->barcode );
5099 my $accountline = Koha::Account::Line->new(
5101 borrowernumber => $patron->borrowernumber,
5102 debit_type_code => 'LOST',
5104 itemnumber => $item->itemnumber,
5106 amountoutstanding => 12,
5107 interface => 'something',
5111 # AddRenewal doesn't call _FixAccountForLostAndFound
5112 AddIssue( $patron, $item->barcode );
5114 is( $patron->checkouts->count, 1,
5115 'Renewal should not return the item even if a LOST payment has been made earlier'
5119 subtest 'Filling a hold should cancel existing transfer' => sub {
5122 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
5124 my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
5125 my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
5126 my $patron = $builder->build_object(
5128 class => 'Koha::Patrons',
5130 categorycode => $patron_category->{categorycode},
5131 branchcode => $libraryA->branchcode,
5136 my $item = $builder->build_sample_item({
5137 homebranch => $libraryB->branchcode,
5140 my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
5141 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
5143 branchcode => $libraryA->branchcode,
5144 borrowernumber => $patron->borrowernumber,
5145 biblionumber => $item->biblionumber,
5146 itemnumber => $item->itemnumber
5148 my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
5149 is( $reserves->count, 1, "Reserve is placed");
5150 ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
5151 my $reserve = $reserves->next;
5152 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
5153 $reserve->discard_changes;
5154 ok( $reserve->found eq 'W', "Reserve is marked waiting" );
5155 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
5158 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub {
5162 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
5163 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5164 my $patron = $builder->build_object(
5166 class => 'Koha::Patrons',
5167 value => { categorycode => $patron_category->{categorycode} }
5171 my $biblionumber = $builder->build_sample_biblio(
5173 branchcode => $library->branchcode,
5177 # And the circulation rule
5178 Koha::CirculationRules->search->delete;
5179 Koha::CirculationRules->set_rules(
5181 categorycode => undef,
5183 branchcode => undef,
5186 lengthunit => 'days',
5192 source => 'CirculationRule',
5194 branchcode => undef,
5195 categorycode => undef,
5197 rule_name => 'lostreturn',
5198 rule_value => 'refund'
5203 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5206 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5207 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5209 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5211 my $item = $builder->build_sample_item(
5213 biblionumber => $biblionumber,
5214 library => $library->branchcode,
5215 replacementprice => '42',
5218 my $issue = AddIssue( $patron, $item->barcode );
5219 LostItem( $item->itemnumber, 'cli', 0 );
5220 $item->_result->itemlost(1);
5221 $item->_result->itemlost_on( $lost_on );
5222 $item->_result->update();
5224 my $a = Koha::Account::Lines->search(
5226 itemnumber => $item->id,
5227 borrowernumber => $patron->borrowernumber
5230 ok( $a, "Found accountline for lost fee" );
5231 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5232 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5233 $a = $a->get_from_storage;
5234 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5238 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5241 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5242 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5244 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5246 my $item = $builder->build_sample_item(
5248 biblionumber => $biblionumber,
5249 library => $library->branchcode,
5250 replacementprice => '42',
5253 my $issue = AddIssue( $patron, $item->barcode );
5254 LostItem( $item->itemnumber, 'cli', 0 );
5255 $item->_result->itemlost(1);
5256 $item->_result->itemlost_on( $lost_on );
5257 $item->_result->update();
5259 my $a = Koha::Account::Lines->search(
5261 itemnumber => $item->id,
5262 borrowernumber => $patron->borrowernumber
5265 ok( $a, "Found accountline for lost fee" );
5266 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5267 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5268 $a = $a->get_from_storage;
5269 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5273 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5276 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5277 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5279 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5281 my $item = $builder->build_sample_item(
5283 biblionumber => $biblionumber,
5284 library => $library->branchcode,
5285 replacementprice => '42',
5288 my $issue = AddIssue( $patron, $item->barcode );
5289 LostItem( $item->itemnumber, 'cli', 0 );
5290 $item->_result->itemlost(1);
5291 $item->_result->itemlost_on( $lost_on );
5292 $item->_result->update();
5294 my $a = Koha::Account::Lines->search(
5296 itemnumber => $item->id,
5297 borrowernumber => $patron->borrowernumber
5300 ok( $a, "Found accountline for lost fee" );
5301 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5302 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5303 $a = $a->get_from_storage;
5304 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5308 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5311 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5312 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5314 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5316 my $item = $builder->build_sample_item(
5318 biblionumber => $biblionumber,
5319 library => $library->branchcode,
5320 replacementprice => '42',
5323 my $issue = AddIssue( $patron, $item->barcode );
5324 LostItem( $item->itemnumber, 'cli', 0 );
5325 $item->_result->itemlost(1);
5326 $item->_result->itemlost_on( $lost_on );
5327 $item->_result->update();
5329 my $a = Koha::Account::Lines->search(
5331 itemnumber => $item->id,
5332 borrowernumber => $patron->borrowernumber
5336 ok( $a, "Found accountline for lost fee" );
5337 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5338 my ( $doreturn, $messages ) = AddReturn( $item->barcode, $library->branchcode, undef, dt_from_string );
5339 $a = $a->get_from_storage;
5340 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5345 subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub {
5349 t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0);
5350 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5351 my $patron = $builder->build_object(
5353 class => 'Koha::Patrons',
5354 value => { categorycode => $patron_category->{categorycode} }
5357 my $patron2 = $builder->build_object(
5359 class => 'Koha::Patrons',
5360 value => { categorycode => $patron_category->{categorycode} }
5364 my $biblionumber = $builder->build_sample_biblio(
5366 branchcode => $library->branchcode,
5370 # And the circulation rule
5371 Koha::CirculationRules->search->delete;
5372 Koha::CirculationRules->set_rules(
5374 categorycode => undef,
5376 branchcode => undef,
5379 lengthunit => 'days',
5385 source => 'CirculationRule',
5387 branchcode => undef,
5388 categorycode => undef,
5390 rule_name => 'lostreturn',
5391 rule_value => 'refund'
5396 subtest 'NoRefundOnLostReturnedItemsAge = undef' => sub {
5399 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5400 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', undef );
5402 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5404 my $item = $builder->build_sample_item(
5406 biblionumber => $biblionumber,
5407 library => $library->branchcode,
5408 replacementprice => '42',
5411 my $issue = AddIssue( $patron, $item->barcode );
5412 LostItem( $item->itemnumber, 'cli', 0 );
5413 $item->_result->itemlost(1);
5414 $item->_result->itemlost_on( $lost_on );
5415 $item->_result->update();
5417 my $a = Koha::Account::Lines->search(
5419 itemnumber => $item->id,
5420 borrowernumber => $patron->borrowernumber
5423 ok( $a, "Found accountline for lost fee" );
5424 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5425 $issue = AddIssue( $patron2, $item->barcode );
5426 $a = $a->get_from_storage;
5427 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5432 subtest 'NoRefundOnLostReturnedItemsAge > length of days item has been lost' => sub {
5435 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5436 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5438 my $lost_on = dt_from_string->subtract( days => 6 )->date;
5440 my $item = $builder->build_sample_item(
5442 biblionumber => $biblionumber,
5443 library => $library->branchcode,
5444 replacementprice => '42',
5447 my $issue = AddIssue( $patron, $item->barcode );
5448 LostItem( $item->itemnumber, 'cli', 0 );
5449 $item->_result->itemlost(1);
5450 $item->_result->itemlost_on( $lost_on );
5451 $item->_result->update();
5453 my $a = Koha::Account::Lines->search(
5455 itemnumber => $item->id,
5456 borrowernumber => $patron->borrowernumber
5459 ok( $a, "Found accountline for lost fee" );
5460 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5461 $issue = AddIssue( $patron2, $item->barcode );
5462 $a = $a->get_from_storage;
5463 is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" );
5467 subtest 'NoRefundOnLostReturnedItemsAge = length of days item has been lost' => sub {
5470 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5471 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5473 my $lost_on = dt_from_string->subtract( days => 7 )->date;
5475 my $item = $builder->build_sample_item(
5477 biblionumber => $biblionumber,
5478 library => $library->branchcode,
5479 replacementprice => '42',
5482 my $issue = AddIssue( $patron, $item->barcode );
5483 LostItem( $item->itemnumber, 'cli', 0 );
5484 $item->_result->itemlost(1);
5485 $item->_result->itemlost_on( $lost_on );
5486 $item->_result->update();
5488 my $a = Koha::Account::Lines->search(
5490 itemnumber => $item->id,
5491 borrowernumber => $patron->borrowernumber
5494 ok( $a, "Found accountline for lost fee" );
5495 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5496 $issue = AddIssue( $patron2, $item->barcode );
5497 $a = $a->get_from_storage;
5498 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5502 subtest 'NoRefundOnLostReturnedItemsAge < length of days item has been lost' => sub {
5505 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
5506 t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', 7 );
5508 my $lost_on = dt_from_string->subtract( days => 8 )->date;
5510 my $item = $builder->build_sample_item(
5512 biblionumber => $biblionumber,
5513 library => $library->branchcode,
5514 replacementprice => '42',
5517 my $issue = AddIssue( $patron, $item->barcode );
5518 LostItem( $item->itemnumber, 'cli', 0 );
5519 $item->_result->itemlost(1);
5520 $item->_result->itemlost_on( $lost_on );
5521 $item->_result->update();
5523 my $a = Koha::Account::Lines->search(
5525 itemnumber => $item->id,
5526 borrowernumber => $patron->borrowernumber
5530 ok( $a, "Found accountline for lost fee" );
5531 is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" );
5532 $issue = AddIssue( $patron2, $item->barcode );
5533 $a = $a->get_from_storage;
5534 is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" );
5539 subtest 'transferbook tests' => sub {
5543 { C4::Circulation::transferbook({}); }
5544 'Koha::Exceptions::MissingParameter',
5545 'Koha::Patron->store raises an exception on missing params';
5548 { C4::Circulation::transferbook({to_branch=>'anything'}); }
5549 'Koha::Exceptions::MissingParameter',
5550 'Koha::Patron->store raises an exception on missing params';
5553 { C4::Circulation::transferbook({from_branch=>'anything'}); }
5554 'Koha::Exceptions::MissingParameter',
5555 'Koha::Patron->store raises an exception on missing params';
5557 my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'});
5558 is( $doreturn, 0, "No return without barcode");
5559 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5560 is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" );
5562 ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'});
5563 is( $doreturn, 0, "No return without barcode");
5564 ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed");
5565 is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" );
5569 subtest 'Checkout should correctly terminate a transfer' => sub {
5572 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5573 my $patron_1 = $builder->build_object(
5575 class => 'Koha::Patrons',
5576 value => { branchcode => $library_1->branchcode }
5579 my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
5580 my $patron_2 = $builder->build_object(
5582 class => 'Koha::Patrons',
5583 value => { branchcode => $library_2->branchcode }
5587 my $item = $builder->build_sample_item(
5589 library => $library_1->branchcode,
5593 t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } );
5594 my $reserve_id = AddReserve(
5596 branchcode => $library_2->branchcode,
5597 borrowernumber => $patron_2->borrowernumber,
5598 biblionumber => $item->biblionumber,
5599 itemnumber => $item->itemnumber,
5604 my $do_transfer = 1;
5605 ModItemTransfer( $item->itemnumber, $library_1->branchcode,
5606 $library_2->branchcode, 'Manual' );
5607 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
5608 GetOtherReserves( $item->itemnumber )
5609 ; # To put the Reason, it's what does returns.pl...
5610 my $hold = Koha::Holds->find($reserve_id);
5611 is( $hold->found, 'T', 'Hold is in transit' );
5612 my $transfer = $item->get_transfer;
5613 is( $transfer->frombranch, $library_1->branchcode );
5614 is( $transfer->tobranch, $library_2->branchcode );
5615 is( $transfer->reason, 'Reserve' );
5617 t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } );
5618 AddIssue( $patron_1, $item->barcode );
5619 $transfer = $transfer->get_from_storage;
5620 isnt( $transfer->datearrived, undef );
5621 $hold = $hold->get_from_storage;
5622 is( $hold->found, undef, 'Hold is waiting' );
5623 is( $hold->priority, 1, );
5626 subtest 'AddIssue records staff who checked out item if appropriate' => sub {
5629 $module->mock( 'userenv', sub { { branch => $library->{id} } } );
5631 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5632 my $patron = $builder->build_object(
5634 class => 'Koha::Patrons',
5635 value => { categorycode => $patron_category->{categorycode} }
5638 my $issuer = $builder->build_object(
5640 class => 'Koha::Patrons',
5641 value => { categorycode => $patron_category->{categorycode} }
5644 my $item_1 = $builder->build_sample_item(
5646 library => $library->{branchcode}
5650 my $item_2 = $builder->build_sample_item(
5652 library => $library->branchcode
5656 $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->borrowernumber } } );
5658 my $dt_from = dt_from_string();
5659 my $dt_to = dt_from_string()->add( days => 7 );
5661 my $issue_1 = AddIssue( $patron, $item_1->barcode, $dt_to, undef, $dt_from );
5663 is( $issue_1->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" );
5665 t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1);
5668 AddIssue( $patron, $item_2->barcode, $dt_to, undef, $dt_from );
5670 is( $issue_2->issuer->borrowernumber, $issuer->borrowernumber, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" );
5673 subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub {
5676 my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
5677 my $patron_1 = $builder->build_object(
5679 class => 'Koha::Patrons',
5680 value => { branchcode => $library_1->branchcode }
5683 my $patron_2 = $builder->build_object(
5685 class => 'Koha::Patrons',
5686 value => { branchcode => $library_1->branchcode }
5690 my $item = $builder->build_sample_item(
5692 library => $library_1->branchcode,
5696 AddIssue( $patron_1, $item->barcode );
5697 ok( $item->get_from_storage->onloan, "Item's onloan column is set after initial checkout" );
5698 AddIssue( $patron_2, $item->barcode );
5699 ok( $item->get_from_storage->onloan, "Item's onloan column is set after second checkout" );
5702 subtest "updateWrongTransfer tests" => sub {
5705 my $library1 = $builder->build_object( { class => 'Koha::Libraries' } );
5706 my $library2 = $builder->build_object( { class => 'Koha::Libraries' } );
5707 my $library3 = $builder->build_object( { class => 'Koha::Libraries' } );
5708 my $item = $builder->build_sample_item(
5710 homebranch => $library1->branchcode,
5711 holdingbranch => $library2->branchcode,
5712 datelastseen => undef
5716 my $transfer = $builder->build_object(
5718 class => 'Koha::Item::Transfers',
5720 itemnumber => $item->itemnumber,
5721 frombranch => $library2->branchcode,
5722 tobranch => $library1->branchcode,
5723 daterequested => dt_from_string,
5724 datesent => dt_from_string,
5725 datecancelled => undef,
5726 datearrived => undef,
5731 is( ref($transfer), 'Koha::Item::Transfer', 'Mock transfer added' );
5733 my $new_transfer = C4::Circulation::updateWrongTransfer($item->itemnumber, $library1->branchcode);
5734 is(ref($new_transfer), 'Koha::Item::Transfer', "updateWrongTransfer returns a 'Koha::Item::Transfer' object");
5735 ok( !$new_transfer->in_transit, "New transfer is NOT created as in transit (or cancelled)");
5737 my $original_transfer = $transfer->get_from_storage;
5738 ok( defined($original_transfer->datecancelled), "Original transfer was cancelled");
5739 is( $original_transfer->cancellation_reason, 'WrongTransfer', "Original transfer cancellation reason is 'WrongTransfer'");
5742 subtest "SendCirculationAlert" => sub {
5745 # When you would unsuspectingly call this unit test (with perl, not prove), you will be bitten by LOCK.
5746 # LOCK will commit changes and ruin your data
5747 # In order to prevent that, we will add KOHA_TESTING to $ENV; see further Circulation.pm
5748 $ENV{KOHA_TESTING} = 1;
5750 # Setup branch, borrowr, and notice
5751 my $library = $builder->build_object({ class => 'Koha::Libraries' });
5752 set_userenv( $library->unblessed);
5753 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
5754 C4::Members::Messaging::SetMessagingPreference({
5755 borrowernumber => $patron->id,
5756 message_transport_types => ['sms'],
5757 message_attribute_id => 5
5759 my $item = $builder->build_sample_item();
5760 my $checkin_notice = $builder->build_object({
5761 class => 'Koha::Notice::Templates',
5763 module => 'circulation',
5765 branchcode => $library->branchcode,
5766 name => 'Test Checkin',
5768 content => "Checkins:\n----\n[% biblio.title %]-[% old_checkout.issue_id %]\n----Thank you.",
5769 message_transport_type => 'sms',
5774 # Checkout an item, mark it returned, generate a notice
5775 my $issue_1 = AddIssue( $patron, $item->barcode);
5776 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5777 C4::Circulation::SendCirculationAlert({
5779 item => $item->unblessed,
5780 borrower => $patron->unblessed,
5781 branch => $library->branchcode,
5784 my $notice = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'CHECKIN' });
5785 is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\nThank you.", 'Letter generated with expected output on first checkin' );
5786 is($notice->to_address, $patron->smsalertnumber, "Letter has the correct to_address set to smsalertnumber for SMS type notices");
5788 # Checkout an item, mark it returned, generate a notice
5789 my $issue_2 = AddIssue( $patron, $item->barcode);
5790 MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} );
5791 C4::Circulation::SendCirculationAlert({
5793 item => $item->unblessed,
5794 borrower => $patron->unblessed,
5795 branch => $library->branchcode,
5798 $notice->discard_changes();
5799 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' );
5803 subtest "GetSoonestRenewDate tests" => sub {
5805 Koha::CirculationRules->set_rule(
5807 categorycode => undef,
5808 branchcode => undef,
5810 rule_name => 'norenewalbefore',
5814 my $patron = $builder->build_object(
5816 class => 'Koha::Patrons',
5818 autorenew_checkouts => 1,
5822 my $item = $builder->build_sample_item();
5823 my $issue = AddIssue( $patron, $item->barcode);
5824 my $datedue = dt_from_string( $issue->date_due() );
5827 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
5828 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
5830 GetSoonestRenewDate( $patron, $issue ),
5831 $datedue->clone->add( days => -7 ),
5832 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5836 # Test 'date' setting for syspref NoRenewalBeforePrecision
5837 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5839 GetSoonestRenewDate( $patron, $issue ),
5840 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
5841 'Bug 14395: Renewals permitted 7 days before due date, as expected'
5845 Koha::CirculationRules->set_rule(
5847 categorycode => undef,
5848 branchcode => undef,
5850 rule_name => 'norenewalbefore',
5851 rule_value => undef,
5856 GetSoonestRenewDate( $patron, $issue ),
5858 'Checkouts without auto-renewal can be renewed immediately if no norenewalbefore'
5861 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5862 $issue->auto_renew(1)->store;
5864 GetSoonestRenewDate( $patron, $issue ),
5865 $datedue->clone->truncate( to => 'day' ),
5866 'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5868 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact' );
5870 GetSoonestRenewDate( $patron, $issue ),
5872 'Checkouts with auto-renewal can be renewed earliest on due date if no renewalbefore'
5875 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
5876 Koha::CirculationRules->set_rule(
5878 categorycode => undef,
5879 branchcode => undef,
5881 rule_name => 'norenewalbefore',
5885 $issue->date_due(dt_from_string)->store;
5887 GetSoonestRenewDate( $patron, $issue ),
5888 dt_from_string->subtract( days => 1 )->truncate( to => 'day' ),
5889 'Checkouts with auto-renewal can be renewed 1 day before due date if no renewalbefore = 1 and precision = "date"'
5894 subtest "CanBookBeIssued + needsconfirmation message" => sub {
5897 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
5898 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
5899 my $biblio = $builder->build_object({ class => 'Koha::Biblios' });
5900 my $biblioitem = $builder->build_object({ class => 'Koha::Biblioitems', value => { biblionumber => $biblio->biblionumber }});
5901 my $item = $builder->build_object({ class => 'Koha::Items' , value => { itype => $itemtype, biblionumber => $biblio->biblionumber }});
5903 my $hold = $builder->build_object({ class => 'Koha::Holds', value => {
5904 biblionumber => $item->biblionumber,
5905 branchcode => $library->branchcode,
5906 itemnumber => undef,
5911 item_group_id => undef
5914 my ( $error, $needsconfirmation, $alerts, $messages );
5916 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5917 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold exists.");
5919 $hold->priority(0)->store();
5921 $hold->found("W")->store();
5922 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5923 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is waiting.");
5925 $hold->found("T")->store();
5926 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5927 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is being transferred.");
5929 $hold->found("P")->store();
5930 ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode );
5931 is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is being processed.");
5934 subtest 'Tests for BlockReturnOfWithdrawnItems' => sub {
5938 t::lib::Mocks::mock_preference('BlockReturnOfWithdrawnItems', 1);
5939 t::lib::Mocks::mock_preference('RecordLocalUseOnReturn', 0);
5940 my $item = $builder->build_sample_item();
5941 $item->withdrawn(1)->itemlost(1)->store;
5942 my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef );
5945 [ 0, { NotIssued => $item->barcode, withdrawn => 1 }, undef, {} ], "Item returned as withdrawn, no other messages");
5948 subtest 'Tests for transfer not in transit' => sub {
5953 # These tests are to ensure a 'pending' transfer, generated by
5954 # stock rotation, will be advanced when checked in
5956 my $item = $builder->build_sample_item();
5957 my $transfer = $builder->build_object({ class => 'Koha::Item::Transfers', value => {
5958 itemnumber => $item->id,
5959 reason => 'StockrotationRepatriation',
5961 frombranch => $item->homebranch,
5963 my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef );
5966 [ 0, { WasTransfered => $transfer->tobranch, TransferTrigger => 'StockrotationRepatriation', NotIssued => $item->barcode }, undef, {} ], "Item is reported to have been transferred");
5968 $transfer->discard_changes;
5969 ok( $transfer->datesent, 'The datesent field is populated, i.e. transfer is initiated');
5973 subtest 'Tests for RecordLocalUseOnReturn' => sub {
5977 t::lib::Mocks::mock_preference('RecordLocalUseOnReturn', 0);
5978 my $item = $builder->build_sample_item();
5979 $item->withdrawn(1)->itemlost(1)->store;
5980 my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef );
5983 [ 0, { NotIssued => $item->barcode, withdrawn => 1 }, undef, {} ], "RecordLocalUSeOnReturn is off, no local use recorded");
5985 t::lib::Mocks::mock_preference('RecordLocalUseOnReturn', 1);
5986 my @return2 = AddReturn( $item->barcode, $item->homebranch, 0, undef );
5989 [ 0, { NotIssued => $item->barcode, withdrawn => 1, LocalUse => 1 }, undef, {} ], "Local use is recorded");
5992 $schema->storage->txn_rollback;
5993 C4::Context->clear_syspref_cache();
5994 $branches = Koha::Libraries->search();
5995 for my $branch ( $branches->next ) {
5996 my $key = $branch->branchcode . "_holidays";
5997 $cache->clear_from_cache($key);