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 => 130;
27 use POSIX qw( floor );
29 use t::lib::TestBuilder;
38 use C4::Overdues qw(UpdateFine CalcFine);
41 use Koha::IssuingRules;
45 use Koha::CirculationRules;
46 use Koha::Subscriptions;
47 use Koha::Account::Lines;
48 use Koha::Account::Offsets;
51 my $schema = Koha::Database->schema;
52 $schema->storage->txn_begin;
53 my $builder = t::lib::TestBuilder->new;
54 my $dbh = C4::Context->dbh;
57 $dbh->{RaiseError} = 1;
59 my $cache = Koha::Caches->get_instance();
60 $dbh->do(q|DELETE FROM special_holidays|);
61 $dbh->do(q|DELETE FROM repeatable_holidays|);
62 $cache->clear_from_cache('single_holidays');
64 # Start with a clean slate
65 $dbh->do('DELETE FROM issues');
66 $dbh->do('DELETE FROM borrowers');
68 my $library = $builder->build({
71 my $library2 = $builder->build({
74 my $itemtype = $builder->build(
80 rentalcharge_daily => 0,
81 defaultreplacecost => undef,
86 my $patron_category = $builder->build(
92 BlockExpiredPatronOpacActions => -1, # Pick the pref value
97 my $CircControl = C4::Context->preference('CircControl');
98 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
101 homebranch => $library2->{branchcode},
102 holdingbranch => $library2->{branchcode}
106 branchcode => $library2->{branchcode}
109 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
111 # No userenv, PickupLibrary
112 t::lib::Mocks::mock_preference('IndependentBranches', '0');
113 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
115 C4::Context->preference('CircControl'),
117 'CircControl changed to PickupLibrary'
120 C4::Circulation::_GetCircControlBranch($item, $borrower),
121 $item->{$HomeOrHoldingBranch},
122 '_GetCircControlBranch returned item branch (no userenv defined)'
125 # No userenv, PatronLibrary
126 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
128 C4::Context->preference('CircControl'),
130 'CircControl changed to PatronLibrary'
133 C4::Circulation::_GetCircControlBranch($item, $borrower),
134 $borrower->{branchcode},
135 '_GetCircControlBranch returned borrower branch'
138 # No userenv, ItemHomeLibrary
139 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
141 C4::Context->preference('CircControl'),
143 'CircControl changed to ItemHomeLibrary'
146 $item->{$HomeOrHoldingBranch},
147 C4::Circulation::_GetCircControlBranch($item, $borrower),
148 '_GetCircControlBranch returned item branch'
152 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
153 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
155 # Userenv set, PickupLibrary
156 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
158 C4::Context->preference('CircControl'),
160 'CircControl changed to PickupLibrary'
163 C4::Circulation::_GetCircControlBranch($item, $borrower),
164 $library2->{branchcode},
165 '_GetCircControlBranch returned current branch'
168 # Userenv set, PatronLibrary
169 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
171 C4::Context->preference('CircControl'),
173 'CircControl changed to PatronLibrary'
176 C4::Circulation::_GetCircControlBranch($item, $borrower),
177 $borrower->{branchcode},
178 '_GetCircControlBranch returned borrower branch'
181 # Userenv set, ItemHomeLibrary
182 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
184 C4::Context->preference('CircControl'),
186 'CircControl changed to ItemHomeLibrary'
189 C4::Circulation::_GetCircControlBranch($item, $borrower),
190 $item->{$HomeOrHoldingBranch},
191 '_GetCircControlBranch returned item branch'
194 # Reset initial configuration
195 t::lib::Mocks::mock_preference('CircControl', $CircControl);
197 C4::Context->preference('CircControl'),
199 'CircControl reset to its initial value'
202 # Set a simple circ policy
203 $dbh->do('DELETE FROM issuingrules');
204 Koha::CirculationRules->search()->delete();
206 q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
207 issuelength, lengthunit,
208 renewalsallowed, renewalperiod,
209 norenewalbefore, auto_renew,
226 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
228 # CanBookBeRenewed tests
229 C4::Context->set_preference('ItemsDeniedRenewal','');
230 # Generate test biblio
231 my $biblio = $builder->build_sample_biblio();
233 my $branch = $library2->{branchcode};
235 my $item_1 = $builder->build_sample_item(
237 biblionumber => $biblio->biblionumber,
239 replacementprice => 12.00,
243 $reused_itemnumber_1 = $item_1->itemnumber;
245 my $item_2 = $builder->build_sample_item(
247 biblionumber => $biblio->biblionumber,
249 replacementprice => 23.00,
253 $reused_itemnumber_2 = $item_2->itemnumber;
255 my $item_3 = $builder->build_sample_item(
257 biblionumber => $biblio->biblionumber,
259 replacementprice => 23.00,
265 my %renewing_borrower_data = (
267 surname => 'Renewal',
268 categorycode => $patron_category->{categorycode},
269 branchcode => $branch,
272 my %reserving_borrower_data = (
273 firstname => 'Katrin',
274 surname => 'Reservation',
275 categorycode => $patron_category->{categorycode},
276 branchcode => $branch,
279 my %hold_waiting_borrower_data = (
281 surname => 'Reservation',
282 categorycode => $patron_category->{categorycode},
283 branchcode => $branch,
286 my %restricted_borrower_data = (
287 firstname => 'Alice',
288 surname => 'Reservation',
289 categorycode => $patron_category->{categorycode},
290 debarred => '3228-01-01',
291 branchcode => $branch,
294 my %expired_borrower_data = (
297 categorycode => $patron_category->{categorycode},
298 branchcode => $branch,
299 dateexpiry => dt_from_string->subtract( months => 1 ),
302 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
303 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
304 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
305 my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
306 my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
308 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
309 my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
310 my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
317 my $checkitem = undef;
320 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
321 my $datedue = dt_from_string( $issue->date_due() );
322 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
324 my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
325 $datedue = dt_from_string( $issue->date_due() );
326 is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
329 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
330 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
332 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
333 is( $renewokay, 1, 'Can renew, no holds for this title or item');
336 # Biblio-level hold, renewal test
338 $branch, $reserving_borrowernumber, $biblio->biblionumber,
339 $bibitems, $priority, $resdate, $expdate, $notes,
340 'a title', $checkitem, $found
343 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
344 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
345 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
346 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
347 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
348 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
349 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
351 # Now let's add an item level hold, we should no longer be able to renew the item
352 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
354 borrowernumber => $hold_waiting_borrowernumber,
355 biblionumber => $biblio->biblionumber,
356 itemnumber => $item_1->itemnumber,
357 branchcode => $branch,
361 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
362 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
365 # 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
366 # be able to renew these items
367 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
369 borrowernumber => $hold_waiting_borrowernumber,
370 biblionumber => $biblio->biblionumber,
371 itemnumber => $item_3->itemnumber,
372 branchcode => $branch,
377 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
378 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
379 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
380 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
381 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
383 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
384 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
385 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
387 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
388 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
389 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
391 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
392 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
393 AddIssue($reserving_borrower, $item_3->barcode);
394 my $reserve = $dbh->selectrow_hashref(
395 'SELECT * FROM old_reserves WHERE reserve_id = ?',
399 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
401 # Item-level hold, renewal test
403 $branch, $reserving_borrowernumber, $biblio->biblionumber,
404 $bibitems, $priority, $resdate, $expdate, $notes,
405 'a title', $item_1->itemnumber, $found
408 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
409 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
410 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
412 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
413 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
415 # Items can't fill hold for reasons
416 ModItem({ notforloan => 1 }, $biblio->biblionumber, $item_1->itemnumber);
417 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
418 is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
419 ModItem({ notforloan => 0, itype => $itemtype }, $biblio->biblionumber, $item_1->itemnumber);
421 # FIXME: Add more for itemtype not for loan etc.
423 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
424 my $item_5 = $builder->build_sample_item(
426 biblionumber => $biblio->biblionumber,
428 replacementprice => 23.00,
432 my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
433 is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
435 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
436 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
437 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
438 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
439 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
441 # Users cannot renew an overdue item
442 my $item_6 = $builder->build_sample_item(
444 biblionumber => $biblio->biblionumber,
446 replacementprice => 23.00,
451 my $item_7 = $builder->build_sample_item(
453 biblionumber => $biblio->biblionumber,
455 replacementprice => 23.00,
460 my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
461 is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
463 my $now = dt_from_string();
464 my $five_weeks = DateTime::Duration->new(weeks => 5);
465 my $five_weeks_ago = $now - $five_weeks;
466 t::lib::Mocks::mock_preference('finesMode', 'production');
468 my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
469 is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
471 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
472 C4::Overdues::UpdateFine(
474 issue_id => $passeddatedue1->id(),
475 itemnumber => $item_7->itemnumber,
476 borrowernumber => $renewing_borrower->{borrowernumber},
478 due => Koha::DateUtils::output_pref($five_weeks_ago)
482 t::lib::Mocks::mock_preference('RenewalLog', 0);
483 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
484 my %params_renewal = (
485 timestamp => { -like => $date . "%" },
486 module => "CIRCULATION",
490 timestamp => { -like => $date . "%" },
491 module => "CIRCULATION",
494 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
495 my $dt = dt_from_string();
496 Time::Fake->offset( $dt->epoch );
497 my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
498 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
499 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
500 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
503 t::lib::Mocks::mock_preference('RenewalLog', 1);
504 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
505 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
506 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
507 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
508 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
510 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
511 is( $fines->count, 2 );
512 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
513 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
517 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
518 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
519 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
520 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
521 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
522 $new_log_size = Koha::ActionLogs->count( \%params_issue );
523 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
525 $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
528 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
529 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
530 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
531 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
532 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
535 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
539 # Test automatic renewal before value for "norenewalbefore" in policy is set
540 # In this case automatic renewal is not permitted prior to due date
541 my $item_4 = $builder->build_sample_item(
543 biblionumber => $biblio->biblionumber,
545 replacementprice => 16.00,
550 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
551 ( $renewokay, $error ) =
552 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
553 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
554 is( $error, 'auto_too_soon',
555 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
558 # Test premature manual renewal
559 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
561 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
562 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
563 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
566 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
567 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
569 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
570 $datedue->clone->add( days => -7 ),
571 'Bug 14395: Renewals permitted 7 days before due date, as expected'
575 # Test 'date' setting for syspref NoRenewalBeforePrecision
576 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
578 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
579 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
580 'Bug 14395: Renewals permitted 7 days before due date, as expected'
584 # Test premature automatic renewal
585 ( $renewokay, $error ) =
586 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
587 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
588 is( $error, 'auto_too_soon',
589 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
592 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
593 # and test automatic renewal again
594 $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
595 ( $renewokay, $error ) =
596 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
597 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
598 is( $error, 'auto_too_soon',
599 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
602 # Change policy so that loans can be renewed 99 days prior to the due date
603 # and test automatic renewal again
604 $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
605 ( $renewokay, $error ) =
606 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
607 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
608 is( $error, 'auto_renew',
609 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
612 subtest "too_late_renewal / no_auto_renewal_after" => sub {
614 my $item_to_auto_renew = $builder->build(
617 biblionumber => $biblio->biblionumber,
618 homebranch => $branch,
619 holdingbranch => $branch,
624 my $ten_days_before = dt_from_string->add( days => -10 );
625 my $ten_days_ahead = dt_from_string->add( days => 10 );
626 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
628 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 9');
629 ( $renewokay, $error ) =
630 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
631 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
632 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
634 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 10');
635 ( $renewokay, $error ) =
636 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
637 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
638 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
640 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 11');
641 ( $renewokay, $error ) =
642 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
643 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
644 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
646 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
647 ( $renewokay, $error ) =
648 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
649 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
650 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
652 $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 ) );
653 ( $renewokay, $error ) =
654 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
655 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
656 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
658 $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 ) );
659 ( $renewokay, $error ) =
660 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
661 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
662 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
664 $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 ) );
665 ( $renewokay, $error ) =
666 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
667 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
668 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
671 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew" => sub {
673 my $item_to_auto_renew = $builder->build({
676 biblionumber => $biblio->biblionumber,
677 homebranch => $branch,
678 holdingbranch => $branch,
682 my $ten_days_before = dt_from_string->add( days => -10 );
683 my $ten_days_ahead = dt_from_string->add( days => 10 );
684 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
686 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
687 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
688 C4::Context->set_preference('OPACFineNoRenewals','10');
689 my $fines_amount = 5;
690 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
693 amount => $fines_amount,
696 item_id => $item_to_auto_renew->{itemnumber},
697 description => "Some fines"
699 )->status('RETURNED')->store;
700 ( $renewokay, $error ) =
701 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
702 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
703 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
707 amount => $fines_amount,
710 item_id => $item_to_auto_renew->{itemnumber},
711 description => "Some fines"
713 )->status('RETURNED')->store;
714 ( $renewokay, $error ) =
715 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
716 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
717 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
721 amount => $fines_amount,
724 item_id => $item_to_auto_renew->{itemnumber},
725 description => "Some fines"
727 )->status('RETURNED')->store;
728 ( $renewokay, $error ) =
729 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
730 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
731 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
733 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
736 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
738 my $item_to_auto_renew = $builder->build({
741 biblionumber => $biblio->biblionumber,
742 homebranch => $branch,
743 holdingbranch => $branch,
747 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
749 my $ten_days_before = dt_from_string->add( days => -10 );
750 my $ten_days_ahead = dt_from_string->add( days => 10 );
752 # Patron is expired and BlockExpiredPatronOpacActions=0
753 # => auto renew is allowed
754 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
755 my $patron = $expired_borrower;
756 my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
757 ( $renewokay, $error ) =
758 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
759 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
760 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
761 Koha::Checkouts->find( $checkout->issue_id )->delete;
764 # Patron is expired and BlockExpiredPatronOpacActions=1
765 # => auto renew is not allowed
766 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
767 $patron = $expired_borrower;
768 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
769 ( $renewokay, $error ) =
770 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
771 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
772 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
773 Koha::Checkouts->find( $checkout->issue_id )->delete;
776 # Patron is not expired and BlockExpiredPatronOpacActions=1
777 # => auto renew is allowed
778 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
779 $patron = $renewing_borrower;
780 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
781 ( $renewokay, $error ) =
782 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
783 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
784 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
785 Koha::Checkouts->find( $checkout->issue_id )->delete;
788 subtest "GetLatestAutoRenewDate" => sub {
790 my $item_to_auto_renew = $builder->build(
793 biblionumber => $biblio->biblionumber,
794 homebranch => $branch,
795 holdingbranch => $branch,
800 my $ten_days_before = dt_from_string->add( days => -10 );
801 my $ten_days_ahead = dt_from_string->add( days => 10 );
802 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
803 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = NULL');
804 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
805 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' );
806 my $five_days_before = dt_from_string->add( days => -5 );
807 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 5, no_auto_renewal_after_hard_limit = NULL');
808 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
809 is( $latest_auto_renew_date->truncate( to => 'minute' ),
810 $five_days_before->truncate( to => 'minute' ),
811 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
813 my $five_days_ahead = dt_from_string->add( days => 5 );
814 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = NULL');
815 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
816 is( $latest_auto_renew_date->truncate( to => 'minute' ),
817 $five_days_ahead->truncate( to => 'minute' ),
818 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
820 my $two_days_ahead = dt_from_string->add( days => 2 );
821 $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 ) );
822 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
823 is( $latest_auto_renew_date->truncate( to => 'day' ),
824 $two_days_ahead->truncate( to => 'day' ),
825 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
827 $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 ) );
828 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
829 is( $latest_auto_renew_date->truncate( to => 'day' ),
830 $two_days_ahead->truncate( to => 'day' ),
831 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
838 # set policy to forbid renewals
839 $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
841 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
842 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
843 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
845 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
846 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
847 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
849 C4::Overdues::UpdateFine(
851 issue_id => $issue->id(),
852 itemnumber => $item_1->itemnumber,
853 borrowernumber => $renewing_borrower->{borrowernumber},
856 due => Koha::DateUtils::output_pref($datedue)
860 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
861 is( $line->accounttype, 'OVERDUE', 'Account line type is OVERDUE' );
862 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
863 is( $line->amountoutstanding, '15.000000', 'Account line amount outstanding is 15.00' );
864 is( $line->amount, '15.000000', 'Account line amount is 15.00' );
865 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
867 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
868 is( $offset->type, 'OVERDUE', 'Account offset type is Fine' );
869 is( $offset->amount, '15.000000', 'Account offset amount is 15.00' );
871 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
872 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
874 LostItem( $item_1->itemnumber, 'test', 1 );
876 $line = Koha::Account::Lines->find($line->id);
877 is( $line->accounttype, 'OVERDUE', 'Account type remains as OVERDUE' );
878 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
880 my $item = Koha::Items->find($item_1->itemnumber);
881 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
882 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
883 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
885 my $total_due = $dbh->selectrow_array(
886 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
887 undef, $renewing_borrower->{borrowernumber}
890 is( $total_due, '15.000000', 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
892 C4::Context->dbh->do("DELETE FROM accountlines");
894 C4::Overdues::UpdateFine(
896 issue_id => $issue2->id(),
897 itemnumber => $item_2->itemnumber,
898 borrowernumber => $renewing_borrower->{borrowernumber},
901 due => Koha::DateUtils::output_pref($datedue)
905 LostItem( $item_2->itemnumber, 'test', 0 );
907 my $item2 = Koha::Items->find($item_2->itemnumber);
908 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
909 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
911 $total_due = $dbh->selectrow_array(
912 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
913 undef, $renewing_borrower->{borrowernumber}
916 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
918 my $future = dt_from_string();
919 $future->add( days => 7 );
920 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
921 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
923 # Users cannot renew any item if there is an overdue item
924 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
925 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
926 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
927 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
928 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
930 my $manager = $builder->build_object({ class => "Koha::Patrons" });
931 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
932 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
933 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
934 LostItem( $item_3->itemnumber, 'test', 0 );
935 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
936 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
938 $accountline->description,
940 $item_3->biblio->title || '',
941 $item_3->barcode || '',
942 $item_3->itemcallnumber || '' ),
943 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
948 # GetUpcomingDueIssues tests
949 my $branch = $library2->{branchcode};
951 #Create another record
952 my $biblio2 = $builder->build_sample_biblio();
955 my $item_1 = Koha::Items->find($reused_itemnumber_1);
956 my $item_2 = Koha::Items->find($reused_itemnumber_2);
957 my $item_3 = $builder->build_sample_item(
959 biblionumber => $biblio2->biblionumber,
967 my %a_borrower_data = (
968 firstname => 'Fridolyn',
970 categorycode => $patron_category->{categorycode},
971 branchcode => $branch,
974 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
975 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
977 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
978 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
979 my $today = DateTime->today(time_zone => C4::Context->tz());
981 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
982 my $datedue = dt_from_string( $issue->date_due() );
983 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
984 my $datedue2 = dt_from_string( $issue->date_due() );
988 # GetUpcomingDueIssues tests
990 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
991 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
994 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
995 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
996 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
999 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1000 is ( scalar( @$upcoming_dues ), 1,
1001 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1004 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1006 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1008 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1009 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1011 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1012 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1014 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1015 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1017 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1018 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1020 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1021 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1023 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1024 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1029 my $branch = $library2->{branchcode};
1031 my $biblio = $builder->build_sample_biblio();
1034 my $item = $builder->build_sample_item(
1036 biblionumber => $biblio->biblionumber,
1043 my %a_borrower_data = (
1044 firstname => 'Kyle',
1046 categorycode => $patron_category->{categorycode},
1047 branchcode => $branch,
1050 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1052 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1053 my $issue = AddIssue( $borrower, $item->barcode );
1056 issue_id => $issue->id(),
1057 itemnumber => $item->itemnumber,
1058 borrowernumber => $borrowernumber,
1064 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1065 my $count = $hr->{count};
1067 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1071 $dbh->do('DELETE FROM issues');
1072 $dbh->do('DELETE FROM items');
1073 $dbh->do('DELETE FROM issuingrules');
1074 Koha::CirculationRules->search()->delete();
1077 INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
1078 norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
1087 Koha::CirculationRules->set_rules(
1089 categorycode => '*',
1097 my $biblio = $builder->build_sample_biblio();
1099 my $item_1 = $builder->build_sample_item(
1101 biblionumber => $biblio->biblionumber,
1102 library => $library2->{branchcode},
1107 my $item_2= $builder->build_sample_item(
1109 biblionumber => $biblio->biblionumber,
1110 library => $library2->{branchcode},
1115 my $borrowernumber1 = Koha::Patron->new({
1116 firstname => 'Kyle',
1118 categorycode => $patron_category->{categorycode},
1119 branchcode => $library2->{branchcode},
1120 })->store->borrowernumber;
1121 my $borrowernumber2 = Koha::Patron->new({
1122 firstname => 'Chelsea',
1124 categorycode => $patron_category->{categorycode},
1125 branchcode => $library2->{branchcode},
1126 })->store->borrowernumber;
1128 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1129 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1131 my $issue = AddIssue( $borrower1, $item_1->barcode );
1133 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1134 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1137 $library2->{branchcode}, $borrowernumber2, $biblio->biblionumber,
1138 '', 1, undef, undef, '',
1142 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1143 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1144 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1145 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' );
1147 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1148 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1149 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1150 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' );
1152 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1153 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1154 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1155 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1157 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1158 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1159 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1160 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1162 # Setting item not checked out to be not for loan but holdable
1163 ModItem({ notforloan => -1 }, $biblio->biblionumber, $item_2->itemnumber);
1165 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1166 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' );
1170 # Don't allow renewing onsite checkout
1171 my $branch = $library->{branchcode};
1173 #Create another record
1174 my $biblio = $builder->build_sample_biblio();
1176 my $item = $builder->build_sample_item(
1178 biblionumber => $biblio->biblionumber,
1184 my $borrowernumber = Koha::Patron->new({
1187 categorycode => $patron_category->{categorycode},
1188 branchcode => $branch,
1189 })->store->borrowernumber;
1191 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1193 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1194 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1195 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1196 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1200 my $library = $builder->build({ source => 'Branch' });
1202 my $biblio = $builder->build_sample_biblio();
1204 my $item = $builder->build_sample_item(
1206 biblionumber => $biblio->biblionumber,
1207 library => $library->{branchcode},
1212 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1214 my $issue = AddIssue( $patron, $item->barcode );
1217 issue_id => $issue->id(),
1218 itemnumber => $item->itemnumber,
1219 borrowernumber => $patron->{borrowernumber},
1226 issue_id => $issue->id(),
1227 itemnumber => $item->itemnumber,
1228 borrowernumber => $patron->{borrowernumber},
1233 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1236 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1239 my $homebranch = $builder->build( { source => 'Branch' } );
1240 my $holdingbranch = $builder->build( { source => 'Branch' } );
1241 my $otherbranch = $builder->build( { source => 'Branch' } );
1242 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1243 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1245 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1246 my $item = $builder->build(
1249 homebranch => $homebranch->{branchcode},
1250 holdingbranch => $holdingbranch->{branchcode},
1251 biblionumber => $biblioitem->{biblionumber}
1256 set_userenv($holdingbranch);
1258 my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1259 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1261 my ( $error, $question, $alerts );
1263 # AllowReturnToBranch == anywhere
1264 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1265 ## Test that unknown barcodes don't generate internal server errors
1266 set_userenv($homebranch);
1267 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1268 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1269 ## Can be issued from homebranch
1270 set_userenv($homebranch);
1271 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1272 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1273 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1274 ## Can be issued from holdingbranch
1275 set_userenv($holdingbranch);
1276 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1277 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1278 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1279 ## Can be issued from another branch
1280 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1281 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1282 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1284 # AllowReturnToBranch == holdingbranch
1285 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1286 ## Cannot be issued from homebranch
1287 set_userenv($homebranch);
1288 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1289 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1290 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1291 is( $error->{branch_to_return}, $holdingbranch->{branchcode} );
1292 ## Can be issued from holdinbranch
1293 set_userenv($holdingbranch);
1294 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1295 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1296 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1297 ## Cannot be issued from another branch
1298 set_userenv($otherbranch);
1299 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1300 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1301 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1302 is( $error->{branch_to_return}, $holdingbranch->{branchcode} );
1304 # AllowReturnToBranch == homebranch
1305 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1306 ## Can be issued from holdinbranch
1307 set_userenv($homebranch);
1308 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1309 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1310 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1311 ## Cannot be issued from holdinbranch
1312 set_userenv($holdingbranch);
1313 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1314 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1315 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1316 is( $error->{branch_to_return}, $homebranch->{branchcode} );
1317 ## Cannot be issued from holdinbranch
1318 set_userenv($otherbranch);
1319 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1320 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1321 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1322 is( $error->{branch_to_return}, $homebranch->{branchcode} );
1324 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1327 subtest 'AddIssue & AllowReturnToBranch' => sub {
1330 my $homebranch = $builder->build( { source => 'Branch' } );
1331 my $holdingbranch = $builder->build( { source => 'Branch' } );
1332 my $otherbranch = $builder->build( { source => 'Branch' } );
1333 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1334 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1336 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1337 my $item = $builder->build(
1340 homebranch => $homebranch->{branchcode},
1341 holdingbranch => $holdingbranch->{branchcode},
1345 biblionumber => $biblioitem->{biblionumber}
1350 set_userenv($holdingbranch);
1352 my $ref_issue = 'Koha::Checkout';
1353 my $issue = AddIssue( $patron_1, $item->{barcode} );
1355 my ( $error, $question, $alerts );
1357 # AllowReturnToBranch == homebranch
1358 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1359 ## Can be issued from homebranch
1360 set_userenv($homebranch);
1361 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1362 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1363 ## Can be issued from holdinbranch
1364 set_userenv($holdingbranch);
1365 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1366 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1367 ## Can be issued from another branch
1368 set_userenv($otherbranch);
1369 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1370 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1372 # AllowReturnToBranch == holdinbranch
1373 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1374 ## Cannot be issued from homebranch
1375 set_userenv($homebranch);
1376 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1377 ## Can be issued from holdingbranch
1378 set_userenv($holdingbranch);
1379 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1380 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1381 ## Cannot be issued from another branch
1382 set_userenv($otherbranch);
1383 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1385 # AllowReturnToBranch == homebranch
1386 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1387 ## Can be issued from homebranch
1388 set_userenv($homebranch);
1389 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1390 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1391 ## Cannot be issued from holdinbranch
1392 set_userenv($holdingbranch);
1393 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1394 ## Cannot be issued from another branch
1395 set_userenv($otherbranch);
1396 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1397 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1400 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1403 my $library = $builder->build( { source => 'Branch' } );
1404 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1406 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1407 my $item_1 = $builder->build(
1410 homebranch => $library->{branchcode},
1411 holdingbranch => $library->{branchcode},
1412 biblionumber => $biblioitem_1->{biblionumber}
1416 my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1417 my $item_2 = $builder->build(
1420 homebranch => $library->{branchcode},
1421 holdingbranch => $library->{branchcode},
1422 biblionumber => $biblioitem_2->{biblionumber}
1427 my ( $error, $question, $alerts );
1429 # Patron cannot issue item_1, they have overdues
1430 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1431 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday ); # Add an overdue
1433 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1434 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1435 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
1436 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1438 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1439 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1440 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1441 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1443 # Patron cannot issue item_1, they are debarred
1444 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1445 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
1446 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1447 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1448 is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1450 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1451 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1452 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1453 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1456 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1459 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1460 my $patron_category_x = $builder->build_object(
1462 class => 'Koha::Patron::Categories',
1463 value => { category_type => 'X' }
1466 my $patron = $builder->build_object(
1468 class => 'Koha::Patrons',
1470 categorycode => $patron_category_x->categorycode,
1471 gonenoaddress => undef,
1478 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1479 my $item_1 = $builder->build(
1483 homebranch => $library->branchcode,
1484 holdingbranch => $library->branchcode,
1485 biblionumber => $biblioitem_1->{biblionumber}
1490 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1491 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1493 # TODO There are other tests to provide here
1496 subtest 'MultipleReserves' => sub {
1499 my $biblio = $builder->build_sample_biblio();
1501 my $branch = $library2->{branchcode};
1503 my $item_1 = $builder->build_sample_item(
1505 biblionumber => $biblio->biblionumber,
1507 replacementprice => 12.00,
1512 my $item_2 = $builder->build_sample_item(
1514 biblionumber => $biblio->biblionumber,
1516 replacementprice => 12.00,
1523 my $resdate = undef;
1524 my $expdate = undef;
1526 my $checkitem = undef;
1529 my %renewing_borrower_data = (
1530 firstname => 'John',
1531 surname => 'Renewal',
1532 categorycode => $patron_category->{categorycode},
1533 branchcode => $branch,
1535 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1536 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1537 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1538 my $datedue = dt_from_string( $issue->date_due() );
1539 is (defined $issue->date_due(), 1, "item 1 checked out");
1540 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1542 my %reserving_borrower_data1 = (
1543 firstname => 'Katrin',
1544 surname => 'Reservation',
1545 categorycode => $patron_category->{categorycode},
1546 branchcode => $branch,
1548 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1550 $branch, $reserving_borrowernumber1, $biblio->biblionumber,
1551 $bibitems, $priority, $resdate, $expdate, $notes,
1552 'a title', $checkitem, $found
1555 my %reserving_borrower_data2 = (
1556 firstname => 'Kirk',
1557 surname => 'Reservation',
1558 categorycode => $patron_category->{categorycode},
1559 branchcode => $branch,
1561 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1563 $branch, $reserving_borrowernumber2, $biblio->biblionumber,
1564 $bibitems, $priority, $resdate, $expdate, $notes,
1565 'a title', $checkitem, $found
1569 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1570 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1573 my $item_3 = $builder->build_sample_item(
1575 biblionumber => $biblio->biblionumber,
1577 replacementprice => 12.00,
1583 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1584 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1588 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1591 my $library = $builder->build( { source => 'Branch' } );
1592 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1594 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1595 my $biblionumber = $biblioitem->{biblionumber};
1596 my $item_1 = $builder->build(
1599 homebranch => $library->{branchcode},
1600 holdingbranch => $library->{branchcode},
1601 biblionumber => $biblionumber,
1605 my $item_2 = $builder->build(
1608 homebranch => $library->{branchcode},
1609 holdingbranch => $library->{branchcode},
1610 biblionumber => $biblionumber,
1615 my ( $error, $question, $alerts );
1616 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1618 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1619 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1620 is( keys(%$error) + keys(%$alerts), 0, 'No error or alert should be raised' . str($error, $question, $alerts) );
1621 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) );
1623 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1624 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1625 is( keys(%$error) + keys(%$question) + keys(%$alerts), 0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' . str($error, $question, $alerts) );
1627 # Add a subscription
1628 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1630 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1631 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1632 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) );
1634 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1635 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1636 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) );
1639 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1642 my $library = $builder->build( { source => 'Branch' } );
1643 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1646 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1647 my $item_1 = $builder->build(
1651 homebranch => $library->{branchcode},
1652 holdingbranch => $library->{branchcode},
1656 biblionumber => $biblioitem_1->{biblionumber}
1660 my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1661 my $item_2 = $builder->build(
1665 homebranch => $library->{branchcode},
1666 holdingbranch => $library->{branchcode},
1670 biblionumber => $biblioitem_2->{biblionumber}
1675 # And the issuing rule
1676 Koha::IssuingRules->search->delete;
1677 my $rule = Koha::IssuingRule->new(
1679 categorycode => '*',
1683 firstremind => 1, # 1 day of grace
1684 finedays => 2, # 2 days of fine per day of overdue
1685 lengthunit => 'days',
1690 # Patron cannot issue item_1, they have overdues
1691 my $five_days_ago = dt_from_string->subtract( days => 5 );
1692 my $ten_days_ago = dt_from_string->subtract( days => 10 );
1693 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
1694 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1695 ; # Add another overdue
1697 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1698 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
1699 my $debarments = Koha::Patron::Debarments::GetDebarments(
1700 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1701 is( scalar(@$debarments), 1 );
1703 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1704 # Same for the others
1705 my $expected_expiration = output_pref(
1707 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1708 dateformat => 'sql',
1712 is( $debarments->[0]->{expiration}, $expected_expiration );
1714 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
1715 $debarments = Koha::Patron::Debarments::GetDebarments(
1716 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1717 is( scalar(@$debarments), 1 );
1718 $expected_expiration = output_pref(
1720 dt => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1721 dateformat => 'sql',
1725 is( $debarments->[0]->{expiration}, $expected_expiration );
1727 Koha::Patron::Debarments::DelUniqueDebarment(
1728 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1730 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1731 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
1732 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1733 ; # Add another overdue
1734 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
1735 $debarments = Koha::Patron::Debarments::GetDebarments(
1736 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1737 is( scalar(@$debarments), 1 );
1738 $expected_expiration = output_pref(
1740 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1741 dateformat => 'sql',
1745 is( $debarments->[0]->{expiration}, $expected_expiration );
1747 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
1748 $debarments = Koha::Patron::Debarments::GetDebarments(
1749 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1750 is( scalar(@$debarments), 1 );
1751 $expected_expiration = output_pref(
1753 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1754 dateformat => 'sql',
1758 is( $debarments->[0]->{expiration}, $expected_expiration );
1761 subtest 'AddReturn + suspension_chargeperiod' => sub {
1764 my $library = $builder->build( { source => 'Branch' } );
1765 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1768 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1769 my $item_1 = $builder->build(
1773 homebranch => $library->{branchcode},
1774 holdingbranch => $library->{branchcode},
1778 biblionumber => $biblioitem_1->{biblionumber}
1783 # And the issuing rule
1784 Koha::IssuingRules->search->delete;
1785 my $rule = Koha::IssuingRule->new(
1787 categorycode => '*',
1791 firstremind => 0, # 0 day of grace
1792 finedays => 2, # 2 days of fine per day of overdue
1793 suspension_chargeperiod => 1,
1794 lengthunit => 'days',
1799 my $five_days_ago = dt_from_string->subtract( days => 5 );
1800 # We want to charge 2 days every day, without grace
1801 # With 5 days of overdue: 5 * Z
1802 my $expected_expiration = dt_from_string->add( days => ( 5 * 2 ) / 1 );
1803 test_debarment_on_checkout(
1806 library => $library,
1808 due_date => $five_days_ago,
1809 expiration_date => $expected_expiration,
1813 # We want to charge 2 days every 2 days, without grace
1814 # With 5 days of overdue: (5 * 2) / 2
1815 $rule->suspension_chargeperiod(2)->store;
1816 $expected_expiration = dt_from_string->add( days => floor( 5 * 2 ) / 2 );
1817 test_debarment_on_checkout(
1820 library => $library,
1822 due_date => $five_days_ago,
1823 expiration_date => $expected_expiration,
1827 # We want to charge 2 days every 3 days, with 1 day of grace
1828 # With 5 days of overdue: ((5-1) / 3 ) * 2
1829 $rule->suspension_chargeperiod(3)->store;
1830 $rule->firstremind(1)->store;
1831 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
1832 test_debarment_on_checkout(
1835 library => $library,
1837 due_date => $five_days_ago,
1838 expiration_date => $expected_expiration,
1842 # Use finesCalendar to know if holiday must be skipped to calculate the due date
1843 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
1844 $rule->finedays(2)->store;
1845 $rule->suspension_chargeperiod(1)->store;
1846 $rule->firstremind(0)->store;
1847 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
1849 # Adding a holiday 2 days ago
1850 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
1851 my $two_days_ago = dt_from_string->subtract( days => 2 );
1852 $calendar->insert_single_holiday(
1853 day => $two_days_ago->day,
1854 month => $two_days_ago->month,
1855 year => $two_days_ago->year,
1856 title => 'holidayTest-2d',
1857 description => 'holidayDesc 2 days ago'
1859 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
1860 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
1861 test_debarment_on_checkout(
1864 library => $library,
1866 due_date => $five_days_ago,
1867 expiration_date => $expected_expiration,
1871 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
1872 my $two_days_ahead = dt_from_string->add( days => 2 );
1873 $calendar->insert_single_holiday(
1874 day => $two_days_ahead->day,
1875 month => $two_days_ahead->month,
1876 year => $two_days_ahead->year,
1877 title => 'holidayTest+2d',
1878 description => 'holidayDesc 2 days ahead'
1881 # Same as above, but we should skip D+2
1882 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
1883 test_debarment_on_checkout(
1886 library => $library,
1888 due_date => $five_days_ago,
1889 expiration_date => $expected_expiration,
1893 # Adding another holiday, day of expiration date
1894 my $expected_expiration_dt = dt_from_string($expected_expiration);
1895 $calendar->insert_single_holiday(
1896 day => $expected_expiration_dt->day,
1897 month => $expected_expiration_dt->month,
1898 year => $expected_expiration_dt->year,
1899 title => 'holidayTest_exp',
1900 description => 'holidayDesc on expiration date'
1902 # Expiration date will be the day after
1903 test_debarment_on_checkout(
1906 library => $library,
1908 due_date => $five_days_ago,
1909 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
1913 test_debarment_on_checkout(
1916 library => $library,
1918 return_date => dt_from_string->add(days => 5),
1919 expiration_date => dt_from_string->add(days => 5 + (5 * 2 - 1) ),
1924 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
1927 my $library = $builder->build( { source => 'Branch' } );
1928 my $patron1 = $builder->build_object(
1930 class => 'Koha::Patrons',
1932 branchcode => $library->{branchcode},
1933 firstname => "Happy",
1934 surname => "Gilmore",
1938 my $patron2 = $builder->build_object(
1940 class => 'Koha::Patrons',
1942 branchcode => $library->{branchcode},
1943 firstname => "Billy",
1944 surname => "Madison",
1949 C4::Context->_new_userenv('xxx');
1950 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, 'Random Library', '', '', '');
1952 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1953 my $biblionumber = $biblioitem->{biblionumber};
1954 my $item = $builder->build(
1957 homebranch => $library->{branchcode},
1958 holdingbranch => $library->{branchcode},
1962 biblionumber => $biblionumber,
1967 my ( $error, $question, $alerts );
1968 my $issue = AddIssue( $patron1->unblessed, $item->{barcode} );
1970 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
1971 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
1972 is( $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER question flag should be set if AutoReturnCheckedOutItems is disabled and item is checked out to another' );
1974 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
1975 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
1976 is( $alerts->{RETURNED_FROM_ANOTHER}->{patron}->borrowernumber, $patron1->borrowernumber, 'RETURNED_FROM_ANOTHER alert flag should be set if AutoReturnCheckedOutItems is enabled and item is checked out to another' );
1978 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
1982 subtest 'AddReturn | is_overdue' => sub {
1985 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
1986 t::lib::Mocks::mock_preference('finesMode', 'production');
1987 t::lib::Mocks::mock_preference('MaxFine', '100');
1989 my $library = $builder->build( { source => 'Branch' } );
1990 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1991 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1992 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
1994 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1995 my $item = $builder->build(
1999 homebranch => $library->{branchcode},
2000 holdingbranch => $library->{branchcode},
2004 biblionumber => $biblioitem->{biblionumber},
2009 Koha::IssuingRules->search->delete;
2010 my $rule = Koha::IssuingRule->new(
2012 categorycode => '*',
2016 lengthunit => 'days',
2017 fine => 1, # Charge 1 every day of overdue
2023 my $one_day_ago = dt_from_string->subtract( days => 1 );
2024 my $five_days_ago = dt_from_string->subtract( days => 5 );
2025 my $ten_days_ago = dt_from_string->subtract( days => 10 );
2026 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2028 # No date specify, today will be used
2029 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2030 AddReturn( $item->{barcode}, $library->{branchcode} );
2031 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2032 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2034 # specify return date 5 days before => no overdue
2035 AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
2036 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
2037 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2038 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2040 # specify return date 5 days later => overdue
2041 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2042 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
2043 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2044 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2046 # specify dropbox date 5 days before => no overdue
2047 AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
2048 AddReturn( $item->{barcode}, $library->{branchcode}, $ten_days_ago );
2049 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2050 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2052 # specify dropbox date 5 days later => overdue, or... not
2053 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2054 AddReturn( $item->{barcode}, $library->{branchcode}, $five_days_ago );
2055 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue in dropbox mode' ); # FIXME? This is weird, the OVERDUE fine is created ( _CalculateAndUpdateFine > C4::Overdues::UpdateFine ) then remove later (in _FixOverduesOnReturn). Looks like it is a feature
2056 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2059 subtest '_FixAccountForLostAndReturned' => sub {
2063 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
2064 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
2066 my $processfee_amount = 20;
2067 my $replacement_amount = 99.00;
2068 my $item_type = $builder->build_object(
2069 { class => 'Koha::ItemTypes',
2071 notforloan => undef,
2073 defaultreplacecost => undef,
2074 processfee => $processfee_amount,
2075 rentalcharge_daily => 0,
2079 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2081 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
2083 subtest 'Full write-off tests' => sub {
2087 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2088 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2089 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
2091 my $item = $builder->build_sample_item(
2093 biblionumber => $biblio->biblionumber,
2094 library => $library->branchcode,
2095 replacementprice => $replacement_amount,
2096 itype => $item_type->itemtype,
2100 AddIssue( $patron->unblessed, $item->barcode );
2102 # Simulate item marked as lost
2103 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2104 LostItem( $item->itemnumber, 1 );
2106 my $processing_fee_lines = Koha::Account::Lines->search(
2107 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2108 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2109 my $processing_fee_line = $processing_fee_lines->next;
2110 is( $processing_fee_line->amount + 0,
2111 $processfee_amount, 'The right PF amount is generated' );
2112 is( $processing_fee_line->amountoutstanding + 0,
2113 $processfee_amount, 'The right PF amountoutstanding is generated' );
2115 my $lost_fee_lines = Koha::Account::Lines->search(
2116 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2117 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2118 my $lost_fee_line = $lost_fee_lines->next;
2119 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2120 is( $lost_fee_line->amountoutstanding + 0,
2121 $replacement_amount, 'The right L amountoutstanding is generated' );
2123 my $account = $patron->account;
2124 my $debts = $account->outstanding_debits;
2126 # Write off the debt
2127 my $credit = $account->add_credit(
2128 { amount => $account->balance,
2130 interface => 'test',
2133 $credit->apply( { debits => $debts, offset_type => 'Writeoff' } );
2135 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2136 is( $credit_return_id, undef, 'No CR account line added' );
2138 $lost_fee_line->discard_changes; # reload from DB
2139 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2140 is( $lost_fee_line->accounttype,
2141 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2143 is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2146 subtest 'Full payment tests' => sub {
2150 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2152 my $item = $builder->build_sample_item(
2154 biblionumber => $biblio->biblionumber,
2155 library => $library->branchcode,
2156 replacementprice => $replacement_amount,
2157 itype => $item_type->itemtype
2161 AddIssue( $patron->unblessed, $item->barcode );
2163 # Simulate item marked as lost
2164 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2165 LostItem( $item->itemnumber, 1 );
2167 my $processing_fee_lines = Koha::Account::Lines->search(
2168 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2169 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2170 my $processing_fee_line = $processing_fee_lines->next;
2171 is( $processing_fee_line->amount + 0,
2172 $processfee_amount, 'The right PF amount is generated' );
2173 is( $processing_fee_line->amountoutstanding + 0,
2174 $processfee_amount, 'The right PF amountoutstanding is generated' );
2176 my $lost_fee_lines = Koha::Account::Lines->search(
2177 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2178 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2179 my $lost_fee_line = $lost_fee_lines->next;
2180 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2181 is( $lost_fee_line->amountoutstanding + 0,
2182 $replacement_amount, 'The right L amountountstanding is generated' );
2184 my $account = $patron->account;
2185 my $debts = $account->outstanding_debits;
2187 # Write off the debt
2188 my $credit = $account->add_credit(
2189 { amount => $account->balance,
2191 interface => 'test',
2194 $credit->apply( { debits => $debts, offset_type => 'Payment' } );
2196 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2197 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2199 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2200 is( $credit_return->amount + 0,
2201 -99.00, 'The account line of type CR has an amount of -99' );
2202 is( $credit_return->amountoutstanding + 0,
2203 -99.00, 'The account line of type CR has an amountoutstanding of -99' );
2205 $lost_fee_line->discard_changes;
2206 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2207 is( $lost_fee_line->accounttype,
2208 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2210 is( $patron->account->balance,
2211 -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2214 subtest 'Test without payment or write off' => sub {
2218 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2220 my $item = $builder->build_sample_item(
2222 biblionumber => $biblio->biblionumber,
2223 library => $library->branchcode,
2224 replacementprice => 23.00,
2225 replacementprice => $replacement_amount,
2226 itype => $item_type->itemtype
2230 AddIssue( $patron->unblessed, $item->barcode );
2232 # Simulate item marked as lost
2233 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2234 LostItem( $item->itemnumber, 1 );
2236 my $processing_fee_lines = Koha::Account::Lines->search(
2237 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2238 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2239 my $processing_fee_line = $processing_fee_lines->next;
2240 is( $processing_fee_line->amount + 0,
2241 $processfee_amount, 'The right PF amount is generated' );
2242 is( $processing_fee_line->amountoutstanding + 0,
2243 $processfee_amount, 'The right PF amountoutstanding is generated' );
2245 my $lost_fee_lines = Koha::Account::Lines->search(
2246 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2247 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2248 my $lost_fee_line = $lost_fee_lines->next;
2249 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2250 is( $lost_fee_line->amountoutstanding + 0,
2251 $replacement_amount, 'The right L amountountstanding is generated' );
2253 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2254 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2256 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2257 is( $credit_return->amount + 0, -99.00, 'The account line of type CR has an amount of -99' );
2258 is( $credit_return->amountoutstanding + 0, 0, 'The account line of type CR has an amountoutstanding of 0' );
2260 $lost_fee_line->discard_changes;
2261 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2262 is( $lost_fee_line->accounttype, 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2264 is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2267 subtest 'Test with partial payement and write off, and remaining debt' => sub {
2271 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2272 my $item = $builder->build_sample_item(
2274 biblionumber => $biblio->biblionumber,
2275 library => $library->branchcode,
2276 replacementprice => $replacement_amount,
2277 itype => $item_type->itemtype
2281 AddIssue( $patron->unblessed, $item->barcode );
2283 # Simulate item marked as lost
2284 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2285 LostItem( $item->itemnumber, 1 );
2287 my $processing_fee_lines = Koha::Account::Lines->search(
2288 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2289 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2290 my $processing_fee_line = $processing_fee_lines->next;
2291 is( $processing_fee_line->amount + 0,
2292 $processfee_amount, 'The right PF amount is generated' );
2293 is( $processing_fee_line->amountoutstanding + 0,
2294 $processfee_amount, 'The right PF amountoutstanding is generated' );
2296 my $lost_fee_lines = Koha::Account::Lines->search(
2297 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2298 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2299 my $lost_fee_line = $lost_fee_lines->next;
2300 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2301 is( $lost_fee_line->amountoutstanding + 0,
2302 $replacement_amount, 'The right L amountountstanding is generated' );
2304 my $account = $patron->account;
2305 is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PF + L' );
2308 my $payment_amount = 27;
2309 my $payment = $account->add_credit(
2310 { amount => $payment_amount,
2312 interface => 'test',
2316 $payment->apply( { debits => $lost_fee_lines->reset, offset_type => 'Payment' } );
2318 # Partially write off fee
2319 my $write_off_amount = 25;
2320 my $write_off = $account->add_credit(
2321 { amount => $write_off_amount,
2323 interface => 'test',
2326 $write_off->apply( { debits => $lost_fee_lines->reset, offset_type => 'Writeoff' } );
2328 is( $account->balance,
2329 $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2330 'Payment and write off applied'
2333 # Store the amountoutstanding value
2334 $lost_fee_line->discard_changes;
2335 my $outstanding = $lost_fee_line->amountoutstanding;
2337 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2338 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2340 is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2342 $lost_fee_line->discard_changes;
2343 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2344 is( $lost_fee_line->accounttype,
2345 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2347 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2348 is( $credit_return->amount + 0,
2349 ($payment_amount + $outstanding ) * -1,
2350 'The account line of type CR has an amount equal to the payment + outstanding'
2352 is( $credit_return->amountoutstanding + 0,
2353 $payment_amount * -1,
2354 'The account line of type CR has an amountoutstanding equal to the payment'
2357 is( $account->balance,
2358 $processfee_amount - $payment_amount,
2359 'The patron balance is the difference between the PF and the credit'
2363 subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2367 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2368 my $barcode = 'KD123456793';
2369 my $replacement_amount = 100;
2370 my $processfee_amount = 20;
2372 my $item_type = $builder->build_object(
2373 { class => 'Koha::ItemTypes',
2375 notforloan => undef,
2377 defaultreplacecost => undef,
2379 rentalcharge_daily => 0,
2383 my ( undef, undef, $item_id ) = AddItem(
2384 { homebranch => $library->branchcode,
2385 holdingbranch => $library->branchcode,
2386 barcode => $barcode,
2387 replacementprice => $replacement_amount,
2388 itype => $item_type->itemtype
2390 $biblio->biblionumber
2393 AddIssue( $patron->unblessed, $barcode );
2395 # Simulate item marked as lost
2396 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item_id );
2397 LostItem( $item_id, 1 );
2399 my $lost_fee_lines = Koha::Account::Lines->search(
2400 { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2401 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2402 my $lost_fee_line = $lost_fee_lines->next;
2403 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2404 is( $lost_fee_line->amountoutstanding + 0,
2405 $replacement_amount, 'The right L amountountstanding is generated' );
2407 my $account = $patron->account;
2408 is( $account->balance, $replacement_amount, 'Balance is L' );
2411 my $payment_amount = 27;
2412 my $payment = $account->add_credit(
2413 { amount => $payment_amount,
2415 interface => 'test',
2418 $payment->apply({ debits => $lost_fee_lines->reset, offset_type => 'Payment' });
2420 is( $account->balance,
2421 $replacement_amount - $payment_amount,
2425 my $manual_debit_amount = 80;
2426 $account->add_debit( { amount => $manual_debit_amount, type => 'overdue', interface =>'test' } );
2428 is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
2430 t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
2432 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2433 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2435 is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2437 my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, accounttype => 'OVERDUE', status => 'UNRETURNED' })->next;
2438 is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
2442 subtest '_FixOverduesOnReturn' => sub {
2445 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2446 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2448 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2450 my $branchcode = $library2->{branchcode};
2452 my $item = $builder->build_sample_item(
2454 biblionumber => $biblio->biblionumber,
2455 library => $branchcode,
2456 replacementprice => 99.00,
2461 my $patron = $builder->build( { source => 'Borrower' } );
2463 ## Start with basic call, should just close out the open fine
2464 my $accountline = Koha::Account::Line->new(
2466 borrowernumber => $patron->{borrowernumber},
2467 accounttype => 'OVERDUE',
2468 status => 'UNRETURNED',
2469 itemnumber => $item->itemnumber,
2471 amountoutstanding => 99.00,
2472 interface => 'test',
2476 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber );
2478 $accountline->_result()->discard_changes();
2480 is( $accountline->amountoutstanding, '99.000000', 'Fine has the same amount outstanding as previously' );
2481 is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status RETURNED )');
2483 ## Run again, with exemptfine enabled
2486 accounttype => 'OVERDUE',
2487 status => 'UNRETURNED',
2488 amountoutstanding => 99.00,
2492 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1 );
2494 $accountline->_result()->discard_changes();
2495 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2497 is( $accountline->amountoutstanding + 0, 0, 'Fine has been reduced to 0' );
2498 is( $accountline->status, 'FORGIVEN', 'Open fine ( account type OVERDUE ) has been set to fine forgiven ( status FORGIVEN )');
2499 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2500 is( $offset->amount, '-99.000000', "Amount of offset is correct" );
2501 my $credit = $offset->credit;
2502 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
2503 is( $credit->amount, '-99.000000', "Credit amount is set correctly" );
2504 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
2507 subtest 'Set waiting flag' => sub {
2510 my $library_1 = $builder->build( { source => 'Branch' } );
2511 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2512 my $library_2 = $builder->build( { source => 'Branch' } );
2513 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2515 my $biblio = $builder->build( { source => 'Biblio' } );
2516 my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2518 my $item = $builder->build(
2522 homebranch => $library_1->{branchcode},
2523 holdingbranch => $library_1->{branchcode},
2527 biblionumber => $biblioitem->{biblionumber},
2532 set_userenv( $library_2 );
2533 my $reserve_id = AddReserve(
2534 $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber},
2535 '', 1, undef, undef, '', undef, $item->{itemnumber},
2538 set_userenv( $library_1 );
2539 my $do_transfer = 1;
2540 my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2541 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2542 my $hold = Koha::Holds->find( $reserve_id );
2543 is( $hold->found, 'T', 'Hold is in transit' );
2545 my ( $status ) = CheckReserves($item->{itemnumber});
2546 is( $status, 'Reserved', 'Hold is not waiting yet');
2548 set_userenv( $library_2 );
2550 AddReturn( $item->{barcode}, $library_2->{branchcode} );
2551 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2552 $hold = Koha::Holds->find( $reserve_id );
2553 is( $hold->found, 'W', 'Hold is waiting' );
2554 ( $status ) = CheckReserves($item->{itemnumber});
2555 is( $status, 'Waiting', 'Now the hold is waiting');
2558 subtest 'Cancel transfers on lost items' => sub {
2560 my $library_1 = $builder->build( { source => 'Branch' } );
2561 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2562 my $library_2 = $builder->build( { source => 'Branch' } );
2563 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2564 my $biblio = $builder->build( { source => 'Biblio' } );
2565 my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2566 my $item = $builder->build(
2570 homebranch => $library_1->{branchcode},
2571 holdingbranch => $library_1->{branchcode},
2575 biblionumber => $biblioitem->{biblionumber},
2580 set_userenv( $library_2 );
2581 my $reserve_id = AddReserve(
2582 $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber}, '', 1, undef, undef, '', undef, $item->{itemnumber},
2585 #Return book and add transfer
2586 set_userenv( $library_1 );
2587 my $do_transfer = 1;
2588 my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2589 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2590 C4::Circulation::transferbook( $library_2->{branchcode}, $item->{barcode} );
2591 my $hold = Koha::Holds->find( $reserve_id );
2592 is( $hold->found, 'T', 'Hold is in transit' );
2594 #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
2595 my ($datesent,$frombranch,$tobranch) = GetTransfers($item->{itemnumber});
2596 is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
2597 my $itemcheck = Koha::Items->find($item->{itemnumber});
2598 is( $itemcheck->holdingbranch, $library_2->{branchcode}, 'Items holding branch is the transfers destination branch before it is marked as lost' );
2600 #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
2601 ModItem( { itemlost => 1 }, $biblio->{biblionumber}, $item->{itemnumber} );
2602 LostItem( $item->{itemnumber}, 'test', 1 );
2603 ($datesent,$frombranch,$tobranch) = GetTransfers($item->{itemnumber});
2604 is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
2605 $itemcheck = Koha::Items->find($item->{itemnumber});
2606 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
2609 subtest 'CanBookBeIssued | is_overdue' => sub {
2612 # Set a simple circ policy
2613 $dbh->do('DELETE FROM issuingrules');
2615 q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
2616 issuelength, lengthunit,
2617 renewalsallowed, renewalperiod,
2618 norenewalbefore, auto_renew,
2635 my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
2636 my $ten_days_go = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
2637 my $library = $builder->build( { source => 'Branch' } );
2638 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2640 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2641 my $item = $builder->build(
2645 homebranch => $library->{branchcode},
2646 holdingbranch => $library->{branchcode},
2650 biblionumber => $biblioitem->{biblionumber},
2655 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
2656 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
2657 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
2658 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
2659 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
2660 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
2663 subtest 'ItemsDeniedRenewal preference' => sub {
2666 C4::Context->set_preference('ItemsDeniedRenewal','');
2668 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
2671 INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
2672 norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
2675 '*', $idr_lib->branchcode, '*', 25,
2682 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
2683 homebranch => $idr_lib->branchcode,
2687 itemcallnumber => undef,
2691 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
2692 homebranch => $idr_lib->branchcode,
2695 location => 'NOPROC'
2699 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
2700 branchcode => $idr_lib->branchcode,
2703 my $future = dt_from_string->add( days => 1 );
2704 my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2705 returndate => undef,
2708 borrowernumber => $idr_borrower->borrowernumber,
2709 itemnumber => $deny_book->itemnumber,
2710 onsite_checkout => 0,
2711 date_due => $future,
2714 my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2715 returndate => undef,
2718 borrowernumber => $idr_borrower->borrowernumber,
2719 itemnumber => $allow_book->itemnumber,
2720 onsite_checkout => 0,
2721 date_due => $future,
2727 my ( $idr_mayrenew, $idr_error ) =
2728 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2729 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
2730 is( $idr_error, undef, 'Renewal allowed when no rules' );
2732 $idr_rules="withdrawn: [1]";
2734 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2735 ( $idr_mayrenew, $idr_error ) =
2736 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2737 is( $idr_mayrenew, 0, 'Renewal blocked when 1 rules (withdrawn)' );
2738 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
2739 ( $idr_mayrenew, $idr_error ) =
2740 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2741 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2742 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2744 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
2746 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2747 ( $idr_mayrenew, $idr_error ) =
2748 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2749 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
2750 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
2751 ( $idr_mayrenew, $idr_error ) =
2752 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2753 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2754 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2756 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
2758 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2759 ( $idr_mayrenew, $idr_error ) =
2760 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2761 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
2762 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
2763 ( $idr_mayrenew, $idr_error ) =
2764 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2765 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2766 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2768 $idr_rules="itemcallnumber: [NULL]";
2769 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2770 ( $idr_mayrenew, $idr_error ) =
2771 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2772 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
2773 $idr_rules="itemcallnumber: ['']";
2774 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2775 ( $idr_mayrenew, $idr_error ) =
2776 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2777 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
2779 $idr_rules="itemnotes: [NULL]";
2780 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2781 ( $idr_mayrenew, $idr_error ) =
2782 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2783 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
2784 $idr_rules="itemnotes: ['']";
2785 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2786 ( $idr_mayrenew, $idr_error ) =
2787 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2788 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
2791 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
2794 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2795 my $library = $builder->build( { source => 'Branch' } );
2796 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2798 my $itemtype = $builder->build(
2800 source => 'Itemtype',
2801 value => { notforloan => undef, }
2805 my $biblioitem = $builder->build( { source => 'Biblioitem', value => { itemtype => $itemtype->{itemtype} } } );
2806 my $item = $builder->build_object(
2808 class => 'Koha::Items',
2810 homebranch => $library->{branchcode},
2811 holdingbranch => $library->{branchcode},
2815 biblionumber => $biblioitem->{biblionumber},
2816 biblioitemnumber => $biblioitem->{biblioitemnumber},
2821 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2822 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2823 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2826 subtest 'CanBookBeIssued | notforloan' => sub {
2829 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
2831 my $library = $builder->build( { source => 'Branch' } );
2832 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2834 my $itemtype = $builder->build(
2836 source => 'Itemtype',
2837 value => { notforloan => undef, }
2841 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2842 my $item = $builder->build_object(
2844 class => 'Koha::Items',
2846 homebranch => $library->{branchcode},
2847 holdingbranch => $library->{branchcode},
2851 itype => $itemtype->{itemtype},
2852 biblionumber => $biblioitem->{biblionumber},
2853 biblioitemnumber => $biblioitem->{biblioitemnumber},
2858 my ( $issuingimpossible, $needsconfirmation );
2861 subtest 'item-level_itypes = 1' => sub {
2864 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
2865 # Is for loan at item type and item level
2866 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2867 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2868 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2870 # not for loan at item type level
2871 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2872 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2873 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2876 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2877 'Item can not be issued, not for loan at item type level'
2880 # not for loan at item level
2881 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2882 $item->notforloan( 1 )->store;
2883 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2884 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2887 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2888 'Item can not be issued, not for loan at item type level'
2892 subtest 'item-level_itypes = 0' => sub {
2895 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2897 # We set another itemtype for biblioitem
2898 my $itemtype = $builder->build(
2900 source => 'Itemtype',
2901 value => { notforloan => undef, }
2905 # for loan at item type and item level
2906 $item->notforloan(0)->store;
2907 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
2908 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2909 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2910 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2912 # not for loan at item type level
2913 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2914 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2915 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2918 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2919 'Item can not be issued, not for loan at item type level'
2922 # not for loan at item level
2923 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2924 $item->notforloan( 1 )->store;
2925 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2926 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2929 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2930 'Item can not be issued, not for loan at item type level'
2934 # TODO test with AllowNotForLoanOverride = 1
2937 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
2940 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
2941 my $item = $builder->build_object({ class => 'Koha::Items', value => { onloan => '2018-01-01' }});
2942 AddReturn( $item->barcode, $item->homebranch );
2943 $item->discard_changes; # refresh
2944 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
2947 $schema->storage->txn_rollback;
2948 C4::Context->clear_syspref_cache();
2949 $cache->clear_from_cache('single_holidays');
2951 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
2955 $schema->storage->txn_begin;
2957 t::lib::Mocks::mock_preference('item-level_itypes', 1);
2959 my $issuing_charges = 15;
2960 my $title = 'A title';
2961 my $author = 'Author, An';
2962 my $barcode = 'WHATARETHEODDS';
2964 my $circ = Test::MockModule->new('C4::Circulation');
2966 'GetIssuingCharges',
2968 return $issuing_charges;
2972 my $library = $builder->build_object({ class => 'Koha::Libraries' });
2973 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
2974 my $patron = $builder->build_object({
2975 class => 'Koha::Patrons',
2976 value => { branchcode => $library->id }
2979 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
2980 my ( undef, undef, $item_id ) = AddItem(
2982 homebranch => $library->id,
2983 holdingbranch => $library->id,
2984 barcode => $barcode,
2985 replacementprice => 23.00,
2986 itype => $itemtype->id
2988 $biblio->biblionumber
2990 my $item = Koha::Items->find( $item_id );
2992 my $context = Test::MockModule->new('C4::Context');
2993 $context->mock( userenv => { branch => $library->id } );
2995 # Check the item out
2996 AddIssue( $patron->unblessed, $item->barcode );
2997 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
2998 my $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
2999 my %params_renewal = (
3000 timestamp => { -like => $date . "%" },
3001 module => "CIRCULATION",
3002 action => "RENEWAL",
3004 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
3005 AddRenewal( $patron->id, $item->id, $library->id );
3006 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3007 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
3009 my $checkouts = $patron->checkouts;
3010 # The following will fail if run on 00:00:00
3011 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
3013 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
3014 $date = output_pref( { dt => dt_from_string(), datenonly => 1, dateformat => 'iso' } );
3015 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
3016 AddRenewal( $patron->id, $item->id, $library->id );
3017 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3018 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
3020 my $lines = Koha::Account::Lines->search({
3021 borrowernumber => $patron->id,
3022 itemnumber => $item->id
3025 is( $lines->count, 3 );
3027 my $line = $lines->next;
3028 is( $line->accounttype, 'Rent', 'The issuing charge generates an accountline' );
3029 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
3030 is( $line->description, 'Rental', 'AddIssuingCharge set a hardcoded description for the accountline' );
3032 $line = $lines->next;
3033 is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
3034 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
3035 is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
3037 $line = $lines->next;
3038 is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
3039 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
3040 is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
3042 $schema->storage->txn_rollback;
3045 subtest 'ProcessOfflinePayment() tests' => sub {
3049 $schema->storage->txn_begin;
3053 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
3054 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3055 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
3057 is( $result, 'Success.', 'The right string is returned' );
3059 my $lines = $patron->account->lines;
3060 is( $lines->count, 1, 'line created correctly');
3062 my $line = $lines->next;
3063 is( $line->amount+0, $amount * -1, 'amount picked from params' );
3064 is( $line->branchcode, $library->id, 'branchcode set correctly' );
3066 $schema->storage->txn_rollback;
3072 my ( $library ) = @_;
3073 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
3077 my ( $error, $question, $alert ) = @_;
3079 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
3080 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
3081 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
3085 sub test_debarment_on_checkout {
3087 my $item = $params->{item};
3088 my $library = $params->{library};
3089 my $patron = $params->{patron};
3090 my $due_date = $params->{due_date} || dt_from_string;
3091 my $return_date = $params->{return_date} || dt_from_string;
3092 my $expected_expiration_date = $params->{expiration_date};
3094 $expected_expiration_date = output_pref(
3096 dt => $expected_expiration_date,
3097 dateformat => 'sql',
3101 my @caller = caller;
3102 my $line_number = $caller[2];
3103 AddIssue( $patron, $item->{barcode}, $due_date );
3105 my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode}, undef, $return_date );
3106 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
3107 or diag('AddReturn returned message ' . Dumper $message );
3108 my $debarments = Koha::Patron::Debarments::GetDebarments(
3109 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
3110 is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
3112 is( $debarments->[0]->{expiration},
3113 $expected_expiration_date, 'Test at line ' . $line_number );
3114 Koha::Patron::Debarments::DelUniqueDebarment(
3115 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
3118 subtest 'Incremented fee tests' => sub {
3121 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3123 my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store;
3125 my $module = new Test::MockModule('C4::Context');
3126 $module->mock('userenv', sub { { branch => $library->id } });
3128 my $patron = $builder->build_object(
3130 class => 'Koha::Patrons',
3131 value => { categorycode => $patron_category->{categorycode} }
3135 my $itemtype = $builder->build_object(
3137 class => 'Koha::ItemTypes',
3139 notforloan => undef,
3141 rentalcharge_daily => 1.000000
3146 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3147 my $item = $builder->build_object(
3149 class => 'Koha::Items',
3151 homebranch => $library->id,
3152 holdingbranch => $library->id,
3156 itype => $itemtype->id,
3157 biblionumber => $biblioitem->{biblionumber},
3158 biblioitemnumber => $biblioitem->{biblioitemnumber},
3163 is( $itemtype->rentalcharge_daily, '1.000000', 'Daily rental charge stored and retreived correctly' );
3164 is( $item->effective_itemtype, $itemtype->id, "Itemtype set correctly for item");
3166 my $dt_from = dt_from_string();
3167 my $dt_to = dt_from_string()->add( days => 7 );
3168 my $dt_to_renew = dt_from_string()->add( days => 13 );
3170 t::lib::Mocks::mock_preference('finesCalendar', 'ignoreCalendar');
3171 my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3172 my $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3173 is( $accountline->amount, '7.000000', "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar" );
3174 $accountline->delete();
3175 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3176 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3177 is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal" );
3178 $accountline->delete();
3181 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
3182 $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3183 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3184 is( $accountline->amount, '7.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed" );
3185 $accountline->delete();
3186 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3187 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3188 is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal" );
3189 $accountline->delete();
3192 my $calendar = C4::Calendar->new( branchcode => $library->id );
3193 $calendar->insert_week_day_holiday(
3195 title => 'Test holiday',
3196 description => 'Test holiday'
3198 $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3199 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3200 is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays" );
3201 $accountline->delete();
3202 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3203 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3204 is( $accountline->amount, '5.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays, for renewal" );
3205 $accountline->delete();
3208 $itemtype->rentalcharge('2.000000')->store;
3209 is( $itemtype->rentalcharge, '2.000000', 'Rental charge updated and retreived correctly' );
3210 $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from);
3211 my $accountlines = Koha::Account::Lines->search({ itemnumber => $item->id });
3212 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly");
3213 $accountlines->delete();
3214 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3215 $accountlines = Koha::Account::Lines->search({ itemnumber => $item->id });
3216 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly, for renewal");
3217 $accountlines->delete();
3221 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
3224 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
3225 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3228 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3229 my $patron = $builder->build_object(
3231 class => 'Koha::Patrons',
3232 value => { categorycode => $patron_category->{categorycode} }
3236 my $itemtype = $builder->build_object(
3238 class => 'Koha::ItemTypes',
3242 rentalcharge_daily => 0
3247 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3248 my $item = $builder->build_object(
3250 class => 'Koha::Items',
3252 homebranch => $library->id,
3253 holdingbranch => $library->id,
3257 itype => $itemtype->id,
3258 biblionumber => $biblioitem->{biblionumber},
3259 biblioitemnumber => $biblioitem->{biblioitemnumber},
3264 my ( $issuingimpossible, $needsconfirmation );
3265 my $dt_from = dt_from_string();
3266 my $dt_due = dt_from_string()->add( days => 3 );
3268 $itemtype->rentalcharge('1.000000')->store;
3269 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3270 is_deeply( $needsconfirmation, { RENTALCHARGE => '1' }, 'Item needs rentalcharge confirmation to be issued' );
3271 $itemtype->rentalcharge('0')->store;
3272 $itemtype->rentalcharge_daily('1.000000')->store;
3273 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3274 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
3275 $itemtype->rentalcharge_daily('0')->store;