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 => 46;
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" => 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 my $fines_amount = 5;
743 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
746 amount => $fines_amount,
749 item_id => $item_to_auto_renew->{itemnumber},
750 description => "Some fines"
752 )->status('RETURNED')->store;
753 ( $renewokay, $error ) =
754 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
755 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
756 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
760 amount => $fines_amount,
763 item_id => $item_to_auto_renew->{itemnumber},
764 description => "Some fines"
766 )->status('RETURNED')->store;
767 ( $renewokay, $error ) =
768 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
769 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
770 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
774 amount => $fines_amount,
777 item_id => $item_to_auto_renew->{itemnumber},
778 description => "Some fines"
780 )->status('RETURNED')->store;
781 ( $renewokay, $error ) =
782 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
783 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
784 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
786 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
789 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
791 my $item_to_auto_renew = $builder->build({
794 biblionumber => $biblio->biblionumber,
795 homebranch => $branch,
796 holdingbranch => $branch,
800 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
802 my $ten_days_before = dt_from_string->add( days => -10 );
803 my $ten_days_ahead = dt_from_string->add( days => 10 );
805 # Patron is expired and BlockExpiredPatronOpacActions=0
806 # => auto renew is allowed
807 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
808 my $patron = $expired_borrower;
809 my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
810 ( $renewokay, $error ) =
811 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
812 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
813 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
814 Koha::Checkouts->find( $checkout->issue_id )->delete;
817 # Patron is expired and BlockExpiredPatronOpacActions=1
818 # => auto renew is not allowed
819 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
820 $patron = $expired_borrower;
821 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
822 ( $renewokay, $error ) =
823 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
824 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
825 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
826 Koha::Checkouts->find( $checkout->issue_id )->delete;
829 # Patron is not expired and BlockExpiredPatronOpacActions=1
830 # => auto renew is allowed
831 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
832 $patron = $renewing_borrower;
833 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
834 ( $renewokay, $error ) =
835 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
836 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
837 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
838 Koha::Checkouts->find( $checkout->issue_id )->delete;
841 subtest "GetLatestAutoRenewDate" => sub {
843 my $item_to_auto_renew = $builder->build(
846 biblionumber => $biblio->biblionumber,
847 homebranch => $branch,
848 holdingbranch => $branch,
853 my $ten_days_before = dt_from_string->add( days => -10 );
854 my $ten_days_ahead = dt_from_string->add( days => 10 );
855 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
856 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = NULL');
857 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
858 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' );
859 my $five_days_before = dt_from_string->add( days => -5 );
860 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 5, no_auto_renewal_after_hard_limit = NULL');
861 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
862 is( $latest_auto_renew_date->truncate( to => 'minute' ),
863 $five_days_before->truncate( to => 'minute' ),
864 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
866 my $five_days_ahead = dt_from_string->add( days => 5 );
867 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = NULL');
868 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
869 is( $latest_auto_renew_date->truncate( to => 'minute' ),
870 $five_days_ahead->truncate( to => 'minute' ),
871 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
873 my $two_days_ahead = dt_from_string->add( days => 2 );
874 $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 ) );
875 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
876 is( $latest_auto_renew_date->truncate( to => 'day' ),
877 $two_days_ahead->truncate( to => 'day' ),
878 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
880 $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 ) );
881 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
882 is( $latest_auto_renew_date->truncate( to => 'day' ),
883 $two_days_ahead->truncate( to => 'day' ),
884 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
891 # set policy to forbid renewals
892 $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
894 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
895 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
896 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
898 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
899 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
900 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
902 C4::Overdues::UpdateFine(
904 issue_id => $issue->id(),
905 itemnumber => $item_1->itemnumber,
906 borrowernumber => $renewing_borrower->{borrowernumber},
909 due => Koha::DateUtils::output_pref($datedue)
913 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
914 is( $line->accounttype, 'OVERDUE', 'Account line type is OVERDUE' );
915 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
916 is( $line->amountoutstanding, '15.000000', 'Account line amount outstanding is 15.00' );
917 is( $line->amount, '15.000000', 'Account line amount is 15.00' );
918 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
920 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
921 is( $offset->type, 'OVERDUE', 'Account offset type is Fine' );
922 is( $offset->amount, '15.000000', 'Account offset amount is 15.00' );
924 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
925 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
927 LostItem( $item_1->itemnumber, 'test', 1 );
929 $line = Koha::Account::Lines->find($line->id);
930 is( $line->accounttype, 'OVERDUE', 'Account type remains as OVERDUE' );
931 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
933 my $item = Koha::Items->find($item_1->itemnumber);
934 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
935 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
936 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
938 my $total_due = $dbh->selectrow_array(
939 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
940 undef, $renewing_borrower->{borrowernumber}
943 is( $total_due, '15.000000', 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
945 C4::Context->dbh->do("DELETE FROM accountlines");
947 C4::Overdues::UpdateFine(
949 issue_id => $issue2->id(),
950 itemnumber => $item_2->itemnumber,
951 borrowernumber => $renewing_borrower->{borrowernumber},
954 due => Koha::DateUtils::output_pref($datedue)
958 LostItem( $item_2->itemnumber, 'test', 0 );
960 my $item2 = Koha::Items->find($item_2->itemnumber);
961 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
962 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
964 $total_due = $dbh->selectrow_array(
965 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
966 undef, $renewing_borrower->{borrowernumber}
969 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
971 my $future = dt_from_string();
972 $future->add( days => 7 );
973 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
974 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
976 # Users cannot renew any item if there is an overdue item
977 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
978 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
979 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
980 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
981 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
983 my $manager = $builder->build_object({ class => "Koha::Patrons" });
984 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
985 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
986 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
987 LostItem( $item_3->itemnumber, 'test', 0 );
988 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
989 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
991 $accountline->description,
993 $item_3->biblio->title || '',
994 $item_3->barcode || '',
995 $item_3->itemcallnumber || '' ),
996 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
1000 subtest "GetUpcomingDueIssues" => sub {
1003 my $branch = $library2->{branchcode};
1005 #Create another record
1006 my $biblio2 = $builder->build_sample_biblio();
1009 my $item_1 = Koha::Items->find($reused_itemnumber_1);
1010 my $item_2 = Koha::Items->find($reused_itemnumber_2);
1011 my $item_3 = $builder->build_sample_item(
1013 biblionumber => $biblio2->biblionumber,
1021 my %a_borrower_data = (
1022 firstname => 'Fridolyn',
1023 surname => 'SOMERS',
1024 categorycode => $patron_category->{categorycode},
1025 branchcode => $branch,
1028 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1029 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
1031 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
1032 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
1033 my $today = DateTime->today(time_zone => C4::Context->tz());
1035 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
1036 my $datedue = dt_from_string( $issue->date_due() );
1037 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
1038 my $datedue2 = dt_from_string( $issue->date_due() );
1042 # GetUpcomingDueIssues tests
1044 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1045 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
1048 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1049 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1050 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1053 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1054 is ( scalar( @$upcoming_dues ), 1,
1055 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1058 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1060 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1062 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1063 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1065 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1066 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1068 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1069 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1071 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1072 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1074 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1075 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1077 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1078 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1082 subtest "Bug 13841 - Do not create new 0 amount fines" => sub {
1083 my $branch = $library2->{branchcode};
1085 my $biblio = $builder->build_sample_biblio();
1088 my $item = $builder->build_sample_item(
1090 biblionumber => $biblio->biblionumber,
1097 my %a_borrower_data = (
1098 firstname => 'Kyle',
1100 categorycode => $patron_category->{categorycode},
1101 branchcode => $branch,
1104 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1106 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1107 my $issue = AddIssue( $borrower, $item->barcode );
1110 issue_id => $issue->id(),
1111 itemnumber => $item->itemnumber,
1112 borrowernumber => $borrowernumber,
1118 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1119 my $count = $hr->{count};
1121 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1124 subtest "AllowRenewalIfOtherItemsAvailable tests" => sub {
1125 $dbh->do('DELETE FROM issues');
1126 $dbh->do('DELETE FROM items');
1127 $dbh->do('DELETE FROM issuingrules');
1128 Koha::CirculationRules->search()->delete();
1131 INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
1132 norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
1141 Koha::CirculationRules->set_rules(
1143 categorycode => '*',
1151 my $biblio = $builder->build_sample_biblio();
1153 my $item_1 = $builder->build_sample_item(
1155 biblionumber => $biblio->biblionumber,
1156 library => $library2->{branchcode},
1161 my $item_2= $builder->build_sample_item(
1163 biblionumber => $biblio->biblionumber,
1164 library => $library2->{branchcode},
1169 my $borrowernumber1 = Koha::Patron->new({
1170 firstname => 'Kyle',
1172 categorycode => $patron_category->{categorycode},
1173 branchcode => $library2->{branchcode},
1174 })->store->borrowernumber;
1175 my $borrowernumber2 = Koha::Patron->new({
1176 firstname => 'Chelsea',
1178 categorycode => $patron_category->{categorycode},
1179 branchcode => $library2->{branchcode},
1180 })->store->borrowernumber;
1182 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1183 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1185 my $issue = AddIssue( $borrower1, $item_1->barcode );
1187 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1188 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1191 $library2->{branchcode}, $borrowernumber2, $biblio->biblionumber,
1192 '', 1, undef, undef, '',
1196 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1197 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1198 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1199 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1201 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1202 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1203 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1204 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1206 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1207 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1208 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1209 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1211 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1212 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1213 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1214 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1216 # Setting item not checked out to be not for loan but holdable
1217 ModItem({ notforloan => -1 }, $biblio->biblionumber, $item_2->itemnumber);
1219 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1220 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' );
1224 # Don't allow renewing onsite checkout
1225 my $branch = $library->{branchcode};
1227 #Create another record
1228 my $biblio = $builder->build_sample_biblio();
1230 my $item = $builder->build_sample_item(
1232 biblionumber => $biblio->biblionumber,
1238 my $borrowernumber = Koha::Patron->new({
1241 categorycode => $patron_category->{categorycode},
1242 branchcode => $branch,
1243 })->store->borrowernumber;
1245 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1247 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1248 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1249 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1250 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1254 my $library = $builder->build({ source => 'Branch' });
1256 my $biblio = $builder->build_sample_biblio();
1258 my $item = $builder->build_sample_item(
1260 biblionumber => $biblio->biblionumber,
1261 library => $library->{branchcode},
1266 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1268 my $issue = AddIssue( $patron, $item->barcode );
1271 issue_id => $issue->id(),
1272 itemnumber => $item->itemnumber,
1273 borrowernumber => $patron->{borrowernumber},
1280 issue_id => $issue->id(),
1281 itemnumber => $item->itemnumber,
1282 borrowernumber => $patron->{borrowernumber},
1287 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1290 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1293 my $homebranch = $builder->build( { source => 'Branch' } );
1294 my $holdingbranch = $builder->build( { source => 'Branch' } );
1295 my $otherbranch = $builder->build( { source => 'Branch' } );
1296 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1297 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1299 my $item = $builder->build_sample_item(
1301 homebranch => $homebranch->{branchcode},
1302 holdingbranch => $holdingbranch->{branchcode},
1306 set_userenv($holdingbranch);
1308 my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1309 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1311 my ( $error, $question, $alerts );
1313 # AllowReturnToBranch == anywhere
1314 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1315 ## Test that unknown barcodes don't generate internal server errors
1316 set_userenv($homebranch);
1317 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1318 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1319 ## Can be issued from homebranch
1320 set_userenv($homebranch);
1321 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1322 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1323 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1324 ## Can be issued from holdingbranch
1325 set_userenv($holdingbranch);
1326 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1327 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1328 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1329 ## Can be issued from another branch
1330 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1331 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1332 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1334 # AllowReturnToBranch == holdingbranch
1335 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1336 ## Cannot be issued from homebranch
1337 set_userenv($homebranch);
1338 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1339 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1340 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1341 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' );
1342 ## Can be issued from holdinbranch
1343 set_userenv($holdingbranch);
1344 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1345 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1346 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1347 ## Cannot be issued from another branch
1348 set_userenv($otherbranch);
1349 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1350 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1351 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1352 is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' );
1354 # AllowReturnToBranch == homebranch
1355 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1356 ## Can be issued from holdinbranch
1357 set_userenv($homebranch);
1358 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1359 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1360 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1361 ## Cannot be issued from holdinbranch
1362 set_userenv($holdingbranch);
1363 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1364 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1365 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1366 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1367 ## Cannot be issued from holdinbranch
1368 set_userenv($otherbranch);
1369 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1370 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1371 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1372 is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' );
1374 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1377 subtest 'AddIssue & AllowReturnToBranch' => sub {
1380 my $homebranch = $builder->build( { source => 'Branch' } );
1381 my $holdingbranch = $builder->build( { source => 'Branch' } );
1382 my $otherbranch = $builder->build( { source => 'Branch' } );
1383 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1384 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1386 my $item = $builder->build_sample_item(
1388 homebranch => $homebranch->{branchcode},
1389 holdingbranch => $holdingbranch->{branchcode},
1393 set_userenv($holdingbranch);
1395 my $ref_issue = 'Koha::Checkout';
1396 my $issue = AddIssue( $patron_1, $item->{barcode} );
1398 my ( $error, $question, $alerts );
1400 # AllowReturnToBranch == homebranch
1401 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1402 ## Can be issued from homebranch
1403 set_userenv($homebranch);
1404 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch');
1405 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1406 ## Can be issued from holdinbranch
1407 set_userenv($holdingbranch);
1408 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch');
1409 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1410 ## Can be issued from another branch
1411 set_userenv($otherbranch);
1412 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch');
1413 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1415 # AllowReturnToBranch == holdinbranch
1416 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1417 ## Cannot be issued from homebranch
1418 set_userenv($homebranch);
1419 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch');
1420 ## Can be issued from holdingbranch
1421 set_userenv($holdingbranch);
1422 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch');
1423 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1424 ## Cannot be issued from another branch
1425 set_userenv($otherbranch);
1426 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch');
1428 # AllowReturnToBranch == homebranch
1429 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1430 ## Can be issued from homebranch
1431 set_userenv($homebranch);
1432 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' );
1433 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1434 ## Cannot be issued from holdinbranch
1435 set_userenv($holdingbranch);
1436 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' );
1437 ## Cannot be issued from another branch
1438 set_userenv($otherbranch);
1439 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' );
1440 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1443 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1446 my $library = $builder->build( { source => 'Branch' } );
1447 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1448 my $item_1 = $builder->build_sample_item(
1450 library => $library->{branchcode},
1453 my $item_2 = $builder->build_sample_item(
1455 library => $library->{branchcode},
1459 my ( $error, $question, $alerts );
1461 # Patron cannot issue item_1, they have overdues
1462 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1463 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday ); # Add an overdue
1465 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1466 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1467 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
1468 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1470 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1471 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1472 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1473 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1475 # Patron cannot issue item_1, they are debarred
1476 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1477 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1478 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1479 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1480 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1482 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1483 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1484 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1485 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1488 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1491 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1492 my $patron_category_x = $builder->build_object(
1494 class => 'Koha::Patron::Categories',
1495 value => { category_type => 'X' }
1498 my $patron = $builder->build_object(
1500 class => 'Koha::Patrons',
1502 categorycode => $patron_category_x->categorycode,
1503 gonenoaddress => undef,
1510 my $item_1 = $builder->build_sample_item(
1512 library => $library->{branchcode},
1516 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1517 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1519 # TODO There are other tests to provide here
1522 subtest 'MultipleReserves' => sub {
1525 my $biblio = $builder->build_sample_biblio();
1527 my $branch = $library2->{branchcode};
1529 my $item_1 = $builder->build_sample_item(
1531 biblionumber => $biblio->biblionumber,
1533 replacementprice => 12.00,
1538 my $item_2 = $builder->build_sample_item(
1540 biblionumber => $biblio->biblionumber,
1542 replacementprice => 12.00,
1549 my $resdate = undef;
1550 my $expdate = undef;
1552 my $checkitem = undef;
1555 my %renewing_borrower_data = (
1556 firstname => 'John',
1557 surname => 'Renewal',
1558 categorycode => $patron_category->{categorycode},
1559 branchcode => $branch,
1561 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1562 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1563 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1564 my $datedue = dt_from_string( $issue->date_due() );
1565 is (defined $issue->date_due(), 1, "item 1 checked out");
1566 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1568 my %reserving_borrower_data1 = (
1569 firstname => 'Katrin',
1570 surname => 'Reservation',
1571 categorycode => $patron_category->{categorycode},
1572 branchcode => $branch,
1574 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1576 $branch, $reserving_borrowernumber1, $biblio->biblionumber,
1577 $bibitems, $priority, $resdate, $expdate, $notes,
1578 'a title', $checkitem, $found
1581 my %reserving_borrower_data2 = (
1582 firstname => 'Kirk',
1583 surname => 'Reservation',
1584 categorycode => $patron_category->{categorycode},
1585 branchcode => $branch,
1587 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1589 $branch, $reserving_borrowernumber2, $biblio->biblionumber,
1590 $bibitems, $priority, $resdate, $expdate, $notes,
1591 'a title', $checkitem, $found
1595 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1596 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1599 my $item_3 = $builder->build_sample_item(
1601 biblionumber => $biblio->biblionumber,
1603 replacementprice => 12.00,
1609 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1610 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1614 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1617 my $library = $builder->build( { source => 'Branch' } );
1618 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1620 my $biblionumber = $builder->build_sample_biblio(
1622 branchcode => $library->{branchcode},
1625 my $item_1 = $builder->build_sample_item(
1627 biblionumber => $biblionumber,
1628 library => $library->{branchcode},
1632 my $item_2 = $builder->build_sample_item(
1634 biblionumber => $biblionumber,
1635 library => $library->{branchcode},
1639 my ( $error, $question, $alerts );
1640 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1642 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1643 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1644 is( keys(%$error) + keys(%$alerts), 0, 'No error or alert should be raised' . str($error, $question, $alerts) );
1645 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) );
1647 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1648 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1649 is( keys(%$error) + keys(%$question) + keys(%$alerts), 0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' . str($error, $question, $alerts) );
1651 # Add a subscription
1652 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1654 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1655 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1656 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) );
1658 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1659 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1660 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) );
1663 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1666 my $library = $builder->build( { source => 'Branch' } );
1667 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1670 my $biblionumber = $builder->build_sample_biblio(
1672 branchcode => $library->{branchcode},
1675 my $item_1 = $builder->build_sample_item(
1677 biblionumber => $biblionumber,
1678 library => $library->{branchcode},
1681 my $item_2 = $builder->build_sample_item(
1683 biblionumber => $biblionumber,
1684 library => $library->{branchcode},
1688 # And the issuing rule
1689 Koha::IssuingRules->search->delete;
1690 my $rule = Koha::IssuingRule->new(
1692 categorycode => '*',
1696 firstremind => 1, # 1 day of grace
1697 finedays => 2, # 2 days of fine per day of overdue
1698 lengthunit => 'days',
1703 # Patron cannot issue item_1, they have overdues
1704 my $five_days_ago = dt_from_string->subtract( days => 5 );
1705 my $ten_days_ago = dt_from_string->subtract( days => 10 );
1706 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
1707 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1708 ; # Add another overdue
1710 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1711 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
1712 my $debarments = Koha::Patron::Debarments::GetDebarments(
1713 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1714 is( scalar(@$debarments), 1 );
1716 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1717 # Same for the others
1718 my $expected_expiration = output_pref(
1720 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1721 dateformat => 'sql',
1725 is( $debarments->[0]->{expiration}, $expected_expiration );
1727 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
1728 $debarments = Koha::Patron::Debarments::GetDebarments(
1729 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1730 is( scalar(@$debarments), 1 );
1731 $expected_expiration = output_pref(
1733 dt => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1734 dateformat => 'sql',
1738 is( $debarments->[0]->{expiration}, $expected_expiration );
1740 Koha::Patron::Debarments::DelUniqueDebarment(
1741 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1743 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1744 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
1745 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1746 ; # Add another overdue
1747 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
1748 $debarments = Koha::Patron::Debarments::GetDebarments(
1749 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1750 is( scalar(@$debarments), 1 );
1751 $expected_expiration = output_pref(
1753 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1754 dateformat => 'sql',
1758 is( $debarments->[0]->{expiration}, $expected_expiration );
1760 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
1761 $debarments = Koha::Patron::Debarments::GetDebarments(
1762 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1763 is( scalar(@$debarments), 1 );
1764 $expected_expiration = output_pref(
1766 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1767 dateformat => 'sql',
1771 is( $debarments->[0]->{expiration}, $expected_expiration );
1774 subtest 'AddReturn + suspension_chargeperiod' => sub {
1777 my $library = $builder->build( { source => 'Branch' } );
1778 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1780 my $biblionumber = $builder->build_sample_biblio(
1782 branchcode => $library->{branchcode},
1785 my $item_1 = $builder->build_sample_item(
1787 biblionumber => $biblionumber,
1788 library => $library->{branchcode},
1792 # And the issuing rule
1793 Koha::IssuingRules->search->delete;
1794 my $rule = Koha::IssuingRule->new(
1796 categorycode => '*',
1800 firstremind => 0, # 0 day of grace
1801 finedays => 2, # 2 days of fine per day of overdue
1802 suspension_chargeperiod => 1,
1803 lengthunit => 'days',
1808 my $five_days_ago = dt_from_string->subtract( days => 5 );
1809 # We want to charge 2 days every day, without grace
1810 # With 5 days of overdue: 5 * Z
1811 my $expected_expiration = dt_from_string->add( days => ( 5 * 2 ) / 1 );
1812 test_debarment_on_checkout(
1815 library => $library,
1817 due_date => $five_days_ago,
1818 expiration_date => $expected_expiration,
1822 # We want to charge 2 days every 2 days, without grace
1823 # With 5 days of overdue: (5 * 2) / 2
1824 $rule->suspension_chargeperiod(2)->store;
1825 $expected_expiration = dt_from_string->add( days => floor( 5 * 2 ) / 2 );
1826 test_debarment_on_checkout(
1829 library => $library,
1831 due_date => $five_days_ago,
1832 expiration_date => $expected_expiration,
1836 # We want to charge 2 days every 3 days, with 1 day of grace
1837 # With 5 days of overdue: ((5-1) / 3 ) * 2
1838 $rule->suspension_chargeperiod(3)->store;
1839 $rule->firstremind(1)->store;
1840 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
1841 test_debarment_on_checkout(
1844 library => $library,
1846 due_date => $five_days_ago,
1847 expiration_date => $expected_expiration,
1851 # Use finesCalendar to know if holiday must be skipped to calculate the due date
1852 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
1853 $rule->finedays(2)->store;
1854 $rule->suspension_chargeperiod(1)->store;
1855 $rule->firstremind(0)->store;
1856 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
1857 t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed');
1859 # Adding a holiday 2 days ago
1860 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
1861 my $two_days_ago = dt_from_string->subtract( days => 2 );
1862 $calendar->insert_single_holiday(
1863 day => $two_days_ago->day,
1864 month => $two_days_ago->month,
1865 year => $two_days_ago->year,
1866 title => 'holidayTest-2d',
1867 description => 'holidayDesc 2 days ago'
1869 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
1870 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
1871 test_debarment_on_checkout(
1874 library => $library,
1876 due_date => $five_days_ago,
1877 expiration_date => $expected_expiration,
1881 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
1882 my $two_days_ahead = dt_from_string->add( days => 2 );
1883 $calendar->insert_single_holiday(
1884 day => $two_days_ahead->day,
1885 month => $two_days_ahead->month,
1886 year => $two_days_ahead->year,
1887 title => 'holidayTest+2d',
1888 description => 'holidayDesc 2 days ahead'
1891 # Same as above, but we should skip D+2
1892 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
1893 test_debarment_on_checkout(
1896 library => $library,
1898 due_date => $five_days_ago,
1899 expiration_date => $expected_expiration,
1903 # Adding another holiday, day of expiration date
1904 my $expected_expiration_dt = dt_from_string($expected_expiration);
1905 $calendar->insert_single_holiday(
1906 day => $expected_expiration_dt->day,
1907 month => $expected_expiration_dt->month,
1908 year => $expected_expiration_dt->year,
1909 title => 'holidayTest_exp',
1910 description => 'holidayDesc on expiration date'
1912 # Expiration date will be the day after
1913 test_debarment_on_checkout(
1916 library => $library,
1918 due_date => $five_days_ago,
1919 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
1923 test_debarment_on_checkout(
1926 library => $library,
1928 return_date => dt_from_string->add(days => 5),
1929 expiration_date => dt_from_string->add(days => 5 + (5 * 2 - 1) ),
1934 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
1937 my $library = $builder->build( { source => 'Branch' } );
1938 my $patron1 = $builder->build_object(
1940 class => 'Koha::Patrons',
1942 branchcode => $library->{branchcode},
1943 firstname => "Happy",
1944 surname => "Gilmore",
1948 my $patron2 = $builder->build_object(
1950 class => 'Koha::Patrons',
1952 branchcode => $library->{branchcode},
1953 firstname => "Billy",
1954 surname => "Madison",
1959 C4::Context->_new_userenv('xxx');
1960 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, 'Random Library', '', '', '');
1962 my $item = $builder->build_sample_item(
1964 library => $library->{branchcode},
1968 my ( $error, $question, $alerts );
1969 my $issue = AddIssue( $patron1->unblessed, $item->{barcode} );
1971 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
1972 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
1973 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' );
1975 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
1976 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
1977 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' );
1979 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
1983 subtest 'AddReturn | is_overdue' => sub {
1986 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
1987 t::lib::Mocks::mock_preference('finesMode', 'production');
1988 t::lib::Mocks::mock_preference('MaxFine', '100');
1990 my $library = $builder->build( { source => 'Branch' } );
1991 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1992 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1993 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
1995 my $item = $builder->build_sample_item(
1997 library => $library->{branchcode},
1998 replacementprice => 7
2002 Koha::IssuingRules->search->delete;
2003 my $rule = Koha::IssuingRule->new(
2005 categorycode => '*',
2009 lengthunit => 'days',
2010 fine => 1, # Charge 1 every day of overdue
2016 my $now = dt_from_string;
2017 my $one_day_ago = dt_from_string->subtract( days => 1 );
2018 my $five_days_ago = dt_from_string->subtract( days => 5 );
2019 my $ten_days_ago = dt_from_string->subtract( days => 10 );
2020 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2022 # No return date specified, today will be used => 10 days overdue charged
2023 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2024 AddReturn( $item->{barcode}, $library->{branchcode} );
2025 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2026 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2028 # specify return date 5 days before => no overdue charged
2029 AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
2030 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
2031 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2032 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2034 # specify return date 5 days later => 5 days overdue charged
2035 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2036 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
2037 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2038 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2040 # specify return date 5 days later, specify exemptfine => no overdue charge
2041 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2042 AddReturn( $item->{barcode}, $library->{branchcode}, 1, $five_days_ago );
2043 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2044 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2046 subtest 'bug 22877' => sub {
2050 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2052 # Fake fines cronjob on this checkout
2054 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2055 $ten_days_ago, $now );
2058 issue_id => $issue->issue_id,
2059 itemnumber => $item->{itemnumber},
2060 borrowernumber => $patron->borrowernumber,
2062 due => output_pref($ten_days_ago)
2065 is( int( $patron->account->balance() ),
2066 10, "Overdue fine of 10 days overdue" );
2068 # Fake longoverdue with charge and not marking returned
2069 LostItem( $item->{itemnumber}, 'cronjob', 0 );
2070 is( int( $patron->account->balance() ),
2071 17, "Lost fine of 7 plus 10 days overdue" );
2073 # Now we return it today
2074 AddReturn( $item->{barcode}, $library->{branchcode} );
2075 is( int( $patron->account->balance() ),
2076 17, "Should have a single 10 days overdue fine and lost charge" );
2080 subtest '_FixAccountForLostAndReturned' => sub {
2084 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
2085 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
2087 my $processfee_amount = 20;
2088 my $replacement_amount = 99.00;
2089 my $item_type = $builder->build_object(
2090 { class => 'Koha::ItemTypes',
2092 notforloan => undef,
2094 defaultreplacecost => undef,
2095 processfee => $processfee_amount,
2096 rentalcharge_daily => 0,
2100 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2102 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
2104 subtest 'Full write-off tests' => sub {
2108 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2109 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2110 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
2112 my $item = $builder->build_sample_item(
2114 biblionumber => $biblio->biblionumber,
2115 library => $library->branchcode,
2116 replacementprice => $replacement_amount,
2117 itype => $item_type->itemtype,
2121 AddIssue( $patron->unblessed, $item->barcode );
2123 # Simulate item marked as lost
2124 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2125 LostItem( $item->itemnumber, 1 );
2127 my $processing_fee_lines = Koha::Account::Lines->search(
2128 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2129 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2130 my $processing_fee_line = $processing_fee_lines->next;
2131 is( $processing_fee_line->amount + 0,
2132 $processfee_amount, 'The right PF amount is generated' );
2133 is( $processing_fee_line->amountoutstanding + 0,
2134 $processfee_amount, 'The right PF amountoutstanding is generated' );
2136 my $lost_fee_lines = Koha::Account::Lines->search(
2137 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2138 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2139 my $lost_fee_line = $lost_fee_lines->next;
2140 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2141 is( $lost_fee_line->amountoutstanding + 0,
2142 $replacement_amount, 'The right L amountoutstanding is generated' );
2144 my $account = $patron->account;
2145 my $debts = $account->outstanding_debits;
2147 # Write off the debt
2148 my $credit = $account->add_credit(
2149 { amount => $account->balance,
2151 interface => 'test',
2154 $credit->apply( { debits => $debts, offset_type => 'Writeoff' } );
2156 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2157 is( $credit_return_id, undef, 'No CR account line added' );
2159 $lost_fee_line->discard_changes; # reload from DB
2160 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2161 is( $lost_fee_line->accounttype,
2162 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2164 is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2167 subtest 'Full payment tests' => sub {
2171 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2173 my $item = $builder->build_sample_item(
2175 biblionumber => $biblio->biblionumber,
2176 library => $library->branchcode,
2177 replacementprice => $replacement_amount,
2178 itype => $item_type->itemtype
2182 AddIssue( $patron->unblessed, $item->barcode );
2184 # Simulate item marked as lost
2185 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2186 LostItem( $item->itemnumber, 1 );
2188 my $processing_fee_lines = Koha::Account::Lines->search(
2189 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2190 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2191 my $processing_fee_line = $processing_fee_lines->next;
2192 is( $processing_fee_line->amount + 0,
2193 $processfee_amount, 'The right PF amount is generated' );
2194 is( $processing_fee_line->amountoutstanding + 0,
2195 $processfee_amount, 'The right PF amountoutstanding is generated' );
2197 my $lost_fee_lines = Koha::Account::Lines->search(
2198 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2199 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2200 my $lost_fee_line = $lost_fee_lines->next;
2201 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2202 is( $lost_fee_line->amountoutstanding + 0,
2203 $replacement_amount, 'The right L amountountstanding is generated' );
2205 my $account = $patron->account;
2206 my $debts = $account->outstanding_debits;
2208 # Write off the debt
2209 my $credit = $account->add_credit(
2210 { amount => $account->balance,
2212 interface => 'test',
2215 $credit->apply( { debits => $debts, offset_type => 'Payment' } );
2217 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2218 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2220 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2221 is( $credit_return->amount + 0,
2222 -99.00, 'The account line of type CR has an amount of -99' );
2223 is( $credit_return->amountoutstanding + 0,
2224 -99.00, 'The account line of type CR has an amountoutstanding of -99' );
2226 $lost_fee_line->discard_changes;
2227 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2228 is( $lost_fee_line->accounttype,
2229 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2231 is( $patron->account->balance,
2232 -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2235 subtest 'Test without payment or write off' => sub {
2239 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2241 my $item = $builder->build_sample_item(
2243 biblionumber => $biblio->biblionumber,
2244 library => $library->branchcode,
2245 replacementprice => 23.00,
2246 replacementprice => $replacement_amount,
2247 itype => $item_type->itemtype
2251 AddIssue( $patron->unblessed, $item->barcode );
2253 # Simulate item marked as lost
2254 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2255 LostItem( $item->itemnumber, 1 );
2257 my $processing_fee_lines = Koha::Account::Lines->search(
2258 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2259 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2260 my $processing_fee_line = $processing_fee_lines->next;
2261 is( $processing_fee_line->amount + 0,
2262 $processfee_amount, 'The right PF amount is generated' );
2263 is( $processing_fee_line->amountoutstanding + 0,
2264 $processfee_amount, 'The right PF amountoutstanding is generated' );
2266 my $lost_fee_lines = Koha::Account::Lines->search(
2267 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2268 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2269 my $lost_fee_line = $lost_fee_lines->next;
2270 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2271 is( $lost_fee_line->amountoutstanding + 0,
2272 $replacement_amount, 'The right L amountountstanding is generated' );
2274 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2275 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2277 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2278 is( $credit_return->amount + 0, -99.00, 'The account line of type CR has an amount of -99' );
2279 is( $credit_return->amountoutstanding + 0, 0, 'The account line of type CR has an amountoutstanding of 0' );
2281 $lost_fee_line->discard_changes;
2282 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2283 is( $lost_fee_line->accounttype, 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2285 is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2288 subtest 'Test with partial payement and write off, and remaining debt' => sub {
2292 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2293 my $item = $builder->build_sample_item(
2295 biblionumber => $biblio->biblionumber,
2296 library => $library->branchcode,
2297 replacementprice => $replacement_amount,
2298 itype => $item_type->itemtype
2302 AddIssue( $patron->unblessed, $item->barcode );
2304 # Simulate item marked as lost
2305 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2306 LostItem( $item->itemnumber, 1 );
2308 my $processing_fee_lines = Koha::Account::Lines->search(
2309 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2310 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2311 my $processing_fee_line = $processing_fee_lines->next;
2312 is( $processing_fee_line->amount + 0,
2313 $processfee_amount, 'The right PF amount is generated' );
2314 is( $processing_fee_line->amountoutstanding + 0,
2315 $processfee_amount, 'The right PF amountoutstanding is generated' );
2317 my $lost_fee_lines = Koha::Account::Lines->search(
2318 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2319 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2320 my $lost_fee_line = $lost_fee_lines->next;
2321 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2322 is( $lost_fee_line->amountoutstanding + 0,
2323 $replacement_amount, 'The right L amountountstanding is generated' );
2325 my $account = $patron->account;
2326 is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PF + L' );
2329 my $payment_amount = 27;
2330 my $payment = $account->add_credit(
2331 { amount => $payment_amount,
2333 interface => 'test',
2337 $payment->apply( { debits => $lost_fee_lines->reset, offset_type => 'Payment' } );
2339 # Partially write off fee
2340 my $write_off_amount = 25;
2341 my $write_off = $account->add_credit(
2342 { amount => $write_off_amount,
2344 interface => 'test',
2347 $write_off->apply( { debits => $lost_fee_lines->reset, offset_type => 'Writeoff' } );
2349 is( $account->balance,
2350 $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2351 'Payment and write off applied'
2354 # Store the amountoutstanding value
2355 $lost_fee_line->discard_changes;
2356 my $outstanding = $lost_fee_line->amountoutstanding;
2358 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2359 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2361 is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2363 $lost_fee_line->discard_changes;
2364 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2365 is( $lost_fee_line->accounttype,
2366 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2368 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2369 is( $credit_return->amount + 0,
2370 ($payment_amount + $outstanding ) * -1,
2371 'The account line of type CR has an amount equal to the payment + outstanding'
2373 is( $credit_return->amountoutstanding + 0,
2374 $payment_amount * -1,
2375 'The account line of type CR has an amountoutstanding equal to the payment'
2378 is( $account->balance,
2379 $processfee_amount - $payment_amount,
2380 'The patron balance is the difference between the PF and the credit'
2384 subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2388 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2389 my $barcode = 'KD123456793';
2390 my $replacement_amount = 100;
2391 my $processfee_amount = 20;
2393 my $item_type = $builder->build_object(
2394 { class => 'Koha::ItemTypes',
2396 notforloan => undef,
2398 defaultreplacecost => undef,
2400 rentalcharge_daily => 0,
2404 my ( undef, undef, $item_id ) = AddItem(
2405 { homebranch => $library->branchcode,
2406 holdingbranch => $library->branchcode,
2407 barcode => $barcode,
2408 replacementprice => $replacement_amount,
2409 itype => $item_type->itemtype
2411 $biblio->biblionumber
2414 AddIssue( $patron->unblessed, $barcode );
2416 # Simulate item marked as lost
2417 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item_id );
2418 LostItem( $item_id, 1 );
2420 my $lost_fee_lines = Koha::Account::Lines->search(
2421 { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2422 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2423 my $lost_fee_line = $lost_fee_lines->next;
2424 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2425 is( $lost_fee_line->amountoutstanding + 0,
2426 $replacement_amount, 'The right L amountountstanding is generated' );
2428 my $account = $patron->account;
2429 is( $account->balance, $replacement_amount, 'Balance is L' );
2432 my $payment_amount = 27;
2433 my $payment = $account->add_credit(
2434 { amount => $payment_amount,
2436 interface => 'test',
2439 $payment->apply({ debits => $lost_fee_lines->reset, offset_type => 'Payment' });
2441 is( $account->balance,
2442 $replacement_amount - $payment_amount,
2446 my $manual_debit_amount = 80;
2447 $account->add_debit( { amount => $manual_debit_amount, type => 'overdue', interface =>'test' } );
2449 is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
2451 t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
2453 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2454 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2456 is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2458 my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, accounttype => 'OVERDUE', status => 'UNRETURNED' })->next;
2459 is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
2463 subtest '_FixOverduesOnReturn' => sub {
2466 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2467 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2469 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2471 my $branchcode = $library2->{branchcode};
2473 my $item = $builder->build_sample_item(
2475 biblionumber => $biblio->biblionumber,
2476 library => $branchcode,
2477 replacementprice => 99.00,
2482 my $patron = $builder->build( { source => 'Borrower' } );
2484 ## Start with basic call, should just close out the open fine
2485 my $accountline = Koha::Account::Line->new(
2487 borrowernumber => $patron->{borrowernumber},
2488 accounttype => 'OVERDUE',
2489 status => 'UNRETURNED',
2490 itemnumber => $item->itemnumber,
2492 amountoutstanding => 99.00,
2493 interface => 'test',
2497 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber );
2499 $accountline->_result()->discard_changes();
2501 is( $accountline->amountoutstanding, '99.000000', 'Fine has the same amount outstanding as previously' );
2502 is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status RETURNED )');
2504 ## Run again, with exemptfine enabled
2507 accounttype => 'OVERDUE',
2508 status => 'UNRETURNED',
2509 amountoutstanding => 99.00,
2513 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1 );
2515 $accountline->_result()->discard_changes();
2516 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2518 is( $accountline->amountoutstanding + 0, 0, 'Fine has been reduced to 0' );
2519 is( $accountline->status, 'FORGIVEN', 'Open fine ( account type OVERDUE ) has been set to fine forgiven ( status FORGIVEN )');
2520 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2521 is( $offset->amount, '-99.000000', "Amount of offset is correct" );
2522 my $credit = $offset->credit;
2523 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
2524 is( $credit->amount, '-99.000000', "Credit amount is set correctly" );
2525 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
2528 subtest '_FixAccountForLostAndReturned returns undef if patron is deleted' => sub {
2531 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2532 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2534 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2536 my $branchcode = $library2->{branchcode};
2538 my $item = $builder->build_sample_item(
2540 biblionumber => $biblio->biblionumber,
2541 library => $branchcode,
2542 replacementprice => 99.00,
2547 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2549 ## Start with basic call, should just close out the open fine
2550 my $accountline = Koha::Account::Line->new(
2552 borrowernumber => $patron->id,
2555 itemnumber => $item->itemnumber,
2557 amountoutstanding => 99.00,
2558 interface => 'test',
2564 my $return_value = C4::Circulation::_FixAccountForLostAndReturned( $patron->id, $item->itemnumber );
2566 is( $return_value, undef, "_FixAccountForLostAndReturned returns undef if patron is deleted" );
2570 subtest 'Set waiting flag' => sub {
2573 my $library_1 = $builder->build( { source => 'Branch' } );
2574 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2575 my $library_2 = $builder->build( { source => 'Branch' } );
2576 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2578 my $item = $builder->build_sample_item(
2580 library => $library_1->{branchcode},
2584 set_userenv( $library_2 );
2585 my $reserve_id = AddReserve(
2586 $library_2->{branchcode}, $patron_2->{borrowernumber}, $item->{biblionumber},
2587 '', 1, undef, undef, '', undef, $item->{itemnumber},
2590 set_userenv( $library_1 );
2591 my $do_transfer = 1;
2592 my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2593 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2594 my $hold = Koha::Holds->find( $reserve_id );
2595 is( $hold->found, 'T', 'Hold is in transit' );
2597 my ( $status ) = CheckReserves($item->{itemnumber});
2598 is( $status, 'Reserved', 'Hold is not waiting yet');
2600 set_userenv( $library_2 );
2602 AddReturn( $item->{barcode}, $library_2->{branchcode} );
2603 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2604 $hold = Koha::Holds->find( $reserve_id );
2605 is( $hold->found, 'W', 'Hold is waiting' );
2606 ( $status ) = CheckReserves($item->{itemnumber});
2607 is( $status, 'Waiting', 'Now the hold is waiting');
2610 subtest 'Cancel transfers on lost items' => sub {
2612 my $library_1 = $builder->build( { source => 'Branch' } );
2613 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2614 my $library_2 = $builder->build( { source => 'Branch' } );
2615 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2616 my $biblio = $builder->build_sample_biblio({branchcode => $library->{branchcode}});
2617 my $item = $builder->build_sample_item({
2618 biblionumber => $biblio->biblionumber,
2619 library => $library_1->{branchcode},
2622 set_userenv( $library_2 );
2623 my $reserve_id = AddReserve(
2624 $library_2->{branchcode}, $patron_2->{borrowernumber}, $item->biblionumber, '', 1, undef, undef, '', undef, $item->itemnumber,
2627 #Return book and add transfer
2628 set_userenv( $library_1 );
2629 my $do_transfer = 1;
2630 my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} );
2631 ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id );
2632 C4::Circulation::transferbook( $library_2->{branchcode}, $item->barcode );
2633 my $hold = Koha::Holds->find( $reserve_id );
2634 is( $hold->found, 'T', 'Hold is in transit' );
2636 #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
2637 my ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
2638 is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
2639 my $itemcheck = Koha::Items->find($item->itemnumber);
2640 is( $itemcheck->holdingbranch, $library_2->{branchcode}, 'Items holding branch is the transfers destination branch before it is marked as lost' );
2642 #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
2643 ModItem( { itemlost => 1 }, $item->biblionumber, $item->itemnumber );
2644 LostItem( $item->itemnumber, 'test', 1 );
2645 ($datesent,$frombranch,$tobranch) = GetTransfers($item->itemnumber);
2646 is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
2647 $itemcheck = Koha::Items->find($item->itemnumber);
2648 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
2651 subtest 'CanBookBeIssued | is_overdue' => sub {
2654 # Set a simple circ policy
2655 $dbh->do('DELETE FROM issuingrules');
2657 q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
2658 issuelength, lengthunit,
2659 renewalsallowed, renewalperiod,
2660 norenewalbefore, auto_renew,
2677 my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
2678 my $ten_days_go = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
2679 my $library = $builder->build( { source => 'Branch' } );
2680 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2682 my $item = $builder->build_sample_item(
2684 library => $library->{branchcode},
2688 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
2689 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
2690 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
2691 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
2692 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
2693 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
2696 subtest 'ItemsDeniedRenewal preference' => sub {
2699 C4::Context->set_preference('ItemsDeniedRenewal','');
2701 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
2704 INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
2705 norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
2708 '*', $idr_lib->branchcode, '*', 25,
2715 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
2716 homebranch => $idr_lib->branchcode,
2720 itemcallnumber => undef,
2724 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
2725 homebranch => $idr_lib->branchcode,
2728 location => 'NOPROC'
2732 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
2733 branchcode => $idr_lib->branchcode,
2736 my $future = dt_from_string->add( days => 1 );
2737 my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2738 returndate => undef,
2741 borrowernumber => $idr_borrower->borrowernumber,
2742 itemnumber => $deny_book->itemnumber,
2743 onsite_checkout => 0,
2744 date_due => $future,
2747 my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2748 returndate => undef,
2751 borrowernumber => $idr_borrower->borrowernumber,
2752 itemnumber => $allow_book->itemnumber,
2753 onsite_checkout => 0,
2754 date_due => $future,
2760 my ( $idr_mayrenew, $idr_error ) =
2761 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2762 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
2763 is( $idr_error, undef, 'Renewal allowed when no rules' );
2765 $idr_rules="withdrawn: [1]";
2767 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2768 ( $idr_mayrenew, $idr_error ) =
2769 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2770 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
2771 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
2772 ( $idr_mayrenew, $idr_error ) =
2773 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2774 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2775 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2777 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
2779 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2780 ( $idr_mayrenew, $idr_error ) =
2781 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2782 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
2783 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
2784 ( $idr_mayrenew, $idr_error ) =
2785 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2786 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2787 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2789 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
2791 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2792 ( $idr_mayrenew, $idr_error ) =
2793 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2794 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
2795 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
2796 ( $idr_mayrenew, $idr_error ) =
2797 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2798 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2799 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2801 $idr_rules="itemcallnumber: [NULL]";
2802 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2803 ( $idr_mayrenew, $idr_error ) =
2804 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2805 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
2806 $idr_rules="itemcallnumber: ['']";
2807 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2808 ( $idr_mayrenew, $idr_error ) =
2809 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2810 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
2812 $idr_rules="itemnotes: [NULL]";
2813 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2814 ( $idr_mayrenew, $idr_error ) =
2815 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2816 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
2817 $idr_rules="itemnotes: ['']";
2818 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2819 ( $idr_mayrenew, $idr_error ) =
2820 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2821 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
2824 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
2827 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2828 my $library = $builder->build( { source => 'Branch' } );
2829 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2831 my $item = $builder->build_sample_item(
2833 library => $library->{branchcode},
2837 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2838 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2839 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2842 subtest 'CanBookBeIssued | notforloan' => sub {
2845 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
2847 my $library = $builder->build( { source => 'Branch' } );
2848 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2850 my $itemtype = $builder->build(
2852 source => 'Itemtype',
2853 value => { notforloan => undef, }
2856 my $item = $builder->build_sample_item(
2858 library => $library->{branchcode},
2859 itype => $itemtype->{itemtype},
2862 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
2864 my ( $issuingimpossible, $needsconfirmation );
2867 subtest 'item-level_itypes = 1' => sub {
2870 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
2871 # Is for loan at item type and item level
2872 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2873 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2874 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2876 # not for loan at item type level
2877 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2878 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2879 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2882 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2883 'Item can not be issued, not for loan at item type level'
2886 # not for loan at item level
2887 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2888 $item->notforloan( 1 )->store;
2889 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2890 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2893 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2894 'Item can not be issued, not for loan at item type level'
2898 subtest 'item-level_itypes = 0' => sub {
2901 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2903 # We set another itemtype for biblioitem
2904 my $itemtype = $builder->build(
2906 source => 'Itemtype',
2907 value => { notforloan => undef, }
2911 # for loan at item type and item level
2912 $item->notforloan(0)->store;
2913 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
2914 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2915 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2916 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2918 # not for loan at item type level
2919 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2920 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2921 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2924 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2925 'Item can not be issued, not for loan at item type level'
2928 # not for loan at item level
2929 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2930 $item->notforloan( 1 )->store;
2931 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2932 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2935 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2936 'Item can not be issued, not for loan at item type level'
2940 # TODO test with AllowNotForLoanOverride = 1
2943 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
2946 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
2947 my $item = $builder->build_sample_item(
2949 onloan => '2018-01-01',
2953 AddReturn( $item->barcode, $item->homebranch );
2954 $item->discard_changes; # refresh
2955 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
2959 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
2964 t::lib::Mocks::mock_preference('item-level_itypes', 1);
2966 my $issuing_charges = 15;
2967 my $title = 'A title';
2968 my $author = 'Author, An';
2969 my $barcode = 'WHATARETHEODDS';
2971 my $circ = Test::MockModule->new('C4::Circulation');
2973 'GetIssuingCharges',
2975 return $issuing_charges;
2979 my $library = $builder->build_object({ class => 'Koha::Libraries' });
2980 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
2981 my $patron = $builder->build_object({
2982 class => 'Koha::Patrons',
2983 value => { branchcode => $library->id }
2986 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
2987 my ( undef, undef, $item_id ) = AddItem(
2989 homebranch => $library->id,
2990 holdingbranch => $library->id,
2991 barcode => $barcode,
2992 replacementprice => 23.00,
2993 itype => $itemtype->id
2995 $biblio->biblionumber
2997 my $item = Koha::Items->find( $item_id );
2999 my $context = Test::MockModule->new('C4::Context');
3000 $context->mock( userenv => { branch => $library->id } );
3002 # Check the item out
3003 AddIssue( $patron->unblessed, $item->barcode );
3004 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
3005 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3006 my %params_renewal = (
3007 timestamp => { -like => $date . "%" },
3008 module => "CIRCULATION",
3009 action => "RENEWAL",
3011 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
3012 AddRenewal( $patron->id, $item->id, $library->id );
3013 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3014 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
3016 my $checkouts = $patron->checkouts;
3017 # The following will fail if run on 00:00:00
3018 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
3020 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
3021 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3022 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
3023 AddRenewal( $patron->id, $item->id, $library->id );
3024 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3025 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
3027 my $lines = Koha::Account::Lines->search({
3028 borrowernumber => $patron->id,
3029 itemnumber => $item->id
3032 is( $lines->count, 3 );
3034 my $line = $lines->next;
3035 is( $line->accounttype, 'Rent', 'The issuing charge generates an accountline' );
3036 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
3037 is( $line->description, 'Rental', 'AddIssuingCharge set a hardcoded description for the accountline' );
3039 $line = $lines->next;
3040 is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
3041 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
3042 is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
3044 $line = $lines->next;
3045 is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
3046 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
3047 is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
3051 subtest 'ProcessOfflinePayment() tests' => sub {
3058 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
3059 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3060 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
3062 is( $result, 'Success.', 'The right string is returned' );
3064 my $lines = $patron->account->lines;
3065 is( $lines->count, 1, 'line created correctly');
3067 my $line = $lines->next;
3068 is( $line->amount+0, $amount * -1, 'amount picked from params' );
3069 is( $line->branchcode, $library->id, 'branchcode set correctly' );
3073 subtest 'Incremented fee tests' => sub {
3076 my $dt = dt_from_string();
3077 Time::Fake->offset( $dt->epoch );
3079 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
3082 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3084 my $module = new Test::MockModule('C4::Context');
3085 $module->mock( 'userenv', sub { { branch => $library->id } } );
3087 my $patron = $builder->build_object(
3089 class => 'Koha::Patrons',
3090 value => { categorycode => $patron_category->{categorycode} }
3094 my $itemtype = $builder->build_object(
3096 class => 'Koha::ItemTypes',
3098 notforloan => undef,
3100 rentalcharge_daily => 1.000000
3105 my $item = $builder->build_sample_item(
3107 library => $library->{branchcode},
3108 itype => $itemtype->id,
3112 is( $itemtype->rentalcharge_daily,
3113 '1.000000', 'Daily rental charge stored and retreived correctly' );
3114 is( $item->effective_itemtype, $itemtype->id,
3115 "Itemtype set correctly for item" );
3117 my $dt_from = dt_from_string();
3118 my $dt_to = dt_from_string()->add( days => 7 );
3119 my $dt_to_renew = dt_from_string()->add( days => 13 );
3122 t::lib::Mocks::mock_preference( 'finesCalendar', 'ignoreCalendar' );
3124 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3125 my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3126 is( $accountline->amount, '7.000000',
3127 "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar"
3129 $accountline->delete();
3130 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3131 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3132 is( $accountline->amount, '6.000000',
3133 "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal"
3135 $accountline->delete();
3138 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3140 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3141 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3142 is( $accountline->amount, '7.000000',
3143 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed"
3145 $accountline->delete();
3146 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3147 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3148 is( $accountline->amount, '6.000000',
3149 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal"
3151 $accountline->delete();
3154 my $calendar = C4::Calendar->new( branchcode => $library->id );
3155 $calendar->insert_week_day_holiday(
3157 title => 'Test holiday',
3158 description => 'Test holiday'
3161 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3162 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3163 is( $accountline->amount, '6.000000',
3164 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays"
3166 $accountline->delete();
3167 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3168 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3169 is( $accountline->amount, '5.000000',
3170 "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays, for renewal"
3172 $accountline->delete();
3175 $itemtype->rentalcharge('2.000000')->store;
3176 is( $itemtype->rentalcharge, '2.000000',
3177 'Rental charge updated and retreived correctly' );
3179 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3181 Koha::Account::Lines->search( { itemnumber => $item->id } );
3182 is( $accountlines->count, '2',
3183 "Fixed charge and accrued charge recorded distinctly" );
3184 $accountlines->delete();
3185 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3186 $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } );
3187 is( $accountlines->count, '2',
3188 "Fixed charge and accrued charge recorded distinctly, for renewal" );
3189 $accountlines->delete();
3191 $itemtype->rentalcharge('00.000000')->store;
3192 is( $itemtype->rentalcharge, '00.000000',
3193 'Rental charge reset and retreived correctly' );
3196 my $issuingrule = Koha::IssuingRules->get_effective_issuing_rule(
3198 categorycode => $patron->categorycode,
3199 itemtype => $itemtype->id,
3200 branchcode => $library->id
3203 $issuingrule->lengthunit('hours')->store();
3204 is( $issuingrule->lengthunit, 'hours',
3205 'Issuingrule updated and retrieved correctly' );
3207 $itemtype->rentalcharge_hourly('0.25')->store();
3208 is( $itemtype->rentalcharge_hourly,
3209 '0.25', 'Hourly rental charge stored and retreived correctly' );
3211 $dt_to = dt_from_string()->add( hours => 168 );
3212 $dt_to_renew = dt_from_string()->add( hours => 312 );
3214 t::lib::Mocks::mock_preference( 'finesCalendar', 'ignoreCalendar' );
3216 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3217 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3218 is( $accountline->amount + 0, 42,
3219 "Hourly rental charge calculated correctly with finesCalendar = ignoreCalendar (168h * 0.25u)" );
3220 $accountline->delete();
3221 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3222 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3223 is( $accountline->amount + 0, 36,
3224 "Hourly rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal (312h - 168h * 0.25u)" );
3225 $accountline->delete();
3228 t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' );
3230 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3231 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3232 is( $accountline->amount + 0, 36,
3233 "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays (168h - 24h * 0.25u)" );
3234 $accountline->delete();
3235 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3236 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3237 is( $accountline->amount + 0, 30,
3238 "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays, for renewal (312h - 168h - 24h * 0.25u" );
3239 $accountline->delete();
3242 $calendar->delete_holiday( weekday => 3 );
3244 AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3245 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3246 is( $accountline->amount + 0, 42,
3247 "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed (168h - 0h * 0.25u" );
3248 $accountline->delete();
3249 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3250 $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } );
3251 is( $accountline->amount + 0, 36,
3252 "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal (312h - 168h - 0h * 0.25u)" );
3253 $accountline->delete();
3255 $issuingrule->lengthunit('days')->store();
3259 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
3262 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
3263 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3266 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3267 my $patron = $builder->build_object(
3269 class => 'Koha::Patrons',
3270 value => { categorycode => $patron_category->{categorycode} }
3274 my $itemtype = $builder->build_object(
3276 class => 'Koha::ItemTypes',
3280 rentalcharge_daily => 0
3285 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3286 my $item = $builder->build_object(
3288 class => 'Koha::Items',
3290 homebranch => $library->id,
3291 holdingbranch => $library->id,
3295 itype => $itemtype->id,
3296 biblionumber => $biblioitem->{biblionumber},
3297 biblioitemnumber => $biblioitem->{biblioitemnumber},
3302 my ( $issuingimpossible, $needsconfirmation );
3303 my $dt_from = dt_from_string();
3304 my $dt_due = dt_from_string()->add( days => 3 );
3306 $itemtype->rentalcharge('1.000000')->store;
3307 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3308 is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' );
3309 $itemtype->rentalcharge('0')->store;
3310 $itemtype->rentalcharge_daily('1.000000')->store;
3311 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3312 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
3313 $itemtype->rentalcharge_daily('0')->store;
3316 subtest "Test Backdating of Returns" => sub {
3319 my $branch = $library2->{branchcode};
3320 my $biblio = $builder->build_sample_biblio();
3321 my $item = $builder->build_sample_item(
3323 biblionumber => $biblio->biblionumber,
3329 my %a_borrower_data = (
3330 firstname => 'Kyle',
3332 categorycode => $patron_category->{categorycode},
3333 branchcode => $branch,
3335 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
3336 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
3338 my $due_date = dt_from_string;
3339 my $issue = AddIssue( $borrower, $item->barcode, $due_date );
3342 issue_id => $issue->id(),
3343 itemnumber => $item->itemnumber,
3344 borrowernumber => $borrowernumber,
3346 amountoutstanding => .25,
3352 my ( undef, $message ) = AddReturn( $item->barcode, $branch, undef, $due_date );
3354 my $accountline = Koha::Account::Lines->find( { issue_id => $issue->id } );
3355 is( $accountline->amountoutstanding, '0.000000', 'Fee amount outstanding was reduced to 0' );
3356 is( $accountline->amount, '0.000000', 'Fee amount was reduced to 0' );
3359 $schema->storage->txn_rollback;
3360 C4::Context->clear_syspref_cache();
3361 $cache->clear_from_cache('single_holidays');