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 => 45;
27 use POSIX qw( floor );
29 use t::lib::TestBuilder;
38 use C4::Overdues qw(UpdateFine CalcFine);
41 use Koha::IssuingRules;
45 use Koha::CirculationRules;
46 use Koha::Subscriptions;
47 use Koha::Account::Lines;
48 use Koha::Account::Offsets;
53 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
57 my ( $error, $question, $alert ) = @_;
59 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
60 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
61 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
65 sub test_debarment_on_checkout {
67 my $item = $params->{item};
68 my $library = $params->{library};
69 my $patron = $params->{patron};
70 my $due_date = $params->{due_date} || dt_from_string;
71 my $return_date = $params->{return_date} || dt_from_string;
72 my $expected_expiration_date = $params->{expiration_date};
74 $expected_expiration_date = output_pref(
76 dt => $expected_expiration_date,
82 my $line_number = $caller[2];
83 AddIssue( $patron, $item->{barcode}, $due_date );
85 my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode}, undef, $return_date );
86 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
87 or diag('AddReturn returned message ' . Dumper $message );
88 my $debarments = Koha::Patron::Debarments::GetDebarments(
89 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
90 is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
92 is( $debarments->[0]->{expiration},
93 $expected_expiration_date, 'Test at line ' . $line_number );
94 Koha::Patron::Debarments::DelUniqueDebarment(
95 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
98 my $schema = Koha::Database->schema;
99 $schema->storage->txn_begin;
100 my $builder = t::lib::TestBuilder->new;
101 my $dbh = C4::Context->dbh;
103 # Prevent random failures by mocking ->now
104 my $now_value = dt_from_string;
105 my $mocked_datetime = Test::MockModule->new('DateTime');
106 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
109 $dbh->{RaiseError} = 1;
111 my $cache = Koha::Caches->get_instance();
112 $dbh->do(q|DELETE FROM special_holidays|);
113 $dbh->do(q|DELETE FROM repeatable_holidays|);
114 $cache->clear_from_cache('single_holidays');
116 # Start with a clean slate
117 $dbh->do('DELETE FROM issues');
118 $dbh->do('DELETE FROM borrowers');
120 my $library = $builder->build({
123 my $library2 = $builder->build({
126 my $itemtype = $builder->build(
128 source => 'Itemtype',
132 rentalcharge_daily => 0,
133 defaultreplacecost => undef,
138 my $patron_category = $builder->build(
140 source => 'Category',
142 category_type => 'P',
144 BlockExpiredPatronOpacActions => -1, # Pick the pref value
149 my $CircControl = C4::Context->preference('CircControl');
150 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
153 homebranch => $library2->{branchcode},
154 holdingbranch => $library2->{branchcode}
158 branchcode => $library2->{branchcode}
161 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
163 # No userenv, PickupLibrary
164 t::lib::Mocks::mock_preference('IndependentBranches', '0');
165 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
167 C4::Context->preference('CircControl'),
169 'CircControl changed to PickupLibrary'
172 C4::Circulation::_GetCircControlBranch($item, $borrower),
173 $item->{$HomeOrHoldingBranch},
174 '_GetCircControlBranch returned item branch (no userenv defined)'
177 # No userenv, PatronLibrary
178 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
180 C4::Context->preference('CircControl'),
182 'CircControl changed to PatronLibrary'
185 C4::Circulation::_GetCircControlBranch($item, $borrower),
186 $borrower->{branchcode},
187 '_GetCircControlBranch returned borrower branch'
190 # No userenv, ItemHomeLibrary
191 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
193 C4::Context->preference('CircControl'),
195 'CircControl changed to ItemHomeLibrary'
198 $item->{$HomeOrHoldingBranch},
199 C4::Circulation::_GetCircControlBranch($item, $borrower),
200 '_GetCircControlBranch returned item branch'
204 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
205 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
207 # Userenv set, PickupLibrary
208 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
210 C4::Context->preference('CircControl'),
212 'CircControl changed to PickupLibrary'
215 C4::Circulation::_GetCircControlBranch($item, $borrower),
216 $library2->{branchcode},
217 '_GetCircControlBranch returned current branch'
220 # Userenv set, PatronLibrary
221 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
223 C4::Context->preference('CircControl'),
225 'CircControl changed to PatronLibrary'
228 C4::Circulation::_GetCircControlBranch($item, $borrower),
229 $borrower->{branchcode},
230 '_GetCircControlBranch returned borrower branch'
233 # Userenv set, ItemHomeLibrary
234 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
236 C4::Context->preference('CircControl'),
238 'CircControl changed to ItemHomeLibrary'
241 C4::Circulation::_GetCircControlBranch($item, $borrower),
242 $item->{$HomeOrHoldingBranch},
243 '_GetCircControlBranch returned item branch'
246 # Reset initial configuration
247 t::lib::Mocks::mock_preference('CircControl', $CircControl);
249 C4::Context->preference('CircControl'),
251 'CircControl reset to its initial value'
254 # Set a simple circ policy
255 $dbh->do('DELETE FROM issuingrules');
256 Koha::CirculationRules->search()->delete();
258 q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
259 issuelength, lengthunit,
260 renewalsallowed, renewalperiod,
261 norenewalbefore, auto_renew,
278 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
279 subtest "CanBookBeRenewed tests" => sub {
282 C4::Context->set_preference('ItemsDeniedRenewal','');
283 # Generate test biblio
284 my $biblio = $builder->build_sample_biblio();
286 my $branch = $library2->{branchcode};
288 my $item_1 = $builder->build_sample_item(
290 biblionumber => $biblio->biblionumber,
292 replacementprice => 12.00,
296 $reused_itemnumber_1 = $item_1->itemnumber;
298 my $item_2 = $builder->build_sample_item(
300 biblionumber => $biblio->biblionumber,
302 replacementprice => 23.00,
306 $reused_itemnumber_2 = $item_2->itemnumber;
308 my $item_3 = $builder->build_sample_item(
310 biblionumber => $biblio->biblionumber,
312 replacementprice => 23.00,
318 my %renewing_borrower_data = (
320 surname => 'Renewal',
321 categorycode => $patron_category->{categorycode},
322 branchcode => $branch,
325 my %reserving_borrower_data = (
326 firstname => 'Katrin',
327 surname => 'Reservation',
328 categorycode => $patron_category->{categorycode},
329 branchcode => $branch,
332 my %hold_waiting_borrower_data = (
334 surname => 'Reservation',
335 categorycode => $patron_category->{categorycode},
336 branchcode => $branch,
339 my %restricted_borrower_data = (
340 firstname => 'Alice',
341 surname => 'Reservation',
342 categorycode => $patron_category->{categorycode},
343 debarred => '3228-01-01',
344 branchcode => $branch,
347 my %expired_borrower_data = (
350 categorycode => $patron_category->{categorycode},
351 branchcode => $branch,
352 dateexpiry => dt_from_string->subtract( months => 1 ),
355 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
356 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
357 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
358 my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
359 my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
361 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
362 my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
363 my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
370 my $checkitem = undef;
373 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
374 my $datedue = dt_from_string( $issue->date_due() );
375 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
377 my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
378 $datedue = dt_from_string( $issue->date_due() );
379 is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
382 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
383 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
385 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
386 is( $renewokay, 1, 'Can renew, no holds for this title or item');
389 # Biblio-level hold, renewal test
391 $branch, $reserving_borrowernumber, $biblio->biblionumber,
392 $bibitems, $priority, $resdate, $expdate, $notes,
393 'a title', $checkitem, $found
396 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
397 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
398 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
399 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
400 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
401 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
402 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
404 # Now let's add an item level hold, we should no longer be able to renew the item
405 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
407 borrowernumber => $hold_waiting_borrowernumber,
408 biblionumber => $biblio->biblionumber,
409 itemnumber => $item_1->itemnumber,
410 branchcode => $branch,
414 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
415 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
418 # 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
419 # be able to renew these items
420 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
422 borrowernumber => $hold_waiting_borrowernumber,
423 biblionumber => $biblio->biblionumber,
424 itemnumber => $item_3->itemnumber,
425 branchcode => $branch,
430 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
431 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
432 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
433 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
434 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
436 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
437 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
438 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
440 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
441 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
442 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
444 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
445 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
446 AddIssue($reserving_borrower, $item_3->barcode);
447 my $reserve = $dbh->selectrow_hashref(
448 'SELECT * FROM old_reserves WHERE reserve_id = ?',
452 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
454 # Item-level hold, renewal test
456 $branch, $reserving_borrowernumber, $biblio->biblionumber,
457 $bibitems, $priority, $resdate, $expdate, $notes,
458 'a title', $item_1->itemnumber, $found
461 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
462 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
463 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
465 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
466 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
468 # Items can't fill hold for reasons
469 ModItem({ notforloan => 1 }, $biblio->biblionumber, $item_1->itemnumber);
470 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
471 is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
472 ModItem({ notforloan => 0, itype => $itemtype }, $biblio->biblionumber, $item_1->itemnumber);
474 # FIXME: Add more for itemtype not for loan etc.
476 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
477 my $item_5 = $builder->build_sample_item(
479 biblionumber => $biblio->biblionumber,
481 replacementprice => 23.00,
485 my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
486 is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
488 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
489 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
490 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
491 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
492 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
494 # Users cannot renew an overdue item
495 my $item_6 = $builder->build_sample_item(
497 biblionumber => $biblio->biblionumber,
499 replacementprice => 23.00,
504 my $item_7 = $builder->build_sample_item(
506 biblionumber => $biblio->biblionumber,
508 replacementprice => 23.00,
513 my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
514 is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
516 my $now = dt_from_string();
517 my $five_weeks = DateTime::Duration->new(weeks => 5);
518 my $five_weeks_ago = $now - $five_weeks;
519 t::lib::Mocks::mock_preference('finesMode', 'production');
521 my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
522 is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
524 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
525 C4::Overdues::UpdateFine(
527 issue_id => $passeddatedue1->id(),
528 itemnumber => $item_7->itemnumber,
529 borrowernumber => $renewing_borrower->{borrowernumber},
531 due => Koha::DateUtils::output_pref($five_weeks_ago)
535 t::lib::Mocks::mock_preference('RenewalLog', 0);
536 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
537 my %params_renewal = (
538 timestamp => { -like => $date . "%" },
539 module => "CIRCULATION",
543 timestamp => { -like => $date . "%" },
544 module => "CIRCULATION",
547 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
548 my $dt = dt_from_string();
549 Time::Fake->offset( $dt->epoch );
550 my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
551 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
552 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
553 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
556 t::lib::Mocks::mock_preference('RenewalLog', 1);
557 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
558 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
559 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
560 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
561 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
563 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
564 is( $fines->count, 2, 'AddRenewal left both fines' );
565 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
566 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
570 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
571 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
572 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
573 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
574 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
575 $new_log_size = Koha::ActionLogs->count( \%params_issue );
576 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
578 $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
581 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
582 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
583 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
584 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
585 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
588 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
592 # Test automatic renewal before value for "norenewalbefore" in policy is set
593 # In this case automatic renewal is not permitted prior to due date
594 my $item_4 = $builder->build_sample_item(
596 biblionumber => $biblio->biblionumber,
598 replacementprice => 16.00,
603 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
604 ( $renewokay, $error ) =
605 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
606 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
607 is( $error, 'auto_too_soon',
608 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
611 # Test premature manual renewal
612 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
614 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
615 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
616 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
619 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
620 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
622 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
623 $datedue->clone->add( days => -7 ),
624 'Bug 14395: Renewals permitted 7 days before due date, as expected'
628 # Test 'date' setting for syspref NoRenewalBeforePrecision
629 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
631 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
632 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
633 'Bug 14395: Renewals permitted 7 days before due date, as expected'
637 # Test premature automatic renewal
638 ( $renewokay, $error ) =
639 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
640 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
641 is( $error, 'auto_too_soon',
642 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
645 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
646 # and test automatic renewal again
647 $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
648 ( $renewokay, $error ) =
649 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
650 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
651 is( $error, 'auto_too_soon',
652 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
655 # Change policy so that loans can be renewed 99 days prior to the due date
656 # and test automatic renewal again
657 $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
658 ( $renewokay, $error ) =
659 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
660 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
661 is( $error, 'auto_renew',
662 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
665 subtest "too_late_renewal / no_auto_renewal_after" => sub {
667 my $item_to_auto_renew = $builder->build(
670 biblionumber => $biblio->biblionumber,
671 homebranch => $branch,
672 holdingbranch => $branch,
677 my $ten_days_before = dt_from_string->add( days => -10 );
678 my $ten_days_ahead = dt_from_string->add( days => 10 );
679 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
681 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 9');
682 ( $renewokay, $error ) =
683 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
684 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
685 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
687 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 10');
688 ( $renewokay, $error ) =
689 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
690 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
691 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
693 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 11');
694 ( $renewokay, $error ) =
695 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
696 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
697 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
699 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
700 ( $renewokay, $error ) =
701 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
702 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
703 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
705 $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 ) );
706 ( $renewokay, $error ) =
707 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
708 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
709 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
711 $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 ) );
712 ( $renewokay, $error ) =
713 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
714 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
715 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
717 $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 ) );
718 ( $renewokay, $error ) =
719 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
720 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
721 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
724 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub {
726 my $item_to_auto_renew = $builder->build({
729 biblionumber => $biblio->biblionumber,
730 homebranch => $branch,
731 holdingbranch => $branch,
735 my $ten_days_before = dt_from_string->add( days => -10 );
736 my $ten_days_ahead = dt_from_string->add( days => 10 );
737 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
739 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
740 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
741 C4::Context->set_preference('OPACFineNoRenewals','10');
742 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
743 my $fines_amount = 5;
744 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
747 amount => $fines_amount,
750 item_id => $item_to_auto_renew->{itemnumber},
751 description => "Some fines"
753 )->status('RETURNED')->store;
754 ( $renewokay, $error ) =
755 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
756 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
757 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
761 amount => $fines_amount,
764 item_id => $item_to_auto_renew->{itemnumber},
765 description => "Some fines"
767 )->status('RETURNED')->store;
768 ( $renewokay, $error ) =
769 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
770 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
771 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
775 amount => $fines_amount,
778 item_id => $item_to_auto_renew->{itemnumber},
779 description => "Some fines"
781 )->status('RETURNED')->store;
782 ( $renewokay, $error ) =
783 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
784 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
785 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
787 $account->add_credit(
789 amount => $fines_amount,
792 description => "Some fines"
795 ( $renewokay, $error ) =
796 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
797 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
798 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
800 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0');
801 ( $renewokay, $error ) =
802 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
803 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
804 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' );
806 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
807 C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1');
810 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
812 my $item_to_auto_renew = $builder->build({
815 biblionumber => $biblio->biblionumber,
816 homebranch => $branch,
817 holdingbranch => $branch,
821 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
823 my $ten_days_before = dt_from_string->add( days => -10 );
824 my $ten_days_ahead = dt_from_string->add( days => 10 );
826 # Patron is expired and BlockExpiredPatronOpacActions=0
827 # => auto renew is allowed
828 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
829 my $patron = $expired_borrower;
830 my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
831 ( $renewokay, $error ) =
832 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
833 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
834 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
835 Koha::Checkouts->find( $checkout->issue_id )->delete;
838 # Patron is expired and BlockExpiredPatronOpacActions=1
839 # => auto renew is not allowed
840 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
841 $patron = $expired_borrower;
842 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
843 ( $renewokay, $error ) =
844 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
845 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
846 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
847 Koha::Checkouts->find( $checkout->issue_id )->delete;
850 # Patron is not expired and BlockExpiredPatronOpacActions=1
851 # => auto renew is allowed
852 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
853 $patron = $renewing_borrower;
854 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
855 ( $renewokay, $error ) =
856 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
857 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
858 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
859 Koha::Checkouts->find( $checkout->issue_id )->delete;
862 subtest "GetLatestAutoRenewDate" => sub {
864 my $item_to_auto_renew = $builder->build(
867 biblionumber => $biblio->biblionumber,
868 homebranch => $branch,
869 holdingbranch => $branch,
874 my $ten_days_before = dt_from_string->add( days => -10 );
875 my $ten_days_ahead = dt_from_string->add( days => 10 );
876 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
877 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = NULL');
878 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
879 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' );
880 my $five_days_before = dt_from_string->add( days => -5 );
881 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 5, no_auto_renewal_after_hard_limit = NULL');
882 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
883 is( $latest_auto_renew_date->truncate( to => 'minute' ),
884 $five_days_before->truncate( to => 'minute' ),
885 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
887 my $five_days_ahead = dt_from_string->add( days => 5 );
888 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = NULL');
889 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
890 is( $latest_auto_renew_date->truncate( to => 'minute' ),
891 $five_days_ahead->truncate( to => 'minute' ),
892 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
894 my $two_days_ahead = dt_from_string->add( days => 2 );
895 $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 ) );
896 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
897 is( $latest_auto_renew_date->truncate( to => 'day' ),
898 $two_days_ahead->truncate( to => 'day' ),
899 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
901 $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 ) );
902 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
903 is( $latest_auto_renew_date->truncate( to => 'day' ),
904 $two_days_ahead->truncate( to => 'day' ),
905 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
912 # set policy to forbid renewals
913 $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
915 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
916 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
917 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
919 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
920 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
921 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
923 C4::Overdues::UpdateFine(
925 issue_id => $issue->id(),
926 itemnumber => $item_1->itemnumber,
927 borrowernumber => $renewing_borrower->{borrowernumber},
930 due => Koha::DateUtils::output_pref($datedue)
934 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
935 is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' );
936 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
937 is( $line->amountoutstanding, '15.000000', 'Account line amount outstanding is 15.00' );
938 is( $line->amount, '15.000000', 'Account line amount is 15.00' );
939 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
941 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
942 is( $offset->type, 'OVERDUE', 'Account offset type is Fine' );
943 is( $offset->amount, '15.000000', 'Account offset amount is 15.00' );
945 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
946 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
948 LostItem( $item_1->itemnumber, 'test', 1 );
950 $line = Koha::Account::Lines->find($line->id);
951 is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' );
952 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
954 my $item = Koha::Items->find($item_1->itemnumber);
955 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
956 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
957 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
959 my $total_due = $dbh->selectrow_array(
960 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
961 undef, $renewing_borrower->{borrowernumber}
964 is( $total_due, '15.000000', 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
966 C4::Context->dbh->do("DELETE FROM accountlines");
968 C4::Overdues::UpdateFine(
970 issue_id => $issue2->id(),
971 itemnumber => $item_2->itemnumber,
972 borrowernumber => $renewing_borrower->{borrowernumber},
975 due => Koha::DateUtils::output_pref($datedue)
979 LostItem( $item_2->itemnumber, 'test', 0 );
981 my $item2 = Koha::Items->find($item_2->itemnumber);
982 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
983 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
985 $total_due = $dbh->selectrow_array(
986 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
987 undef, $renewing_borrower->{borrowernumber}
990 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
992 my $future = dt_from_string();
993 $future->add( days => 7 );
994 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
995 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
997 # Users cannot renew any item if there is an overdue item
998 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
999 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
1000 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1001 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
1002 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
1004 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1005 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
1006 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
1007 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
1008 LostItem( $item_3->itemnumber, 'test', 0 );
1009 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
1010 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
1012 $accountline->description,
1013 sprintf( "%s %s %s",
1014 $item_3->biblio->title || '',
1015 $item_3->barcode || '',
1016 $item_3->itemcallnumber || '' ),
1017 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1021 subtest "GetUpcomingDueIssues" => sub {
1024 my $branch = $library2->{branchcode};
1026 #Create another record
1027 my $biblio2 = $builder->build_sample_biblio();
1030 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1031 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1032 my $item_3 = $builder->build_sample_item(
1034 biblionumber => $biblio2->biblionumber,
1042 my %a_borrower_data = (
1043 firstname => 'Fridolyn',
1044 surname => 'SOMERS',
1045 categorycode => $patron_category->{categorycode},
1046 branchcode => $branch,
1049 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1050 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1052 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1053 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1054 my $today = DateTime->today(time_zone => C4::Context->tz());
1056 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1057 my $datedue = dt_from_string( $issue->date_due() );
1058 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1059 my $datedue2 = dt_from_string( $issue->date_due() );
1063 # GetUpcomingDueIssues tests
1065 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1066 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1069 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1070 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1071 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1074 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1075 is ( scalar( @$upcoming_dues ), 1,
1076 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1079 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1081 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1083 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1084 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1086 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1087 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1089 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1090 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1092 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1093 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1095 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1096 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1098 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1099 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1103 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1104 my $branch = $library2->{branchcode};
1106 my $biblio = $builder->build_sample_biblio();
1109 my $item = $builder->build_sample_item(
1111 biblionumber => $biblio->biblionumber,
1118 my %a_borrower_data = (
1119 firstname => 'Kyle',
1121 categorycode => $patron_category->{categorycode},
1122 branchcode => $branch,
1125 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1127 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1128 my $issue = AddIssue( $borrower, $item->barcode );
1131 issue_id => $issue->id(),
1132 itemnumber => $item->itemnumber,
1133 borrowernumber => $borrowernumber,
1139 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1140 my $count = $hr->{count};
1142 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1145 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1146 $dbh->do('DELETE FROM issues');
1147 $dbh->do('DELETE FROM items');
1148 $dbh->do('DELETE FROM issuingrules');
1149 Koha::CirculationRules->search()->delete();
1152 INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
1153 norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
1162 Koha::CirculationRules->set_rules(
1164 categorycode => '*',
1172 my $biblio = $builder->build_sample_biblio();
1174 my $item_1 = $builder->build_sample_item(
1176 biblionumber => $biblio->biblionumber,
1177 library => $library2->{branchcode},
1182 my $item_2= $builder->build_sample_item(
1184 biblionumber => $biblio->biblionumber,
1185 library => $library2->{branchcode},
1190 my $borrowernumber1 = Koha::Patron->new({
1191 firstname => 'Kyle',
1193 categorycode => $patron_category->{categorycode},
1194 branchcode => $library2->{branchcode},
1195 })->store->borrowernumber;
1196 my $borrowernumber2 = Koha::Patron->new({
1197 firstname => 'Chelsea',
1199 categorycode => $patron_category->{categorycode},
1200 branchcode => $library2->{branchcode},
1201 })->store->borrowernumber;
1203 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1204 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1206 my $issue = AddIssue( $borrower1, $item_1->barcode );
1208 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1209 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1212 $library2->{branchcode}, $borrowernumber2, $biblio->biblionumber,
1213 '', 1, undef, undef, '',
1217 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1218 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1219 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1220 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1222 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1223 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1224 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1225 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1227 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1228 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1229 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1230 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1232 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1233 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1234 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1235 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1237 # Setting item not checked out to be not for loan but holdable
1238 ModItem({ notforloan => -1 }, $biblio->biblionumber, $item_2->itemnumber);
1240 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1241 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' );
1245 # Don't allow renewing onsite checkout
1246 my $branch = $library->{branchcode};
1248 #Create another record
1249 my $biblio = $builder->build_sample_biblio();
1251 my $item = $builder->build_sample_item(
1253 biblionumber => $biblio->biblionumber,
1259 my $borrowernumber = Koha::Patron->new({
1262 categorycode => $patron_category->{categorycode},
1263 branchcode => $branch,
1264 })->store->borrowernumber;
1266 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1268 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1269 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1270 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1271 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1275 my $library = $builder->build({ source => 'Branch' });
1277 my $biblio = $builder->build_sample_biblio();
1279 my $item = $builder->build_sample_item(
1281 biblionumber => $biblio->biblionumber,
1282 library => $library->{branchcode},
1287 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1289 my $issue = AddIssue( $patron, $item->barcode );
1292 issue_id => $issue->id(),
1293 itemnumber => $item->itemnumber,
1294 borrowernumber => $patron->{borrowernumber},
1301 issue_id => $issue->id(),
1302 itemnumber => $item->itemnumber,
1303 borrowernumber => $patron->{borrowernumber},
1308 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1311 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1314 my $homebranch = $builder->build( { source => 'Branch' } );
1315 my $holdingbranch = $builder->build( { source => 'Branch' } );
1316 my $otherbranch = $builder->build( { source => 'Branch' } );
1317 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1318 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1320 my $item = $builder->build_sample_item(
1322 homebranch => $homebranch->{branchcode},
1323 holdingbranch => $holdingbranch->{branchcode},
1327 set_userenv($holdingbranch);
1329 my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1330 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1332 my ( $error, $question, $alerts );
1334 # AllowReturnToBranch == anywhere
1335 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1336 ## Test that unknown barcodes don't generate internal server errors
1337 set_userenv($homebranch);
1338 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1339 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1340 ## Can be issued from homebranch
1341 set_userenv($homebranch);
1342 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1343 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1344 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1345 ## Can be issued from holdingbranch
1346 set_userenv($holdingbranch);
1347 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1348 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1349 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1350 ## Can be issued from another branch
1351 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1352 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1353 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1355 # AllowReturnToBranch == holdingbranch
1356 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1357 ## Cannot be issued from homebranch
1358 set_userenv($homebranch);
1359 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1360 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1361 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1362 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1363 ## Can be issued from holdinbranch
1364 set_userenv($holdingbranch);
1365 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1366 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1367 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1368 ## Cannot be issued from another branch
1369 set_userenv($otherbranch);
1370 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1371 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1372 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1373 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
1375 # AllowReturnToBranch == homebranch
1376 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1377 ## Can be issued from holdinbranch
1378 set_userenv($homebranch);
1379 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1380 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1381 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1382 ## Cannot be issued from holdinbranch
1383 set_userenv($holdingbranch);
1384 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1385 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1386 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1387 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1388 ## Cannot be issued from holdinbranch
1389 set_userenv($otherbranch);
1390 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1391 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1392 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1393 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1395 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1398 subtest 'AddIssue & AllowReturnToBranch' => sub {
1401 my $homebranch = $builder->build( { source => 'Branch' } );
1402 my $holdingbranch = $builder->build( { source => 'Branch' } );
1403 my $otherbranch = $builder->build( { source => 'Branch' } );
1404 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1405 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1407 my $item = $builder->build_sample_item(
1409 homebranch => $homebranch->{branchcode},
1410 holdingbranch => $holdingbranch->{branchcode},
1414 set_userenv($holdingbranch);
1416 my $ref_issue = 'Koha::Checkout';
1417 my $issue = AddIssue( $patron_1, $item->{barcode} );
1419 my ( $error, $question, $alerts );
1421 # AllowReturnToBranch == homebranch
1422 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1423 ## Can be issued from homebranch
1424 set_userenv($homebranch);
1425 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
1426 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1427 ## Can be issued from holdinbranch
1428 set_userenv($holdingbranch);
1429 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
1430 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1431 ## Can be issued from another branch
1432 set_userenv($otherbranch);
1433 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
1434 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1436 # AllowReturnToBranch == holdinbranch
1437 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1438 ## Cannot be issued from homebranch
1439 set_userenv($homebranch);
1440 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
1441 ## Can be issued from holdingbranch
1442 set_userenv($holdingbranch);
1443 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
1444 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1445 ## Cannot be issued from another branch
1446 set_userenv($otherbranch);
1447 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
1449 # AllowReturnToBranch == homebranch
1450 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1451 ## Can be issued from homebranch
1452 set_userenv($homebranch);
1453 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
1454 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1455 ## Cannot be issued from holdinbranch
1456 set_userenv($holdingbranch);
1457 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
1458 ## Cannot be issued from another branch
1459 set_userenv($otherbranch);
1460 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
1461 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1464 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1467 my $library = $builder->build( { source => 'Branch' } );
1468 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1469 my $item_1 = $builder->build_sample_item(
1471 library => $library->{branchcode},
1474 my $item_2 = $builder->build_sample_item(
1476 library => $library->{branchcode},
1480 my ( $error, $question, $alerts );
1482 # Patron cannot issue item_1, they have overdues
1483 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1484 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday ); # Add an overdue
1486 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1487 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1488 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
1489 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1491 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1492 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1493 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1494 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1496 # Patron cannot issue item_1, they are debarred
1497 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1498 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1499 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1500 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1501 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1503 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1504 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1505 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1506 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1509 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1512 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1513 my $patron_category_x = $builder->build_object(
1515 class => 'Koha::Patron::Categories',
1516 value => { category_type => 'X' }
1519 my $patron = $builder->build_object(
1521 class => 'Koha::Patrons',
1523 categorycode => $patron_category_x->categorycode,
1524 gonenoaddress => undef,
1531 my $item_1 = $builder->build_sample_item(
1533 library => $library->{branchcode},
1537 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1538 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1540 # TODO There are other tests to provide here
1543 subtest 'MultipleReserves' => sub {
1546 my $biblio = $builder->build_sample_biblio();
1548 my $branch = $library2->{branchcode};
1550 my $item_1 = $builder->build_sample_item(
1552 biblionumber => $biblio->biblionumber,
1554 replacementprice => 12.00,
1559 my $item_2 = $builder->build_sample_item(
1561 biblionumber => $biblio->biblionumber,
1563 replacementprice => 12.00,
1570 my $resdate = undef;
1571 my $expdate = undef;
1573 my $checkitem = undef;
1576 my %renewing_borrower_data = (
1577 firstname => 'John',
1578 surname => 'Renewal',
1579 categorycode => $patron_category->{categorycode},
1580 branchcode => $branch,
1582 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1583 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1584 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1585 my $datedue = dt_from_string( $issue->date_due() );
1586 is (defined $issue->date_due(), 1, "item 1 checked out");
1587 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1589 my %reserving_borrower_data1 = (
1590 firstname => 'Katrin',
1591 surname => 'Reservation',
1592 categorycode => $patron_category->{categorycode},
1593 branchcode => $branch,
1595 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1597 $branch, $reserving_borrowernumber1, $biblio->biblionumber,
1598 $bibitems, $priority, $resdate, $expdate, $notes,
1599 'a title', $checkitem, $found
1602 my %reserving_borrower_data2 = (
1603 firstname => 'Kirk',
1604 surname => 'Reservation',
1605 categorycode => $patron_category->{categorycode},
1606 branchcode => $branch,
1608 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1610 $branch, $reserving_borrowernumber2, $biblio->biblionumber,
1611 $bibitems, $priority, $resdate, $expdate, $notes,
1612 'a title', $checkitem, $found
1616 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1617 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1620 my $item_3 = $builder->build_sample_item(
1622 biblionumber => $biblio->biblionumber,
1624 replacementprice => 12.00,
1630 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1631 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1635 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1638 my $library = $builder->build( { source => 'Branch' } );
1639 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1641 my $biblionumber = $builder->build_sample_biblio(
1643 branchcode => $library->{branchcode},
1646 my $item_1 = $builder->build_sample_item(
1648 biblionumber => $biblionumber,
1649 library => $library->{branchcode},
1653 my $item_2 = $builder->build_sample_item(
1655 biblionumber => $biblionumber,
1656 library => $library->{branchcode},
1660 my ( $error, $question, $alerts );
1661 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1663 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1664 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1665 is( keys(%$error) + keys(%$alerts), 0, 'No error or alert should be raised' . str($error, $question, $alerts) );
1666 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) );
1668 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1669 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1670 is( keys(%$error) + keys(%$question) + keys(%$alerts), 0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' . str($error, $question, $alerts) );
1672 # Add a subscription
1673 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1675 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1676 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1677 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) );
1679 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1680 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1681 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) );
1684 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1687 my $library = $builder->build( { source => 'Branch' } );
1688 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1691 my $biblionumber = $builder->build_sample_biblio(
1693 branchcode => $library->{branchcode},
1696 my $item_1 = $builder->build_sample_item(
1698 biblionumber => $biblionumber,
1699 library => $library->{branchcode},
1702 my $item_2 = $builder->build_sample_item(
1704 biblionumber => $biblionumber,
1705 library => $library->{branchcode},
1709 # And the issuing rule
1710 Koha::IssuingRules->search->delete;
1711 my $rule = Koha::IssuingRule->new(
1713 categorycode => '*',
1717 firstremind => 1, # 1 day of grace
1718 finedays => 2, # 2 days of fine per day of overdue
1719 lengthunit => 'days',
1724 # Patron cannot issue item_1, they have overdues
1725 my $five_days_ago = dt_from_string->subtract( days => 5 );
1726 my $ten_days_ago = dt_from_string->subtract( days => 10 );
1727 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
1728 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1729 ; # Add another overdue
1731 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1732 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
1733 my $debarments = Koha::Patron::Debarments::GetDebarments(
1734 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1735 is( scalar(@$debarments), 1 );
1737 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1738 # Same for the others
1739 my $expected_expiration = output_pref(
1741 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1742 dateformat => 'sql',
1746 is( $debarments->[0]->{expiration}, $expected_expiration );
1748 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
1749 $debarments = Koha::Patron::Debarments::GetDebarments(
1750 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1751 is( scalar(@$debarments), 1 );
1752 $expected_expiration = output_pref(
1754 dt => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1755 dateformat => 'sql',
1759 is( $debarments->[0]->{expiration}, $expected_expiration );
1761 Koha::Patron::Debarments::DelUniqueDebarment(
1762 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1764 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1765 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
1766 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1767 ; # Add another overdue
1768 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
1769 $debarments = Koha::Patron::Debarments::GetDebarments(
1770 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1771 is( scalar(@$debarments), 1 );
1772 $expected_expiration = output_pref(
1774 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1775 dateformat => 'sql',
1779 is( $debarments->[0]->{expiration}, $expected_expiration );
1781 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
1782 $debarments = Koha::Patron::Debarments::GetDebarments(
1783 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1784 is( scalar(@$debarments), 1 );
1785 $expected_expiration = output_pref(
1787 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1788 dateformat => 'sql',
1792 is( $debarments->[0]->{expiration}, $expected_expiration );
1795 subtest 'AddReturn + suspension_chargeperiod' => sub {
1798 my $library = $builder->build( { source => 'Branch' } );
1799 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1801 my $biblionumber = $builder->build_sample_biblio(
1803 branchcode => $library->{branchcode},
1806 my $item_1 = $builder->build_sample_item(
1808 biblionumber => $biblionumber,
1809 library => $library->{branchcode},
1813 # And the issuing rule
1814 Koha::IssuingRules->search->delete;
1815 my $rule = Koha::IssuingRule->new(
1817 categorycode => '*',
1821 firstremind => 0, # 0 day of grace
1822 finedays => 2, # 2 days of fine per day of overdue
1823 suspension_chargeperiod => 1,
1824 lengthunit => 'days',
1829 my $five_days_ago = dt_from_string->subtract( days => 5 );
1830 # We want to charge 2 days every day, without grace
1831 # With 5 days of overdue: 5 * Z
1832 my $expected_expiration = dt_from_string->add( days => ( 5 * 2 ) / 1 );
1833 test_debarment_on_checkout(
1836 library => $library,
1838 due_date => $five_days_ago,
1839 expiration_date => $expected_expiration,
1843 # We want to charge 2 days every 2 days, without grace
1844 # With 5 days of overdue: (5 * 2) / 2
1845 $rule->suspension_chargeperiod(2)->store;
1846 $expected_expiration = dt_from_string->add( days => floor( 5 * 2 ) / 2 );
1847 test_debarment_on_checkout(
1850 library => $library,
1852 due_date => $five_days_ago,
1853 expiration_date => $expected_expiration,
1857 # We want to charge 2 days every 3 days, with 1 day of grace
1858 # With 5 days of overdue: ((5-1) / 3 ) * 2
1859 $rule->suspension_chargeperiod(3)->store;
1860 $rule->firstremind(1)->store;
1861 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
1862 test_debarment_on_checkout(
1865 library => $library,
1867 due_date => $five_days_ago,
1868 expiration_date => $expected_expiration,
1872 # Use finesCalendar to know if holiday must be skipped to calculate the due date
1873 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
1874 $rule->finedays(2)->store;
1875 $rule->suspension_chargeperiod(1)->store;
1876 $rule->firstremind(0)->store;
1877 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
1878 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
1880 # Adding a holiday 2 days ago
1881 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
1882 my $two_days_ago = dt_from_string->subtract( days => 2 );
1883 $calendar->insert_single_holiday(
1884 day => $two_days_ago->day,
1885 month => $two_days_ago->month,
1886 year => $two_days_ago->year,
1887 title => 'holidayTest-2d',
1888 description => 'holidayDesc 2 days ago'
1890 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
1891 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
1892 test_debarment_on_checkout(
1895 library => $library,
1897 due_date => $five_days_ago,
1898 expiration_date => $expected_expiration,
1902 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
1903 my $two_days_ahead = dt_from_string->add( days => 2 );
1904 $calendar->insert_single_holiday(
1905 day => $two_days_ahead->day,
1906 month => $two_days_ahead->month,
1907 year => $two_days_ahead->year,
1908 title => 'holidayTest+2d',
1909 description => 'holidayDesc 2 days ahead'
1912 # Same as above, but we should skip D+2
1913 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
1914 test_debarment_on_checkout(
1917 library => $library,
1919 due_date => $five_days_ago,
1920 expiration_date => $expected_expiration,
1924 # Adding another holiday, day of expiration date
1925 my $expected_expiration_dt = dt_from_string($expected_expiration);
1926 $calendar->insert_single_holiday(
1927 day => $expected_expiration_dt->day,
1928 month => $expected_expiration_dt->month,
1929 year => $expected_expiration_dt->year,
1930 title => 'holidayTest_exp',
1931 description => 'holidayDesc on expiration date'
1933 # Expiration date will be the day after
1934 test_debarment_on_checkout(
1937 library => $library,
1939 due_date => $five_days_ago,
1940 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
1944 test_debarment_on_checkout(
1947 library => $library,
1949 return_date => dt_from_string->add(days => 5),
1950 expiration_date => dt_from_string->add(days => 5 + (5 * 2 - 1) ),
1955 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
1958 my $library = $builder->build( { source => 'Branch' } );
1959 my $patron1 = $builder->build_object(
1961 class => 'Koha::Patrons',
1963 branchcode => $library->{branchcode},
1964 firstname => "Happy",
1965 surname => "Gilmore",
1969 my $patron2 = $builder->build_object(
1971 class => 'Koha::Patrons',
1973 branchcode => $library->{branchcode},
1974 firstname => "Billy",
1975 surname => "Madison",
1980 C4::Context->_new_userenv('xxx');
1981 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, 'Random Library', '', '', '');
1983 my $item = $builder->build_sample_item(
1985 library => $library->{branchcode},
1989 my ( $error, $question, $alerts );
1990 my $issue = AddIssue( $patron1->unblessed, $item->{barcode} );
1992 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
1993 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
1994 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' );
1996 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
1997 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
1998 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' );
2000 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
2004 subtest 'AddReturn | is_overdue' => sub {
2007 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
2008 t::lib::Mocks::mock_preference('finesMode', 'production');
2009 t::lib::Mocks::mock_preference('MaxFine', '100');
2011 my $library = $builder->build( { source => 'Branch' } );
2012 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
2013 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2014 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2016 my $item = $builder->build_sample_item(
2018 library => $library->{branchcode},
2019 replacementprice => 7
2023 Koha::IssuingRules->search->delete;
2024 my $rule = Koha::IssuingRule->new(
2026 categorycode => '*',
2030 lengthunit => 'days',
2031 fine => 1, # Charge 1 every day of overdue
2037 my $now = dt_from_string;
2038 my $one_day_ago = dt_from_string->subtract( days => 1 );
2039 my $five_days_ago = dt_from_string->subtract( days => 5 );
2040 my $ten_days_ago = dt_from_string->subtract( days => 10 );
2041 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2043 # No return date specified, today will be used => 10 days overdue charged
2044 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2045 AddReturn( $item->{barcode}, $library->{branchcode} );
2046 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2047 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2049 # specify return date 5 days before => no overdue charged
2050 AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
2051 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
2052 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2053 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2055 # specify return date 5 days later => 5 days overdue charged
2056 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2057 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
2058 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2059 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2061 # specify return date 5 days later, specify exemptfine => no overdue charge
2062 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2063 AddReturn( $item->{barcode}, $library->{branchcode}, 1, $five_days_ago );
2064 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2065 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2067 subtest 'bug 22877' => sub {
2071 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2073 # Fake fines cronjob on this checkout
2075 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2076 $ten_days_ago, $now );
2079 issue_id => $issue->issue_id,
2080 itemnumber => $item->{itemnumber},
2081 borrowernumber => $patron->borrowernumber,
2083 due => output_pref($ten_days_ago)
2086 is( int( $patron->account->balance() ),
2087 10, "Overdue fine of 10 days overdue" );
2089 # Fake longoverdue with charge and not marking returned
2090 LostItem( $item->{itemnumber}, 'cronjob', 0 );
2091 is( int( $patron->account->balance() ),
2092 17, "Lost fine of 7 plus 10 days overdue" );
2094 # Now we return it today
2095 AddReturn( $item->{barcode}, $library->{branchcode} );
2096 is( int( $patron->account->balance() ),
2097 17, "Should have a single 10 days overdue fine and lost charge" );
2101 subtest '_FixAccountForLostAndReturned' => sub {
2105 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
2106 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
2108 my $processfee_amount = 20;
2109 my $replacement_amount = 99.00;
2110 my $item_type = $builder->build_object(
2111 { class => 'Koha::ItemTypes',
2113 notforloan => undef,
2115 defaultreplacecost => undef,
2116 processfee => $processfee_amount,
2117 rentalcharge_daily => 0,
2121 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2123 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
2125 subtest 'Full write-off tests' => sub {
2129 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2130 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2131 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
2133 my $item = $builder->build_sample_item(
2135 biblionumber => $biblio->biblionumber,
2136 library => $library->branchcode,
2137 replacementprice => $replacement_amount,
2138 itype => $item_type->itemtype,
2142 AddIssue( $patron->unblessed, $item->barcode );
2144 # Simulate item marked as lost
2145 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2146 LostItem( $item->itemnumber, 1 );
2148 my $processing_fee_lines = Koha::Account::Lines->search(
2149 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2150 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2151 my $processing_fee_line = $processing_fee_lines->next;
2152 is( $processing_fee_line->amount + 0,
2153 $processfee_amount, 'The right PROCESSING amount is generated' );
2154 is( $processing_fee_line->amountoutstanding + 0,
2155 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2157 my $lost_fee_lines = Koha::Account::Lines->search(
2158 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2159 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2160 my $lost_fee_line = $lost_fee_lines->next;
2161 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2162 is( $lost_fee_line->amountoutstanding + 0,
2163 $replacement_amount, 'The right LOST amountoutstanding is generated' );
2164 is( $lost_fee_line->status,
2165 undef, 'The LOST status was not set' );
2167 my $account = $patron->account;
2168 my $debts = $account->outstanding_debits;
2170 # Write off the debt
2171 my $credit = $account->add_credit(
2172 { amount => $account->balance,
2174 interface => 'test',
2177 $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Writeoff' } );
2179 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2180 is( $credit_return_id, undef, 'No LOST_RETURN account line added' );
2182 $lost_fee_line->discard_changes; # reload from DB
2183 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2184 is( $lost_fee_line->debit_type_code,
2185 'LOST', 'Lost fee now still has account type of LOST' );
2186 is( $lost_fee_line->status, 'RETURNED', "Lost fee now has account status of RETURNED");
2188 is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2191 subtest 'Full payment tests' => sub {
2195 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2197 my $item = $builder->build_sample_item(
2199 biblionumber => $biblio->biblionumber,
2200 library => $library->branchcode,
2201 replacementprice => $replacement_amount,
2202 itype => $item_type->itemtype
2206 AddIssue( $patron->unblessed, $item->barcode );
2208 # Simulate item marked as lost
2209 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2210 LostItem( $item->itemnumber, 1 );
2212 my $processing_fee_lines = Koha::Account::Lines->search(
2213 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2214 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2215 my $processing_fee_line = $processing_fee_lines->next;
2216 is( $processing_fee_line->amount + 0,
2217 $processfee_amount, 'The right PROCESSING amount is generated' );
2218 is( $processing_fee_line->amountoutstanding + 0,
2219 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2221 my $lost_fee_lines = Koha::Account::Lines->search(
2222 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2223 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2224 my $lost_fee_line = $lost_fee_lines->next;
2225 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2226 is( $lost_fee_line->amountoutstanding + 0,
2227 $replacement_amount, 'The right LOST amountountstanding is generated' );
2229 my $account = $patron->account;
2230 my $debts = $account->outstanding_debits;
2232 # Write off the debt
2233 my $credit = $account->add_credit(
2234 { amount => $account->balance,
2236 interface => 'test',
2239 $credit->apply( { debits => [ $debts->as_list ], offset_type => 'Payment' } );
2241 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2242 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2244 is( $credit_return->credit_type_code, 'LOST_RETURN', 'An account line of type LOST_RETURN is added' );
2245 is( $credit_return->amount + 0,
2246 -99.00, 'The account line of type LOST_RETURN has an amount of -99' );
2247 is( $credit_return->amountoutstanding + 0,
2248 -99.00, 'The account line of type LOST_RETURN has an amountoutstanding of -99' );
2250 $lost_fee_line->discard_changes;
2251 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2252 is( $lost_fee_line->debit_type_code,
2253 'LOST', 'Lost fee now still has account type of LOST' );
2254 is( $lost_fee_line->status, 'RETURNED', "Lost fee now has account status of RETURNED");
2256 is( $patron->account->balance,
2257 -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2260 subtest 'Test without payment or write off' => sub {
2264 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2266 my $item = $builder->build_sample_item(
2268 biblionumber => $biblio->biblionumber,
2269 library => $library->branchcode,
2270 replacementprice => 23.00,
2271 replacementprice => $replacement_amount,
2272 itype => $item_type->itemtype
2276 AddIssue( $patron->unblessed, $item->barcode );
2278 # Simulate item marked as lost
2279 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2280 LostItem( $item->itemnumber, 1 );
2282 my $processing_fee_lines = Koha::Account::Lines->search(
2283 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2284 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2285 my $processing_fee_line = $processing_fee_lines->next;
2286 is( $processing_fee_line->amount + 0,
2287 $processfee_amount, 'The right PROCESSING amount is generated' );
2288 is( $processing_fee_line->amountoutstanding + 0,
2289 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2291 my $lost_fee_lines = Koha::Account::Lines->search(
2292 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2293 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2294 my $lost_fee_line = $lost_fee_lines->next;
2295 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2296 is( $lost_fee_line->amountoutstanding + 0,
2297 $replacement_amount, 'The right LOST amountountstanding is generated' );
2299 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2300 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2302 is( $credit_return->credit_type_code, 'LOST_RETURN', 'An account line of type LOST_RETURN is added' );
2303 is( $credit_return->amount + 0, -99.00, 'The account line of type LOST_RETURN has an amount of -99' );
2304 is( $credit_return->amountoutstanding + 0, 0, 'The account line of type LOST_RETURN has an amountoutstanding of 0' );
2306 $lost_fee_line->discard_changes;
2307 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2308 is( $lost_fee_line->debit_type_code,
2309 'LOST', 'Lost fee now still has account type of LOST' );
2310 is( $lost_fee_line->status, 'RETURNED', "Lost fee now has account status of RETURNED");
2312 is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2315 subtest 'Test with partial payement and write off, and remaining debt' => sub {
2319 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2320 my $item = $builder->build_sample_item(
2322 biblionumber => $biblio->biblionumber,
2323 library => $library->branchcode,
2324 replacementprice => $replacement_amount,
2325 itype => $item_type->itemtype
2329 AddIssue( $patron->unblessed, $item->barcode );
2331 # Simulate item marked as lost
2332 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2333 LostItem( $item->itemnumber, 1 );
2335 my $processing_fee_lines = Koha::Account::Lines->search(
2336 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'PROCESSING' } );
2337 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2338 my $processing_fee_line = $processing_fee_lines->next;
2339 is( $processing_fee_line->amount + 0,
2340 $processfee_amount, 'The right PROCESSING amount is generated' );
2341 is( $processing_fee_line->amountoutstanding + 0,
2342 $processfee_amount, 'The right PROCESSING amountoutstanding is generated' );
2344 my $lost_fee_lines = Koha::Account::Lines->search(
2345 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, debit_type_code => 'LOST' } );
2346 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2347 my $lost_fee_line = $lost_fee_lines->next;
2348 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2349 is( $lost_fee_line->amountoutstanding + 0,
2350 $replacement_amount, 'The right LOST amountountstanding is generated' );
2352 my $account = $patron->account;
2353 is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PROCESSING + L' );
2356 my $payment_amount = 27;
2357 my $payment = $account->add_credit(
2358 { amount => $payment_amount,
2360 interface => 'test',
2364 $payment->apply( { debits => [ $lost_fee_line ], offset_type => 'Payment' } );
2366 # Partially write off fee
2367 my $write_off_amount = 25;
2368 my $write_off = $account->add_credit(
2369 { amount => $write_off_amount,
2371 interface => 'test',
2374 $write_off->apply( { debits => [ $lost_fee_line ], offset_type => 'Writeoff' } );
2376 is( $account->balance,
2377 $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2378 'Payment and write off applied'
2381 # Store the amountoutstanding value
2382 $lost_fee_line->discard_changes;
2383 my $outstanding = $lost_fee_line->amountoutstanding;
2385 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2386 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2388 is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PROCESSING - PAYMENT (LOST_RETURN)' );
2390 $lost_fee_line->discard_changes;
2391 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2392 is( $lost_fee_line->debit_type_code,
2393 'LOST', 'Lost fee now still has account type of LOST' );
2394 is( $lost_fee_line->status, 'RETURNED', "Lost fee now has account status of RETURNED");
2396 is( $credit_return->credit_type_code, 'LOST_RETURN', 'An account line of type LOST_RETURN is added' );
2397 is( $credit_return->amount + 0,
2398 ($payment_amount + $outstanding ) * -1,
2399 'The account line of type LOST_RETURN has an amount equal to the payment + outstanding'
2401 is( $credit_return->amountoutstanding + 0,
2402 $payment_amount * -1,
2403 'The account line of type LOST_RETURN has an amountoutstanding equal to the payment'
2406 is( $account->balance,
2407 $processfee_amount - $payment_amount,
2408 'The patron balance is the difference between the PROCESSING and the credit'
2412 subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2416 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2417 my $barcode = 'KD123456793';
2418 my $replacement_amount = 100;
2419 my $processfee_amount = 20;
2421 my $item_type = $builder->build_object(
2422 { class => 'Koha::ItemTypes',
2424 notforloan => undef,
2426 defaultreplacecost => undef,
2428 rentalcharge_daily => 0,
2432 my ( undef, undef, $item_id ) = AddItem(
2433 { homebranch => $library->branchcode,
2434 holdingbranch => $library->branchcode,
2435 barcode => $barcode,
2436 replacementprice => $replacement_amount,
2437 itype => $item_type->itemtype
2439 $biblio->biblionumber
2442 AddIssue( $patron->unblessed, $barcode );
2444 # Simulate item marked as lost
2445 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item_id );
2446 LostItem( $item_id, 1 );
2448 my $lost_fee_lines = Koha::Account::Lines->search(
2449 { borrowernumber => $patron->id, itemnumber => $item_id, debit_type_code => 'LOST' } );
2450 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2451 my $lost_fee_line = $lost_fee_lines->next;
2452 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right LOST amount is generated' );
2453 is( $lost_fee_line->amountoutstanding + 0,
2454 $replacement_amount, 'The right LOST amountountstanding is generated' );
2456 my $account = $patron->account;
2457 is( $account->balance, $replacement_amount, 'Balance is L' );
2460 my $payment_amount = 27;
2461 my $payment = $account->add_credit(
2462 { amount => $payment_amount,
2464 interface => 'test',
2467 $payment->apply({ debits => [ $lost_fee_line ], offset_type => 'Payment' });
2469 is( $account->balance,
2470 $replacement_amount - $payment_amount,
2474 my $manual_debit_amount = 80;
2475 $account->add_debit( { amount => $manual_debit_amount, type => 'OVERDUE', interface =>'test' } );
2477 is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
2479 t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
2481 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2482 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2484 is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PROCESSING - payment (LOST_RETURN)' );
2486 my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, debit_type_code => 'OVERDUE', status => 'UNRETURNED' })->next;
2487 is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
2491 subtest '_FixOverduesOnReturn' => sub {
2494 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2495 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2497 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2499 my $branchcode = $library2->{branchcode};
2501 my $item = $builder->build_sample_item(
2503 biblionumber => $biblio->biblionumber,
2504 library => $branchcode,
2505 replacementprice => 99.00,
2510 my $patron = $builder->build( { source => 'Borrower' } );
2512 ## Start with basic call, should just close out the open fine
2513 my $accountline = Koha::Account::Line->new(
2515 borrowernumber => $patron->{borrowernumber},
2516 debit_type_code => 'OVERDUE',
2517 status => 'UNRETURNED',
2518 itemnumber => $item->itemnumber,
2520 amountoutstanding => 99.00,
2521 interface => 'test',
2525 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, undef, 'RETURNED' );
2527 $accountline->_result()->discard_changes();
2529 is( $accountline->amountoutstanding, '99.000000', 'Fine has the same amount outstanding as previously' );
2530 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
2531 is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )');
2533 ## Run again, with exemptfine enabled
2536 debit_type_code => 'OVERDUE',
2537 status => 'UNRETURNED',
2538 amountoutstanding => 99.00,
2542 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' );
2544 $accountline->_result()->discard_changes();
2545 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2547 is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' );
2548 isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )');
2549 is( $accountline->status, 'FORGIVEN', 'Open fine ( account type OVERDUE ) has been set to fine forgiven ( status FORGIVEN )');
2550 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2551 is( $offset->amount + 0, -99, "Amount of offset is correct" );
2552 my $credit = $offset->credit;
2553 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
2554 is( $credit->amount + 0, -99, "Credit amount is set correctly" );
2555 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
2558 subtest '_FixAccountForLostAndReturned returns undef if patron is deleted' => sub {
2561 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2562 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2564 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2566 my $branchcode = $library2->{branchcode};
2568 my $item = $builder->build_sample_item(
2570 biblionumber => $biblio->biblionumber,
2571 library => $branchcode,
2572 replacementprice => 99.00,
2577 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2579 ## Start with basic call, should just close out the open fine
2580 my $accountline = Koha::Account::Line->new(
2582 borrowernumber => $patron->id,
2583 debit_type_code => 'LOST',
2585 itemnumber => $item->itemnumber,
2587 amountoutstanding => 99.00,
2588 interface => 'test',
2594 my $return_value = C4::Circulation::_FixAccountForLostAndReturned( $patron->id, $item->itemnumber );
2596 is( $return_value, undef, "_FixAccountForLostAndReturned returns undef if patron is deleted" );
2600 subtest 'Set waiting flag' => sub {
2603 my $library_1 = $builder->build( { source => 'Branch' } );
2604 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2605 my $library_2 = $builder->build( { source => 'Branch' } );
2606 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2608 my $item = $builder->build_sample_item(
2610 library => $library_1->{branchcode},
2614 set_userenv( $library_2 );
2615 my $reserve_id = AddReserve(
2616 $library_2->{branchcode}, $patron_2->{borrowernumber}, $item->{biblionumber},
2617 '', 1, undef, undef, '', undef, $item->{itemnumber},
2620 set_userenv( $library_1 );
2621 my $do_transfer = 1;
2622 my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2623 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2624 my $hold = Koha::Holds->find( $reserve_id );
2625 is( $hold->found, 'T', 'Hold is in transit' );
2627 my ( $status ) = CheckReserves($item->{itemnumber});
2628 is( $status, 'Reserved', 'Hold is not waiting yet');
2630 set_userenv( $library_2 );
2632 AddReturn( $item->{barcode}, $library_2->{branchcode} );
2633 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2634 $hold = Koha::Holds->find( $reserve_id );
2635 is( $hold->found, 'W', 'Hold is waiting' );
2636 ( $status ) = CheckReserves($item->{itemnumber});
2637 is( $status, 'Waiting', 'Now the hold is waiting');
2640 subtest 'Cancel transfers on lost items' => sub {
2642 my $library_1 = $builder->build( { source => 'Branch' } );
2643 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2644 my $library_2 = $builder->build( { source => 'Branch' } );
2645 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2646 my $biblio = $builder->build_sample_biblio({branchcode => $library->{branchcode}});
2647 my $item = $builder->build_sample_item({
2648 biblionumber => $biblio->biblionumber,
2649 library => $library_1->{branchcode},
2652 set_userenv( $library_2 );
2653 my $reserve_id = AddReserve(
2654 $library_2->{branchcode}, $patron_2->{borrowernumber}, $item->biblionumber, '', 1, undef, undef, '', undef, $item->itemnumber,
2657 #Return book and add transfer
2658 set_userenv( $library_1 );
2659 my $do_transfer = 1;
2660 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
2661 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
2662 C4::Circulation::transferbook( $library_2->{branchcode}, $item->barcode );
2663 my $hold = Koha::Holds->find( $reserve_id );
2664 is( $hold->found, 'T', 'Hold is in transit' );
2666 #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
2667 my ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
2668 is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
2669 my $itemcheck = Koha::Items->find($item->itemnumber);
2670 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Items holding branch is the transfers origin branch before it is marked as lost' );
2672 #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
2673 ModItem( { itemlost => 1 }, $item->biblionumber, $item->itemnumber );
2674 LostItem( $item->itemnumber, 'test', 1 );
2675 ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
2676 is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
2677 $itemcheck = Koha::Items->find($item->itemnumber);
2678 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
2681 subtest 'CanBookBeIssued | is_overdue' => sub {
2684 # Set a simple circ policy
2685 $dbh->do('DELETE FROM issuingrules');
2687 q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
2688 issuelength, lengthunit,
2689 renewalsallowed, renewalperiod,
2690 norenewalbefore, auto_renew,
2707 my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
2708 my $ten_days_go = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
2709 my $library = $builder->build( { source => 'Branch' } );
2710 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2712 my $item = $builder->build_sample_item(
2714 library => $library->{branchcode},
2718 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
2719 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
2720 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
2721 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
2722 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
2723 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
2726 subtest 'ItemsDeniedRenewal preference' => sub {
2729 C4::Context->set_preference('ItemsDeniedRenewal','');
2731 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
2734 INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
2735 norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
2738 '*', $idr_lib->branchcode, '*', 25,
2745 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
2746 homebranch => $idr_lib->branchcode,
2750 itemcallnumber => undef,
2754 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
2755 homebranch => $idr_lib->branchcode,
2758 location => 'NOPROC'
2762 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
2763 branchcode => $idr_lib->branchcode,
2766 my $future = dt_from_string->add( days => 1 );
2767 my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2768 returndate => undef,
2771 borrowernumber => $idr_borrower->borrowernumber,
2772 itemnumber => $deny_book->itemnumber,
2773 onsite_checkout => 0,
2774 date_due => $future,
2777 my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2778 returndate => undef,
2781 borrowernumber => $idr_borrower->borrowernumber,
2782 itemnumber => $allow_book->itemnumber,
2783 onsite_checkout => 0,
2784 date_due => $future,
2790 my ( $idr_mayrenew, $idr_error ) =
2791 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2792 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
2793 is( $idr_error, undef, 'Renewal allowed when no rules' );
2795 $idr_rules="withdrawn: [1]";
2797 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2798 ( $idr_mayrenew, $idr_error ) =
2799 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2800 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
2801 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
2802 ( $idr_mayrenew, $idr_error ) =
2803 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2804 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2805 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2807 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
2809 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2810 ( $idr_mayrenew, $idr_error ) =
2811 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2812 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
2813 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
2814 ( $idr_mayrenew, $idr_error ) =
2815 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2816 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2817 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2819 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
2821 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2822 ( $idr_mayrenew, $idr_error ) =
2823 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2824 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
2825 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
2826 ( $idr_mayrenew, $idr_error ) =
2827 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2828 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2829 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2831 $idr_rules="itemcallnumber: [NULL]";
2832 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2833 ( $idr_mayrenew, $idr_error ) =
2834 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2835 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
2836 $idr_rules="itemcallnumber: ['']";
2837 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2838 ( $idr_mayrenew, $idr_error ) =
2839 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2840 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
2842 $idr_rules="itemnotes: [NULL]";
2843 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2844 ( $idr_mayrenew, $idr_error ) =
2845 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2846 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
2847 $idr_rules="itemnotes: ['']";
2848 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2849 ( $idr_mayrenew, $idr_error ) =
2850 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2851 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
2854 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
2857 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2858 my $library = $builder->build( { source => 'Branch' } );
2859 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2861 my $item = $builder->build_sample_item(
2863 library => $library->{branchcode},
2867 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2868 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2869 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2872 subtest 'CanBookBeIssued | notforloan' => sub {
2875 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
2877 my $library = $builder->build( { source => 'Branch' } );
2878 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2880 my $itemtype = $builder->build(
2882 source => 'Itemtype',
2883 value => { notforloan => undef, }
2886 my $item = $builder->build_sample_item(
2888 library => $library->{branchcode},
2889 itype => $itemtype->{itemtype},
2892 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
2894 my ( $issuingimpossible, $needsconfirmation );
2897 subtest 'item-level_itypes = 1' => sub {
2900 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
2901 # Is for loan at item type and item level
2902 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2903 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2904 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2906 # not for loan at item type level
2907 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2908 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2909 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2912 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2913 'Item can not be issued, not for loan at item type level'
2916 # not for loan at item level
2917 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2918 $item->notforloan( 1 )->store;
2919 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2920 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2923 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2924 'Item can not be issued, not for loan at item type level'
2928 subtest 'item-level_itypes = 0' => sub {
2931 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2933 # We set another itemtype for biblioitem
2934 my $itemtype = $builder->build(
2936 source => 'Itemtype',
2937 value => { notforloan => undef, }
2941 # for loan at item type and item level
2942 $item->notforloan(0)->store;
2943 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
2944 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2945 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2946 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2948 # not for loan at item type level
2949 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2950 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2951 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2954 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2955 'Item can not be issued, not for loan at item type level'
2958 # not for loan at item level
2959 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2960 $item->notforloan( 1 )->store;
2961 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2962 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2965 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2966 'Item can not be issued, not for loan at item type level'
2970 # TODO test with AllowNotForLoanOverride = 1
2973 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
2976 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
2977 my $item = $builder->build_sample_item(
2979 onloan => '2018-01-01',
2983 AddReturn( $item->barcode, $item->homebranch );
2984 $item->discard_changes; # refresh
2985 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
2989 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
2994 t::lib::Mocks::mock_preference('item-level_itypes', 1);
2996 my $issuing_charges = 15;
2997 my $title = 'A title';
2998 my $author = 'Author, An';
2999 my $barcode = 'WHATARETHEODDS';
3001 my $circ = Test::MockModule->new('C4::Circulation');
3003 'GetIssuingCharges',
3005 return $issuing_charges;
3009 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3010 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
3011 my $patron = $builder->build_object({
3012 class => 'Koha::Patrons',
3013 value => { branchcode => $library->id }
3016 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
3017 my ( undef, undef, $item_id ) = AddItem(
3019 homebranch => $library->id,
3020 holdingbranch => $library->id,
3021 barcode => $barcode,
3022 replacementprice => 23.00,
3023 itype => $itemtype->id
3025 $biblio->biblionumber
3027 my $item = Koha::Items->find( $item_id );
3029 my $context = Test::MockModule->new('C4::Context');
3030 $context->mock( userenv => { branch => $library->id } );
3032 # Check the item out
3033 AddIssue( $patron->unblessed, $item->barcode );
3034 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
3035 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3036 my %params_renewal = (
3037 timestamp => { -like => $date . "%" },
3038 module => "CIRCULATION",
3039 action => "RENEWAL",
3041 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
3042 AddRenewal( $patron->id, $item->id, $library->id );
3043 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3044 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
3046 my $checkouts = $patron->checkouts;
3047 # The following will fail if run on 00:00:00
3048 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
3050 my $lines = Koha::Account::Lines->search({
3051 borrowernumber => $patron->id,
3052 itemnumber => $item->id
3055 is( $lines->count, 2 );
3057 my $line = $lines->next;
3058 is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' );
3059 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
3060 is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' );
3062 $line = $lines->next;
3063 is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' );
3064 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
3065 is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' );
3067 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
3068 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3069 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
3070 AddRenewal( $patron->id, $item->id, $library->id );
3071 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3072 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
3076 subtest 'ProcessOfflinePayment() tests' => sub {
3083 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
3084 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3085 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
3087 is( $result, 'Success.', 'The right string is returned' );
3089 my $lines = $patron->account->lines;
3090 is( $lines->count, 1, 'line created correctly');
3092 my $line = $lines->next;
3093 is( $line->amount+0, $amount * -1, 'amount picked from params' );
3094 is( $line->branchcode, $library->id, 'branchcode set correctly' );
3098 subtest 'Incremented fee tests' => sub {
3101 my $dt = dt_from_string();
3102 Time::Fake->offset( $dt->epoch );
3104 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
3107 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3109 my $module = new Test::MockModule('C4::Context');
3110 $module->mock( 'userenv', sub { { branch => $library->id } } );
3112 my $patron = $builder->build_object(
3114 class => 'Koha::Patrons',
3115 value => { categorycode => $patron_category->{categorycode} }
3119 my $itemtype = $builder->build_object(
3121 class => 'Koha::ItemTypes',
3123 notforloan => undef,
3125 rentalcharge_daily => 1.000000
3130 my $item = $builder->build_sample_item(
3132 library => $library->{branchcode},
3133 itype => $itemtype->id,
3137 is( $itemtype->rentalcharge_daily,
3138 '1.000000', 'Daily rental charge stored and retreived correctly' );
3139 is( $item->effective_itemtype, $itemtype->id,
3140 "Itemtype set correctly for item" );
3142 my $dt_from = dt_from_string();
3143 my $dt_to = dt_from_string()->add( days => 7 );
3144 my $dt_to_renew = dt_from_string()->add( days => 13 );
3147 t::lib::Mocks::mock_preference( 'finesCalendar', 'ignoreCalendar' );
3149 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3150 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3151 is( $accountline->amount, '7.000000',
3152 "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar"
3154 $accountline->delete();
3155 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3156 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3157 is( $accountline->amount, '6.000000',
3158 "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal"
3160 $accountline->delete();
3163 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3165 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3166 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3167 is( $accountline->amount, '7.000000',
3168 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed"
3170 $accountline->delete();
3171 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3172 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3173 is( $accountline->amount, '6.000000',
3174 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal"
3176 $accountline->delete();
3179 my $calendar = C4::Calendar->new( branchcode => $library->id );
3180 # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat)
3182 ( $dt_from->day_of_week == 6 ) ? 0
3183 : ( $dt_from->day_of_week == 7 ) ? 1
3184 : $dt_from->day_of_week + 1;
3185 my $closed_day_name = $dt_from->clone->add(days => 1)->day_name;
3186 $calendar->insert_week_day_holiday(
3187 weekday => $closed_day,
3188 title => 'Test holiday',
3189 description => 'Test holiday'
3192 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3193 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3194 is( $accountline->amount, '6.000000',
3195 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name"
3197 $accountline->delete();
3198 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3199 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3200 is( $accountline->amount, '5.000000',
3201 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name, for renewal"
3203 $accountline->delete();
3206 $itemtype->rentalcharge('2.000000')->store;
3207 is( $itemtype->rentalcharge, '2.000000',
3208 'Rental charge updated and retreived correctly' );
3210 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3212 Koha::Account::Lines->search( { itemnumber => $item->id } );
3213 is( $accountlines->count, '2',
3214 "Fixed charge and accrued charge recorded distinctly" );
3215 $accountlines->delete();
3216 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3217 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
3218 is( $accountlines->count, '2',
3219 "Fixed charge and accrued charge recorded distinctly, for renewal" );
3220 $accountlines->delete();
3222 $itemtype->rentalcharge('00.000000')->store;
3223 is( $itemtype->rentalcharge, '00.000000',
3224 'Rental charge reset and retreived correctly' );
3227 my $issuingrule = Koha::IssuingRules->get_effective_issuing_rule(
3229 categorycode => $patron->categorycode,
3230 itemtype => $itemtype->id,
3231 branchcode => $library->id
3234 $issuingrule->lengthunit('hours')->store();
3235 is( $issuingrule->lengthunit, 'hours',
3236 'Issuingrule updated and retrieved correctly' );
3238 $itemtype->rentalcharge_hourly('0.25')->store();
3239 is( $itemtype->rentalcharge_hourly,
3240 '0.25', 'Hourly rental charge stored and retreived correctly' );
3242 $dt_to = dt_from_string()->add( hours => 168 );
3243 $dt_to_renew = dt_from_string()->add( hours => 312 );
3245 t::lib::Mocks::mock_preference( 'finesCalendar', 'ignoreCalendar' );
3247 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3248 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3249 is( $accountline->amount + 0, 42,
3250 "Hourly rental charge calculated correctly with finesCalendar = ignoreCalendar (168h * 0.25u)" );
3251 $accountline->delete();
3252 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3253 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3254 is( $accountline->amount + 0, 36,
3255 "Hourly rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal (312h - 168h * 0.25u)" );
3256 $accountline->delete();
3259 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3261 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3262 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3263 is( $accountline->amount + 0, 36,
3264 "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name (168h - 24h * 0.25u)" );
3265 $accountline->delete();
3266 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3267 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3268 is( $accountline->amount + 0, 30,
3269 "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $closed_day_name, for renewal (312h - 168h - 24h * 0.25u" );
3270 $accountline->delete();
3273 $calendar->delete_holiday( weekday => $closed_day );
3275 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3276 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3277 is( $accountline->amount + 0, 42,
3278 "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed (168h - 0h * 0.25u" );
3279 $accountline->delete();
3280 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3281 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3282 is( $accountline->amount + 0, 36,
3283 "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal (312h - 168h - 0h * 0.25u)" );
3284 $accountline->delete();
3286 $issuingrule->lengthunit('days')->store();
3290 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
3293 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
3294 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3297 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3298 my $patron = $builder->build_object(
3300 class => 'Koha::Patrons',
3301 value => { categorycode => $patron_category->{categorycode} }
3305 my $itemtype = $builder->build_object(
3307 class => 'Koha::ItemTypes',
3311 rentalcharge_daily => 0
3316 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3317 my $item = $builder->build_object(
3319 class => 'Koha::Items',
3321 homebranch => $library->id,
3322 holdingbranch => $library->id,
3326 itype => $itemtype->id,
3327 biblionumber => $biblioitem->{biblionumber},
3328 biblioitemnumber => $biblioitem->{biblioitemnumber},
3333 my ( $issuingimpossible, $needsconfirmation );
3334 my $dt_from = dt_from_string();
3335 my $dt_due = dt_from_string()->add( days => 3 );
3337 $itemtype->rentalcharge('1.000000')->store;
3338 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3339 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
3340 $itemtype->rentalcharge('0')->store;
3341 $itemtype->rentalcharge_daily('1.000000')->store;
3342 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3343 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
3344 $itemtype->rentalcharge_daily('0')->store;
3347 $schema->storage->txn_rollback;
3348 C4::Context->clear_syspref_cache();
3349 $cache->clear_from_cache('single_holidays');