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 => 47;
27 use POSIX qw( floor );
29 use t::lib::TestBuilder;
38 use C4::Overdues qw(UpdateFine CalcFine);
41 use Koha::IssuingRules;
43 use Koha::Item::Transfers;
47 use Koha::CirculationRules;
48 use Koha::Subscriptions;
49 use Koha::Account::Lines;
50 use Koha::Account::Offsets;
55 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
59 my ( $error, $question, $alert ) = @_;
61 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
62 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
63 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
67 sub test_debarment_on_checkout {
69 my $item = $params->{item};
70 my $library = $params->{library};
71 my $patron = $params->{patron};
72 my $due_date = $params->{due_date} || dt_from_string;
73 my $return_date = $params->{return_date} || dt_from_string;
74 my $expected_expiration_date = $params->{expiration_date};
76 $expected_expiration_date = output_pref(
78 dt => $expected_expiration_date,
84 my $line_number = $caller[2];
85 AddIssue( $patron, $item->{barcode}, $due_date );
87 my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode}, undef, $return_date );
88 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
89 or diag('AddReturn returned message ' . Dumper $message );
90 my $debarments = Koha::Patron::Debarments::GetDebarments(
91 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
92 is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
94 is( $debarments->[0]->{expiration},
95 $expected_expiration_date, 'Test at line ' . $line_number );
96 Koha::Patron::Debarments::DelUniqueDebarment(
97 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
100 my $schema = Koha::Database->schema;
101 $schema->storage->txn_begin;
102 my $builder = t::lib::TestBuilder->new;
103 my $dbh = C4::Context->dbh;
105 # Prevent random failures by mocking ->now
106 my $now_value = dt_from_string;
107 my $mocked_datetime = Test::MockModule->new('DateTime');
108 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
111 $dbh->{RaiseError} = 1;
113 my $cache = Koha::Caches->get_instance();
114 $dbh->do(q|DELETE FROM special_holidays|);
115 $dbh->do(q|DELETE FROM repeatable_holidays|);
116 $cache->clear_from_cache('single_holidays');
118 # Start with a clean slate
119 $dbh->do('DELETE FROM issues');
120 $dbh->do('DELETE FROM borrowers');
122 my $library = $builder->build({
125 my $library2 = $builder->build({
128 my $itemtype = $builder->build(
130 source => 'Itemtype',
134 rentalcharge_daily => 0,
135 defaultreplacecost => undef,
140 my $patron_category = $builder->build(
142 source => 'Category',
144 category_type => 'P',
146 BlockExpiredPatronOpacActions => -1, # Pick the pref value
151 my $CircControl = C4::Context->preference('CircControl');
152 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
155 homebranch => $library2->{branchcode},
156 holdingbranch => $library2->{branchcode}
160 branchcode => $library2->{branchcode}
163 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
165 # No userenv, PickupLibrary
166 t::lib::Mocks::mock_preference('IndependentBranches', '0');
167 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
169 C4::Context->preference('CircControl'),
171 'CircControl changed to PickupLibrary'
174 C4::Circulation::_GetCircControlBranch($item, $borrower),
175 $item->{$HomeOrHoldingBranch},
176 '_GetCircControlBranch returned item branch (no userenv defined)'
179 # No userenv, PatronLibrary
180 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
182 C4::Context->preference('CircControl'),
184 'CircControl changed to PatronLibrary'
187 C4::Circulation::_GetCircControlBranch($item, $borrower),
188 $borrower->{branchcode},
189 '_GetCircControlBranch returned borrower branch'
192 # No userenv, ItemHomeLibrary
193 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
195 C4::Context->preference('CircControl'),
197 'CircControl changed to ItemHomeLibrary'
200 $item->{$HomeOrHoldingBranch},
201 C4::Circulation::_GetCircControlBranch($item, $borrower),
202 '_GetCircControlBranch returned item branch'
206 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
207 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
209 # Userenv set, PickupLibrary
210 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
212 C4::Context->preference('CircControl'),
214 'CircControl changed to PickupLibrary'
217 C4::Circulation::_GetCircControlBranch($item, $borrower),
218 $library2->{branchcode},
219 '_GetCircControlBranch returned current branch'
222 # Userenv set, PatronLibrary
223 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
225 C4::Context->preference('CircControl'),
227 'CircControl changed to PatronLibrary'
230 C4::Circulation::_GetCircControlBranch($item, $borrower),
231 $borrower->{branchcode},
232 '_GetCircControlBranch returned borrower branch'
235 # Userenv set, ItemHomeLibrary
236 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
238 C4::Context->preference('CircControl'),
240 'CircControl changed to ItemHomeLibrary'
243 C4::Circulation::_GetCircControlBranch($item, $borrower),
244 $item->{$HomeOrHoldingBranch},
245 '_GetCircControlBranch returned item branch'
248 # Reset initial configuration
249 t::lib::Mocks::mock_preference('CircControl', $CircControl);
251 C4::Context->preference('CircControl'),
253 'CircControl reset to its initial value'
256 # Set a simple circ policy
257 $dbh->do('DELETE FROM issuingrules');
258 Koha::CirculationRules->search()->delete();
260 q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
261 issuelength, lengthunit,
262 renewalsallowed, renewalperiod,
263 norenewalbefore, auto_renew,
280 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
281 subtest "CanBookBeRenewed tests" => sub {
284 C4::Context->set_preference('ItemsDeniedRenewal','');
285 # Generate test biblio
286 my $biblio = $builder->build_sample_biblio();
288 my $branch = $library2->{branchcode};
290 my $item_1 = $builder->build_sample_item(
292 biblionumber => $biblio->biblionumber,
294 replacementprice => 12.00,
298 $reused_itemnumber_1 = $item_1->itemnumber;
300 my $item_2 = $builder->build_sample_item(
302 biblionumber => $biblio->biblionumber,
304 replacementprice => 23.00,
308 $reused_itemnumber_2 = $item_2->itemnumber;
310 my $item_3 = $builder->build_sample_item(
312 biblionumber => $biblio->biblionumber,
314 replacementprice => 23.00,
320 my %renewing_borrower_data = (
322 surname => 'Renewal',
323 categorycode => $patron_category->{categorycode},
324 branchcode => $branch,
327 my %reserving_borrower_data = (
328 firstname => 'Katrin',
329 surname => 'Reservation',
330 categorycode => $patron_category->{categorycode},
331 branchcode => $branch,
334 my %hold_waiting_borrower_data = (
336 surname => 'Reservation',
337 categorycode => $patron_category->{categorycode},
338 branchcode => $branch,
341 my %restricted_borrower_data = (
342 firstname => 'Alice',
343 surname => 'Reservation',
344 categorycode => $patron_category->{categorycode},
345 debarred => '3228-01-01',
346 branchcode => $branch,
349 my %expired_borrower_data = (
352 categorycode => $patron_category->{categorycode},
353 branchcode => $branch,
354 dateexpiry => dt_from_string->subtract( months => 1 ),
357 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
358 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
359 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
360 my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
361 my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
363 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
364 my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
365 my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
372 my $checkitem = undef;
375 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
376 my $datedue = dt_from_string( $issue->date_due() );
377 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
379 my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
380 $datedue = dt_from_string( $issue->date_due() );
381 is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
384 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
385 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
387 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
388 is( $renewokay, 1, 'Can renew, no holds for this title or item');
391 # Biblio-level hold, renewal test
393 $branch, $reserving_borrowernumber, $biblio->biblionumber,
394 $bibitems, $priority, $resdate, $expdate, $notes,
395 'a title', $checkitem, $found
398 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
399 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
400 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
401 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
402 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
403 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
404 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
406 # Now let's add an item level hold, we should no longer be able to renew the item
407 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
409 borrowernumber => $hold_waiting_borrowernumber,
410 biblionumber => $biblio->biblionumber,
411 itemnumber => $item_1->itemnumber,
412 branchcode => $branch,
416 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
417 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
420 # 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
421 # be able to renew these items
422 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
424 borrowernumber => $hold_waiting_borrowernumber,
425 biblionumber => $biblio->biblionumber,
426 itemnumber => $item_3->itemnumber,
427 branchcode => $branch,
432 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
433 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
434 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
435 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
436 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
438 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
439 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
440 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
442 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
443 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
444 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
446 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
447 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
448 AddIssue($reserving_borrower, $item_3->barcode);
449 my $reserve = $dbh->selectrow_hashref(
450 'SELECT * FROM old_reserves WHERE reserve_id = ?',
454 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
456 # Item-level hold, renewal test
458 $branch, $reserving_borrowernumber, $biblio->biblionumber,
459 $bibitems, $priority, $resdate, $expdate, $notes,
460 'a title', $item_1->itemnumber, $found
463 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
464 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
465 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
467 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
468 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
470 # Items can't fill hold for reasons
471 ModItem({ notforloan => 1 }, $biblio->biblionumber, $item_1->itemnumber);
472 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
473 is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
474 ModItem({ notforloan => 0, itype => $itemtype }, $biblio->biblionumber, $item_1->itemnumber);
476 # FIXME: Add more for itemtype not for loan etc.
478 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
479 my $item_5 = $builder->build_sample_item(
481 biblionumber => $biblio->biblionumber,
483 replacementprice => 23.00,
487 my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
488 is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
490 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
491 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
492 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
493 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
494 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
496 # Users cannot renew an overdue item
497 my $item_6 = $builder->build_sample_item(
499 biblionumber => $biblio->biblionumber,
501 replacementprice => 23.00,
506 my $item_7 = $builder->build_sample_item(
508 biblionumber => $biblio->biblionumber,
510 replacementprice => 23.00,
515 my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
516 is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
518 my $now = dt_from_string();
519 my $five_weeks = DateTime::Duration->new(weeks => 5);
520 my $five_weeks_ago = $now - $five_weeks;
521 t::lib::Mocks::mock_preference('finesMode', 'production');
523 my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
524 is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
526 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
527 C4::Overdues::UpdateFine(
529 issue_id => $passeddatedue1->id(),
530 itemnumber => $item_7->itemnumber,
531 borrowernumber => $renewing_borrower->{borrowernumber},
533 due => Koha::DateUtils::output_pref($five_weeks_ago)
537 t::lib::Mocks::mock_preference('RenewalLog', 0);
538 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
539 my %params_renewal = (
540 timestamp => { -like => $date . "%" },
541 module => "CIRCULATION",
545 timestamp => { -like => $date . "%" },
546 module => "CIRCULATION",
549 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
550 my $dt = dt_from_string();
551 Time::Fake->offset( $dt->epoch );
552 my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
553 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
554 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
555 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
558 t::lib::Mocks::mock_preference('RenewalLog', 1);
559 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
560 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
561 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
562 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
563 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
565 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
566 is( $fines->count, 2, 'AddRenewal left both fines' );
567 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
568 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
572 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
573 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
574 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
575 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
576 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
577 $new_log_size = Koha::ActionLogs->count( \%params_issue );
578 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
580 $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
583 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
584 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
585 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
586 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
587 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
590 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
594 # Test automatic renewal before value for "norenewalbefore" in policy is set
595 # In this case automatic renewal is not permitted prior to due date
596 my $item_4 = $builder->build_sample_item(
598 biblionumber => $biblio->biblionumber,
600 replacementprice => 16.00,
605 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
606 ( $renewokay, $error ) =
607 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
608 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
609 is( $error, 'auto_too_soon',
610 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
612 $branch, $reserving_borrowernumber, $biblio->biblionumber,
613 $bibitems, $priority, $resdate, $expdate, $notes,
614 'a title', $item_4->itemnumber, $found
616 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
617 is( $renewokay, 0, 'Still should not be able to renew' );
618 is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' );
619 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, undef, 1 );
620 is( $renewokay, 0, 'Still should not be able to renew' );
621 is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' );
622 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
623 is( $renewokay, 0, 'Still should not be able to renew' );
624 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
625 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1, 1 );
626 is( $renewokay, 0, 'Still should not be able to renew' );
627 is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' );
628 $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"');
629 ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber, 1 );
630 is( $renewokay, 0, 'Still should not be able to renew' );
631 is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' );
632 ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber);
637 # Test premature manual renewal
638 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
640 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
641 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
642 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
645 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
646 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
648 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
649 $datedue->clone->add( days => -7 ),
650 'Bug 14395: Renewals permitted 7 days before due date, as expected'
654 # Test 'date' setting for syspref NoRenewalBeforePrecision
655 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
657 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
658 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
659 'Bug 14395: Renewals permitted 7 days before due date, as expected'
663 # Test premature automatic renewal
664 ( $renewokay, $error ) =
665 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
666 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
667 is( $error, 'auto_too_soon',
668 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
671 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
672 # and test automatic renewal again
673 $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
674 ( $renewokay, $error ) =
675 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
676 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
677 is( $error, 'auto_too_soon',
678 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
681 # Change policy so that loans can be renewed 99 days prior to the due date
682 # and test automatic renewal again
683 $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
684 ( $renewokay, $error ) =
685 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
686 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
687 is( $error, 'auto_renew',
688 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
691 subtest "too_late_renewal / no_auto_renewal_after" => sub {
693 my $item_to_auto_renew = $builder->build(
696 biblionumber => $biblio->biblionumber,
697 homebranch => $branch,
698 holdingbranch => $branch,
703 my $ten_days_before = dt_from_string->add( days => -10 );
704 my $ten_days_ahead = dt_from_string->add( days => 10 );
705 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
707 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 9');
708 ( $renewokay, $error ) =
709 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
710 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
711 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
713 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 10');
714 ( $renewokay, $error ) =
715 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
716 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
717 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
719 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 11');
720 ( $renewokay, $error ) =
721 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
722 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
723 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
725 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
726 ( $renewokay, $error ) =
727 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
728 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
729 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
731 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => -1 ) );
732 ( $renewokay, $error ) =
733 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
734 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
735 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
737 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => -1 ) );
738 ( $renewokay, $error ) =
739 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
740 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
741 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
743 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => 1 ) );
744 ( $renewokay, $error ) =
745 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
746 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
747 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
750 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
752 my $item_to_auto_renew = $builder->build({
755 biblionumber => $biblio->biblionumber,
756 homebranch => $branch,
757 holdingbranch => $branch,
761 my $ten_days_before = dt_from_string->add( days => -10 );
762 my $ten_days_ahead = dt_from_string->add( days => 10 );
763 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
765 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
766 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
767 C4::Context->set_preference('OPACFineNoRenewals','10');
768 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
769 my $fines_amount = 5;
770 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
773 amount => $fines_amount,
776 item_id => $item_to_auto_renew->{itemnumber},
777 description => "Some fines"
779 )->status('RETURNED')->store;
780 ( $renewokay, $error ) =
781 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
782 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
783 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
787 amount => $fines_amount,
790 item_id => $item_to_auto_renew->{itemnumber},
791 description => "Some fines"
793 )->status('RETURNED')->store;
794 ( $renewokay, $error ) =
795 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
796 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
797 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
801 amount => $fines_amount,
804 item_id => $item_to_auto_renew->{itemnumber},
805 description => "Some fines"
807 )->status('RETURNED')->store;
808 ( $renewokay, $error ) =
809 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
810 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
811 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
813 $account->add_credit(
815 amount => $fines_amount,
818 description => "Some payment"
821 ( $renewokay, $error ) =
822 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
823 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
824 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
826 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
827 ( $renewokay, $error ) =
828 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
829 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
830 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
832 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
833 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
836 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
838 my $item_to_auto_renew = $builder->build({
841 biblionumber => $biblio->biblionumber,
842 homebranch => $branch,
843 holdingbranch => $branch,
847 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
849 my $ten_days_before = dt_from_string->add( days => -10 );
850 my $ten_days_ahead = dt_from_string->add( days => 10 );
852 # Patron is expired and BlockExpiredPatronOpacActions=0
853 # => auto renew is allowed
854 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
855 my $patron = $expired_borrower;
856 my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
857 ( $renewokay, $error ) =
858 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
859 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
860 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
861 Koha::Checkouts->find( $checkout->issue_id )->delete;
864 # Patron is expired and BlockExpiredPatronOpacActions=1
865 # => auto renew is not allowed
866 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
867 $patron = $expired_borrower;
868 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
869 ( $renewokay, $error ) =
870 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
871 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
872 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
873 Koha::Checkouts->find( $checkout->issue_id )->delete;
876 # Patron is not expired and BlockExpiredPatronOpacActions=1
877 # => auto renew is allowed
878 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
879 $patron = $renewing_borrower;
880 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
881 ( $renewokay, $error ) =
882 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
883 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
884 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
885 Koha::Checkouts->find( $checkout->issue_id )->delete;
888 subtest "GetLatestAutoRenewDate" => sub {
890 my $item_to_auto_renew = $builder->build(
893 biblionumber => $biblio->biblionumber,
894 homebranch => $branch,
895 holdingbranch => $branch,
900 my $ten_days_before = dt_from_string->add( days => -10 );
901 my $ten_days_ahead = dt_from_string->add( days => 10 );
902 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
903 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = NULL');
904 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
905 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' );
906 my $five_days_before = dt_from_string->add( days => -5 );
907 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 5, no_auto_renewal_after_hard_limit = NULL');
908 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
909 is( $latest_auto_renew_date->truncate( to => 'minute' ),
910 $five_days_before->truncate( to => 'minute' ),
911 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
913 my $five_days_ahead = dt_from_string->add( days => 5 );
914 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = NULL');
915 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
916 is( $latest_auto_renew_date->truncate( to => 'minute' ),
917 $five_days_ahead->truncate( to => 'minute' ),
918 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
920 my $two_days_ahead = dt_from_string->add( days => 2 );
921 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => 2 ) );
922 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
923 is( $latest_auto_renew_date->truncate( to => 'day' ),
924 $two_days_ahead->truncate( to => 'day' ),
925 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
927 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = ?', undef, dt_from_string->add( days => 2 ) );
928 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
929 is( $latest_auto_renew_date->truncate( to => 'day' ),
930 $two_days_ahead->truncate( to => 'day' ),
931 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
938 # set policy to forbid renewals
939 $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
941 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
942 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
943 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
945 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
946 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
947 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
949 C4::Overdues::UpdateFine(
951 issue_id => $issue->id(),
952 itemnumber => $item_1->itemnumber,
953 borrowernumber => $renewing_borrower->{borrowernumber},
956 due => Koha::DateUtils::output_pref($datedue)
960 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
961 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
962 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
963 is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' );
964 is( $line->amount+0, 15, 'Account line amount is 15.00' );
965 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
967 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
968 is( $offset->type, 'OVERDUE', 'Account offset type is Fine' );
969 is( $offset->amount+0, 15, 'Account offset amount is 15.00' );
971 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
972 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
974 LostItem( $item_1->itemnumber, 'test', 1 );
976 $line = Koha::Account::Lines->find($line->id);
977 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
978 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
980 my $item = Koha::Items->find($item_1->itemnumber);
981 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
982 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
983 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
985 my $total_due = $dbh->selectrow_array(
986 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
987 undef, $renewing_borrower->{borrowernumber}
990 is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
992 C4::Context->dbh->do("DELETE FROM accountlines");
994 C4::Overdues::UpdateFine(
996 issue_id => $issue2->id(),
997 itemnumber => $item_2->itemnumber,
998 borrowernumber => $renewing_borrower->{borrowernumber},
1001 due => Koha::DateUtils::output_pref($datedue)
1005 LostItem( $item_2->itemnumber, 'test', 0 );
1007 my $item2 = Koha::Items->find($item_2->itemnumber);
1008 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
1009 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
1011 $total_due = $dbh->selectrow_array(
1012 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
1013 undef, $renewing_borrower->{borrowernumber}
1016 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
1018 my $future = dt_from_string();
1019 $future->add( days => 7 );
1020 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
1021 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
1023 # Users cannot renew any item if there is an overdue item
1024 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
1025 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
1026 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1027 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
1028 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1030 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1031 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1032 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1033 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1034 LostItem( $item_3->itemnumber, 'test', 0 );
1035 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1036 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1038 $accountline->description,
1039 sprintf( "%s %s %s",
1040 $item_3->biblio->title || '',
1041 $item_3->barcode || '',
1042 $item_3->itemcallnumber || '' ),
1043 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1047 subtest "GetUpcomingDueIssues" => sub {
1050 my $branch = $library2->{branchcode};
1052 #Create another record
1053 my $biblio2 = $builder->build_sample_biblio();
1056 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1057 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1058 my $item_3 = $builder->build_sample_item(
1060 biblionumber => $biblio2->biblionumber,
1068 my %a_borrower_data = (
1069 firstname => 'Fridolyn',
1070 surname => 'SOMERS',
1071 categorycode => $patron_category->{categorycode},
1072 branchcode => $branch,
1075 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1076 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1078 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1079 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1080 my $today = DateTime->today(time_zone => C4::Context->tz());
1082 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1083 my $datedue = dt_from_string( $issue->date_due() );
1084 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1085 my $datedue2 = dt_from_string( $issue->date_due() );
1089 # GetUpcomingDueIssues tests
1091 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1092 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1095 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1096 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1097 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1100 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1101 is ( scalar( @$upcoming_dues ), 1,
1102 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1105 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1107 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1109 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1110 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1112 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1113 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1115 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1116 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1118 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1119 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1121 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1122 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1124 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1125 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1129 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1130 my $branch = $library2->{branchcode};
1132 my $biblio = $builder->build_sample_biblio();
1135 my $item = $builder->build_sample_item(
1137 biblionumber => $biblio->biblionumber,
1144 my %a_borrower_data = (
1145 firstname => 'Kyle',
1147 categorycode => $patron_category->{categorycode},
1148 branchcode => $branch,
1151 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1153 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1154 my $issue = AddIssue( $borrower, $item->barcode );
1157 issue_id => $issue->id(),
1158 itemnumber => $item->itemnumber,
1159 borrowernumber => $borrowernumber,
1165 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1166 my $count = $hr->{count};
1168 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1171 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1172 $dbh->do('DELETE FROM issues');
1173 $dbh->do('DELETE FROM items');
1174 $dbh->do('DELETE FROM issuingrules');
1175 Koha::CirculationRules->search()->delete();
1178 INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
1179 norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
1188 Koha::CirculationRules->set_rules(
1190 categorycode => '*',
1198 my $biblio = $builder->build_sample_biblio();
1200 my $item_1 = $builder->build_sample_item(
1202 biblionumber => $biblio->biblionumber,
1203 library => $library2->{branchcode},
1208 my $item_2= $builder->build_sample_item(
1210 biblionumber => $biblio->biblionumber,
1211 library => $library2->{branchcode},
1216 my $borrowernumber1 = Koha::Patron->new({
1217 firstname => 'Kyle',
1219 categorycode => $patron_category->{categorycode},
1220 branchcode => $library2->{branchcode},
1221 })->store->borrowernumber;
1222 my $borrowernumber2 = Koha::Patron->new({
1223 firstname => 'Chelsea',
1225 categorycode => $patron_category->{categorycode},
1226 branchcode => $library2->{branchcode},
1227 })->store->borrowernumber;
1229 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1230 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1232 my $issue = AddIssue( $borrower1, $item_1->barcode );
1234 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1235 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1238 $library2->{branchcode}, $borrowernumber2, $biblio->biblionumber,
1239 '', 1, undef, undef, '',
1243 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1244 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1245 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1246 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1248 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1249 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1250 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1251 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1253 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1254 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1255 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1256 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1258 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1259 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1260 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1261 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1263 # Setting item not checked out to be not for loan but holdable
1264 ModItem({ notforloan => -1 }, $biblio->biblionumber, $item_2->itemnumber);
1266 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1267 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' );
1271 # Don't allow renewing onsite checkout
1272 my $branch = $library->{branchcode};
1274 #Create another record
1275 my $biblio = $builder->build_sample_biblio();
1277 my $item = $builder->build_sample_item(
1279 biblionumber => $biblio->biblionumber,
1285 my $borrowernumber = Koha::Patron->new({
1288 categorycode => $patron_category->{categorycode},
1289 branchcode => $branch,
1290 })->store->borrowernumber;
1292 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1294 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1295 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1296 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1297 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1301 my $library = $builder->build({ source => 'Branch' });
1303 my $biblio = $builder->build_sample_biblio();
1305 my $item = $builder->build_sample_item(
1307 biblionumber => $biblio->biblionumber,
1308 library => $library->{branchcode},
1313 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1315 my $issue = AddIssue( $patron, $item->barcode );
1318 issue_id => $issue->id(),
1319 itemnumber => $item->itemnumber,
1320 borrowernumber => $patron->{borrowernumber},
1327 issue_id => $issue->id(),
1328 itemnumber => $item->itemnumber,
1329 borrowernumber => $patron->{borrowernumber},
1334 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1337 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1340 my $homebranch = $builder->build( { source => 'Branch' } );
1341 my $holdingbranch = $builder->build( { source => 'Branch' } );
1342 my $otherbranch = $builder->build( { source => 'Branch' } );
1343 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1344 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1346 my $item = $builder->build_sample_item(
1348 homebranch => $homebranch->{branchcode},
1349 holdingbranch => $holdingbranch->{branchcode},
1353 set_userenv($holdingbranch);
1355 my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1356 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1358 my ( $error, $question, $alerts );
1360 # AllowReturnToBranch == anywhere
1361 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1362 ## Test that unknown barcodes don't generate internal server errors
1363 set_userenv($homebranch);
1364 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1365 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1366 ## Can be issued from homebranch
1367 set_userenv($homebranch);
1368 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1369 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1370 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1371 ## Can be issued from holdingbranch
1372 set_userenv($holdingbranch);
1373 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1374 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1375 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1376 ## Can be issued from another branch
1377 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1378 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1379 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1381 # AllowReturnToBranch == holdingbranch
1382 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1383 ## Cannot be issued from homebranch
1384 set_userenv($homebranch);
1385 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1386 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1387 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1388 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1389 ## Can be issued from holdinbranch
1390 set_userenv($holdingbranch);
1391 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1392 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1393 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1394 ## Cannot be issued from another branch
1395 set_userenv($otherbranch);
1396 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1397 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1398 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1399 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
1401 # AllowReturnToBranch == homebranch
1402 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1403 ## Can be issued from holdinbranch
1404 set_userenv($homebranch);
1405 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1406 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1407 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1408 ## Cannot be issued from holdinbranch
1409 set_userenv($holdingbranch);
1410 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1411 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1412 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1413 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1414 ## Cannot be issued from holdinbranch
1415 set_userenv($otherbranch);
1416 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1417 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1418 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1419 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1421 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1424 subtest 'AddIssue & AllowReturnToBranch' => sub {
1427 my $homebranch = $builder->build( { source => 'Branch' } );
1428 my $holdingbranch = $builder->build( { source => 'Branch' } );
1429 my $otherbranch = $builder->build( { source => 'Branch' } );
1430 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1431 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1433 my $item = $builder->build_sample_item(
1435 homebranch => $homebranch->{branchcode},
1436 holdingbranch => $holdingbranch->{branchcode},
1440 set_userenv($holdingbranch);
1442 my $ref_issue = 'Koha::Checkout';
1443 my $issue = AddIssue( $patron_1, $item->{barcode} );
1445 my ( $error, $question, $alerts );
1447 # AllowReturnToBranch == homebranch
1448 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1449 ## Can be issued from homebranch
1450 set_userenv($homebranch);
1451 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
1452 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1453 ## Can be issued from holdinbranch
1454 set_userenv($holdingbranch);
1455 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
1456 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1457 ## Can be issued from another branch
1458 set_userenv($otherbranch);
1459 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
1460 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1462 # AllowReturnToBranch == holdinbranch
1463 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1464 ## Cannot be issued from homebranch
1465 set_userenv($homebranch);
1466 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
1467 ## Can be issued from holdingbranch
1468 set_userenv($holdingbranch);
1469 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
1470 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1471 ## Cannot be issued from another branch
1472 set_userenv($otherbranch);
1473 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
1475 # AllowReturnToBranch == homebranch
1476 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1477 ## Can be issued from homebranch
1478 set_userenv($homebranch);
1479 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
1480 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1481 ## Cannot be issued from holdinbranch
1482 set_userenv($holdingbranch);
1483 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
1484 ## Cannot be issued from another branch
1485 set_userenv($otherbranch);
1486 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
1487 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1490 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1493 my $library = $builder->build( { source => 'Branch' } );
1494 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1495 my $item_1 = $builder->build_sample_item(
1497 library => $library->{branchcode},
1500 my $item_2 = $builder->build_sample_item(
1502 library => $library->{branchcode},
1506 my ( $error, $question, $alerts );
1508 # Patron cannot issue item_1, they have overdues
1509 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1510 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday ); # Add an overdue
1512 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1513 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1514 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
1515 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1517 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1518 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1519 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1520 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1522 # Patron cannot issue item_1, they are debarred
1523 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1524 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1525 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1526 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1527 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1529 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1530 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1531 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1532 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1535 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1538 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1539 my $patron_category_x = $builder->build_object(
1541 class => 'Koha::Patron::Categories',
1542 value => { category_type => 'X' }
1545 my $patron = $builder->build_object(
1547 class => 'Koha::Patrons',
1549 categorycode => $patron_category_x->categorycode,
1550 gonenoaddress => undef,
1557 my $item_1 = $builder->build_sample_item(
1559 library => $library->{branchcode},
1563 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1564 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1566 # TODO There are other tests to provide here
1569 subtest 'MultipleReserves' => sub {
1572 my $biblio = $builder->build_sample_biblio();
1574 my $branch = $library2->{branchcode};
1576 my $item_1 = $builder->build_sample_item(
1578 biblionumber => $biblio->biblionumber,
1580 replacementprice => 12.00,
1585 my $item_2 = $builder->build_sample_item(
1587 biblionumber => $biblio->biblionumber,
1589 replacementprice => 12.00,
1596 my $resdate = undef;
1597 my $expdate = undef;
1599 my $checkitem = undef;
1602 my %renewing_borrower_data = (
1603 firstname => 'John',
1604 surname => 'Renewal',
1605 categorycode => $patron_category->{categorycode},
1606 branchcode => $branch,
1608 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1609 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1610 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1611 my $datedue = dt_from_string( $issue->date_due() );
1612 is (defined $issue->date_due(), 1, "item 1 checked out");
1613 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1615 my %reserving_borrower_data1 = (
1616 firstname => 'Katrin',
1617 surname => 'Reservation',
1618 categorycode => $patron_category->{categorycode},
1619 branchcode => $branch,
1621 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1623 $branch, $reserving_borrowernumber1, $biblio->biblionumber,
1624 $bibitems, $priority, $resdate, $expdate, $notes,
1625 'a title', $checkitem, $found
1628 my %reserving_borrower_data2 = (
1629 firstname => 'Kirk',
1630 surname => 'Reservation',
1631 categorycode => $patron_category->{categorycode},
1632 branchcode => $branch,
1634 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1636 $branch, $reserving_borrowernumber2, $biblio->biblionumber,
1637 $bibitems, $priority, $resdate, $expdate, $notes,
1638 'a title', $checkitem, $found
1642 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1643 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1646 my $item_3 = $builder->build_sample_item(
1648 biblionumber => $biblio->biblionumber,
1650 replacementprice => 12.00,
1656 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1657 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1661 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1664 my $library = $builder->build( { source => 'Branch' } );
1665 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1667 my $biblionumber = $builder->build_sample_biblio(
1669 branchcode => $library->{branchcode},
1672 my $item_1 = $builder->build_sample_item(
1674 biblionumber => $biblionumber,
1675 library => $library->{branchcode},
1679 my $item_2 = $builder->build_sample_item(
1681 biblionumber => $biblionumber,
1682 library => $library->{branchcode},
1686 my ( $error, $question, $alerts );
1687 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1689 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1690 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1691 is( keys(%$error) + keys(%$alerts), 0, 'No error or alert should be raised' . str($error, $question, $alerts) );
1692 is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' . str($error, $question, $alerts) );
1694 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1695 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1696 is( keys(%$error) + keys(%$question) + keys(%$alerts), 0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' . str($error, $question, $alerts) );
1698 # Add a subscription
1699 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1701 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1702 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1703 is( keys(%$error) + keys(%$question) + keys(%$alerts), 0, 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription' . str($error, $question, $alerts) );
1705 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1706 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1707 is( keys(%$error) + keys(%$question) + keys(%$alerts), 0, 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription' . str($error, $question, $alerts) );
1710 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1713 my $library = $builder->build( { source => 'Branch' } );
1714 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1717 my $biblionumber = $builder->build_sample_biblio(
1719 branchcode => $library->{branchcode},
1722 my $item_1 = $builder->build_sample_item(
1724 biblionumber => $biblionumber,
1725 library => $library->{branchcode},
1728 my $item_2 = $builder->build_sample_item(
1730 biblionumber => $biblionumber,
1731 library => $library->{branchcode},
1735 # And the issuing rule
1736 Koha::IssuingRules->search->delete;
1737 my $rule = Koha::IssuingRule->new(
1739 categorycode => '*',
1743 firstremind => 1, # 1 day of grace
1744 finedays => 2, # 2 days of fine per day of overdue
1745 lengthunit => 'days',
1750 # Patron cannot issue item_1, they have overdues
1751 my $now = dt_from_string;
1752 my $five_days_ago = $now->clone->subtract( days => 5 );
1753 my $ten_days_ago = $now->clone->subtract( days => 10 );
1754 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
1755 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1756 ; # Add another overdue
1758 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1759 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, $now );
1760 my $debarments = Koha::Patron::Debarments::GetDebarments(
1761 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1762 is( scalar(@$debarments), 1 );
1764 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1765 # Same for the others
1766 my $expected_expiration = output_pref(
1768 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
1769 dateformat => 'sql',
1773 is( $debarments->[0]->{expiration}, $expected_expiration );
1775 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, $now );
1776 $debarments = Koha::Patron::Debarments::GetDebarments(
1777 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1778 is( scalar(@$debarments), 1 );
1779 $expected_expiration = output_pref(
1781 dt => $now->clone->add( days => ( 10 - 1 ) * 2 ),
1782 dateformat => 'sql',
1786 is( $debarments->[0]->{expiration}, $expected_expiration );
1788 Koha::Patron::Debarments::DelUniqueDebarment(
1789 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1791 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1792 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
1793 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1794 ; # Add another overdue
1795 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, $now );
1796 $debarments = Koha::Patron::Debarments::GetDebarments(
1797 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1798 is( scalar(@$debarments), 1 );
1799 $expected_expiration = output_pref(
1801 dt => $now->clone->add( days => ( 5 - 1 ) * 2 ),
1802 dateformat => 'sql',
1806 is( $debarments->[0]->{expiration}, $expected_expiration );
1808 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, $now );
1809 $debarments = Koha::Patron::Debarments::GetDebarments(
1810 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1811 is( scalar(@$debarments), 1 );
1812 $expected_expiration = output_pref(
1814 dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1815 dateformat => 'sql',
1819 is( $debarments->[0]->{expiration}, $expected_expiration );
1822 subtest 'AddReturn + suspension_chargeperiod' => sub {
1825 my $library = $builder->build( { source => 'Branch' } );
1826 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1828 my $biblionumber = $builder->build_sample_biblio(
1830 branchcode => $library->{branchcode},
1833 my $item_1 = $builder->build_sample_item(
1835 biblionumber => $biblionumber,
1836 library => $library->{branchcode},
1840 # And the issuing rule
1841 Koha::IssuingRules->search->delete;
1842 my $rule = Koha::IssuingRule->new(
1844 categorycode => '*',
1848 firstremind => 0, # 0 day of grace
1849 finedays => 2, # 2 days of fine per day of overdue
1850 suspension_chargeperiod => 1,
1851 lengthunit => 'days',
1856 my $now = dt_from_string;
1857 my $five_days_ago = $now->clone->subtract( days => 5 );
1858 # We want to charge 2 days every day, without grace
1859 # With 5 days of overdue: 5 * Z
1860 my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 );
1861 test_debarment_on_checkout(
1864 library => $library,
1866 due_date => $five_days_ago,
1867 expiration_date => $expected_expiration,
1871 # We want to charge 2 days every 2 days, without grace
1872 # With 5 days of overdue: (5 * 2) / 2
1873 $rule->suspension_chargeperiod(2)->store;
1874 $expected_expiration = $now->clone->add( days => floor( 5 * 2 ) / 2 );
1875 test_debarment_on_checkout(
1878 library => $library,
1880 due_date => $five_days_ago,
1881 expiration_date => $expected_expiration,
1885 # We want to charge 2 days every 3 days, with 1 day of grace
1886 # With 5 days of overdue: ((5-1) / 3 ) * 2
1887 $rule->suspension_chargeperiod(3)->store;
1888 $rule->firstremind(1)->store;
1889 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
1890 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
1891 test_debarment_on_checkout(
1894 library => $library,
1896 due_date => $five_days_ago,
1897 expiration_date => $expected_expiration,
1901 # Use finesCalendar to know if holiday must be skipped to calculate the due date
1902 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
1903 $rule->finedays(2)->store;
1904 $rule->suspension_chargeperiod(1)->store;
1905 $rule->firstremind(0)->store;
1906 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
1907 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
1909 # Adding a holiday 2 days ago
1910 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
1911 my $two_days_ago = $now->clone->subtract( days => 2 );
1912 $calendar->insert_single_holiday(
1913 day => $two_days_ago->day,
1914 month => $two_days_ago->month,
1915 year => $two_days_ago->year,
1916 title => 'holidayTest-2d',
1917 description => 'holidayDesc 2 days ago'
1919 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
1920 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
1921 test_debarment_on_checkout(
1924 library => $library,
1926 due_date => $five_days_ago,
1927 expiration_date => $expected_expiration,
1931 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
1932 my $two_days_ahead = $now->clone->add( days => 2 );
1933 $calendar->insert_single_holiday(
1934 day => $two_days_ahead->day,
1935 month => $two_days_ahead->month,
1936 year => $two_days_ahead->year,
1937 title => 'holidayTest+2d',
1938 description => 'holidayDesc 2 days ahead'
1941 # Same as above, but we should skip D+2
1942 $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
1943 test_debarment_on_checkout(
1946 library => $library,
1948 due_date => $five_days_ago,
1949 expiration_date => $expected_expiration,
1953 # Adding another holiday, day of expiration date
1954 my $expected_expiration_dt = dt_from_string($expected_expiration);
1955 $calendar->insert_single_holiday(
1956 day => $expected_expiration_dt->day,
1957 month => $expected_expiration_dt->month,
1958 year => $expected_expiration_dt->year,
1959 title => 'holidayTest_exp',
1960 description => 'holidayDesc on expiration date'
1962 # Expiration date will be the day after
1963 test_debarment_on_checkout(
1966 library => $library,
1968 due_date => $five_days_ago,
1969 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
1973 test_debarment_on_checkout(
1976 library => $library,
1978 return_date => $now->clone->add(days => 5),
1979 expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ),
1983 test_debarment_on_checkout(
1986 library => $library,
1988 due_date => $now->clone->add(days => 1),
1989 return_date => $now->clone->add(days => 5),
1990 expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ),
1996 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
1999 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2000 my $patron1 = $builder->build_object(
2002 class => 'Koha::Patrons',
2004 library => $library->branchcode,
2005 categorycode => $patron_category->{categorycode}
2009 my $patron2 = $builder->build_object(
2011 class => 'Koha::Patrons',
2013 library => $library->branchcode,
2014 categorycode => $patron_category->{categorycode}
2019 t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
2021 my $item = $builder->build_sample_item(
2023 library => $library->branchcode,
2027 my ( $error, $question, $alerts );
2028 my $issue = AddIssue( $patron1->unblessed, $item->{barcode} );
2030 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2031 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
2032 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' );
2034 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
2035 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
2036 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' );
2038 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2042 subtest 'AddReturn | is_overdue' => sub {
2045 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2046 t::lib::Mocks::mock_preference('finesMode', 'production');
2047 t::lib::Mocks::mock_preference('MaxFine', '100');
2049 my $library = $builder->build( { source => 'Branch' } );
2050 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2051 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2052 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2054 my $item = $builder->build_sample_item(
2056 library => $library->{branchcode},
2057 replacementprice => 7
2061 Koha::IssuingRules->search->delete;
2062 my $rule = Koha::IssuingRule->new(
2064 categorycode => '*',
2068 lengthunit => 'days',
2069 fine => 1, # Charge 1 every day of overdue
2075 my $now = dt_from_string;
2076 my $one_day_ago = $now->clone->subtract( days => 1 );
2077 my $five_days_ago = $now->clone->subtract( days => 5 );
2078 my $ten_days_ago = $now->clone->subtract( days => 10 );
2079 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2081 # No return date specified, today will be used => 10 days overdue charged
2082 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2083 AddReturn( $item->{barcode}, $library->{branchcode} );
2084 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2085 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2087 # specify return date 5 days before => no overdue charged
2088 AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
2089 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
2090 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2091 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2093 # specify return date 5 days later => 5 days overdue charged
2094 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2095 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
2096 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2097 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2099 # specify return date 5 days later, specify exemptfine => no overdue charge
2100 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2101 AddReturn( $item->{barcode}, $library->{branchcode}, 1, $five_days_ago );
2102 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2103 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2105 subtest 'bug 22877' => sub {
2109 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2111 # Fake fines cronjob on this checkout
2113 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2114 $ten_days_ago, $now );
2117 issue_id => $issue->issue_id,
2118 itemnumber => $item->{itemnumber},
2119 borrowernumber => $patron->borrowernumber,
2121 due => output_pref($ten_days_ago)
2124 is( int( $patron->account->balance() ),
2125 10, "Overdue fine of 10 days overdue" );
2127 # Fake longoverdue with charge and not marking returned
2128 LostItem( $item->{itemnumber}, 'cronjob', 0 );
2129 is( int( $patron->account->balance() ),
2130 17, "Lost fine of 7 plus 10 days overdue" );
2132 # Now we return it today
2133 AddReturn( $item->{barcode}, $library->{branchcode} );
2134 is( int( $patron->account->balance() ),
2135 17, "Should have a single 10 days overdue fine and lost charge" );
2138 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2141 subtest 'bug 25417 | backdated return + exemptfine' => sub {
2145 t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1);
2147 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $one_day_ago ); # date due was 1d ago
2149 # Fake fines cronjob on this checkout
2151 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2152 $one_day_ago, $now );
2155 issue_id => $issue->issue_id,
2156 itemnumber => $item->{itemnumber},
2157 borrowernumber => $patron->borrowernumber,
2159 due => output_pref($one_day_ago)
2162 is( int( $patron->account->balance() ),
2163 1, "Overdue fine of 1 day overdue" );
2165 # Backdated return (dropbox mode example - charge should exist but be zero)
2166 AddReturn( $item->{barcode}, $library->{branchcode}, 1, $one_day_ago );
2167 is( int( $patron->account->balance() ),
2168 0, "Overdue fine should be annulled" );
2169 my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber });
2170 is( $lines->count, 1, "Overdue fine accountlines still exists");
2171 my $line = $lines->next;
2172 is($line->amount+0,0, "Overdue fine amount has been reduced to 0");
2173 is($line->amountoutstanding+0,0, "Overdue fine amount outstanding has been reduced to 0");
2174 is($line->status,'RETURNED', "Overdue fine was fixed");
2177 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2181 subtest '_FixAccountForLostAndReturned' => sub {
2185 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
2186 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
2188 my $processfee_amount = 20;
2189 my $replacement_amount = 99.00;
2190 my $item_type = $builder->build_object(
2191 { class => 'Koha::ItemTypes',
2193 notforloan => undef,
2195 defaultreplacecost => undef,
2196 processfee => $processfee_amount,
2197 rentalcharge_daily => 0,
2201 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2203 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
2205 subtest 'Full write-off tests' => sub {
2209 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2210 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2211 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
2213 my $item = $builder->build_sample_item(
2215 biblionumber => $biblio->biblionumber,
2216 library => $library->branchcode,
2217 replacementprice => $replacement_amount,
2218 itype => $item_type->itemtype,
2222 AddIssue( $patron->unblessed, $item->barcode );
2224 # Simulate item marked as lost
2225 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2226 LostItem( $item->itemnumber, 1 );
2228 my $processing_fee_lines = Koha::Account::Lines->search(
2229 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2230 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2231 my $processing_fee_line = $processing_fee_lines->next;
2232 is( $processing_fee_line->amount + 0,
2233 $processfee_amount, 'The right PROCESSING amount is generated' );
2234 is( $processing_fee_line->amountoutstanding + 0,
2235 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2237 my $lost_fee_lines = Koha::Account::Lines->search(
2238 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2239 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2240 my $lost_fee_line = $lost_fee_lines->next;
2241 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2242 is( $lost_fee_line->amountoutstanding + 0,
2243 $replacement_amount, 'The right LOST amountoutstanding is generated' );
2244 is( $lost_fee_line->status,
2245 undef, 'The LOST status was not set' );
2247 my $account = $patron->account;
2248 my $debts = $account->outstanding_debits;
2250 # Write off the debt
2251 my $credit = $account->add_credit(
2252 { amount => $account->balance,
2254 interface => 'test',
2257 $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Writeoff' } );
2259 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2260 is( $credit_return_id, undef, 'No LOST_RETURN account line added' );
2262 $lost_fee_line->discard_changes; # reload from DB
2263 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2264 is( $lost_fee_line->debit_type_code,
2265 'LOST', 'Lost fee now still has account type of LOST' );
2266 is( $lost_fee_line->status, 'RETURNED', "Lost fee now has account status of RETURNED");
2268 is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2271 subtest 'Full payment tests' => sub {
2275 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2277 my $item = $builder->build_sample_item(
2279 biblionumber => $biblio->biblionumber,
2280 library => $library->branchcode,
2281 replacementprice => $replacement_amount,
2282 itype => $item_type->itemtype
2286 AddIssue( $patron->unblessed, $item->barcode );
2288 # Simulate item marked as lost
2289 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2290 LostItem( $item->itemnumber, 1 );
2292 my $processing_fee_lines = Koha::Account::Lines->search(
2293 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2294 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2295 my $processing_fee_line = $processing_fee_lines->next;
2296 is( $processing_fee_line->amount + 0,
2297 $processfee_amount, 'The right PROCESSING amount is generated' );
2298 is( $processing_fee_line->amountoutstanding + 0,
2299 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2301 my $lost_fee_lines = Koha::Account::Lines->search(
2302 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2303 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2304 my $lost_fee_line = $lost_fee_lines->next;
2305 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2306 is( $lost_fee_line->amountoutstanding + 0,
2307 $replacement_amount, 'The right LOST amountountstanding is generated' );
2309 my $account = $patron->account;
2310 my $debts = $account->outstanding_debits;
2312 # Write off the debt
2313 my $credit = $account->add_credit(
2314 { amount => $account->balance,
2316 interface => 'test',
2319 $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Payment' } );
2321 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2322 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2324 is( $credit_return->credit_type_code, 'LOST_RETURN', 'An account line of type LOST_RETURN is added' );
2325 is( $credit_return->amount + 0,
2326 -99.00, 'The account line of type LOST_RETURN has an amount of -99' );
2327 is( $credit_return->amountoutstanding + 0,
2328 -99.00, 'The account line of type LOST_RETURN has an amountoutstanding of -99' );
2330 $lost_fee_line->discard_changes;
2331 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2332 is( $lost_fee_line->debit_type_code,
2333 'LOST', 'Lost fee now still has account type of LOST' );
2334 is( $lost_fee_line->status, 'RETURNED', "Lost fee now has account status of RETURNED");
2336 is( $patron->account->balance,
2337 -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2340 subtest 'Test without payment or write off' => sub {
2344 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2346 my $item = $builder->build_sample_item(
2348 biblionumber => $biblio->biblionumber,
2349 library => $library->branchcode,
2350 replacementprice => 23.00,
2351 replacementprice => $replacement_amount,
2352 itype => $item_type->itemtype
2356 AddIssue( $patron->unblessed, $item->barcode );
2358 # Simulate item marked as lost
2359 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2360 LostItem( $item->itemnumber, 1 );
2362 my $processing_fee_lines = Koha::Account::Lines->search(
2363 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2364 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2365 my $processing_fee_line = $processing_fee_lines->next;
2366 is( $processing_fee_line->amount + 0,
2367 $processfee_amount, 'The right PROCESSING amount is generated' );
2368 is( $processing_fee_line->amountoutstanding + 0,
2369 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2371 my $lost_fee_lines = Koha::Account::Lines->search(
2372 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2373 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2374 my $lost_fee_line = $lost_fee_lines->next;
2375 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2376 is( $lost_fee_line->amountoutstanding + 0,
2377 $replacement_amount, 'The right LOST amountountstanding is generated' );
2379 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2380 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2382 is( $credit_return->credit_type_code, 'LOST_RETURN', 'An account line of type LOST_RETURN is added' );
2383 is( $credit_return->amount + 0, -99.00, 'The account line of type LOST_RETURN has an amount of -99' );
2384 is( $credit_return->amountoutstanding + 0, 0, 'The account line of type LOST_RETURN has an amountoutstanding of 0' );
2386 $lost_fee_line->discard_changes;
2387 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2388 is( $lost_fee_line->debit_type_code,
2389 'LOST', 'Lost fee now still has account type of LOST' );
2390 is( $lost_fee_line->status, 'RETURNED', "Lost fee now has account status of RETURNED");
2392 is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2395 subtest 'Test with partial payement and write off, and remaining debt' => sub {
2399 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2400 my $item = $builder->build_sample_item(
2402 biblionumber => $biblio->biblionumber,
2403 library => $library->branchcode,
2404 replacementprice => $replacement_amount,
2405 itype => $item_type->itemtype
2409 AddIssue( $patron->unblessed, $item->barcode );
2411 # Simulate item marked as lost
2412 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2413 LostItem( $item->itemnumber, 1 );
2415 my $processing_fee_lines = Koha::Account::Lines->search(
2416 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2417 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2418 my $processing_fee_line = $processing_fee_lines->next;
2419 is( $processing_fee_line->amount + 0,
2420 $processfee_amount, 'The right PROCESSING amount is generated' );
2421 is( $processing_fee_line->amountoutstanding + 0,
2422 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2424 my $lost_fee_lines = Koha::Account::Lines->search(
2425 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2426 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2427 my $lost_fee_line = $lost_fee_lines->next;
2428 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2429 is( $lost_fee_line->amountoutstanding + 0,
2430 $replacement_amount, 'The right LOST amountountstanding is generated' );
2432 my $account = $patron->account;
2433 is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PROCESSING + L' );
2436 my $payment_amount = 27;
2437 my $payment = $account->add_credit(
2438 { amount => $payment_amount,
2440 interface => 'test',
2444 $payment->apply( { debits => [ $lost_fee_line ], offset_type => 'Payment' } );
2446 # Partially write off fee
2447 my $write_off_amount = 25;
2448 my $write_off = $account->add_credit(
2449 { amount => $write_off_amount,
2451 interface => 'test',
2454 $write_off->apply( { debits => [ $lost_fee_line ], offset_type => 'Writeoff' } );
2456 is( $account->balance,
2457 $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2458 'Payment and write off applied'
2461 # Store the amountoutstanding value
2462 $lost_fee_line->discard_changes;
2463 my $outstanding = $lost_fee_line->amountoutstanding;
2465 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2466 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2468 is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PROCESSING - PAYMENT (LOST_RETURN)' );
2470 $lost_fee_line->discard_changes;
2471 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2472 is( $lost_fee_line->debit_type_code,
2473 'LOST', 'Lost fee now still has account type of LOST' );
2474 is( $lost_fee_line->status, 'RETURNED', "Lost fee now has account status of RETURNED");
2476 is( $credit_return->credit_type_code, 'LOST_RETURN', 'An account line of type LOST_RETURN is added' );
2477 is( $credit_return->amount + 0,
2478 ($payment_amount + $outstanding ) * -1,
2479 'The account line of type LOST_RETURN has an amount equal to the payment + outstanding'
2481 is( $credit_return->amountoutstanding + 0,
2482 $payment_amount * -1,
2483 'The account line of type LOST_RETURN has an amountoutstanding equal to the payment'
2486 is( $account->balance,
2487 $processfee_amount - $payment_amount,
2488 'The patron balance is the difference between the PROCESSING and the credit'
2492 subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2496 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2497 my $barcode = 'KD123456793';
2498 my $replacement_amount = 100;
2499 my $processfee_amount = 20;
2501 my $item_type = $builder->build_object(
2502 { class => 'Koha::ItemTypes',
2504 notforloan => undef,
2506 defaultreplacecost => undef,
2508 rentalcharge_daily => 0,
2512 my ( undef, undef, $item_id ) = AddItem(
2513 { homebranch => $library->branchcode,
2514 holdingbranch => $library->branchcode,
2515 barcode => $barcode,
2516 replacementprice => $replacement_amount,
2517 itype => $item_type->itemtype
2519 $biblio->biblionumber
2522 AddIssue( $patron->unblessed, $barcode );
2524 # Simulate item marked as lost
2525 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item_id );
2526 LostItem( $item_id, 1 );
2528 my $lost_fee_lines = Koha::Account::Lines->search(
2529 { borrowernumber => $patron->id, itemnumber => $item_id, debit_type_code => 'LOST' } );
2530 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2531 my $lost_fee_line = $lost_fee_lines->next;
2532 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2533 is( $lost_fee_line->amountoutstanding + 0,
2534 $replacement_amount, 'The right LOST amountountstanding is generated' );
2536 my $account = $patron->account;
2537 is( $account->balance, $replacement_amount, 'Balance is L' );
2540 my $payment_amount = 27;
2541 my $payment = $account->add_credit(
2542 { amount => $payment_amount,
2544 interface => 'test',
2547 $payment->apply({ debits => [ $lost_fee_line ], offset_type => 'Payment' });
2549 is( $account->balance,
2550 $replacement_amount - $payment_amount,
2554 my $manual_debit_amount = 80;
2555 $account->add_debit( { amount => $manual_debit_amount, type => 'OVERDUE', interface =>'test' } );
2557 is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
2559 t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
2561 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2562 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2564 is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PROCESSING - payment (LOST_RETURN)' );
2566 my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, debit_type_code => 'OVERDUE', status => 'UNRETURNED' })->next;
2567 is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
2571 subtest '_FixOverduesOnReturn' => sub {
2574 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2575 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2577 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2579 my $branchcode = $library2->{branchcode};
2581 my $item = $builder->build_sample_item(
2583 biblionumber => $biblio->biblionumber,
2584 library => $branchcode,
2585 replacementprice => 99.00,
2590 my $patron = $builder->build( { source => 'Borrower' } );
2592 ## Start with basic call, should just close out the open fine
2593 my $accountline = Koha::Account::Line->new(
2595 borrowernumber => $patron->{borrowernumber},
2596 debit_type_code => 'OVERDUE',
2597 status => 'UNRETURNED',
2598 itemnumber => $item->itemnumber,
2600 amountoutstanding => 99.00,
2601 interface => 'test',
2605 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
2607 $accountline->_result()->discard_changes();
2609 is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' );
2610 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
2611 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
2613 ## Run again, with exemptfine enabled
2616 debit_type_code => 'OVERDUE',
2617 status => 'UNRETURNED',
2618 amountoutstanding => 99.00,
2622 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
2624 $accountline->_result()->discard_changes();
2625 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2627 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
2628 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
2629 is( $accountline->status, 'FORGIVEN', 'Open fine ( account type OVERDUE ) has been set to fine forgiven ( status FORGIVEN )');
2630 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2631 is( $offset->amount + 0, -99, "Amount of offset is correct" );
2632 my $credit = $offset->credit;
2633 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
2634 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
2635 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
2637 # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive
2640 debit_type_code => 'OVERDUE',
2641 status => 'UNRETURNED',
2642 amountoutstanding => 0.00,
2647 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
2649 $accountline->_result()->discard_changes();
2650 $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2651 is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" );
2652 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
2653 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
2656 subtest '_FixAccountForLostAndReturned returns undef if patron is deleted' => sub {
2659 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2660 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2662 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2664 my $branchcode = $library2->{branchcode};
2666 my $item = $builder->build_sample_item(
2668 biblionumber => $biblio->biblionumber,
2669 library => $branchcode,
2670 replacementprice => 99.00,
2675 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2677 ## Start with basic call, should just close out the open fine
2678 my $accountline = Koha::Account::Line->new(
2680 borrowernumber => $patron->id,
2681 debit_type_code => 'LOST',
2683 itemnumber => $item->itemnumber,
2685 amountoutstanding => 99.00,
2686 interface => 'test',
2692 my $return_value = C4::Circulation::_FixAccountForLostAndReturned( $patron->id, $item->itemnumber );
2694 is( $return_value, undef, "_FixAccountForLostAndReturned returns undef if patron is deleted" );
2698 subtest 'Set waiting flag' => sub {
2701 my $library_1 = $builder->build( { source => 'Branch' } );
2702 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2703 my $library_2 = $builder->build( { source => 'Branch' } );
2704 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2706 my $item = $builder->build_sample_item(
2708 library => $library_1->{branchcode},
2712 set_userenv( $library_2 );
2713 my $reserve_id = AddReserve(
2714 $library_2->{branchcode}, $patron_2->{borrowernumber}, $item->{biblionumber},
2715 '', 1, undef, undef, '', undef, $item->{itemnumber},
2718 set_userenv( $library_1 );
2719 my $do_transfer = 1;
2720 my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2721 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2722 my $hold = Koha::Holds->find( $reserve_id );
2723 is( $hold->found, 'T', 'Hold is in transit' );
2725 my ( $status ) = CheckReserves($item->{itemnumber});
2726 is( $status, 'Reserved', 'Hold is not waiting yet');
2728 set_userenv( $library_2 );
2730 AddReturn( $item->{barcode}, $library_2->{branchcode} );
2731 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2732 $hold = Koha::Holds->find( $reserve_id );
2733 is( $hold->found, 'W', 'Hold is waiting' );
2734 ( $status ) = CheckReserves($item->{itemnumber});
2735 is( $status, 'Waiting', 'Now the hold is waiting');
2737 #Bug 21944 - Waiting transfer checked in at branch other than pickup location
2738 set_userenv( $library_1 );
2739 (undef, my $messages, undef, undef ) = AddReturn ( $item->{barcode}, $library_1->{branchcode} );
2740 $hold = Koha::Holds->find( $reserve_id );
2741 is( $hold->found, undef, 'Hold is no longer marked waiting' );
2742 is( $hold->priority, 1, "Hold is now priority one again");
2743 is( $hold->waitingdate, undef, "Hold no longer has a waiting date");
2744 is( $hold->itemnumber, $item->{itemnumber}, "Hold has retained its' itemnumber");
2745 is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned");
2746 is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message");
2747 is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message");
2750 subtest 'Cancel transfers on lost items' => sub {
2752 my $library_1 = $builder->build( { source => 'Branch' } );
2753 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2754 my $library_2 = $builder->build( { source => 'Branch' } );
2755 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2756 my $biblio = $builder->build_sample_biblio({branchcode => $library->{branchcode}});
2757 my $item = $builder->build_sample_item({
2758 biblionumber => $biblio->biblionumber,
2759 library => $library_1->{branchcode},
2762 set_userenv( $library_2 );
2763 my $reserve_id = AddReserve(
2764 $library_2->{branchcode}, $patron_2->{borrowernumber}, $item->biblionumber, '', 1, undef, undef, '', undef, $item->itemnumber,
2767 #Return book and add transfer
2768 set_userenv( $library_1 );
2769 my $do_transfer = 1;
2770 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
2771 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
2772 C4::Circulation::transferbook( $library_2->{branchcode}, $item->barcode );
2773 my $hold = Koha::Holds->find( $reserve_id );
2774 is( $hold->found, 'T', 'Hold is in transit' );
2776 #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
2777 my ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
2778 is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
2779 my $itemcheck = Koha::Items->find($item->itemnumber);
2780 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Items holding branch is the transfers origin branch before it is marked as lost' );
2782 #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
2783 ModItem( { itemlost => 1 }, $item->biblionumber, $item->itemnumber );
2784 LostItem( $item->itemnumber, 'test', 1 );
2785 ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
2786 is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
2787 $itemcheck = Koha::Items->find($item->itemnumber);
2788 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
2791 subtest 'CanBookBeIssued | is_overdue' => sub {
2794 # Set a simple circ policy
2795 $dbh->do('DELETE FROM issuingrules');
2797 q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
2798 issuelength, lengthunit,
2799 renewalsallowed, renewalperiod,
2800 norenewalbefore, auto_renew,
2817 my $now = dt_from_string;
2818 my $five_days_go = output_pref({ dt => $now->clone->add( days => 5 ), dateonly => 1});
2819 my $ten_days_go = output_pref({ dt => $now->clone->add( days => 10), dateonly => 1 });
2820 my $library = $builder->build( { source => 'Branch' } );
2821 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2823 my $item = $builder->build_sample_item(
2825 library => $library->{branchcode},
2829 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
2830 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
2831 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
2832 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
2833 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
2834 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
2837 subtest 'ItemsDeniedRenewal preference' => sub {
2840 C4::Context->set_preference('ItemsDeniedRenewal','');
2842 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
2845 INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
2846 norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
2849 '*', $idr_lib->branchcode, '*', 25,
2856 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
2857 homebranch => $idr_lib->branchcode,
2861 itemcallnumber => undef,
2865 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
2866 homebranch => $idr_lib->branchcode,
2869 location => 'NOPROC'
2873 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
2874 branchcode => $idr_lib->branchcode,
2877 my $future = dt_from_string->add( days => 1 );
2878 my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2879 returndate => undef,
2882 borrowernumber => $idr_borrower->borrowernumber,
2883 itemnumber => $deny_book->itemnumber,
2884 onsite_checkout => 0,
2885 date_due => $future,
2888 my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2889 returndate => undef,
2892 borrowernumber => $idr_borrower->borrowernumber,
2893 itemnumber => $allow_book->itemnumber,
2894 onsite_checkout => 0,
2895 date_due => $future,
2901 my ( $idr_mayrenew, $idr_error ) =
2902 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2903 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
2904 is( $idr_error, undef, 'Renewal allowed when no rules' );
2906 $idr_rules="withdrawn: [1]";
2908 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2909 ( $idr_mayrenew, $idr_error ) =
2910 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2911 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
2912 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
2913 ( $idr_mayrenew, $idr_error ) =
2914 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2915 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2916 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2918 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
2920 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2921 ( $idr_mayrenew, $idr_error ) =
2922 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2923 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
2924 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
2925 ( $idr_mayrenew, $idr_error ) =
2926 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2927 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2928 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2930 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
2932 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2933 ( $idr_mayrenew, $idr_error ) =
2934 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2935 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
2936 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
2937 ( $idr_mayrenew, $idr_error ) =
2938 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2939 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2940 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2942 $idr_rules="itemcallnumber: [NULL]";
2943 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2944 ( $idr_mayrenew, $idr_error ) =
2945 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2946 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
2947 $idr_rules="itemcallnumber: ['']";
2948 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2949 ( $idr_mayrenew, $idr_error ) =
2950 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2951 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
2953 $idr_rules="itemnotes: [NULL]";
2954 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2955 ( $idr_mayrenew, $idr_error ) =
2956 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2957 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
2958 $idr_rules="itemnotes: ['']";
2959 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2960 ( $idr_mayrenew, $idr_error ) =
2961 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2962 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
2965 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
2968 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2969 my $library = $builder->build( { source => 'Branch' } );
2970 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2972 my $item = $builder->build_sample_item(
2974 library => $library->{branchcode},
2978 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2979 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2980 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2983 subtest 'CanBookBeIssued | notforloan' => sub {
2986 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
2988 my $library = $builder->build( { source => 'Branch' } );
2989 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2991 my $itemtype = $builder->build(
2993 source => 'Itemtype',
2994 value => { notforloan => undef, }
2997 my $item = $builder->build_sample_item(
2999 library => $library->{branchcode},
3000 itype => $itemtype->{itemtype},
3003 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3005 my ( $issuingimpossible, $needsconfirmation );
3008 subtest 'item-level_itypes = 1' => sub {
3011 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
3012 # Is for loan at item type and item level
3013 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3014 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3015 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3017 # not for loan at item type level
3018 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3019 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3020 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3023 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3024 'Item can not be issued, not for loan at item type level'
3027 # not for loan at item level
3028 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3029 $item->notforloan( 1 )->store;
3030 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3031 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3034 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3035 'Item can not be issued, not for loan at item type level'
3039 subtest 'item-level_itypes = 0' => sub {
3042 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
3044 # We set another itemtype for biblioitem
3045 my $itemtype = $builder->build(
3047 source => 'Itemtype',
3048 value => { notforloan => undef, }
3052 # for loan at item type and item level
3053 $item->notforloan(0)->store;
3054 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
3055 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3056 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
3057 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
3059 # not for loan at item type level
3060 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
3061 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3062 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3065 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
3066 'Item can not be issued, not for loan at item type level'
3069 # not for loan at item level
3070 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
3071 $item->notforloan( 1 )->store;
3072 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
3073 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
3076 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
3077 'Item can not be issued, not for loan at item type level'
3081 # TODO test with AllowNotForLoanOverride = 1
3084 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
3087 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
3088 my $item = $builder->build_sample_item(
3090 onloan => '2018-01-01',
3094 AddReturn( $item->barcode, $item->homebranch );
3095 $item->discard_changes; # refresh
3096 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
3100 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
3105 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3107 my $issuing_charges = 15;
3108 my $title = 'A title';
3109 my $author = 'Author, An';
3110 my $barcode = 'WHATARETHEODDS';
3112 my $circ = Test::MockModule->new('C4::Circulation');
3114 'GetIssuingCharges',
3116 return $issuing_charges;
3120 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3121 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
3122 my $patron = $builder->build_object({
3123 class => 'Koha::Patrons',
3124 value => { branchcode => $library->id }
3127 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
3128 my ( undef, undef, $item_id ) = AddItem(
3130 homebranch => $library->id,
3131 holdingbranch => $library->id,
3132 barcode => $barcode,
3133 replacementprice => 23.00,
3134 itype => $itemtype->id
3136 $biblio->biblionumber
3138 my $item = Koha::Items->find( $item_id );
3140 my $context = Test::MockModule->new('C4::Context');
3141 $context->mock( userenv => { branch => $library->id } );
3143 # Check the item out
3144 AddIssue( $patron->unblessed, $item->barcode );
3145 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
3146 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3147 my %params_renewal = (
3148 timestamp => { -like => $date . "%" },
3149 module => "CIRCULATION",
3150 action => "RENEWAL",
3152 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
3153 AddRenewal( $patron->id, $item->id, $library->id );
3154 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3155 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
3157 my $checkouts = $patron->checkouts;
3158 # The following will fail if run on 00:00:00
3159 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
3161 my $lines = Koha::Account::Lines->search({
3162 borrowernumber => $patron->id,
3163 itemnumber => $item->id
3166 is( $lines->count, 2 );
3168 my $line = $lines->next;
3169 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
3170 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
3171 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
3173 $line = $lines->next;
3174 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
3175 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
3176 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
3178 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
3180 $context = Test::MockModule->new('C4::Context');
3181 $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew)
3183 my $now = dt_from_string;
3184 $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } );
3185 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
3186 my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?");
3187 $sth->execute($item->id, $library->id);
3188 my ($old_stats_size) = $sth->fetchrow_array;
3189 AddRenewal( $patron->id, $item->id, $library->id );
3190 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3191 $sth->execute($item->id, $library->id);
3192 my ($new_stats_size) = $sth->fetchrow_array;
3193 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
3194 is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' );
3198 subtest 'ProcessOfflinePayment() tests' => sub {
3205 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
3206 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3207 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
3209 is( $result, 'Success.', 'The right string is returned' );
3211 my $lines = $patron->account->lines;
3212 is( $lines->count, 1, 'line created correctly');
3214 my $line = $lines->next;
3215 is( $line->amount+0, $amount * -1, 'amount picked from params' );
3216 is( $line->branchcode, $library->id, 'branchcode set correctly' );
3220 subtest 'Incremented fee tests' => sub {
3223 my $dt = dt_from_string();
3224 Time::Fake->offset( $dt->epoch );
3226 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
3229 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3231 my $module = new Test::MockModule('C4::Context');
3232 $module->mock( 'userenv', sub { { branch => $library->id } } );
3234 my $patron = $builder->build_object(
3236 class => 'Koha::Patrons',
3237 value => { categorycode => $patron_category->{categorycode} }
3241 my $itemtype = $builder->build_object(
3243 class => 'Koha::ItemTypes',
3245 notforloan => undef,
3247 rentalcharge_daily => 1,
3252 my $item = $builder->build_sample_item(
3254 library => $library->{branchcode},
3255 itype => $itemtype->id,
3259 is( $itemtype->rentalcharge_daily+0,
3260 1, 'Daily rental charge stored and retreived correctly' );
3261 is( $item->effective_itemtype, $itemtype->id,
3262 "Itemtype set correctly for item" );
3264 my $now = dt_from_string;
3265 my $dt_from = $now->clone;
3266 my $dt_to = $now->clone->add( days => 7 );
3267 my $dt_to_renew = $now->clone->add( days => 13 );
3270 t::lib::Mocks::mock_preference( 'finesCalendar', 'ignoreCalendar' );
3272 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3273 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3274 is( $accountline->amount+0, 7,
3275 "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar"
3277 $accountline->delete();
3278 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3279 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3280 is( $accountline->amount+0, 6,
3281 "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal"
3283 $accountline->delete();
3286 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3288 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3289 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3290 is( $accountline->amount+0, 7,
3291 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed"
3293 $accountline->delete();
3294 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3295 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3296 is( $accountline->amount+0, 6,
3297 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal"
3299 $accountline->delete();
3302 my $calendar = C4::Calendar->new( branchcode => $library->id );
3303 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
3305 ( $dt_from->day_of_week == 6 ) ? 0
3306 : ( $dt_from->day_of_week == 7 ) ? 1
3307 : $dt_from->day_of_week + 1;
3308 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
3309 $calendar->insert_week_day_holiday(
3310 weekday => $closed_day,
3311 title => 'Test holiday',
3312 description => 'Test holiday'
3315 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3316 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3317 is( $accountline->amount+0, 6,
3318 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name"
3320 $accountline->delete();
3321 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3322 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3323 is( $accountline->amount+0, 5,
3324 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name, for renewal"
3326 $accountline->delete();
3329 $itemtype->rentalcharge(2)->store;
3330 is( $itemtype->rentalcharge+0, 2,
3331 'Rental charge updated and retreived correctly' );
3333 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3335 Koha::Account::Lines->search( { itemnumber => $item->id } );
3336 is( $accountlines->count, '2',
3337 "Fixed charge and accrued charge recorded distinctly" );
3338 $accountlines->delete();
3339 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3340 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
3341 is( $accountlines->count, '2',
3342 "Fixed charge and accrued charge recorded distinctly, for renewal" );
3343 $accountlines->delete();
3345 $itemtype->rentalcharge(0)->store;
3346 is( $itemtype->rentalcharge+0, 0,
3347 'Rental charge reset and retreived correctly' );
3350 my $issuingrule = Koha::IssuingRules->get_effective_issuing_rule(
3352 categorycode => $patron->categorycode,
3353 itemtype => $itemtype->id,
3354 branchcode => $library->id
3357 $issuingrule->lengthunit('hours')->store();
3358 is( $issuingrule->lengthunit, 'hours',
3359 'Issuingrule updated and retrieved correctly' );
3361 $itemtype->rentalcharge_hourly('0.25')->store();
3362 is( $itemtype->rentalcharge_hourly,
3363 '0.25', 'Hourly rental charge stored and retreived correctly' );
3365 $dt_to = $now->clone->add( hours => 168 );
3366 $dt_to_renew = $now->clone->add( hours => 312 );
3368 t::lib::Mocks::mock_preference( 'finesCalendar', 'ignoreCalendar' );
3370 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3371 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3372 is( $accountline->amount + 0, 42,
3373 "Hourly rental charge calculated correctly with finesCalendar = ignoreCalendar (168h * 0.25u)" );
3374 $accountline->delete();
3375 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3376 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3377 is( $accountline->amount + 0, 36,
3378 "Hourly rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal (312h - 168h * 0.25u)" );
3379 $accountline->delete();
3382 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3384 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3385 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3386 is( $accountline->amount + 0, 36,
3387 "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name (168h - 24h * 0.25u)" );
3388 $accountline->delete();
3389 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3390 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3391 is( $accountline->amount + 0, 30,
3392 "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
3393 $accountline->delete();
3396 $calendar->delete_holiday( weekday => $closed_day );
3398 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3399 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3400 is( $accountline->amount + 0, 42,
3401 "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed (168h - 0h * 0.25u" );
3402 $accountline->delete();
3403 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3404 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3405 is( $accountline->amount + 0, 36,
3406 "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal (312h - 168h - 0h * 0.25u)" );
3407 $accountline->delete();
3409 $issuingrule->lengthunit('days')->store();
3413 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
3416 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
3417 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3420 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3421 my $patron = $builder->build_object(
3423 class => 'Koha::Patrons',
3424 value => { categorycode => $patron_category->{categorycode} }
3428 my $itemtype = $builder->build_object(
3430 class => 'Koha::ItemTypes',
3434 rentalcharge_daily => 0
3439 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3440 my $item = $builder->build_object(
3442 class => 'Koha::Items',
3444 homebranch => $library->id,
3445 holdingbranch => $library->id,
3449 itype => $itemtype->id,
3450 biblionumber => $biblioitem->{biblionumber},
3451 biblioitemnumber => $biblioitem->{biblioitemnumber},
3456 my ( $issuingimpossible, $needsconfirmation );
3457 my $dt_from = dt_from_string();
3458 my $dt_due = $dt_from->clone->add( days => 3 );
3460 $itemtype->rentalcharge(1)->store;
3461 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3462 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
3463 $itemtype->rentalcharge('0')->store;
3464 $itemtype->rentalcharge_daily(1)->store;
3465 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3466 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
3467 $itemtype->rentalcharge_daily('0')->store;
3470 subtest "Test Backdating of Returns" => sub {
3473 my $branch = $library2->{branchcode};
3474 my $biblio = $builder->build_sample_biblio();
3475 my $item = $builder->build_sample_item(
3477 biblionumber => $biblio->biblionumber,
3483 my %a_borrower_data = (
3484 firstname => 'Kyle',
3486 categorycode => $patron_category->{categorycode},
3487 branchcode => $branch,
3489 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
3490 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
3492 my $due_date = dt_from_string;
3493 my $issue = AddIssue( $borrower, $item->barcode, $due_date );
3496 issue_id => $issue->id(),
3497 itemnumber => $item->itemnumber,
3498 borrowernumber => $borrowernumber,
3500 amountoutstanding => .25,
3506 my ( undef, $message ) = AddReturn( $item->barcode, $branch, undef, $due_date );
3508 my $accountline = Koha::Account::Lines->find( { issue_id => $issue->id } );
3509 is( $accountline->amountoutstanding+0, 0, 'Fee amount outstanding was reduced to 0' );
3510 is( $accountline->amount+0, 0, 'Fee amount was reduced to 0' );
3513 subtest 'Filling a hold should cancel existing transfer' => sub {
3516 t::lib::Mocks::mock_preference('AutomaticItemReturn', 1);
3518 my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } );
3519 my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } );
3520 my $patron = $builder->build_object(
3522 class => 'Koha::Patrons',
3524 categorycode => $patron_category->{categorycode},
3525 branchcode => $libraryA->branchcode,
3530 my $item = $builder->build_sample_item({
3531 homebranch => $libraryB->branchcode,
3534 my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
3535 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin");
3536 AddReserve($libraryA->branchcode,$patron->borrowernumber,$item->biblionumber,undef,undef,undef,undef,undef,undef,$item->itemnumber);
3537 my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber });
3538 is( $reserves->count, 1, "Reserve is placed");
3539 ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef );
3540 my $reserve = $reserves->next;
3541 ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id );
3542 $reserve->discard_changes;
3543 ok( $reserve->found eq 'W', "Reserve is marked waiting" );
3544 is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting");
3547 $schema->storage->txn_rollback;
3548 C4::Context->clear_syspref_cache();
3549 $cache->clear_from_cache('single_holidays');