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 => 126;
26 use POSIX qw( floor );
28 use t::lib::TestBuilder;
37 use C4::Overdues qw(UpdateFine CalcFine);
40 use Koha::IssuingRules;
44 use Koha::CirculationRules;
45 use Koha::Subscriptions;
46 use Koha::Account::Lines;
47 use Koha::Account::Offsets;
50 my $schema = Koha::Database->schema;
51 $schema->storage->txn_begin;
52 my $builder = t::lib::TestBuilder->new;
53 my $dbh = C4::Context->dbh;
56 $dbh->{RaiseError} = 1;
58 my $cache = Koha::Caches->get_instance();
59 $dbh->do(q|DELETE FROM special_holidays|);
60 $dbh->do(q|DELETE FROM repeatable_holidays|);
61 $cache->clear_from_cache('single_holidays');
63 # Start with a clean slate
64 $dbh->do('DELETE FROM issues');
65 $dbh->do('DELETE FROM borrowers');
67 my $library = $builder->build({
70 my $library2 = $builder->build({
73 my $itemtype = $builder->build(
79 rentalcharge_daily => 0,
80 defaultreplacecost => undef,
85 my $patron_category = $builder->build(
91 BlockExpiredPatronOpacActions => -1, # Pick the pref value
96 my $CircControl = C4::Context->preference('CircControl');
97 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
100 homebranch => $library2->{branchcode},
101 holdingbranch => $library2->{branchcode}
105 branchcode => $library2->{branchcode}
108 # No userenv, PickupLibrary
109 t::lib::Mocks::mock_preference('IndependentBranches', '0');
110 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
112 C4::Context->preference('CircControl'),
114 'CircControl changed to PickupLibrary'
117 C4::Circulation::_GetCircControlBranch($item, $borrower),
118 $item->{$HomeOrHoldingBranch},
119 '_GetCircControlBranch returned item branch (no userenv defined)'
122 # No userenv, PatronLibrary
123 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
125 C4::Context->preference('CircControl'),
127 'CircControl changed to PatronLibrary'
130 C4::Circulation::_GetCircControlBranch($item, $borrower),
131 $borrower->{branchcode},
132 '_GetCircControlBranch returned borrower branch'
135 # No userenv, ItemHomeLibrary
136 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
138 C4::Context->preference('CircControl'),
140 'CircControl changed to ItemHomeLibrary'
143 $item->{$HomeOrHoldingBranch},
144 C4::Circulation::_GetCircControlBranch($item, $borrower),
145 '_GetCircControlBranch returned item branch'
149 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
150 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
152 # Userenv set, PickupLibrary
153 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
155 C4::Context->preference('CircControl'),
157 'CircControl changed to PickupLibrary'
160 C4::Circulation::_GetCircControlBranch($item, $borrower),
161 $library2->{branchcode},
162 '_GetCircControlBranch returned current branch'
165 # Userenv set, PatronLibrary
166 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
168 C4::Context->preference('CircControl'),
170 'CircControl changed to PatronLibrary'
173 C4::Circulation::_GetCircControlBranch($item, $borrower),
174 $borrower->{branchcode},
175 '_GetCircControlBranch returned borrower branch'
178 # Userenv set, ItemHomeLibrary
179 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
181 C4::Context->preference('CircControl'),
183 'CircControl changed to ItemHomeLibrary'
186 C4::Circulation::_GetCircControlBranch($item, $borrower),
187 $item->{$HomeOrHoldingBranch},
188 '_GetCircControlBranch returned item branch'
191 # Reset initial configuration
192 t::lib::Mocks::mock_preference('CircControl', $CircControl);
194 C4::Context->preference('CircControl'),
196 'CircControl reset to its initial value'
199 # Set a simple circ policy
200 $dbh->do('DELETE FROM issuingrules');
201 Koha::CirculationRules->search()->delete();
203 q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
204 issuelength, lengthunit,
205 renewalsallowed, renewalperiod,
206 norenewalbefore, auto_renew,
223 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
225 # CanBookBeRenewed tests
226 C4::Context->set_preference('ItemsDeniedRenewal','');
227 # Generate test biblio
228 my $biblio = $builder->build_sample_biblio();
230 my $branch = $library2->{branchcode};
232 my $item_1 = $builder->build_sample_item(
234 biblionumber => $biblio->biblionumber,
236 replacementprice => 12.00,
240 $reused_itemnumber_1 = $item_1->itemnumber;
242 my $item_2 = $builder->build_sample_item(
244 biblionumber => $biblio->biblionumber,
246 replacementprice => 23.00,
250 $reused_itemnumber_2 = $item_2->itemnumber;
252 my $item_3 = $builder->build_sample_item(
254 biblionumber => $biblio->biblionumber,
256 replacementprice => 23.00,
262 my %renewing_borrower_data = (
264 surname => 'Renewal',
265 categorycode => $patron_category->{categorycode},
266 branchcode => $branch,
269 my %reserving_borrower_data = (
270 firstname => 'Katrin',
271 surname => 'Reservation',
272 categorycode => $patron_category->{categorycode},
273 branchcode => $branch,
276 my %hold_waiting_borrower_data = (
278 surname => 'Reservation',
279 categorycode => $patron_category->{categorycode},
280 branchcode => $branch,
283 my %restricted_borrower_data = (
284 firstname => 'Alice',
285 surname => 'Reservation',
286 categorycode => $patron_category->{categorycode},
287 debarred => '3228-01-01',
288 branchcode => $branch,
291 my %expired_borrower_data = (
294 categorycode => $patron_category->{categorycode},
295 branchcode => $branch,
296 dateexpiry => dt_from_string->subtract( months => 1 ),
299 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
300 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
301 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
302 my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
303 my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
305 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
306 my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
307 my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
314 my $checkitem = undef;
317 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
318 my $datedue = dt_from_string( $issue->date_due() );
319 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
321 my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
322 $datedue = dt_from_string( $issue->date_due() );
323 is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
326 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
327 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
329 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
330 is( $renewokay, 1, 'Can renew, no holds for this title or item');
333 # Biblio-level hold, renewal test
335 $branch, $reserving_borrowernumber, $biblio->biblionumber,
336 $bibitems, $priority, $resdate, $expdate, $notes,
337 'a title', $checkitem, $found
340 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
341 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
342 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
343 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
344 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
345 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
346 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
348 # Now let's add an item level hold, we should no longer be able to renew the item
349 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
351 borrowernumber => $hold_waiting_borrowernumber,
352 biblionumber => $biblio->biblionumber,
353 itemnumber => $item_1->itemnumber,
354 branchcode => $branch,
358 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
359 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
362 # 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
363 # be able to renew these items
364 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
366 borrowernumber => $hold_waiting_borrowernumber,
367 biblionumber => $biblio->biblionumber,
368 itemnumber => $item_3->itemnumber,
369 branchcode => $branch,
374 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
375 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
376 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
377 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
378 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
380 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
381 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
382 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
384 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
385 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
386 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
388 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
389 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
390 AddIssue($reserving_borrower, $item_3->barcode);
391 my $reserve = $dbh->selectrow_hashref(
392 'SELECT * FROM old_reserves WHERE reserve_id = ?',
396 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
398 # Item-level hold, renewal test
400 $branch, $reserving_borrowernumber, $biblio->biblionumber,
401 $bibitems, $priority, $resdate, $expdate, $notes,
402 'a title', $item_1->itemnumber, $found
405 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
406 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
407 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
409 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
410 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
412 # Items can't fill hold for reasons
413 ModItem({ notforloan => 1 }, $biblio->biblionumber, $item_1->itemnumber);
414 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
415 is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
416 ModItem({ notforloan => 0, itype => $itemtype }, $biblio->biblionumber, $item_1->itemnumber);
418 # FIXME: Add more for itemtype not for loan etc.
420 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
421 my $item_5 = $builder->build_sample_item(
423 biblionumber => $biblio->biblionumber,
425 replacementprice => 23.00,
429 my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
430 is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
432 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
433 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
434 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
435 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
436 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
438 # Users cannot renew an overdue item
439 my $item_6 = $builder->build_sample_item(
441 biblionumber => $biblio->biblionumber,
443 replacementprice => 23.00,
448 my $item_7 = $builder->build_sample_item(
450 biblionumber => $biblio->biblionumber,
452 replacementprice => 23.00,
457 my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
458 is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
460 my $now = dt_from_string();
461 my $five_weeks = DateTime::Duration->new(weeks => 5);
462 my $five_weeks_ago = $now - $five_weeks;
463 t::lib::Mocks::mock_preference('finesMode', 'production');
465 my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
466 is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
468 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
469 C4::Overdues::UpdateFine(
471 issue_id => $passeddatedue1->id(),
472 itemnumber => $item_7->itemnumber,
473 borrowernumber => $renewing_borrower->{borrowernumber},
475 due => Koha::DateUtils::output_pref($five_weeks_ago)
479 t::lib::Mocks::mock_preference('RenewalLog', 0);
480 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
481 my %params_renewal = (
482 timestamp => { -like => $date . "%" },
483 module => "CIRCULATION",
487 timestamp => { -like => $date . "%" },
488 module => "CIRCULATION",
491 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
492 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
493 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
494 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
496 t::lib::Mocks::mock_preference('RenewalLog', 1);
497 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
498 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
499 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
500 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
501 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
503 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
504 is( $fines->count, 2 );
505 is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
506 is( $fines->next->accounttype, 'F', 'Fine on renewed item is closed out properly' );
510 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
511 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
512 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
513 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
514 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
515 $new_log_size = Koha::ActionLogs->count( \%params_issue );
516 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
518 $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
521 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
522 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
523 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
524 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
525 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
528 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
532 # Test automatic renewal before value for "norenewalbefore" in policy is set
533 # In this case automatic renewal is not permitted prior to due date
534 my $item_4 = $builder->build_sample_item(
536 biblionumber => $biblio->biblionumber,
538 replacementprice => 16.00,
543 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
544 ( $renewokay, $error ) =
545 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
546 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
547 is( $error, 'auto_too_soon',
548 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
551 # Test premature manual renewal
552 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
554 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
555 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
556 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
559 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
560 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
562 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
563 $datedue->clone->add( days => -7 ),
564 'Bug 14395: Renewals permitted 7 days before due date, as expected'
568 # Test 'date' setting for syspref NoRenewalBeforePrecision
569 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
571 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
572 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
573 'Bug 14395: Renewals permitted 7 days before due date, as expected'
577 # Test premature automatic renewal
578 ( $renewokay, $error ) =
579 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
580 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
581 is( $error, 'auto_too_soon',
582 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
585 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
586 # and test automatic renewal again
587 $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
588 ( $renewokay, $error ) =
589 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
590 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
591 is( $error, 'auto_too_soon',
592 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
595 # Change policy so that loans can be renewed 99 days prior to the due date
596 # and test automatic renewal again
597 $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
598 ( $renewokay, $error ) =
599 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
600 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
601 is( $error, 'auto_renew',
602 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
605 subtest "too_late_renewal / no_auto_renewal_after" => sub {
607 my $item_to_auto_renew = $builder->build(
610 biblionumber => $biblio->biblionumber,
611 homebranch => $branch,
612 holdingbranch => $branch,
617 my $ten_days_before = dt_from_string->add( days => -10 );
618 my $ten_days_ahead = dt_from_string->add( days => 10 );
619 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
621 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 9');
622 ( $renewokay, $error ) =
623 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
624 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
625 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
627 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 10');
628 ( $renewokay, $error ) =
629 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
630 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
631 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
633 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 11');
634 ( $renewokay, $error ) =
635 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
636 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
637 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
639 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
640 ( $renewokay, $error ) =
641 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
642 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
643 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
645 $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 ) );
646 ( $renewokay, $error ) =
647 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
648 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
649 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
651 $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 ) );
652 ( $renewokay, $error ) =
653 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
654 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
655 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
657 $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 ) );
658 ( $renewokay, $error ) =
659 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
660 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
661 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
664 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew" => sub {
666 my $item_to_auto_renew = $builder->build({
669 biblionumber => $biblio->biblionumber,
670 homebranch => $branch,
671 holdingbranch => $branch,
675 my $ten_days_before = dt_from_string->add( days => -10 );
676 my $ten_days_ahead = dt_from_string->add( days => 10 );
677 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
679 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
680 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
681 C4::Context->set_preference('OPACFineNoRenewals','10');
682 my $fines_amount = 5;
683 C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
684 ( $renewokay, $error ) =
685 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
686 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
687 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
689 C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
690 ( $renewokay, $error ) =
691 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
692 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
693 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
695 C4::Accounts::manualinvoice( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber}, "Some fines", 'F', $fines_amount );
696 ( $renewokay, $error ) =
697 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
698 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
699 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
701 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
704 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
706 my $item_to_auto_renew = $builder->build({
709 biblionumber => $biblio->biblionumber,
710 homebranch => $branch,
711 holdingbranch => $branch,
715 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
717 my $ten_days_before = dt_from_string->add( days => -10 );
718 my $ten_days_ahead = dt_from_string->add( days => 10 );
720 # Patron is expired and BlockExpiredPatronOpacActions=0
721 # => auto renew is allowed
722 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
723 my $patron = $expired_borrower;
724 my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
725 ( $renewokay, $error ) =
726 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
727 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
728 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
729 Koha::Checkouts->find( $checkout->issue_id )->delete;
732 # Patron is expired and BlockExpiredPatronOpacActions=1
733 # => auto renew is not allowed
734 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
735 $patron = $expired_borrower;
736 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
737 ( $renewokay, $error ) =
738 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
739 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
740 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
741 Koha::Checkouts->find( $checkout->issue_id )->delete;
744 # Patron is not expired and BlockExpiredPatronOpacActions=1
745 # => auto renew is allowed
746 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
747 $patron = $renewing_borrower;
748 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
749 ( $renewokay, $error ) =
750 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
751 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
752 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
753 Koha::Checkouts->find( $checkout->issue_id )->delete;
756 subtest "GetLatestAutoRenewDate" => sub {
758 my $item_to_auto_renew = $builder->build(
761 biblionumber => $biblio->biblionumber,
762 homebranch => $branch,
763 holdingbranch => $branch,
768 my $ten_days_before = dt_from_string->add( days => -10 );
769 my $ten_days_ahead = dt_from_string->add( days => 10 );
770 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
771 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = NULL');
772 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
773 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' );
774 my $five_days_before = dt_from_string->add( days => -5 );
775 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 5, no_auto_renewal_after_hard_limit = NULL');
776 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
777 is( $latest_auto_renew_date->truncate( to => 'minute' ),
778 $five_days_before->truncate( to => 'minute' ),
779 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
781 my $five_days_ahead = dt_from_string->add( days => 5 );
782 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = NULL');
783 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
784 is( $latest_auto_renew_date->truncate( to => 'minute' ),
785 $five_days_ahead->truncate( to => 'minute' ),
786 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
788 my $two_days_ahead = dt_from_string->add( days => 2 );
789 $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 ) );
790 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
791 is( $latest_auto_renew_date->truncate( to => 'day' ),
792 $two_days_ahead->truncate( to => 'day' ),
793 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
795 $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 ) );
796 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
797 is( $latest_auto_renew_date->truncate( to => 'day' ),
798 $two_days_ahead->truncate( to => 'day' ),
799 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
806 # set policy to forbid renewals
807 $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
809 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
810 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
811 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
813 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
814 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
815 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
817 C4::Overdues::UpdateFine(
819 issue_id => $issue->id(),
820 itemnumber => $item_1->itemnumber,
821 borrowernumber => $renewing_borrower->{borrowernumber},
824 due => Koha::DateUtils::output_pref($datedue)
828 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
829 is( $line->accounttype, 'FU', 'Account line type is FU' );
830 is( $line->lastincrement, '15.000000', 'Account line last increment is 15.00' );
831 is( $line->amountoutstanding, '15.000000', 'Account line amount outstanding is 15.00' );
832 is( $line->amount, '15.000000', 'Account line amount is 15.00' );
833 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
835 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
836 is( $offset->type, 'Fine', 'Account offset type is Fine' );
837 is( $offset->amount, '15.000000', 'Account offset amount is 15.00' );
839 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
840 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
842 LostItem( $item_1->itemnumber, 'test', 1 );
844 $line = Koha::Account::Lines->find($line->id);
845 is( $line->accounttype, 'F', 'Account type correctly changed from FU to F' );
847 my $item = Koha::Items->find($item_1->itemnumber);
848 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
849 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
850 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
852 my $total_due = $dbh->selectrow_array(
853 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
854 undef, $renewing_borrower->{borrowernumber}
857 is( $total_due, '15.000000', 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
859 C4::Context->dbh->do("DELETE FROM accountlines");
861 C4::Overdues::UpdateFine(
863 issue_id => $issue2->id(),
864 itemnumber => $item_2->itemnumber,
865 borrowernumber => $renewing_borrower->{borrowernumber},
868 due => Koha::DateUtils::output_pref($datedue)
872 LostItem( $item_2->itemnumber, 'test', 0 );
874 my $item2 = Koha::Items->find($item_2->itemnumber);
875 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
876 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
878 $total_due = $dbh->selectrow_array(
879 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
880 undef, $renewing_borrower->{borrowernumber}
883 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
885 my $future = dt_from_string();
886 $future->add( days => 7 );
887 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
888 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
890 # Users cannot renew any item if there is an overdue item
891 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
892 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
893 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
894 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
895 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
897 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
898 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
899 LostItem( $item_3->itemnumber, 'test', 0 );
900 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
901 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
905 # GetUpcomingDueIssues tests
906 my $branch = $library2->{branchcode};
908 #Create another record
909 my $biblio2 = $builder->build_sample_biblio();
912 my $item_1 = Koha::Items->find($reused_itemnumber_1);
913 my $item_2 = Koha::Items->find($reused_itemnumber_2);
914 my $item_3 = $builder->build_sample_item(
916 biblionumber => $biblio2->biblionumber,
924 my %a_borrower_data = (
925 firstname => 'Fridolyn',
927 categorycode => $patron_category->{categorycode},
928 branchcode => $branch,
931 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
932 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
934 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
935 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
936 my $today = DateTime->today(time_zone => C4::Context->tz());
938 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
939 my $datedue = dt_from_string( $issue->date_due() );
940 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
941 my $datedue2 = dt_from_string( $issue->date_due() );
945 # GetUpcomingDueIssues tests
947 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
948 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
951 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
952 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
953 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
956 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
957 is ( scalar( @$upcoming_dues ), 1,
958 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
961 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
963 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
965 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
966 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
968 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
969 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
971 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
972 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
974 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
975 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
977 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
978 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
980 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
981 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
986 my $branch = $library2->{branchcode};
988 my $biblio = $builder->build_sample_biblio();
991 my $item = $builder->build_sample_item(
993 biblionumber => $biblio->biblionumber,
1000 my %a_borrower_data = (
1001 firstname => 'Kyle',
1003 categorycode => $patron_category->{categorycode},
1004 branchcode => $branch,
1007 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1009 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1010 my $issue = AddIssue( $borrower, $item->barcode );
1013 issue_id => $issue->id(),
1014 itemnumber => $item->itemnumber,
1015 borrowernumber => $borrowernumber,
1021 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1022 my $count = $hr->{count};
1024 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1028 $dbh->do('DELETE FROM issues');
1029 $dbh->do('DELETE FROM items');
1030 $dbh->do('DELETE FROM issuingrules');
1031 Koha::CirculationRules->search()->delete();
1034 INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
1035 norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
1044 Koha::CirculationRules->set_rules(
1046 categorycode => '*',
1054 my $biblio = $builder->build_sample_biblio();
1056 my $item_1 = $builder->build_sample_item(
1058 biblionumber => $biblio->biblionumber,
1059 library => $library2->{branchcode},
1064 my $item_2= $builder->build_sample_item(
1066 biblionumber => $biblio->biblionumber,
1067 library => $library2->{branchcode},
1072 my $borrowernumber1 = Koha::Patron->new({
1073 firstname => 'Kyle',
1075 categorycode => $patron_category->{categorycode},
1076 branchcode => $library2->{branchcode},
1077 })->store->borrowernumber;
1078 my $borrowernumber2 = Koha::Patron->new({
1079 firstname => 'Chelsea',
1081 categorycode => $patron_category->{categorycode},
1082 branchcode => $library2->{branchcode},
1083 })->store->borrowernumber;
1085 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1086 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1088 my $issue = AddIssue( $borrower1, $item_1->barcode );
1090 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1091 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1094 $library2->{branchcode}, $borrowernumber2, $biblio->biblionumber,
1095 '', 1, undef, undef, '',
1099 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1100 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1101 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1102 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1104 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1105 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1106 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1107 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1109 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1110 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1111 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1112 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1114 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1115 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1116 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1117 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1119 # Setting item not checked out to be not for loan but holdable
1120 ModItem({ notforloan => -1 }, $biblio->biblionumber, $item_2->itemnumber);
1122 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1123 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' );
1127 # Don't allow renewing onsite checkout
1128 my $branch = $library->{branchcode};
1130 #Create another record
1131 my $biblio = $builder->build_sample_biblio();
1133 my $item = $builder->build_sample_item(
1135 biblionumber => $biblio->biblionumber,
1141 my $borrowernumber = Koha::Patron->new({
1144 categorycode => $patron_category->{categorycode},
1145 branchcode => $branch,
1146 })->store->borrowernumber;
1148 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1150 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1151 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1152 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1153 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1157 my $library = $builder->build({ source => 'Branch' });
1159 my $biblio = $builder->build_sample_biblio();
1161 my $item = $builder->build_sample_item(
1163 biblionumber => $biblio->biblionumber,
1164 library => $library->{branchcode},
1169 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1171 my $issue = AddIssue( $patron, $item->barcode );
1174 issue_id => $issue->id(),
1175 itemnumber => $item->itemnumber,
1176 borrowernumber => $patron->{borrowernumber},
1183 issue_id => $issue->id(),
1184 itemnumber => $item->itemnumber,
1185 borrowernumber => $patron->{borrowernumber},
1190 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1193 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1196 my $homebranch = $builder->build( { source => 'Branch' } );
1197 my $holdingbranch = $builder->build( { source => 'Branch' } );
1198 my $otherbranch = $builder->build( { source => 'Branch' } );
1199 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1200 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1202 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1203 my $item = $builder->build(
1206 homebranch => $homebranch->{branchcode},
1207 holdingbranch => $holdingbranch->{branchcode},
1208 biblionumber => $biblioitem->{biblionumber}
1213 set_userenv($holdingbranch);
1215 my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1216 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1218 my ( $error, $question, $alerts );
1220 # AllowReturnToBranch == anywhere
1221 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1222 ## Test that unknown barcodes don't generate internal server errors
1223 set_userenv($homebranch);
1224 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1225 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1226 ## Can be issued from homebranch
1227 set_userenv($homebranch);
1228 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1229 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1230 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1231 ## Can be issued from holdingbranch
1232 set_userenv($holdingbranch);
1233 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1234 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1235 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1236 ## Can be issued from another branch
1237 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1238 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1239 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1241 # AllowReturnToBranch == holdingbranch
1242 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1243 ## Cannot be issued from homebranch
1244 set_userenv($homebranch);
1245 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1246 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1247 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1248 is( $error->{branch_to_return}, $holdingbranch->{branchcode} );
1249 ## Can be issued from holdinbranch
1250 set_userenv($holdingbranch);
1251 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1252 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1253 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1254 ## Cannot be issued from another branch
1255 set_userenv($otherbranch);
1256 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1257 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1258 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1259 is( $error->{branch_to_return}, $holdingbranch->{branchcode} );
1261 # AllowReturnToBranch == homebranch
1262 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1263 ## Can be issued from holdinbranch
1264 set_userenv($homebranch);
1265 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1266 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1267 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1268 ## Cannot be issued from holdinbranch
1269 set_userenv($holdingbranch);
1270 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1271 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1272 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1273 is( $error->{branch_to_return}, $homebranch->{branchcode} );
1274 ## Cannot be issued from holdinbranch
1275 set_userenv($otherbranch);
1276 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1277 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1278 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1279 is( $error->{branch_to_return}, $homebranch->{branchcode} );
1281 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1284 subtest 'AddIssue & AllowReturnToBranch' => sub {
1287 my $homebranch = $builder->build( { source => 'Branch' } );
1288 my $holdingbranch = $builder->build( { source => 'Branch' } );
1289 my $otherbranch = $builder->build( { source => 'Branch' } );
1290 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1291 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1293 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1294 my $item = $builder->build(
1297 homebranch => $homebranch->{branchcode},
1298 holdingbranch => $holdingbranch->{branchcode},
1302 biblionumber => $biblioitem->{biblionumber}
1307 set_userenv($holdingbranch);
1309 my $ref_issue = 'Koha::Checkout';
1310 my $issue = AddIssue( $patron_1, $item->{barcode} );
1312 my ( $error, $question, $alerts );
1314 # AllowReturnToBranch == homebranch
1315 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1316 ## Can be issued from homebranch
1317 set_userenv($homebranch);
1318 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1319 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1320 ## Can be issued from holdinbranch
1321 set_userenv($holdingbranch);
1322 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1323 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1324 ## Can be issued from another branch
1325 set_userenv($otherbranch);
1326 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1327 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1329 # AllowReturnToBranch == holdinbranch
1330 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1331 ## Cannot be issued from homebranch
1332 set_userenv($homebranch);
1333 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1334 ## Can be issued from holdingbranch
1335 set_userenv($holdingbranch);
1336 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1337 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1338 ## Cannot be issued from another branch
1339 set_userenv($otherbranch);
1340 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1342 # AllowReturnToBranch == homebranch
1343 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1344 ## Can be issued from homebranch
1345 set_userenv($homebranch);
1346 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1347 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1348 ## Cannot be issued from holdinbranch
1349 set_userenv($holdingbranch);
1350 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1351 ## Cannot be issued from another branch
1352 set_userenv($otherbranch);
1353 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1354 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1357 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1360 my $library = $builder->build( { source => 'Branch' } );
1361 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1363 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1364 my $item_1 = $builder->build(
1367 homebranch => $library->{branchcode},
1368 holdingbranch => $library->{branchcode},
1369 biblionumber => $biblioitem_1->{biblionumber}
1373 my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1374 my $item_2 = $builder->build(
1377 homebranch => $library->{branchcode},
1378 holdingbranch => $library->{branchcode},
1379 biblionumber => $biblioitem_2->{biblionumber}
1384 my ( $error, $question, $alerts );
1386 # Patron cannot issue item_1, they have overdues
1387 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1388 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday ); # Add an overdue
1390 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1391 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1392 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
1393 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1395 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1396 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1397 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1398 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1400 # Patron cannot issue item_1, they are debarred
1401 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1402 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1403 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1404 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1405 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1407 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1408 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1409 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1410 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1413 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1416 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1417 my $patron_category_x = $builder->build_object(
1419 class => 'Koha::Patron::Categories',
1420 value => { category_type => 'X' }
1423 my $patron = $builder->build_object(
1425 class => 'Koha::Patrons',
1427 categorycode => $patron_category_x->categorycode,
1428 gonenoaddress => undef,
1435 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1436 my $item_1 = $builder->build(
1440 homebranch => $library->branchcode,
1441 holdingbranch => $library->branchcode,
1442 biblionumber => $biblioitem_1->{biblionumber}
1447 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1448 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1450 # TODO There are other tests to provide here
1453 subtest 'MultipleReserves' => sub {
1456 my $biblio = $builder->build_sample_biblio();
1458 my $branch = $library2->{branchcode};
1460 my $item_1 = $builder->build_sample_item(
1462 biblionumber => $biblio->biblionumber,
1464 replacementprice => 12.00,
1469 my $item_2 = $builder->build_sample_item(
1471 biblionumber => $biblio->biblionumber,
1473 replacementprice => 12.00,
1480 my $resdate = undef;
1481 my $expdate = undef;
1483 my $checkitem = undef;
1486 my %renewing_borrower_data = (
1487 firstname => 'John',
1488 surname => 'Renewal',
1489 categorycode => $patron_category->{categorycode},
1490 branchcode => $branch,
1492 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1493 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1494 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1495 my $datedue = dt_from_string( $issue->date_due() );
1496 is (defined $issue->date_due(), 1, "item 1 checked out");
1497 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1499 my %reserving_borrower_data1 = (
1500 firstname => 'Katrin',
1501 surname => 'Reservation',
1502 categorycode => $patron_category->{categorycode},
1503 branchcode => $branch,
1505 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1507 $branch, $reserving_borrowernumber1, $biblio->biblionumber,
1508 $bibitems, $priority, $resdate, $expdate, $notes,
1509 'a title', $checkitem, $found
1512 my %reserving_borrower_data2 = (
1513 firstname => 'Kirk',
1514 surname => 'Reservation',
1515 categorycode => $patron_category->{categorycode},
1516 branchcode => $branch,
1518 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1520 $branch, $reserving_borrowernumber2, $biblio->biblionumber,
1521 $bibitems, $priority, $resdate, $expdate, $notes,
1522 'a title', $checkitem, $found
1526 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1527 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1530 my $item_3 = $builder->build_sample_item(
1532 biblionumber => $biblio->biblionumber,
1534 replacementprice => 12.00,
1540 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1541 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1545 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1548 my $library = $builder->build( { source => 'Branch' } );
1549 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1551 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1552 my $biblionumber = $biblioitem->{biblionumber};
1553 my $item_1 = $builder->build(
1556 homebranch => $library->{branchcode},
1557 holdingbranch => $library->{branchcode},
1558 biblionumber => $biblionumber,
1562 my $item_2 = $builder->build(
1565 homebranch => $library->{branchcode},
1566 holdingbranch => $library->{branchcode},
1567 biblionumber => $biblionumber,
1572 my ( $error, $question, $alerts );
1573 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1575 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1576 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1577 is( keys(%$error) + keys(%$alerts), 0, 'No error or alert should be raised' . str($error, $question, $alerts) );
1578 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) );
1580 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1581 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1582 is( keys(%$error) + keys(%$question) + keys(%$alerts), 0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' . str($error, $question, $alerts) );
1584 # Add a subscription
1585 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1587 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1588 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1589 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) );
1591 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1592 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1593 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) );
1596 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1599 my $library = $builder->build( { source => 'Branch' } );
1600 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1603 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1604 my $item_1 = $builder->build(
1608 homebranch => $library->{branchcode},
1609 holdingbranch => $library->{branchcode},
1613 biblionumber => $biblioitem_1->{biblionumber}
1617 my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1618 my $item_2 = $builder->build(
1622 homebranch => $library->{branchcode},
1623 holdingbranch => $library->{branchcode},
1627 biblionumber => $biblioitem_2->{biblionumber}
1632 # And the issuing rule
1633 Koha::IssuingRules->search->delete;
1634 my $rule = Koha::IssuingRule->new(
1636 categorycode => '*',
1640 firstremind => 1, # 1 day of grace
1641 finedays => 2, # 2 days of fine per day of overdue
1642 lengthunit => 'days',
1647 # Patron cannot issue item_1, they have overdues
1648 my $five_days_ago = dt_from_string->subtract( days => 5 );
1649 my $ten_days_ago = dt_from_string->subtract( days => 10 );
1650 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
1651 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1652 ; # Add another overdue
1654 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1655 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
1656 my $debarments = Koha::Patron::Debarments::GetDebarments(
1657 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1658 is( scalar(@$debarments), 1 );
1660 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1661 # Same for the others
1662 my $expected_expiration = output_pref(
1664 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1665 dateformat => 'sql',
1669 is( $debarments->[0]->{expiration}, $expected_expiration );
1671 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
1672 $debarments = Koha::Patron::Debarments::GetDebarments(
1673 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1674 is( scalar(@$debarments), 1 );
1675 $expected_expiration = output_pref(
1677 dt => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1678 dateformat => 'sql',
1682 is( $debarments->[0]->{expiration}, $expected_expiration );
1684 Koha::Patron::Debarments::DelUniqueDebarment(
1685 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1687 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1688 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
1689 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1690 ; # Add another overdue
1691 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
1692 $debarments = Koha::Patron::Debarments::GetDebarments(
1693 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1694 is( scalar(@$debarments), 1 );
1695 $expected_expiration = output_pref(
1697 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1698 dateformat => 'sql',
1702 is( $debarments->[0]->{expiration}, $expected_expiration );
1704 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
1705 $debarments = Koha::Patron::Debarments::GetDebarments(
1706 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1707 is( scalar(@$debarments), 1 );
1708 $expected_expiration = output_pref(
1710 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1711 dateformat => 'sql',
1715 is( $debarments->[0]->{expiration}, $expected_expiration );
1718 subtest 'AddReturn + suspension_chargeperiod' => sub {
1721 my $library = $builder->build( { source => 'Branch' } );
1722 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1725 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1726 my $item_1 = $builder->build(
1730 homebranch => $library->{branchcode},
1731 holdingbranch => $library->{branchcode},
1735 biblionumber => $biblioitem_1->{biblionumber}
1740 # And the issuing rule
1741 Koha::IssuingRules->search->delete;
1742 my $rule = Koha::IssuingRule->new(
1744 categorycode => '*',
1748 firstremind => 0, # 0 day of grace
1749 finedays => 2, # 2 days of fine per day of overdue
1750 suspension_chargeperiod => 1,
1751 lengthunit => 'days',
1756 my $five_days_ago = dt_from_string->subtract( days => 5 );
1757 # We want to charge 2 days every day, without grace
1758 # With 5 days of overdue: 5 * Z
1759 my $expected_expiration = dt_from_string->add( days => ( 5 * 2 ) / 1 );
1760 test_debarment_on_checkout(
1763 library => $library,
1765 due_date => $five_days_ago,
1766 expiration_date => $expected_expiration,
1770 # We want to charge 2 days every 2 days, without grace
1771 # With 5 days of overdue: (5 * 2) / 2
1772 $rule->suspension_chargeperiod(2)->store;
1773 $expected_expiration = dt_from_string->add( days => floor( 5 * 2 ) / 2 );
1774 test_debarment_on_checkout(
1777 library => $library,
1779 due_date => $five_days_ago,
1780 expiration_date => $expected_expiration,
1784 # We want to charge 2 days every 3 days, with 1 day of grace
1785 # With 5 days of overdue: ((5-1) / 3 ) * 2
1786 $rule->suspension_chargeperiod(3)->store;
1787 $rule->firstremind(1)->store;
1788 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
1789 test_debarment_on_checkout(
1792 library => $library,
1794 due_date => $five_days_ago,
1795 expiration_date => $expected_expiration,
1799 # Use finesCalendar to know if holiday must be skipped to calculate the due date
1800 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
1801 $rule->finedays(2)->store;
1802 $rule->suspension_chargeperiod(1)->store;
1803 $rule->firstremind(0)->store;
1804 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
1806 # Adding a holiday 2 days ago
1807 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
1808 my $two_days_ago = dt_from_string->subtract( days => 2 );
1809 $calendar->insert_single_holiday(
1810 day => $two_days_ago->day,
1811 month => $two_days_ago->month,
1812 year => $two_days_ago->year,
1813 title => 'holidayTest-2d',
1814 description => 'holidayDesc 2 days ago'
1816 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
1817 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
1818 test_debarment_on_checkout(
1821 library => $library,
1823 due_date => $five_days_ago,
1824 expiration_date => $expected_expiration,
1828 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
1829 my $two_days_ahead = dt_from_string->add( days => 2 );
1830 $calendar->insert_single_holiday(
1831 day => $two_days_ahead->day,
1832 month => $two_days_ahead->month,
1833 year => $two_days_ahead->year,
1834 title => 'holidayTest+2d',
1835 description => 'holidayDesc 2 days ahead'
1838 # Same as above, but we should skip D+2
1839 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
1840 test_debarment_on_checkout(
1843 library => $library,
1845 due_date => $five_days_ago,
1846 expiration_date => $expected_expiration,
1850 # Adding another holiday, day of expiration date
1851 my $expected_expiration_dt = dt_from_string($expected_expiration);
1852 $calendar->insert_single_holiday(
1853 day => $expected_expiration_dt->day,
1854 month => $expected_expiration_dt->month,
1855 year => $expected_expiration_dt->year,
1856 title => 'holidayTest_exp',
1857 description => 'holidayDesc on expiration date'
1859 # Expiration date will be the day after
1860 test_debarment_on_checkout(
1863 library => $library,
1865 due_date => $five_days_ago,
1866 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
1870 test_debarment_on_checkout(
1873 library => $library,
1875 return_date => dt_from_string->add(days => 5),
1876 expiration_date => dt_from_string->add(days => 5 + (5 * 2 - 1) ),
1881 subtest 'AddReturn | is_overdue' => sub {
1884 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
1885 t::lib::Mocks::mock_preference('finesMode', 'production');
1886 t::lib::Mocks::mock_preference('MaxFine', '100');
1888 my $library = $builder->build( { source => 'Branch' } );
1889 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1891 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1892 my $item = $builder->build(
1896 homebranch => $library->{branchcode},
1897 holdingbranch => $library->{branchcode},
1901 biblionumber => $biblioitem->{biblionumber},
1906 Koha::IssuingRules->search->delete;
1907 my $rule = Koha::IssuingRule->new(
1909 categorycode => '*',
1913 lengthunit => 'days',
1914 fine => 1, # Charge 1 every day of overdue
1920 my $one_day_ago = dt_from_string->subtract( days => 1 );
1921 my $five_days_ago = dt_from_string->subtract( days => 5 );
1922 my $ten_days_ago = dt_from_string->subtract( days => 10 );
1923 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1925 # No date specify, today will be used
1926 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1927 AddReturn( $item->{barcode}, $library->{branchcode} );
1928 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
1929 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1931 # specify return date 5 days before => no overdue
1932 AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1933 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
1934 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1935 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1937 # specify return date 5 days later => overdue
1938 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1939 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
1940 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
1941 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1943 # specify dropbox date 5 days before => no overdue
1944 AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
1945 AddReturn( $item->{barcode}, $library->{branchcode}, $ten_days_ago );
1946 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
1947 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1949 # specify dropbox date 5 days later => overdue, or... not
1950 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
1951 AddReturn( $item->{barcode}, $library->{branchcode}, $five_days_ago );
1952 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue in dropbox mode' ); # FIXME? This is weird, the FU fine is created ( _CalculateAndUpdateFine > C4::Overdues::UpdateFine ) then remove later (in _FixOverduesOnReturn). Looks like it is a feature
1953 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
1956 subtest '_FixAccountForLostAndReturned' => sub {
1960 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
1961 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
1963 my $processfee_amount = 20;
1964 my $replacement_amount = 99.00;
1965 my $item_type = $builder->build_object(
1966 { class => 'Koha::ItemTypes',
1968 notforloan => undef,
1970 defaultreplacecost => undef,
1971 processfee => $processfee_amount,
1972 rentalcharge_daily => 0,
1976 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1978 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
1980 subtest 'Full write-off tests' => sub {
1984 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1986 my $item = $builder->build_sample_item(
1988 biblionumber => $biblio->biblionumber,
1989 library => $library->branchcode,
1990 replacementprice => $replacement_amount,
1991 itype => $item_type->itemtype,
1995 AddIssue( $patron->unblessed, $item->barcode );
1997 # Simulate item marked as lost
1998 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
1999 LostItem( $item->itemnumber, 1 );
2001 my $processing_fee_lines = Koha::Account::Lines->search(
2002 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2003 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2004 my $processing_fee_line = $processing_fee_lines->next;
2005 is( $processing_fee_line->amount + 0,
2006 $processfee_amount, 'The right PF amount is generated' );
2007 is( $processing_fee_line->amountoutstanding + 0,
2008 $processfee_amount, 'The right PF amountoutstanding is generated' );
2010 my $lost_fee_lines = Koha::Account::Lines->search(
2011 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2012 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2013 my $lost_fee_line = $lost_fee_lines->next;
2014 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2015 is( $lost_fee_line->amountoutstanding + 0,
2016 $replacement_amount, 'The right L amountoutstanding is generated' );
2018 my $account = $patron->account;
2019 my $debts = $account->outstanding_debits;
2021 # Write off the debt
2022 my $credit = $account->add_credit(
2023 { amount => $account->balance,
2027 $credit->apply( { debits => $debts, offset_type => 'Writeoff' } );
2029 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2030 is( $credit_return_id, undef, 'No CR account line added' );
2032 $lost_fee_line->discard_changes; # reload from DB
2033 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2034 is( $lost_fee_line->accounttype,
2035 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2037 is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2040 subtest 'Full payment tests' => sub {
2044 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2046 my $item = $builder->build_sample_item(
2048 biblionumber => $biblio->biblionumber,
2049 library => $library->branchcode,
2050 replacementprice => $replacement_amount,
2051 itype => $item_type->itemtype
2055 AddIssue( $patron->unblessed, $item->barcode );
2057 # Simulate item marked as lost
2058 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2059 LostItem( $item->itemnumber, 1 );
2061 my $processing_fee_lines = Koha::Account::Lines->search(
2062 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2063 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2064 my $processing_fee_line = $processing_fee_lines->next;
2065 is( $processing_fee_line->amount + 0,
2066 $processfee_amount, 'The right PF amount is generated' );
2067 is( $processing_fee_line->amountoutstanding + 0,
2068 $processfee_amount, 'The right PF amountoutstanding is generated' );
2070 my $lost_fee_lines = Koha::Account::Lines->search(
2071 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2072 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2073 my $lost_fee_line = $lost_fee_lines->next;
2074 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2075 is( $lost_fee_line->amountoutstanding + 0,
2076 $replacement_amount, 'The right L amountountstanding is generated' );
2078 my $account = $patron->account;
2079 my $debts = $account->outstanding_debits;
2081 # Write off the debt
2082 my $credit = $account->add_credit(
2083 { amount => $account->balance,
2087 $credit->apply( { debits => $debts, offset_type => 'Payment' } );
2089 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2090 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2092 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2093 is( $credit_return->amount + 0,
2094 -99.00, 'The account line of type CR has an amount of -99' );
2095 is( $credit_return->amountoutstanding + 0,
2096 -99.00, 'The account line of type CR has an amountoutstanding of -99' );
2098 $lost_fee_line->discard_changes;
2099 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2100 is( $lost_fee_line->accounttype,
2101 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2103 is( $patron->account->balance,
2104 -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2107 subtest 'Test without payment or write off' => sub {
2111 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2113 my $item = $builder->build_sample_item(
2115 biblionumber => $biblio->biblionumber,
2116 library => $library->branchcode,
2117 replacementprice => 23.00,
2118 replacementprice => $replacement_amount,
2119 itype => $item_type->itemtype
2123 AddIssue( $patron->unblessed, $item->barcode );
2125 # Simulate item marked as lost
2126 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2127 LostItem( $item->itemnumber, 1 );
2129 my $processing_fee_lines = Koha::Account::Lines->search(
2130 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2131 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2132 my $processing_fee_line = $processing_fee_lines->next;
2133 is( $processing_fee_line->amount + 0,
2134 $processfee_amount, 'The right PF amount is generated' );
2135 is( $processing_fee_line->amountoutstanding + 0,
2136 $processfee_amount, 'The right PF amountoutstanding is generated' );
2138 my $lost_fee_lines = Koha::Account::Lines->search(
2139 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2140 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2141 my $lost_fee_line = $lost_fee_lines->next;
2142 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2143 is( $lost_fee_line->amountoutstanding + 0,
2144 $replacement_amount, 'The right L amountountstanding is generated' );
2146 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2147 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2149 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2150 is( $credit_return->amount + 0, -99.00, 'The account line of type CR has an amount of -99' );
2151 is( $credit_return->amountoutstanding + 0, 0, 'The account line of type CR has an amountoutstanding of 0' );
2153 $lost_fee_line->discard_changes;
2154 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2155 is( $lost_fee_line->accounttype, 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2157 is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2160 subtest 'Test with partial payement and write off, and remaining debt' => sub {
2164 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2165 my $item = $builder->build_sample_item(
2167 biblionumber => $biblio->biblionumber,
2168 library => $library->branchcode,
2169 replacementprice => $replacement_amount,
2170 itype => $item_type->itemtype
2174 AddIssue( $patron->unblessed, $item->barcode );
2176 # Simulate item marked as lost
2177 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2178 LostItem( $item->itemnumber, 1 );
2180 my $processing_fee_lines = Koha::Account::Lines->search(
2181 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2182 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2183 my $processing_fee_line = $processing_fee_lines->next;
2184 is( $processing_fee_line->amount + 0,
2185 $processfee_amount, 'The right PF amount is generated' );
2186 is( $processing_fee_line->amountoutstanding + 0,
2187 $processfee_amount, 'The right PF amountoutstanding is generated' );
2189 my $lost_fee_lines = Koha::Account::Lines->search(
2190 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2191 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2192 my $lost_fee_line = $lost_fee_lines->next;
2193 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2194 is( $lost_fee_line->amountoutstanding + 0,
2195 $replacement_amount, 'The right L amountountstanding is generated' );
2197 my $account = $patron->account;
2198 is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PF + L' );
2201 my $payment_amount = 27;
2202 my $payment = $account->add_credit(
2203 { amount => $payment_amount,
2208 $payment->apply( { debits => $lost_fee_lines->reset, offset_type => 'Payment' } );
2210 # Partially write off fee
2211 my $write_off_amount = 25;
2212 my $write_off = $account->add_credit(
2213 { amount => $write_off_amount,
2217 $write_off->apply( { debits => $lost_fee_lines->reset, offset_type => 'Writeoff' } );
2219 is( $account->balance,
2220 $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2221 'Payment and write off applied'
2224 # Store the amountoutstanding value
2225 $lost_fee_line->discard_changes;
2226 my $outstanding = $lost_fee_line->amountoutstanding;
2228 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2229 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2231 is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2233 $lost_fee_line->discard_changes;
2234 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2235 is( $lost_fee_line->accounttype,
2236 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2238 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2239 is( $credit_return->amount + 0,
2240 ($payment_amount + $outstanding ) * -1,
2241 'The account line of type CR has an amount equal to the payment + outstanding'
2243 is( $credit_return->amountoutstanding + 0,
2244 $payment_amount * -1,
2245 'The account line of type CR has an amountoutstanding equal to the payment'
2248 is( $account->balance,
2249 $processfee_amount - $payment_amount,
2250 'The patron balance is the difference between the PF and the credit'
2254 subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2258 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2259 my $barcode = 'KD123456793';
2260 my $replacement_amount = 100;
2261 my $processfee_amount = 20;
2263 my $item_type = $builder->build_object(
2264 { class => 'Koha::ItemTypes',
2266 notforloan => undef,
2268 defaultreplacecost => undef,
2270 rentalcharge_daily => 0,
2274 my ( undef, undef, $item_id ) = AddItem(
2275 { homebranch => $library->branchcode,
2276 holdingbranch => $library->branchcode,
2277 barcode => $barcode,
2278 replacementprice => $replacement_amount,
2279 itype => $item_type->itemtype
2281 $biblio->biblionumber
2284 AddIssue( $patron->unblessed, $barcode );
2286 # Simulate item marked as lost
2287 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item_id );
2288 LostItem( $item_id, 1 );
2290 my $lost_fee_lines = Koha::Account::Lines->search(
2291 { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2292 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2293 my $lost_fee_line = $lost_fee_lines->next;
2294 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2295 is( $lost_fee_line->amountoutstanding + 0,
2296 $replacement_amount, 'The right L amountountstanding is generated' );
2298 my $account = $patron->account;
2299 is( $account->balance, $replacement_amount, 'Balance is L' );
2302 my $payment_amount = 27;
2303 my $payment = $account->add_credit(
2304 { amount => $payment_amount,
2308 $payment->apply({ debits => $lost_fee_lines->reset, offset_type => 'Payment' });
2310 is( $account->balance,
2311 $replacement_amount - $payment_amount,
2315 # TODO use add_debit when time comes
2316 my $manual_debit_amount = 80;
2317 C4::Accounts::manualinvoice( $patron->id, undef, undef, 'FU', $manual_debit_amount );
2319 is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
2321 t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
2323 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2324 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2326 is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2328 my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, accounttype => 'FU' })->next;
2329 is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
2333 subtest '_FixOverduesOnReturn' => sub {
2336 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2338 my $branchcode = $library2->{branchcode};
2340 my $item = $builder->build_sample_item(
2342 biblionumber => $biblio->biblionumber,
2343 library => $branchcode,
2344 replacementprice => 99.00,
2349 my $patron = $builder->build( { source => 'Borrower' } );
2351 ## Start with basic call, should just close out the open fine
2352 my $accountline = Koha::Account::Line->new(
2354 borrowernumber => $patron->{borrowernumber},
2355 accounttype => 'FU',
2356 itemnumber => $item->itemnumber,
2358 amountoutstanding => 99.00,
2359 lastincrement => 9.00,
2363 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber );
2365 $accountline->_result()->discard_changes();
2367 is( $accountline->amountoutstanding, '99.000000', 'Fine has the same amount outstanding as previously' );
2368 is( $accountline->accounttype, 'F', 'Open fine ( account type FU ) has been closed out ( account type F )');
2371 ## Run again, with exemptfine enabled
2374 accounttype => 'FU',
2375 amountoutstanding => 99.00,
2379 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1 );
2381 $accountline->_result()->discard_changes();
2382 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2384 is( $accountline->amountoutstanding + 0, 0, 'Fine has been reduced to 0' );
2385 is( $accountline->accounttype, 'FFOR', 'Open fine ( account type FU ) has been set to fine forgiven ( account type FFOR )');
2386 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2387 is( $offset->amount, '-99.000000', "Amount of offset is correct" );
2390 subtest 'Set waiting flag' => sub {
2393 my $library_1 = $builder->build( { source => 'Branch' } );
2394 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2395 my $library_2 = $builder->build( { source => 'Branch' } );
2396 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2398 my $biblio = $builder->build( { source => 'Biblio' } );
2399 my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2401 my $item = $builder->build(
2405 homebranch => $library_1->{branchcode},
2406 holdingbranch => $library_1->{branchcode},
2410 biblionumber => $biblioitem->{biblionumber},
2415 set_userenv( $library_2 );
2416 my $reserve_id = AddReserve(
2417 $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber},
2418 '', 1, undef, undef, '', undef, $item->{itemnumber},
2421 set_userenv( $library_1 );
2422 my $do_transfer = 1;
2423 my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2424 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2425 my $hold = Koha::Holds->find( $reserve_id );
2426 is( $hold->found, 'T', 'Hold is in transit' );
2428 my ( $status ) = CheckReserves($item->{itemnumber});
2429 is( $status, 'Reserved', 'Hold is not waiting yet');
2431 set_userenv( $library_2 );
2433 AddReturn( $item->{barcode}, $library_2->{branchcode} );
2434 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2435 $hold = Koha::Holds->find( $reserve_id );
2436 is( $hold->found, 'W', 'Hold is waiting' );
2437 ( $status ) = CheckReserves($item->{itemnumber});
2438 is( $status, 'Waiting', 'Now the hold is waiting');
2441 subtest 'Cancel transfers on lost items' => sub {
2443 my $library_1 = $builder->build( { source => 'Branch' } );
2444 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2445 my $library_2 = $builder->build( { source => 'Branch' } );
2446 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2447 my $biblio = $builder->build( { source => 'Biblio' } );
2448 my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2449 my $item = $builder->build(
2453 homebranch => $library_1->{branchcode},
2454 holdingbranch => $library_1->{branchcode},
2458 biblionumber => $biblioitem->{biblionumber},
2463 set_userenv( $library_2 );
2464 my $reserve_id = AddReserve(
2465 $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber}, '', 1, undef, undef, '', undef, $item->{itemnumber},
2468 #Return book and add transfer
2469 set_userenv( $library_1 );
2470 my $do_transfer = 1;
2471 my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2472 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2473 C4::Circulation::transferbook( $library_2->{branchcode}, $item->{barcode} );
2474 my $hold = Koha::Holds->find( $reserve_id );
2475 is( $hold->found, 'T', 'Hold is in transit' );
2477 #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
2478 my ($datesent,$frombranch,$tobranch) = GetTransfers($item->{itemnumber});
2479 is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
2480 my $itemcheck = Koha::Items->find($item->{itemnumber});
2481 is( $itemcheck->holdingbranch, $library_2->{branchcode}, 'Items holding branch is the transfers destination branch before it is marked as lost' );
2483 #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
2484 ModItem( { itemlost => 1 }, $biblio->{biblionumber}, $item->{itemnumber} );
2485 LostItem( $item->{itemnumber}, 'test', 1 );
2486 ($datesent,$frombranch,$tobranch) = GetTransfers($item->{itemnumber});
2487 is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
2488 $itemcheck = Koha::Items->find($item->{itemnumber});
2489 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
2492 subtest 'CanBookBeIssued | is_overdue' => sub {
2495 # Set a simple circ policy
2496 $dbh->do('DELETE FROM issuingrules');
2498 q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
2499 issuelength, lengthunit,
2500 renewalsallowed, renewalperiod,
2501 norenewalbefore, auto_renew,
2518 my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
2519 my $ten_days_go = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
2520 my $library = $builder->build( { source => 'Branch' } );
2521 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2523 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2524 my $item = $builder->build(
2528 homebranch => $library->{branchcode},
2529 holdingbranch => $library->{branchcode},
2533 biblionumber => $biblioitem->{biblionumber},
2538 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
2539 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
2540 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
2541 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
2542 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
2543 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
2546 subtest 'ItemsDeniedRenewal preference' => sub {
2549 C4::Context->set_preference('ItemsDeniedRenewal','');
2551 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
2554 INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
2555 norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
2558 '*', $idr_lib->branchcode, '*', 25,
2565 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
2566 homebranch => $idr_lib->branchcode,
2570 itemcallnumber => undef,
2574 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
2575 homebranch => $idr_lib->branchcode,
2578 location => 'NOPROC'
2582 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
2583 branchcode => $idr_lib->branchcode,
2586 my $future = dt_from_string->add( days => 1 );
2587 my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2588 returndate => undef,
2591 borrowernumber => $idr_borrower->borrowernumber,
2592 itemnumber => $deny_book->itemnumber,
2593 onsite_checkout => 0,
2594 date_due => $future,
2597 my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2598 returndate => undef,
2601 borrowernumber => $idr_borrower->borrowernumber,
2602 itemnumber => $allow_book->itemnumber,
2603 onsite_checkout => 0,
2604 date_due => $future,
2610 my ( $idr_mayrenew, $idr_error ) =
2611 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2612 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
2613 is( $idr_error, undef, 'Renewal allowed when no rules' );
2615 $idr_rules="withdrawn: [1]";
2617 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2618 ( $idr_mayrenew, $idr_error ) =
2619 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2620 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
2621 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
2622 ( $idr_mayrenew, $idr_error ) =
2623 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2624 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2625 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2627 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
2629 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2630 ( $idr_mayrenew, $idr_error ) =
2631 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2632 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
2633 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
2634 ( $idr_mayrenew, $idr_error ) =
2635 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2636 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2637 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2639 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
2641 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2642 ( $idr_mayrenew, $idr_error ) =
2643 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2644 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
2645 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
2646 ( $idr_mayrenew, $idr_error ) =
2647 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2648 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2649 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2651 $idr_rules="itemcallnumber: [NULL]";
2652 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2653 ( $idr_mayrenew, $idr_error ) =
2654 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2655 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
2656 $idr_rules="itemcallnumber: ['']";
2657 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2658 ( $idr_mayrenew, $idr_error ) =
2659 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2660 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
2662 $idr_rules="itemnotes: [NULL]";
2663 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2664 ( $idr_mayrenew, $idr_error ) =
2665 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2666 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
2667 $idr_rules="itemnotes: ['']";
2668 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2669 ( $idr_mayrenew, $idr_error ) =
2670 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2671 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
2674 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
2677 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2678 my $library = $builder->build( { source => 'Branch' } );
2679 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2681 my $itemtype = $builder->build(
2683 source => 'Itemtype',
2684 value => { notforloan => undef, }
2688 my $biblioitem = $builder->build( { source => 'Biblioitem', value => { itemtype => $itemtype->{itemtype} } } );
2689 my $item = $builder->build_object(
2691 class => 'Koha::Items',
2693 homebranch => $library->{branchcode},
2694 holdingbranch => $library->{branchcode},
2698 biblionumber => $biblioitem->{biblionumber},
2699 biblioitemnumber => $biblioitem->{biblioitemnumber},
2704 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2705 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2706 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2709 subtest 'CanBookBeIssued | notforloan' => sub {
2712 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
2714 my $library = $builder->build( { source => 'Branch' } );
2715 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2717 my $itemtype = $builder->build(
2719 source => 'Itemtype',
2720 value => { notforloan => undef, }
2724 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2725 my $item = $builder->build_object(
2727 class => 'Koha::Items',
2729 homebranch => $library->{branchcode},
2730 holdingbranch => $library->{branchcode},
2734 itype => $itemtype->{itemtype},
2735 biblionumber => $biblioitem->{biblionumber},
2736 biblioitemnumber => $biblioitem->{biblioitemnumber},
2741 my ( $issuingimpossible, $needsconfirmation );
2744 subtest 'item-level_itypes = 1' => sub {
2747 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
2748 # Is for loan at item type and item level
2749 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2750 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2751 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2753 # not for loan at item type level
2754 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2755 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2756 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2759 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2760 'Item can not be issued, not for loan at item type level'
2763 # not for loan at item level
2764 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2765 $item->notforloan( 1 )->store;
2766 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2767 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2770 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2771 'Item can not be issued, not for loan at item type level'
2775 subtest 'item-level_itypes = 0' => sub {
2778 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2780 # We set another itemtype for biblioitem
2781 my $itemtype = $builder->build(
2783 source => 'Itemtype',
2784 value => { notforloan => undef, }
2788 # for loan at item type and item level
2789 $item->notforloan(0)->store;
2790 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
2791 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2792 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2793 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2795 # not for loan at item type level
2796 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2797 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2798 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2801 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2802 'Item can not be issued, not for loan at item type level'
2805 # not for loan at item level
2806 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2807 $item->notforloan( 1 )->store;
2808 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2809 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2812 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2813 'Item can not be issued, not for loan at item type level'
2817 # TODO test with AllowNotForLoanOverride = 1
2820 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
2823 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
2824 my $item = $builder->build_object({ class => 'Koha::Items', value => { onloan => '2018-01-01' }});
2825 AddReturn( $item->barcode, $item->homebranch );
2826 $item->discard_changes; # refresh
2827 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
2830 $schema->storage->txn_rollback;
2831 C4::Context->clear_syspref_cache();
2832 $cache->clear_from_cache('single_holidays');
2834 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
2838 $schema->storage->txn_begin;
2840 t::lib::Mocks::mock_preference('item-level_itypes', 1);
2842 my $issuing_charges = 15;
2843 my $title = 'A title';
2844 my $author = 'Author, An';
2845 my $barcode = 'WHATARETHEODDS';
2847 my $circ = Test::MockModule->new('C4::Circulation');
2849 'GetIssuingCharges',
2851 return $issuing_charges;
2855 my $library = $builder->build_object({ class => 'Koha::Libraries' });
2856 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
2857 my $patron = $builder->build_object({
2858 class => 'Koha::Patrons',
2859 value => { branchcode => $library->id }
2862 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
2863 my ( undef, undef, $item_id ) = AddItem(
2865 homebranch => $library->id,
2866 holdingbranch => $library->id,
2867 barcode => $barcode,
2868 replacementprice => 23.00,
2869 itype => $itemtype->id
2871 $biblio->biblionumber
2873 my $item = Koha::Items->find( $item_id );
2875 my $context = Test::MockModule->new('C4::Context');
2876 $context->mock( userenv => { branch => $library->id } );
2878 # Check the item out
2879 AddIssue( $patron->unblessed, $item->barcode );
2880 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
2881 my $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
2882 my %params_renewal = (
2883 timestamp => { -like => $date . "%" },
2884 module => "CIRCULATION",
2885 action => "RENEWAL",
2887 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
2888 AddRenewal( $patron->id, $item->id, $library->id );
2889 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
2890 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
2892 my $checkouts = $patron->checkouts;
2893 # The following will fail if run on 00:00:00
2894 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
2896 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
2897 $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
2898 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
2899 AddRenewal( $patron->id, $item->id, $library->id );
2900 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
2901 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
2903 my $lines = Koha::Account::Lines->search({
2904 borrowernumber => $patron->id,
2905 itemnumber => $item->id
2908 is( $lines->count, 3 );
2910 my $line = $lines->next;
2911 is( $line->accounttype, 'Rent', 'The issuing charge generates an accountline' );
2912 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
2913 is( $line->description, 'Rental', 'AddIssuingCharge set a hardcoded description for the accountline' );
2915 $line = $lines->next;
2916 is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
2917 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
2918 is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
2920 $line = $lines->next;
2921 is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
2922 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
2923 is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
2925 $schema->storage->txn_rollback;
2928 subtest 'ProcessOfflinePayment() tests' => sub {
2932 $schema->storage->txn_begin;
2936 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
2937 my $library = $builder->build_object({ class => 'Koha::Libraries' });
2938 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
2940 is( $result, 'Success.', 'The right string is returned' );
2942 my $lines = $patron->account->lines;
2943 is( $lines->count, 1, 'line created correctly');
2945 my $line = $lines->next;
2946 is( $line->amount+0, $amount * -1, 'amount picked from params' );
2947 is( $line->branchcode, $library->id, 'branchcode set correctly' );
2949 $schema->storage->txn_rollback;
2955 my ( $library ) = @_;
2956 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
2960 my ( $error, $question, $alert ) = @_;
2962 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
2963 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
2964 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
2968 sub test_debarment_on_checkout {
2970 my $item = $params->{item};
2971 my $library = $params->{library};
2972 my $patron = $params->{patron};
2973 my $due_date = $params->{due_date} || dt_from_string;
2974 my $return_date = $params->{return_date} || dt_from_string;
2975 my $expected_expiration_date = $params->{expiration_date};
2977 $expected_expiration_date = output_pref(
2979 dt => $expected_expiration_date,
2980 dateformat => 'sql',
2984 my @caller = caller;
2985 my $line_number = $caller[2];
2986 AddIssue( $patron, $item->{barcode}, $due_date );
2988 my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode}, undef, $return_date );
2989 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
2990 or diag('AddReturn returned message ' . Dumper $message );
2991 my $debarments = Koha::Patron::Debarments::GetDebarments(
2992 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
2993 is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
2995 is( $debarments->[0]->{expiration},
2996 $expected_expiration_date, 'Test at line ' . $line_number );
2997 Koha::Patron::Debarments::DelUniqueDebarment(
2998 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
3001 subtest 'Incremented fee tests' => sub {
3004 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3006 my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store;
3008 my $module = new Test::MockModule('C4::Context');
3009 $module->mock('userenv', sub { { branch => $library->id } });
3011 my $patron = $builder->build_object(
3013 class => 'Koha::Patrons',
3014 value => { categorycode => $patron_category->{categorycode} }
3018 my $itemtype = $builder->build_object(
3020 class => 'Koha::ItemTypes',
3022 notforloan => undef,
3024 rentalcharge_daily => 1.000000
3029 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3030 my $item = $builder->build_object(
3032 class => 'Koha::Items',
3034 homebranch => $library->id,
3035 holdingbranch => $library->id,
3039 itype => $itemtype->id,
3040 biblionumber => $biblioitem->{biblionumber},
3041 biblioitemnumber => $biblioitem->{biblioitemnumber},
3046 is( $itemtype->rentalcharge_daily, '1.000000', 'Daily rental charge stored and retreived correctly' );
3047 is( $item->effective_itemtype, $itemtype->id, "Itemtype set correctly for item");
3049 my $dt_from = dt_from_string();
3050 my $dt_to = dt_from_string()->add( days => 7 );
3051 my $dt_to_renew = dt_from_string()->add( days => 13 );
3053 t::lib::Mocks::mock_preference('finesCalendar', 'ignoreCalendar');
3054 my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3055 my $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3056 is( $accountline->amount, '7.000000', "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar" );
3057 $accountline->delete();
3058 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3059 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3060 is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal" );
3061 $accountline->delete();
3064 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
3065 $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3066 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3067 is( $accountline->amount, '7.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed" );
3068 $accountline->delete();
3069 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3070 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3071 is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal" );
3072 $accountline->delete();
3075 my $calendar = C4::Calendar->new( branchcode => $library->id );
3076 $calendar->insert_week_day_holiday(
3078 title => 'Test holiday',
3079 description => 'Test holiday'
3081 $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3082 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3083 is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays" );
3084 $accountline->delete();
3085 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3086 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3087 is( $accountline->amount, '5.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays, for renewal" );
3088 $accountline->delete();
3091 $itemtype->rentalcharge('2.000000')->store;
3092 is( $itemtype->rentalcharge, '2.000000', 'Rental charge updated and retreived correctly' );
3093 $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from);
3094 my $accountlines = Koha::Account::Lines->search({ itemnumber => $item->id });
3095 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly");
3096 $accountlines->delete();
3097 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3098 $accountlines = Koha::Account::Lines->search({ itemnumber => $item->id });
3099 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly, for renewal");
3100 $accountlines->delete();
3104 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
3107 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
3108 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3111 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3112 my $patron = $builder->build_object(
3114 class => 'Koha::Patrons',
3115 value => { categorycode => $patron_category->{categorycode} }
3119 my $itemtype = $builder->build_object(
3121 class => 'Koha::ItemTypes',
3125 rentalcharge_daily => 0
3130 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3131 my $item = $builder->build_object(
3133 class => 'Koha::Items',
3135 homebranch => $library->id,
3136 holdingbranch => $library->id,
3140 itype => $itemtype->id,
3141 biblionumber => $biblioitem->{biblionumber},
3142 biblioitemnumber => $biblioitem->{biblioitemnumber},
3147 my ( $issuingimpossible, $needsconfirmation );
3148 my $dt_from = dt_from_string();
3149 my $dt_due = dt_from_string()->add( days => 3 );
3151 $itemtype->rentalcharge('1.000000')->store;
3152 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3153 is_deeply( $needsconfirmation, { RENTALCHARGE => '1' }, 'Item needs rentalcharge confirmation to be issued' );
3154 $itemtype->rentalcharge('0')->store;
3155 $itemtype->rentalcharge_daily('1.000000')->store;
3156 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3157 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
3158 $itemtype->rentalcharge_daily('0')->store;