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 => 48;
24 use Test::Deep qw( cmp_deeply );
29 use POSIX qw( floor );
31 use t::lib::TestBuilder;
40 use C4::Overdues qw(UpdateFine CalcFine);
44 use Koha::Item::Transfers;
48 use Koha::CirculationRules;
49 use Koha::Subscriptions;
50 use Koha::Account::Lines;
51 use Koha::Account::Offsets;
56 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
60 my ( $error, $question, $alert ) = @_;
62 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
63 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
64 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
68 sub test_debarment_on_checkout {
70 my $item = $params->{item};
71 my $library = $params->{library};
72 my $patron = $params->{patron};
73 my $due_date = $params->{due_date} || dt_from_string;
74 my $return_date = $params->{return_date} || dt_from_string;
75 my $expected_expiration_date = $params->{expiration_date};
77 $expected_expiration_date = output_pref(
79 dt => $expected_expiration_date,
85 my $line_number = $caller[2];
86 AddIssue( $patron, $item->{barcode}, $due_date );
88 my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode}, undef, $return_date );
89 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
90 or diag('AddReturn returned message ' . Dumper $message );
91 my $debarments = Koha::Patron::Debarments::GetDebarments(
92 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
93 is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
95 is( $debarments->[0]->{expiration},
96 $expected_expiration_date, 'Test at line ' . $line_number );
97 Koha::Patron::Debarments::DelUniqueDebarment(
98 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
101 my $schema = Koha::Database->schema;
102 $schema->storage->txn_begin;
103 my $builder = t::lib::TestBuilder->new;
104 my $dbh = C4::Context->dbh;
106 # Prevent random failures by mocking ->now
107 my $now_value = dt_from_string;
108 my $mocked_datetime = Test::MockModule->new('DateTime');
109 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
111 my $cache = Koha::Caches->get_instance();
112 $dbh->do(q|DELETE FROM special_holidays|);
113 $dbh->do(q|DELETE FROM repeatable_holidays|);
114 my $branches = Koha::Libraries->search();
115 for my $branch ( $branches->next ) {
116 my $key = $branch->branchcode . "_holidays";
117 $cache->clear_from_cache($key);
120 # Start with a clean slate
121 $dbh->do('DELETE FROM issues');
122 $dbh->do('DELETE FROM borrowers');
124 my $library = $builder->build({
127 my $library2 = $builder->build({
130 my $itemtype = $builder->build(
132 source => 'Itemtype',
136 rentalcharge_daily => 0,
137 defaultreplacecost => undef,
142 my $patron_category = $builder->build(
144 source => 'Category',
146 category_type => 'P',
148 BlockExpiredPatronOpacActions => -1, # Pick the pref value
153 my $CircControl = C4::Context->preference('CircControl');
154 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
157 homebranch => $library2->{branchcode},
158 holdingbranch => $library2->{branchcode}
162 branchcode => $library2->{branchcode}
165 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
167 # No userenv, PickupLibrary
168 t::lib::Mocks::mock_preference('IndependentBranches', '0');
169 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
171 C4::Context->preference('CircControl'),
173 'CircControl changed to PickupLibrary'
176 C4::Circulation::_GetCircControlBranch($item, $borrower),
177 $item->{$HomeOrHoldingBranch},
178 '_GetCircControlBranch returned item branch (no userenv defined)'
181 # No userenv, PatronLibrary
182 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
184 C4::Context->preference('CircControl'),
186 'CircControl changed to PatronLibrary'
189 C4::Circulation::_GetCircControlBranch($item, $borrower),
190 $borrower->{branchcode},
191 '_GetCircControlBranch returned borrower branch'
194 # No userenv, ItemHomeLibrary
195 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
197 C4::Context->preference('CircControl'),
199 'CircControl changed to ItemHomeLibrary'
202 $item->{$HomeOrHoldingBranch},
203 C4::Circulation::_GetCircControlBranch($item, $borrower),
204 '_GetCircControlBranch returned item branch'
208 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
209 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
211 # Userenv set, PickupLibrary
212 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
214 C4::Context->preference('CircControl'),
216 'CircControl changed to PickupLibrary'
219 C4::Circulation::_GetCircControlBranch($item, $borrower),
220 $library2->{branchcode},
221 '_GetCircControlBranch returned current branch'
224 # Userenv set, PatronLibrary
225 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
227 C4::Context->preference('CircControl'),
229 'CircControl changed to PatronLibrary'
232 C4::Circulation::_GetCircControlBranch($item, $borrower),
233 $borrower->{branchcode},
234 '_GetCircControlBranch returned borrower branch'
237 # Userenv set, ItemHomeLibrary
238 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
240 C4::Context->preference('CircControl'),
242 'CircControl changed to ItemHomeLibrary'
245 C4::Circulation::_GetCircControlBranch($item, $borrower),
246 $item->{$HomeOrHoldingBranch},
247 '_GetCircControlBranch returned item branch'
250 # Reset initial configuration
251 t::lib::Mocks::mock_preference('CircControl', $CircControl);
253 C4::Context->preference('CircControl'),
255 'CircControl reset to its initial value'
258 # Set a simple circ policy
259 $dbh->do('DELETE FROM circulation_rules');
260 Koha::CirculationRules->set_rules(
262 categorycode => undef,
266 reservesallowed => 25,
268 lengthunit => 'days',
269 renewalsallowed => 1,
271 norenewalbefore => undef,
279 subtest "GetIssuingCharges tests" => sub {
281 my $branch_discount = $builder->build_object({ class => 'Koha::Libraries' });
282 my $branch_no_discount = $builder->build_object({ class => 'Koha::Libraries' });
283 Koha::CirculationRules->set_rule(
285 categorycode => undef,
286 branchcode => $branch_discount->branchcode,
288 rule_name => 'rentaldiscount',
292 my $itype_charge = $builder->build_object({
293 class => 'Koha::ItemTypes',
298 my $itype_no_charge = $builder->build_object({
299 class => 'Koha::ItemTypes',
304 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
305 my $item_1 = $builder->build_sample_item({ itype => $itype_charge->itemtype });
306 my $item_2 = $builder->build_sample_item({ itype => $itype_no_charge->itemtype });
308 t::lib::Mocks::mock_userenv({ branchcode => $branch_no_discount->branchcode });
309 # For now the sub always uses the env branch, this should follow CircControl instead
310 my ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
311 is( $charge + 0, 10.00, "Charge fetched correctly when no discount exists");
312 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
313 is( $charge + 0, 0.00, "Charge fetched correctly when no discount exists and no charge");
315 t::lib::Mocks::mock_userenv({ branchcode => $branch_discount->branchcode });
316 # For now the sub always uses the env branch, this should follow CircControl instead
317 ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber);
318 is( $charge + 0, 8.50, "Charge fetched correctly when discount exists");
319 ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber);
320 is( $charge + 0, 0.00, "Charge fetched correctly when discount exists and no charge");
324 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
325 subtest "CanBookBeRenewed tests" => sub {
328 C4::Context->set_preference('ItemsDeniedRenewal','');
329 # Generate test biblio
330 my $biblio = $builder->build_sample_biblio();
332 my $branch = $library2->{branchcode};
334 my $item_1 = $builder->build_sample_item(
336 biblionumber => $biblio->biblionumber,
338 replacementprice => 12.00,
342 $reused_itemnumber_1 = $item_1->itemnumber;
344 my $item_2 = $builder->build_sample_item(
346 biblionumber => $biblio->biblionumber,
348 replacementprice => 23.00,
352 $reused_itemnumber_2 = $item_2->itemnumber;
354 my $item_3 = $builder->build_sample_item(
356 biblionumber => $biblio->biblionumber,
358 replacementprice => 23.00,
364 my %renewing_borrower_data = (
366 surname => 'Renewal',
367 categorycode => $patron_category->{categorycode},
368 branchcode => $branch,
371 my %reserving_borrower_data = (
372 firstname => 'Katrin',
373 surname => 'Reservation',
374 categorycode => $patron_category->{categorycode},
375 branchcode => $branch,
378 my %hold_waiting_borrower_data = (
380 surname => 'Reservation',
381 categorycode => $patron_category->{categorycode},
382 branchcode => $branch,
385 my %restricted_borrower_data = (
386 firstname => 'Alice',
387 surname => 'Reservation',
388 categorycode => $patron_category->{categorycode},
389 debarred => '3228-01-01',
390 branchcode => $branch,
393 my %expired_borrower_data = (
396 categorycode => $patron_category->{categorycode},
397 branchcode => $branch,
398 dateexpiry => dt_from_string->subtract( months => 1 ),
401 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
402 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
403 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
404 my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
405 my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
407 my $renewing_borrower_obj = Koha::Patrons->find( $renewing_borrowernumber );
408 my $renewing_borrower = $renewing_borrower_obj->unblessed;
409 my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
410 my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
417 my $checkitem = undef;
420 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
421 my $datedue = dt_from_string( $issue->date_due() );
422 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
424 my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
425 $datedue = dt_from_string( $issue->date_due() );
426 is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
429 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
430 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
432 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
433 is( $renewokay, 1, 'Can renew, no holds for this title or item');
436 # Biblio-level hold, renewal test
439 branchcode => $branch,
440 borrowernumber => $reserving_borrowernumber,
441 biblionumber => $biblio->biblionumber,
442 priority => $priority,
443 reservation_date => $resdate,
444 expiration_date => $expdate,
446 itemnumber => $checkitem,
451 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
452 Koha::CirculationRules->set_rule(
454 categorycode => undef,
457 rule_name => 'onshelfholds',
461 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
462 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
463 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
464 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
465 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
467 # Now let's add an item level hold, we should no longer be able to renew the item
468 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
470 borrowernumber => $hold_waiting_borrowernumber,
471 biblionumber => $biblio->biblionumber,
472 itemnumber => $item_1->itemnumber,
473 branchcode => $branch,
477 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
478 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
481 # 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
482 # be able to renew these items
483 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
485 borrowernumber => $hold_waiting_borrowernumber,
486 biblionumber => $biblio->biblionumber,
487 itemnumber => $item_3->itemnumber,
488 branchcode => $branch,
493 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
494 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
495 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
496 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
497 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
499 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
500 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
501 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
503 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
504 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
505 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
507 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
508 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
509 AddIssue($reserving_borrower, $item_3->barcode);
510 my $reserve = $dbh->selectrow_hashref(
511 'SELECT * FROM old_reserves WHERE reserve_id = ?',
515 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
517 # Item-level hold, renewal test
520 branchcode => $branch,
521 borrowernumber => $reserving_borrowernumber,
522 biblionumber => $biblio->biblionumber,
523 priority => $priority,
524 reservation_date => $resdate,
525 expiration_date => $expdate,
527 itemnumber => $item_1->itemnumber,
532 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
533 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
534 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
536 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
537 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
539 # Items can't fill hold for reasons
540 $item_1->notforloan(1)->store;
541 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
542 is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
543 $item_1->set({notforloan => 0, itype => $itemtype })->store;
545 # FIXME: Add more for itemtype not for loan etc.
547 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
548 my $item_5 = $builder->build_sample_item(
550 biblionumber => $biblio->biblionumber,
552 replacementprice => 23.00,
556 my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
557 is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
559 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
560 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
561 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
562 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
563 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
565 # Users cannot renew an overdue item
566 my $item_6 = $builder->build_sample_item(
568 biblionumber => $biblio->biblionumber,
570 replacementprice => 23.00,
575 my $item_7 = $builder->build_sample_item(
577 biblionumber => $biblio->biblionumber,
579 replacementprice => 23.00,
584 my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
585 is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
587 my $now = dt_from_string();
588 my $five_weeks = DateTime::Duration->new(weeks => 5);
589 my $five_weeks_ago = $now - $five_weeks;
590 t::lib::Mocks::mock_preference('finesMode', 'production');
592 my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
593 is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
595 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
596 C4::Overdues::UpdateFine(
598 issue_id => $passeddatedue1->id(),
599 itemnumber => $item_7->itemnumber,
600 borrowernumber => $renewing_borrower->{borrowernumber},
602 due => Koha::DateUtils::output_pref($five_weeks_ago)
606 t::lib::Mocks::mock_preference('RenewalLog', 0);
607 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
608 my %params_renewal = (
609 timestamp => { -like => $date . "%" },
610 module => "CIRCULATION",
614 timestamp => { -like => $date . "%" },
615 module => "CIRCULATION",
618 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
619 my $dt = dt_from_string();
620 Time::Fake->offset( $dt->epoch );
621 my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
622 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
623 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
624 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
627 t::lib::Mocks::mock_preference('RenewalLog', 1);
628 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
629 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
630 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
631 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
632 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
634 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
635 is( $fines->count, 2, 'AddRenewal left both fines' );
636 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
637 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
641 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
642 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
643 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
644 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
645 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
646 $new_log_size = Koha::ActionLogs->count( \%params_issue );
647 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
649 $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
652 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
653 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
654 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
655 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
656 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
659 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
663 # Test automatic renewal before value for "norenewalbefore" in policy is set
664 # In this case automatic renewal is not permitted prior to due date
665 my $item_4 = $builder->build_sample_item(
667 biblionumber => $biblio->biblionumber,
669 replacementprice => 16.00,
674 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
675 ( $renewokay, $error ) =
676 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
677 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
678 is( $error, 'auto_too_soon',
679 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
682 branchcode => $branch,
683 borrowernumber => $reserving_borrowernumber,
684 biblionumber => $biblio->biblionumber,
685 itemnumber => $bibitems,
686 priority => $priority,
687 reservation_date => $resdate,
688 expiration_date => $expdate,
691 itemnumber => $item_4->itemnumber,
695 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
696 is( $renewokay, 0, 'Still should not be able to renew' );
697 is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' );
698 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, undef, 1 );
699 is( $renewokay, 0, 'Still should not be able to renew' );
700 is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' );
701 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
702 is( $renewokay, 0, 'Still should not be able to renew' );
703 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
704 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1, 1 );
705 is( $renewokay, 0, 'Still should not be able to renew' );
706 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
707 $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
708 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
709 is( $renewokay, 0, 'Still should not be able to renew' );
710 is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
711 ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
715 $renewing_borrower_obj->autorenew_checkouts(0)->store;
716 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
717 is( $renewokay, 1, 'No renewal before is undef, but patron opted out of auto_renewal' );
718 $renewing_borrower_obj->autorenew_checkouts(1)->store;
722 # Test premature manual renewal
723 Koha::CirculationRules->set_rule(
725 categorycode => undef,
728 rule_name => 'norenewalbefore',
733 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
734 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
735 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
738 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
739 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
741 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
742 $datedue->clone->add( days => -7 ),
743 'Bug 14395: Renewals permitted 7 days before due date, as expected'
747 # Test 'date' setting for syspref NoRenewalBeforePrecision
748 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
750 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
751 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
752 'Bug 14395: Renewals permitted 7 days before due date, as expected'
756 # Test premature automatic renewal
757 ( $renewokay, $error ) =
758 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
759 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
760 is( $error, 'auto_too_soon',
761 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
764 $renewing_borrower_obj->autorenew_checkouts(0)->store;
765 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
766 is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' );
767 is( $error, 'too_soon', 'Error is too_soon, no auto' );
768 $renewing_borrower_obj->autorenew_checkouts(1)->store;
770 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
771 # and test automatic renewal again
772 $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'});
773 ( $renewokay, $error ) =
774 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
775 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
776 is( $error, 'auto_too_soon',
777 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
780 $renewing_borrower_obj->autorenew_checkouts(0)->store;
781 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
782 is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' );
783 is( $error, 'too_soon', 'Error is too_soon, no auto' );
784 $renewing_borrower_obj->autorenew_checkouts(1)->store;
786 # Change policy so that loans can be renewed 99 days prior to the due date
787 # and test automatic renewal again
788 $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'});
789 ( $renewokay, $error ) =
790 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
791 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
792 is( $error, 'auto_renew',
793 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
796 $renewing_borrower_obj->autorenew_checkouts(0)->store;
797 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
798 is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' );
799 $renewing_borrower_obj->autorenew_checkouts(1)->store;
801 subtest "too_late_renewal / no_auto_renewal_after" => sub {
803 my $item_to_auto_renew = $builder->build(
806 biblionumber => $biblio->biblionumber,
807 homebranch => $branch,
808 holdingbranch => $branch,
813 my $ten_days_before = dt_from_string->add( days => -10 );
814 my $ten_days_ahead = dt_from_string->add( days => 10 );
815 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
817 Koha::CirculationRules->set_rules(
819 categorycode => undef,
823 norenewalbefore => '7',
824 no_auto_renewal_after => '9',
828 ( $renewokay, $error ) =
829 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
830 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
831 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
833 Koha::CirculationRules->set_rules(
835 categorycode => undef,
839 norenewalbefore => '7',
840 no_auto_renewal_after => '10',
844 ( $renewokay, $error ) =
845 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
846 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
847 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
849 Koha::CirculationRules->set_rules(
851 categorycode => undef,
855 norenewalbefore => '7',
856 no_auto_renewal_after => '11',
860 ( $renewokay, $error ) =
861 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
862 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
863 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
865 Koha::CirculationRules->set_rules(
867 categorycode => undef,
871 norenewalbefore => '10',
872 no_auto_renewal_after => '11',
876 ( $renewokay, $error ) =
877 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
878 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
879 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
881 Koha::CirculationRules->set_rules(
883 categorycode => undef,
887 norenewalbefore => '10',
888 no_auto_renewal_after => undef,
889 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
893 ( $renewokay, $error ) =
894 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
895 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
896 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
898 Koha::CirculationRules->set_rules(
900 categorycode => undef,
904 norenewalbefore => '7',
905 no_auto_renewal_after => '15',
906 no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ),
910 ( $renewokay, $error ) =
911 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
912 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
913 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
915 Koha::CirculationRules->set_rules(
917 categorycode => undef,
921 norenewalbefore => '10',
922 no_auto_renewal_after => undef,
923 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ),
927 ( $renewokay, $error ) =
928 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
929 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
930 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
933 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
935 my $item_to_auto_renew = $builder->build({
938 biblionumber => $biblio->biblionumber,
939 homebranch => $branch,
940 holdingbranch => $branch,
944 my $ten_days_before = dt_from_string->add( days => -10 );
945 my $ten_days_ahead = dt_from_string->add( days => 10 );
946 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
948 Koha::CirculationRules->set_rules(
950 categorycode => undef,
954 norenewalbefore => '10',
955 no_auto_renewal_after => '11',
959 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
960 C4::Context->set_preference('OPACFineNoRenewals','10');
961 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
962 my $fines_amount = 5;
963 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
966 amount => $fines_amount,
969 item_id => $item_to_auto_renew->{itemnumber},
970 description => "Some fines"
972 )->status('RETURNED')->store;
973 ( $renewokay, $error ) =
974 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
975 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
976 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
980 amount => $fines_amount,
983 item_id => $item_to_auto_renew->{itemnumber},
984 description => "Some fines"
986 )->status('RETURNED')->store;
987 ( $renewokay, $error ) =
988 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
989 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
990 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
994 amount => $fines_amount,
997 item_id => $item_to_auto_renew->{itemnumber},
998 description => "Some fines"
1000 )->status('RETURNED')->store;
1001 ( $renewokay, $error ) =
1002 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1003 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1004 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
1006 $account->add_credit(
1008 amount => $fines_amount,
1009 interface => 'test',
1011 description => "Some payment"
1014 ( $renewokay, $error ) =
1015 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1016 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1017 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1019 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
1020 ( $renewokay, $error ) =
1021 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1022 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1023 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
1025 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
1026 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
1029 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
1031 my $item_to_auto_renew = $builder->build({
1034 biblionumber => $biblio->biblionumber,
1035 homebranch => $branch,
1036 holdingbranch => $branch,
1040 Koha::CirculationRules->set_rules(
1042 categorycode => undef,
1043 branchcode => undef,
1046 norenewalbefore => 10,
1047 no_auto_renewal_after => 11,
1052 my $ten_days_before = dt_from_string->add( days => -10 );
1053 my $ten_days_ahead = dt_from_string->add( days => 10 );
1055 # Patron is expired and BlockExpiredPatronOpacActions=0
1056 # => auto renew is allowed
1057 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
1058 my $patron = $expired_borrower;
1059 my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1060 ( $renewokay, $error ) =
1061 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
1062 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1063 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
1064 Koha::Checkouts->find( $checkout->issue_id )->delete;
1067 # Patron is expired and BlockExpiredPatronOpacActions=1
1068 # => auto renew is not allowed
1069 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1070 $patron = $expired_borrower;
1071 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1072 ( $renewokay, $error ) =
1073 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
1074 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1075 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
1076 Koha::Checkouts->find( $checkout->issue_id )->delete;
1079 # Patron is not expired and BlockExpiredPatronOpacActions=1
1080 # => auto renew is allowed
1081 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
1082 $patron = $renewing_borrower;
1083 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1084 ( $renewokay, $error ) =
1085 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
1086 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
1087 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
1088 Koha::Checkouts->find( $checkout->issue_id )->delete;
1091 subtest "GetLatestAutoRenewDate" => sub {
1093 my $item_to_auto_renew = $builder->build(
1096 biblionumber => $biblio->biblionumber,
1097 homebranch => $branch,
1098 holdingbranch => $branch,
1103 my $ten_days_before = dt_from_string->add( days => -10 );
1104 my $ten_days_ahead = dt_from_string->add( days => 10 );
1105 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
1106 Koha::CirculationRules->set_rules(
1108 categorycode => undef,
1109 branchcode => undef,
1112 norenewalbefore => '7',
1113 no_auto_renewal_after => '',
1114 no_auto_renewal_after_hard_limit => undef,
1118 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1119 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' );
1120 my $five_days_before = dt_from_string->add( days => -5 );
1121 Koha::CirculationRules->set_rules(
1123 categorycode => undef,
1124 branchcode => undef,
1127 norenewalbefore => '10',
1128 no_auto_renewal_after => '5',
1129 no_auto_renewal_after_hard_limit => undef,
1133 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1134 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1135 $five_days_before->truncate( to => 'minute' ),
1136 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
1138 my $five_days_ahead = dt_from_string->add( days => 5 );
1139 $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'});
1140 $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'});
1141 $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'});
1142 Koha::CirculationRules->set_rules(
1144 categorycode => undef,
1145 branchcode => undef,
1148 norenewalbefore => '10',
1149 no_auto_renewal_after => '15',
1150 no_auto_renewal_after_hard_limit => undef,
1154 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1155 is( $latest_auto_renew_date->truncate( to => 'minute' ),
1156 $five_days_ahead->truncate( to => 'minute' ),
1157 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
1159 my $two_days_ahead = dt_from_string->add( days => 2 );
1160 Koha::CirculationRules->set_rules(
1162 categorycode => undef,
1163 branchcode => undef,
1166 norenewalbefore => '10',
1167 no_auto_renewal_after => '',
1168 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1172 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1173 is( $latest_auto_renew_date->truncate( to => 'day' ),
1174 $two_days_ahead->truncate( to => 'day' ),
1175 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
1177 Koha::CirculationRules->set_rules(
1179 categorycode => undef,
1180 branchcode => undef,
1183 norenewalbefore => '10',
1184 no_auto_renewal_after => '15',
1185 no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ),
1189 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
1190 is( $latest_auto_renew_date->truncate( to => 'day' ),
1191 $two_days_ahead->truncate( to => 'day' ),
1192 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
1198 # set policy to forbid renewals
1199 Koha::CirculationRules->set_rules(
1201 categorycode => undef,
1202 branchcode => undef,
1205 norenewalbefore => undef,
1206 renewalsallowed => 0,
1211 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
1212 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
1213 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
1215 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
1216 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
1217 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1219 C4::Overdues::UpdateFine(
1221 issue_id => $issue->id(),
1222 itemnumber => $item_1->itemnumber,
1223 borrowernumber => $renewing_borrower->{borrowernumber},
1226 due => Koha::DateUtils::output_pref($datedue)
1230 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
1231 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
1232 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
1233 is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
1234 is( $line->amount+0, 15, 'Account line amount is 15.00' );
1235 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
1237 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
1238 is( $offset->type, 'OVERDUE', 'Account offset type is Fine' );
1239 is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
1241 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
1242 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
1244 LostItem( $item_1->itemnumber, 'test', 1 );
1246 $line = Koha::Account::Lines->find($line->id);
1247 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
1248 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
1250 my $item = Koha::Items->find($item_1->itemnumber);
1251 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
1252 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
1253 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
1255 my $total_due = $dbh->selectrow_array(
1256 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1257 undef, $renewing_borrower->{borrowernumber}
1260 is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
1262 C4::Context->dbh->do("DELETE FROM accountlines");
1264 C4::Overdues::UpdateFine(
1266 issue_id => $issue2->id(),
1267 itemnumber => $item_2->itemnumber,
1268 borrowernumber => $renewing_borrower->{borrowernumber},
1271 due => Koha::DateUtils::output_pref($datedue)
1275 LostItem( $item_2->itemnumber, 'test', 0 );
1277 my $item2 = Koha::Items->find($item_2->itemnumber);
1278 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1279 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1281 $total_due = $dbh->selectrow_array(
1282 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1283 undef, $renewing_borrower->{borrowernumber}
1286 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1288 my $future = dt_from_string();
1289 $future->add( days => 7 );
1290 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1291 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1293 # Users cannot renew any item if there is an overdue item
1294 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
1295 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
1296 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1297 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
1298 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1300 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1301 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1302 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1303 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1304 LostItem( $item_3->itemnumber, 'test', 0 );
1305 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1306 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1308 $accountline->description,
1309 sprintf( "%s %s %s",
1310 $item_3->biblio->title || '',
1311 $item_3->barcode || '',
1312 $item_3->itemcallnumber || '' ),
1313 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1317 subtest "GetUpcomingDueIssues" => sub {
1320 my $branch = $library2->{branchcode};
1322 #Create another record
1323 my $biblio2 = $builder->build_sample_biblio();
1326 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1327 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1328 my $item_3 = $builder->build_sample_item(
1330 biblionumber => $biblio2->biblionumber,
1338 my %a_borrower_data = (
1339 firstname => 'Fridolyn',
1340 surname => 'SOMERS',
1341 categorycode => $patron_category->{categorycode},
1342 branchcode => $branch,
1345 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1346 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1348 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1349 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1350 my $today = DateTime->today(time_zone => C4::Context->tz());
1352 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1353 my $datedue = dt_from_string( $issue->date_due() );
1354 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1355 my $datedue2 = dt_from_string( $issue->date_due() );
1359 # GetUpcomingDueIssues tests
1361 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1362 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1365 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1366 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1367 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1370 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1371 is ( scalar( @$upcoming_dues ), 1,
1372 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1375 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1377 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1379 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1380 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1382 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1383 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1385 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1386 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1388 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1389 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1391 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1392 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1394 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1395 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1399 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1400 my $branch = $library2->{branchcode};
1402 my $biblio = $builder->build_sample_biblio();
1405 my $item = $builder->build_sample_item(
1407 biblionumber => $biblio->biblionumber,
1414 my %a_borrower_data = (
1415 firstname => 'Kyle',
1417 categorycode => $patron_category->{categorycode},
1418 branchcode => $branch,
1421 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1423 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1424 my $issue = AddIssue( $borrower, $item->barcode );
1427 issue_id => $issue->id(),
1428 itemnumber => $item->itemnumber,
1429 borrowernumber => $borrowernumber,
1435 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1436 my $count = $hr->{count};
1438 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1441 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1442 $dbh->do('DELETE FROM issues');
1443 $dbh->do('DELETE FROM items');
1444 $dbh->do('DELETE FROM circulation_rules');
1445 Koha::CirculationRules->set_rules(
1447 categorycode => undef,
1449 branchcode => undef,
1451 reservesallowed => 25,
1453 lengthunit => 'days',
1454 renewalsallowed => 1,
1456 norenewalbefore => undef,
1464 my $biblio = $builder->build_sample_biblio();
1466 my $item_1 = $builder->build_sample_item(
1468 biblionumber => $biblio->biblionumber,
1469 library => $library2->{branchcode},
1474 my $item_2= $builder->build_sample_item(
1476 biblionumber => $biblio->biblionumber,
1477 library => $library2->{branchcode},
1482 my $borrowernumber1 = Koha::Patron->new({
1483 firstname => 'Kyle',
1485 categorycode => $patron_category->{categorycode},
1486 branchcode => $library2->{branchcode},
1487 })->store->borrowernumber;
1488 my $borrowernumber2 = Koha::Patron->new({
1489 firstname => 'Chelsea',
1491 categorycode => $patron_category->{categorycode},
1492 branchcode => $library2->{branchcode},
1493 })->store->borrowernumber;
1495 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1496 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1498 my $issue = AddIssue( $borrower1, $item_1->barcode );
1500 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1501 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1505 branchcode => $library2->{branchcode},
1506 borrowernumber => $borrowernumber2,
1507 biblionumber => $biblio->biblionumber,
1512 Koha::CirculationRules->set_rules(
1514 categorycode => undef,
1516 branchcode => undef,
1522 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1523 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1524 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1526 Koha::CirculationRules->set_rules(
1528 categorycode => undef,
1530 branchcode => undef,
1536 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1537 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1538 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1540 Koha::CirculationRules->set_rules(
1542 categorycode => undef,
1544 branchcode => undef,
1550 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1551 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1552 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1554 Koha::CirculationRules->set_rules(
1556 categorycode => undef,
1558 branchcode => undef,
1564 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1565 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1566 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1568 # Setting item not checked out to be not for loan but holdable
1569 $item_2->notforloan(-1)->store;
1571 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1572 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' );
1576 # Don't allow renewing onsite checkout
1577 my $branch = $library->{branchcode};
1579 #Create another record
1580 my $biblio = $builder->build_sample_biblio();
1582 my $item = $builder->build_sample_item(
1584 biblionumber => $biblio->biblionumber,
1590 my $borrowernumber = Koha::Patron->new({
1593 categorycode => $patron_category->{categorycode},
1594 branchcode => $branch,
1595 })->store->borrowernumber;
1597 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1599 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1600 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1601 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1602 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1606 my $library = $builder->build({ source => 'Branch' });
1608 my $biblio = $builder->build_sample_biblio();
1610 my $item = $builder->build_sample_item(
1612 biblionumber => $biblio->biblionumber,
1613 library => $library->{branchcode},
1618 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1620 my $issue = AddIssue( $patron, $item->barcode );
1623 issue_id => $issue->id(),
1624 itemnumber => $item->itemnumber,
1625 borrowernumber => $patron->{borrowernumber},
1632 issue_id => $issue->id(),
1633 itemnumber => $item->itemnumber,
1634 borrowernumber => $patron->{borrowernumber},
1639 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1642 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1645 my $homebranch = $builder->build( { source => 'Branch' } );
1646 my $holdingbranch = $builder->build( { source => 'Branch' } );
1647 my $otherbranch = $builder->build( { source => 'Branch' } );
1648 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1649 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1651 my $item = $builder->build_sample_item(
1653 homebranch => $homebranch->{branchcode},
1654 holdingbranch => $holdingbranch->{branchcode},
1658 set_userenv($holdingbranch);
1660 my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1661 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1663 my ( $error, $question, $alerts );
1665 # AllowReturnToBranch == anywhere
1666 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1667 ## Test that unknown barcodes don't generate internal server errors
1668 set_userenv($homebranch);
1669 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1670 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1671 ## Can be issued from homebranch
1672 set_userenv($homebranch);
1673 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1674 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1675 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1676 ## Can be issued from holdingbranch
1677 set_userenv($holdingbranch);
1678 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1679 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1680 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1681 ## Can be issued from another branch
1682 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1683 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1684 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1686 # AllowReturnToBranch == holdingbranch
1687 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1688 ## Cannot be issued from homebranch
1689 set_userenv($homebranch);
1690 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1691 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1692 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1693 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1694 ## Can be issued from holdinbranch
1695 set_userenv($holdingbranch);
1696 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1697 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1698 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1699 ## Cannot be issued from another branch
1700 set_userenv($otherbranch);
1701 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1702 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1703 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1704 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
1706 # AllowReturnToBranch == homebranch
1707 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1708 ## Can be issued from holdinbranch
1709 set_userenv($homebranch);
1710 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1711 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1712 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1713 ## Cannot be issued from holdinbranch
1714 set_userenv($holdingbranch);
1715 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1716 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1717 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1718 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1719 ## Cannot be issued from holdinbranch
1720 set_userenv($otherbranch);
1721 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1722 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1723 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1724 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1726 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1729 subtest 'AddIssue & AllowReturnToBranch' => sub {
1732 my $homebranch = $builder->build( { source => 'Branch' } );
1733 my $holdingbranch = $builder->build( { source => 'Branch' } );
1734 my $otherbranch = $builder->build( { source => 'Branch' } );
1735 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1736 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1738 my $item = $builder->build_sample_item(
1740 homebranch => $homebranch->{branchcode},
1741 holdingbranch => $holdingbranch->{branchcode},
1745 set_userenv($holdingbranch);
1747 my $ref_issue = 'Koha::Checkout';
1748 my $issue = AddIssue( $patron_1, $item->{barcode} );
1750 my ( $error, $question, $alerts );
1752 # AllowReturnToBranch == homebranch
1753 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1754 ## Can be issued from homebranch
1755 set_userenv($homebranch);
1756 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
1757 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1758 ## Can be issued from holdinbranch
1759 set_userenv($holdingbranch);
1760 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
1761 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1762 ## Can be issued from another branch
1763 set_userenv($otherbranch);
1764 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
1765 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1767 # AllowReturnToBranch == holdinbranch
1768 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1769 ## Cannot be issued from homebranch
1770 set_userenv($homebranch);
1771 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
1772 ## Can be issued from holdingbranch
1773 set_userenv($holdingbranch);
1774 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
1775 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1776 ## Cannot be issued from another branch
1777 set_userenv($otherbranch);
1778 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
1780 # AllowReturnToBranch == homebranch
1781 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1782 ## Can be issued from homebranch
1783 set_userenv($homebranch);
1784 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
1785 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1786 ## Cannot be issued from holdinbranch
1787 set_userenv($holdingbranch);
1788 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
1789 ## Cannot be issued from another branch
1790 set_userenv($otherbranch);
1791 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
1792 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1795 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1798 my $library = $builder->build( { source => 'Branch' } );
1799 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1800 my $item_1 = $builder->build_sample_item(
1802 library => $library->{branchcode},
1805 my $item_2 = $builder->build_sample_item(
1807 library => $library->{branchcode},
1811 my ( $error, $question, $alerts );
1813 # Patron cannot issue item_1, they have overdues
1814 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1815 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday ); # Add an overdue
1817 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1818 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1819 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
1820 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1822 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1823 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1824 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1825 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1827 # Patron cannot issue item_1, they are debarred
1828 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1829 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1830 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1831 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1832 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1834 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1835 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1836 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1837 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1840 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1843 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1844 my $patron_category_x = $builder->build_object(
1846 class => 'Koha::Patron::Categories',
1847 value => { category_type => 'X' }
1850 my $patron = $builder->build_object(
1852 class => 'Koha::Patrons',
1854 categorycode => $patron_category_x->categorycode,
1855 gonenoaddress => undef,
1862 my $item_1 = $builder->build_sample_item(
1864 library => $library->{branchcode},
1868 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1869 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1871 # TODO There are other tests to provide here
1874 subtest 'MultipleReserves' => sub {
1877 my $biblio = $builder->build_sample_biblio();
1879 my $branch = $library2->{branchcode};
1881 my $item_1 = $builder->build_sample_item(
1883 biblionumber => $biblio->biblionumber,
1885 replacementprice => 12.00,
1890 my $item_2 = $builder->build_sample_item(
1892 biblionumber => $biblio->biblionumber,
1894 replacementprice => 12.00,
1901 my $resdate = undef;
1902 my $expdate = undef;
1904 my $checkitem = undef;
1907 my %renewing_borrower_data = (
1908 firstname => 'John',
1909 surname => 'Renewal',
1910 categorycode => $patron_category->{categorycode},
1911 branchcode => $branch,
1913 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1914 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1915 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1916 my $datedue = dt_from_string( $issue->date_due() );
1917 is (defined $issue->date_due(), 1, "item 1 checked out");
1918 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1920 my %reserving_borrower_data1 = (
1921 firstname => 'Katrin',
1922 surname => 'Reservation',
1923 categorycode => $patron_category->{categorycode},
1924 branchcode => $branch,
1926 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1929 branchcode => $branch,
1930 borrowernumber => $reserving_borrowernumber1,
1931 biblionumber => $biblio->biblionumber,
1932 priority => $priority,
1933 reservation_date => $resdate,
1934 expiration_date => $expdate,
1936 itemnumber => $checkitem,
1941 my %reserving_borrower_data2 = (
1942 firstname => 'Kirk',
1943 surname => 'Reservation',
1944 categorycode => $patron_category->{categorycode},
1945 branchcode => $branch,
1947 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1950 branchcode => $branch,
1951 borrowernumber => $reserving_borrowernumber2,
1952 biblionumber => $biblio->biblionumber,
1953 priority => $priority,
1954 reservation_date => $resdate,
1955 expiration_date => $expdate,
1957 itemnumber => $checkitem,
1963 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1964 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1967 my $item_3 = $builder->build_sample_item(
1969 biblionumber => $biblio->biblionumber,
1971 replacementprice => 12.00,
1977 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1978 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1982 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1985 my $library = $builder->build( { source => 'Branch' } );
1986 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1988 my $biblionumber = $builder->build_sample_biblio(
1990 branchcode => $library->{branchcode},
1993 my $item_1 = $builder->build_sample_item(
1995 biblionumber => $biblionumber,
1996 library => $library->{branchcode},
2000 my $item_2 = $builder->build_sample_item(
2002 biblionumber => $biblionumber,
2003 library => $library->{branchcode},
2007 my ( $error, $question, $alerts );
2008 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
2010 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2011 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
2013 { error => $error, alerts => $alerts },
2014 { error => {}, alerts => {} },
2015 'No error or alert should be raised'
2017 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' );
2019 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2020 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
2022 { error => $error, question => $question, alerts => $alerts },
2023 { error => {}, question => {}, alerts => {} },
2024 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1'
2027 # Add a subscription
2028 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
2030 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
2031 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
2033 { error => $error, question => $question, alerts => $alerts },
2034 { error => {}, question => {}, alerts => {} },
2035 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2038 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
2039 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
2041 { error => $error, question => $question, alerts => $alerts },
2042 { error => {}, question => {}, alerts => {} },
2043 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription'
2047 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
2050 my $library = $builder->build( { source => 'Branch' } );
2051 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2054 my $biblionumber = $builder->build_sample_biblio(
2056 branchcode => $library->{branchcode},
2059 my $item_1 = $builder->build_sample_item(
2061 biblionumber => $biblionumber,
2062 library => $library->{branchcode},
2065 my $item_2 = $builder->build_sample_item(
2067 biblionumber => $biblionumber,
2068 library => $library->{branchcode},
2072 # And the circulation rule
2073 Koha::CirculationRules->search->delete;
2074 Koha::CirculationRules->set_rules(
2076 categorycode => undef,
2078 branchcode => undef,
2081 firstremind => 1, # 1 day of grace
2082 finedays => 2, # 2 days of fine per day of overdue
2083 lengthunit => 'days',
2088 # Patron cannot issue item_1, they have overdues
2089 my $now = dt_from_string;
2090 my $five_days_ago = $now->clone->subtract( days => 5 );
2091 my $ten_days_ago = $now->clone->subtract( days => 10 );
2092 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
2093 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
2094 ; # Add another overdue
2096 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
2097 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, $now );
2098 my $debarments = Koha::Patron::Debarments::GetDebarments(
2099 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2100 is( scalar(@$debarments), 1 );
2102 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
2103 # Same for the others
2104 my $expected_expiration = output_pref(
2106 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2107 dateformat => 'sql',
2111 is( $debarments->[0]->{expiration}, $expected_expiration );
2113 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, $now );
2114 $debarments = Koha::Patron::Debarments::GetDebarments(
2115 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2116 is( scalar(@$debarments), 1 );
2117 $expected_expiration = output_pref(
2119 dt => $now->clone->add( days => ( 10 - 1 ) * 2 ),
2120 dateformat => 'sql',
2124 is( $debarments->[0]->{expiration}, $expected_expiration );
2126 Koha::Patron::Debarments::DelUniqueDebarment(
2127 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2129 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
2130 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
2131 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
2132 ; # Add another overdue
2133 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, $now );
2134 $debarments = Koha::Patron::Debarments::GetDebarments(
2135 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2136 is( scalar(@$debarments), 1 );
2137 $expected_expiration = output_pref(
2139 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
2140 dateformat => 'sql',
2144 is( $debarments->[0]->{expiration}, $expected_expiration );
2146 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, $now );
2147 $debarments = Koha::Patron::Debarments::GetDebarments(
2148 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2149 is( scalar(@$debarments), 1 );
2150 $expected_expiration = output_pref(
2152 dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
2153 dateformat => 'sql',
2157 is( $debarments->[0]->{expiration}, $expected_expiration );
2160 subtest 'AddReturn + suspension_chargeperiod' => sub {
2163 my $library = $builder->build( { source => 'Branch' } );
2164 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2166 my $biblionumber = $builder->build_sample_biblio(
2168 branchcode => $library->{branchcode},
2171 my $item_1 = $builder->build_sample_item(
2173 biblionumber => $biblionumber,
2174 library => $library->{branchcode},
2178 # And the issuing rule
2179 Koha::CirculationRules->search->delete;
2180 Koha::CirculationRules->set_rules(
2182 categorycode => '*',
2187 firstremind => 0, # 0 day of grace
2188 finedays => 2, # 2 days of fine per day of overdue
2189 suspension_chargeperiod => 1,
2190 lengthunit => 'days',
2195 my $now = dt_from_string;
2196 my $five_days_ago = $now->clone->subtract( days => 5 );
2197 # We want to charge 2 days every day, without grace
2198 # With 5 days of overdue: 5 * Z
2199 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2200 test_debarment_on_checkout(
2203 library => $library,
2205 due_date => $five_days_ago,
2206 expiration_date => $expected_expiration,
2210 # Same with undef firstremind
2211 Koha::CirculationRules->search->delete;
2212 Koha::CirculationRules->set_rules(
2214 categorycode => '*',
2219 firstremind => undef, # 0 day of grace
2220 finedays => 2, # 2 days of fine per day of overdue
2221 suspension_chargeperiod => 1,
2222 lengthunit => 'days',
2227 my $now = dt_from_string;
2228 my $five_days_ago = $now->clone->subtract( days => 5 );
2229 # We want to charge 2 days every day, without grace
2230 # With 5 days of overdue: 5 * Z
2231 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
2232 test_debarment_on_checkout(
2235 library => $library,
2237 due_date => $five_days_ago,
2238 expiration_date => $expected_expiration,
2242 # We want to charge 2 days every 2 days, without grace
2243 # With 5 days of overdue: (5 * 2) / 2
2244 Koha::CirculationRules->set_rule(
2246 categorycode => undef,
2247 branchcode => undef,
2249 rule_name => 'suspension_chargeperiod',
2254 $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
2255 test_debarment_on_checkout(
2258 library => $library,
2260 due_date => $five_days_ago,
2261 expiration_date => $expected_expiration,
2265 # We want to charge 2 days every 3 days, with 1 day of grace
2266 # With 5 days of overdue: ((5-1) / 3 ) * 2
2267 Koha::CirculationRules->set_rules(
2269 categorycode => undef,
2270 branchcode => undef,
2273 suspension_chargeperiod => 3,
2278 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
2279 test_debarment_on_checkout(
2282 library => $library,
2284 due_date => $five_days_ago,
2285 expiration_date => $expected_expiration,
2289 # Use finesCalendar to know if holiday must be skipped to calculate the due date
2290 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
2291 Koha::CirculationRules->set_rules(
2293 categorycode => undef,
2294 branchcode => undef,
2298 suspension_chargeperiod => 1,
2303 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
2304 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
2306 # Adding a holiday 2 days ago
2307 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
2308 my $two_days_ago = $now->clone->subtract( days => 2 );
2309 $calendar->insert_single_holiday(
2310 day => $two_days_ago->day,
2311 month => $two_days_ago->month,
2312 year => $two_days_ago->year,
2313 title => 'holidayTest-2d',
2314 description => 'holidayDesc 2 days ago'
2316 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
2317 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
2318 test_debarment_on_checkout(
2321 library => $library,
2323 due_date => $five_days_ago,
2324 expiration_date => $expected_expiration,
2328 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
2329 my $two_days_ahead = $now->clone->add( days => 2 );
2330 $calendar->insert_single_holiday(
2331 day => $two_days_ahead->day,
2332 month => $two_days_ahead->month,
2333 year => $two_days_ahead->year,
2334 title => 'holidayTest+2d',
2335 description => 'holidayDesc 2 days ahead'
2338 # Same as above, but we should skip D+2
2339 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
2340 test_debarment_on_checkout(
2343 library => $library,
2345 due_date => $five_days_ago,
2346 expiration_date => $expected_expiration,
2350 # Adding another holiday, day of expiration date
2351 my $expected_expiration_dt = dt_from_string($expected_expiration);
2352 $calendar->insert_single_holiday(
2353 day => $expected_expiration_dt->day,
2354 month => $expected_expiration_dt->month,
2355 year => $expected_expiration_dt->year,
2356 title => 'holidayTest_exp',
2357 description => 'holidayDesc on expiration date'
2359 # Expiration date will be the day after
2360 test_debarment_on_checkout(
2363 library => $library,
2365 due_date => $five_days_ago,
2366 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
2370 test_debarment_on_checkout(
2373 library => $library,
2375 return_date => $now->clone->add(days => 5),
2376 expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
2380 test_debarment_on_checkout(
2383 library => $library,
2385 due_date => $now->clone->add(days => 1),
2386 return_date => $now->clone->add(days => 5),
2387 expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
2393 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
2396 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2397 my $patron1 = $builder->build_object(
2399 class => 'Koha::Patrons',
2401 library => $library->branchcode,
2402 categorycode => $patron_category->{categorycode}
2406 my $patron2 = $builder->build_object(
2408 class => 'Koha::Patrons',
2410 library => $library->branchcode,
2411 categorycode => $patron_category->{categorycode}
2416 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2418 my $item = $builder->build_sample_item(
2420 library => $library->branchcode,
2424 my ( $error, $question, $alerts );
2425 my $issue = AddIssue( $patron1->unblessed, $item->{barcode} );
2427 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2428 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
2429 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' );
2431 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2432 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
2433 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' );
2435 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2439 subtest 'AddReturn | is_overdue' => sub {
2442 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment');
2443 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2444 t::lib::Mocks::mock_preference('finesMode', 'production');
2445 t::lib::Mocks::mock_preference('MaxFine', '100');
2447 my $library = $builder->build( { source => 'Branch' } );
2448 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2449 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2450 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2452 my $item = $builder->build_sample_item(
2454 library => $library->{branchcode},
2455 replacementprice => 7
2459 Koha::CirculationRules->search->delete;
2460 Koha::CirculationRules->set_rules(
2462 categorycode => undef,
2464 branchcode => undef,
2467 lengthunit => 'days',
2468 fine => 1, # Charge 1 every day of overdue
2474 my $now = dt_from_string;
2475 my $one_day_ago = $now->clone->subtract( days => 1 );
2476 my $two_days_ago = $now->clone->subtract( days => 2 );
2477 my $five_days_ago = $now->clone->subtract( days => 5 );
2478 my $ten_days_ago = $now->clone->subtract( days => 10 );
2479 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2481 # No return date specified, today will be used => 10 days overdue charged
2482 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2483 AddReturn( $item->{barcode}, $library->{branchcode} );
2484 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2485 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2487 # specify return date 5 days before => no overdue charged
2488 AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
2489 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
2490 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2491 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2493 # specify return date 5 days later => 5 days overdue charged
2494 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2495 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
2496 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2497 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2499 # specify return date 5 days later, specify exemptfine => no overdue charge
2500 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2501 AddReturn( $item->{barcode}, $library->{branchcode}, 1, $five_days_ago );
2502 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2503 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2505 subtest 'bug 22877' => sub {
2509 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2511 # Fake fines cronjob on this checkout
2513 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2514 $ten_days_ago, $now );
2517 issue_id => $issue->issue_id,
2518 itemnumber => $item->{itemnumber},
2519 borrowernumber => $patron->borrowernumber,
2521 due => output_pref($ten_days_ago)
2524 is( int( $patron->account->balance() ),
2525 10, "Overdue fine of 10 days overdue" );
2527 # Fake longoverdue with charge and not marking returned
2528 LostItem( $item->{itemnumber}, 'cronjob', 0 );
2529 is( int( $patron->account->balance() ),
2530 17, "Lost fine of 7 plus 10 days overdue" );
2532 # Now we return it today
2533 AddReturn( $item->{barcode}, $library->{branchcode} );
2534 is( int( $patron->account->balance() ),
2535 17, "Should have a single 10 days overdue fine and lost charge" );
2538 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2541 subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub {
2545 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2547 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $one_day_ago ); # date due was 1d ago
2549 # Fake fines cronjob on this checkout
2551 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2552 $one_day_ago, $now );
2555 issue_id => $issue->issue_id,
2556 itemnumber => $item->{itemnumber},
2557 borrowernumber => $patron->borrowernumber,
2559 due => output_pref($one_day_ago)
2562 is( int( $patron->account->balance() ),
2563 1, "Overdue fine of 1 day overdue" );
2565 # Backdated return (dropbox mode example - charge should be removed)
2566 AddReturn( $item->{barcode}, $library->{branchcode}, 1, $one_day_ago );
2567 is( int( $patron->account->balance() ),
2568 0, "Overdue fine should be annulled" );
2569 my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2570 is( $lines->count, 0, "Overdue fine accountline has been removed");
2572 $issue = AddIssue( $patron->unblessed, $item->{barcode}, $two_days_ago ); # date due was 2d ago
2574 # Fake fines cronjob on this checkout
2576 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2577 $two_days_ago, $now );
2580 issue_id => $issue->issue_id,
2581 itemnumber => $item->{itemnumber},
2582 borrowernumber => $patron->borrowernumber,
2584 due => output_pref($one_day_ago)
2587 is( int( $patron->account->balance() ),
2588 2, "Overdue fine of 2 days overdue" );
2590 # Payment made against fine
2591 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2592 my $debit = $lines->next;
2593 my $credit = $patron->account->add_credit(
2597 interface => 'test',
2601 { debits => [ $debit ], offset_type => 'Payment' } );
2603 is( int( $patron->account->balance() ),
2604 0, "Overdue fine should be paid off" );
2605 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2606 is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present");
2607 my $line = $lines->next;
2608 is( $line->amount+0, 2, "Overdue fine amount remains as 2 days");
2609 is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0");
2611 # Backdated return (dropbox mode example - charge should be removed)
2612 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $one_day_ago );
2613 is( int( $patron->account->balance() ),
2614 -1, "Refund credit has been applied" );
2615 $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }});
2616 is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present");
2618 $line = $lines->next;
2619 is($line->amount+0,1, "Overdue fine amount has been reduced to 1");
2620 is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0");
2621 is($line->status,'RETURNED', "Overdue fine is fixed");
2622 $line = $lines->next;
2623 is($line->amount+0,-2, "Original payment amount remains as 2");
2624 is($line->amountoutstanding+0,0, "Original payment remains applied");
2625 $line = $lines->next;
2626 is($line->amount+0,-1, "Refund amount correctly set to 1");
2627 is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent");
2630 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2633 subtest 'bug 25417 | backdated return + exemptfine' => sub {
2637 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2639 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $one_day_ago ); # date due was 1d ago
2641 # Fake fines cronjob on this checkout
2643 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2644 $one_day_ago, $now );
2647 issue_id => $issue->issue_id,
2648 itemnumber => $item->{itemnumber},
2649 borrowernumber => $patron->borrowernumber,
2651 due => output_pref($one_day_ago)
2654 is( int( $patron->account->balance() ),
2655 1, "Overdue fine of 1 day overdue" );
2657 # Backdated return (dropbox mode example - charge should no longer exist)
2658 AddReturn( $item->{barcode}, $library->{branchcode}, 1, $one_day_ago );
2659 is( int( $patron->account->balance() ),
2660 0, "Overdue fine should be annulled" );
2663 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2666 subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub {
2669 t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 );
2671 my $due_date = dt_from_string;
2672 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $due_date );
2677 issue_id => $issue->issue_id,
2678 itemnumber => $item->{itemnumber},
2679 borrowernumber => $patron->borrowernumber,
2681 due => output_pref($due_date)
2684 is( $patron->account->balance(),
2685 0.25, 'Overdue fine of $0.25 recorded' );
2687 # Backdate return to exact due date and time
2688 my ( undef, $message ) =
2689 AddReturn( $item->{barcode}, $library->{branchcode},
2693 Koha::Account::Lines->find( { issue_id => $issue->id } );
2694 ok( !$accountline, 'accountline removed as expected' );
2697 $issue = AddIssue( $patron->unblessed, $item->{barcode}, $due_date );
2702 issue_id => $issue->issue_id,
2703 itemnumber => $item->{itemnumber},
2704 borrowernumber => $patron->borrowernumber,
2706 due => output_pref($due_date)
2709 is( $patron->account->balance(),
2710 0.25, 'Overdue fine of $0.25 recorded' );
2712 # Partial pay accruing fine
2713 my $lines = Koha::Account::Lines->search(
2715 borrowernumber => $patron->borrowernumber,
2716 issue_id => $issue->id
2719 my $debit = $lines->next;
2720 my $credit = $patron->account->add_credit(
2724 interface => 'test',
2727 $credit->apply( { debits => [$debit], offset_type => 'Payment' } );
2729 is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' );
2731 # Backdate return to exact due date and time
2732 ( undef, $message ) =
2733 AddReturn( $item->{barcode}, $library->{branchcode},
2736 $lines = Koha::Account::Lines->search(
2738 borrowernumber => $patron->borrowernumber,
2739 issue_id => $issue->id
2742 $accountline = $lines->next;
2743 is( $accountline->amountoutstanding + 0,
2744 0, 'Partially paid fee amount outstanding was reduced to 0' );
2745 is( $accountline->amount + 0,
2746 0, 'Partially paid fee amount was reduced to 0' );
2747 is( $patron->account->balance(), -0.20, 'Patron refund recorded' );
2750 Koha::Account::Lines->search(
2751 { borrowernumber => $patron->borrowernumber } )->delete;
2755 subtest '_FixAccountForLostAndFound' => sub {
2759 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
2760 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
2762 my $processfee_amount = 20;
2763 my $replacement_amount = 99.00;
2764 my $item_type = $builder->build_object(
2765 { class => 'Koha::ItemTypes',
2767 notforloan => undef,
2769 defaultreplacecost => undef,
2770 processfee => $processfee_amount,
2771 rentalcharge_daily => 0,
2775 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2777 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
2779 subtest 'Full write-off tests' => sub {
2783 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2784 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2785 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
2787 my $item = $builder->build_sample_item(
2789 biblionumber => $biblio->biblionumber,
2790 library => $library->branchcode,
2791 replacementprice => $replacement_amount,
2792 itype => $item_type->itemtype,
2796 AddIssue( $patron->unblessed, $item->barcode );
2798 # Simulate item marked as lost
2799 $item->itemlost(3)->store;
2800 LostItem( $item->itemnumber, 1 );
2802 my $processing_fee_lines = Koha::Account::Lines->search(
2803 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2804 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2805 my $processing_fee_line = $processing_fee_lines->next;
2806 is( $processing_fee_line->amount + 0,
2807 $processfee_amount, 'The right PROCESSING amount is generated' );
2808 is( $processing_fee_line->amountoutstanding + 0,
2809 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2811 my $lost_fee_lines = Koha::Account::Lines->search(
2812 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2813 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2814 my $lost_fee_line = $lost_fee_lines->next;
2815 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2816 is( $lost_fee_line->amountoutstanding + 0,
2817 $replacement_amount, 'The right LOST amountoutstanding is generated' );
2818 is( $lost_fee_line->status,
2819 undef, 'The LOST status was not set' );
2821 my $account = $patron->account;
2822 my $debts = $account->outstanding_debits;
2824 # Write off the debt
2825 my $credit = $account->add_credit(
2826 { amount => $account->balance,
2828 interface => 'test',
2831 $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Writeoff' } );
2833 my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2834 is( $credit_return_id, undef, 'No LOST_FOUND account line added' );
2836 $lost_fee_line->discard_changes; # reload from DB
2837 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2838 is( $lost_fee_line->debit_type_code,
2839 'LOST', 'Lost fee now still has account type of LOST' );
2840 is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2842 is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2845 subtest 'Full payment tests' => sub {
2849 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2851 my $item = $builder->build_sample_item(
2853 biblionumber => $biblio->biblionumber,
2854 library => $library->branchcode,
2855 replacementprice => $replacement_amount,
2856 itype => $item_type->itemtype
2860 AddIssue( $patron->unblessed, $item->barcode );
2862 # Simulate item marked as lost
2863 $item->itemlost(1)->store;
2864 LostItem( $item->itemnumber, 1 );
2866 my $processing_fee_lines = Koha::Account::Lines->search(
2867 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2868 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2869 my $processing_fee_line = $processing_fee_lines->next;
2870 is( $processing_fee_line->amount + 0,
2871 $processfee_amount, 'The right PROCESSING amount is generated' );
2872 is( $processing_fee_line->amountoutstanding + 0,
2873 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2875 my $lost_fee_lines = Koha::Account::Lines->search(
2876 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2877 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2878 my $lost_fee_line = $lost_fee_lines->next;
2879 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2880 is( $lost_fee_line->amountoutstanding + 0,
2881 $replacement_amount, 'The right LOST amountountstanding is generated' );
2883 my $account = $patron->account;
2884 my $debts = $account->outstanding_debits;
2886 # Write off the debt
2887 my $credit = $account->add_credit(
2888 { amount => $account->balance,
2890 interface => 'test',
2893 $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Payment' } );
2895 my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2896 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2898 is( $credit_return->credit_type_code, 'LOST_FOUND', 'An account line of type LOST_FOUND is added' );
2899 is( $credit_return->amount + 0,
2900 -99.00, 'The account line of type LOST_FOUND has an amount of -99' );
2901 is( $credit_return->amountoutstanding + 0,
2902 -99.00, 'The account line of type LOST_FOUND has an amountoutstanding of -99' );
2904 $lost_fee_line->discard_changes;
2905 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2906 is( $lost_fee_line->debit_type_code,
2907 'LOST', 'Lost fee now still has account type of LOST' );
2908 is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2910 is( $patron->account->balance,
2911 -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2914 subtest 'Test without payment or write off' => sub {
2918 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2920 my $item = $builder->build_sample_item(
2922 biblionumber => $biblio->biblionumber,
2923 library => $library->branchcode,
2924 replacementprice => 23.00,
2925 replacementprice => $replacement_amount,
2926 itype => $item_type->itemtype
2930 AddIssue( $patron->unblessed, $item->barcode );
2932 # Simulate item marked as lost
2933 $item->itemlost(3)->store;
2934 LostItem( $item->itemnumber, 1 );
2936 my $processing_fee_lines = Koha::Account::Lines->search(
2937 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2938 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2939 my $processing_fee_line = $processing_fee_lines->next;
2940 is( $processing_fee_line->amount + 0,
2941 $processfee_amount, 'The right PROCESSING amount is generated' );
2942 is( $processing_fee_line->amountoutstanding + 0,
2943 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2945 my $lost_fee_lines = Koha::Account::Lines->search(
2946 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2947 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2948 my $lost_fee_line = $lost_fee_lines->next;
2949 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2950 is( $lost_fee_line->amountoutstanding + 0,
2951 $replacement_amount, 'The right LOST amountountstanding is generated' );
2953 my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
2954 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2956 is( $credit_return->credit_type_code, 'LOST_FOUND', 'An account line of type LOST_FOUND is added' );
2957 is( $credit_return->amount + 0, -99.00, 'The account line of type LOST_FOUND has an amount of -99' );
2958 is( $credit_return->amountoutstanding + 0, 0, 'The account line of type LOST_FOUND has an amountoutstanding of 0' );
2960 $lost_fee_line->discard_changes;
2961 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2962 is( $lost_fee_line->debit_type_code,
2963 'LOST', 'Lost fee now still has account type of LOST' );
2964 is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
2966 is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2969 subtest 'Test with partial payement and write off, and remaining debt' => sub {
2973 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2974 my $item = $builder->build_sample_item(
2976 biblionumber => $biblio->biblionumber,
2977 library => $library->branchcode,
2978 replacementprice => $replacement_amount,
2979 itype => $item_type->itemtype
2983 AddIssue( $patron->unblessed, $item->barcode );
2985 # Simulate item marked as lost
2986 $item->itemlost(1)->store;
2987 LostItem( $item->itemnumber, 1 );
2989 my $processing_fee_lines = Koha::Account::Lines->search(
2990 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2991 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2992 my $processing_fee_line = $processing_fee_lines->next;
2993 is( $processing_fee_line->amount + 0,
2994 $processfee_amount, 'The right PROCESSING amount is generated' );
2995 is( $processing_fee_line->amountoutstanding + 0,
2996 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2998 my $lost_fee_lines = Koha::Account::Lines->search(
2999 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
3000 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
3001 my $lost_fee_line = $lost_fee_lines->next;
3002 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
3003 is( $lost_fee_line->amountoutstanding + 0,
3004 $replacement_amount, 'The right LOST amountountstanding is generated' );
3006 my $account = $patron->account;
3007 is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PROCESSING + L' );
3010 my $payment_amount = 27;
3011 my $payment = $account->add_credit(
3012 { amount => $payment_amount,
3014 interface => 'test',
3018 $payment->apply( { debits => [ $lost_fee_line ], offset_type => 'Payment' } );
3020 # Partially write off fee
3021 my $write_off_amount = 25;
3022 my $write_off = $account->add_credit(
3023 { amount => $write_off_amount,
3025 interface => 'test',
3028 $write_off->apply( { debits => [ $lost_fee_line ], offset_type => 'Writeoff' } );
3030 is( $account->balance,
3031 $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
3032 'Payment and write off applied'
3035 # Store the amountoutstanding value
3036 $lost_fee_line->discard_changes;
3037 my $outstanding = $lost_fee_line->amountoutstanding;
3039 my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
3040 my $credit_return = Koha::Account::Lines->find($credit_return_id);
3042 is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PROCESSING - PAYMENT (LOST_FOUND)' );
3044 $lost_fee_line->discard_changes;
3045 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
3046 is( $lost_fee_line->debit_type_code,
3047 'LOST', 'Lost fee now still has account type of LOST' );
3048 is( $lost_fee_line->status, 'FOUND', "Lost fee now has account status of FOUND");
3050 is( $credit_return->credit_type_code, 'LOST_FOUND', 'An account line of type LOST_FOUND is added' );
3051 is( $credit_return->amount + 0,
3052 ($payment_amount + $outstanding ) * -1,
3053 'The account line of type LOST_FOUND has an amount equal to the payment + outstanding'
3055 is( $credit_return->amountoutstanding + 0,
3056 $payment_amount * -1,
3057 'The account line of type LOST_FOUND has an amountoutstanding equal to the payment'
3060 is( $account->balance,
3061 $processfee_amount - $payment_amount,
3062 'The patron balance is the difference between the PROCESSING and the credit'
3066 subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
3070 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
3071 my $barcode = 'KD123456793';
3072 my $replacement_amount = 100;
3073 my $processfee_amount = 20;
3075 my $item_type = $builder->build_object(
3076 { class => 'Koha::ItemTypes',
3078 notforloan => undef,
3080 defaultreplacecost => undef,
3082 rentalcharge_daily => 0,
3086 my $item = Koha::Item->new(
3088 biblionumber => $biblio->biblionumber,
3089 homebranch => $library->branchcode,
3090 holdingbranch => $library->branchcode,
3091 barcode => $barcode,
3092 replacementprice => $replacement_amount,
3093 itype => $item_type->itemtype
3097 AddIssue( $patron->unblessed, $barcode );
3099 # Simulate item marked as lost
3100 $item->itemlost(1)->store;
3101 LostItem( $item->itemnumber, 1 );
3103 my $lost_fee_lines = Koha::Account::Lines->search(
3104 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
3105 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
3106 my $lost_fee_line = $lost_fee_lines->next;
3107 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
3108 is( $lost_fee_line->amountoutstanding + 0,
3109 $replacement_amount, 'The right LOST amountountstanding is generated' );
3111 my $account = $patron->account;
3112 is( $account->balance, $replacement_amount, 'Balance is L' );
3115 my $payment_amount = 27;
3116 my $payment = $account->add_credit(
3117 { amount => $payment_amount,
3119 interface => 'test',
3122 $payment->apply({ debits => [ $lost_fee_line ], offset_type => 'Payment' });
3124 is( $account->balance,
3125 $replacement_amount - $payment_amount,
3129 my $manual_debit_amount = 80;
3130 $account->add_debit( { amount => $manual_debit_amount, type => 'OVERDUE', interface =>'test' } );
3132 is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
3134 t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
3136 my $credit_return_id = C4::Circulation::_FixAccountForLostAndFound( $item->itemnumber, $patron->id );
3137 my $credit_return = Koha::Account::Lines->find($credit_return_id);
3139 is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PROCESSING - payment (LOST_FOUND)' );
3141 my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, debit_type_code => 'OVERDUE', status => 'UNRETURNED' })->next;
3142 is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
3146 subtest '_FixOverduesOnReturn' => sub {
3149 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3150 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3152 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3154 my $branchcode = $library2->{branchcode};
3156 my $item = $builder->build_sample_item(
3158 biblionumber => $biblio->biblionumber,
3159 library => $branchcode,
3160 replacementprice => 99.00,
3165 my $patron = $builder->build( { source => 'Borrower' } );
3167 ## Start with basic call, should just close out the open fine
3168 my $accountline = Koha::Account::Line->new(
3170 borrowernumber => $patron->{borrowernumber},
3171 debit_type_code => 'OVERDUE',
3172 status => 'UNRETURNED',
3173 itemnumber => $item->itemnumber,
3175 amountoutstanding => 99.00,
3176 interface => 'test',
3180 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
3182 $accountline->_result()->discard_changes();
3184 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
3185 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3186 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3188 ## Run again, with exemptfine enabled
3191 debit_type_code => 'OVERDUE',
3192 status => 'UNRETURNED',
3193 amountoutstanding => 99.00,
3197 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3199 $accountline->_result()->discard_changes();
3200 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
3202 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
3203 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3204 is( $accountline->status, 'FORGIVEN', 'Open fine ( account type OVERDUE ) has been set to fine forgiven ( status FORGIVEN )');
3205 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
3206 is( $offset->amount + 0, -99, "Amount of offset is correct" );
3207 my $credit = $offset->credit;
3208 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
3209 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
3210 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
3212 # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
3215 debit_type_code => 'OVERDUE',
3216 status => 'UNRETURNED',
3217 amountoutstanding => 0.00,
3222 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
3224 $accountline->_result()->discard_changes();
3225 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
3226 is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
3227 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
3228 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
3231 subtest '_FixAccountForLostAndFound returns undef if patron is deleted' => sub {
3234 my $manager = $builder->build_object({ class => "Koha::Patrons" });
3235 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
3237 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
3239 my $branchcode = $library2->{branchcode};
3241 my $item = $builder->build_sample_item(
3243 biblionumber => $biblio->biblionumber,
3244 library => $branchcode,
3245 replacementprice => 99.00,
3250 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
3252 ## Start with basic call, should just close out the open fine
3253 my $accountline = Koha::Account::Line->new(
3255 borrowernumber => $patron->id,
3256 debit_type_code => 'LOST',
3258 itemnumber => $item->itemnumber,
3260 amountoutstanding => 99.00,
3261 interface => 'test',
3267 my $return_value = C4::Circulation::_FixAccountForLostAndFound( $patron->id, $item->itemnumber );
3269 is( $return_value, undef, "_FixAccountForLostAndFound returns undef if patron is deleted" );
3273 subtest 'Set waiting flag' => sub {
3276 my $library_1 = $builder->build( { source => 'Branch' } );
3277 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3278 my $library_2 = $builder->build( { source => 'Branch' } );
3279 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3281 my $item = $builder->build_sample_item(
3283 library => $library_1->{branchcode},
3287 set_userenv( $library_2 );
3288 my $reserve_id = AddReserve(
3290 branchcode => $library_2->{branchcode},
3291 borrowernumber => $patron_2->{borrowernumber},
3292 biblionumber => $item->{biblionumber},
3294 itemnumber => $item->{itemnumber},
3298 set_userenv( $library_1 );
3299 my $do_transfer = 1;
3300 my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
3301 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
3302 my $hold = Koha::Holds->find( $reserve_id );
3303 is( $hold->found, 'T', 'Hold is in transit' );
3305 my ( $status ) = CheckReserves($item->{itemnumber});
3306 is( $status, 'Reserved', 'Hold is not waiting yet');
3308 set_userenv( $library_2 );
3310 AddReturn( $item->{barcode}, $library_2->{branchcode} );
3311 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
3312 $hold = Koha::Holds->find( $reserve_id );
3313 is( $hold->found, 'W', 'Hold is waiting' );
3314 ( $status ) = CheckReserves($item->{itemnumber});
3315 is( $status, 'Waiting', 'Now the hold is waiting');
3317 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
3318 set_userenv( $library_1 );
3319 (undef, my $messages, undef, undef ) = AddReturn ( $item->{barcode}, $library_1->{branchcode} );
3320 $hold = Koha::Holds->find( $reserve_id );
3321 is( $hold->found, undef, 'Hold is no longer marked waiting' );
3322 is( $hold->priority, 1, "Hold is now priority one again");
3323 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
3324 is( $hold->itemnumber, $item->{itemnumber}, "Hold has retained its' itemnumber");
3325 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
3326 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
3327 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
3330 subtest 'Cancel transfers on lost items' => sub {
3332 my $library_1 = $builder->build( { source => 'Branch' } );
3333 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3334 my $library_2 = $builder->build( { source => 'Branch' } );
3335 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
3336 my $biblio = $builder->build_sample_biblio({branchcode => $library->{branchcode}});
3337 my $item = $builder->build_sample_item({
3338 biblionumber => $biblio->biblionumber,
3339 library => $library_1->{branchcode},
3342 set_userenv( $library_2 );
3343 my $reserve_id = AddReserve(
3345 branchcode => $library_2->{branchcode},
3346 borrowernumber => $patron_2->{borrowernumber},
3347 biblionumber => $item->biblionumber,
3349 itemnumber => $item->itemnumber,
3353 #Return book and add transfer
3354 set_userenv( $library_1 );
3355 my $do_transfer = 1;
3356 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
3357 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
3358 C4::Circulation::transferbook( $library_2->{branchcode}, $item->barcode );
3359 my $hold = Koha::Holds->find( $reserve_id );
3360 is( $hold->found, 'T', 'Hold is in transit' );
3362 #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
3363 my ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
3364 is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
3365 my $itemcheck = Koha::Items->find($item->itemnumber);
3366 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Items holding branch is the transfers origin branch before it is marked as lost' );
3368 #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
3369 $item->itemlost(1)->store;
3370 LostItem( $item->itemnumber, 'test', 1 );
3371 ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
3372 is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
3373 $itemcheck = Koha::Items->find($item->itemnumber);
3374 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
3377 subtest 'CanBookBeIssued | is_overdue' => sub {
3380 # Set a simple circ policy
3381 Koha::CirculationRules->set_rules(
3383 categorycode => undef,
3384 branchcode => undef,
3388 reservesallowed => 25,
3390 lengthunit => 'days',
3391 renewalsallowed => 1,
3393 norenewalbefore => undef,
3401 my $now = dt_from_string;
3402 my $five_days_go = output_pref({ dt => $now->clone->add( days => 5 ), dateonly => 1});
3403 my $ten_days_go = output_pref({ dt => $now->clone->add( days => 10), dateonly => 1 });
3404 my $library = $builder->build( { source => 'Branch' } );
3405 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
3407 my $item = $builder->build_sample_item(
3409 library => $library->{branchcode},
3413 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
3414 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
3415 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
3416 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
3417 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
3418 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
3421 subtest 'ItemsDeniedRenewal preference' => sub {
3424 C4::Context->set_preference('ItemsDeniedRenewal','');
3426 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
3427 Koha::CirculationRules->set_rules(
3429 categorycode => '*',
3431 branchcode => $idr_lib->branchcode,
3433 reservesallowed => 25,
3435 lengthunit => 'days',
3436 renewalsallowed => 10,
3438 norenewalbefore => undef,
3446 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
3447 homebranch => $idr_lib->branchcode,
3451 itemcallnumber => undef,
3455 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
3456 homebranch => $idr_lib->branchcode,
3459 location => 'NOPROC'
3463 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
3464 branchcode => $idr_lib->branchcode,
3467 my $future = dt_from_string->add( days => 1 );
3468 my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3469 returndate => undef,
3472 borrowernumber => $idr_borrower->borrowernumber,
3473 itemnumber => $deny_book->itemnumber,
3474 onsite_checkout => 0,
3475 date_due => $future,
3478 my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
3479 returndate => undef,
3482 borrowernumber => $idr_borrower->borrowernumber,
3483 itemnumber => $allow_book->itemnumber,
3484 onsite_checkout => 0,
3485 date_due => $future,
3491 my ( $idr_mayrenew, $idr_error ) =
3492 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3493 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
3494 is( $idr_error, undef, 'Renewal allowed when no rules' );
3496 $idr_rules="withdrawn: [1]";
3498 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3499 ( $idr_mayrenew, $idr_error ) =
3500 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3501 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
3502 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
3503 ( $idr_mayrenew, $idr_error ) =
3504 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3505 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3506 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
3508 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
3510 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3511 ( $idr_mayrenew, $idr_error ) =
3512 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3513 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
3514 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
3515 ( $idr_mayrenew, $idr_error ) =
3516 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3517 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3518 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
3520 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
3522 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3523 ( $idr_mayrenew, $idr_error ) =
3524 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3525 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
3526 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
3527 ( $idr_mayrenew, $idr_error ) =
3528 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
3529 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3530 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
3532 $idr_rules="itemcallnumber: [NULL]";
3533 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3534 ( $idr_mayrenew, $idr_error ) =
3535 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3536 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
3537 $idr_rules="itemcallnumber: ['']";
3538 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3539 ( $idr_mayrenew, $idr_error ) =
3540 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3541 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
3543 $idr_rules="itemnotes: [NULL]";
3544 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3545 ( $idr_mayrenew, $idr_error ) =
3546 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3547 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
3548 $idr_rules="itemnotes: ['']";
3549 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
3550 ( $idr_mayrenew, $idr_error ) =
3551 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
3552 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
3555 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
3558 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3559 my $library = $builder->build( { source => 'Branch' } );
3560 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3562 my $item = $builder->build_sample_item(
3564 library => $library->{branchcode},
3568 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3569 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3570 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3573 subtest 'CanBookBeIssued | notforloan' => sub {
3576 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
3578 my $library = $builder->build( { source => 'Branch' } );
3579 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
3581 my $itemtype = $builder->build(
3583 source => 'Itemtype',
3584 value => { notforloan => undef, }
3587 my $item = $builder->build_sample_item(
3589 library => $library->{branchcode},
3590 itype => $itemtype->{itemtype},
3593 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3595 my ( $issuingimpossible, $needsconfirmation );
3598 subtest 'item-level_itypes = 1' => sub {
3601 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
3602 # Is for loan at item type and item level
3603 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3604 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3605 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3607 # not for loan at item type level
3608 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3609 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3610 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3613 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3614 'Item can not be issued, not for loan at item type level'
3617 # not for loan at item level
3618 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3619 $item->notforloan( 1 )->store;
3620 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3621 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3624 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3625 'Item can not be issued, not for loan at item type level'
3629 subtest 'item-level_itypes = 0' => sub {
3632 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3634 # We set another itemtype for biblioitem
3635 my $itemtype = $builder->build(
3637 source => 'Itemtype',
3638 value => { notforloan => undef, }
3642 # for loan at item type and item level
3643 $item->notforloan(0)->store;
3644 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3645 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3646 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3647 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3649 # not for loan at item type level
3650 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3651 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3652 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3655 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3656 'Item can not be issued, not for loan at item type level'
3659 # not for loan at item level
3660 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3661 $item->notforloan( 1 )->store;
3662 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3663 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3666 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3667 'Item can not be issued, not for loan at item type level'
3671 # TODO test with AllowNotForLoanOverride = 1
3674 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
3677 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
3678 my $item = $builder->build_sample_item(
3680 onloan => '2018-01-01',
3684 AddReturn( $item->barcode, $item->homebranch );
3685 $item->discard_changes; # refresh
3686 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
3690 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
3695 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3697 my $issuing_charges = 15;
3698 my $title = 'A title';
3699 my $author = 'Author, An';
3700 my $barcode = 'WHATARETHEODDS';
3702 my $circ = Test::MockModule->new('C4::Circulation');
3704 'GetIssuingCharges',
3706 return $issuing_charges;
3710 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3711 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
3712 my $patron = $builder->build_object({
3713 class => 'Koha::Patrons',
3714 value => { branchcode => $library->id }
3717 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
3718 my $item_id = Koha::Item->new(
3720 biblionumber => $biblio->biblionumber,
3721 homebranch => $library->id,
3722 holdingbranch => $library->id,
3723 barcode => $barcode,
3724 replacementprice => 23.00,
3725 itype => $itemtype->id
3727 )->store->itemnumber;
3728 my $item = Koha::Items->find( $item_id );
3730 my $context = Test::MockModule->new('C4::Context');
3731 $context->mock( userenv => { branch => $library->id } );
3733 # Check the item out
3734 AddIssue( $patron->unblessed, $item->barcode );
3737 AddRenewal( $patron->borrowernumber, $item->itemnumber, $library->id, undef, {break=>"the_renewal"} );
3738 } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails';
3740 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
3741 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3742 my %params_renewal = (
3743 timestamp => { -like => $date . "%" },
3744 module => "CIRCULATION",
3745 action => "RENEWAL",
3747 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
3748 AddRenewal( $patron->id, $item->id, $library->id );
3749 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3750 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
3752 my $checkouts = $patron->checkouts;
3753 # The following will fail if run on 00:00:00
3754 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
3756 my $lines = Koha::Account::Lines->search({
3757 borrowernumber => $patron->id,
3758 itemnumber => $item->id
3761 is( $lines->count, 2 );
3763 my $line = $lines->next;
3764 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
3765 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
3766 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
3768 $line = $lines->next;
3769 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
3770 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
3771 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
3773 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
3775 $context = Test::MockModule->new('C4::Context');
3776 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
3778 my $now = dt_from_string;
3779 $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
3780 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
3781 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
3782 $sth->execute($item->id, $library->id);
3783 my ($old_stats_size) = $sth->fetchrow_array;
3784 AddRenewal( $patron->id, $item->id, $library->id );
3785 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3786 $sth->execute($item->id, $library->id);
3787 my ($new_stats_size) = $sth->fetchrow_array;
3788 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
3789 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
3791 AddReturn( $item->id, $library->id, undef, $date );
3792 AddIssue( $patron->unblessed, $item->barcode, $now );
3793 AddRenewal( $patron->id, $item->id, $library->id, undef, undef, 1 );
3794 my $lines_skipped = Koha::Account::Lines->search({
3795 borrowernumber => $patron->id,
3796 itemnumber => $item->id
3798 is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' );
3802 subtest 'ProcessOfflinePayment() tests' => sub {
3809 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
3810 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3811 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
3813 is( $result, 'Success.', 'The right string is returned' );
3815 my $lines = $patron->account->lines;
3816 is( $lines->count, 1, 'line created correctly');
3818 my $line = $lines->next;
3819 is( $line->amount+0, $amount * -1, 'amount picked from params' );
3820 is( $line->branchcode, $library->id, 'branchcode set correctly' );
3824 subtest 'Incremented fee tests' => sub {
3827 my $dt = dt_from_string();
3828 Time::Fake->offset( $dt->epoch );
3830 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
3833 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3835 my $module = new Test::MockModule('C4::Context');
3836 $module->mock( 'userenv', sub { { branch => $library->id } } );
3838 my $patron = $builder->build_object(
3840 class => 'Koha::Patrons',
3841 value => { categorycode => $patron_category->{categorycode} }
3845 my $itemtype = $builder->build_object(
3847 class => 'Koha::ItemTypes',
3849 notforloan => undef,
3851 rentalcharge_daily => 1,
3852 rentalcharge_daily_calendar => 0
3857 my $item = $builder->build_sample_item(
3859 library => $library->{branchcode},
3860 itype => $itemtype->id,
3864 is( $itemtype->rentalcharge_daily+0,
3865 1, 'Daily rental charge stored and retreived correctly' );
3866 is( $item->effective_itemtype, $itemtype->id,
3867 "Itemtype set correctly for item" );
3869 my $now = dt_from_string;
3870 my $dt_from = $now->clone;
3871 my $dt_to = $now->clone->add( days => 7 );
3872 my $dt_to_renew = $now->clone->add( days => 13 );
3876 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3877 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3878 is( $accountline->amount+0, 7,
3879 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0"
3881 $accountline->delete();
3882 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3883 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3884 is( $accountline->amount+0, 6,
3885 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 0, for renewal"
3887 $accountline->delete();
3890 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3891 $itemtype->rentalcharge_daily_calendar(1)->store();
3893 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3894 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3895 is( $accountline->amount+0, 7,
3896 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1"
3898 $accountline->delete();
3899 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3900 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3901 is( $accountline->amount+0, 6,
3902 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1, for renewal"
3904 $accountline->delete();
3907 my $calendar = C4::Calendar->new( branchcode => $library->id );
3908 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
3910 ( $dt_from->day_of_week == 6 ) ? 0
3911 : ( $dt_from->day_of_week == 7 ) ? 1
3912 : $dt_from->day_of_week + 1;
3913 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
3914 $calendar->insert_week_day_holiday(
3915 weekday => $closed_day,
3916 title => 'Test holiday',
3917 description => 'Test holiday'
3920 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3921 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3922 is( $accountline->amount+0, 6,
3923 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name"
3925 $accountline->delete();
3926 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3927 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3928 is( $accountline->amount+0, 5,
3929 "Daily rental charge calculated correctly with rentalcharge_daily_calendar = 1 and closed $closed_day_name, for renewal"
3931 $accountline->delete();
3934 $itemtype->rentalcharge(2)->store;
3935 is( $itemtype->rentalcharge+0, 2,
3936 'Rental charge updated and retreived correctly' );
3938 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3940 Koha::Account::Lines->search( { itemnumber => $item->id } );
3941 is( $accountlines->count, '2',
3942 "Fixed charge and accrued charge recorded distinctly" );
3943 $accountlines->delete();
3944 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3945 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
3946 is( $accountlines->count, '2',
3947 "Fixed charge and accrued charge recorded distinctly, for renewal" );
3948 $accountlines->delete();
3950 $itemtype->rentalcharge(0)->store;
3951 is( $itemtype->rentalcharge+0, 0,
3952 'Rental charge reset and retreived correctly' );
3955 Koha::CirculationRules->set_rule(
3957 categorycode => $patron->categorycode,
3958 itemtype => $itemtype->id,
3959 branchcode => $library->id,
3960 rule_name => 'lengthunit',
3961 rule_value => 'hours',
3965 $itemtype->rentalcharge_hourly('0.25')->store();
3966 is( $itemtype->rentalcharge_hourly,
3967 '0.25', 'Hourly rental charge stored and retreived correctly' );
3969 $dt_to = $now->clone->add( hours => 168 );
3970 $dt_to_renew = $now->clone->add( hours => 312 );
3972 $itemtype->rentalcharge_hourly_calendar(0)->store();
3974 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3975 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3976 is( $accountline->amount + 0, 42,
3977 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0 (168h * 0.25u)" );
3978 $accountline->delete();
3979 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3980 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3981 is( $accountline->amount + 0, 36,
3982 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 0, for renewal (312h - 168h * 0.25u)" );
3983 $accountline->delete();
3986 $itemtype->rentalcharge_hourly_calendar(1)->store();
3988 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3989 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3990 is( $accountline->amount + 0, 36,
3991 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name (168h - 24h * 0.25u)" );
3992 $accountline->delete();
3993 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3994 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3995 is( $accountline->amount + 0, 30,
3996 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
3997 $accountline->delete();
4000 $calendar->delete_holiday( weekday => $closed_day );
4002 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
4003 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4004 is( $accountline->amount + 0, 42,
4005 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1 (168h - 0h * 0.25u" );
4006 $accountline->delete();
4007 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
4008 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
4009 is( $accountline->amount + 0, 36,
4010 "Hourly rental charge calculated correctly with rentalcharge_hourly_calendar = 1, for renewal (312h - 168h - 0h * 0.25u)" );
4011 $accountline->delete();
4016 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
4019 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
4020 t::lib::Mocks::mock_preference('item-level_itypes', 1);
4023 $builder->build_object( { class => 'Koha::Libraries' } )->store;
4024 my $patron = $builder->build_object(
4026 class => 'Koha::Patrons',
4027 value => { categorycode => $patron_category->{categorycode} }
4031 my $itemtype = $builder->build_object(
4033 class => 'Koha::ItemTypes',
4037 rentalcharge_daily => 0
4042 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
4043 my $item = $builder->build_object(
4045 class => 'Koha::Items',
4047 homebranch => $library->id,
4048 holdingbranch => $library->id,
4052 itype => $itemtype->id,
4053 biblionumber => $biblioitem->{biblionumber},
4054 biblioitemnumber => $biblioitem->{biblioitemnumber},
4059 my ( $issuingimpossible, $needsconfirmation );
4060 my $dt_from = dt_from_string();
4061 my $dt_due = $dt_from->clone->add( days => 3 );
4063 $itemtype->rentalcharge(1)->store;
4064 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4065 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
4066 $itemtype->rentalcharge('0')->store;
4067 $itemtype->rentalcharge_daily(1)->store;
4068 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
4069 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
4070 $itemtype->rentalcharge_daily('0')->store;
4073 subtest 'Do not return on renewal (LOST charge)' => sub {
4076 t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment');
4077 my $library = $builder->build_object( { class => "Koha::Libraries" } );
4078 my $manager = $builder->build_object( { class => "Koha::Patrons" } );
4079 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
4081 my $biblio = $builder->build_sample_biblio;
4083 my $item = $builder->build_sample_item(
4085 biblionumber => $biblio->biblionumber,
4086 library => $library->branchcode,
4087 replacementprice => 99.00,
4092 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
4093 AddIssue( $patron->unblessed, $item->barcode );
4095 my $accountline = Koha::Account::Line->new(
4097 borrowernumber => $patron->borrowernumber,
4098 debit_type_code => 'LOST',
4100 itemnumber => $item->itemnumber,
4102 amountoutstanding => 12,
4103 interface => 'something',
4107 # AddRenewal doesn't call _FixAccountForLostAndFound
4108 AddIssue( $patron->unblessed, $item->barcode );
4110 is( $patron->checkouts->count, 1,
4111 'Renewal should not return the item even if a LOST payment has been made earlier'
4115 subtest 'Filling a hold should cancel existing transfer' => sub {
4118 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
4120 my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
4121 my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
4122 my $patron = $builder->build_object(
4124 class => 'Koha::Patrons',
4126 categorycode => $patron_category->{categorycode},
4127 branchcode => $libraryA->branchcode,
4132 my $item = $builder->build_sample_item({
4133 homebranch => $libraryB->branchcode,
4136 my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4137 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
4139 branchcode => $libraryA->branchcode,
4140 borrowernumber => $patron->borrowernumber,
4141 biblionumber => $item->biblionumber,
4142 itemnumber => $item->itemnumber
4144 my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
4145 is( $reserves->count, 1, "Reserve is placed");
4146 ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
4147 my $reserve = $reserves->next;
4148 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
4149 $reserve->discard_changes;
4150 ok( $reserve->found eq 'W', "Reserve is marked waiting" );
4151 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
4154 $schema->storage->txn_rollback;
4155 C4::Context->clear_syspref_cache();
4156 $branches = Koha::Libraries->search();
4157 for my $branch ( $branches->next ) {
4158 my $key = $branch->branchcode . "_holidays";
4159 $cache->clear_from_cache($key);