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;
56 # Prevent random failures by mocking ->now
57 my $now_value = DateTime->now();
58 my $mocked_datetime = Test::MockModule->new('DateTime');
59 $mocked_datetime->mock( 'now', sub { return $now_value->clone; } );
62 $dbh->{RaiseError} = 1;
64 my $cache = Koha::Caches->get_instance();
65 $dbh->do(q|DELETE FROM special_holidays|);
66 $dbh->do(q|DELETE FROM repeatable_holidays|);
67 $cache->clear_from_cache('single_holidays');
69 # Start with a clean slate
70 $dbh->do('DELETE FROM issues');
71 $dbh->do('DELETE FROM borrowers');
73 my $library = $builder->build({
76 my $library2 = $builder->build({
79 my $itemtype = $builder->build(
85 rentalcharge_daily => 0,
86 defaultreplacecost => undef,
91 my $patron_category = $builder->build(
97 BlockExpiredPatronOpacActions => -1, # Pick the pref value
102 my $CircControl = C4::Context->preference('CircControl');
103 my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch');
106 homebranch => $library2->{branchcode},
107 holdingbranch => $library2->{branchcode}
111 branchcode => $library2->{branchcode}
114 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
116 # No userenv, PickupLibrary
117 t::lib::Mocks::mock_preference('IndependentBranches', '0');
118 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
120 C4::Context->preference('CircControl'),
122 'CircControl changed to PickupLibrary'
125 C4::Circulation::_GetCircControlBranch($item, $borrower),
126 $item->{$HomeOrHoldingBranch},
127 '_GetCircControlBranch returned item branch (no userenv defined)'
130 # No userenv, PatronLibrary
131 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
133 C4::Context->preference('CircControl'),
135 'CircControl changed to PatronLibrary'
138 C4::Circulation::_GetCircControlBranch($item, $borrower),
139 $borrower->{branchcode},
140 '_GetCircControlBranch returned borrower branch'
143 # No userenv, ItemHomeLibrary
144 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
146 C4::Context->preference('CircControl'),
148 'CircControl changed to ItemHomeLibrary'
151 $item->{$HomeOrHoldingBranch},
152 C4::Circulation::_GetCircControlBranch($item, $borrower),
153 '_GetCircControlBranch returned item branch'
157 t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} });
158 is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set');
160 # Userenv set, PickupLibrary
161 t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary');
163 C4::Context->preference('CircControl'),
165 'CircControl changed to PickupLibrary'
168 C4::Circulation::_GetCircControlBranch($item, $borrower),
169 $library2->{branchcode},
170 '_GetCircControlBranch returned current branch'
173 # Userenv set, PatronLibrary
174 t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary');
176 C4::Context->preference('CircControl'),
178 'CircControl changed to PatronLibrary'
181 C4::Circulation::_GetCircControlBranch($item, $borrower),
182 $borrower->{branchcode},
183 '_GetCircControlBranch returned borrower branch'
186 # Userenv set, ItemHomeLibrary
187 t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary');
189 C4::Context->preference('CircControl'),
191 'CircControl changed to ItemHomeLibrary'
194 C4::Circulation::_GetCircControlBranch($item, $borrower),
195 $item->{$HomeOrHoldingBranch},
196 '_GetCircControlBranch returned item branch'
199 # Reset initial configuration
200 t::lib::Mocks::mock_preference('CircControl', $CircControl);
202 C4::Context->preference('CircControl'),
204 'CircControl reset to its initial value'
207 # Set a simple circ policy
208 $dbh->do('DELETE FROM issuingrules');
209 Koha::CirculationRules->search()->delete();
211 q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
212 issuelength, lengthunit,
213 renewalsallowed, renewalperiod,
214 norenewalbefore, auto_renew,
231 my ( $reused_itemnumber_1, $reused_itemnumber_2 );
233 # CanBookBeRenewed tests
234 C4::Context->set_preference('ItemsDeniedRenewal','');
235 # Generate test biblio
236 my $biblio = $builder->build_sample_biblio();
238 my $branch = $library2->{branchcode};
240 my $item_1 = $builder->build_sample_item(
242 biblionumber => $biblio->biblionumber,
244 replacementprice => 12.00,
248 $reused_itemnumber_1 = $item_1->itemnumber;
250 my $item_2 = $builder->build_sample_item(
252 biblionumber => $biblio->biblionumber,
254 replacementprice => 23.00,
258 $reused_itemnumber_2 = $item_2->itemnumber;
260 my $item_3 = $builder->build_sample_item(
262 biblionumber => $biblio->biblionumber,
264 replacementprice => 23.00,
270 my %renewing_borrower_data = (
272 surname => 'Renewal',
273 categorycode => $patron_category->{categorycode},
274 branchcode => $branch,
277 my %reserving_borrower_data = (
278 firstname => 'Katrin',
279 surname => 'Reservation',
280 categorycode => $patron_category->{categorycode},
281 branchcode => $branch,
284 my %hold_waiting_borrower_data = (
286 surname => 'Reservation',
287 categorycode => $patron_category->{categorycode},
288 branchcode => $branch,
291 my %restricted_borrower_data = (
292 firstname => 'Alice',
293 surname => 'Reservation',
294 categorycode => $patron_category->{categorycode},
295 debarred => '3228-01-01',
296 branchcode => $branch,
299 my %expired_borrower_data = (
302 categorycode => $patron_category->{categorycode},
303 branchcode => $branch,
304 dateexpiry => dt_from_string->subtract( months => 1 ),
307 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
308 my $reserving_borrowernumber = Koha::Patron->new(\%reserving_borrower_data)->store->borrowernumber;
309 my $hold_waiting_borrowernumber = Koha::Patron->new(\%hold_waiting_borrower_data)->store->borrowernumber;
310 my $restricted_borrowernumber = Koha::Patron->new(\%restricted_borrower_data)->store->borrowernumber;
311 my $expired_borrowernumber = Koha::Patron->new(\%expired_borrower_data)->store->borrowernumber;
313 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
314 my $restricted_borrower = Koha::Patrons->find( $restricted_borrowernumber )->unblessed;
315 my $expired_borrower = Koha::Patrons->find( $expired_borrowernumber )->unblessed;
322 my $checkitem = undef;
325 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
326 my $datedue = dt_from_string( $issue->date_due() );
327 is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() );
329 my $issue2 = AddIssue( $renewing_borrower, $item_2->barcode);
330 $datedue = dt_from_string( $issue->date_due() );
331 is (defined $issue2, 1, "Item 2 checked out, due date: " . $issue2->date_due());
334 my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber;
335 is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to $renewing_borrower->{firstname} $renewing_borrower->{surname}");
337 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
338 is( $renewokay, 1, 'Can renew, no holds for this title or item');
341 # Biblio-level hold, renewal test
343 $branch, $reserving_borrowernumber, $biblio->biblionumber,
344 $bibitems, $priority, $resdate, $expdate, $notes,
345 'a title', $checkitem, $found
348 # Testing of feature to allow the renewal of reserved items if other items on the record can fill all needed holds
349 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
350 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 );
351 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
352 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
353 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
354 is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
356 # Now let's add an item level hold, we should no longer be able to renew the item
357 my $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
359 borrowernumber => $hold_waiting_borrowernumber,
360 biblionumber => $biblio->biblionumber,
361 itemnumber => $item_1->itemnumber,
362 branchcode => $branch,
366 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
367 is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item');
370 # 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
371 # be able to renew these items
372 $hold = Koha::Database->new()->schema()->resultset('Reserve')->create(
374 borrowernumber => $hold_waiting_borrowernumber,
375 biblionumber => $biblio->biblionumber,
376 itemnumber => $item_3->itemnumber,
377 branchcode => $branch,
382 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
383 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
384 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
385 is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds');
386 t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 );
388 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
389 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
390 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
392 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
393 is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved');
394 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)');
396 my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id;
397 my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber )->unblessed;
398 AddIssue($reserving_borrower, $item_3->barcode);
399 my $reserve = $dbh->selectrow_hashref(
400 'SELECT * FROM old_reserves WHERE reserve_id = ?',
404 is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it');
406 # Item-level hold, renewal test
408 $branch, $reserving_borrowernumber, $biblio->biblionumber,
409 $bibitems, $priority, $resdate, $expdate, $notes,
410 'a title', $item_1->itemnumber, $found
413 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
414 is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved');
415 is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)');
417 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber, 1);
418 is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1');
420 # Items can't fill hold for reasons
421 ModItem({ notforloan => 1 }, $biblio->biblionumber, $item_1->itemnumber);
422 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
423 is( $renewokay, 1, 'Can renew, item is marked not for loan, hold does not block');
424 ModItem({ notforloan => 0, itype => $itemtype }, $biblio->biblionumber, $item_1->itemnumber);
426 # FIXME: Add more for itemtype not for loan etc.
428 # Restricted users cannot renew when RestrictionBlockRenewing is enabled
429 my $item_5 = $builder->build_sample_item(
431 biblionumber => $biblio->biblionumber,
433 replacementprice => 23.00,
437 my $datedue5 = AddIssue($restricted_borrower, $item_5->barcode);
438 is (defined $datedue5, 1, "Item with date due checked out, due date: $datedue5");
440 t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1');
441 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_2->itemnumber);
442 is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted');
443 ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrowernumber, $item_5->itemnumber);
444 is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted');
446 # Users cannot renew an overdue item
447 my $item_6 = $builder->build_sample_item(
449 biblionumber => $biblio->biblionumber,
451 replacementprice => 23.00,
456 my $item_7 = $builder->build_sample_item(
458 biblionumber => $biblio->biblionumber,
460 replacementprice => 23.00,
465 my $datedue6 = AddIssue( $renewing_borrower, $item_6->barcode);
466 is (defined $datedue6, 1, "Item 2 checked out, due date: ".$datedue6->date_due);
468 my $now = dt_from_string();
469 my $five_weeks = DateTime::Duration->new(weeks => 5);
470 my $five_weeks_ago = $now - $five_weeks;
471 t::lib::Mocks::mock_preference('finesMode', 'production');
473 my $passeddatedue1 = AddIssue($renewing_borrower, $item_7->barcode, $five_weeks_ago);
474 is (defined $passeddatedue1, 1, "Item with passed date due checked out, due date: " . $passeddatedue1->date_due);
476 my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower->{categorycode}, $branch, $five_weeks_ago, $now );
477 C4::Overdues::UpdateFine(
479 issue_id => $passeddatedue1->id(),
480 itemnumber => $item_7->itemnumber,
481 borrowernumber => $renewing_borrower->{borrowernumber},
483 due => Koha::DateUtils::output_pref($five_weeks_ago)
487 t::lib::Mocks::mock_preference('RenewalLog', 0);
488 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
489 my %params_renewal = (
490 timestamp => { -like => $date . "%" },
491 module => "CIRCULATION",
495 timestamp => { -like => $date . "%" },
496 module => "CIRCULATION",
499 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );
500 my $dt = dt_from_string();
501 Time::Fake->offset( $dt->epoch );
502 my $datedue1 = AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
503 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
504 is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog');
505 isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate");
508 t::lib::Mocks::mock_preference('RenewalLog', 1);
509 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
510 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
511 AddRenewal( $renewing_borrower->{borrowernumber}, $item_7->itemnumber, $branch );
512 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
513 is ($new_log_size, $old_log_size + 1, 'renew log successfully added');
515 my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
516 is( $fines->count, 2 );
517 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
518 isnt( $fines->next->status, 'UNRETURNED', 'Fine on renewed item is closed out properly' );
522 my $old_issue_log_size = Koha::ActionLogs->count( \%params_issue );
523 my $old_renew_log_size = Koha::ActionLogs->count( \%params_renewal );
524 AddIssue( $renewing_borrower,$item_7->barcode,Koha::DateUtils::output_pref({str=>$datedue6->date_due, dateformat =>'iso'}),0,$date, 0, undef );
525 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
526 is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing');
527 $new_log_size = Koha::ActionLogs->count( \%params_issue );
528 is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing');
530 $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower->{borrowernumber}, itemnumber => $item_7->itemnumber } );
533 t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem');
534 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
535 is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue');
536 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
537 is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue');
540 $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next;
544 # Test automatic renewal before value for "norenewalbefore" in policy is set
545 # In this case automatic renewal is not permitted prior to due date
546 my $item_4 = $builder->build_sample_item(
548 biblionumber => $biblio->biblionumber,
550 replacementprice => 16.00,
555 $issue = AddIssue( $renewing_borrower, $item_4->barcode, undef, undef, undef, undef, { auto_renew => 1 } );
556 ( $renewokay, $error ) =
557 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
558 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
559 is( $error, 'auto_too_soon',
560 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = undef (returned code is auto_too_soon)' );
563 # Test premature manual renewal
564 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7');
566 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
567 is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature');
568 is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)');
571 # Test 'exact time' setting for syspref NoRenewalBeforePrecision
572 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'exact_time' );
574 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
575 $datedue->clone->add( days => -7 ),
576 'Bug 14395: Renewals permitted 7 days before due date, as expected'
580 # Test 'date' setting for syspref NoRenewalBeforePrecision
581 t::lib::Mocks::mock_preference( 'NoRenewalBeforePrecision', 'date' );
583 GetSoonestRenewDate( $renewing_borrowernumber, $item_1->itemnumber ),
584 $datedue->clone->add( days => -7 )->truncate( to => 'day' ),
585 'Bug 14395: Renewals permitted 7 days before due date, as expected'
589 # Test premature automatic renewal
590 ( $renewokay, $error ) =
591 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
592 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
593 is( $error, 'auto_too_soon',
594 'Bug 14101: Cannot renew, renewal is automatic and premature (returned code is auto_too_soon)'
597 # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date)
598 # and test automatic renewal again
599 $dbh->do('UPDATE issuingrules SET norenewalbefore = 0');
600 ( $renewokay, $error ) =
601 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
602 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic and premature' );
603 is( $error, 'auto_too_soon',
604 'Bug 14101: Cannot renew, renewal is automatic and premature, "No renewal before" = 0 (returned code is auto_too_soon)'
607 # Change policy so that loans can be renewed 99 days prior to the due date
608 # and test automatic renewal again
609 $dbh->do('UPDATE issuingrules SET norenewalbefore = 99');
610 ( $renewokay, $error ) =
611 CanBookBeRenewed( $renewing_borrowernumber, $item_4->itemnumber );
612 is( $renewokay, 0, 'Bug 14101: Cannot renew, renewal is automatic' );
613 is( $error, 'auto_renew',
614 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)'
617 subtest "too_late_renewal / no_auto_renewal_after" => sub {
619 my $item_to_auto_renew = $builder->build(
622 biblionumber => $biblio->biblionumber,
623 homebranch => $branch,
624 holdingbranch => $branch,
629 my $ten_days_before = dt_from_string->add( days => -10 );
630 my $ten_days_ahead = dt_from_string->add( days => 10 );
631 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
633 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 9');
634 ( $renewokay, $error ) =
635 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
636 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
637 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
639 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 10');
640 ( $renewokay, $error ) =
641 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
642 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
643 is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' );
645 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = 11');
646 ( $renewokay, $error ) =
647 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
648 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
649 is( $error, 'auto_too_soon', 'Cannot auto renew, too soon - no_auto_renewal_after is defined(returned code is auto_too_soon)' );
651 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
652 ( $renewokay, $error ) =
653 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
654 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
655 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
657 $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 ) );
658 ( $renewokay, $error ) =
659 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
660 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
661 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
663 $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 ) );
664 ( $renewokay, $error ) =
665 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
666 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
667 is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' );
669 $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 ) );
670 ( $renewokay, $error ) =
671 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
672 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
673 is( $error, 'auto_renew', 'Cannot renew, renew is automatic' );
676 subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew" => sub {
678 my $item_to_auto_renew = $builder->build({
681 biblionumber => $biblio->biblionumber,
682 homebranch => $branch,
683 holdingbranch => $branch,
687 my $ten_days_before = dt_from_string->add( days => -10 );
688 my $ten_days_ahead = dt_from_string->add( days => 10 );
689 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
691 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
692 C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1');
693 C4::Context->set_preference('OPACFineNoRenewals','10');
694 my $fines_amount = 5;
695 my $account = Koha::Account->new({patron_id => $renewing_borrowernumber});
698 amount => $fines_amount,
701 item_id => $item_to_auto_renew->{itemnumber},
702 description => "Some fines"
704 )->status('RETURNED')->store;
705 ( $renewokay, $error ) =
706 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
707 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
708 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' );
712 amount => $fines_amount,
715 item_id => $item_to_auto_renew->{itemnumber},
716 description => "Some fines"
718 )->status('RETURNED')->store;
719 ( $renewokay, $error ) =
720 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
721 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
722 is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' );
726 amount => $fines_amount,
729 item_id => $item_to_auto_renew->{itemnumber},
730 description => "Some fines"
732 )->status('RETURNED')->store;
733 ( $renewokay, $error ) =
734 CanBookBeRenewed( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
735 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
736 is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' );
738 $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber);
741 subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub {
743 my $item_to_auto_renew = $builder->build({
746 biblionumber => $biblio->biblionumber,
747 homebranch => $branch,
748 holdingbranch => $branch,
752 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 11');
754 my $ten_days_before = dt_from_string->add( days => -10 );
755 my $ten_days_ahead = dt_from_string->add( days => 10 );
757 # Patron is expired and BlockExpiredPatronOpacActions=0
758 # => auto renew is allowed
759 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 0);
760 my $patron = $expired_borrower;
761 my $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
762 ( $renewokay, $error ) =
763 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
764 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
765 is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=0' );
766 Koha::Checkouts->find( $checkout->issue_id )->delete;
769 # Patron is expired and BlockExpiredPatronOpacActions=1
770 # => auto renew is not allowed
771 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
772 $patron = $expired_borrower;
773 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
774 ( $renewokay, $error ) =
775 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
776 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
777 is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' );
778 Koha::Checkouts->find( $checkout->issue_id )->delete;
781 # Patron is not expired and BlockExpiredPatronOpacActions=1
782 # => auto renew is allowed
783 t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 1);
784 $patron = $renewing_borrower;
785 $checkout = AddIssue( $patron, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
786 ( $renewokay, $error ) =
787 CanBookBeRenewed( $patron->{borrowernumber}, $item_to_auto_renew->{itemnumber} );
788 is( $renewokay, 0, 'Do not renew, renewal is automatic' );
789 is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=1 but patron is not expired' );
790 Koha::Checkouts->find( $checkout->issue_id )->delete;
793 subtest "GetLatestAutoRenewDate" => sub {
795 my $item_to_auto_renew = $builder->build(
798 biblionumber => $biblio->biblionumber,
799 homebranch => $branch,
800 holdingbranch => $branch,
805 my $ten_days_before = dt_from_string->add( days => -10 );
806 my $ten_days_ahead = dt_from_string->add( days => 10 );
807 AddIssue( $renewing_borrower, $item_to_auto_renew->{barcode}, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } );
808 $dbh->do('UPDATE issuingrules SET norenewalbefore = 7, no_auto_renewal_after = NULL, no_auto_renewal_after_hard_limit = NULL');
809 my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
810 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' );
811 my $five_days_before = dt_from_string->add( days => -5 );
812 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 5, no_auto_renewal_after_hard_limit = NULL');
813 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
814 is( $latest_auto_renew_date->truncate( to => 'minute' ),
815 $five_days_before->truncate( to => 'minute' ),
816 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before'
818 my $five_days_ahead = dt_from_string->add( days => 5 );
819 $dbh->do('UPDATE issuingrules SET norenewalbefore = 10, no_auto_renewal_after = 15, no_auto_renewal_after_hard_limit = NULL');
820 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
821 is( $latest_auto_renew_date->truncate( to => 'minute' ),
822 $five_days_ahead->truncate( to => 'minute' ),
823 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before'
825 my $two_days_ahead = dt_from_string->add( days => 2 );
826 $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 ) );
827 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
828 is( $latest_auto_renew_date->truncate( to => 'day' ),
829 $two_days_ahead->truncate( to => 'day' ),
830 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after'
832 $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 ) );
833 $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrowernumber, $item_to_auto_renew->{itemnumber} );
834 is( $latest_auto_renew_date->truncate( to => 'day' ),
835 $two_days_ahead->truncate( to => 'day' ),
836 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after'
843 # set policy to forbid renewals
844 $dbh->do('UPDATE issuingrules SET norenewalbefore = NULL, renewalsallowed = 0');
846 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber);
847 is( $renewokay, 0, 'Cannot renew, 0 renewals allowed');
848 is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)');
850 # Test WhenLostForgiveFine and WhenLostChargeReplacementFee
851 t::lib::Mocks::mock_preference('WhenLostForgiveFine','1');
852 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
854 C4::Overdues::UpdateFine(
856 issue_id => $issue->id(),
857 itemnumber => $item_1->itemnumber,
858 borrowernumber => $renewing_borrower->{borrowernumber},
861 due => Koha::DateUtils::output_pref($datedue)
865 my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower->{borrowernumber} })->next();
866 is( $line->accounttype, 'OVERDUE', 'Account line type is OVERDUE' );
867 is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' );
868 is( $line->amountoutstanding, '15.000000', 'Account line amount outstanding is 15.00' );
869 is( $line->amount, '15.000000', 'Account line amount is 15.00' );
870 is( $line->issue_id, $issue->id, 'Account line issue id matches' );
872 my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next();
873 is( $offset->type, 'OVERDUE', 'Account offset type is Fine' );
874 is( $offset->amount, '15.000000', 'Account offset amount is 15.00' );
876 t::lib::Mocks::mock_preference('WhenLostForgiveFine','0');
877 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0');
879 LostItem( $item_1->itemnumber, 'test', 1 );
881 $line = Koha::Account::Lines->find($line->id);
882 is( $line->accounttype, 'OVERDUE', 'Account type remains as OVERDUE' );
883 isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' );
885 my $item = Koha::Items->find($item_1->itemnumber);
886 ok( !$item->onloan(), "Lost item marked as returned has false onloan value" );
887 my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber });
888 is( $checkout, undef, 'LostItem called with forced return has checked in the item' );
890 my $total_due = $dbh->selectrow_array(
891 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
892 undef, $renewing_borrower->{borrowernumber}
895 is( $total_due, '15.000000', 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' );
897 C4::Context->dbh->do("DELETE FROM accountlines");
899 C4::Overdues::UpdateFine(
901 issue_id => $issue2->id(),
902 itemnumber => $item_2->itemnumber,
903 borrowernumber => $renewing_borrower->{borrowernumber},
906 due => Koha::DateUtils::output_pref($datedue)
910 LostItem( $item_2->itemnumber, 'test', 0 );
912 my $item2 = Koha::Items->find($item_2->itemnumber);
913 ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" );
914 ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' );
916 $total_due = $dbh->selectrow_array(
917 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?',
918 undef, $renewing_borrower->{borrowernumber}
921 ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' );
923 my $future = dt_from_string();
924 $future->add( days => 7 );
925 my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode});
926 ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' );
928 # Users cannot renew any item if there is an overdue item
929 t::lib::Mocks::mock_preference('OverduesBlockRenewing','block');
930 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_6->itemnumber);
931 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
932 ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_7->itemnumber);
933 is( $renewokay, 0, '(Bug 8236), Cannot renew, one of the items is overdue');
935 my $manager = $builder->build_object({ class => "Koha::Patrons" });
936 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
937 t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1');
938 $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } );
939 LostItem( $item_3->itemnumber, 'test', 0 );
940 my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } );
941 is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" );
943 $accountline->description,
945 $item_3->biblio->title || '',
946 $item_3->barcode || '',
947 $item_3->itemcallnumber || '' ),
948 "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber"
953 # GetUpcomingDueIssues tests
954 my $branch = $library2->{branchcode};
956 #Create another record
957 my $biblio2 = $builder->build_sample_biblio();
960 my $item_1 = Koha::Items->find($reused_itemnumber_1);
961 my $item_2 = Koha::Items->find($reused_itemnumber_2);
962 my $item_3 = $builder->build_sample_item(
964 biblionumber => $biblio2->biblionumber,
972 my %a_borrower_data = (
973 firstname => 'Fridolyn',
975 categorycode => $patron_category->{categorycode},
976 branchcode => $branch,
979 my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
980 my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber )->unblessed;
982 my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
983 my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 );
984 my $today = DateTime->today(time_zone => C4::Context->tz());
986 my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday );
987 my $datedue = dt_from_string( $issue->date_due() );
988 my $issue2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead );
989 my $datedue2 = dt_from_string( $issue->date_due() );
993 # GetUpcomingDueIssues tests
995 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
996 is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" );
999 #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc.
1000 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1001 is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" );
1004 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } );
1005 is ( scalar( @$upcoming_dues ), 1,
1006 "Bug 9362: Only one item due in more than 2 days ($i days in advance)" );
1009 # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well
1011 my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today );
1013 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } );
1014 is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" );
1016 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } );
1017 is ( scalar ( @$upcoming_dues), 1, "1 item is due today" );
1019 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } );
1020 is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" );
1022 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } );
1023 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1025 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } );
1026 is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" );
1028 $upcoming_dues = C4::Circulation::GetUpcomingDueIssues();
1029 is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" );
1034 my $branch = $library2->{branchcode};
1036 my $biblio = $builder->build_sample_biblio();
1039 my $item = $builder->build_sample_item(
1041 biblionumber => $biblio->biblionumber,
1048 my %a_borrower_data = (
1049 firstname => 'Kyle',
1051 categorycode => $patron_category->{categorycode},
1052 branchcode => $branch,
1055 my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber;
1057 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1058 my $issue = AddIssue( $borrower, $item->barcode );
1061 issue_id => $issue->id(),
1062 itemnumber => $item->itemnumber,
1063 borrowernumber => $borrowernumber,
1069 my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber );
1070 my $count = $hr->{count};
1072 is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" );
1076 $dbh->do('DELETE FROM issues');
1077 $dbh->do('DELETE FROM items');
1078 $dbh->do('DELETE FROM issuingrules');
1079 Koha::CirculationRules->search()->delete();
1082 INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
1083 norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
1092 Koha::CirculationRules->set_rules(
1094 categorycode => '*',
1102 my $biblio = $builder->build_sample_biblio();
1104 my $item_1 = $builder->build_sample_item(
1106 biblionumber => $biblio->biblionumber,
1107 library => $library2->{branchcode},
1112 my $item_2= $builder->build_sample_item(
1114 biblionumber => $biblio->biblionumber,
1115 library => $library2->{branchcode},
1120 my $borrowernumber1 = Koha::Patron->new({
1121 firstname => 'Kyle',
1123 categorycode => $patron_category->{categorycode},
1124 branchcode => $library2->{branchcode},
1125 })->store->borrowernumber;
1126 my $borrowernumber2 = Koha::Patron->new({
1127 firstname => 'Chelsea',
1129 categorycode => $patron_category->{categorycode},
1130 branchcode => $library2->{branchcode},
1131 })->store->borrowernumber;
1133 my $borrower1 = Koha::Patrons->find( $borrowernumber1 )->unblessed;
1134 my $borrower2 = Koha::Patrons->find( $borrowernumber2 )->unblessed;
1136 my $issue = AddIssue( $borrower1, $item_1->barcode );
1138 my ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1139 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with no hold on the record' );
1142 $library2->{branchcode}, $borrowernumber2, $biblio->biblionumber,
1143 '', 1, undef, undef, '',
1147 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1148 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
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 and onshelfholds are disabled' );
1152 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 0");
1153 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
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 enabled and onshelfholds is disabled' );
1157 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1158 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 );
1159 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1160 is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' );
1162 C4::Context->dbh->do("UPDATE issuingrules SET onshelfholds = 1");
1163 t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 );
1164 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1165 is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' );
1167 # Setting item not checked out to be not for loan but holdable
1168 ModItem({ notforloan => -1 }, $biblio->biblionumber, $item_2->itemnumber);
1170 ( $renewokay, $error ) = CanBookBeRenewed( $borrowernumber1, $item_1->itemnumber );
1171 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' );
1175 # Don't allow renewing onsite checkout
1176 my $branch = $library->{branchcode};
1178 #Create another record
1179 my $biblio = $builder->build_sample_biblio();
1181 my $item = $builder->build_sample_item(
1183 biblionumber => $biblio->biblionumber,
1189 my $borrowernumber = Koha::Patron->new({
1192 categorycode => $patron_category->{categorycode},
1193 branchcode => $branch,
1194 })->store->borrowernumber;
1196 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
1198 my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } );
1199 my ( $renewed, $error ) = CanBookBeRenewed( $borrowernumber, $item->itemnumber );
1200 is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' );
1201 is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' );
1205 my $library = $builder->build({ source => 'Branch' });
1207 my $biblio = $builder->build_sample_biblio();
1209 my $item = $builder->build_sample_item(
1211 biblionumber => $biblio->biblionumber,
1212 library => $library->{branchcode},
1217 my $patron = $builder->build({ source => 'Borrower', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } );
1219 my $issue = AddIssue( $patron, $item->barcode );
1222 issue_id => $issue->id(),
1223 itemnumber => $item->itemnumber,
1224 borrowernumber => $patron->{borrowernumber},
1231 issue_id => $issue->id(),
1232 itemnumber => $item->itemnumber,
1233 borrowernumber => $patron->{borrowernumber},
1238 is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine');
1241 subtest 'CanBookBeIssued & AllowReturnToBranch' => sub {
1244 my $homebranch = $builder->build( { source => 'Branch' } );
1245 my $holdingbranch = $builder->build( { source => 'Branch' } );
1246 my $otherbranch = $builder->build( { source => 'Branch' } );
1247 my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1248 my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1250 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1251 my $item = $builder->build(
1254 homebranch => $homebranch->{branchcode},
1255 holdingbranch => $holdingbranch->{branchcode},
1256 biblionumber => $biblioitem->{biblionumber}
1261 set_userenv($holdingbranch);
1263 my $issue = AddIssue( $patron_1->unblessed, $item->{barcode} );
1264 is( ref($issue), 'Koha::Checkout', 'AddIssue should return a Koha::Checkout object' );
1266 my ( $error, $question, $alerts );
1268 # AllowReturnToBranch == anywhere
1269 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1270 ## Test that unknown barcodes don't generate internal server errors
1271 set_userenv($homebranch);
1272 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, 'KohaIsAwesome' );
1273 ok( $error->{UNKNOWN_BARCODE}, '"KohaIsAwesome" is not a valid barcode as expected.' );
1274 ## Can be issued from homebranch
1275 set_userenv($homebranch);
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 holdingbranch
1280 set_userenv($holdingbranch);
1281 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1282 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1283 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1284 ## Can be issued from another branch
1285 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1286 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1287 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1289 # AllowReturnToBranch == holdingbranch
1290 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1291 ## Cannot be issued from homebranch
1292 set_userenv($homebranch);
1293 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1294 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1295 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1296 is( $error->{branch_to_return}, $holdingbranch->{branchcode} );
1297 ## Can be issued from holdinbranch
1298 set_userenv($holdingbranch);
1299 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1300 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1301 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1302 ## Cannot be issued from another branch
1303 set_userenv($otherbranch);
1304 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1305 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1306 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1307 is( $error->{branch_to_return}, $holdingbranch->{branchcode} );
1309 # AllowReturnToBranch == homebranch
1310 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1311 ## Can be issued from holdinbranch
1312 set_userenv($homebranch);
1313 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1314 is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1315 is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' );
1316 ## Cannot be issued from holdinbranch
1317 set_userenv($holdingbranch);
1318 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1319 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1320 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1321 is( $error->{branch_to_return}, $homebranch->{branchcode} );
1322 ## Cannot be issued from holdinbranch
1323 set_userenv($otherbranch);
1324 ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->{barcode} );
1325 is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) );
1326 is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' );
1327 is( $error->{branch_to_return}, $homebranch->{branchcode} );
1329 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1332 subtest 'AddIssue & AllowReturnToBranch' => sub {
1335 my $homebranch = $builder->build( { source => 'Branch' } );
1336 my $holdingbranch = $builder->build( { source => 'Branch' } );
1337 my $otherbranch = $builder->build( { source => 'Branch' } );
1338 my $patron_1 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1339 my $patron_2 = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1341 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1342 my $item = $builder->build(
1345 homebranch => $homebranch->{branchcode},
1346 holdingbranch => $holdingbranch->{branchcode},
1350 biblionumber => $biblioitem->{biblionumber}
1355 set_userenv($holdingbranch);
1357 my $ref_issue = 'Koha::Checkout';
1358 my $issue = AddIssue( $patron_1, $item->{barcode} );
1360 my ( $error, $question, $alerts );
1362 # AllowReturnToBranch == homebranch
1363 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' );
1364 ## Can be issued from homebranch
1365 set_userenv($homebranch);
1366 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1367 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1368 ## Can be issued from holdinbranch
1369 set_userenv($holdingbranch);
1370 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1371 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1372 ## Can be issued from another branch
1373 set_userenv($otherbranch);
1374 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1375 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1377 # AllowReturnToBranch == holdinbranch
1378 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' );
1379 ## Cannot be issued from homebranch
1380 set_userenv($homebranch);
1381 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1382 ## Can be issued from holdingbranch
1383 set_userenv($holdingbranch);
1384 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1385 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1386 ## Cannot be issued from another branch
1387 set_userenv($otherbranch);
1388 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1390 # AllowReturnToBranch == homebranch
1391 t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' );
1392 ## Can be issued from homebranch
1393 set_userenv($homebranch);
1394 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), $ref_issue );
1395 set_userenv($holdingbranch); AddIssue( $patron_1, $item->{barcode} ); # Reinsert the original issue
1396 ## Cannot be issued from holdinbranch
1397 set_userenv($holdingbranch);
1398 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1399 ## Cannot be issued from another branch
1400 set_userenv($otherbranch);
1401 is ( ref( AddIssue( $patron_2, $item->{barcode} ) ), '' );
1402 # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch');
1405 subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub {
1408 my $library = $builder->build( { source => 'Branch' } );
1409 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1411 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1412 my $item_1 = $builder->build(
1415 homebranch => $library->{branchcode},
1416 holdingbranch => $library->{branchcode},
1417 biblionumber => $biblioitem_1->{biblionumber}
1421 my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1422 my $item_2 = $builder->build(
1425 homebranch => $library->{branchcode},
1426 holdingbranch => $library->{branchcode},
1427 biblionumber => $biblioitem_2->{biblionumber}
1432 my ( $error, $question, $alerts );
1434 # Patron cannot issue item_1, they have overdues
1435 my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 );
1436 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, $yesterday ); # Add an overdue
1438 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' );
1439 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1440 is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) );
1441 is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' );
1443 t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' );
1444 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1445 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1446 is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' );
1448 # Patron cannot issue item_1, they are debarred
1449 my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
1450 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } );
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->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' );
1455 Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } );
1456 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1457 is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) );
1458 is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' );
1461 subtest 'CanBookBeIssued + Statistic patrons "X"' => sub {
1464 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1465 my $patron_category_x = $builder->build_object(
1467 class => 'Koha::Patron::Categories',
1468 value => { category_type => 'X' }
1471 my $patron = $builder->build_object(
1473 class => 'Koha::Patrons',
1475 categorycode => $patron_category_x->categorycode,
1476 gonenoaddress => undef,
1483 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1484 my $item_1 = $builder->build(
1488 homebranch => $library->branchcode,
1489 holdingbranch => $library->branchcode,
1490 biblionumber => $biblioitem_1->{biblionumber}
1495 my ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_1->{barcode} );
1496 is( $error->{STATS}, 1, '"Error" flag "STATS" must be set if CanBookBeIssued is called with a statistic patron (category_type=X)' );
1498 # TODO There are other tests to provide here
1501 subtest 'MultipleReserves' => sub {
1504 my $biblio = $builder->build_sample_biblio();
1506 my $branch = $library2->{branchcode};
1508 my $item_1 = $builder->build_sample_item(
1510 biblionumber => $biblio->biblionumber,
1512 replacementprice => 12.00,
1517 my $item_2 = $builder->build_sample_item(
1519 biblionumber => $biblio->biblionumber,
1521 replacementprice => 12.00,
1528 my $resdate = undef;
1529 my $expdate = undef;
1531 my $checkitem = undef;
1534 my %renewing_borrower_data = (
1535 firstname => 'John',
1536 surname => 'Renewal',
1537 categorycode => $patron_category->{categorycode},
1538 branchcode => $branch,
1540 my $renewing_borrowernumber = Koha::Patron->new(\%renewing_borrower_data)->store->borrowernumber;
1541 my $renewing_borrower = Koha::Patrons->find( $renewing_borrowernumber )->unblessed;
1542 my $issue = AddIssue( $renewing_borrower, $item_1->barcode);
1543 my $datedue = dt_from_string( $issue->date_due() );
1544 is (defined $issue->date_due(), 1, "item 1 checked out");
1545 my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber;
1547 my %reserving_borrower_data1 = (
1548 firstname => 'Katrin',
1549 surname => 'Reservation',
1550 categorycode => $patron_category->{categorycode},
1551 branchcode => $branch,
1553 my $reserving_borrowernumber1 = Koha::Patron->new(\%reserving_borrower_data1)->store->borrowernumber;
1555 $branch, $reserving_borrowernumber1, $biblio->biblionumber,
1556 $bibitems, $priority, $resdate, $expdate, $notes,
1557 'a title', $checkitem, $found
1560 my %reserving_borrower_data2 = (
1561 firstname => 'Kirk',
1562 surname => 'Reservation',
1563 categorycode => $patron_category->{categorycode},
1564 branchcode => $branch,
1566 my $reserving_borrowernumber2 = Koha::Patron->new(\%reserving_borrower_data2)->store->borrowernumber;
1568 $branch, $reserving_borrowernumber2, $biblio->biblionumber,
1569 $bibitems, $priority, $resdate, $expdate, $notes,
1570 'a title', $checkitem, $found
1574 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1575 is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing');
1578 my $item_3 = $builder->build_sample_item(
1580 biblionumber => $biblio->biblionumber,
1582 replacementprice => 12.00,
1588 my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrowernumber, $item_1->itemnumber, 1);
1589 is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available');
1593 subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub {
1596 my $library = $builder->build( { source => 'Branch' } );
1597 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
1599 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1600 my $biblionumber = $biblioitem->{biblionumber};
1601 my $item_1 = $builder->build(
1604 homebranch => $library->{branchcode},
1605 holdingbranch => $library->{branchcode},
1606 biblionumber => $biblionumber,
1610 my $item_2 = $builder->build(
1613 homebranch => $library->{branchcode},
1614 holdingbranch => $library->{branchcode},
1615 biblionumber => $biblionumber,
1620 my ( $error, $question, $alerts );
1621 my $issue = AddIssue( $patron->unblessed, $item_1->{barcode}, dt_from_string->add( days => 1 ) );
1623 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1624 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1625 is( keys(%$error) + keys(%$alerts), 0, 'No error or alert should be raised' . str($error, $question, $alerts) );
1626 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) );
1628 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1629 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1630 is( keys(%$error) + keys(%$question) + keys(%$alerts), 0, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' . str($error, $question, $alerts) );
1632 # Add a subscription
1633 Koha::Subscription->new({ biblionumber => $biblionumber })->store;
1635 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0);
1636 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1637 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 t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1);
1640 ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->{barcode} );
1641 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) );
1644 subtest 'AddReturn + CumulativeRestrictionPeriods' => sub {
1647 my $library = $builder->build( { source => 'Branch' } );
1648 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1651 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1652 my $item_1 = $builder->build(
1656 homebranch => $library->{branchcode},
1657 holdingbranch => $library->{branchcode},
1661 biblionumber => $biblioitem_1->{biblionumber}
1665 my $biblioitem_2 = $builder->build( { source => 'Biblioitem' } );
1666 my $item_2 = $builder->build(
1670 homebranch => $library->{branchcode},
1671 holdingbranch => $library->{branchcode},
1675 biblionumber => $biblioitem_2->{biblionumber}
1680 # And the issuing rule
1681 Koha::IssuingRules->search->delete;
1682 my $rule = Koha::IssuingRule->new(
1684 categorycode => '*',
1688 firstremind => 1, # 1 day of grace
1689 finedays => 2, # 2 days of fine per day of overdue
1690 lengthunit => 'days',
1695 # Patron cannot issue item_1, they have overdues
1696 my $five_days_ago = dt_from_string->subtract( days => 5 );
1697 my $ten_days_ago = dt_from_string->subtract( days => 10 );
1698 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
1699 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1700 ; # Add another overdue
1702 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' );
1703 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
1704 my $debarments = Koha::Patron::Debarments::GetDebarments(
1705 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1706 is( scalar(@$debarments), 1 );
1708 # FIXME Is it right? I'd have expected 5 * 2 - 1 instead
1709 # Same for the others
1710 my $expected_expiration = output_pref(
1712 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1713 dateformat => 'sql',
1717 is( $debarments->[0]->{expiration}, $expected_expiration );
1719 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
1720 $debarments = Koha::Patron::Debarments::GetDebarments(
1721 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1722 is( scalar(@$debarments), 1 );
1723 $expected_expiration = output_pref(
1725 dt => dt_from_string->add( days => ( 10 - 1 ) * 2 ),
1726 dateformat => 'sql',
1730 is( $debarments->[0]->{expiration}, $expected_expiration );
1732 Koha::Patron::Debarments::DelUniqueDebarment(
1733 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1735 t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' );
1736 AddIssue( $patron, $item_1->{barcode}, $five_days_ago ); # Add an overdue
1737 AddIssue( $patron, $item_2->{barcode}, $ten_days_ago )
1738 ; # Add another overdue
1739 AddReturn( $item_1->{barcode}, $library->{branchcode}, undef, dt_from_string );
1740 $debarments = Koha::Patron::Debarments::GetDebarments(
1741 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1742 is( scalar(@$debarments), 1 );
1743 $expected_expiration = output_pref(
1745 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 ),
1746 dateformat => 'sql',
1750 is( $debarments->[0]->{expiration}, $expected_expiration );
1752 AddReturn( $item_2->{barcode}, $library->{branchcode}, undef, dt_from_string );
1753 $debarments = Koha::Patron::Debarments::GetDebarments(
1754 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
1755 is( scalar(@$debarments), 1 );
1756 $expected_expiration = output_pref(
1758 dt => dt_from_string->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ),
1759 dateformat => 'sql',
1763 is( $debarments->[0]->{expiration}, $expected_expiration );
1766 subtest 'AddReturn + suspension_chargeperiod' => sub {
1769 my $library = $builder->build( { source => 'Branch' } );
1770 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1773 my $biblioitem_1 = $builder->build( { source => 'Biblioitem' } );
1774 my $item_1 = $builder->build(
1778 homebranch => $library->{branchcode},
1779 holdingbranch => $library->{branchcode},
1783 biblionumber => $biblioitem_1->{biblionumber}
1788 # And the issuing rule
1789 Koha::IssuingRules->search->delete;
1790 my $rule = Koha::IssuingRule->new(
1792 categorycode => '*',
1796 firstremind => 0, # 0 day of grace
1797 finedays => 2, # 2 days of fine per day of overdue
1798 suspension_chargeperiod => 1,
1799 lengthunit => 'days',
1804 my $five_days_ago = dt_from_string->subtract( days => 5 );
1805 # We want to charge 2 days every day, without grace
1806 # With 5 days of overdue: 5 * Z
1807 my $expected_expiration = dt_from_string->add( days => ( 5 * 2 ) / 1 );
1808 test_debarment_on_checkout(
1811 library => $library,
1813 due_date => $five_days_ago,
1814 expiration_date => $expected_expiration,
1818 # We want to charge 2 days every 2 days, without grace
1819 # With 5 days of overdue: (5 * 2) / 2
1820 $rule->suspension_chargeperiod(2)->store;
1821 $expected_expiration = dt_from_string->add( days => floor( 5 * 2 ) / 2 );
1822 test_debarment_on_checkout(
1825 library => $library,
1827 due_date => $five_days_ago,
1828 expiration_date => $expected_expiration,
1832 # We want to charge 2 days every 3 days, with 1 day of grace
1833 # With 5 days of overdue: ((5-1) / 3 ) * 2
1834 $rule->suspension_chargeperiod(3)->store;
1835 $rule->firstremind(1)->store;
1836 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 1 ) / 3 ) * 2 ) );
1837 test_debarment_on_checkout(
1840 library => $library,
1842 due_date => $five_days_ago,
1843 expiration_date => $expected_expiration,
1847 # Use finesCalendar to know if holiday must be skipped to calculate the due date
1848 # We want to charge 2 days every days, with 0 day of grace (to not burn brains)
1849 $rule->finedays(2)->store;
1850 $rule->suspension_chargeperiod(1)->store;
1851 $rule->firstremind(0)->store;
1852 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
1854 # Adding a holiday 2 days ago
1855 my $calendar = C4::Calendar->new(branchcode => $library->{branchcode});
1856 my $two_days_ago = dt_from_string->subtract( days => 2 );
1857 $calendar->insert_single_holiday(
1858 day => $two_days_ago->day,
1859 month => $two_days_ago->month,
1860 year => $two_days_ago->year,
1861 title => 'holidayTest-2d',
1862 description => 'holidayDesc 2 days ago'
1864 # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday)
1865 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) );
1866 test_debarment_on_checkout(
1869 library => $library,
1871 due_date => $five_days_ago,
1872 expiration_date => $expected_expiration,
1876 # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped
1877 my $two_days_ahead = dt_from_string->add( days => 2 );
1878 $calendar->insert_single_holiday(
1879 day => $two_days_ahead->day,
1880 month => $two_days_ahead->month,
1881 year => $two_days_ahead->year,
1882 title => 'holidayTest+2d',
1883 description => 'holidayDesc 2 days ahead'
1886 # Same as above, but we should skip D+2
1887 $expected_expiration = dt_from_string->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) + 1 );
1888 test_debarment_on_checkout(
1891 library => $library,
1893 due_date => $five_days_ago,
1894 expiration_date => $expected_expiration,
1898 # Adding another holiday, day of expiration date
1899 my $expected_expiration_dt = dt_from_string($expected_expiration);
1900 $calendar->insert_single_holiday(
1901 day => $expected_expiration_dt->day,
1902 month => $expected_expiration_dt->month,
1903 year => $expected_expiration_dt->year,
1904 title => 'holidayTest_exp',
1905 description => 'holidayDesc on expiration date'
1907 # Expiration date will be the day after
1908 test_debarment_on_checkout(
1911 library => $library,
1913 due_date => $five_days_ago,
1914 expiration_date => $expected_expiration_dt->clone->add( days => 1 ),
1918 test_debarment_on_checkout(
1921 library => $library,
1923 return_date => dt_from_string->add(days => 5),
1924 expiration_date => dt_from_string->add(days => 5 + (5 * 2 - 1) ),
1929 subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub {
1932 my $library = $builder->build( { source => 'Branch' } );
1933 my $patron1 = $builder->build_object(
1935 class => 'Koha::Patrons',
1937 branchcode => $library->{branchcode},
1938 firstname => "Happy",
1939 surname => "Gilmore",
1943 my $patron2 = $builder->build_object(
1945 class => 'Koha::Patrons',
1947 branchcode => $library->{branchcode},
1948 firstname => "Billy",
1949 surname => "Madison",
1954 C4::Context->_new_userenv('xxx');
1955 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, 'Random Library', '', '', '');
1957 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
1958 my $biblionumber = $biblioitem->{biblionumber};
1959 my $item = $builder->build(
1962 homebranch => $library->{branchcode},
1963 holdingbranch => $library->{branchcode},
1967 biblionumber => $biblionumber,
1972 my ( $error, $question, $alerts );
1973 my $issue = AddIssue( $patron1->unblessed, $item->{barcode} );
1975 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
1976 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
1977 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' );
1979 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1);
1980 ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->{barcode} );
1981 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' );
1983 t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0);
1987 subtest 'AddReturn | is_overdue' => sub {
1990 t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1);
1991 t::lib::Mocks::mock_preference('finesMode', 'production');
1992 t::lib::Mocks::mock_preference('MaxFine', '100');
1994 my $library = $builder->build( { source => 'Branch' } );
1995 my $patron = $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } );
1996 my $manager = $builder->build_object({ class => "Koha::Patrons" });
1997 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
1999 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2000 my $item_type = $builder->build_object(
2001 { class => 'Koha::ItemTypes',
2003 notforloan => undef,
2005 defaultreplacecost => undef,
2007 rentalcharge_daily => 0,
2011 my $item = $builder->build(
2015 homebranch => $library->{branchcode},
2016 holdingbranch => $library->{branchcode},
2020 biblionumber => $biblioitem->{biblionumber},
2021 replacementprice => 7,
2022 itype => $item_type->itemtype
2027 Koha::IssuingRules->search->delete;
2028 my $rule = Koha::IssuingRule->new(
2030 categorycode => '*',
2034 lengthunit => 'days',
2035 fine => 1, # Charge 1 every day of overdue
2041 my $now = dt_from_string;
2042 my $one_day_ago = dt_from_string->subtract( days => 1 );
2043 my $five_days_ago = dt_from_string->subtract( days => 5 );
2044 my $ten_days_ago = dt_from_string->subtract( days => 10 );
2045 $patron = Koha::Patrons->find( $patron->{borrowernumber} );
2047 # No return date specified, today will be used => 10 days overdue charged
2048 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2049 AddReturn( $item->{barcode}, $library->{branchcode} );
2050 is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' );
2051 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2053 # specify return date 5 days before => no overdue charged
2054 AddIssue( $patron->unblessed, $item->{barcode}, $five_days_ago ); # date due was 5d ago
2055 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $ten_days_ago );
2056 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2057 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2059 # specify return date 5 days later => 5 days overdue charged
2060 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2061 AddReturn( $item->{barcode}, $library->{branchcode}, undef, $five_days_ago );
2062 is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' );
2063 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2065 # specify return date 5 days later, specify exemptfine => no overdue charge
2066 AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2067 AddReturn( $item->{barcode}, $library->{branchcode}, 1, $five_days_ago );
2068 is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' );
2069 Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete;
2071 subtest 'bug 22877' => sub {
2075 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $ten_days_ago ); # date due was 10d ago
2077 # Fake fines cronjob on this checkout
2079 CalcFine( $item, $patron->categorycode, $library->{branchcode},
2080 $ten_days_ago, $now );
2083 issue_id => $issue->issue_id,
2084 itemnumber => $item->{itemnumber},
2085 borrowernumber => $patron->borrowernumber,
2087 due => output_pref($ten_days_ago)
2090 is( int( $patron->account->balance() ),
2091 10, "Overdue fine of 10 days overdue" );
2093 # Fake longoverdue with charge and not marking returned
2094 LostItem( $item->{itemnumber}, 'cronjob', 0 );
2095 is( int( $patron->account->balance() ),
2096 17, "Lost fine of 7 plus 10 days overdue" );
2098 # Now we return it today
2099 AddReturn( $item->{barcode}, $library->{branchcode} );
2100 is( int( $patron->account->balance() ),
2101 17, "Should have a single 10 days overdue fine and lost charge" );
2105 subtest '_FixAccountForLostAndReturned' => sub {
2109 t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 );
2110 t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 );
2112 my $processfee_amount = 20;
2113 my $replacement_amount = 99.00;
2114 my $item_type = $builder->build_object(
2115 { class => 'Koha::ItemTypes',
2117 notforloan => undef,
2119 defaultreplacecost => undef,
2120 processfee => $processfee_amount,
2121 rentalcharge_daily => 0,
2125 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
2127 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Daria' });
2129 subtest 'Full write-off tests' => sub {
2133 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2134 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2135 t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode });
2137 my $item = $builder->build_sample_item(
2139 biblionumber => $biblio->biblionumber,
2140 library => $library->branchcode,
2141 replacementprice => $replacement_amount,
2142 itype => $item_type->itemtype,
2146 AddIssue( $patron->unblessed, $item->barcode );
2148 # Simulate item marked as lost
2149 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2150 LostItem( $item->itemnumber, 1 );
2152 my $processing_fee_lines = Koha::Account::Lines->search(
2153 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2154 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2155 my $processing_fee_line = $processing_fee_lines->next;
2156 is( $processing_fee_line->amount + 0,
2157 $processfee_amount, 'The right PF amount is generated' );
2158 is( $processing_fee_line->amountoutstanding + 0,
2159 $processfee_amount, 'The right PF amountoutstanding is generated' );
2161 my $lost_fee_lines = Koha::Account::Lines->search(
2162 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2163 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2164 my $lost_fee_line = $lost_fee_lines->next;
2165 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2166 is( $lost_fee_line->amountoutstanding + 0,
2167 $replacement_amount, 'The right L amountoutstanding is generated' );
2169 my $account = $patron->account;
2170 my $debts = $account->outstanding_debits;
2172 # Write off the debt
2173 my $credit = $account->add_credit(
2174 { amount => $account->balance,
2176 interface => 'test',
2179 $credit->apply( { debits => $debts, offset_type => 'Writeoff' } );
2181 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2182 is( $credit_return_id, undef, 'No CR account line added' );
2184 $lost_fee_line->discard_changes; # reload from DB
2185 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2186 is( $lost_fee_line->accounttype,
2187 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2189 is( $patron->account->balance, -0, 'The patron balance is 0, everything was written off' );
2192 subtest 'Full payment tests' => sub {
2196 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2198 my $item = $builder->build_sample_item(
2200 biblionumber => $biblio->biblionumber,
2201 library => $library->branchcode,
2202 replacementprice => $replacement_amount,
2203 itype => $item_type->itemtype
2207 AddIssue( $patron->unblessed, $item->barcode );
2209 # Simulate item marked as lost
2210 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2211 LostItem( $item->itemnumber, 1 );
2213 my $processing_fee_lines = Koha::Account::Lines->search(
2214 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2215 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2216 my $processing_fee_line = $processing_fee_lines->next;
2217 is( $processing_fee_line->amount + 0,
2218 $processfee_amount, 'The right PF amount is generated' );
2219 is( $processing_fee_line->amountoutstanding + 0,
2220 $processfee_amount, 'The right PF amountoutstanding is generated' );
2222 my $lost_fee_lines = Koha::Account::Lines->search(
2223 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2224 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2225 my $lost_fee_line = $lost_fee_lines->next;
2226 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2227 is( $lost_fee_line->amountoutstanding + 0,
2228 $replacement_amount, 'The right L amountountstanding is generated' );
2230 my $account = $patron->account;
2231 my $debts = $account->outstanding_debits;
2233 # Write off the debt
2234 my $credit = $account->add_credit(
2235 { amount => $account->balance,
2237 interface => 'test',
2240 $credit->apply( { debits => $debts, offset_type => 'Payment' } );
2242 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2243 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2245 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2246 is( $credit_return->amount + 0,
2247 -99.00, 'The account line of type CR has an amount of -99' );
2248 is( $credit_return->amountoutstanding + 0,
2249 -99.00, 'The account line of type CR has an amountoutstanding of -99' );
2251 $lost_fee_line->discard_changes;
2252 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2253 is( $lost_fee_line->accounttype,
2254 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2256 is( $patron->account->balance,
2257 -99, 'The patron balance is -99, a credit that equals the lost fee payment' );
2260 subtest 'Test without payment or write off' => sub {
2264 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2266 my $item = $builder->build_sample_item(
2268 biblionumber => $biblio->biblionumber,
2269 library => $library->branchcode,
2270 replacementprice => 23.00,
2271 replacementprice => $replacement_amount,
2272 itype => $item_type->itemtype
2276 AddIssue( $patron->unblessed, $item->barcode );
2278 # Simulate item marked as lost
2279 ModItem( { itemlost => 3 }, $biblio->biblionumber, $item->itemnumber );
2280 LostItem( $item->itemnumber, 1 );
2282 my $processing_fee_lines = Koha::Account::Lines->search(
2283 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2284 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2285 my $processing_fee_line = $processing_fee_lines->next;
2286 is( $processing_fee_line->amount + 0,
2287 $processfee_amount, 'The right PF amount is generated' );
2288 is( $processing_fee_line->amountoutstanding + 0,
2289 $processfee_amount, 'The right PF amountoutstanding is generated' );
2291 my $lost_fee_lines = Koha::Account::Lines->search(
2292 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2293 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2294 my $lost_fee_line = $lost_fee_lines->next;
2295 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2296 is( $lost_fee_line->amountoutstanding + 0,
2297 $replacement_amount, 'The right L amountountstanding is generated' );
2299 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2300 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2302 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2303 is( $credit_return->amount + 0, -99.00, 'The account line of type CR has an amount of -99' );
2304 is( $credit_return->amountoutstanding + 0, 0, 'The account line of type CR has an amountoutstanding of 0' );
2306 $lost_fee_line->discard_changes;
2307 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2308 is( $lost_fee_line->accounttype, 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2310 is( $patron->account->balance, 20, 'The patron balance is 20, still owes the processing fee' );
2313 subtest 'Test with partial payement and write off, and remaining debt' => sub {
2317 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2318 my $item = $builder->build_sample_item(
2320 biblionumber => $biblio->biblionumber,
2321 library => $library->branchcode,
2322 replacementprice => $replacement_amount,
2323 itype => $item_type->itemtype
2327 AddIssue( $patron->unblessed, $item->barcode );
2329 # Simulate item marked as lost
2330 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item->itemnumber );
2331 LostItem( $item->itemnumber, 1 );
2333 my $processing_fee_lines = Koha::Account::Lines->search(
2334 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'PF' } );
2335 is( $processing_fee_lines->count, 1, 'Only one processing fee produced' );
2336 my $processing_fee_line = $processing_fee_lines->next;
2337 is( $processing_fee_line->amount + 0,
2338 $processfee_amount, 'The right PF amount is generated' );
2339 is( $processing_fee_line->amountoutstanding + 0,
2340 $processfee_amount, 'The right PF amountoutstanding is generated' );
2342 my $lost_fee_lines = Koha::Account::Lines->search(
2343 { borrowernumber => $patron->id, itemnumber => $item->itemnumber, accounttype => 'L' } );
2344 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2345 my $lost_fee_line = $lost_fee_lines->next;
2346 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2347 is( $lost_fee_line->amountoutstanding + 0,
2348 $replacement_amount, 'The right L amountountstanding is generated' );
2350 my $account = $patron->account;
2351 is( $account->balance, $processfee_amount + $replacement_amount, 'Balance is PF + L' );
2354 my $payment_amount = 27;
2355 my $payment = $account->add_credit(
2356 { amount => $payment_amount,
2358 interface => 'test',
2362 $payment->apply( { debits => $lost_fee_lines->reset, offset_type => 'Payment' } );
2364 # Partially write off fee
2365 my $write_off_amount = 25;
2366 my $write_off = $account->add_credit(
2367 { amount => $write_off_amount,
2369 interface => 'test',
2372 $write_off->apply( { debits => $lost_fee_lines->reset, offset_type => 'Writeoff' } );
2374 is( $account->balance,
2375 $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount,
2376 'Payment and write off applied'
2379 # Store the amountoutstanding value
2380 $lost_fee_line->discard_changes;
2381 my $outstanding = $lost_fee_line->amountoutstanding;
2383 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item->itemnumber, $patron->id );
2384 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2386 is( $account->balance, $processfee_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2388 $lost_fee_line->discard_changes;
2389 is( $lost_fee_line->amountoutstanding + 0, 0, 'Lost fee has no outstanding amount' );
2390 is( $lost_fee_line->accounttype,
2391 'LR', 'Lost fee now has account type of LR ( Lost Returned )' );
2393 is( $credit_return->accounttype, 'CR', 'An account line of type CR is added' );
2394 is( $credit_return->amount + 0,
2395 ($payment_amount + $outstanding ) * -1,
2396 'The account line of type CR has an amount equal to the payment + outstanding'
2398 is( $credit_return->amountoutstanding + 0,
2399 $payment_amount * -1,
2400 'The account line of type CR has an amountoutstanding equal to the payment'
2403 is( $account->balance,
2404 $processfee_amount - $payment_amount,
2405 'The patron balance is the difference between the PF and the credit'
2409 subtest 'Partial payement, existing debits and AccountAutoReconcile' => sub {
2413 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2414 my $barcode = 'KD123456793';
2415 my $replacement_amount = 100;
2416 my $processfee_amount = 20;
2418 my $item_type = $builder->build_object(
2419 { class => 'Koha::ItemTypes',
2421 notforloan => undef,
2423 defaultreplacecost => undef,
2425 rentalcharge_daily => 0,
2429 my ( undef, undef, $item_id ) = AddItem(
2430 { homebranch => $library->branchcode,
2431 holdingbranch => $library->branchcode,
2432 barcode => $barcode,
2433 replacementprice => $replacement_amount,
2434 itype => $item_type->itemtype
2436 $biblio->biblionumber
2439 AddIssue( $patron->unblessed, $barcode );
2441 # Simulate item marked as lost
2442 ModItem( { itemlost => 1 }, $biblio->biblionumber, $item_id );
2443 LostItem( $item_id, 1 );
2445 my $lost_fee_lines = Koha::Account::Lines->search(
2446 { borrowernumber => $patron->id, itemnumber => $item_id, accounttype => 'L' } );
2447 is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' );
2448 my $lost_fee_line = $lost_fee_lines->next;
2449 is( $lost_fee_line->amount + 0, $replacement_amount, 'The right L amount is generated' );
2450 is( $lost_fee_line->amountoutstanding + 0,
2451 $replacement_amount, 'The right L amountountstanding is generated' );
2453 my $account = $patron->account;
2454 is( $account->balance, $replacement_amount, 'Balance is L' );
2457 my $payment_amount = 27;
2458 my $payment = $account->add_credit(
2459 { amount => $payment_amount,
2461 interface => 'test',
2464 $payment->apply({ debits => $lost_fee_lines->reset, offset_type => 'Payment' });
2466 is( $account->balance,
2467 $replacement_amount - $payment_amount,
2471 my $manual_debit_amount = 80;
2472 $account->add_debit( { amount => $manual_debit_amount, type => 'overdue', interface =>'test' } );
2474 is( $account->balance, $manual_debit_amount + $replacement_amount - $payment_amount, 'Manual debit applied' );
2476 t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
2478 my $credit_return_id = C4::Circulation::_FixAccountForLostAndReturned( $item_id, $patron->id );
2479 my $credit_return = Koha::Account::Lines->find($credit_return_id);
2481 is( $account->balance, $manual_debit_amount - $payment_amount, 'Balance is PF - payment (CR)' );
2483 my $manual_debit = Koha::Account::Lines->search({ borrowernumber => $patron->id, accounttype => 'OVERDUE', status => 'UNRETURNED' })->next;
2484 is( $manual_debit->amountoutstanding + 0, $manual_debit_amount - $payment_amount, 'reconcile_balance was called' );
2488 subtest '_FixOverduesOnReturn' => sub {
2491 my $manager = $builder->build_object({ class => "Koha::Patrons" });
2492 t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode });
2494 my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' });
2496 my $branchcode = $library2->{branchcode};
2498 my $item = $builder->build_sample_item(
2500 biblionumber => $biblio->biblionumber,
2501 library => $branchcode,
2502 replacementprice => 99.00,
2507 my $patron = $builder->build( { source => 'Borrower' } );
2509 ## Start with basic call, should just close out the open fine
2510 my $accountline = Koha::Account::Line->new(
2512 borrowernumber => $patron->{borrowernumber},
2513 accounttype => 'OVERDUE',
2514 status => 'UNRETURNED',
2515 itemnumber => $item->itemnumber,
2517 amountoutstanding => 99.00,
2518 interface => 'test',
2522 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber );
2524 $accountline->_result()->discard_changes();
2526 is( $accountline->amountoutstanding, '99.000000', 'Fine has the same amount outstanding as previously' );
2527 is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status RETURNED )');
2529 ## Run again, with exemptfine enabled
2532 accounttype => 'OVERDUE',
2533 status => 'UNRETURNED',
2534 amountoutstanding => 99.00,
2538 C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1 );
2540 $accountline->_result()->discard_changes();
2541 my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'Forgiven' })->next();
2543 is( $accountline->amountoutstanding + 0, 0, 'Fine has been reduced to 0' );
2544 is( $accountline->status, 'FORGIVEN', 'Open fine ( account type OVERDUE ) has been set to fine forgiven ( status FORGIVEN )');
2545 is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" );
2546 is( $offset->amount, '-99.000000', "Amount of offset is correct" );
2547 my $credit = $offset->credit;
2548 is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" );
2549 is( $credit->amount, '-99.000000', "Credit amount is set correctly" );
2550 is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" );
2553 subtest 'Set waiting flag' => sub {
2556 my $library_1 = $builder->build( { source => 'Branch' } );
2557 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2558 my $library_2 = $builder->build( { source => 'Branch' } );
2559 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2561 my $biblio = $builder->build( { source => 'Biblio' } );
2562 my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2564 my $item = $builder->build(
2568 homebranch => $library_1->{branchcode},
2569 holdingbranch => $library_1->{branchcode},
2573 biblionumber => $biblioitem->{biblionumber},
2578 set_userenv( $library_2 );
2579 my $reserve_id = AddReserve(
2580 $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber},
2581 '', 1, undef, undef, '', undef, $item->{itemnumber},
2584 set_userenv( $library_1 );
2585 my $do_transfer = 1;
2586 my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2587 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2588 my $hold = Koha::Holds->find( $reserve_id );
2589 is( $hold->found, 'T', 'Hold is in transit' );
2591 my ( $status ) = CheckReserves($item->{itemnumber});
2592 is( $status, 'Reserved', 'Hold is not waiting yet');
2594 set_userenv( $library_2 );
2596 AddReturn( $item->{barcode}, $library_2->{branchcode} );
2597 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2598 $hold = Koha::Holds->find( $reserve_id );
2599 is( $hold->found, 'W', 'Hold is waiting' );
2600 ( $status ) = CheckReserves($item->{itemnumber});
2601 is( $status, 'Waiting', 'Now the hold is waiting');
2604 subtest 'Cancel transfers on lost items' => sub {
2606 my $library_1 = $builder->build( { source => 'Branch' } );
2607 my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2608 my $library_2 = $builder->build( { source => 'Branch' } );
2609 my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } );
2610 my $biblio = $builder->build( { source => 'Biblio' } );
2611 my $biblioitem = $builder->build( { source => 'Biblioitem', value => { biblionumber => $biblio->{biblionumber} } } );
2612 my $item = $builder->build(
2616 homebranch => $library_1->{branchcode},
2617 holdingbranch => $library_1->{branchcode},
2621 biblionumber => $biblioitem->{biblionumber},
2626 set_userenv( $library_2 );
2627 my $reserve_id = AddReserve(
2628 $library_2->{branchcode}, $patron_2->{borrowernumber}, $biblioitem->{biblionumber}, '', 1, undef, undef, '', undef, $item->{itemnumber},
2631 #Return book and add transfer
2632 set_userenv( $library_1 );
2633 my $do_transfer = 1;
2634 my ( $res, $rr ) = AddReturn( $item->{barcode}, $library_1->{branchcode} );
2635 ModReserveAffect( $item->{itemnumber}, undef, $do_transfer, $reserve_id );
2636 C4::Circulation::transferbook( $library_2->{branchcode}, $item->{barcode} );
2637 my $hold = Koha::Holds->find( $reserve_id );
2638 is( $hold->found, 'T', 'Hold is in transit' );
2640 #Check transfer exists and the items holding branch is the transfer destination branch before marking it as lost
2641 my ($datesent,$frombranch,$tobranch) = GetTransfers($item->{itemnumber});
2642 is( $tobranch, $library_2->{branchcode}, 'The transfer record exists in the branchtransfers table');
2643 my $itemcheck = Koha::Items->find($item->{itemnumber});
2644 is( $itemcheck->holdingbranch, $library_2->{branchcode}, 'Items holding branch is the transfers destination branch before it is marked as lost' );
2646 #Simulate item being marked as lost and confirm the transfer is deleted and the items holding branch is the transfers source branch
2647 ModItem( { itemlost => 1 }, $biblio->{biblionumber}, $item->{itemnumber} );
2648 LostItem( $item->{itemnumber}, 'test', 1 );
2649 ($datesent,$frombranch,$tobranch) = GetTransfers($item->{itemnumber});
2650 is( $tobranch, undef, 'The transfer on the lost item has been deleted as the LostItemCancelOutstandingTransfer is enabled');
2651 $itemcheck = Koha::Items->find($item->{itemnumber});
2652 is( $itemcheck->holdingbranch, $library_1->{branchcode}, 'Lost item with cancelled hold has holding branch equallying the transfers source branch' );
2655 subtest 'CanBookBeIssued | is_overdue' => sub {
2658 # Set a simple circ policy
2659 $dbh->do('DELETE FROM issuingrules');
2661 q{INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed,
2662 issuelength, lengthunit,
2663 renewalsallowed, renewalperiod,
2664 norenewalbefore, auto_renew,
2681 my $five_days_go = output_pref({ dt => dt_from_string->add( days => 5 ), dateonly => 1});
2682 my $ten_days_go = output_pref({ dt => dt_from_string->add( days => 10), dateonly => 1 });
2683 my $library = $builder->build( { source => 'Branch' } );
2684 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } );
2686 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2687 my $item = $builder->build(
2691 homebranch => $library->{branchcode},
2692 holdingbranch => $library->{branchcode},
2696 biblionumber => $biblioitem->{biblionumber},
2701 my $issue = AddIssue( $patron->unblessed, $item->{barcode}, $five_days_go ); # date due was 10d ago
2702 my $actualissue = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } );
2703 is( output_pref({ str => $actualissue->date_due, dateonly => 1}), $five_days_go, "First issue works");
2704 my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron,$item->{barcode},$ten_days_go, undef, undef, undef);
2705 is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal");
2706 is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal");
2709 subtest 'ItemsDeniedRenewal preference' => sub {
2712 C4::Context->set_preference('ItemsDeniedRenewal','');
2714 my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'});
2717 INSERT INTO issuingrules ( categorycode, branchcode, itemtype, reservesallowed, issuelength, lengthunit, renewalsallowed, renewalperiod,
2718 norenewalbefore, auto_renew, fine, chargeperiod ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
2721 '*', $idr_lib->branchcode, '*', 25,
2728 my $deny_book = $builder->build_object({ class => 'Koha::Items', value => {
2729 homebranch => $idr_lib->branchcode,
2733 itemcallnumber => undef,
2737 my $allow_book = $builder->build_object({ class => 'Koha::Items', value => {
2738 homebranch => $idr_lib->branchcode,
2741 location => 'NOPROC'
2745 my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> {
2746 branchcode => $idr_lib->branchcode,
2749 my $future = dt_from_string->add( days => 1 );
2750 my $deny_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2751 returndate => undef,
2754 borrowernumber => $idr_borrower->borrowernumber,
2755 itemnumber => $deny_book->itemnumber,
2756 onsite_checkout => 0,
2757 date_due => $future,
2760 my $allow_issue = $builder->build_object({ class => 'Koha::Checkouts', value => {
2761 returndate => undef,
2764 borrowernumber => $idr_borrower->borrowernumber,
2765 itemnumber => $allow_book->itemnumber,
2766 onsite_checkout => 0,
2767 date_due => $future,
2773 my ( $idr_mayrenew, $idr_error ) =
2774 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2775 is( $idr_mayrenew, 1, 'Renewal allowed when no rules' );
2776 is( $idr_error, undef, 'Renewal allowed when no rules' );
2778 $idr_rules="withdrawn: [1]";
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, 0, 'Renewal blocked when 1 rules (withdrawn)' );
2784 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 1 rule (withdrawn)' );
2785 ( $idr_mayrenew, $idr_error ) =
2786 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2787 is( $idr_mayrenew, 1, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2788 is( $idr_error, undef, 'Renewal allowed when 1 rules not matched (withdrawn)' );
2790 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]";
2792 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2793 ( $idr_mayrenew, $idr_error ) =
2794 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2795 is( $idr_mayrenew, 0, 'Renewal blocked when 2 rules matched (withdrawn, itype)' );
2796 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 2 rules matched (withdrawn,itype)' );
2797 ( $idr_mayrenew, $idr_error ) =
2798 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2799 is( $idr_mayrenew, 1, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2800 is( $idr_error, undef, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' );
2802 $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]";
2804 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2805 ( $idr_mayrenew, $idr_error ) =
2806 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2807 is( $idr_mayrenew, 0, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' );
2808 is( $idr_error, 'item_denied_renewal', 'Renewal blocked when 3 rules matched (withdrawn,itype, location)' );
2809 ( $idr_mayrenew, $idr_error ) =
2810 CanBookBeRenewed( $idr_borrower->borrowernumber, $allow_issue->itemnumber );
2811 is( $idr_mayrenew, 1, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2812 is( $idr_error, undef, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' );
2814 $idr_rules="itemcallnumber: [NULL]";
2815 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2816 ( $idr_mayrenew, $idr_error ) =
2817 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2818 is( $idr_mayrenew, 0, 'Renewal blocked for undef when NULL in pref' );
2819 $idr_rules="itemcallnumber: ['']";
2820 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2821 ( $idr_mayrenew, $idr_error ) =
2822 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2823 is( $idr_mayrenew, 1, 'Renewal not blocked for undef when "" in pref' );
2825 $idr_rules="itemnotes: [NULL]";
2826 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2827 ( $idr_mayrenew, $idr_error ) =
2828 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2829 is( $idr_mayrenew, 1, 'Renewal not blocked for "" when NULL in pref' );
2830 $idr_rules="itemnotes: ['']";
2831 C4::Context->set_preference('ItemsDeniedRenewal',$idr_rules);
2832 ( $idr_mayrenew, $idr_error ) =
2833 CanBookBeRenewed( $idr_borrower->borrowernumber, $deny_issue->itemnumber );
2834 is( $idr_mayrenew, 0, 'Renewal blocked for empty string when "" in pref' );
2837 subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub {
2840 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2841 my $library = $builder->build( { source => 'Branch' } );
2842 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2844 my $itemtype = $builder->build(
2846 source => 'Itemtype',
2847 value => { notforloan => undef, }
2851 my $biblioitem = $builder->build( { source => 'Biblioitem', value => { itemtype => $itemtype->{itemtype} } } );
2852 my $item = $builder->build_object(
2854 class => 'Koha::Items',
2856 homebranch => $library->{branchcode},
2857 holdingbranch => $library->{branchcode},
2861 biblionumber => $biblioitem->{biblionumber},
2862 biblioitemnumber => $biblioitem->{biblioitemnumber},
2867 my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2868 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2869 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2872 subtest 'CanBookBeIssued | notforloan' => sub {
2875 t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0);
2877 my $library = $builder->build( { source => 'Branch' } );
2878 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } )->store;
2880 my $itemtype = $builder->build(
2882 source => 'Itemtype',
2883 value => { notforloan => undef, }
2887 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
2888 my $item = $builder->build_object(
2890 class => 'Koha::Items',
2892 homebranch => $library->{branchcode},
2893 holdingbranch => $library->{branchcode},
2897 itype => $itemtype->{itemtype},
2898 biblionumber => $biblioitem->{biblionumber},
2899 biblioitemnumber => $biblioitem->{biblioitemnumber},
2904 my ( $issuingimpossible, $needsconfirmation );
2907 subtest 'item-level_itypes = 1' => sub {
2910 t::lib::Mocks::mock_preference('item-level_itypes', 1); # item
2911 # Is for loan at item type and item level
2912 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2913 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2914 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2916 # not for loan at item type level
2917 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2918 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2919 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2922 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2923 'Item can not be issued, not for loan at item type level'
2926 # not for loan at item level
2927 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2928 $item->notforloan( 1 )->store;
2929 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2930 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2933 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2934 'Item can not be issued, not for loan at item type level'
2938 subtest 'item-level_itypes = 0' => sub {
2941 t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio
2943 # We set another itemtype for biblioitem
2944 my $itemtype = $builder->build(
2946 source => 'Itemtype',
2947 value => { notforloan => undef, }
2951 # for loan at item type and item level
2952 $item->notforloan(0)->store;
2953 $item->biblioitem->itemtype($itemtype->{itemtype})->store;
2954 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2955 is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' );
2956 is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' );
2958 # not for loan at item type level
2959 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store;
2960 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2961 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2964 { NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->{itemtype} },
2965 'Item can not be issued, not for loan at item type level'
2968 # not for loan at item level
2969 Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(undef)->store;
2970 $item->notforloan( 1 )->store;
2971 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef );
2972 is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' );
2975 { NOT_FOR_LOAN => 1, item_notforloan => 1 },
2976 'Item can not be issued, not for loan at item type level'
2980 # TODO test with AllowNotForLoanOverride = 1
2983 subtest 'AddReturn should clear items.onloan for unissued items' => sub {
2986 t::lib::Mocks::mock_preference( "AllowReturnToBranch", 'anywhere' );
2987 my $item = $builder->build_object({ class => 'Koha::Items', value => { onloan => '2018-01-01' }});
2988 AddReturn( $item->barcode, $item->homebranch );
2989 $item->discard_changes; # refresh
2990 is( $item->onloan, undef, 'AddReturn did clear items.onloan' );
2993 $schema->storage->txn_rollback;
2994 C4::Context->clear_syspref_cache();
2995 $cache->clear_from_cache('single_holidays');
2997 subtest 'AddRenewal and AddIssuingCharge tests' => sub {
3001 $schema->storage->txn_begin;
3003 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3005 my $issuing_charges = 15;
3006 my $title = 'A title';
3007 my $author = 'Author, An';
3008 my $barcode = 'WHATARETHEODDS';
3010 my $circ = Test::MockModule->new('C4::Circulation');
3012 'GetIssuingCharges',
3014 return $issuing_charges;
3018 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3019 my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }});
3020 my $patron = $builder->build_object({
3021 class => 'Koha::Patrons',
3022 value => { branchcode => $library->id }
3025 my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author });
3026 my ( undef, undef, $item_id ) = AddItem(
3028 homebranch => $library->id,
3029 holdingbranch => $library->id,
3030 barcode => $barcode,
3031 replacementprice => 23.00,
3032 itype => $itemtype->id
3034 $biblio->biblionumber
3036 my $item = Koha::Items->find( $item_id );
3038 my $context = Test::MockModule->new('C4::Context');
3039 $context->mock( userenv => { branch => $library->id } );
3041 # Check the item out
3042 AddIssue( $patron->unblessed, $item->barcode );
3043 t::lib::Mocks::mock_preference( 'RenewalLog', 0 );
3044 my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3045 my %params_renewal = (
3046 timestamp => { -like => $date . "%" },
3047 module => "CIRCULATION",
3048 action => "RENEWAL",
3050 my $old_log_size = Koha::ActionLogs->count( \%params_renewal );;
3051 AddRenewal( $patron->id, $item->id, $library->id );
3052 my $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3053 is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' );
3055 my $checkouts = $patron->checkouts;
3056 # The following will fail if run on 00:00:00
3057 unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part');
3059 t::lib::Mocks::mock_preference( 'RenewalLog', 1 );
3060 $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } );
3061 $old_log_size = Koha::ActionLogs->count( \%params_renewal );
3062 AddRenewal( $patron->id, $item->id, $library->id );
3063 $new_log_size = Koha::ActionLogs->count( \%params_renewal );
3064 is( $new_log_size, $old_log_size + 1, 'renew log successfully added' );
3066 my $lines = Koha::Account::Lines->search({
3067 borrowernumber => $patron->id,
3068 itemnumber => $item->id
3071 is( $lines->count, 3 );
3073 my $line = $lines->next;
3074 is( $line->accounttype, 'Rent', 'The issuing charge generates an accountline' );
3075 is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' );
3076 is( $line->description, 'Rental', 'AddIssuingCharge set a hardcoded description for the accountline' );
3078 $line = $lines->next;
3079 is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
3080 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
3081 is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
3083 $line = $lines->next;
3084 is( $line->accounttype, 'Rent', 'Fine on renewed item is closed out properly' );
3085 is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' );
3086 is( $line->description, "Renewal of Rental Item $title $barcode", 'AddRenewal set a hardcoded description for the accountline' );
3088 $schema->storage->txn_rollback;
3091 subtest 'ProcessOfflinePayment() tests' => sub {
3095 $schema->storage->txn_begin;
3099 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
3100 my $library = $builder->build_object({ class => 'Koha::Libraries' });
3101 my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id });
3103 is( $result, 'Success.', 'The right string is returned' );
3105 my $lines = $patron->account->lines;
3106 is( $lines->count, 1, 'line created correctly');
3108 my $line = $lines->next;
3109 is( $line->amount+0, $amount * -1, 'amount picked from params' );
3110 is( $line->branchcode, $library->id, 'branchcode set correctly' );
3112 $schema->storage->txn_rollback;
3118 my ( $library ) = @_;
3119 t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
3123 my ( $error, $question, $alert ) = @_;
3125 $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : '';
3126 $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : '';
3127 $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : '';
3131 sub test_debarment_on_checkout {
3133 my $item = $params->{item};
3134 my $library = $params->{library};
3135 my $patron = $params->{patron};
3136 my $due_date = $params->{due_date} || dt_from_string;
3137 my $return_date = $params->{return_date} || dt_from_string;
3138 my $expected_expiration_date = $params->{expiration_date};
3140 $expected_expiration_date = output_pref(
3142 dt => $expected_expiration_date,
3143 dateformat => 'sql',
3147 my @caller = caller;
3148 my $line_number = $caller[2];
3149 AddIssue( $patron, $item->{barcode}, $due_date );
3151 my ( undef, $message ) = AddReturn( $item->{barcode}, $library->{branchcode}, undef, $return_date );
3152 is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' )
3153 or diag('AddReturn returned message ' . Dumper $message );
3154 my $debarments = Koha::Patron::Debarments::GetDebarments(
3155 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
3156 is( scalar(@$debarments), 1, 'Test at line ' . $line_number );
3158 is( $debarments->[0]->{expiration},
3159 $expected_expiration_date, 'Test at line ' . $line_number );
3160 Koha::Patron::Debarments::DelUniqueDebarment(
3161 { borrowernumber => $patron->{borrowernumber}, type => 'SUSPENSION' } );
3164 subtest 'Incremented fee tests' => sub {
3167 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3169 my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store;
3171 my $module = new Test::MockModule('C4::Context');
3172 $module->mock('userenv', sub { { branch => $library->id } });
3174 my $patron = $builder->build_object(
3176 class => 'Koha::Patrons',
3177 value => { categorycode => $patron_category->{categorycode} }
3181 my $itemtype = $builder->build_object(
3183 class => 'Koha::ItemTypes',
3185 notforloan => undef,
3187 rentalcharge_daily => 1.000000
3192 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3193 my $item = $builder->build_object(
3195 class => 'Koha::Items',
3197 homebranch => $library->id,
3198 holdingbranch => $library->id,
3202 itype => $itemtype->id,
3203 biblionumber => $biblioitem->{biblionumber},
3204 biblioitemnumber => $biblioitem->{biblioitemnumber},
3209 is( $itemtype->rentalcharge_daily, '1.000000', 'Daily rental charge stored and retreived correctly' );
3210 is( $item->effective_itemtype, $itemtype->id, "Itemtype set correctly for item");
3212 my $dt_from = dt_from_string();
3213 my $dt_to = dt_from_string()->add( days => 7 );
3214 my $dt_to_renew = dt_from_string()->add( days => 13 );
3216 t::lib::Mocks::mock_preference('finesCalendar', 'ignoreCalendar');
3217 my $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3218 my $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3219 is( $accountline->amount, '7.000000', "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar" );
3220 $accountline->delete();
3221 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3222 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3223 is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = ignoreCalendar, for renewal" );
3224 $accountline->delete();
3227 t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed');
3228 $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3229 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3230 is( $accountline->amount, '7.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed" );
3231 $accountline->delete();
3232 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3233 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3234 is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed, for renewal" );
3235 $accountline->delete();
3238 my $calendar = C4::Calendar->new( branchcode => $library->id );
3239 $calendar->insert_week_day_holiday(
3241 title => 'Test holiday',
3242 description => 'Test holiday'
3244 $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from );
3245 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3246 is( $accountline->amount, '6.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays" );
3247 $accountline->delete();
3248 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3249 $accountline = Koha::Account::Lines->find({ itemnumber => $item->id });
3250 is( $accountline->amount, '5.000000', "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed Wednesdays, for renewal" );
3251 $accountline->delete();
3254 $itemtype->rentalcharge('2.000000')->store;
3255 is( $itemtype->rentalcharge, '2.000000', 'Rental charge updated and retreived correctly' );
3256 $issue = AddIssue( $patron->unblessed, $item->barcode, $dt_to, undef, $dt_from);
3257 my $accountlines = Koha::Account::Lines->search({ itemnumber => $item->id });
3258 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly");
3259 $accountlines->delete();
3260 AddRenewal( $patron->id, $item->id, $library->id, $dt_to_renew, $dt_to );
3261 $accountlines = Koha::Account::Lines->search({ itemnumber => $item->id });
3262 is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly, for renewal");
3263 $accountlines->delete();
3267 subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub {
3270 t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1);
3271 t::lib::Mocks::mock_preference('item-level_itypes', 1);
3274 $builder->build_object( { class => 'Koha::Libraries' } )->store;
3275 my $patron = $builder->build_object(
3277 class => 'Koha::Patrons',
3278 value => { categorycode => $patron_category->{categorycode} }
3282 my $itemtype = $builder->build_object(
3284 class => 'Koha::ItemTypes',
3288 rentalcharge_daily => 0
3293 my $biblioitem = $builder->build( { source => 'Biblioitem' } );
3294 my $item = $builder->build_object(
3296 class => 'Koha::Items',
3298 homebranch => $library->id,
3299 holdingbranch => $library->id,
3303 itype => $itemtype->id,
3304 biblionumber => $biblioitem->{biblionumber},
3305 biblioitemnumber => $biblioitem->{biblioitemnumber},
3310 my ( $issuingimpossible, $needsconfirmation );
3311 my $dt_from = dt_from_string();
3312 my $dt_due = dt_from_string()->add( days => 3 );
3314 $itemtype->rentalcharge('1.000000')->store;
3315 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3316 is_deeply( $needsconfirmation, { RENTALCHARGE => '1' }, 'Item needs rentalcharge confirmation to be issued' );
3317 $itemtype->rentalcharge('0')->store;
3318 $itemtype->rentalcharge_daily('1.000000')->store;
3319 ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef );
3320 is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' );
3321 $itemtype->rentalcharge_daily('0')->store;